LangChain의 에이전트가 툴 사용 중 에러를 만나도 멈추지 않고 적절히 처리하고 계속 실행되게 하려면, 에러 핸들링 전략이 필요하다.
Tool Exception
일반적인 raise Exception이 아니라 Tool Exception을 던져야 LangChain이 에이전트 차원에서 인식할 수 있다. 툴 객체 생성 시 handle_tool_error 옵션을 반드시 줘야 한다. handle_tool_error=False(default)이면 ToolException이 던져져도 그냥 예외로 끝나게 된다.
from langchain_core.tools import StructuredTool
from langchain_core.tools import ToolException
def get_weather(city: str) -> int:
"""Get weather for the given city."""
raise ToolException(f"Error: There is no city by the name of {city}.")
get_weather_tool = StructuredTool.from_function(
func=get_weather,
handle_tool_error=True,
)
result = get_weather_tool.invoke({"city": "foobar"})
print(result)
# Error: There is no city by the name of foobar.
Custom Error Handling
handle_tool_error에 True 대신 사용자 정의 함수를 넣으면 툴 실행 중 발생한 Tool Exception을 직접 가공해서 원하는 메세지로 반환할 수 있다.
from langchain_core.tools import StructuredTool
from langchain_core.tools import ToolException
def get_weather(city: str) -> int:
"""Get weather for the given city."""
raise ToolException(f"Error: There is no city by the name of {city}.")
def _handle_error(error: ToolException) -> str:
return f"The following errors occurred during tool execution: `{error.args[0]}`"
get_weather_tool = StructuredTool.from_function(
func=get_weather,
handle_tool_error=_handle_error,
)
result = get_weather_tool.invoke({"city": "foobar"})
print(result)
# The following errors occurred during tool execution: `Error: There is no city by the name of foobar.`
Reference
'AI4C' 카테고리의 다른 글
LangChain artifact 분리 (0) | 2025.05.14 |
---|---|
LangChain tool 등록 (0) | 2025.05.14 |
LangGraph Persistence Layer 동작 원리 (0) | 2025.05.13 |
LangGraph 코드 예제 (0) | 2025.05.11 |
LangGraph 아키텍처 (0) | 2025.05.11 |