Tool Calling은 LLM이 외부 시스템과 상호작용하기 위한 함수 호출 메커니즘
LLM은 정의된 도구나 함수를 통해 외부 시스템과 통신하고 작업을 수행
Tool calling은 모델이 시스템과 직접 상호작용할 수 있게 하는 기능
구조화된 출력을 통해 API나 데이터베이스와 같은 시스템 요구사항 충족
스키마 기반 응답으로 시스템 간 효율적 통신 가능
[참조] - [Python Docs / Tool_Calling]
@tool
데코레이터 사용)@tool 데코레이터로 함수에 스키마 정보 추가
함수와 스키마 간 자동 연결로 도구 생성
from langchain_core.tools import tool
from typing import Literal
@tool
def get_weather(city: Literal["서울", "부산", "대구", "인천", "광주"]):
"""한국 주요 도시의 날씨 정보를 가져옵니다."""
weather_data = {
"서울": "맑음",
"부산": "흐림",
"대구": "맑음",
"인천": "비",
"광주": "구름많음"
}
if city in weather_data:
return f"{city}은(는) {weather_data[city]}"
else:
raise AssertionError("지원하지 않는 도시입니다")
get_weather
- 출력
StructuredTool(name='get_weather', description='한국 주요 도시의 날씨 정보를 가져옵니다.', args_schema=<class 'langchain_core.utils.pydantic.get_weather'>, func=<function get_weather at 0x00000241A08BFCE0>)
get_weather.args
- 출력
{'city': {'enum': ['서울', '부산', '대구', '인천', '광주'],
'title': 'City',
'type': 'string'}}
모델-도구 연결로 입력 스키마 자동 인식
스키마 기반 검증으로 올바른 입력 보장
from langchain_openai import ChatOpenAI
# 모델
model = ChatOpenAI(model="gpt-4o-mini",temperature=0)
# 도구 목록
tools = [get_weather]
# 도구를 모델에 바인딩 (bind_tools 메소드 사용)
model_with_tools = model.bind_tools([get_weather])
model_with_tools
- 출력
RunnableBinding(bound=ChatOpenAI(client=<openai.resources.chat.completions.Completions object at 0x00000213E6E39820>, async_client=<openai.resources.chat.completions.AsyncCompletions object at 0x00000213E6E3B3E0>, root_client=<openai.OpenAI object at 0x00000213E6C3B770>, root_async_client=<openai.AsyncOpenAI object at 0x00000213E6E39880>, model_name='gpt-4o-mini', temperature=0.0, model_kwargs={}, openai_api_key=SecretStr('**********')), kwargs={'tools': [{'type': 'function', 'function': {'name': 'get_weather', 'description': '한국 주요 도시의 날씨 정보를 가져옵니다.', 'parameters': {'properties': {'city': {'enum': ['서울', '부산', '대구', '인천', '광주'], 'type': 'string'}}, 'required': ['city'], 'type': 'object'}}}]}, config={}, config_factories=[])
스키마 기반 응답 생성으로 정확한 입력 형식 준수
자동 유효성 검증으로 오류 방지
구조화된 출력 생성으로 시스템 호환성 보장
# 사용자 쿼리를 모델에 전달
result = model_with_tools.invoke("서울 날씨 어때?")
result
- 출력
AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_4nAAimNoDervWleG8FNVVlna', 'function': {'arguments': '{"city":"서울"}', 'name': 'get_weather'}, ... })
model_with_tools.invoke("3+2 는 얼마인가요?") # tool 이 필요없는 질문이므로 content 로 바로 출력하는 모습
- 출력
AIMessage(content='3 + 2는 5입니다.', additional_kwargs={'refusal': None}, ...})
# tool_calls 출력
pprint(result.tool_calls)
- 출력
[{'args': {'city': '서울'},
'id': 'call_4nAAimNoDervWleG8FNVVlna',
'name': 'get_weather',
'type': 'tool_call'}]
인자 기반 실행으로 도구 기능 수행
모델 제공 파라미터로 자동화된 실행
실행 결과 처리 및 반환
# 함수의 인자를 직접 전달하는 방식으로 실행 -> 도구를 직접 호출
get_weather.invoke("서울")
# ToolCall 객체를 전달 전달하는 방식으로 실행 -> ToolMessage 객체를 반환
get_weather.invoke(result.tool_calls[0]).content
- 출력
'서울은(는) 맑음'