Course contentsShow
← AI Engineering
Lesson 663 of 1,88616. AI Agents - ImplementationFree lesson

Handling Tool Execution Errors

Implement error handling for tool failures and provide the agent with error messages to recover or retry gracefully.

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:

  1. Catch the exception during tool execution
  2. Extract meaningful information about what went wrong
  3. Return the error message to the agent as part of the observation
  4. 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.