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.
| Failure | Example | Where LangChain surfaces it | Who fixes it | Mechanism |
|---|---|---|---|---|
| Malformed JSON | {"order_id": "3} | AIMessage.invalid_tool_calls; tool_calls is empty | Model | Custom route plus an error message per call |
| Schema violation | {"order_id": "three"}, missing field, value outside an enum | ToolNode validation | Model | ToolNode’s default error message |
| Hallucinated tool | cancel_order when no such tool exists | ToolNode lookup | Model | ToolNode’s default error message |
| Rejected by the backend | Order exists but hasn’t shipped; 404; 400 for an invalid combination | Exception raised inside the tool | Model | wrap_tool_call turns it into an observation |
| Transient | Timeout, 429, 503 | Exception raised inside the tool | Infrastructure | RetryPolicy with backoff on the node |
| Model API failure | The provider returns 5xx or 429 | Exception from llm.invoke | Infrastructure | .with_retry() on the model |
| Fatal | Revoked credentials, a bug in the tool | Exception raised inside the tool | Humans | Re-raise, alert, return an apology |
| No progress | The model repeats the same failing call | Nothing, by default | The loop’s budget | Count 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:
from langchain_core.messages import AIMessagefrom 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 --> [*]
Three rules make it work:
- 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.
- 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. - 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:
from langchain_core.tools import toolfrom 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
import tracebackfrom typing import Annotated, TypedDict
from langchain.chat_models import init_chat_modelfrom langchain_core.messages import AIMessage, AnyMessage, ToolMessagefrom langgraph.checkpoint.memory import InMemorySaverfrom langgraph.graph import END, START, StateGraphfrom langgraph.graph.message import add_messagesfrom langgraph.prebuilt import ToolNodefrom 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_agentchecksinvalid_tool_callsbeforetool_calls, andreject_malformedanswers 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:
ToolNodealready turns these into errorToolMessages beforeexecute()returns, soexplain_errorsnever sees an exception for them. - Backend rejections: anything else raised inside a tool reaches
explain_errorsthroughexecute()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
RetryPolicyreruns it with exponential backoff and jitter.retry_on=TransientErrormatters: by default,RetryPolicyretries any exception exceptValueErrorandTypeError(and, forrequests/httpxerrors, only 5xx responses), which would retry fatal errors too. - Fatal errors: re-raised past the retry policy, so
app.invokeraises. Your server catches it, alerts, and shows a generic apology. - No progress:
count_failuresincrementsfailed_roundsafter any round with an error and resets it after a clean one. Three in a row routes togive_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:
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: 0The 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: 3Without 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
RetryPolicyretriestools, 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 toTransientError. - 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_conditionwith a model that can emit broken JSON. It routes toEND; checkinvalid_tool_calls. - Catching
Exceptionand 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
ToolMessagein 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_limitbe the budget. It’s a safety net, not a user experience. Give up deliberately with a message, before the limit raises.
Study checklist
- Swap
route_agentfortools_condition, script an invalid call, and watch the run end with an empty answer. - Remove
retry_on=TransientErrorand raiseFatalErrorfrom the tool. Count how many times it’s retried. - Make the tool raise a
LookupErrorand compare the model’s next move with and without the traceback line. - 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.
- 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 defaultretry_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
strictmode - Anthropic, Handle tool calls: returning failures in
tool_resultblocks withis_error
Self-correction research
- Huang et al., Large Language Models Cannot Self-Correct Reasoning Yet (2023): why intrinsic self-correction disappoints
- Gou et al., CRITIC: Large Language Models Can Self-Correct with Tool-Interactive Critiquing (2023): external feedback makes it work
- Madaan et al., Self-Refine: Iterative Refinement with Self-Feedback (2023)
- Shinn et al., Reflexion: Language Agents with Verbal Reinforcement Learning (2023)
- Berkeley Function Calling Leaderboard: measured tool-calling error rates across models