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?: "continue" | "error" | ((...args: [Error, ...unknown[]]) => string)Behavior when all retries are exhausted. Options:
"continue" (default): Return an AIMessage with error details, allowing
the agent to potentially handle the failure gracefully."error": 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.
A middleware instance that handles model failures with retries
import { createAgent, modelRetryMiddleware } from "langchain";
const agent = createAgent({
model: "openai:gpt-4o",
tools: [searchTool],
middleware: [modelRetryMiddleware()],
});
import { modelRetryMiddleware } from "langchain";
const retry = modelRetryMiddleware({
maxRetries: 4,
retryOn: [TimeoutError, NetworkError],
backoffFactor: 1.5,
});
function shouldRetry(error: Error): boolean {
// Only retry on rate limit errors
if (error.name === "RateLimitError") {
return true;
}
// Or check for specific HTTP status codes
if (error.name === "HTTPError" && "statusCode" in error) {
const statusCode = (error as any).statusCode;
return statusCode === 429 || statusCode === 503;
}
return false;
}
const retry = modelRetryMiddleware({
maxRetries: 3,
retryOn: shouldRetry,
});
const retry = modelRetryMiddleware({
maxRetries: 4,
onFailure: "continue", // Return AIMessage with error instead of throwing
});
const formatError = (error: Error) =>
`Model call failed: ${error.message}. Please try again later.`;
const retry = modelRetryMiddleware({
maxRetries: 4,
onFailure: formatError,
});
Middleware that automatically retries failed model calls with configurable backoff.
Supports retrying on specific exceptions and exponential backoff.