AI Hints
Home›LangChain Tutorial›Context and Errors
LangChain · Lesson 53 of 120

Tool Errors

Failing gracefully.

⏱ 2 min read▶ Video at 59:00🎓 Free
Watch this lesson in the LangChain courseWatch on YouTube ↗Full LangChain course

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.

Tool Errors
From the video: Tool Errors
  • Tools fail sometimes
  • Don't crash
  • Let the model adapt

Returning errors to the model

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_agent
from langchain.agents.middleware import wrap_tool_call
from langchain.messages import ToolMessage
from langchain.tools import tool

@tool
def 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_call
def 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.

Good error messages

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.

keyvalue
Say whatwent wrong
Say howto fix it
Neversecrets or stack traces
TimeoutsToolRetryMiddleware

Summary

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.

Key takeaways
  • Catch in wrap_tool_call
  • Return a ToolMessage
  • Helpful error text
Next up: Runtime Context — who is asking