Session 8· 03· 10 min
Tool Error Handling
What you'll learn
- ▸Wrap tool execution with @wrap_tool_call to catch errors
- ▸Return friendly error messages as ToolMessages instead of crashing
- ▸See the agent recover gracefully from tool failures
Real tools fail. APIs time out, databases go down, files go missing. This lesson teaches you the @wrap_tool_call middleware pattern — catch any exception and return it as a ToolMessage so the agent can apologise or retry instead of crashing.
03_tool_errors.py (middleware)
@wrap_tool_call
def safe_tool_call(
request: ToolRequest,
handler: Callable[[ToolRequest], ToolResponse],
) -> ToolResponse:
try:
return handler(request) ①
except Exception as e:
return ToolResponse( ②
messages=[
ToolMessage(
content=f"Error: {e}",
tool_call_id=request.tool_call["id"],
)
]
)①handler(request) runs the actual tool. If it succeeds, pass through.
②On failure, return a ToolMessage with the error. The agent sees it and can react.
$ python 03_tool_errors.py
Knowledge Check
Why return the error as a ToolMessage instead of letting the exception propagate?
Recap — what you just learned
- ✓@wrap_tool_call intercepts tool execution
- ✓Catch exceptions and return them as ToolMessage content
- ✓The agent reads the error and can apologise, retry, or try another approach