Error Handling, Retries, and Stop Conditions
Make your agent robust: tool errors the model can recover from, API retries, iteration limits, and budgets.
Your agent works on your laptop, on a good day, with tasks you chose. Then reality arrives. The API returns a 529 because it's overloaded. A web page times out. The model asks for a file that doesn't exist, then asks for it again, and again. A task that should take five steps takes fifty and quietly spends real money. None of these are rare; run an agent enough and you'll see all of them in a week.
This lesson makes your agent robust in three layers: API failures handled with retries, tool failures turned into information the model can recover from, and hard stop conditions (turn limits, token budgets, timeouts) that end every run gracefully. You'll finish with the final version of the hand-rolled agent, the one you'll reuse in the multi-agent module.
A field guide to how agents fail
Before writing code, sort failures by who should handle them. Most bugs in agent error handling come from handling a failure at the wrong layer.
| Failure | Example | Who handles it | How |
|---|---|---|---|
| Transient API error | 429 rate limit, 529 overloaded, dropped connection | Your code | Retry with backoff |
| Permanent API error | 401 bad key, 400 malformed request | You, the developer | Fail fast with a clear message |
| Tool failure | File not found, HTTP 404, bad input | The model | Return an error result it can read |
| Model stops early | Hit max_tokens, declined the request | Your code | Detect via stop_reason, report it |
| Runaway run | Loops, repeats calls, grows without converging | Your code | Turn limits, budgets, timeouts |
The key insight is the middle row. A tool failure is not an exception to crash on; it's an observation. "File not found" is exactly the kind of feedback a capable model uses to change course, the same way you would.