Table of Contents
- What does AI agent error recovery cover that basic error handling does not?
- Which failure modes should an AI agent plan for?
- How do you classify an error as transient, permanent, or semantic before you act?
- How many retries are reasonable, and how do you stop runaway loops and cost blowups?
- When should an agent fall back instead of retrying?
- How do you detect silent failures when the API returns 200 OK but the output is wrong?
- What state should an agent checkpoint so a failed run can be resumed or replayed?
- How do you make multi-step agent actions idempotent or reversible?
- Should the agent self-correct, and what does each correction turn cost?
- How should an AI agent escalate to a human, and what should it show them?
- Where do the checkpoints, ledger, and pending approvals live when the laptop sleeps?
- Which sources shaped these recommendations?
- What is the smallest first project for a recovery stack on Agent 37?
- What do people also ask?
Do not index
AI agent error recovery is the set of mechanisms that lets an agent survive a failed step: classify the error, retry transient faults with backoff and a budget, fall back to another model or tool, re-plan from a checkpoint, and escalate to a human before anything irreversible. The order of those layers matters more than any single technique. Agent 37 is the always-on runtime those layers need, hosting OpenClaw and Hermes agents in isolated containers from $3.99 per month.
Key takeaways
- Recovery is a ladder, not a loop: retry transient errors, fall back on permanent ones, re-plan from the last checkpoint on semantic ones, and escalate to a person on anything irreversible.
- Three attempts, full jitter, and a budget: cap each LLM or tool call at three tries with exponential backoff from one second to about 30 seconds, plus a hard per-run token and retry budget.
- A timeout is an unknown, not a failure: check the action ledger or the target system before re-issuing any call that timed out.
- Checkpoint six things: run ID and step index, plan, context summary, tool-call ledger, external IDs created, and token spend, stored outside process memory.
- Agent 37 is the runtime, from $3.99 per month: isolated always-on containers, API keys that go directly to Anthropic or OpenAI, a browser terminal and file browser, and a task board for reviewing what failed.

What does AI agent error recovery cover that basic error handling does not?
AI agent error recovery is the process of detecting that a step failed, deciding what the failure means, and returning the agent to a good state, either by completing the task another way or by handing it to a person. Basic error handling catches an exception; recovery owns the side effects, saved state, and the decision about what happens next.
A try/except block answers one question: did this call throw? An agent asks four more: did the call execute on the other side, is the result correct, which completed steps need undoing, and who decides now?
Which failure modes should an AI agent plan for?
Agent failures fall into six recurring types: tool and HTTP errors such as timeouts and 429 rate limits, context overflow when history exceeds the window, formatting errors that break the schema, hallucinated tool arguments or facts, infinite loops where the agent repeats the same step, and stalls on long-running tasks. Each needs its own signal and response.
Failure mode | Typical signal | First response |
Tool or HTTP error | 5xx, 429, connection reset, timeout | Classify, then retry or fall back |
Context overflow | Context-length error, or quality drops late in a run | Summarize history, restart from checkpoint |
Formatting error | Output fails JSON or schema parse | Feed the parse error back, one correction turn |
Hallucinated arguments | Tool rejects an ID or path that does not exist | Validate inputs before the call, re-plan |
Infinite loop | Same tool called with the same arguments more than twice | Loop detector trips, escalate |
Stall | Step exceeds its time budget without progress | Cancel, checkpoint, resume or escalate |
The loop detector is a hash of tool name plus arguments with a counter per run; three identical calls is a loop. The stall detector is a wall-clock budget per step, cancelling anything that crosses it.
How do you classify an error as transient, permanent, or semantic before you act?
Classify every error into one of three classes before choosing a response. Transient errors (timeouts, 429s, 5xx) are expected to clear on their own, so retry with backoff. Permanent errors (401, 404, invalid arguments) will not clear, so fall back or re-plan. Semantic errors (valid response, wrong content) need validation and self-correction, not retries.
Error class | How to recognize it | Recovery action | Budget |
Transient | 408, 429, 500, 502, 503, 504, network timeout | Retry with exponential backoff and jitter | Up to 3 attempts |
Permanent | 400, 401, 403, 404, 422, schema rejected by the tool | Fall back to an alternate tool or model, or re-plan | 0 retries |
Semantic | 200 OK but output fails a validation gate | Feed the validation error back, self-correct | Up to 2 correction turns |
Unknown outcome | Timeout on a call with side effects | Query the target system or ledger before anything else | 1 verification call |
Retrying a permanent error burns budget on a call that can never succeed, and retrying a semantic error re-sends the prompt that produced the wrong answer. The fourth row causes real damage: a timed-out write may have happened, and retrying it is how an agent sends the same invoice twice.
How many retries are reasonable, and how do you stop runaway loops and cost blowups?
Three attempts is a sensible ceiling for a single LLM or tool call, with exponential backoff starting at one second, capped at about 30 seconds, and full jitter on every wait. Pair that with a per-run retry budget and a circuit breaker that opens after five consecutive failures, so one flaky dependency cannot become an unbounded loop or bill.
Jitter is not optional. The AWS Builders' Library guidance on timeouts, retries, and backoff with jitter shows how synchronized retries from many clients create waves of load that keep a recovering service down; full jitter, a random wait between zero and the current cap, spreads them out.
Retries need two budgets. The per-call cap of three protects against one flaky request; a per-run budget, say ten retries or a fixed token spend, protects against a run that hits a different flaky request at every step. Google's SRE book chapter on cascading failures recommends both limits because retries amplify load on a struggling system.
The circuit breaker sits above both budgets. Following the circuit breaker pattern documented by Microsoft, it tracks failures per dependency, opens after five consecutive failures, rejects calls instantly while open, and lets one probe through after a cooldown of around 30 seconds.

When should an agent fall back instead of retrying?
Fall back when the error is permanent or the retry budget is spent. The four fallback patterns are an alternate model, an alternate tool for the same job, a cached or default response, and a degraded mode that returns a partial result flagged as partial. Configure fallbacks before the run; never let the model improvise them.
Model fallback is the simplest: if the primary provider returns 5xx or the breaker is open, route the same prompt to a second provider or a smaller model with the same output schema. Tool fallback needs two tools for the same job, such as Slack with email behind it for a send-message step; Agent 37 exposes 1000+ integrations through Composio, which makes wiring that second provider practical.
How do you detect silent failures when the API returns 200 OK but the output is wrong?
A 200 OK tells you the transport worked, not that the content is right. Catch silent failures with three gates: a schema check on tool input and model output, a plausibility check on values (empty result sets, dates in the past, totals that do not add up), and a spot check by a second model on high-stakes outputs.
The schema gate is the cheapest and catches the most. Define a Pydantic model for every tool's arguments and every structured model response and parse against it before the result moves on; in Pydantic AI, a tool that raises ModelRetry sends the validation message back to the model, bounded by its retries setting.
The plausibility gate catches what the schema cannot: a search tool returning zero results with a 200 is a valid list and a probable failure. The second-model gate is expensive, so reserve it for outputs that trigger a side effect, and use a different model so the check is an independent audit.
What state should an agent checkpoint so a failed run can be resumed or replayed?
Checkpoint six things after every completed step and before every external side effect: run ID and step index, the current plan, a compact context summary, the ledger of tool calls with inputs, outputs, and status, every external ID the run created, and cumulative token spend. Store it outside process memory, in SQLite on persistent disk, Postgres, or Redis.
The ledger is the piece most implementations leave out. Each entry records the step, tool, arguments, status (pending, done, failed), and result. A pending entry with no result is the signature of a crash mid-call, exactly the case where you must verify before retrying.
A minimal checkpoint and resume loop with SQLite:
import json, sqlite3
db = sqlite3.connect("/data/agent_runs.sqlite")
db.execute("""CREATE TABLE IF NOT EXISTS checkpoints
(run_id TEXT, step INTEGER, state TEXT, PRIMARY KEY (run_id, step))""")
def save(run_id, step, state):
db.execute("INSERT OR REPLACE INTO checkpoints VALUES (?, ?, ?)",
(run_id, step, json.dumps(state)))
db.commit()
def resume(run_id):
row = db.execute("SELECT step, state FROM checkpoints WHERE run_id=? "
"ORDER BY step DESC LIMIT 1", (run_id,)).fetchone()
if row is None:
return 0, {"plan": [], "ledger": [], "created_ids": {}, "tokens": 0}
return row[0] + 1, json.loads(row[1])
step, state = resume(run_id)
while step < len(state["plan"]):
result = run_step(state["plan"][step], state)
state["ledger"].append({"step": step, "status": "done", "result": result})
save(run_id, step, state)
step += 1LangGraph does the same through a checkpointer at every node boundary, resuming a crashed run from the last node by thread ID. Its default in-memory checkpointer loses everything on restart, so use the SQLite or Postgres one on storage that survives the process.
How do you make multi-step agent actions idempotent or reversible?
Make each step idempotent by giving every side-effecting call an idempotency key derived from the run ID and step index, and by checking the action ledger before re-issuing any call that timed out. For steps that cannot be made idempotent, pair each forward action with a compensating action and run compensations in reverse order when the run fails.
Many APIs accept an idempotency key directly, with Stripe's Idempotency-Key header the well-known example. For APIs that do not, the key still belongs in your ledger.
def call_once(run_id, step, action, do_call):
key = f"{run_id}:{step}"
prior = ledger.get(key)
if prior and prior["status"] == "done":
return prior["result"]
if prior and prior["status"] == "pending":
existing = action.lookup(key) # ask the target system first
if existing:
ledger.put(key, status="done", result=existing)
return existing
ledger.put(key, status="pending")
result = do_call(idempotency_key=key)
ledger.put(key, status="done", result=result)
return resultThe saga pattern covers everything else. Each forward step declares its compensation when planned: create ticket pairs with close ticket, open branch pairs with delete branch. When step four fails, the agent walks the ledger backward running each compensation. Some actions have none (an email, once sent, is sent), which is the strongest argument for a human approval gate.

Should the agent self-correct, and what does each correction turn cost?
Self-correction means feeding the error message back to the model and asking for a revised plan. It works for semantic and formatting errors, but every correction turn re-sends the whole context, so cap it at two turns and set a token budget per run. When expected recovery cost exceeds the cost of failing fast, fail fast.
A correction turn is a full new request. If the run's context is 60,000 tokens, each correction pays for those input tokens again, so two corrections triple the cost of the step with a falling chance of success. If the second correction still fails validation, the step is permanent and moves to fallback or escalation. Our guide on reducing Claude Code API costs covers context trimming and model routing that make correction turns cheaper.
How should an AI agent escalate to a human, and what should it show them?
Escalate when the action is irreversible, when the retry and fallback budgets are spent, or when confidence falls below a threshold you set in advance. The handoff should show what the agent was trying to do, what failed, what it already did, and one proposed next step, with approve, retry, and abort as the only three choices.
The irreversible-action rule should be written down, not inferred by the model. We describe this as confidence routing in our AI agent CI/CD pipeline guide: the agent proceeds alone above a threshold, hands off below it, and always hands off on merges, deploys, payments, and outbound messages. The NIST AI Risk Management Framework frames this as meaningful human oversight over consequential decisions before they execute.
When the agent escalates, it writes its state as waitingforhuman and exits the step. The person reviews the ledger, chooses approve, retry, or abort, and the run resumes from the same checkpoint.
Where do the checkpoints, ledger, and pending approvals live when the laptop sleeps?
Recovery only works if the process holding the checkpoints, the ledger, and the pending human approval is still running when the failure happens. Agent 37 is that runtime: managed OpenClaw and Hermes agents in isolated, always-on containers from $3.99 per month, with a task board for reviewing failed outputs and a browser terminal and file browser for inspecting state.
An agent on a laptop loses its in-memory state when the lid closes. Agent 37's persistent AI agent hosting keeps files and memory on the instance between runs, so the SQLite checkpoint file above is still there in the morning. The full TTY terminal queries the checkpoint table, the visual file browser opens the ledger, and the live Linux desktop via noVNC shows a browser step failing in real time. Each agent runs in its own container with API keys going directly to Anthropic or OpenAI; our piece on keeping coding agents in bounds explains why an agent should never run as your user on your machine.
The task board closes the human-in-the-loop gap. Recurring jobs run on a schedule you set, outputs land in a review queue, and a failed job shows as a failed job rather than a silent gap in a cron log; see how to schedule AI agents on a timer.
Which sources shaped these recommendations?
We drew on AWS and Google guidance on retries, backoff, and cascading failures, Microsoft's circuit breaker pattern documentation, the persistence and retry features in the LangGraph and Pydantic AI docs, and Agent 37's own published feature set and pricing.
What is the smallest first project for a recovery stack on Agent 37?
Start with one agent and one recurring job that fails sometimes. Deploy a managed OpenClaw or Hermes instance in one click from $3.99 per month, add the checkpoint and ledger code from this guide, point the SQLite file at the instance's persistent disk, and route the job through the task board so every failure shows up for review.
Deploy your first always-on agent on Agent 37 and give your recovery code a machine that stays awake.
What do people also ask?
What is the difference between error handling and error recovery in AI agents?
Error handling catches an exception and stops the crash. Error recovery decides what the error means, verifies whether a timed-out action executed, resumes or undoes partial work from a checkpoint, and chooses between retry, fallback, re-plan, and human escalation. Handling is one line; recovery is an architecture.
How do you detect silent failures when the API returns 200 OK but the agent output is wrong?
Run three gates after every call: a schema check on tool inputs and model outputs, a plausibility check on values such as empty result sets or dates in the past, and a second-model spot check on outputs that trigger a side effect. Treat any gate failure as a semantic error and route it to self-correction, capped at two turns.
How many retries should an AI agent make before giving up?
Three attempts per call, with exponential backoff from one second to about 30 seconds and full jitter. Add a per-run retry budget and a circuit breaker that opens after five consecutive failures on one dependency. Never retry a permanent error such as 401 or 404, and never retry a timed-out write without checking whether it executed.
What state should an agent checkpoint so a failed run can be resumed or replayed?
Persist the run ID and step index, the current plan, a compact context summary, a ledger of every tool call with arguments, status, and result, every external ID the run created, and cumulative token spend. Write it to SQLite on persistent disk, Postgres, or Redis after each completed step and before each side effect.
How do you test and observe agent recovery behavior in production?
Inject failures deliberately: wrap tool clients so a configurable share of calls return 429, 503, or a timeout, and confirm the agent retries within budget, falls back, and escalates correctly. In production, trace every run with the error class, attempt count, breaker state, and correction tokens, and turn each real failure into a new test case.
