LangChain Reference home pageLangChain ReferenceLangChain Reference
  • GitHub
  • Main Docs
Deep Agents
LangChain
LangGraph
Integrations
LangSmith
  • Overview
  • Agent
  • Middleware
  • Backends
  • Sandboxes
  • Skills
  • Subagents
  • Configuration
  • Types
Modal
Daytona
Deno
Node VFS
Sandbox Standard Tests
  • Vitest
⌘I

LangChain Assistant

Ask a question to get started

Enter to send•Shift+Enter new line

Menu

OverviewAgentMiddlewareBackendsSandboxesSkillsSubagentsConfigurationTypes
Modal
Daytona
Deno
Node VFS
Sandbox Standard Tests
Vitest
Language
Theme
JavaScriptdeepagentsmiddlewarecreatePatchToolCallsMiddleware
Function●Since v1.4

createPatchToolCallsMiddleware

Copy
createPatchToolCallsMiddleware(

): AgentMiddleware<undefined, undefined, unknown, readonly ClientTool | ServerTool[]>
View source on GitHub

Example

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)
Copy
import { createAgent } from "langchain";
import { createPatchToolCallsMiddleware } from "./middleware/patch_tool_calls";

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