[langgraph] 도구
원문 출처: https://langchain-ai.github.io/langgraph/agents/tools/
도구(Tools)는 함수와 그 입력 스키마를 캡슐화하여, 도구 호출을 지원하는 챗 모델에 전달할 수 있도록 하는 방법입니다. 이를 통해 모델이 특정 입력값으로 해당 함수를 실행하도록 요청할 수 있습니다.
직접 도구를 정의하거나, LangChain에서 제공하는 사전 구축된 통합 도구를 사용할 수 있습니다.
간단한 도구 정의하기(Define simple tools)
create_react_agent
에 일반 함수를 전달하면 도구로 사용할 수 있습니다.
API Reference: create_react_agent
from langgraph.prebuilt import create_react_agent
def multiply(a: int, b: int) -> int:
"""두 수를 곱합니다."""
return a * b
create_react_agent(
model="anthropic:claude-3-7-sonnet",
tools=[multiply]
)
create_react_agent
는 일반 함수를 자동으로 LangChain 도구로 변환합니다.
도구 커스터마이즈(Customize tools)
도구 동작을 더 세밀하게 제어하려면 @tool
데코레이터를 사용하세요.
API Reference: tool
from langchain_core.tools import tool
@tool("multiply_tool", parse_docstring=True)
def multiply(a: int, b: int) -> int:
"""두 수를 곱합니다.
Args:
a: 첫 번째 피연산자
b: 두 번째 피연산자
"""
return a * b
Pydantic을 사용해 커스텀 입력 스키마도 정의할 수 있습니다.
from pydantic import BaseModel, Field
class MultiplyInputSchema(BaseModel):
"""두 수를 곱합니다"""
a: int = Field(description="첫 번째 피연산자")
b: int = Field(description="두 번째 피연산자")
@tool("multiply_tool", args_schema=MultiplyInputSchema)
def multiply(a: int, b: int) -> int:
return a * b
추가 커스터마이즈 방법은 커스텀 도구 가이드를 참고하세요.
모델에 노출하지 않을 인자 숨기기(Hide arguments from the model)
일부 도구는 사용자 ID나 세션 컨텍스트 등 런타임에만 필요한 인자가 있을 수 있습니다. 이런 인자는 모델이 직접 제어하지 못하도록 해야 합니다.
이런 인자는 에이전트의 state
나 config
에 넣고, 도구 내부에서 접근할 수 있습니다.
API Reference: InjectedState | AgentState | RunnableConfig
from langgraph.prebuilt import InjectedState
from langgraph.prebuilt.chat_agent_executor import AgentState
from langchain_core.runnables import RunnableConfig
def my_tool(
tool_arg: str, # LLM이 채워줌
state: Annotated[AgentState, InjectedState], # 에이전트 내부 동적 정보
config: RunnableConfig, # 에이전트 호출 시 전달되는 정적 정보
) -> str:
"""나만의 도구."""
do_something_with_state(state["messages"])
do_something_with_config(config)
...
병렬 도구 호출 비활성화(Disable parallel tool calling)
일부 모델 제공자는 여러 도구를 병렬로 실행할 수 있지만, 이 기능을 비활성화할 수도 있습니다.
지원되는 공급자의 경우, model.bind_tools()
에서 parallel_tool_calls=False
로 설정하면 병렬 도구 호출을 비활성화할 수 있습니다.
API Reference: init_chat_model
from langchain.chat_models import init_chat_model
def add(a: int, b: int) -> int:
"""두 수를 더합니다"""
return a + b
def multiply(a: int, b: int) -> int:
"""두 수를 곱합니다."""
return a * b
model = init_chat_model("anthropic:claude-3-5-sonnet-latest", temperature=0)
tools = [add, multiply]
agent = create_react_agent(
# 병렬 도구 호출 비활성화
model=model.bind_tools(tools, parallel_tool_calls=False),
tools=tools
)
agent.invoke(
{"messages": [{"role": "user", "content": "what's 3 + 5 and 4 * 7?"}]}
)
도구 결과 즉시 반환(Return tool results directly)
return_direct=True
로 설정하면 도구 결과를 즉시 반환하고 에이전트 루프를 중단할 수 있습니다.
API Reference: tool
from langchain_core.tools import tool
@tool(return_direct=True)
def add(a: int, b: int) -> int:
"""두 수를 더합니다"""
return a + b
agent = create_react_agent(
model="anthropic:claude-3-7-sonnet-latest",
tools=[add]
)
agent.invoke(
{"messages": [{"role": "user", "content": "what's 3 + 5?"}]}
)
도구 사용 강제(Force tool use)
특정 도구 사용을 강제하려면 model.bind_tools()
의 tool_choice
옵션을 사용하세요.
API Reference: tool
from langchain_core.tools import tool
@tool(return_direct=True)
def greet(user_name: str) -> int:
"""사용자에게 인사합니다."""
return f"Hello {user_name}!"
tools = [greet]
agent = create_react_agent(
model=model.bind_tools(tools, tool_choice={"type": "tool", "name": "greet"}),
tools=tools
)
agent.invoke(
{"messages": [{"role": "user", "content": "Hi, I am Bob"}]}
)
무한 루프 방지: 도구 사용을 강제할 때는 반드시 중단 조건을 설정하세요. (예: return_direct=True, recursion_limit 등)
도구 에러 처리(Handle tool errors)
기본적으로 에이전트는 도구 호출 중 발생한 모든 예외를 잡아 LLM에 도구 메시지로 전달합니다. 에러 처리 방식을 제어하려면, create_react_agent
내부에서 도구를 실행하는 ToolNode의 handle_tool_errors
파라미터를 사용하세요.
에러 처리 활성화(기본값)
from langgraph.prebuilt import create_react_agent
def multiply(a: int, b: int) -> int:
"""두 수를 곱합니다."""
if a == 42:
raise ValueError("The ultimate error")
return a * b
# 기본 에러 처리
agent = create_react_agent(
model="anthropic:claude-3-7-sonnet-latest",
tools=[multiply]
)
agent.invoke(
{"messages": [{"role": "user", "content": "what's 42 x 7?"}]}
)
에러 처리 비활성화
from langgraph.prebuilt import create_react_agent, ToolNode
def multiply(a: int, b: int) -> int:
"""두 수를 곱합니다."""
if a == 42:
raise ValueError("The ultimate error")
return a * b
tool_node = ToolNode(
[multiply],
handle_tool_errors=False # (1)!
)
agent_no_error_handling = create_react_agent(
model="anthropic:claude-3-7-sonnet-latest",
tools=tool_node
)
agent_no_error_handling.invoke(
{"messages": [{"role": "user", "content": "what's 42 x 7?"}]}
)
커스텀 에러 메시지
from langgraph.prebuilt import create_react_agent, ToolNode
def multiply(a: int, b: int) -> int:
"""두 수를 곱합니다."""
if a == 42:
raise ValueError("The ultimate error")
return a * b
tool_node = ToolNode(
[multiply],
handle_tool_errors=(
"Can't use 42 as a first operand, you must switch operands!" # (1)!
)
)
agent_custom_error_handling = create_react_agent(
model="anthropic:claude-3-7-sonnet-latest",
tools=tool_node
)
agent_custom_error_handling.invoke(
{"messages": [{"role": "user", "content": "what's 42 x 7?"}]}
)
(1) 예외 발생 시 LLM에 전달할 커스텀 메시지입니다. 다양한 에러 처리 전략은 API 레퍼런스를 참고하세요.
메모리와 함께 사용(Working with memory)
LangGraph에서는 도구에서 단기/장기 메모리에 접근할 수 있습니다. 자세한 내용은 메모리 가이드를 참고하세요.
- 단기 메모리: 읽기/쓰기 방법
- 장기 메모리: 읽기/쓰기 방법
사전 구축 도구(Prebuilt tools)
LangChain은 API, 데이터베이스, 파일 시스템, 웹 데이터 등과 상호작용할 수 있는 다양한 사전 구축 도구 통합을 지원합니다. 이 도구들은 에이전트의 기능을 확장하고 빠른 개발을 가능하게 합니다.
전체 통합 목록은 LangChain integrations 디렉터리에서 확인할 수 있습니다.
주요 도구 카테고리 예시:
- 검색: Bing, SerpAPI, Tavily
- 코드 인터프리터: Python REPL, Node.js REPL
- 데이터베이스: SQL, MongoDB, Redis
- 웹 데이터: 웹 스크래핑 및 브라우징
- API: OpenWeatherMap, NewsAPI 등
이러한 통합 도구는 위 예시처럼 tools
파라미터로 에이전트에 추가할 수 있습니다.