Handling Tool Execution Errors
What you'll learn: How to implement robust error handling when agent tools fail, enabling your agent to recover gracefully and continue its task.
Why Tool Errors Matter
When your AI agent calls a tool—whether it's querying a database, making an API request, or executing code—things can go wrong. Networks fail, APIs return errors, files don't exist, or code crashes. Without proper error handling, your agent stops dead in its tracks.
The Core Pattern
Think of tool error handling like a helpful coach giving feedback. When a tool fails, you don't just say "error occurred." Instead, you:
- Catch the exception during tool execution
- Extract meaningful information about what went wrong
- Return the error message to the agent as part of the observation
- Let the agent decide whether to retry, use a different tool, or adjust its approach
def execute_tool(tool_name: str, args: dict) -> dict:
try:
result = tool_registry[tool_name](**args)
return {"success": True, "output": result}
except FileNotFoundError as e:
return {"success": False, "error": f"File not found: {e.filename}"}
except TimeoutError:
return {"success": False, "error": "Tool execution timed out after 30s"}
except Exception as e:
return {"success": False, "error": f"Tool failed: {str(e)}"}
Enabling Recovery
The key is returning structured error information that the agent can reason about. Instead of crashing, the agent sees: "Error: API returned 404. The resource /users/123 was not found." Now it can try a different user ID or ask the user for clarification.
Key Takeaway: Always catch tool execution errors and return descriptive messages to your agent—this transforms failures into recoverable observations that enable intelligent retry and adaptation strategies.