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
JavaScriptdeepagentsindexcreatePatchToolCallsMiddleware
Function●Since v1.4

createPatchToolCallsMiddleware

Create middleware that patches dangling tool calls in the messages history.

When an AI message contains tool_calls but subsequent messages don't include the corresponding ToolMessage responses, this middleware adds synthetic ToolMessages saying the tool call was cancelled.

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
createPatchToolCallsMiddleware(

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

Example

Copy
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