Failure Handling: Building Resilient Retry Loops for LLM Hallucinations

Malformed JSON, hallucinated arguments, unknown tools, and flaky APIs: how to route each failure to whoever can fix it, feed errors back so the model corrects itself, and bound the loop so it can't spin forever.

In the previous post, the loop worked: the model asked for a tool, the application ran it, the result went back. That loop is a demo. In production, models send arguments that aren’t JSON, invent field values, call tools that don’t exist, and hit APIs that time out. Smaller open-weight models do it more often; frontier models still do it, and no model scores perfectly on function-calling benchmarks like the Berkeley Function Calling Leaderboard.

A tool-calling loop without failure handling is a toy that works until the first bad token. The good news is that this is a solved engineering problem, not a research one: the model is quite good at fixing its own mistakes when you tell it precisely what went wrong. The work is in classifying failures, writing errors the model can act on, and bounding the loop.

1. Who fixes it? A taxonomy of failures

The single most useful question for each failure is who can fix it. Send a validation error back to the model and it corrects the call; retry it silently and you get the same bad call again. Send a 503 to the model and it wastes a turn, or worse, “works around” the outage by inventing an answer.

FailureExampleWhere LangChain surfaces itWho fixes itMechanism
Malformed JSON{"order_id": "3}AIMessage.invalid_tool_calls; tool_calls is emptyModelCustom route plus an error message per call
Schema violation{"order_id": "three"}, missing field, value outside an enumToolNode validationModelToolNode’s default error message
Hallucinated toolcancel_order when no such tool existsToolNode lookupModelToolNode’s default error message
Rejected by the backendOrder exists but hasn’t shipped; 404; 400 for an invalid combinationException raised inside the toolModelwrap_tool_call turns it into an observation
TransientTimeout, 429, 503Exception raised inside the toolInfrastructureRetryPolicy with backoff on the node
Model API failureThe provider returns 5xx or 429Exception from llm.invokeInfrastructure.with_retry() on the model
FatalRevoked credentials, a bug in the toolException raised inside the toolHumansRe-raise, alert, return an apology
No progressThe model repeats the same failing callNothing, by defaultThe loop’s budgetCount failed rounds, then give up

LangGraph’s own guide to designing agents, Thinking in LangGraph, uses the same split: transient errors get a retry policy, LLM-recoverable errors go back to the model, user-fixable errors pause for a human, and unexpected ones surface to the developer.

The silent failure: malformed JSON skips your tools entirely

When a provider returns arguments that aren’t valid JSON, LangChain can’t parse them into tool_calls. It moves the call to invalid_tool_calls instead. This is the real behavior for an OpenAI-format response with a missing quote:

what broken JSON turns into
from langchain_core.messages import AIMessage
from langgraph.prebuilt import tools_condition
raw = AIMessage("", additional_kwargs={"tool_calls": [{
"id": "call_1", "type": "function",
"function": {"name": "track_shipment", "arguments": '{"order_id": "3}'},
}]})
raw.tool_calls # []
raw.invalid_tool_calls # [{'type': 'invalid_tool_call', 'id': 'call_1', 'name': 'track_shipment',
# 'args': '{"order_id": "3}', 'error': None}]
tools_condition({"messages": [raw]}) # '__end__'

tools_condition only looks at tool_calls, so the graph routes to END and the “final answer” is an empty message. Nothing raises, nothing logs. The fix is a router that checks invalid_tool_calls first.

2. The self-correction loop

The pattern: catch the error, write it into the message history as a tool result, and route back to the agent. The model reads its own mistake on the next turn, the same way it reads any other tool output.

stateDiagram-v2
[*] --> agent
agent --> tools: valid tool calls
agent --> reject_malformed: invalid JSON
agent --> [*]: final answer
tools --> count_failures: results, or error ToolMessages
tools --> tools: transient error, retried with backoff
reject_malformed --> count_failures: error ToolMessages
count_failures --> agent: no errors, or errors within budget
count_failures --> give_up: too many failed rounds
give_up --> [*]
Happy path: agent, tools, count_failures, agent, end. Every error path also returns to the agent, except transient retries (handled inside the tools node) and an exhausted budget.

Three rules make it work:

  1. Every call ID gets exactly one result. Providers reject the next request if a tool call has no matching result. That includes calls that were never executed because a sibling in the same batch was malformed.
  2. The error is written for the model, not for a log file. Say what was wrong, show the offending value, say what valid looks like, and tell it to try again. ToolNode’s validation messages already do this: order_id: Input should be a valid integer, unable to parse string as an integer ... Please fix the error and try again.
  3. The loop has a budget. Count consecutive rounds that produced an error and stop at a threshold. Consecutive, not total: a long conversation with occasional recovered errors is healthy; three failures in a row usually means the model is stuck.

Why does this work when “ask the model to check its own answer” often doesn’t? Because the feedback is external. Huang et al. found that LLMs can’t reliably self-correct reasoning from their own judgment alone, while CRITIC showed large gains when the critique comes from tool interaction. A validation error is exactly that kind of signal: objective, specific, and impossible to argue with.

3. The code

Tools that fail in realistic ways

One tool, two exception classes the graph treats specially, and a carrier API stub whose first request times out:

tools.py
from langchain_core.tools import tool
from pydantic import BaseModel, Field
class TransientError(Exception):
"""Worth retrying without the model: timeouts, rate limits, 503s."""
class FatalError(Exception):
"""No retry can help: bad credentials, a bug. Stop and alert someone."""
ORDERS = {
3: {"status": "shipped", "tracking": "1Z999AA10123456784"},
4: {"status": "pending", "tracking": None},
}
class Carrier:
"""Stand-in for a flaky third-party API: its first request times out."""
def __init__(self):
self.requests = 0
def lookup(self, tracking: str) -> dict:
self.requests += 1
if self.requests == 1:
raise TransientError("carrier API timed out after 5s")
return {"status": "in transit", "eta": "2026-11-06", "last_scan": "Columbus, OH"}
carrier = Carrier()
class TrackShipment(BaseModel):
order_id: int = Field(description="Numeric order ID, for example 3.")
@tool(args_schema=TrackShipment)
def track_shipment(order_id: int) -> dict:
"""Get the carrier status and estimated delivery date for a shipped order."""
order = ORDERS.get(order_id)
if order is None:
raise LookupError(f"order {order_id} does not exist")
if order["tracking"] is None:
raise ValueError(f"order {order_id} is {order['status']!r} and has no tracking number yet")
return carrier.lookup(order["tracking"])
TOOLS = [track_shipment]

In a real client, map the library’s errors onto these classes at the boundary: httpx.TimeoutException and 429/5xx responses become TransientError, 401/403 become FatalError, and 404/400 stay as ordinary exceptions for the model to read.

The graph

resilient_agent.py
import traceback
from typing import Annotated, TypedDict
from langchain.chat_models import init_chat_model
from langchain_core.messages import AIMessage, AnyMessage, ToolMessage
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, StateGraph
from langgraph.graph.message import add_messages
from langgraph.prebuilt import ToolNode
from langgraph.types import RetryPolicy
from tools import TOOLS, FatalError, TransientError
MAX_FAILED_ROUNDS = 3
class State(TypedDict):
messages: Annotated[list[AnyMessage], add_messages]
failed_rounds: int # consecutive tool rounds that produced at least one error
# Provider-side failures (429s, 5xx) are retried here, before the graph sees them.
# Narrow retry_if_exception_type to your provider's rate-limit and server errors.
llm = init_chat_model("<provider>:<model>", temperature=0).bind_tools(TOOLS).with_retry(stop_after_attempt=3)
def agent(state: State):
return {"messages": [llm.invoke(state["messages"])]}
def route_agent(state: State) -> str:
last = state["messages"][-1]
if last.invalid_tool_calls:
return "reject_malformed" # tools_condition would send this to END
if last.tool_calls:
return "tools"
return END
def reject_malformed(state: State):
"""Reply to every call in a batch that contains unparseable JSON: each call ID needs a result."""
last = state["messages"][-1]
replies = [
ToolMessage(
f"Your arguments for {bad['name']} are not valid JSON ({bad.get('error') or 'parse error'}): "
f"{bad['args']!r}. Send the call again with a JSON object that matches the schema.",
tool_call_id=bad["id"],
status="error",
)
for bad in last.invalid_tool_calls
]
replies += [
ToolMessage(
"Not executed because another call in the same batch was malformed. Send it again.",
tool_call_id=call["id"],
status="error",
)
for call in last.tool_calls
]
return {"messages": replies}
def explain_errors(request, execute):
"""Turn failures the model can act on into observations; re-raise the rest."""
try:
return execute(request) # schema violations already come back as error ToolMessages
except (TransientError, FatalError):
raise # transient: the node's RetryPolicy retries it; fatal: the run stops
except Exception as e:
trace = "".join(traceback.format_exception(e, limit=-1)) # last frame only
return ToolMessage(
f"Tool {request.tool_call['name']} failed.\n{trace[-800:]}",
tool_call_id=request.tool_call["id"],
status="error",
)
def count_failures(state: State):
batch = []
for m in reversed(state["messages"]): # the ToolMessages from the round that just ran
if not isinstance(m, ToolMessage):
break
batch.append(m)
failed = any(m.status == "error" for m in batch)
return {"failed_rounds": state.get("failed_rounds", 0) + 1 if failed else 0}
def route_failures(state: State) -> str:
return "give_up" if state["failed_rounds"] >= MAX_FAILED_ROUNDS else "agent"
def give_up(state: State):
return {
"messages": [
AIMessage(
"I couldn't complete that after several attempts, so I stopped instead of guessing. "
"Please rephrase the request, or contact support."
)
]
}
builder = StateGraph(State)
builder.add_node("agent", agent)
builder.add_node("reject_malformed", reject_malformed)
builder.add_node(
"tools",
ToolNode(TOOLS, wrap_tool_call=explain_errors),
retry_policy=RetryPolicy(max_attempts=3, initial_interval=0.5, retry_on=TransientError),
)
builder.add_node("count_failures", count_failures)
builder.add_node("give_up", give_up)
builder.add_edge(START, "agent")
builder.add_conditional_edges("agent", route_agent, ["reject_malformed", "tools", END])
builder.add_edge("reject_malformed", "count_failures")
builder.add_edge("tools", "count_failures")
builder.add_conditional_edges("count_failures", route_failures, ["agent", "give_up"])
builder.add_edge("give_up", END)
app = builder.compile(checkpointer=InMemorySaver())

How each failure flows through it:

  • Malformed JSON: route_agent checks invalid_tool_calls before tool_calls, and reject_malformed answers every call in that batch, including any valid siblings. Re-running half a batch is a recipe for duplicate side effects, so the model is asked to resend the whole thing.
  • Schema violations and unknown tools: ToolNode already turns these into error ToolMessages before execute() returns, so explain_errors never sees an exception for them.
  • Backend rejections: anything else raised inside a tool reaches explain_errors through execute() and comes back as an error observation with the last stack frame. It’s enough to say where and why without dumping the whole stack into the context.
  • Transient errors: re-raised, so the node’s RetryPolicy reruns it with exponential backoff and jitter. retry_on=TransientError matters: by default, RetryPolicy retries any exception except ValueError and TypeError (and, for requests/httpx errors, only 5xx responses), which would retry fatal errors too.
  • Fatal errors: re-raised past the retry policy, so app.invoke raises. Your server catches it, alerts, and shows a generic apology.
  • No progress: count_failures increments failed_rounds after any round with an error and resets it after a clean one. Three in a row routes to give_up.

4. Three runs

The model is scripted (so it fails on cue); everything else, including validation, retries, and messages, is the real graph.

Every recoverable failure in one conversation. The model sends broken JSON, then a string where an integer belongs, then a valid call that hits the carrier timeout:

run.py
from resilient_agent import app
config = {"configurable": {"thread_id": "support-7"}, "recursion_limit": 25}
result = app.invoke({"messages": [("user", "Where is order 3, and when will it arrive?")]}, config)
for m in result["messages"]:
print(f"{m.type:>5} | {m.content or m.tool_calls or m.invalid_tool_calls}")
print("failed_rounds:", result["failed_rounds"])
human | Where is order 3, and when will it arrive?
ai | [{'type': 'invalid_tool_call', 'id': 'call_1', 'name': 'track_shipment', 'args': '{"order_id": "3}', 'error': None}]
tool | Your arguments for track_shipment are not valid JSON (parse error): '{"order_id": "3}'. Send the call again
with a JSON object that matches the schema.
ai | [{'name': 'track_shipment', 'args': {'order_id': 'three'}, 'id': 'call_2', 'type': 'tool_call'}]
tool | Error invoking tool 'track_shipment' with kwargs {'order_id': 'three'} with error:
order_id: Input should be a valid integer, unable to parse string as an integer
Please fix the error and try again.
ai | [{'name': 'track_shipment', 'args': {'order_id': 3}, 'id': 'call_3', 'type': 'tool_call'}]
tool | {"status": "in transit", "eta": "2026-11-06", "last_scan": "Columbus, OH"}
ai | Order 3 is in transit (last scanned in Columbus, OH) and should arrive on November 6.
failed_rounds: 0

The carrier received two requests: the first timed out, the RetryPolicy reran the node, and the model never knew. failed_rounds reset to 0 after the clean round.

A model that can’t recover. It keeps calling a tool that doesn’t exist:

human | Cancel order 3.
ai | [{'name': 'cancel_order', 'args': {'order_id': 3}, 'id': 'call_1', 'type': 'tool_call'}]
tool | Error: cancel_order is not a valid tool, try one of [track_shipment].
ai | [{'name': 'cancel_order', 'args': {'order_id': 3}, 'id': 'call_2', 'type': 'tool_call'}]
tool | Error: cancel_order is not a valid tool, try one of [track_shipment].
ai | [{'name': 'cancel_order', 'args': {'order_id': 3}, 'id': 'call_3', 'type': 'tool_call'}]
tool | Error: cancel_order is not a valid tool, try one of [track_shipment].
ai | I couldn't complete that after several attempts, so I stopped instead of guessing. Please rephrase the
request, or contact support.
failed_rounds: 3

Without the budget this runs until recursion_limit raises GraphRecursionError: more tokens, and an exception instead of an answer.

A rejection the model should explain, not retry. Order 4 exists but hasn’t shipped (file path shortened):

human | Where is order 4?
ai | [{'name': 'track_shipment', 'args': {'order_id': 4}, 'id': 'call_1', 'type': 'tool_call'}]
tool | Tool track_shipment failed.
Traceback (most recent call last):
File "tools.py", line 46, in track_shipment
raise ValueError(f"order {order_id} is {order['status']!r} and has no tracking number yet")
ValueError: order 4 is 'pending' and has no tracking number yet
ai | Order 4 hasn't shipped yet.

5. Design notes

  • Retries rerun the whole node. When RetryPolicy retries tools, every call in the batch runs again, including ones that succeeded. That’s fine for reads. For writes, retry inside the tool around the single request, and make the operation idempotent (an idempotency key per order and action).
  • Error text is an output channel. It goes into the prompt and can come out in the answer. The last frame is useful; absolute paths, connection strings, and SQL aren’t. Strip them before they reach the model, and send the full traceback to your logs and traces instead.
  • Timeouts belong in the client. LangGraph’s node timeout= only applies to async nodes; sync nodes can’t be cancelled in-process. Give every HTTP client its own timeout and map it to TransientError.
  • Constrained decoding reduces, but doesn’t remove, the work. Providers with a strict schema mode (OpenAI’s strict: true) eliminate malformed JSON and most schema violations. Backend rejections, wrong-but-valid values, and loops remain.
  • Make failures visible. Count invalid_tool_calls, validation errors, retries, and give-ups per model and per tool. A rising rate after a model or prompt change is the earliest regression signal you’ll get.
  • Lower the temperature for retries if you need to. A model at high temperature may not converge; at 0 it may repeat the same mistake. If one specific error recurs, put its fix in the tool description instead.

6. Pitfalls

  • Using tools_condition with a model that can emit broken JSON. It routes to END; check invalid_tool_calls.
  • Catching Exception and retrying everything. Retrying a validation error without telling the model just repeats it; retrying a 401 just delays the page.
  • Leaving tool calls unanswered. One missing ToolMessage in a batch and the provider rejects the whole next request.
  • Counting total errors instead of consecutive ones. Long, healthy sessions eventually trip a total-errors limit.
  • Letting recursion_limit be the budget. It’s a safety net, not a user experience. Give up deliberately with a message, before the limit raises.

Study checklist

  1. Swap route_agent for tools_condition, script an invalid call, and watch the run end with an empty answer.
  2. Remove retry_on=TransientError and raise FatalError from the tool. Count how many times it’s retried.
  3. Make the tool raise a LookupError and compare the model’s next move with and without the traceback line.
  4. Add a second, side-effecting tool to the same batch as a flaky read, then move the retry into the tool and make the write idempotent.
  5. Run the graph against a small open-weight model and log every error class for 50 questions.

References

Error handling in LangGraph and LangChain

  • LangGraph, Thinking in LangGraph: the “who fixes it” error taxonomy (transient, LLM-recoverable, user-fixable, unexpected)
  • LangGraph, Fault tolerance: RetryPolicy, its default retry_on, and timeouts
  • LangGraph, Durable execution: resuming runs after failures
  • LangChain, Tools: ToolNode, error handling, and tool-call wrappers
  • OpenAI, Function calling: parallel calls and strict mode
  • Anthropic, Handle tool calls: returning failures in tool_result blocks with is_error

Self-correction research