Skip to main content
Fault tolerance middleware keeps your deep agent running when things go wrong. Not all errors should be handled the same way: transient failures (network timeouts, rate limits) should be retried automatically, errors the LLM can recover from (bad tool output, parsing failures) should be fed back to the model, and errors that need human input should pause the agent.

Error handling strategies

Different errors need different handling strategies: The sections below cover each strategy with code examples.
Add retry middleware to automatically retry network issues and rate limits. Model calls and tool calls each have their own retry middleware with exponential backoff:

Rate limiting

There are two complementary ways to limit resource usage: controlling the request rate to your model provider, and capping the total number of calls per run.

Provider rate limiting

Chat model providers impose a limit on the number of invocations that can be made in a given time period. To control the rate at which requests are made, initialize your model with a rate_limiter:
For the full configuration, see Rate limiting.

Call limits

Without limits, a confused agent can burn through your LLM API budget in minutes by looping on the same tool call or making hundreds of model calls. Set caps on both model calls and tool executions per run:
Use run_limit to cap calls within a single invocation (resets each turn). Use thread_limit to cap calls across an entire conversation (requires a checkpointer). See ModelCallLimitMiddleware and ToolCallLimitMiddleware for the full configuration.

Retries

Transient failures (network timeouts, rate limits) should be retried automatically. Model calls and tool calls each have their own retry middleware with exponential backoff:
Scope ToolRetryMiddleware to specific tools rather than retrying everything. A filesystem read_file that fails will not benefit from a retry, but a web search that times out probably will. See ModelRetryMiddleware for the full configuration.

Fallbacks

If your primary model provider goes down entirely, the fallback middleware switches to an alternative model:
See ModelFallbackMiddleware for the full configuration.

Error handling

When a tool raises an exception during execution, the agent run halts by default. Use ToolErrorMiddleware to catch specific exceptions and convert them into error ToolMessages that the model can see and recover from, instead of crashing the run.
ToolErrorMiddleware requires langchain>=1.3.14.
For the full configuration options and usage patterns, including async handlers and composing with retry middleware, see Prebuilt middleware.