Basic Error Handling
You'll learn how to make your AI agent resilient by catching and recovering from common runtime failures.
Why Agents Need Error Recovery
An AI agent operates in an unpredictable environment: the LLM might return malformed JSON, a tool call could fail due to network issues, or the agent might enter an unexpected state. Without error handling, a single failure crashes your entire agent. With it, your agent can recover gracefully and continue working toward its goal.
Three Common Error Types
1. Malformed LLM Outputs
The LLM returns invalid JSON or missing required fields when you expected structured data.
Recovery: Catch parsing errors, log the malformed response, and retry with a clarifying prompt like "Please respond with valid JSON."
2. Failed Tool Calls
A tool execution raises an exception (API timeout, invalid parameters, resource unavailable).
Recovery: Wrap tool execution in try-catch blocks, return error descriptions to the agent, and let it choose an alternative action or retry with different parameters.
3. Unexpected Agent States
The agent reaches a state you didn't anticipate (empty action list, circular reasoning, contradiction).
Recovery: Define fallback behaviors—default to a safe action, ask the user for clarification, or gracefully terminate with a meaningful error message.
The Recovery Pattern
Think of error handling like a safety net beneath a tightrope walker. You don't expect them to fall, but when they do, the net catches them and they can climb back up to try again. Your agent should:
- Detect the error immediately
- Log what went wrong for debugging
- Inform the LLM about the failure
- Retry or choose an alternative path
Key Takeaway: Robust agents wrap critical operations (parsing, tool execution, state transitions) in error handlers that log failures and provide recovery paths, preventing single errors from cascading into total failure.