LangChain Handling Tool Errors

2025. 5. 14. 18:37·AI4C

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

  • https://python.langchain.com/docs/how_to/custom_tools/#handling-tool-errors

'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
'AI4C' 카테고리의 다른 글
  • LangChain artifact 분리
  • LangChain tool 등록
  • LangGraph Persistence Layer 동작 원리
  • LangGraph 코드 예제
bde574786
bde574786
  • bde574786
    꾸러기해커
    bde574786
  • 전체
    오늘
    어제
    • 분류 전체보기 (172) N
      • 워게임 (107)
        • 웹해킹 (87)
        • 시스템해킹 (6)
        • 리버싱 (12)
        • 암호학 (2)
      • 보안 (3)
        • 웹 (3)
      • Report (7)
        • One-Day (1)
        • Zero-Day (6)
      • Git (35)
      • CTF Write Up (10)
        • b01lers CTF 2025 (5)
        • BYU CTF 2025 (5)
      • AI4C (7)
      • etc (1) N
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    sql injection
    crlf injection
    type juggling
    CVE
    prototype pollution
    SSTI
    XSS
    Blind SQL Injection
    RCE
    Path Traversal
    git
    case mapping collision
    Wordpress
    return address overwrite
    SSRF
    dom clobbering
    LFI
    Stack Buffer Overflow
    php deserialization
    url globbing
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.2
bde574786
LangChain Handling Tool Errors
상단으로

티스토리툴바