Skip to content
47% off: the complete course for $79 (reg. $149)Order now →
Agent Builder
Module 5Full course16 min read

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.

FailureExampleWho handles itHow
Transient API error429 rate limit, 529 overloaded, dropped connectionYour codeRetry with backoff
Permanent API error401 bad key, 400 malformed requestYou, the developerFail fast with a clear message
Tool failureFile not found, HTTP 404, bad inputThe modelReturn an error result it can read
Model stops earlyHit max_tokens, declined the requestYour codeDetect via stop_reason, report it
Runaway runLoops, repeats calls, grows without convergingYour codeTurn 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.