Tools talk to databases and other services, so they sometimes fail. If a tool raises an error, the agent shouldn't crash. Ideally, the model sees what went wrong, and adapts.
Here, an order lookup tool fails for unknown order numbers. A wrap tool call middleware catches the error, and returns it as a tool message, instead of crashing. Run it. The model reads the error, and tells the customer politely that the order number wasn't found, and asks them to check it.
tool_errors.pypython
from langchain.agents import create_agentfrom langchain.agents.middleware import wrap_tool_callfrom langchain.messages import ToolMessagefrom langchain.tools import tool@tooldef order_status(order_id: str) -> str: """Status of an order, like RB-1234.""" return {"RB-1234": "shipped"}[order_id] # unknown ids raise KeyError@wrap_tool_calldef catch_errors(request, handler): try: return handler(request) except KeyError as e: return ToolMessage(f"Error: no order {e}", tool_call_id=request.tool_call["id"])agent = create_agent("google_genai:gemini-flash-lite-latest", tools=[order_status], middleware=[catch_errors])out = agent.invoke({"messages": [{"role": "user", "content": "Status of order RB-9999?"}]})print(out["messages"][-1].text)
Output
The order RB-9999 could not be found. Please check the order number and try again.
Write tool errors for the model to read. Say what went wrong, and what might fix it, like, order not found, check the format RB dash four digits. Never include secrets or stack traces. And for errors that might go away, like timeouts, add tool retry middleware.
Catch tool errors and return them as tool messages, so the model can explain or try again. Write errors the model can act on. Next, telling tools who the user is.