# createPatchToolCallsMiddleware

> **Function** in `deepagents`

📖 [View in docs](https://reference.langchain.com/javascript/deepagents/middleware/createPatchToolCallsMiddleware)

Create middleware that enforces strict tool call / tool response parity in
the messages history.

Two kinds of violations are repaired:
1. **Dangling tool_calls** — an AIMessage contains tool_calls with no
   matching ToolMessage responses. Synthetic cancellation ToolMessages are
   injected so every tool_call has a response.
2. **Orphaned ToolMessages** — a ToolMessage exists whose `tool_call_id`
   does not match any tool_call in a preceding AIMessage. These are removed.

This is critical for providers like Google Gemini that reject requests with
mismatched function call / function response counts (400 INVALID_ARGUMENT).

This middleware patches in two places:
1. `beforeAgent`: Patches state at the start of the agent loop (handles most cases)
2. `wrapModelCall`: Patches the request right before model invocation (handles
   edge cases like HITL rejection during graph resume where state updates from
   beforeAgent may not be applied in time)

## Signature

```javascript
createPatchToolCallsMiddleware(): AgentMiddleware<undefined, undefined, unknown, readonly ClientTool | ServerTool[], readonly []>
```

## Returns

`AgentMiddleware<undefined, undefined, unknown, readonly ClientTool | ServerTool[], readonly []>`

AgentMiddleware that enforces tool call / response parity

## Examples

```typescript
import { createAgent } from "langchain";
import { createPatchToolCallsMiddleware } from "./middleware/patch_tool_calls";

const agent = createAgent({
  model: "claude-sonnet-4-5-20250929",
  middleware: [createPatchToolCallsMiddleware()],
});
```

---

[View source on GitHub](https://github.com/langchain-ai/deepagentsjs/blob/60e32118b0ba24ea7ef636476a9a96add9d1a99b/libs/deepagents/src/middleware/patch_tool_calls.ts#L134)