When an AI Agent Makes a Mistake: Failure Modes and the Controls That Contain Them
Agents fail in production in seven predictable ways: bad tool calls, retry loops, duplicate actions, confident wrong answers and more. Here is how each one is caught, capped and recovered, with a working LangGraph skeleton and the deep post for every control.
Your agent just tried to issue a refund. The payment API took twelve seconds to answer, so the agent assumed it had failed and tried again. Now the customer has two refunds, and nothing in your logs looks wrong.
That is not just a model problem. A different model, given the same information, might make the same choice. It is a system problem, and system problems have engineering fixes. Validate before you execute. Cap retries in code. Save state at every step. Make every write idempotent. Put a human gate on anything that moves money.
Each of those fixes is a few lines of ordinary code, and none of them depends on the model behaving well.
Why the prompt cannot carry reliability
Under deadline pressure, teams add rules to the system prompt. Two typical ones: "ALWAYS format dates as YYYY-MM-DD" and "NEVER retry more than twice." The model treats these as strong guidance. It does not treat them as guarantees.
The arithmetic is unforgiving. Suppose a rule slips once in every 1,000 runs. At 10 runs a day, you may never see it. At 10,000 runs a day, that is ten bad actions every day.
The fix is to split the job. The model proposes. Code decides whether the proposal is valid, permitted and safe to run. If you need a date in a fixed format, let the model extract it however it likes. Then parse and validate it in ordinary code before it touches your database.
Treat every model output, and every tool result the model reads, as untrusted input. Validate it the way you would validate data from a public web form.
The seven failure modes, and the control for each
Each failure mode has a distinct business cost and a distinct deterministic control. None of the controls depend on the model behaving well.
| Failure mode | What it looks like | How you detect it | Deterministic control | When the control trips |
|---|---|---|---|---|
| Schema violation | Wrong type, invented field, unsupported value, ID that does not exist | Validation error before the call, or an API 400 | Typed schema check (e.g. Pydantic) before any request leaves your system | Return the exact error to the model; retry a fixed number of times, then escalate |
| Retry loop | The same failing call repeated, with context growing each time | Repeated tool name and arguments in the trace | Failure counter in state, plus a graph-wide step limit | Stop, save state, hand over to a human or fallback |
| Downstream outage | Timeouts, 500s, 503s, locked records | HTTP status class | Classify errors in code; transient ones get backoff retries the model never sees | Tell the user plainly, queue the task for later |
| Provider outage | Model API rate-limited or down | Timeouts at the gateway | Gateway fallback to a second provider or a self-hosted model | Same prompt and tool schema run on the backup |
| Duplicate side effect | Two refunds or two emails after a slow response or a resumed run | Usually the customer tells you | Idempotency key derived from the run and the action | The receiving system returns the first result instead of acting twice |
| State hallucination | Valid call, wrong logic: wrong discount tier, buyer and seller swapped | Nothing errors | Business-rule checks in code, approval gates, sampled trace review | Roll back via checkpoint; add the case to your test set |
| Over-privileged tool or injected instruction | Agent follows instructions hidden in an email or document, using broad credentials | Unexpected tool use in traces | Least privilege, allowlists, sandboxed execution | Damage is limited to what that one tool can do |
The first four are loud. They throw errors, and a well-built system catches them automatically. The last three are quiet, and they are where real money and reputation are lost.
Each control has a post of its own that goes deeper than this one:
- ▸Schema violation and downstream outage: the seven silent failures at the API layer, where a call can succeed and still lose data.
- ▸Retry loop: the step and token caps below, and prompt caching in LangGraph for keeping each step's input cheap.
- ▸Provider outage: a LiteLLM gateway with routing and fallback.
- ▸Duplicate side effect: idempotency keys, covered in this post, and the retry policy in LangGraph production patterns.
- ▸State hallucination, caught before the customer: where the approval gate belongs and what an output check does instead of a prompt rule.
- ▸State hallucination, caught after the fact: tracing and step-level evals.
- ▸Injected instruction: the least-privilege section below, and the prompt-injection checks in the output check post.
The arithmetic of a retry loop
A loop does not cost exponentially more. Each retry resends the full context plus the earlier error messages, so cost grows a little faster than the attempt count. It is still worth capping, and the cap is easy to set. Limit tokens per step and total steps per run, and the worst case becomes steps × max tokens per step. With 10 steps at 20,000 tokens, no run can exceed 200,000 input tokens plus output. That is a number your finance team can plan around. For the full cost picture for retries, including context growth and evaluation overhead, use the running-cost post.
Tokens are rarely the biggest cost, though. The bigger cost is a customer watching a spinner for thirty seconds, and the task still not done. A capped loop fails in seconds and hands over clean, saved state. An uncapped one burns budget first and often saves nothing.
Retries belong to code, not to the model
A failed tool call should rarely reach the model at all. Sort errors into three kinds, each with its own response.
Transient errors (timeouts, 429 rate limits, 503s). Retry in code with exponential backoff and jitter. The model does not need to know. Feeding it a timeout invites it to "fix" a request that was never wrong.
Model-correctable errors (a 400 or a local validation failure). Return the exact error text as a tool observation. "expected integer for amount_cents, got string" lets the model fix its call. A bare "Error" gives it nothing to work with.
Permanent errors (404 record not found, 403 forbidden). Stop. No amount of retrying will create a missing record or grant a permission.
Outages on the model side need the same treatment one layer up. Routing calls through a gateway such as LiteLLM lets you fall back to a second provider or a self-hosted model when the primary times out. Keep the tool schemas provider-neutral so the backup can run the same call.
When a tool stays down, degrade on purpose. A booking agent that cannot reach the calendar should say so, take the customer's preferred times, and queue a follow-up. It should not crash, and it should never claim the booking succeeded.
Idempotency: making "try again" safe
Duplicate refunds, duplicate emails and double bookings all come from the same gap. An action is idempotent when doing it twice has the same effect as doing it once. Reading a record is idempotent. Issuing a refund is not, unless you make it so.
The method is simple. Derive a key from the run and the specific action, for example thread_id:refund:order_id. Send it with every request for that action. Stripe's API accepts an idempotency key on every request and returns the original result when it sees a repeat. Several other payment providers do the same.
For your own internal APIs, store the key alongside the result in a table with a unique constraint. On a repeat, return the stored result instead of acting again.
The key must be deterministic. A fresh random ID on each attempt defeats the purpose. This matters more once you add checkpoints, because a resumed graph can re-run the node that was in flight when it stopped. Parallel tool calls are a second source of duplicates: a model can issue two writes in one round trip. Anthropic documents a disable_parallel_tool_use setting in tool_choice that limits Claude to one tool call per turn, which is the safer default for write-heavy agents.
Least privilege and sandboxing
A mistake can never do more damage than the tool allows. That makes permissions your real safety boundary, not the prompt.
- ▸One narrow tool per action.
refund_order(order_id, amount_cents, reason), never a generic "run SQL" or "call any URL." - ▸Separate reads from writes. Read tools connect with a read-only database user.
- ▸Scope credentials per tool. Keep them short-lived and held by the execution layer. They never appear in the prompt.
- ▸Put hard limits inside the tool. Refund ceilings, allowlisted recipient domains, a per-run rate limit.
- ▸Make destructive actions soft. The agent flags a record for deletion; a person or a scheduled job carries it out.
- ▸Sandbox generated code. Use an isolated container with no network by default and no production credentials. Add CPU and wall-clock timeouts and a disposable filesystem.
The last point covers a threat prompts cannot stop. An email, ticket or web page the agent reads can contain instructions aimed at the agent. This is prompt injection, and prompt filters alone cannot guarantee safety. Tight permissions mean an injected instruction can only reach a tool that is already narrow, capped and logged.
The LangGraph skeleton
This section is for your engineers. The graph below puts the core controls in one place. Validation runs before execution, and a failure counter acts as a circuit breaker. A recursion_limit serves as the outer backstop, a checkpointer saves state at every step, and an approval pause sits before the write. The write itself carries an idempotency key.
</>View technical implementation · عرض التفاصيل التقنية
from typing import Literal, Optional, TypedDict
from langchain_core.runnables import RunnableConfig
from langgraph.checkpoint.memory import MemorySaver # tests only; use PostgresSaver in production
from langgraph.errors import GraphRecursionError
from langgraph.graph import END, START, StateGraph
from pydantic import BaseModel, Field, ValidationError
MAX_TOOL_FAILURES = 3
class RefundArgs(BaseModel):
order_id: str = Field(pattern=r"^ORD-\d{8}$")
amount_cents: int = Field(gt=0, le=50_000) # the hard ceiling lives in code
reason: Literal["damaged", "late", "duplicate"]
class AgentState(TypedDict):
messages: list
proposed: Optional[dict]
error: Optional[str]
failures: int
def plan(state: AgentState) -> dict:
# The model proposes a tool call. The last validation error is fed back verbatim.
proposed = propose_refund(state["messages"], last_error=state["error"])
return {"proposed": proposed}
def validate(state: AgentState) -> dict:
try:
RefundArgs(**state["proposed"])
return {"error": None}
except ValidationError as exc:
return {"error": str(exc), "failures": state["failures"] + 1}
def route(state: AgentState) -> str:
if state["error"] is None:
return "execute_refund"
if state["failures"] >= MAX_TOOL_FAILURES:
return "escalate" # circuit breaker: stop asking the model
return "plan"
def execute_refund(state: AgentState, config: RunnableConfig) -> dict:
args = RefundArgs(**state["proposed"])
thread_id = config["configurable"]["thread_id"]
# Same run + same order = same key, so a retry or resume cannot refund twice.
key = f"{thread_id}:refund:{args.order_id}"
result = payments.refund(args, idempotency_key=key)
return {"messages": state["messages"] + [result]}
def escalate(state: AgentState) -> dict:
human_queue.put(state) # full state, including every failed attempt
return {}
builder = StateGraph(AgentState)
builder.add_node("plan", plan)
builder.add_node("validate", validate)
builder.add_node("execute_refund", execute_refund)
builder.add_node("escalate", escalate)
builder.add_edge(START, "plan")
builder.add_edge("plan", "validate")
builder.add_conditional_edges("validate", route, ["plan", "execute_refund", "escalate"])
builder.add_edge("execute_refund", END)
builder.add_edge("escalate", END)
graph = builder.compile(
checkpointer=MemorySaver(),
interrupt_before=["execute_refund"], # a human approves every write
)
# propose_refund, payments, human_queue and user_message are your own implementations.
config = {"configurable": {"thread_id": "ticket-4812"}, "recursion_limit": 12}
start = {"messages": [user_message], "proposed": None, "error": None, "failures": 0}
try:
graph.invoke(start, config) # runs until it pauses before execute_refund, or escalates
snapshot = graph.get_state(config)
if snapshot.next == ("execute_refund",):
# Reviewer inspects snapshot.values["proposed"]. To correct it first:
# graph.update_state(config, {"proposed": corrected_args})
graph.invoke(None, config) # resumes from the checkpoint and executes
except GraphRecursionError:
human_queue.put(graph.get_state(config).values) # outer backstop tripped
Three notes, and then the engineering detail lives in LangGraph production patterns:
- ▸Set
recursion_limityourself. It caps the steps in one run and raisesGraphRecursionErrorwhen exceeded. LangGraph's graph API docs note that the default rose from 25 to 1,000 steps in version 1.0.6. That is no backstop at all for a refund agent. Set it from your expected path length plus a margin. - ▸Use a persistent checkpointer. In-memory savers lose everything on restart. The Postgres saver lets a reviewer approve a paused run hours later.
- ▸The failure counter and
recursion_limitdo different jobs. The counter stops a specific bad loop early and routes it cleanly. The recursion limit catches anything the counter's logic missed.
Catching the failure that throws no error
State hallucination is the expensive one. The call is well-formed, the API accepts it, and the logic is wrong. Your uptime monitors stay green while a customer gets the wrong discount. Vectara's September 2024 leaderboard research found models hallucinate from 1% to nearly 30% of the time, even with reference sources provided.
Four controls catch it.
Business rules in code. Wherever a rule is known, check it outside the model. The discount tier must match the customer's tier. A refund cannot exceed the order total. These checks take minutes to write and remove whole categories of error.
Approval gates set by rules, not model confidence. Anything that moves money, alters a legal document or sends a mass message pauses for a person. Where the approval gate belongs, and how to keep reviewers from rubber-stamping, is its own post. The same principle applies to anything that reaches a customer. Verel Coordinator applies it to inbound work: it routes under your rules, and nothing reaches a customer without passing a compliance gate. It also logs every decision with its reasoning.
Tracing every run. Record the input, the assembled prompt, the model output, tool arguments, results, timings and token counts. Tracing tools such as Langfuse and Weave are built for this. Langfuse's docs state that its SDKs queue trace events locally and flush them in batches, so the user-facing path barely slows. The trace is also your audit record when a customer disputes an automated decision.
Turning every confirmed failure into a test. Pull the trace and write the expectation: given this input, the agent must produce this tool call. Run the suite before any prompt edit or model change. That is how fixing one failure avoids creating three more.
Frequently Asked Questions
How do we stop an agent from taking destructive actions in our database? Enforce limits at the tool level, not in the prompt. Give the agent read-only tools for gathering data and narrow, parameter-checked endpoints for writes. Never grant raw SQL or direct database access. For deletions, the tool flags the record and a person or scheduled job carries out the deletion.
Do these controls slow the agent down? Barely, on the automated path. Schema validation and checkpoint writes typically take milliseconds per step. A model call usually takes one to several seconds. Human approval does add waiting time, which is why you reserve it for writes that move money, change legal documents or reach customers.
How do we test failure recovery before customers see it? Inject faults on purpose. Simulate a timeout, return malformed data, revoke a credential mid-run and feed contradictory instructions. Then check the trace. The graph should retry transient errors in code and escalate after the failure cap. It should pause before writes and never act twice. A crash, a loop or a duplicate action is a failed test.
→ Human-in-the-Loop AI Agents: Where to Put the Approval Gate and How to Build It → Agent Evals in Production: Tracing Tool Use and Trajectories → LangGraph in Production: Five Patterns That Keep Agents SafeFive questions before the next agent goes live
Gartner predicted in June 2025 that over 40% of agentic AI projects will be cancelled by the end of 2027. The reasons it gave: escalating costs, unclear business value or inadequate risk controls. The pilots that stall tend to stall at the same point: the demo works, and nobody can say what happens when it does not. Ask these before launch:
- ▸Is every tool argument validated in code before the request is sent?
- ▸What is the hard cap on attempts and steps per run, and who receives the case when it trips?
- ▸Does every write carry a deterministic idempotency key?
- ▸Could an injected instruction reach any tool broader than one narrow action?
- ▸Can you open a trace for yesterday's worst run and see exactly where it went wrong?
If any answer is "the prompt handles it," fix that item first, this week. If the agent is already live and you cannot answer them, an AI System Audit ($2,500 fixed, 10 days) reviews it against this list.
