Configuration options for the retry middleware
OptionalbackoffFactor?: numberMultiplier for exponential backoff. Each retry waits
initialDelayMs * (backoffFactor ** retryNumber) milliseconds.
Set to 0.0 for constant delay. Default is 2.0.
OptionalinitialDelayMs?: numberInitial delay in milliseconds before first retry. Default is 1000 (1 second).
Optionaljitter?: booleanWhether to add random jitter (±25%) to delay to avoid thundering herd.
Default is true.
OptionalmaxDelayMs?: numberMaximum delay in milliseconds between retries. Caps exponential backoff growth. Default is 60000 (60 seconds).
OptionalmaxRetries?: numberMaximum number of retry attempts after the initial call. Default is 2 retries (3 total attempts). Must be >= 0.
OptionalonFailure?: "raise" | "return_message" | ((...args: [Error, ...unknown[]]) => string)Behavior when all retries are exhausted. Options:
"return_message" (default): Return a ToolMessage with error details,
allowing the LLM to handle the failure and potentially recover."raise": Re-raise the exception, stopping agent execution.OptionalretryOn?: Either an array of error constructors to retry on, or a function
that takes an error and returns true if it should be retried.
Default is to retry on all errors.
Optionaltools?: any[]Optional list of tools or tool names to apply retry logic to.
Can be a list of BaseTool instances or tool name strings.
If undefined, applies to all tools. Default is undefined.
A middleware instance that handles tool failures with retries
import { createAgent, toolRetryMiddleware } from "langchain";
const agent = createAgent({
model: "openai:gpt-4o",
tools: [searchTool],
middleware: [toolRetryMiddleware()],
});
import { toolRetryMiddleware } from "langchain";
const retry = toolRetryMiddleware({
maxRetries: 4,
retryOn: [TimeoutError, NetworkError],
backoffFactor: 1.5,
});
function shouldRetry(error: Error): boolean {
// Only retry on 5xx errors
if (error.name === "HTTPError" && "statusCode" in error) {
const statusCode = (error as any).statusCode;
return 500 <= statusCode && statusCode < 600;
}
return false;
}
const retry = toolRetryMiddleware({
maxRetries: 3,
retryOn: shouldRetry,
});
const formatError = (error: Error) =>
"Database temporarily unavailable. Please try again later.";
const retry = toolRetryMiddleware({
maxRetries: 4,
tools: ["search_database"],
onFailure: formatError,
});
import { tool } from "@langchain/core/tools";
import { z } from "zod";
const searchDatabase = tool(
async ({ query }) => {
// Search implementation
return results;
},
{
name: "search_database",
description: "Search the database",
schema: z.object({ query: z.string() }),
}
);
const retry = toolRetryMiddleware({
maxRetries: 4,
tools: [searchDatabase], // Pass BaseTool instance
});
Middleware that automatically retries failed tool calls with configurable backoff.
Supports retrying on specific exceptions and exponential backoff.