Build Your First AI Agent · Lesson 6 of 8

Lesson 6 — Errors, retries, and recovery

45 minutes. What happens when something breaks mid-task — and how to make sure it doesn't cost you a customer.

---

The four failure modes
  • The model returns garbage. Bad JSON, wrong tool, hallucinated arg. Rare with modern models but happens.
  • A tool throws. Gmail API rate limit, DB connection drop, customer record missing.
  • The loop runs forever. Model keeps requesting tools and never reaches `end_turn`.
  • The agent makes a wrong but plausible decision. Drafted an apology when the customer was complimenting. Bad decision, no error thrown.

Failure mode 4 is the dangerous one — there's no exception to catch. Approval gates (Lesson 7) are how you protect against it.

Patterns for modes 1-3

For garbage model output: wrap tool calls in try/catch. If parsing fails, return an error to the model. It'll retry with a corrected call most of the time.

```js try { const result = await runTool(block.name, block.input) toolResults.push({ type: 'tool_result', tool_use_id: block.id, content: JSON.stringify(result) }) } catch (err) { toolResults.push({ type: 'tool_result', tool_use_id: block.id, content: `Error: ${err.message}. Please retry with corrected input or explain the situation.`, is_error: true, }) } ```

For tool failures: retry with backoff for transient errors (network, rate limit). Hard-fail for non-transient (missing record, permission denied) and let the model decide what to do.

For runaway loops: cap iterations. After 20 turns, force `end_turn` and dump state for human review.

```js const MAX_TURNS = 20 let turn = 0 while (turn++ < MAX_TURNS) { /* loop body */ } if (turn === MAX_TURNS) { console.warn('Agent hit turn limit', { messages }) await logEscalation(messages) } ```

The recovery principle

When the agent gets stuck or confused, the right answer is *almost always* "escalate to a human." It's not failure — it's the agent doing its job. The `request_approval` tool from Lesson 2 exists for exactly this moment.

→ Lesson 7 — Approval gates and human-in-the-loop

Previous: Lesson 5 — Hooking the agent to real services · Next: Lesson 7 — Approval gates and human-in-the-loop