createPatchToolCallsMiddleware(
): AgentMiddleware<undefined, undefined, unknown, readonly ClientTool | ServerTool[]>Create middleware that enforces strict tool call / tool response parity in the messages history.
Two kinds of violations are repaired:
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:
beforeAgent: Patches state at the start of the agent loop (handles most cases)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)import { createAgent } from "langchain";
import { createPatchToolCallsMiddleware } from "./middleware/patch_tool_calls";
const agent = createAgent({
model: "claude-sonnet-4-5-20250929",
middleware: [createPatchToolCallsMiddleware()],
});