# toolRetryMiddleware

> **Function** in `langchain`

📖 [View in docs](https://reference.langchain.com/javascript/langchain/index/toolRetryMiddleware)

Middleware that automatically retries failed tool calls with configurable backoff.

Supports retrying on specific exceptions and exponential backoff.

## Signature

```javascript
toolRetryMiddleware(config: __type = {}): AgentMiddleware<undefined, ZodObject<__type & __type, "strip", ZodTypeAny, __type, __type>, __type, readonly ClientTool | ServerTool[]>
```

## Parameters

| Name | Type | Required | Description |
|------|------|----------|-------------|
| `config` | `__type` | No | Configuration options for the retry middleware (default: `{}`) |

## Returns

`AgentMiddleware<undefined, ZodObject<__type & __type, "strip", ZodTypeAny, __type, __type>, __type, readonly ClientTool | ServerTool[]>`

A middleware instance that handles tool failures with retries

## Examples

### Example 1

```ts
import { createAgent, toolRetryMiddleware } from "langchain";

const agent = createAgent({
  model: "openai:gpt-4o",
  tools: [searchTool],
  middleware: [toolRetryMiddleware()],
});
```

### Example 2

```ts
import { toolRetryMiddleware } from "langchain";

const retry = toolRetryMiddleware({
  maxRetries: 4,
  retryOn: [TimeoutError, NetworkError],
  backoffFactor: 1.5,
});
```

### Example 3

```ts
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,
});
```

### Example 4

```ts
const formatError = (error: Error) =>
  "Database temporarily unavailable. Please try again later.";

const retry = toolRetryMiddleware({
  maxRetries: 4,
  tools: ["search_database"],
  onFailure: formatError,
});
```

### Example 5

```ts
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
});
```

### Example 6

```ts
const retry = toolRetryMiddleware({
  maxRetries: 5,
  backoffFactor: 0.0, // No exponential growth
  initialDelayMs: 2000, // Always wait 2 seconds
});
```

### Example 7

```ts
const retry = toolRetryMiddleware({
  maxRetries: 2,
  onFailure: "raise", // Re-raise exception instead of returning message
});
```

---

[View source on GitHub](https://github.com/langchain-ai/langchainjs/blob/0c9440396c725d43b4758eb1b931c955e64ad8ec/libs/langchain/src/agents/middleware/toolRetry.ts#L162)