langchain 1.5.10 → 1.5.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/_virtual/_rolldown/runtime.cjs +1 -1
  3. package/dist/agents/ReactAgent.cjs.map +1 -1
  4. package/dist/agents/ReactAgent.js.map +1 -1
  5. package/dist/agents/RunnableCallable.cjs.map +1 -1
  6. package/dist/agents/RunnableCallable.js.map +1 -1
  7. package/dist/agents/annotation.cjs.map +1 -1
  8. package/dist/agents/errors.cjs.map +1 -1
  9. package/dist/agents/middleware/constants.cjs.map +1 -1
  10. package/dist/agents/middleware/contextEditing.cjs.map +1 -1
  11. package/dist/agents/middleware/contextEditing.js.map +1 -1
  12. package/dist/agents/middleware/hitl.cjs +2 -1
  13. package/dist/agents/middleware/hitl.cjs.map +1 -1
  14. package/dist/agents/middleware/hitl.js +2 -1
  15. package/dist/agents/middleware/hitl.js.map +1 -1
  16. package/dist/agents/middleware/llmToolSelector.cjs +2 -1
  17. package/dist/agents/middleware/llmToolSelector.cjs.map +1 -1
  18. package/dist/agents/middleware/llmToolSelector.js +2 -1
  19. package/dist/agents/middleware/llmToolSelector.js.map +1 -1
  20. package/dist/agents/middleware/pii.cjs +17 -15
  21. package/dist/agents/middleware/pii.cjs.map +1 -1
  22. package/dist/agents/middleware/pii.js +17 -15
  23. package/dist/agents/middleware/pii.js.map +1 -1
  24. package/dist/agents/middleware/providerToolSearch.cjs.map +1 -1
  25. package/dist/agents/middleware/summarization.cjs +9 -2
  26. package/dist/agents/middleware/summarization.cjs.map +1 -1
  27. package/dist/agents/middleware/summarization.js +9 -2
  28. package/dist/agents/middleware/summarization.js.map +1 -1
  29. package/dist/agents/middleware/todoListMiddleware.cjs.map +1 -1
  30. package/dist/agents/middleware/toolCallLimit.cjs +5 -1
  31. package/dist/agents/middleware/toolCallLimit.cjs.map +1 -1
  32. package/dist/agents/middleware/toolCallLimit.js +5 -1
  33. package/dist/agents/middleware/toolCallLimit.js.map +1 -1
  34. package/dist/agents/middleware/toolEmulator.cjs +4 -2
  35. package/dist/agents/middleware/toolEmulator.cjs.map +1 -1
  36. package/dist/agents/middleware/toolEmulator.js +4 -2
  37. package/dist/agents/middleware/toolEmulator.js.map +1 -1
  38. package/dist/agents/middleware/toolError.cjs.map +1 -1
  39. package/dist/agents/middleware/utils.cjs.map +1 -1
  40. package/dist/agents/nodes/AgentNode.cjs +4 -1
  41. package/dist/agents/nodes/AgentNode.cjs.map +1 -1
  42. package/dist/agents/nodes/AgentNode.js +4 -1
  43. package/dist/agents/nodes/AgentNode.js.map +1 -1
  44. package/dist/agents/nodes/ToolNode.cjs +9 -7
  45. package/dist/agents/nodes/ToolNode.cjs.map +1 -1
  46. package/dist/agents/nodes/ToolNode.js +9 -7
  47. package/dist/agents/nodes/ToolNode.js.map +1 -1
  48. package/dist/agents/nodes/middleware.cjs.map +1 -1
  49. package/dist/agents/nodes/utils.cjs +2 -1
  50. package/dist/agents/nodes/utils.cjs.map +1 -1
  51. package/dist/agents/nodes/utils.js +2 -1
  52. package/dist/agents/nodes/utils.js.map +1 -1
  53. package/dist/agents/responses.cjs +1 -1
  54. package/dist/agents/responses.cjs.map +1 -1
  55. package/dist/agents/responses.d.cts.map +1 -1
  56. package/dist/agents/responses.d.ts.map +1 -1
  57. package/dist/agents/responses.js +1 -1
  58. package/dist/agents/responses.js.map +1 -1
  59. package/dist/agents/transformers/subagent.cjs.map +1 -1
  60. package/dist/agents/transformers/subagent.js.map +1 -1
  61. package/dist/agents/transformers/tool-call.cjs.map +1 -1
  62. package/dist/agents/transformers/tool-call.js.map +1 -1
  63. package/dist/agents/types.d.cts.map +1 -1
  64. package/dist/agents/types.d.ts.map +1 -1
  65. package/dist/agents/utils.cjs.map +1 -1
  66. package/dist/chat_models/universal.cjs +12 -10
  67. package/dist/chat_models/universal.cjs.map +1 -1
  68. package/dist/chat_models/universal.js +12 -10
  69. package/dist/chat_models/universal.js.map +1 -1
  70. package/dist/hub/base.cjs.map +1 -1
  71. package/dist/hub/base.js.map +1 -1
  72. package/dist/hub/index.cjs +2 -1
  73. package/dist/hub/index.cjs.map +1 -1
  74. package/dist/hub/index.js +2 -1
  75. package/dist/hub/index.js.map +1 -1
  76. package/dist/hub/node.cjs +4 -2
  77. package/dist/hub/node.cjs.map +1 -1
  78. package/dist/hub/node.js +4 -2
  79. package/dist/hub/node.js.map +1 -1
  80. package/dist/load/index.cjs.map +1 -1
  81. package/dist/tools/headless.cjs.map +1 -1
  82. package/package.json +18 -18
@@ -1 +1 @@
1
- {"version":3,"file":"toolEmulator.cjs","names":["initChatModel","createMiddleware","INTERNAL_CALL_TAG","HumanMessage","ToolMessage"],"sources":["../../../src/agents/middleware/toolEmulator.ts"],"sourcesContent":["import { HumanMessage, ToolMessage } from \"@langchain/core/messages\";\nimport type { BaseChatModel } from \"@langchain/core/language_models/chat_models\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\nimport { initChatModel } from \"../../chat_models/universal.js\";\nimport {\n mergeConfigs,\n pickRunnableConfigKeys,\n type RunnableConfig,\n} from \"@langchain/core/runnables\";\nimport { createMiddleware } from \"../middleware.js\";\nimport { INTERNAL_CALL_TAG } from \"./constants.js\";\n\n/**\n * Options for configuring the Tool Emulator middleware.\n */\nexport interface ToolEmulatorOptions {\n /**\n * List of tool names (string) or tool instances to emulate.\n * - If `undefined` (default), ALL tools will be emulated.\n * - If empty array, no tools will be emulated.\n * - If array with tool names/instances, only those tools will be emulated.\n */\n tools?: (string | ClientTool | ServerTool)[];\n\n /**\n * Model to use for emulation.\n * - Can be a model identifier string (e.g., \"anthropic:claude-sonnet-4-5-20250929\")\n * - Can be a BaseChatModel instance\n * - Defaults to agent model\n */\n model?: string | BaseChatModel;\n}\n\n/**\n * Middleware that emulates specified tools using an LLM instead of executing them.\n *\n * This middleware allows selective emulation of tools for testing purposes.\n * By default (when `tools` is undefined), all tools are emulated. You can specify\n * which tools to emulate by passing a list of tool names or tool instances.\n *\n * @param options - Configuration options for the middleware\n * @param options.tools - List of tool names or tool instances to emulate. If undefined, all tools are emulated.\n * @param options.model - Model to use for emulation. Defaults to \"anthropic:claude-sonnet-4-5-20250929\".\n *\n * @example Emulate all tools (default behavior)\n * ```ts\n * import { toolEmulatorMiddleware } from \"@langchain/langchain/agents/middleware\";\n * import { createAgent } from \"@langchain/langchain/agents\";\n *\n * const middleware = toolEmulatorMiddleware();\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * tools: [getWeather, getUserLocation, calculator],\n * middleware: [middleware],\n * });\n * ```\n *\n * @example Emulate specific tools by name\n * ```ts\n * const middleware = toolEmulatorMiddleware({\n * tools: [\"get_weather\", \"get_user_location\"]\n * });\n * ```\n *\n * @example Use a custom model for emulation\n * ```ts\n * const middleware = toolEmulatorMiddleware({\n * tools: [\"get_weather\"],\n * model: \"anthropic:claude-sonnet-4-5-20250929\"\n * });\n * ```\n *\n * @example Emulate specific tools by passing tool instances\n * ```ts\n * const middleware = toolEmulatorMiddleware({\n * tools: [getWeather, getUserLocation]\n * });\n * ```\n */\nexport function toolEmulatorMiddleware(options: ToolEmulatorOptions = {}) {\n let agentModel: BaseChatModel | undefined;\n const { tools, model } = options;\n\n /**\n * Extract tool names from tools\n */\n const emulateAll = !tools || tools.length === 0;\n const toolsToEmulate = new Set<string>();\n\n if (!emulateAll && tools) {\n for (const tool of tools) {\n if (typeof tool === \"string\") {\n toolsToEmulate.add(tool);\n } else {\n // Assume tool instance with .name property\n const toolName =\n typeof tool.name === \"string\" ? tool.name : String(tool.name);\n toolsToEmulate.add(toolName);\n }\n }\n }\n\n /**\n * Initialize emulator model\n * We'll initialize it lazily in wrapToolCall to handle async initChatModel\n */\n let emulatorModel: BaseChatModel | undefined;\n const getEmulatorModel = async (): Promise<BaseChatModel> => {\n if (typeof model === \"object\") {\n return model;\n }\n if (typeof model === \"string\") {\n emulatorModel =\n emulatorModel ??\n (await initChatModel(model, { temperature: 1 }).catch((err) => {\n console.error(\n \"Error initializing emulator model, using agent model:\",\n err\n );\n return agentModel as BaseChatModel;\n }));\n return emulatorModel ?? (agentModel as BaseChatModel);\n }\n return agentModel as BaseChatModel;\n };\n\n return createMiddleware({\n name: \"ToolEmulatorMiddleware\",\n wrapModelCall: async (request, handler) => {\n agentModel = request.model as BaseChatModel;\n return handler(request);\n },\n wrapToolCall: async (request, handler) => {\n const toolName = request.toolCall.name;\n\n // Check if this tool should be emulated\n const shouldEmulate = emulateAll || toolsToEmulate.has(toolName);\n\n if (!shouldEmulate) {\n // Let it execute normally by calling the handler\n return handler(request);\n }\n\n // Extract tool information for emulation\n const toolArgs = request.toolCall.args;\n const toolDescription =\n request.tool?.description || \"No description available\";\n\n // Build prompt for emulator LLM\n const toolArgsString =\n typeof toolArgs === \"string\" ? toolArgs : JSON.stringify(toolArgs);\n const prompt = `You are emulating a tool call for testing purposes.\n\nTool: ${toolName}\nDescription: ${toolDescription}\nArguments: ${toolArgsString}\n\nGenerate a realistic response that this tool would return given these arguments.\nReturn ONLY the tool's output, no explanation or preamble. Introduce variation into your responses.`;\n\n // Get emulated response from LLM\n const emulator = await getEmulatorModel();\n const baseConfig: RunnableConfig =\n pickRunnableConfigKeys(request.runtime) ?? {};\n const config = mergeConfigs(baseConfig, {\n metadata: { lc_source: \"toolEmulation\" },\n tags: [INTERNAL_CALL_TAG],\n });\n const response = await emulator.invoke(\n [new HumanMessage(prompt)],\n config\n );\n\n // Extract content from response\n const content =\n typeof response.content === \"string\"\n ? response.content\n : JSON.stringify(response.content);\n\n // Short-circuit: return emulated result without executing real tool\n return new ToolMessage({\n content,\n tool_call_id: request.toolCall.id ?? \"\",\n name: toolName,\n });\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgFA,SAAgB,uBAAuB,UAA+B,CAAC,GAAG;CACxE,IAAI;CACJ,MAAM,EAAE,OAAO,UAAU;;;;CAKzB,M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SAAS,OAC9B,CAAC,IAAIC,yBAAAA,aAAa,MAAM,CAAC,GACzB,MACF;GASA,OAAO,IAAIC,yBAAAA,YAAY;IACrB,SANA,OAAO,SAAS,YAAY,WACxB,SAAS,UACT,KAAK,UAAU,SAAS,OAAO;IAKnC,cAAc,QAAQ,SAAS,MAAM;IACrC,MAAM;GACR,CAAC;EACH;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"toolEmulator.cjs","names":["initChatModel","createMiddleware","pickRunnableConfigKeys","mergeConfigs","INTERNAL_CALL_TAG","HumanMessage","ToolMessage"],"sources":["../../../src/agents/middleware/toolEmulator.ts"],"sourcesContent":["import { HumanMessage, ToolMessage } from \"@langchain/core/messages\";\nimport type { BaseChatModel } from \"@langchain/core/language_models/chat_models\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\nimport { initChatModel } from \"../../chat_models/universal.js\";\nimport {\n mergeConfigs,\n pickRunnableConfigKeys,\n type RunnableConfig,\n} from \"@langchain/core/runnables\";\nimport { createMiddleware } from \"../middleware.js\";\nimport { INTERNAL_CALL_TAG } from \"./constants.js\";\n\n/**\n * Options for configuring the Tool Emulator middleware.\n */\nexport interface ToolEmulatorOptions {\n /**\n * List of tool names (string) or tool instances to emulate.\n * - If `undefined` (default), ALL tools will be emulated.\n * - If empty array, no tools will be emulated.\n * - If array with tool names/instances, only those tools will be emulated.\n */\n tools?: (string | ClientTool | ServerTool)[];\n\n /**\n * Model to use for emulation.\n * - Can be a model identifier string (e.g., \"anthropic:claude-sonnet-4-5-20250929\")\n * - Can be a BaseChatModel instance\n * - Defaults to agent model\n */\n model?: string | BaseChatModel;\n}\n\n/**\n * Middleware that emulates specified tools using an LLM instead of executing them.\n *\n * This middleware allows selective emulation of tools for testing purposes.\n * By default (when `tools` is undefined), all tools are emulated. You can specify\n * which tools to emulate by passing a list of tool names or tool instances.\n *\n * @param options - Configuration options for the middleware\n * @param options.tools - List of tool names or tool instances to emulate. If undefined, all tools are emulated.\n * @param options.model - Model to use for emulation. Defaults to \"anthropic:claude-sonnet-4-5-20250929\".\n *\n * @example Emulate all tools (default behavior)\n * ```ts\n * import { toolEmulatorMiddleware } from \"@langchain/langchain/agents/middleware\";\n * import { createAgent } from \"@langchain/langchain/agents\";\n *\n * const middleware = toolEmulatorMiddleware();\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * tools: [getWeather, getUserLocation, calculator],\n * middleware: [middleware],\n * });\n * ```\n *\n * @example Emulate specific tools by name\n * ```ts\n * const middleware = toolEmulatorMiddleware({\n * tools: [\"get_weather\", \"get_user_location\"]\n * });\n * ```\n *\n * @example Use a custom model for emulation\n * ```ts\n * const middleware = toolEmulatorMiddleware({\n * tools: [\"get_weather\"],\n * model: \"anthropic:claude-sonnet-4-5-20250929\"\n * });\n * ```\n *\n * @example Emulate specific tools by passing tool instances\n * ```ts\n * const middleware = toolEmulatorMiddleware({\n * tools: [getWeather, getUserLocation]\n * });\n * ```\n */\nexport function toolEmulatorMiddleware(options: ToolEmulatorOptions = {}) {\n let agentModel: BaseChatModel | undefined;\n const { tools, model } = options;\n\n /**\n * Extract tool names from tools\n */\n const emulateAll = !tools || tools.length === 0;\n const toolsToEmulate = new Set<string>();\n\n if (!emulateAll && tools) {\n for (const tool of tools) {\n if (typeof tool === \"string\") {\n toolsToEmulate.add(tool);\n } else {\n // Assume tool instance with .name property\n const toolName =\n typeof tool.name === \"string\" ? tool.name : String(tool.name);\n toolsToEmulate.add(toolName);\n }\n }\n }\n\n /**\n * Initialize emulator model\n * We'll initialize it lazily in wrapToolCall to handle async initChatModel\n */\n let emulatorModel: BaseChatModel | undefined;\n const getEmulatorModel = async (): Promise<BaseChatModel> => {\n if (typeof model === \"object\") {\n return model;\n }\n if (typeof model === \"string\") {\n emulatorModel =\n emulatorModel ??\n (await initChatModel(model, { temperature: 1 }).catch((err) => {\n console.error(\n \"Error initializing emulator model, using agent model:\",\n err\n );\n return agentModel as BaseChatModel;\n }));\n return emulatorModel ?? (agentModel as BaseChatModel);\n }\n return agentModel as BaseChatModel;\n };\n\n return createMiddleware({\n name: \"ToolEmulatorMiddleware\",\n wrapModelCall: async (request, handler) => {\n agentModel = request.model as BaseChatModel;\n return handler(request);\n },\n wrapToolCall: async (request, handler) => {\n const toolName = request.toolCall.name;\n\n // Check if this tool should be emulated\n const shouldEmulate = emulateAll || toolsToEmulate.has(toolName);\n\n if (!shouldEmulate) {\n // Let it execute normally by calling the handler\n return handler(request);\n }\n\n // Extract tool information for emulation\n const toolArgs = request.toolCall.args;\n const toolDescription =\n request.tool?.description || \"No description available\";\n\n // Build prompt for emulator LLM\n const toolArgsString =\n typeof toolArgs === \"string\" ? toolArgs : JSON.stringify(toolArgs);\n const prompt = `You are emulating a tool call for testing purposes.\n\nTool: ${toolName}\nDescription: ${toolDescription}\nArguments: ${toolArgsString}\n\nGenerate a realistic response that this tool would return given these arguments.\nReturn ONLY the tool's output, no explanation or preamble. Introduce variation into your responses.`;\n\n // Get emulated response from LLM\n const emulator = await getEmulatorModel();\n const baseConfig: RunnableConfig =\n pickRunnableConfigKeys(request.runtime) ?? {};\n const config = mergeConfigs(baseConfig, {\n metadata: { lc_source: \"toolEmulation\" },\n tags: [INTERNAL_CALL_TAG],\n });\n const response = await emulator.invoke(\n [new HumanMessage(prompt)],\n config\n );\n\n // Extract content from response\n const content =\n typeof response.content === \"string\"\n ? response.content\n : JSON.stringify(response.content);\n\n // Short-circuit: return emulated result without executing real tool\n return new ToolMessage({\n content,\n tool_call_id: request.toolCall.id ?? \"\",\n name: toolName,\n });\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgFA,SAAgB,uBAAuB,UAA+B,CAAC,GAAG;CACxE,IAAI;CACJ,MAAM,EAAE,OAAO,UAAU;;;;CAKzB,MAAM,aAAa,CAAC,SAAS,MAAM,WAAW;CAC9C,MAAM,iCAAiB,IAAI,IAAY;CAEvC,IAAI,CAAC,cAAc,OACjB,K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UACJ,OAAO,SAAS,YAAY,WACxB,SAAS,UACT,KAAK,UAAU,SAAS,OAAO;GAGrC,OAAO,IAAIC,yBAAAA,YAAY;IACrB;IACA,cAAc,QAAQ,SAAS,MAAM;IACrC,MAAM;GACR,CAAC;EACH;CACF,CAAC;AACH"}
@@ -99,13 +99,15 @@ Arguments: ${typeof toolArgs === "string" ? toolArgs : JSON.stringify(toolArgs)}
99
99
  Generate a realistic response that this tool would return given these arguments.
100
100
  Return ONLY the tool's output, no explanation or preamble. Introduce variation into your responses.`;
101
101
  const emulator = await getEmulatorModel();
102
- const config = mergeConfigs(pickRunnableConfigKeys(request.runtime) ?? {}, {
102
+ const baseConfig = pickRunnableConfigKeys(request.runtime) ?? {};
103
+ const config = mergeConfigs(baseConfig, {
103
104
  metadata: { lc_source: "toolEmulation" },
104
105
  tags: [INTERNAL_CALL_TAG]
105
106
  });
106
107
  const response = await emulator.invoke([new HumanMessage(prompt)], config);
108
+ const content = typeof response.content === "string" ? response.content : JSON.stringify(response.content);
107
109
  return new ToolMessage({
108
- content: typeof response.content === "string" ? response.content : JSON.stringify(response.content),
110
+ content,
109
111
  tool_call_id: request.toolCall.id ?? "",
110
112
  name: toolName
111
113
  });
@@ -1 +1 @@
1
- {"version":3,"file":"toolEmulator.js","names":[],"sources":["../../../src/agents/middleware/toolEmulator.ts"],"sourcesContent":["import { HumanMessage, ToolMessage } from \"@langchain/core/messages\";\nimport type { BaseChatModel } from \"@langchain/core/language_models/chat_models\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\nimport { initChatModel } from \"../../chat_models/universal.js\";\nimport {\n mergeConfigs,\n pickRunnableConfigKeys,\n type RunnableConfig,\n} from \"@langchain/core/runnables\";\nimport { createMiddleware } from \"../middleware.js\";\nimport { INTERNAL_CALL_TAG } from \"./constants.js\";\n\n/**\n * Options for configuring the Tool Emulator middleware.\n */\nexport interface ToolEmulatorOptions {\n /**\n * List of tool names (string) or tool instances to emulate.\n * - If `undefined` (default), ALL tools will be emulated.\n * - If empty array, no tools will be emulated.\n * - If array with tool names/instances, only those tools will be emulated.\n */\n tools?: (string | ClientTool | ServerTool)[];\n\n /**\n * Model to use for emulation.\n * - Can be a model identifier string (e.g., \"anthropic:claude-sonnet-4-5-20250929\")\n * - Can be a BaseChatModel instance\n * - Defaults to agent model\n */\n model?: string | BaseChatModel;\n}\n\n/**\n * Middleware that emulates specified tools using an LLM instead of executing them.\n *\n * This middleware allows selective emulation of tools for testing purposes.\n * By default (when `tools` is undefined), all tools are emulated. You can specify\n * which tools to emulate by passing a list of tool names or tool instances.\n *\n * @param options - Configuration options for the middleware\n * @param options.tools - List of tool names or tool instances to emulate. If undefined, all tools are emulated.\n * @param options.model - Model to use for emulation. Defaults to \"anthropic:claude-sonnet-4-5-20250929\".\n *\n * @example Emulate all tools (default behavior)\n * ```ts\n * import { toolEmulatorMiddleware } from \"@langchain/langchain/agents/middleware\";\n * import { createAgent } from \"@langchain/langchain/agents\";\n *\n * const middleware = toolEmulatorMiddleware();\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * tools: [getWeather, getUserLocation, calculator],\n * middleware: [middleware],\n * });\n * ```\n *\n * @example Emulate specific tools by name\n * ```ts\n * const middleware = toolEmulatorMiddleware({\n * tools: [\"get_weather\", \"get_user_location\"]\n * });\n * ```\n *\n * @example Use a custom model for emulation\n * ```ts\n * const middleware = toolEmulatorMiddleware({\n * tools: [\"get_weather\"],\n * model: \"anthropic:claude-sonnet-4-5-20250929\"\n * });\n * ```\n *\n * @example Emulate specific tools by passing tool instances\n * ```ts\n * const middleware = toolEmulatorMiddleware({\n * tools: [getWeather, getUserLocation]\n * });\n * ```\n */\nexport function toolEmulatorMiddleware(options: ToolEmulatorOptions = {}) {\n let agentModel: BaseChatModel | undefined;\n const { tools, model } = options;\n\n /**\n * Extract tool names from tools\n */\n const emulateAll = !tools || tools.length === 0;\n const toolsToEmulate = new Set<string>();\n\n if (!emulateAll && tools) {\n for (const tool of tools) {\n if (typeof tool === \"string\") {\n toolsToEmulate.add(tool);\n } else {\n // Assume tool instance with .name property\n const toolName =\n typeof tool.name === \"string\" ? tool.name : String(tool.name);\n toolsToEmulate.add(toolName);\n }\n }\n }\n\n /**\n * Initialize emulator model\n * We'll initialize it lazily in wrapToolCall to handle async initChatModel\n */\n let emulatorModel: BaseChatModel | undefined;\n const getEmulatorModel = async (): Promise<BaseChatModel> => {\n if (typeof model === \"object\") {\n return model;\n }\n if (typeof model === \"string\") {\n emulatorModel =\n emulatorModel ??\n (await initChatModel(model, { temperature: 1 }).catch((err) => {\n console.error(\n \"Error initializing emulator model, using agent model:\",\n err\n );\n return agentModel as BaseChatModel;\n }));\n return emulatorModel ?? (agentModel as BaseChatModel);\n }\n return agentModel as BaseChatModel;\n };\n\n return createMiddleware({\n name: \"ToolEmulatorMiddleware\",\n wrapModelCall: async (request, handler) => {\n agentModel = request.model as BaseChatModel;\n return handler(request);\n },\n wrapToolCall: async (request, handler) => {\n const toolName = request.toolCall.name;\n\n // Check if this tool should be emulated\n const shouldEmulate = emulateAll || toolsToEmulate.has(toolName);\n\n if (!shouldEmulate) {\n // Let it execute normally by calling the handler\n return handler(request);\n }\n\n // Extract tool information for emulation\n const toolArgs = request.toolCall.args;\n const toolDescription =\n request.tool?.description || \"No description available\";\n\n // Build prompt for emulator LLM\n const toolArgsString =\n typeof toolArgs === \"string\" ? toolArgs : JSON.stringify(toolArgs);\n const prompt = `You are emulating a tool call for testing purposes.\n\nTool: ${toolName}\nDescription: ${toolDescription}\nArguments: ${toolArgsString}\n\nGenerate a realistic response that this tool would return given these arguments.\nReturn ONLY the tool's output, no explanation or preamble. Introduce variation into your responses.`;\n\n // Get emulated response from LLM\n const emulator = await getEmulatorModel();\n const baseConfig: RunnableConfig =\n pickRunnableConfigKeys(request.runtime) ?? {};\n const config = mergeConfigs(baseConfig, {\n metadata: { lc_source: \"toolEmulation\" },\n tags: [INTERNAL_CALL_TAG],\n });\n const response = await emulator.invoke(\n [new HumanMessage(prompt)],\n config\n );\n\n // Extract content from response\n const content =\n typeof response.content === \"string\"\n ? response.content\n : JSON.stringify(response.content);\n\n // Short-circuit: return emulated result without executing real tool\n return new ToolMessage({\n content,\n tool_call_id: request.toolCall.id ?? \"\",\n name: toolName,\n });\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgFA,SAAgB,uBAAuB,UAA+B,CAAC,GAAG;CACxE,IAAI;CACJ,MAAM,EAAE,OAAO,UAAU;;;;CAKzB,MAAM,aAAa,CAAC,SAAS,MAAM,WAAW;CAC9C,MAAM,iCAAiB,IAAI,IAAY;CAEvC,IAAI,CAAC,cAAc,OACjB,KAAK,MAAM,QAAQ,OACjB,IAAI,OAAO,SAAS,UAClB,eAAe,IAAI,IAAI;MAClB;EAEL,MAAM,WACJ,OAAO,KAAK,SAAS,WAAW,KAAK,OAAO,OAAO,KAAK,IAAI;EAC9D,eAAe,IAAI,QAAQ;CAC7B;;;;;CAQJ,IAAI;CACJ,MAAM,mBAAmB,YAAoC;EAC3D,IAAI,OAAO,UAAU,UACnB,OAAO;EAET,IAAI,OAAO,UAAU,UAAU;GAC7B,gBACE,iBACC,MAAM,cAAc,OAAO,EAAE,aAAa,EAAE,CAAC,CAAC,CAAC,OAAO,QAAQ;IAC7D,QAAQ,MACN,yDACA,GACF;IACA,OAAO;GACT,CAAC;GACH,OAAO,iBAAkB;EAC3B;EACA,OAAO;CACT;CAEA,OAAO,iBAAiB;EACtB,MAAM;EACN,eAAe,OAAO,SAAS,YAAY;GACzC,aAAa,QAAQ;GACrB,OAAO,QAAQ,OAAO;EACxB;EACA,cAAc,OAAO,SAAS,YAAY;GACxC,MAAM,WAAW,QAAQ,SAAS;GAKlC,IAAI,EAFkB,cAAc,eAAe,IAAI,QAAQ,IAI7D,OAAO,QAAQ,OAAO;GAIxB,MAAM,WAAW,QAAQ,SAAS;GAOlC,MAAM,SAAS;;QAEb,SAAS;eAPT,QAAQ,MAAM,eAAe,2BAQN;aAJvB,OAAO,aAAa,WAAW,WAAW,KAAK,UAAU,QAAQ,EAK7C;;;;GAMtB,MAAM,WAAW,MAAM,iBAAiB;GAGxC,MAAM,SAAS,aADb,uBAAuB,QAAQ,OAAO,KAAK,CAAC,GACN;IACtC,UAAU,EAAE,WAAW,gBAAgB;IACvC,MAAM,CAAC,iBAAiB;GAC1B,CAAC;GACD,MAAM,WAAW,MAAM,SAAS,OAC9B,CAAC,IAAI,aAAa,MAAM,CAAC,GACzB,MACF;GASA,OAAO,IAAI,YAAY;IACrB,SANA,OAAO,SAAS,YAAY,WACxB,SAAS,UACT,KAAK,UAAU,SAAS,OAAO;IAKnC,cAAc,QAAQ,SAAS,MAAM;IACrC,MAAM;GACR,CAAC;EACH;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"toolEmulator.js","names":[],"sources":["../../../src/agents/middleware/toolEmulator.ts"],"sourcesContent":["import { HumanMessage, ToolMessage } from \"@langchain/core/messages\";\nimport type { BaseChatModel } from \"@langchain/core/language_models/chat_models\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\nimport { initChatModel } from \"../../chat_models/universal.js\";\nimport {\n mergeConfigs,\n pickRunnableConfigKeys,\n type RunnableConfig,\n} from \"@langchain/core/runnables\";\nimport { createMiddleware } from \"../middleware.js\";\nimport { INTERNAL_CALL_TAG } from \"./constants.js\";\n\n/**\n * Options for configuring the Tool Emulator middleware.\n */\nexport interface ToolEmulatorOptions {\n /**\n * List of tool names (string) or tool instances to emulate.\n * - If `undefined` (default), ALL tools will be emulated.\n * - If empty array, no tools will be emulated.\n * - If array with tool names/instances, only those tools will be emulated.\n */\n tools?: (string | ClientTool | ServerTool)[];\n\n /**\n * Model to use for emulation.\n * - Can be a model identifier string (e.g., \"anthropic:claude-sonnet-4-5-20250929\")\n * - Can be a BaseChatModel instance\n * - Defaults to agent model\n */\n model?: string | BaseChatModel;\n}\n\n/**\n * Middleware that emulates specified tools using an LLM instead of executing them.\n *\n * This middleware allows selective emulation of tools for testing purposes.\n * By default (when `tools` is undefined), all tools are emulated. You can specify\n * which tools to emulate by passing a list of tool names or tool instances.\n *\n * @param options - Configuration options for the middleware\n * @param options.tools - List of tool names or tool instances to emulate. If undefined, all tools are emulated.\n * @param options.model - Model to use for emulation. Defaults to \"anthropic:claude-sonnet-4-5-20250929\".\n *\n * @example Emulate all tools (default behavior)\n * ```ts\n * import { toolEmulatorMiddleware } from \"@langchain/langchain/agents/middleware\";\n * import { createAgent } from \"@langchain/langchain/agents\";\n *\n * const middleware = toolEmulatorMiddleware();\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * tools: [getWeather, getUserLocation, calculator],\n * middleware: [middleware],\n * });\n * ```\n *\n * @example Emulate specific tools by name\n * ```ts\n * const middleware = toolEmulatorMiddleware({\n * tools: [\"get_weather\", \"get_user_location\"]\n * });\n * ```\n *\n * @example Use a custom model for emulation\n * ```ts\n * const middleware = toolEmulatorMiddleware({\n * tools: [\"get_weather\"],\n * model: \"anthropic:claude-sonnet-4-5-20250929\"\n * });\n * ```\n *\n * @example Emulate specific tools by passing tool instances\n * ```ts\n * const middleware = toolEmulatorMiddleware({\n * tools: [getWeather, getUserLocation]\n * });\n * ```\n */\nexport function toolEmulatorMiddleware(options: ToolEmulatorOptions = {}) {\n let agentModel: BaseChatModel | undefined;\n const { tools, model } = options;\n\n /**\n * Extract tool names from tools\n */\n const emulateAll = !tools || tools.length === 0;\n const toolsToEmulate = new Set<string>();\n\n if (!emulateAll && tools) {\n for (const tool of tools) {\n if (typeof tool === \"string\") {\n toolsToEmulate.add(tool);\n } else {\n // Assume tool instance with .name property\n const toolName =\n typeof tool.name === \"string\" ? tool.name : String(tool.name);\n toolsToEmulate.add(toolName);\n }\n }\n }\n\n /**\n * Initialize emulator model\n * We'll initialize it lazily in wrapToolCall to handle async initChatModel\n */\n let emulatorModel: BaseChatModel | undefined;\n const getEmulatorModel = async (): Promise<BaseChatModel> => {\n if (typeof model === \"object\") {\n return model;\n }\n if (typeof model === \"string\") {\n emulatorModel =\n emulatorModel ??\n (await initChatModel(model, { temperature: 1 }).catch((err) => {\n console.error(\n \"Error initializing emulator model, using agent model:\",\n err\n );\n return agentModel as BaseChatModel;\n }));\n return emulatorModel ?? (agentModel as BaseChatModel);\n }\n return agentModel as BaseChatModel;\n };\n\n return createMiddleware({\n name: \"ToolEmulatorMiddleware\",\n wrapModelCall: async (request, handler) => {\n agentModel = request.model as BaseChatModel;\n return handler(request);\n },\n wrapToolCall: async (request, handler) => {\n const toolName = request.toolCall.name;\n\n // Check if this tool should be emulated\n const shouldEmulate = emulateAll || toolsToEmulate.has(toolName);\n\n if (!shouldEmulate) {\n // Let it execute normally by calling the handler\n return handler(request);\n }\n\n // Extract tool information for emulation\n const toolArgs = request.toolCall.args;\n const toolDescription =\n request.tool?.description || \"No description available\";\n\n // Build prompt for emulator LLM\n const toolArgsString =\n typeof toolArgs === \"string\" ? toolArgs : JSON.stringify(toolArgs);\n const prompt = `You are emulating a tool call for testing purposes.\n\nTool: ${toolName}\nDescription: ${toolDescription}\nArguments: ${toolArgsString}\n\nGenerate a realistic response that this tool would return given these arguments.\nReturn ONLY the tool's output, no explanation or preamble. Introduce variation into your responses.`;\n\n // Get emulated response from LLM\n const emulator = await getEmulatorModel();\n const baseConfig: RunnableConfig =\n pickRunnableConfigKeys(request.runtime) ?? {};\n const config = mergeConfigs(baseConfig, {\n metadata: { lc_source: \"toolEmulation\" },\n tags: [INTERNAL_CALL_TAG],\n });\n const response = await emulator.invoke(\n [new HumanMessage(prompt)],\n config\n );\n\n // Extract content from response\n const content =\n typeof response.content === \"string\"\n ? response.content\n : JSON.stringify(response.content);\n\n // Short-circuit: return emulated result without executing real tool\n return new ToolMessage({\n content,\n tool_call_id: request.toolCall.id ?? \"\",\n name: toolName,\n });\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgFA,SAAgB,uBAAuB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CAAC;GACD,MAAM,WAAW,MAAM,SAAS,OAC9B,CAAC,IAAI,aAAa,MAAM,CAAC,GACzB,MACF;GAGA,MAAM,UACJ,OAAO,SAAS,YAAY,WACxB,SAAS,UACT,KAAK,UAAU,SAAS,OAAO;GAGrC,OAAO,IAAI,YAAY;IACrB;IACA,cAAc,QAAQ,SAAS,MAAM;IACrC,MAAM;GACR,CAAC;EACH;CACF,CAAC;AACH"}
@@ -1 +1 @@
1
- {"version":3,"file":"toolError.cjs","names":["createMiddleware","ToolMessage"],"sources":["../../../src/agents/middleware/toolError.ts"],"sourcesContent":["/**\n * Tool error middleware for agents.\n */\nimport { ToolMessage, type MessageContent } from \"@langchain/core/messages\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\nimport { isGraphBubbleUp } from \"@langchain/langgraph\";\n\nimport { createMiddleware } from \"../middleware.js\";\nimport type { ToolCallRequest } from \"./types.js\";\n\n/**\n * Handler called when tool execution throws.\n *\n * Return content to surface the error to the model as an error `ToolMessage`.\n * Return nothing to propagate the original error.\n */\nexport type ToolErrorHandler = (\n error: unknown,\n request: ToolCallRequest\n) => MessageContent | void | Promise<MessageContent | void>;\n\n/**\n * Configuration for {@link toolErrorMiddleware}.\n */\nexport interface ToolErrorMiddlewareConfig {\n /**\n * Handler called when tool execution throws. Return content to convert the\n * error into an error `ToolMessage`, or return nothing to propagate it.\n */\n onError: ToolErrorHandler;\n\n /**\n * Optional tools or tool names to handle errors for. Handles all tools when\n * omitted.\n */\n tools?: Array<ClientTool | ServerTool | string>;\n}\n\n/**\n * Converts selected tool execution errors into error `ToolMessage`s.\n *\n * Handling is opt-in: {@link ToolErrorMiddlewareConfig.onError} must return\n * content for an error to be sent to the model. Returning nothing propagates\n * the original error unchanged. LangGraph control-flow signals always\n * propagate and are never passed to `onError`.\n *\n * Prefer returning content that identifies the error type without including\n * the raw error message, which may contain sensitive or internal details.\n *\n * This middleware does not retry. To retry before handling an error, place\n * `toolRetryMiddleware({ onFailure: \"error\" })` after this middleware.\n *\n * @example\n * ```ts\n * import { createAgent, toolErrorMiddleware } from \"langchain\";\n *\n * const agent = createAgent({\n * model,\n * tools: [searchTool],\n * middleware: [\n * toolErrorMiddleware({\n * onError: (error, request) => {\n * if (error instanceof TypeError) {\n * return `Tool '${request.toolCall.name}' failed with TypeError.`;\n * }\n * },\n * }),\n * ],\n * });\n * ```\n */\nexport function toolErrorMiddleware(config: ToolErrorMiddlewareConfig) {\n const toolFilter = config.tools?.map((tool) =>\n typeof tool === \"string\" ? tool : tool.name\n );\n\n return createMiddleware({\n name: \"toolErrorMiddleware\",\n wrapToolCall: async (request, handler) => {\n const toolName = request.tool?.name ?? request.toolCall.name;\n\n if (toolFilter !== undefined && !toolFilter.includes(toolName)) {\n return handler(request);\n }\n\n try {\n return await handler(request);\n } catch (error: unknown) {\n if (isGraphBubbleUp(error)) {\n throw error;\n }\n\n const content = await config.onError(error, request);\n if (content === undefined) {\n throw error;\n }\n\n return new ToolMessage({\n content,\n tool_call_id: request.toolCall.id ?? \"\",\n ...(typeof toolName === \"string\" ? { name: toolName } : {}),\n status: \"error\",\n });\n }\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuEA,SAAgB,oBAAoB,QAAmC;CACrE,MAAM,aAAa,OAAO,OAAO,KAAK,SACpC,OAAO,SAAS,WAAW,OAAO,KAAK,IACzC;CAEA,OAAOA,mBAAAA,iBAAiB;EACtB,MAAM;EACN,cAAc,OAAO,SAAS,YAAY;GACxC,MAAM,WAAW,QAAQ,MAAM,QAAQ,QAAQ,SAAS;GAExD,IAAI,eAAe,KAAA,KAAa,CAAC,WAAW,SAAS,QAAQ,GAC3D,OAAO,QAAQ,OAAO;GAGxB,IAAI;IACF,OAAO,MAAM,QAAQ,OAAO;GAC9B,SAAS,OAAgB;IACvB,KAAA,GAAA,qBAAA,gBAAA,CAAoB,KAAK,GACvB,MAAM;IAGR,MAAM,UAAU,MAAM,OAAO,QAAQ,OAAO,OAAO;IACnD,IAAI,YAAY,KAAA,GACd,MAAM;IAGR,OAAO,IAAIC,yBAAAA,YAAY;KACrB;KACA,cAAc,QAAQ,SAAS,MAAM;KACrC,GAAI,OAAO,aAAa,WAAW,EAAE,MAAM,SAAS,IAAI,CAAC;KACzD,QAAQ;IACV,CAAC;GACH;EACF;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"toolError.cjs","names":["createMiddleware","isGraphBubbleUp","ToolMessage"],"sources":["../../../src/agents/middleware/toolError.ts"],"sourcesContent":["/**\n * Tool error middleware for agents.\n */\nimport { ToolMessage, type MessageContent } from \"@langchain/core/messages\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\nimport { isGraphBubbleUp } from \"@langchain/langgraph\";\n\nimport { createMiddleware } from \"../middleware.js\";\nimport type { ToolCallRequest } from \"./types.js\";\n\n/**\n * Handler called when tool execution throws.\n *\n * Return content to surface the error to the model as an error `ToolMessage`.\n * Return nothing to propagate the original error.\n */\nexport type ToolErrorHandler = (\n error: unknown,\n request: ToolCallRequest\n) => MessageContent | void | Promise<MessageContent | void>;\n\n/**\n * Configuration for {@link toolErrorMiddleware}.\n */\nexport interface ToolErrorMiddlewareConfig {\n /**\n * Handler called when tool execution throws. Return content to convert the\n * error into an error `ToolMessage`, or return nothing to propagate it.\n */\n onError: ToolErrorHandler;\n\n /**\n * Optional tools or tool names to handle errors for. Handles all tools when\n * omitted.\n */\n tools?: Array<ClientTool | ServerTool | string>;\n}\n\n/**\n * Converts selected tool execution errors into error `ToolMessage`s.\n *\n * Handling is opt-in: {@link ToolErrorMiddlewareConfig.onError} must return\n * content for an error to be sent to the model. Returning nothing propagates\n * the original error unchanged. LangGraph control-flow signals always\n * propagate and are never passed to `onError`.\n *\n * Prefer returning content that identifies the error type without including\n * the raw error message, which may contain sensitive or internal details.\n *\n * This middleware does not retry. To retry before handling an error, place\n * `toolRetryMiddleware({ onFailure: \"error\" })` after this middleware.\n *\n * @example\n * ```ts\n * import { createAgent, toolErrorMiddleware } from \"langchain\";\n *\n * const agent = createAgent({\n * model,\n * tools: [searchTool],\n * middleware: [\n * toolErrorMiddleware({\n * onError: (error, request) => {\n * if (error instanceof TypeError) {\n * return `Tool '${request.toolCall.name}' failed with TypeError.`;\n * }\n * },\n * }),\n * ],\n * });\n * ```\n */\nexport function toolErrorMiddleware(config: ToolErrorMiddlewareConfig) {\n const toolFilter = config.tools?.map((tool) =>\n typeof tool === \"string\" ? tool : tool.name\n );\n\n return createMiddleware({\n name: \"toolErrorMiddleware\",\n wrapToolCall: async (request, handler) => {\n const toolName = request.tool?.name ?? request.toolCall.name;\n\n if (toolFilter !== undefined && !toolFilter.includes(toolName)) {\n return handler(request);\n }\n\n try {\n return await handler(request);\n } catch (error: unknown) {\n if (isGraphBubbleUp(error)) {\n throw error;\n }\n\n const content = await config.onError(error, request);\n if (content === undefined) {\n throw error;\n }\n\n return new ToolMessage({\n content,\n tool_call_id: request.toolCall.id ?? \"\",\n ...(typeof toolName === \"string\" ? { name: toolName } : {}),\n status: \"error\",\n });\n }\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuEA,SAAgB,oBAAoB,QAAmC;CACrE,MAAM,aAAa,OAAO,OAAO,KAAK,SACpC,OAAO,SAAS,WAAW,OAAO,KAAK,IACzC;CAEA,OAAOA,mBAAAA,iBAAiB;EACtB,MAAM;EACN,cAAc,OAAO,SAAS,YAAY;GACxC,MAAM,WAAW,QAAQ,MAAM,QAAQ,QAAQ,SAAS;GAExD,IAAI,eAAe,KAAA,KAAa,CAAC,WAAW,SAAS,QAAQ,GAC3D,OAAO,QAAQ,OAAO;GAGxB,IAAI;IACF,OAAO,MAAM,QAAQ,OAAO;GAC9B,SAAS,OAAgB;IACvB,KAAA,GAAIC,qBAAAA,gBAAAA,CAAgB,KAAK,GACvB,MAAM;IAGR,MAAM,UAAU,MAAM,OAAO,QAAQ,OAAO,OAAO;IACnD,IAAI,YAAY,KAAA,GACd,MAAM;IAGR,OAAO,IAAIC,yBAAAA,YAAY;KACrB;KACA,cAAc,QAAQ,SAAS,MAAM;KACrC,GAAI,OAAO,aAAa,WAAW,EAAE,MAAM,SAAS,IAAI,CAAC;KACzD,QAAQ;IACV,CAAC;GACH;EACF;CACF,CAAC;AACH"}
@@ -1 +1 @@
1
- {"version":3,"file":"utils.cjs","names":["AIMessage","ToolMessage"],"sources":["../../../src/agents/middleware/utils.ts"],"sourcesContent":["import {\n AIMessage,\n ToolMessage,\n type BaseMessage,\n} from \"@langchain/core/messages\";\nimport { isLangChainTool } from \"@langchain/core/tools\";\nimport { convertToOpenAITool } from \"@langchain/core/utils/function_calling\";\nimport {\n AfterModelHook,\n AfterAgentHook,\n BeforeAgentHook,\n BeforeModelHook,\n} from \"./types.js\";\nimport { JumpToTarget } from \"../constants.js\";\n\n/**\n * Default token counter that approximates based on character count.\n *\n * If tools are provided, the token count also includes stringified tool schemas.\n *\n * @param messages Messages to count tokens for\n * @param tools Optional list of tools to include in the token count. Each tool\n * can be either a LangChain tool instance or a dict representing a tool schema.\n * LangChain tool instances are converted to OpenAI tool format before counting.\n * @returns Approximate token count\n */\nexport function countTokensApproximately(\n messages: BaseMessage[],\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n tools?: Array<Record<string, any>> | null\n): number {\n const charsPerToken = 4;\n let totalChars = 0;\n\n // Count tokens for tools if provided\n if (tools && tools.length > 0) {\n let toolsChars = 0;\n for (const tool of tools) {\n const toolDict = isLangChainTool(tool) ? convertToOpenAITool(tool) : tool;\n toolsChars += JSON.stringify(toolDict).length;\n }\n totalChars += toolsChars;\n }\n\n for (const msg of messages) {\n let textContent: string;\n if (typeof msg.content === \"string\") {\n textContent = msg.content;\n } else if (Array.isArray(msg.content)) {\n textContent = msg.content\n .map((item) => {\n if (typeof item === \"string\") return item;\n if (item.type === \"text\" && \"text\" in item) return item.text;\n return \"\";\n })\n .join(\"\");\n } else {\n textContent = \"\";\n }\n\n if (\n AIMessage.isInstance(msg) &&\n Array.isArray(msg.tool_calls) &&\n msg.tool_calls.length > 0\n ) {\n textContent += JSON.stringify(msg.tool_calls);\n }\n\n if (ToolMessage.isInstance(msg)) {\n textContent += msg.tool_call_id ?? \"\";\n }\n\n totalChars += textContent.length;\n }\n // Approximate 1 token = 4 characters\n return Math.ceil(totalChars / charsPerToken);\n}\n\nexport function getHookConstraint(\n hook:\n | BeforeAgentHook\n | BeforeModelHook\n | AfterAgentHook\n | AfterModelHook\n | undefined\n): JumpToTarget[] | undefined {\n if (!hook || typeof hook === \"function\") {\n return undefined;\n }\n return hook.canJumpTo;\n}\n\nexport function getHookFunction(\n arg: BeforeAgentHook | BeforeModelHook | AfterAgentHook | AfterModelHook\n) {\n if (typeof arg === \"function\") {\n return arg;\n }\n return arg.hook;\n}\n\n/**\n * Sleep for the specified number of milliseconds.\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Calculate delay for a retry attempt with exponential backoff and jitter.\n *\n * @param retryNumber - The retry attempt number (0-indexed)\n * @param config - Configuration for backoff calculation\n * @param retryAfterMs - A provider-supplied wait hint, e.g. from a `Retry-After`\n * header. Used as a floor so we never retry sooner than the server asked.\n * @returns Delay in milliseconds before next retry\n *\n * @internal Exported for testing purposes\n */\nexport function calculateRetryDelay(\n config: {\n backoffFactor: number;\n initialDelayMs: number;\n maxDelayMs: number;\n jitter: boolean;\n },\n retryNumber: number,\n retryAfterMs?: number\n): number {\n const { backoffFactor, initialDelayMs, maxDelayMs, jitter } = config;\n\n let delay: number;\n if (backoffFactor === 0.0) {\n delay = initialDelayMs;\n } else {\n delay = initialDelayMs * backoffFactor ** retryNumber;\n }\n\n // Cap at maxDelayMs\n delay = Math.min(delay, maxDelayMs);\n\n if (jitter && delay > 0) {\n const jitterAmount = delay * 0.25;\n delay = delay + (Math.random() * 2 - 1) * jitterAmount;\n // Ensure delay is not negative after jitter\n delay = Math.max(0, delay);\n }\n\n return Math.max(delay, retryAfterMs ?? 0);\n}\n\nexport function getRetryAfterMs(error: unknown): number | undefined {\n if (typeof error !== \"object\" || error === null) {\n return undefined;\n }\n const { retryAfterMs } = error as { retryAfterMs?: unknown };\n return typeof retryAfterMs === \"number\" && retryAfterMs >= 0\n ? retryAfterMs\n : undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;AA0BA,SAAgB,yBACd,UAEA,OACQ;CACR,MAAM,gBAAgB;CACtB,IAAI,aAAa;CAGjB,IAAI,SAAS,MAAM,SAAS,GAAG;EAC7B,IAAI,aAAa;EACjB,KAAK,MAAM,QAAQ,OAAO;GACxB,MAAM,YAAA,GAAA,sBAAA,gBAAA,CAA2B,IAAI,KAAA,GAAA,uCAAA,oBAAA,CAAwB,IAAI,IAAI;GACrE,cAAc,KAAK,UAAU,QAAQ,CAAC,CAAC;EACzC;EACA,cAAc;CAChB;CAEA,KAAK,MAAM,OAAO,UAAU;EAC1B,IAAI;EACJ,IAAI,OAAO,IAAI,YAAY,UACzB,cAAc,IAAI;OACb,IAAI,MAAM,QAAQ,IAAI,OAAO,GAClC,cAAc,IAAI,QACf,KAAK,SAAS;GACb,IAAI,OAAO,SAAS,UAAU,OAAO;GACrC,IAAI,KAAK,SAAS,UAAU,UAAU,MAAM,OAAO,KAAK;GACxD,OAAO;EACT,CAAC,CAAC,CACD,KAAK,EAAE;OAEV,cAAc;EAGhB,IACEA,yBAAAA,UAAU,WAAW,GAAG,KACxB,MAAM,QAAQ,IAAI,UAAU,KAC5B,IAAI,WAAW,SAAS,GAExB,eAAe,KAAK,UAAU,IAAI,UAAU;EAG9C,IAAIC,yBAAAA,YAAY,WAAW,GAAG,GAC5B,eAAe,IAAI,gBAAgB;EAGrC,cAAc,YAAY;CAC5B;CAEA,OAAO,KAAK,KAAK,aAAa,aAAa;AAC7C;AAEA,SAAgB,kBACd,MAM4B;CAC5B,IAAI,CAAC,QAAQ,OAAO,SAAS,YAC3B;CAEF,OAAO,KAAK;AACd;AAEA,SAAgB,gBACd,KACA;CACA,IAAI,OAAO,QAAQ,YACjB,OAAO;CAET,OAAO,IAAI;AACb;;;;AAKA,SAAgB,MAAM,IAA2B;CAC/C,OAAO,IAAI,SAAS,YAAY,WAAW,SAAS,EAAE,CAAC;AACzD;;;;;;;;;;;;AAaA,SAAgB,oBACd,QAMA,aACA,cACQ;CACR,MAAM,EAAE,eAAe,gBAAgB,YAAY,WAAW;CAE9D,IAAI;CACJ,IAAI,kBAAkB,GACpB,QAAQ;MAER,QAAQ,iBAAiB,iBAAiB;CAI5C,QAAQ,KAAK,IAAI,OAAO,UAAU;CAElC,IAAI,UAAU,QAAQ,GAAG;EACvB,MAAM,eAAe,QAAQ;EAC7B,QAAQ,SAAS,KAAK,OAAO,IAAI,IAAI,KAAK;EAE1C,QAAQ,KAAK,IAAI,GAAG,KAAK;CAC3B;CAEA,OAAO,KAAK,IAAI,OAAO,gBAAgB,CAAC;AAC1C;AAEA,SAAgB,gBAAgB,OAAoC;CAClE,IAAI,OAAO,UAAU,YAAY,UAAU,MACzC;CAEF,MAAM,EAAE,iBAAiB;CACzB,OAAO,OAAO,iBAAiB,YAAY,gBAAgB,IACvD,eACA,KAAA;AACN"}
1
+ {"version":3,"file":"utils.cjs","names":["isLangChainTool","convertToOpenAITool","AIMessage","ToolMessage"],"sources":["../../../src/agents/middleware/utils.ts"],"sourcesContent":["import {\n AIMessage,\n ToolMessage,\n type BaseMessage,\n} from \"@langchain/core/messages\";\nimport { isLangChainTool } from \"@langchain/core/tools\";\nimport { convertToOpenAITool } from \"@langchain/core/utils/function_calling\";\nimport {\n AfterModelHook,\n AfterAgentHook,\n BeforeAgentHook,\n BeforeModelHook,\n} from \"./types.js\";\nimport { JumpToTarget } from \"../constants.js\";\n\n/**\n * Default token counter that approximates based on character count.\n *\n * If tools are provided, the token count also includes stringified tool schemas.\n *\n * @param messages Messages to count tokens for\n * @param tools Optional list of tools to include in the token count. Each tool\n * can be either a LangChain tool instance or a dict representing a tool schema.\n * LangChain tool instances are converted to OpenAI tool format before counting.\n * @returns Approximate token count\n */\nexport function countTokensApproximately(\n messages: BaseMessage[],\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n tools?: Array<Record<string, any>> | null\n): number {\n const charsPerToken = 4;\n let totalChars = 0;\n\n // Count tokens for tools if provided\n if (tools && tools.length > 0) {\n let toolsChars = 0;\n for (const tool of tools) {\n const toolDict = isLangChainTool(tool) ? convertToOpenAITool(tool) : tool;\n toolsChars += JSON.stringify(toolDict).length;\n }\n totalChars += toolsChars;\n }\n\n for (const msg of messages) {\n let textContent: string;\n if (typeof msg.content === \"string\") {\n textContent = msg.content;\n } else if (Array.isArray(msg.content)) {\n textContent = msg.content\n .map((item) => {\n if (typeof item === \"string\") return item;\n if (item.type === \"text\" && \"text\" in item) return item.text;\n return \"\";\n })\n .join(\"\");\n } else {\n textContent = \"\";\n }\n\n if (\n AIMessage.isInstance(msg) &&\n Array.isArray(msg.tool_calls) &&\n msg.tool_calls.length > 0\n ) {\n textContent += JSON.stringify(msg.tool_calls);\n }\n\n if (ToolMessage.isInstance(msg)) {\n textContent += msg.tool_call_id ?? \"\";\n }\n\n totalChars += textContent.length;\n }\n // Approximate 1 token = 4 characters\n return Math.ceil(totalChars / charsPerToken);\n}\n\nexport function getHookConstraint(\n hook:\n | BeforeAgentHook\n | BeforeModelHook\n | AfterAgentHook\n | AfterModelHook\n | undefined\n): JumpToTarget[] | undefined {\n if (!hook || typeof hook === \"function\") {\n return undefined;\n }\n return hook.canJumpTo;\n}\n\nexport function getHookFunction(\n arg: BeforeAgentHook | BeforeModelHook | AfterAgentHook | AfterModelHook\n) {\n if (typeof arg === \"function\") {\n return arg;\n }\n return arg.hook;\n}\n\n/**\n * Sleep for the specified number of milliseconds.\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Calculate delay for a retry attempt with exponential backoff and jitter.\n *\n * @param retryNumber - The retry attempt number (0-indexed)\n * @param config - Configuration for backoff calculation\n * @param retryAfterMs - A provider-supplied wait hint, e.g. from a `Retry-After`\n * header. Used as a floor so we never retry sooner than the server asked.\n * @returns Delay in milliseconds before next retry\n *\n * @internal Exported for testing purposes\n */\nexport function calculateRetryDelay(\n config: {\n backoffFactor: number;\n initialDelayMs: number;\n maxDelayMs: number;\n jitter: boolean;\n },\n retryNumber: number,\n retryAfterMs?: number\n): number {\n const { backoffFactor, initialDelayMs, maxDelayMs, jitter } = config;\n\n let delay: number;\n if (backoffFactor === 0.0) {\n delay = initialDelayMs;\n } else {\n delay = initialDelayMs * backoffFactor ** retryNumber;\n }\n\n // Cap at maxDelayMs\n delay = Math.min(delay, maxDelayMs);\n\n if (jitter && delay > 0) {\n const jitterAmount = delay * 0.25;\n delay = delay + (Math.random() * 2 - 1) * jitterAmount;\n // Ensure delay is not negative after jitter\n delay = Math.max(0, delay);\n }\n\n return Math.max(delay, retryAfterMs ?? 0);\n}\n\nexport function getRetryAfterMs(error: unknown): number | undefined {\n if (typeof error !== \"object\" || error === null) {\n return undefined;\n }\n const { retryAfterMs } = error as { retryAfterMs?: unknown };\n return typeof retryAfterMs === \"number\" && retryAfterMs >= 0\n ? retryAfterMs\n : undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;AA0BA,SAAgB,yBACd,UAEA,OACQ;CACR,MAAM,gBAAgB;CACtB,IAAI,aAAa;CAGjB,IAAI,SAAS,MAAM,SAAS,GAAG;EAC7B,IAAI,aAAa;EACjB,KAAK,MAAM,QAAQ,OAAO;GACxB,MAAM,YAAA,GAAWA,sBAAAA,gBAAAA,CAAgB,IAAI,KAAA,GAAIC,uCAAAA,oBAAAA,CAAoB,IAAI,IAAI;GACrE,cAAc,KAAK,UAAU,QAAQ,CAAC,CAAC;EACzC;EACA,cAAc;CAChB;CAEA,KAAK,MAAM,OAAO,UAAU;EAC1B,IAAI;EACJ,IAAI,OAAO,IAAI,YAAY,UACzB,cAAc,IAAI;OACb,IAAI,MAAM,QAAQ,IAAI,OAAO,GA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,OAAO,OAAO,iBAAiB,YAAY,gBAAgB,IACvD,eACA,KAAA;AACN"}
@@ -171,7 +171,10 @@ var AgentNode = class extends require_RunnableCallable.RunnableCallable {
171
171
  * agent loop continues and a subsequent terminal step will get
172
172
  * another chance to produce a valid structured response.
173
173
  */
174
- if (!response.tool_calls || response.tool_calls.length === 0) throw new require_errors.StructuredOutputParsingError(typeof structuredResponseFormat.strategy.schema?.title === "string" ? structuredResponseFormat.strategy.schema.title : "providerStrategy", ["Model output did not satisfy the provided response schema."]);
174
+ if (!response.tool_calls || response.tool_calls.length === 0) {
175
+ const schemaTitle = typeof structuredResponseFormat.strategy.schema?.title === "string" ? structuredResponseFormat.strategy.schema.title : "providerStrategy";
176
+ throw new require_errors.StructuredOutputParsingError(schemaTitle, ["Model output did not satisfy the provided response schema."]);
177
+ }
175
178
  return response;
176
179
  }
177
180
  if (!structuredResponseFormat || !response.tool_calls) return response;
@@ -1 +1 @@
1
- {"version":3,"file":"AgentNode.cjs","names":["AIMessage","RunnableCallable","#run","#options","#systemMessage","#getResponseFormat","isConfigurableModel","transformResponseFormat","ProviderStrategy","ToolStrategy","ToolMessage","Command","#invokeModel","#areMoreStepsNeeded","initChatModel","#deriveModel","#bindTools","mergeAbortSignals","StructuredOutputParsingError","#handleMultipleStructuredOutputs","#handleSingleStructuredOutput","toPartialZodObject","isClientTool","SystemMessage","MiddlewareError","MultipleStructuredOutputsError","#handleToolStrategyError","hasToolCalls","bindTools","withAgentName"],"sources":["../../../src/agents/nodes/AgentNode.ts"],"sourcesContent":["/* oxlint-disable no-instanceof/no-instanceof */\nimport { Runnable, RunnableConfig } from \"@langchain/core/runnables\";\nimport {\n BaseMessage,\n AIMessage,\n ToolMessage,\n SystemMessage,\n} from \"@langchain/core/messages\";\nimport {\n Command,\n isCommand,\n type LangGraphRunnableConfig,\n} from \"@langchain/langgraph\";\nimport { type BaseChatModelCallOptions } from \"@langchain/core/language_models/chat_models\";\nimport {\n InteropZodObject,\n getSchemaDescription,\n interopParse,\n} from \"@langchain/core/utils/types\";\nimport { raceWithSignal } from \"@langchain/core/runnables\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport { initChatModel } from \"../../chat_models/universal.js\";\nimport {\n MultipleStructuredOutputsError,\n MiddlewareError,\n StructuredOutputParsingError,\n} from \"../errors.js\";\nimport { RunnableCallable } from \"../RunnableCallable.js\";\nimport type { AgentLanguageModelLike as LanguageModelLike } from \"../model.js\";\nimport {\n bindTools,\n validateLLMHasNoBoundTools,\n hasToolCalls,\n isClientTool,\n} from \"../utils.js\";\nimport { isConfigurableModel } from \"../model.js\";\nimport { mergeAbortSignals, toPartialZodObject } from \"../nodes/utils.js\";\nimport { CreateAgentParams } from \"../types.js\";\nimport type { InternalAgentState, Runtime } from \"../runtime.js\";\nimport type {\n AgentMiddleware,\n AnyAnnotationRoot,\n WrapModelCallHandler,\n} from \"../middleware/types.js\";\nimport type { ModelRequest } from \"./types.js\";\nimport { withAgentName } from \"../withAgentName.js\";\nimport {\n ToolStrategy,\n ProviderStrategy,\n transformResponseFormat,\n ToolStrategyError,\n type ResponseFormatInput,\n} from \"../responses.js\";\n\ntype ResponseHandlerResult<StructuredResponseFormat> =\n | {\n structuredResponse: StructuredResponseFormat;\n messages: BaseMessage[];\n }\n | Promise<Command>;\n\n/**\n * Wrap the base handler with middleware wrapModelCall hooks\n * Middleware are composed so the first middleware is the outermost wrapper\n * Example: [auth, retry, cache] means auth wraps retry wraps cache wraps baseHandler\n */\ntype InternalModelResponse<StructuredResponseFormat> =\n | AIMessage\n | ResponseHandlerResult<StructuredResponseFormat>\n | Command;\n\n/**\n * Check if the response is an internal model response.\n * @param response - The response to check.\n * @returns True if the response is an internal model response, false otherwise.\n */\nfunction isInternalModelResponse<StructuredResponseFormat>(\n response: unknown\n): response is InternalModelResponse<StructuredResponseFormat> {\n return (\n AIMessage.isInstance(response) ||\n isCommand(response) ||\n (typeof response === \"object\" &&\n response !== null &&\n \"structuredResponse\" in response &&\n \"messages\" in response)\n );\n}\n\n/**\n * The name of the agent node in the state graph.\n */\nexport const AGENT_NODE_NAME = \"model_request\";\n\nexport interface AgentNodeOptions<\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject =\n AnyAnnotationRoot,\n> extends Pick<\n CreateAgentParams<StructuredResponseFormat, StateSchema, ContextSchema>,\n \"model\" | \"includeAgentName\" | \"name\" | \"responseFormat\" | \"middleware\"\n> {\n toolClasses: (ClientTool | ServerTool)[];\n shouldReturnDirect: Set<string>;\n signal?: AbortSignal;\n systemMessage: SystemMessage;\n wrapModelCallHookMiddleware?: (\n | AgentMiddleware\n | [AgentMiddleware, (...args: unknown[]) => Record<string, unknown>]\n )[];\n}\n\ninterface NativeResponseFormat {\n type: \"native\";\n strategy: ProviderStrategy;\n}\n\ninterface ToolResponseFormat {\n type: \"tool\";\n tools: Record<string, ToolStrategy>;\n}\n\ntype ResponseFormat = NativeResponseFormat | ToolResponseFormat;\n\nexport class AgentNode<\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject =\n AnyAnnotationRoot,\n> extends RunnableCallable<\n InternalAgentState<StructuredResponseFormat>,\n | Command[]\n | {\n messages: BaseMessage[];\n structuredResponse: StructuredResponseFormat;\n }\n> {\n #options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>;\n #systemMessage: SystemMessage;\n\n constructor(\n options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>\n ) {\n super({\n name: options.name ?? \"model\",\n func: (input, config) => this.#run(input, config as RunnableConfig),\n });\n\n this.#options = options;\n this.#systemMessage = options.systemMessage;\n }\n\n /**\n * Returns response format primtivies based on given model and response format provided by the user.\n *\n * If the user selects a tool output:\n * - return a record of tools to extract structured output from the model's response\n *\n * if the user selects a native schema output or if the model supports JSON schema output:\n * - return a provider strategy to extract structured output from the model's response\n *\n * @param model - The model to get the response format for.\n * @returns The response format.\n */\n async #getResponseFormat(\n model: string | LanguageModelLike,\n responseFormat: ResponseFormatInput | undefined = this.#options\n .responseFormat\n ): Promise<ResponseFormat | undefined> {\n if (!responseFormat) {\n return undefined;\n }\n\n let resolvedModel: LanguageModelLike | undefined;\n if (isConfigurableModel(model)) {\n resolvedModel = await (\n model as unknown as {\n _getModelInstance: () => Promise<LanguageModelLike>;\n }\n )._getModelInstance();\n } else if (typeof model !== \"string\") {\n resolvedModel = model;\n }\n\n const strategies = transformResponseFormat(\n responseFormat,\n undefined,\n resolvedModel\n );\n\n if (strategies.length === 0) {\n return undefined;\n }\n\n /**\n * we either define a list of provider strategies or a list of tool strategies\n */\n const isProviderStrategy = strategies.every(\n (format) => format instanceof ProviderStrategy\n );\n\n /**\n * Populate a list of structured tool info.\n */\n if (!isProviderStrategy) {\n return {\n type: \"tool\",\n tools: (\n strategies.filter(\n (format) => format instanceof ToolStrategy\n ) as ToolStrategy[]\n ).reduce(\n (acc, format) => {\n acc[format.name] = format;\n return acc;\n },\n {} as Record<string, ToolStrategy>\n ),\n };\n }\n\n return {\n type: \"native\",\n /**\n * there can only be one provider strategy\n */\n strategy: strategies[0] as ProviderStrategy,\n };\n }\n\n async #run(\n state: InternalAgentState<StructuredResponseFormat>,\n config: RunnableConfig\n ) {\n /**\n * Check if we just executed a returnDirect tool\n * If so, we should generate structured response (if needed) and stop\n */\n const lastMessage = state.messages.at(-1);\n if (\n lastMessage &&\n ToolMessage.isInstance(lastMessage) &&\n lastMessage.name &&\n this.#options.shouldReturnDirect.has(lastMessage.name)\n ) {\n return [new Command({ update: { messages: [] } })];\n }\n\n const { response, lastAiMessage, collectedCommands } =\n await this.#invokeModel(state, config);\n\n /**\n * structuredResponse — return as a plain state update dict (not a Command)\n * because the structuredResponse channel uses UntrackedValue(guard=true)\n * which only allows a single write per step.\n */\n if (\n typeof response === \"object\" &&\n response !== null &&\n \"structuredResponse\" in response &&\n \"messages\" in response\n ) {\n const { structuredResponse, messages } = response as {\n structuredResponse: StructuredResponseFormat;\n messages: BaseMessage[];\n };\n return {\n messages: [...state.messages, ...messages],\n structuredResponse,\n };\n }\n\n const commands: Command[] = [];\n const aiMessage: AIMessage | null = AIMessage.isInstance(response)\n ? response\n : lastAiMessage;\n\n // messages\n if (aiMessage) {\n aiMessage.name = this.name;\n aiMessage.lc_kwargs.name = this.name;\n\n if (this.#areMoreStepsNeeded(state, aiMessage)) {\n commands.push(\n new Command({\n update: {\n messages: [\n new AIMessage({\n content: \"Sorry, need more steps to process this request.\",\n name: this.name,\n id: aiMessage.id,\n }),\n ],\n },\n })\n );\n } else {\n commands.push(new Command({ update: { messages: [aiMessage] } }));\n }\n }\n\n // Commands (from base handler retries or middleware)\n if (isCommand(response) && !collectedCommands.includes(response)) {\n commands.push(response);\n }\n commands.push(...collectedCommands);\n\n return commands;\n }\n\n /**\n * Derive the model from the options.\n * @param state - The state of the agent.\n * @param config - The config of the agent.\n * @returns The model.\n */\n #deriveModel() {\n if (typeof this.#options.model === \"string\") {\n return initChatModel(this.#options.model);\n }\n\n if (this.#options.model) {\n return this.#options.model;\n }\n\n throw new Error(\"No model option was provided, either via `model` option.\");\n }\n\n async #invokeModel(\n state: InternalAgentState<StructuredResponseFormat>,\n config: RunnableConfig,\n options: {\n lastMessage?: string;\n } = {}\n ): Promise<{\n response: InternalModelResponse<StructuredResponseFormat>;\n lastAiMessage: AIMessage | null;\n collectedCommands: Command[];\n }> {\n const model = await this.#deriveModel();\n const lgConfig = config as LangGraphRunnableConfig;\n\n /**\n * Create a local variable for current system message to avoid concurrency issues\n * Each invocation gets its own copy\n */\n let currentSystemMessage = this.#systemMessage;\n\n /**\n * Shared tracking state for AIMessage and Command collection.\n * lastAiMessage tracks the effective AIMessage through the middleware chain.\n * collectedCommands accumulates Commands returned by middleware (not base handler).\n */\n let lastAiMessage: AIMessage | null = null;\n const collectedCommands: Command[] = [];\n\n /**\n * Create the base handler that performs the actual model invocation\n */\n const baseHandler = async (\n request: ModelRequest\n ): Promise<AIMessage | ResponseHandlerResult<StructuredResponseFormat>> => {\n /**\n * Check if the LLM already has bound tools and throw if it does.\n */\n validateLLMHasNoBoundTools(request.model);\n\n const structuredResponseFormat = await this.#getResponseFormat(\n request.model,\n request.responseFormat\n );\n const modelWithTools = await this.#bindTools(\n request.model,\n request,\n structuredResponseFormat\n );\n\n /**\n * prepend the system message to the messages if it is not empty\n */\n const messages = [\n ...(currentSystemMessage.text === \"\" ? [] : [currentSystemMessage]),\n ...request.messages,\n ];\n\n const signal = mergeAbortSignals(this.#options.signal, config.signal);\n const response = (await raceWithSignal(\n modelWithTools.invoke(messages, {\n ...config,\n signal,\n }),\n signal\n )) as AIMessage;\n\n lastAiMessage = response;\n\n /**\n * if the user requests a native schema output, try to parse the response\n * and return the structured response if it is valid\n */\n if (structuredResponseFormat?.type === \"native\") {\n const structuredResponse =\n structuredResponseFormat.strategy.parse(response);\n if (structuredResponse) {\n return { structuredResponse, messages: [response] };\n }\n\n /**\n * If the model produced a terminal response (no tool calls) but the\n * output failed to satisfy the provider strategy's schema, throw an\n * informative error instead of silently exiting with\n * `structuredResponse: undefined`. If tool calls are present, the\n * agent loop continues and a subsequent terminal step will get\n * another chance to produce a valid structured response.\n */\n if (!response.tool_calls || response.tool_calls.length === 0) {\n const schemaTitle =\n typeof structuredResponseFormat.strategy.schema?.title === \"string\"\n ? structuredResponseFormat.strategy.schema.title\n : \"providerStrategy\";\n throw new StructuredOutputParsingError(schemaTitle, [\n \"Model output did not satisfy the provided response schema.\",\n ]);\n }\n\n return response;\n }\n\n if (!structuredResponseFormat || !response.tool_calls) {\n return response;\n }\n\n const toolCalls = response.tool_calls.filter(\n (call) => call.name in structuredResponseFormat.tools\n );\n\n /**\n * if there were not structured tool calls, we can return the response\n */\n if (toolCalls.length === 0) {\n return response;\n }\n\n /**\n * if there were multiple structured tool calls, we should throw an error as this\n * scenario is not defined/supported.\n */\n if (toolCalls.length > 1) {\n return this.#handleMultipleStructuredOutputs(\n response,\n toolCalls,\n structuredResponseFormat\n );\n }\n\n const toolStrategy = structuredResponseFormat.tools[toolCalls[0].name];\n const toolMessageContent = toolStrategy?.options?.toolMessageContent;\n return this.#handleSingleStructuredOutput(\n response,\n toolCalls[0],\n structuredResponseFormat,\n toolMessageContent ?? options.lastMessage\n );\n };\n\n const wrapperMiddleware = this.#options.wrapModelCallHookMiddleware ?? [];\n let wrappedHandler: (\n request: ModelRequest<\n InternalAgentState<StructuredResponseFormat>,\n unknown\n >\n ) => Promise<InternalModelResponse<StructuredResponseFormat>> = baseHandler;\n\n /**\n * Build composed handler from last to first so first middleware becomes outermost\n */\n for (let i = wrapperMiddleware.length - 1; i >= 0; i--) {\n const middlewareEntry = wrapperMiddleware[i];\n const middleware = Array.isArray(middlewareEntry)\n ? middlewareEntry[0]\n : middlewareEntry;\n if (middleware.wrapModelCall) {\n const innerHandler = wrappedHandler;\n const currentMiddleware = middleware;\n\n wrappedHandler = async (\n request: ModelRequest<\n InternalAgentState<StructuredResponseFormat>,\n unknown\n >\n ): Promise<InternalModelResponse<StructuredResponseFormat>> => {\n const baselineSystemMessage = currentSystemMessage;\n\n /**\n * Merge context with default context of middleware\n */\n const context = currentMiddleware.contextSchema\n ? interopParse(\n currentMiddleware.contextSchema,\n lgConfig?.context || {}\n )\n : lgConfig?.context;\n\n /**\n * Create runtime\n */\n const runtime: Runtime<unknown> = Object.freeze({\n context,\n store: lgConfig.store,\n configurable: lgConfig.configurable,\n writer: lgConfig.writer,\n interrupt: lgConfig.interrupt,\n signal: lgConfig.signal,\n });\n\n /**\n * Create the request with state and runtime\n */\n const requestWithStateAndRuntime: ModelRequest<\n InternalAgentState<StructuredResponseFormat>,\n unknown\n > = {\n ...request,\n state: {\n ...(middleware.stateSchema\n ? interopParse(\n toPartialZodObject(middleware.stateSchema),\n state\n )\n : {}),\n messages: state.messages,\n } as InternalAgentState<StructuredResponseFormat>,\n runtime,\n };\n\n /**\n * Create handler that validates tools and calls the inner handler\n */\n const handlerWithValidation = async (\n req: ModelRequest<\n InternalAgentState<StructuredResponseFormat>,\n unknown\n >\n ): Promise<InternalModelResponse<StructuredResponseFormat>> => {\n currentSystemMessage = baselineSystemMessage;\n\n /**\n * Validate tool modifications in wrapModelCall.\n *\n * Classify each client tool as either:\n * - \"added\": a genuinely new tool name not in the static toolClasses\n * - \"replaced\": same name as a registered tool but different instance\n *\n * Added tools are allowed when a wrapToolCall middleware exists to\n * handle their execution. Replaced tools are always rejected to\n * preserve ToolNode execution identity.\n */\n const modifiedTools = req.tools ?? [];\n const registeredToolsByName = new Map(\n this.#options.toolClasses\n .filter(isClientTool)\n .map((t) => [t.name, t] as const)\n );\n\n const addedClientTools = modifiedTools.filter(\n (tool) =>\n isClientTool(tool) && !registeredToolsByName.has(tool.name)\n );\n\n const replacedClientTools = modifiedTools.filter((tool) => {\n if (!isClientTool(tool)) return false;\n const original = registeredToolsByName.get(tool.name);\n return original != null && original !== tool;\n });\n\n if (addedClientTools.length > 0) {\n const hasWrapToolCallHandler = this.#options.middleware?.some(\n (m) => m.wrapToolCall != null\n );\n if (!hasWrapToolCallHandler) {\n throw new Error(\n `You have added a new tool in \"wrapModelCall\" hook of middleware \"${\n currentMiddleware.name\n }\": ${addedClientTools\n .map((tool) => tool.name)\n .join(\n \", \"\n )}. This is not supported unless a middleware provides a \"wrapToolCall\" handler to execute it.`\n );\n }\n }\n\n if (replacedClientTools.length > 0) {\n throw new Error(\n `You have modified a tool in \"wrapModelCall\" hook of middleware \"${\n currentMiddleware.name\n }\": ${replacedClientTools\n .map((tool) => tool.name)\n .join(\", \")}. This is not supported.`\n );\n }\n\n let normalizedReq = req;\n const hasSystemPromptChanged =\n req.systemPrompt !== currentSystemMessage.text;\n const hasSystemMessageChanged =\n req.systemMessage !== currentSystemMessage;\n if (hasSystemPromptChanged && hasSystemMessageChanged) {\n throw new Error(\n \"Cannot change both systemPrompt and systemMessage in the same request.\"\n );\n }\n\n /**\n * Check if systemPrompt is a string was changed, if so create a new SystemMessage\n */\n if (hasSystemPromptChanged) {\n currentSystemMessage = new SystemMessage({\n content: [{ type: \"text\", text: req.systemPrompt }],\n });\n normalizedReq = {\n ...req,\n systemPrompt: currentSystemMessage.text,\n systemMessage: currentSystemMessage,\n };\n }\n /**\n * If the systemMessage was changed, update the current system message\n */\n if (hasSystemMessageChanged) {\n currentSystemMessage = new SystemMessage({\n ...req.systemMessage,\n });\n normalizedReq = {\n ...req,\n systemPrompt: currentSystemMessage.text,\n systemMessage: currentSystemMessage,\n };\n }\n\n const innerHandlerResult = await innerHandler(normalizedReq);\n\n /**\n * Normalize Commands so middleware always sees AIMessage from handler().\n * When an inner handler (base handler or nested middleware) returns a\n * Command (e.g. structured-output retry), substitute the tracked\n * lastAiMessage so the middleware sees an AIMessage, and collect the\n * raw Command so the framework can still propagate it (e.g. for retries).\n *\n * Only collect if not already present: Commands from inner middleware\n * are already tracked via the middleware validation layer (line ~627).\n */\n if (isCommand(innerHandlerResult) && lastAiMessage) {\n if (!collectedCommands.includes(innerHandlerResult)) {\n collectedCommands.push(innerHandlerResult);\n }\n return lastAiMessage as InternalModelResponse<StructuredResponseFormat>;\n }\n\n return innerHandlerResult;\n };\n\n // Call middleware's wrapModelCall with the validation handler\n if (!currentMiddleware.wrapModelCall) {\n return handlerWithValidation(requestWithStateAndRuntime);\n }\n\n try {\n const middlewareResponse = await currentMiddleware.wrapModelCall(\n requestWithStateAndRuntime,\n handlerWithValidation as WrapModelCallHandler\n );\n\n /**\n * Validate that this specific middleware returned a valid response\n */\n if (!isInternalModelResponse(middlewareResponse)) {\n throw new Error(\n `Invalid response from \"wrapModelCall\" in middleware \"${\n currentMiddleware.name\n }\": expected AIMessage or Command, got ${typeof middlewareResponse}`\n );\n }\n\n if (AIMessage.isInstance(middlewareResponse)) {\n lastAiMessage = middlewareResponse;\n } else if (isCommand(middlewareResponse)) {\n collectedCommands.push(middlewareResponse);\n }\n\n return middlewareResponse;\n } catch (error) {\n throw MiddlewareError.wrap(error, currentMiddleware.name);\n }\n };\n }\n }\n\n /**\n * Execute the wrapped handler with the initial request\n * Reset current system prompt to initial state and convert to string using .text getter\n * for backwards compatibility with ModelRequest\n */\n currentSystemMessage = this.#systemMessage;\n const initialRequest: ModelRequest<\n InternalAgentState<StructuredResponseFormat>,\n unknown\n > = {\n model,\n responseFormat: this.#options.responseFormat,\n systemPrompt: currentSystemMessage?.text,\n systemMessage: currentSystemMessage,\n messages: state.messages,\n tools: this.#options.toolClasses,\n state,\n runtime: Object.freeze({\n context: lgConfig?.context,\n store: lgConfig.store,\n configurable: lgConfig.configurable,\n writer: lgConfig.writer,\n interrupt: lgConfig.interrupt,\n signal: lgConfig.signal,\n }) as Runtime<unknown>,\n };\n\n const response = await wrappedHandler(initialRequest);\n return { response, lastAiMessage, collectedCommands };\n }\n\n /**\n * If the model returns multiple structured outputs, we need to handle it.\n * @param response - The response from the model\n * @param toolCalls - The tool calls that were made\n * @returns The response from the model\n */\n #handleMultipleStructuredOutputs(\n response: AIMessage,\n toolCalls: ToolCall[],\n responseFormat: ToolResponseFormat\n ): Promise<Command> {\n const multipleStructuredOutputsError = new MultipleStructuredOutputsError(\n toolCalls.map((call) => call.name)\n );\n\n return this.#handleToolStrategyError(\n multipleStructuredOutputsError,\n response,\n toolCalls[0],\n responseFormat\n );\n }\n\n /**\n * If the model returns a single structured output, we need to handle it.\n * @param toolCall - The tool call that was made\n * @returns The structured response and a message to the LLM if needed\n */\n #handleSingleStructuredOutput(\n response: AIMessage,\n toolCall: ToolCall,\n responseFormat: ToolResponseFormat,\n lastMessage?: string\n ): ResponseHandlerResult<StructuredResponseFormat> {\n const tool = responseFormat.tools[toolCall.name];\n\n try {\n const structuredResponse = tool.parse(\n toolCall.args\n ) as StructuredResponseFormat;\n\n return {\n structuredResponse,\n messages: [\n response,\n new ToolMessage({\n tool_call_id: toolCall.id ?? \"\",\n content: JSON.stringify(structuredResponse),\n name: toolCall.name,\n }),\n new AIMessage(\n lastMessage ??\n `Returning structured response: ${JSON.stringify(\n structuredResponse\n )}`\n ),\n ],\n };\n } catch (error) {\n return this.#handleToolStrategyError(\n error as ToolStrategyError,\n response,\n toolCall,\n responseFormat\n );\n }\n }\n\n async #handleToolStrategyError(\n error: ToolStrategyError,\n response: AIMessage,\n toolCall: ToolCall,\n responseFormat: ToolResponseFormat\n ): Promise<Command> {\n /**\n * Using the `errorHandler` option of the first `ToolStrategy` entry is sufficient here.\n * There is technically only one `ToolStrategy` entry in `structuredToolInfo` if the user\n * uses `toolStrategy` to define the response format. If the user applies a list of json\n * schema objects, these will be transformed into multiple `ToolStrategy` entries but all\n * with the same `handleError` option.\n */\n const errorHandler = Object.values(responseFormat.tools).at(0)?.options\n ?.handleError;\n\n const toolCallId = toolCall.id;\n if (!toolCallId) {\n throw new Error(\n \"Tool call ID is required to handle tool output errors. Please provide a tool call ID.\"\n );\n }\n\n /**\n * Default behavior: retry if `errorHandler` is undefined or truthy.\n * Only throw if explicitly set to `false`.\n */\n if (errorHandler === false) {\n throw error;\n }\n\n /**\n * retry if:\n */\n if (\n /**\n * if the user has provided truthy value as the `errorHandler`, return a new AIMessage\n * with the error message and retry the tool call.\n */\n errorHandler === undefined ||\n (typeof errorHandler === \"boolean\" && errorHandler) ||\n /**\n * if `errorHandler` is an array and contains MultipleStructuredOutputsError\n */\n (Array.isArray(errorHandler) &&\n errorHandler.some((h) => h instanceof MultipleStructuredOutputsError))\n ) {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: error.message,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: AGENT_NODE_NAME,\n });\n }\n\n /**\n * if `errorHandler` is a string, retry the tool call with given string\n */\n if (typeof errorHandler === \"string\") {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: errorHandler,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: AGENT_NODE_NAME,\n });\n }\n\n /**\n * if `errorHandler` is a function, retry the tool call with the function\n */\n if (typeof errorHandler === \"function\") {\n const content = await errorHandler(error);\n if (typeof content !== \"string\") {\n throw new Error(\"Error handler must return a string.\");\n }\n\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: AGENT_NODE_NAME,\n });\n }\n\n /**\n * Default: retry if we reach here\n */\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: error.message,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: AGENT_NODE_NAME,\n });\n }\n\n #areMoreStepsNeeded(\n state: InternalAgentState<StructuredResponseFormat>,\n response: BaseMessage\n ): boolean {\n const allToolsReturnDirect =\n AIMessage.isInstance(response) &&\n response.tool_calls?.every((call) =>\n this.#options.shouldReturnDirect.has(call.name)\n );\n const remainingSteps =\n \"remainingSteps\" in state ? (state.remainingSteps as number) : undefined;\n return Boolean(\n remainingSteps &&\n ((remainingSteps < 1 && allToolsReturnDirect) ||\n (remainingSteps < 2 && hasToolCalls(state.messages.at(-1))))\n );\n }\n\n async #bindTools(\n model: LanguageModelLike,\n preparedOptions: ModelRequest | undefined,\n structuredResponseFormat: ResponseFormat | undefined\n ): Promise<LanguageModelLike | Runnable> {\n const options: Partial<BaseChatModelCallOptions> = {};\n const structuredTools = Object.values(\n structuredResponseFormat && \"tools\" in structuredResponseFormat\n ? structuredResponseFormat.tools\n : {}\n );\n\n /**\n * Use tools from preparedOptions if provided, otherwise use default tools\n */\n const allTools = [\n ...(preparedOptions?.tools ?? this.#options.toolClasses),\n ...structuredTools.map((toolStrategy) => toolStrategy.tool),\n ];\n\n /**\n * If there are structured tools, we need to set the tool choice to \"any\"\n * so that the model can choose to use a structured tool or not.\n */\n const toolChoice =\n preparedOptions?.toolChoice ||\n (structuredTools.length > 0 ? \"any\" : undefined);\n\n /**\n * check if the user requests a native schema output\n */\n if (structuredResponseFormat?.type === \"native\") {\n const resolvedStrict =\n preparedOptions?.modelSettings?.strict ??\n structuredResponseFormat?.strategy?.strict ??\n true;\n\n const jsonSchemaParams = {\n name: structuredResponseFormat.strategy.schema?.name ?? \"extract\",\n description: getSchemaDescription(\n structuredResponseFormat.strategy.schema\n ),\n schema: structuredResponseFormat.strategy.schema,\n strict: resolvedStrict,\n };\n\n Object.assign(options, {\n /**\n * OpenAI-style options\n * Used by ChatOpenAI, ChatXAI, and other OpenAI-compatible providers.\n */\n response_format: {\n type: \"json_schema\",\n json_schema: jsonSchemaParams,\n },\n\n /**\n * Anthropic-style options\n */\n outputConfig: {\n format: {\n type: \"json_schema\",\n schema: structuredResponseFormat.strategy.schema,\n },\n },\n\n /**\n * Google-style options\n * Used by ChatGoogle and other Gemini-based providers.\n */\n responseSchema: structuredResponseFormat.strategy.schema,\n\n /**\n * for LangSmith structured output tracing\n */\n ls_structured_output_format: {\n kwargs: { method: \"json_schema\" },\n schema: structuredResponseFormat.strategy.schema,\n },\n\n /**\n * Don't force strict on tools: it makes Anthropic's combined grammar\n * \"too complex for compilation\", and only OpenAI Chat Completions needs\n * it (re-applied there). Honor an explicit override; else leave unset.\n */\n strict: preparedOptions?.modelSettings?.strict,\n });\n }\n\n /**\n * Bind tools to the model if they are not already bound.\n */\n const modelWithTools = await bindTools(model, allTools, {\n ...options,\n ...preparedOptions?.modelSettings,\n tool_choice: toolChoice,\n });\n\n /**\n * Create a model runnable with the prompt and agent name\n * Use current SystemMessage state (which may have been modified by middleware)\n */\n const modelRunnable =\n this.#options.includeAgentName === \"inline\"\n ? withAgentName(modelWithTools, this.#options.includeAgentName)\n : modelWithTools;\n\n return modelRunnable;\n }\n\n /**\n * Returns internal bookkeeping state for StateManager, not graph output.\n * The return shape differs from the node's output type (Command).\n */\n // @ts-expect-error Internal state shape differs from graph output type\n getState(): { messages: BaseMessage[] } {\n const state = super.getState();\n const origState = state && !isCommand(state) ? state : {};\n\n return {\n messages: [],\n ...origState,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA8EA,SAAS,wBACP,U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3B,QAAQ,EAAE,QAAQ,cAAc;KAChC,QAAQ,yBAAyB,SAAS;IAC5C;;;;;;IAOA,QAAQ,iBAAiB,eAAe;GAC1C,CAAC;EACH;;;;EAKA,MAAM,iBAAiB,MAAMyB,cAAAA,UAAU,OAAO,UAAU;GACtD,GAAG;GACH,GAAG,iBAAiB;GACpB,aAAa;EACf,CAAC;EAWD,OAJE,KAAKzB,SAAS,qBAAqB,WAC/B0B,sBAAAA,cAAc,gBAAgB,KAAK1B,SAAS,gBAAgB,IAC5D;CAGR;;;;;CAOA,WAAwC;EACtC,MAAM,QAAQ,MAAM,SAAS;EAG7B,OAAO;GACL,UAAU,CAAC;GACX,GAJgB,SAAS,EAAA,GAAA,qBAAA,UAAA,CAAW,KAAK,IAAI,QAAQ,CAAC;EAKxD;CACF;AACF"}
1
+ {"version":3,"file":"AgentNode.cjs","names":["AIMessage","isCommand","RunnableCallable","isConfigurableModel","transformResponseFormat","ProviderStrategy","ToolStrategy","ToolMessage","Command","initChatModel","mergeAbortSignals","raceWithSignal","StructuredOutputParsingError","interopParse","toPartialZodObject","isClientTool","SystemMessage","MiddlewareError","MultipleStructuredOutputsError","hasToolCalls","getSchemaDescription","bindTools","withAgentName"],"sources":["../../../src/agents/nodes/AgentNode.ts"],"sourcesContent":["/* oxlint-disable no-instanceof/no-instanceof */\nimport { Runnable, RunnableConfig } from \"@langchain/core/runnables\";\nimport {\n BaseMessage,\n AIMessage,\n ToolMessage,\n SystemMessage,\n} from \"@langchain/core/messages\";\nimport {\n Command,\n isCommand,\n type LangGraphRunnableConfig,\n} from \"@langchain/langgraph\";\nimport { type BaseChatModelCallOptions } from \"@langchain/core/language_models/chat_models\";\nimport {\n InteropZodObject,\n getSchemaDescription,\n interopParse,\n} from \"@langchain/core/utils/types\";\nimport { raceWithSignal } from \"@langchain/core/runnables\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport { initChatModel } from \"../../chat_models/universal.js\";\nimport {\n MultipleStructuredOutputsError,\n MiddlewareError,\n StructuredOutputParsingError,\n} from \"../errors.js\";\nimport { RunnableCallable } from \"../RunnableCallable.js\";\nimport type { AgentLanguageModelLike as LanguageModelLike } from \"../model.js\";\nimport {\n bindTools,\n validateLLMHasNoBoundTools,\n hasToolCalls,\n isClientTool,\n} from \"../utils.js\";\nimport { isConfigurableModel } from \"../model.js\";\nimport { mergeAbortSignals, toPartialZodObject } from \"../nodes/utils.js\";\nimport { CreateAgentParams } from \"../types.js\";\nimport type { InternalAgentState, Runtime } from \"../runtime.js\";\nimport type {\n AgentMiddleware,\n AnyAnnotationRoot,\n WrapModelCallHandler,\n} from \"../middleware/types.js\";\nimport type { ModelRequest } from \"./types.js\";\nimport { withAgentName } from \"../withAgentName.js\";\nimport {\n ToolStrategy,\n ProviderStrategy,\n transformResponseFormat,\n ToolStrategyError,\n type ResponseFormatInput,\n} from \"../responses.js\";\n\ntype ResponseHandlerResult<StructuredResponseFormat> =\n | {\n structuredResponse: StructuredResponseFormat;\n messages: BaseMessage[];\n }\n | Promise<Command>;\n\n/**\n * Wrap the base handler with middleware wrapModelCall hooks\n * Middleware are composed so the first middleware is the outermost wrapper\n * Example: [auth, retry, cache] means auth wraps retry wraps cache wraps baseHandler\n */\ntype InternalModelResponse<StructuredResponseFormat> =\n | AIMessage\n | ResponseHandlerResult<StructuredResponseFormat>\n | Command;\n\n/**\n * Check if the response is an internal model response.\n * @param response - The response to check.\n * @returns True if the response is an internal model response, false otherwise.\n */\nfunction isInternalModelResponse<StructuredResponseFormat>(\n response: unknown\n): response is InternalModelResponse<StructuredResponseFormat> {\n return (\n AIMessage.isInstance(response) ||\n isCommand(response) ||\n (typeof response === \"object\" &&\n response !== null &&\n \"structuredResponse\" in response &&\n \"messages\" in response)\n );\n}\n\n/**\n * The name of the agent node in the state graph.\n */\nexport const AGENT_NODE_NAME = \"model_request\";\n\nexport interface AgentNodeOptions<\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject =\n AnyAnnotationRoot,\n> extends Pick<\n CreateAgentParams<StructuredResponseFormat, StateSchema, ContextSchema>,\n \"model\" | \"includeAgentName\" | \"name\" | \"responseFormat\" | \"middleware\"\n> {\n toolClasses: (ClientTool | ServerTool)[];\n shouldReturnDirect: Set<string>;\n signal?: AbortSignal;\n systemMessage: SystemMessage;\n wrapModelCallHookMiddleware?: (\n | AgentMiddleware\n | [AgentMiddleware, (...args: unknown[]) => Record<string, unknown>]\n )[];\n}\n\ninterface NativeResponseFormat {\n type: \"native\";\n strategy: ProviderStrategy;\n}\n\ninterface ToolResponseFormat {\n type: \"tool\";\n tools: Record<string, ToolStrategy>;\n}\n\ntype ResponseFormat = NativeResponseFormat | ToolResponseFormat;\n\nexport class AgentNode<\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject =\n AnyAnnotationRoot,\n> extends RunnableCallable<\n InternalAgentState<StructuredResponseFormat>,\n | Command[]\n | {\n messages: BaseMessage[];\n structuredResponse: StructuredResponseFormat;\n }\n> {\n #options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>;\n #systemMessage: SystemMessage;\n\n constructor(\n options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>\n ) {\n super({\n name: options.name ?? \"model\",\n func: (input, config) => this.#run(input, config as RunnableConfig),\n });\n\n this.#options = options;\n this.#systemMessage = options.systemMessage;\n }\n\n /**\n * Returns response format primtivies based on given model and response format provided by the user.\n *\n * If the user selects a tool output:\n * - return a record of tools to extract structured output from the model's response\n *\n * if the user selects a native schema output or if the model supports JSON schema output:\n * - return a provider strategy to extract structured output from the model's response\n *\n * @param model - The model to get the response format for.\n * @returns The response format.\n */\n async #getResponseFormat(\n model: string | LanguageModelLike,\n responseFormat: ResponseFormatInput | undefined = this.#options\n .responseFormat\n ): Promise<ResponseFormat | undefined> {\n if (!responseFormat) {\n return undefined;\n }\n\n let resolvedModel: LanguageModelLike | undefined;\n if (isConfigurableModel(model)) {\n resolvedModel = await (\n model as unknown as {\n _getModelInstance: () => Promise<LanguageModelLike>;\n }\n )._getModelInstance();\n } else if (typeof model !== \"string\") {\n resolvedModel = model;\n }\n\n const strategies = transformResponseFormat(\n responseFormat,\n undefined,\n resolvedModel\n );\n\n if (strategies.length === 0) {\n return undefined;\n }\n\n /**\n * we either define a list of provider strategies or a list of tool strategies\n */\n const isProviderStrategy = strategies.every(\n (format) => format instanceof ProviderStrategy\n );\n\n /**\n * Populate a list of structured tool info.\n */\n if (!isProviderStrategy) {\n return {\n type: \"tool\",\n tools: (\n strategies.filter(\n (format) => format instanceof ToolStrategy\n ) as ToolStrategy[]\n ).reduce(\n (acc, format) => {\n acc[format.name] = format;\n return acc;\n },\n {} as Record<string, ToolStrategy>\n ),\n };\n }\n\n return {\n type: \"native\",\n /**\n * there can only be one provider strategy\n */\n strategy: strategies[0] as ProviderStrategy,\n };\n }\n\n async #run(\n state: InternalAgentState<StructuredResponseFormat>,\n config: RunnableConfig\n ) {\n /**\n * Check if we just executed a returnDirect tool\n * If so, we should generate structured response (if needed) and stop\n */\n const lastMessage = state.messages.at(-1);\n if (\n lastMessage &&\n ToolMessage.isInstance(lastMessage) &&\n lastMessage.name &&\n this.#options.shouldReturnDirect.has(lastMessage.name)\n ) {\n return [new Command({ update: { messages: [] } })];\n }\n\n const { response, lastAiMessage, collectedCommands } =\n await this.#invokeModel(state, config);\n\n /**\n * structuredResponse — return as a plain state update dict (not a Command)\n * because the structuredResponse channel uses UntrackedValue(guard=true)\n * which only allows a single write per step.\n */\n if (\n typeof response === \"object\" &&\n response !== null &&\n \"structuredResponse\" in response &&\n \"messages\" in response\n ) {\n const { structuredResponse, messages } = response as {\n structuredResponse: StructuredResponseFormat;\n messages: BaseMessage[];\n };\n return {\n messages: [...state.messages, ...messages],\n structuredResponse,\n };\n }\n\n const commands: Command[] = [];\n const aiMessage: AIMessage | null = AIMessage.isInstance(response)\n ? response\n : lastAiMessage;\n\n // messages\n if (aiMessage) {\n aiMessage.name = this.name;\n aiMessage.lc_kwargs.name = this.name;\n\n if (this.#areMoreStepsNeeded(state, aiMessage)) {\n commands.push(\n new Command({\n update: {\n messages: [\n new AIMessage({\n content: \"Sorry, need more steps to process this request.\",\n name: this.name,\n id: aiMessage.id,\n }),\n ],\n },\n })\n );\n } else {\n commands.push(new Command({ update: { messages: [aiMessage] } }));\n }\n }\n\n // Commands (from base handler retries or middleware)\n if (isCommand(response) && !collectedCommands.includes(response)) {\n commands.push(response);\n }\n commands.push(...collectedCommands);\n\n return commands;\n }\n\n /**\n * Derive the model from the options.\n * @param state - The state of the agent.\n * @param config - The config of the agent.\n * @returns The model.\n */\n #deriveModel() {\n if (typeof this.#options.model === \"string\") {\n return initChatModel(this.#options.model);\n }\n\n if (this.#options.model) {\n return this.#options.model;\n }\n\n throw new Error(\"No model option was provided, either via `model` option.\");\n }\n\n async #invokeModel(\n state: InternalAgentState<StructuredResponseFormat>,\n config: RunnableConfig,\n options: {\n lastMessage?: string;\n } = {}\n ): Promise<{\n response: InternalModelResponse<StructuredResponseFormat>;\n lastAiMessage: AIMessage | null;\n collectedCommands: Command[];\n }> {\n const model = await this.#deriveModel();\n const lgConfig = config as LangGraphRunnableConfig;\n\n /**\n * Create a local variable for current system message to avoid concurrency issues\n * Each invocation gets its own copy\n */\n let currentSystemMessage = this.#systemMessage;\n\n /**\n * Shared tracking state for AIMessage and Command collection.\n * lastAiMessage tracks the effective AIMessage through the middleware chain.\n * collectedCommands accumulates Commands returned by middleware (not base handler).\n */\n let lastAiMessage: AIMessage | null = null;\n const collectedCommands: Command[] = [];\n\n /**\n * Create the base handler that performs the actual model invocation\n */\n const baseHandler = async (\n request: ModelRequest\n ): Promise<AIMessage | ResponseHandlerResult<StructuredResponseFormat>> => {\n /**\n * Check if the LLM already has bound tools and throw if it does.\n */\n validateLLMHasNoBoundTools(request.model);\n\n const structuredResponseFormat = await this.#getResponseFormat(\n request.model,\n request.responseFormat\n );\n const modelWithTools = await this.#bindTools(\n request.model,\n request,\n structuredResponseFormat\n );\n\n /**\n * prepend the system message to the messages if it is not empty\n */\n const messages = [\n ...(currentSystemMessage.text === \"\" ? [] : [currentSystemMessage]),\n ...request.messages,\n ];\n\n const signal = mergeAbortSignals(this.#options.signal, config.signal);\n const response = (await raceWithSignal(\n modelWithTools.invoke(messages, {\n ...config,\n signal,\n }),\n signal\n )) as AIMessage;\n\n lastAiMessage = response;\n\n /**\n * if the user requests a native schema output, try to parse the response\n * and return the structured response if it is valid\n */\n if (structuredResponseFormat?.type === \"native\") {\n const structuredResponse =\n structuredResponseFormat.strategy.parse(response);\n if (structuredResponse) {\n return { structuredResponse, messages: [response] };\n }\n\n /**\n * If the model produced a terminal response (no tool calls) but the\n * output failed to satisfy the provider strategy's schema, throw an\n * informative error instead of silently exiting with\n * `structuredResponse: undefined`. If tool calls are present, the\n * agent loop continues and a subsequent terminal step will get\n * another chance to produce a valid structured response.\n */\n if (!response.tool_calls || response.tool_calls.length === 0) {\n const schemaTitle =\n typeof structuredResponseFormat.strategy.schema?.title === \"string\"\n ? structuredResponseFormat.strategy.schema.title\n : \"providerStrategy\";\n throw new StructuredOutputParsingError(schemaTitle, [\n \"Model output did not satisfy the provided response schema.\",\n ]);\n }\n\n return response;\n }\n\n if (!structuredResponseFormat || !response.tool_calls) {\n return response;\n }\n\n const toolCalls = response.tool_calls.filter(\n (call) => call.name in structuredResponseFormat.tools\n );\n\n /**\n * if there were not structured tool calls, we can return the response\n */\n if (toolCalls.length === 0) {\n return response;\n }\n\n /**\n * if there were multiple structured tool calls, we should throw an error as this\n * scenario is not defined/supported.\n */\n if (toolCalls.length > 1) {\n return this.#handleMultipleStructuredOutputs(\n response,\n toolCalls,\n structuredResponseFormat\n );\n }\n\n const toolStrategy = structuredResponseFormat.tools[toolCalls[0].name];\n const toolMessageContent = toolStrategy?.options?.toolMessageContent;\n return this.#handleSingleStructuredOutput(\n response,\n toolCalls[0],\n structuredResponseFormat,\n toolMessageContent ?? options.lastMessage\n );\n };\n\n const wrapperMiddleware = this.#options.wrapModelCallHookMiddleware ?? [];\n let wrappedHandler: (\n request: ModelRequest<\n InternalAgentState<StructuredResponseFormat>,\n unknown\n >\n ) => Promise<InternalModelResponse<StructuredResponseFormat>> = baseHandler;\n\n /**\n * Build composed handler from last to first so first middleware becomes outermost\n */\n for (let i = wrapperMiddleware.length - 1; i >= 0; i--) {\n const middlewareEntry = wrapperMiddleware[i];\n const middleware = Array.isArray(middlewareEntry)\n ? middlewareEntry[0]\n : middlewareEntry;\n if (middleware.wrapModelCall) {\n const innerHandler = wrappedHandler;\n const currentMiddleware = middleware;\n\n wrappedHandler = async (\n request: ModelRequest<\n InternalAgentState<StructuredResponseFormat>,\n unknown\n >\n ): Promise<InternalModelResponse<StructuredResponseFormat>> => {\n const baselineSystemMessage = currentSystemMessage;\n\n /**\n * Merge context with default context of middleware\n */\n const context = currentMiddleware.contextSchema\n ? interopParse(\n currentMiddleware.contextSchema,\n lgConfig?.context || {}\n )\n : lgConfig?.context;\n\n /**\n * Create runtime\n */\n const runtime: Runtime<unknown> = Object.freeze({\n context,\n store: lgConfig.store,\n configurable: lgConfig.configurable,\n writer: lgConfig.writer,\n interrupt: lgConfig.interrupt,\n signal: lgConfig.signal,\n });\n\n /**\n * Create the request with state and runtime\n */\n const requestWithStateAndRuntime: ModelRequest<\n InternalAgentState<StructuredResponseFormat>,\n unknown\n > = {\n ...request,\n state: {\n ...(middleware.stateSchema\n ? interopParse(\n toPartialZodObject(middleware.stateSchema),\n state\n )\n : {}),\n messages: state.messages,\n } as InternalAgentState<StructuredResponseFormat>,\n runtime,\n };\n\n /**\n * Create handler that validates tools and calls the inner handler\n */\n const handlerWithValidation = async (\n req: ModelRequest<\n InternalAgentState<StructuredResponseFormat>,\n unknown\n >\n ): Promise<InternalModelResponse<StructuredResponseFormat>> => {\n currentSystemMessage = baselineSystemMessage;\n\n /**\n * Validate tool modifications in wrapModelCall.\n *\n * Classify each client tool as either:\n * - \"added\": a genuinely new tool name not in the static toolClasses\n * - \"replaced\": same name as a registered tool but different instance\n *\n * Added tools are allowed when a wrapToolCall middleware exists to\n * handle their execution. Replaced tools are always rejected to\n * preserve ToolNode execution identity.\n */\n const modifiedTools = req.tools ?? [];\n const registeredToolsByName = new Map(\n this.#options.toolClasses\n .filter(isClientTool)\n .map((t) => [t.name, t] as const)\n );\n\n const addedClientTools = modifiedTools.filter(\n (tool) =>\n isClientTool(tool) && !registeredToolsByName.has(tool.name)\n );\n\n const replacedClientTools = modifiedTools.filter((tool) => {\n if (!isClientTool(tool)) return false;\n const original = registeredToolsByName.get(tool.name);\n return original != null && original !== tool;\n });\n\n if (addedClientTools.length > 0) {\n const hasWrapToolCallHandler = this.#options.middleware?.some(\n (m) => m.wrapToolCall != null\n );\n if (!hasWrapToolCallHandler) {\n throw new Error(\n `You have added a new tool in \"wrapModelCall\" hook of middleware \"${\n currentMiddleware.name\n }\": ${addedClientTools\n .map((tool) => tool.name)\n .join(\n \", \"\n )}. This is not supported unless a middleware provides a \"wrapToolCall\" handler to execute it.`\n );\n }\n }\n\n if (replacedClientTools.length > 0) {\n throw new Error(\n `You have modified a tool in \"wrapModelCall\" hook of middleware \"${\n currentMiddleware.name\n }\": ${replacedClientTools\n .map((tool) => tool.name)\n .join(\", \")}. This is not supported.`\n );\n }\n\n let normalizedReq = req;\n const hasSystemPromptChanged =\n req.systemPrompt !== currentSystemMessage.text;\n const hasSystemMessageChanged =\n req.systemMessage !== currentSystemMessage;\n if (hasSystemPromptChanged && hasSystemMessageChanged) {\n throw new Error(\n \"Cannot change both systemPrompt and systemMessage in the same request.\"\n );\n }\n\n /**\n * Check if systemPrompt is a string was changed, if so create a new SystemMessage\n */\n if (hasSystemPromptChanged) {\n currentSystemMessage = new SystemMessage({\n content: [{ type: \"text\", text: req.systemPrompt }],\n });\n normalizedReq = {\n ...req,\n systemPrompt: currentSystemMessage.text,\n systemMessage: currentSystemMessage,\n };\n }\n /**\n * If the systemMessage was changed, update the current system message\n */\n if (hasSystemMessageChanged) {\n currentSystemMessage = new SystemMessage({\n ...req.systemMessage,\n });\n normalizedReq = {\n ...req,\n systemPrompt: currentSystemMessage.text,\n systemMessage: currentSystemMessage,\n };\n }\n\n const innerHandlerResult = await innerHandler(normalizedReq);\n\n /**\n * Normalize Commands so middleware always sees AIMessage from handler().\n * When an inner handler (base handler or nested middleware) returns a\n * Command (e.g. structured-output retry), substitute the tracked\n * lastAiMessage so the middleware sees an AIMessage, and collect the\n * raw Command so the framework can still propagate it (e.g. for retries).\n *\n * Only collect if not already present: Commands from inner middleware\n * are already tracked via the middleware validation layer (line ~627).\n */\n if (isCommand(innerHandlerResult) && lastAiMessage) {\n if (!collectedCommands.includes(innerHandlerResult)) {\n collectedCommands.push(innerHandlerResult);\n }\n return lastAiMessage as InternalModelResponse<StructuredResponseFormat>;\n }\n\n return innerHandlerResult;\n };\n\n // Call middleware's wrapModelCall with the validation handler\n if (!currentMiddleware.wrapModelCall) {\n return handlerWithValidation(requestWithStateAndRuntime);\n }\n\n try {\n const middlewareResponse = await currentMiddleware.wrapModelCall(\n requestWithStateAndRuntime,\n handlerWithValidation as WrapModelCallHandler\n );\n\n /**\n * Validate that this specific middleware returned a valid response\n */\n if (!isInternalModelResponse(middlewareResponse)) {\n throw new Error(\n `Invalid response from \"wrapModelCall\" in middleware \"${\n currentMiddleware.name\n }\": expected AIMessage or Command, got ${typeof middlewareResponse}`\n );\n }\n\n if (AIMessage.isInstance(middlewareResponse)) {\n lastAiMessage = middlewareResponse;\n } else if (isCommand(middlewareResponse)) {\n collectedCommands.push(middlewareResponse);\n }\n\n return middlewareResponse;\n } catch (error) {\n throw MiddlewareError.wrap(error, currentMiddleware.name);\n }\n };\n }\n }\n\n /**\n * Execute the wrapped handler with the initial request\n * Reset current system prompt to initial state and convert to string using .text getter\n * for backwards compatibility with ModelRequest\n */\n currentSystemMessage = this.#systemMessage;\n const initialRequest: ModelRequest<\n InternalAgentState<StructuredResponseFormat>,\n unknown\n > = {\n model,\n responseFormat: this.#options.responseFormat,\n systemPrompt: currentSystemMessage?.text,\n systemMessage: currentSystemMessage,\n messages: state.messages,\n tools: this.#options.toolClasses,\n state,\n runtime: Object.freeze({\n context: lgConfig?.context,\n store: lgConfig.store,\n configurable: lgConfig.configurable,\n writer: lgConfig.writer,\n interrupt: lgConfig.interrupt,\n signal: lgConfig.signal,\n }) as Runtime<unknown>,\n };\n\n const response = await wrappedHandler(initialRequest);\n return { response, lastAiMessage, collectedCommands };\n }\n\n /**\n * If the model returns multiple structured outputs, we need to handle it.\n * @param response - The response from the model\n * @param toolCalls - The tool calls that were made\n * @returns The response from the model\n */\n #handleMultipleStructuredOutputs(\n response: AIMessage,\n toolCalls: ToolCall[],\n responseFormat: ToolResponseFormat\n ): Promise<Command> {\n const multipleStructuredOutputsError = new MultipleStructuredOutputsError(\n toolCalls.map((call) => call.name)\n );\n\n return this.#handleToolStrategyError(\n multipleStructuredOutputsError,\n response,\n toolCalls[0],\n responseFormat\n );\n }\n\n /**\n * If the model returns a single structured output, we need to handle it.\n * @param toolCall - The tool call that was made\n * @returns The structured response and a message to the LLM if needed\n */\n #handleSingleStructuredOutput(\n response: AIMessage,\n toolCall: ToolCall,\n responseFormat: ToolResponseFormat,\n lastMessage?: string\n ): ResponseHandlerResult<StructuredResponseFormat> {\n const tool = responseFormat.tools[toolCall.name];\n\n try {\n const structuredResponse = tool.parse(\n toolCall.args\n ) as StructuredResponseFormat;\n\n return {\n structuredResponse,\n messages: [\n response,\n new ToolMessage({\n tool_call_id: toolCall.id ?? \"\",\n content: JSON.stringify(structuredResponse),\n name: toolCall.name,\n }),\n new AIMessage(\n lastMessage ??\n `Returning structured response: ${JSON.stringify(\n structuredResponse\n )}`\n ),\n ],\n };\n } catch (error) {\n return this.#handleToolStrategyError(\n error as ToolStrategyError,\n response,\n toolCall,\n responseFormat\n );\n }\n }\n\n async #handleToolStrategyError(\n error: ToolStrategyError,\n response: AIMessage,\n toolCall: ToolCall,\n responseFormat: ToolResponseFormat\n ): Promise<Command> {\n /**\n * Using the `errorHandler` option of the first `ToolStrategy` entry is sufficient here.\n * There is technically only one `ToolStrategy` entry in `structuredToolInfo` if the user\n * uses `toolStrategy` to define the response format. If the user applies a list of json\n * schema objects, these will be transformed into multiple `ToolStrategy` entries but all\n * with the same `handleError` option.\n */\n const errorHandler = Object.values(responseFormat.tools).at(0)?.options\n ?.handleError;\n\n const toolCallId = toolCall.id;\n if (!toolCallId) {\n throw new Error(\n \"Tool call ID is required to handle tool output errors. Please provide a tool call ID.\"\n );\n }\n\n /**\n * Default behavior: retry if `errorHandler` is undefined or truthy.\n * Only throw if explicitly set to `false`.\n */\n if (errorHandler === false) {\n throw error;\n }\n\n /**\n * retry if:\n */\n if (\n /**\n * if the user has provided truthy value as the `errorHandler`, return a new AIMessage\n * with the error message and retry the tool call.\n */\n errorHandler === undefined ||\n (typeof errorHandler === \"boolean\" && errorHandler) ||\n /**\n * if `errorHandler` is an array and contains MultipleStructuredOutputsError\n */\n (Array.isArray(errorHandler) &&\n errorHandler.some((h) => h instanceof MultipleStructuredOutputsError))\n ) {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: error.message,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: AGENT_NODE_NAME,\n });\n }\n\n /**\n * if `errorHandler` is a string, retry the tool call with given string\n */\n if (typeof errorHandler === \"string\") {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: errorHandler,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: AGENT_NODE_NAME,\n });\n }\n\n /**\n * if `errorHandler` is a function, retry the tool call with the function\n */\n if (typeof errorHandler === \"function\") {\n const content = await errorHandler(error);\n if (typeof content !== \"string\") {\n throw new Error(\"Error handler must return a string.\");\n }\n\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: AGENT_NODE_NAME,\n });\n }\n\n /**\n * Default: retry if we reach here\n */\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: error.message,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: AGENT_NODE_NAME,\n });\n }\n\n #areMoreStepsNeeded(\n state: InternalAgentState<StructuredResponseFormat>,\n response: BaseMessage\n ): boolean {\n const allToolsReturnDirect =\n AIMessage.isInstance(response) &&\n response.tool_calls?.every((call) =>\n this.#options.shouldReturnDirect.has(call.name)\n );\n const remainingSteps =\n \"remainingSteps\" in state ? (state.remainingSteps as number) : undefined;\n return Boolean(\n remainingSteps &&\n ((remainingSteps < 1 && allToolsReturnDirect) ||\n (remainingSteps < 2 && hasToolCalls(state.messages.at(-1))))\n );\n }\n\n async #bindTools(\n model: LanguageModelLike,\n preparedOptions: ModelRequest | undefined,\n structuredResponseFormat: ResponseFormat | undefined\n ): Promise<LanguageModelLike | Runnable> {\n const options: Partial<BaseChatModelCallOptions> = {};\n const structuredTools = Object.values(\n structuredResponseFormat && \"tools\" in structuredResponseFormat\n ? structuredResponseFormat.tools\n : {}\n );\n\n /**\n * Use tools from preparedOptions if provided, otherwise use default tools\n */\n const allTools = [\n ...(preparedOptions?.tools ?? this.#options.toolClasses),\n ...structuredTools.map((toolStrategy) => toolStrategy.tool),\n ];\n\n /**\n * If there are structured tools, we need to set the tool choice to \"any\"\n * so that the model can choose to use a structured tool or not.\n */\n const toolChoice =\n preparedOptions?.toolChoice ||\n (structuredTools.length > 0 ? \"any\" : undefined);\n\n /**\n * check if the user requests a native schema output\n */\n if (structuredResponseFormat?.type === \"native\") {\n const resolvedStrict =\n preparedOptions?.modelSettings?.strict ??\n structuredResponseFormat?.strategy?.strict ??\n true;\n\n const jsonSchemaParams = {\n name: structuredResponseFormat.strategy.schema?.name ?? \"extract\",\n description: getSchemaDescription(\n structuredResponseFormat.strategy.schema\n ),\n schema: structuredResponseFormat.strategy.schema,\n strict: resolvedStrict,\n };\n\n Object.assign(options, {\n /**\n * OpenAI-style options\n * Used by ChatOpenAI, ChatXAI, and other OpenAI-compatible providers.\n */\n response_format: {\n type: \"json_schema\",\n json_schema: jsonSchemaParams,\n },\n\n /**\n * Anthropic-style options\n */\n outputConfig: {\n format: {\n type: \"json_schema\",\n schema: structuredResponseFormat.strategy.schema,\n },\n },\n\n /**\n * Google-style options\n * Used by ChatGoogle and other Gemini-based providers.\n */\n responseSchema: structuredResponseFormat.strategy.schema,\n\n /**\n * for LangSmith structured output tracing\n */\n ls_structured_output_format: {\n kwargs: { method: \"json_schema\" },\n schema: structuredResponseFormat.strategy.schema,\n },\n\n /**\n * Don't force strict on tools: it makes Anthropic's combined grammar\n * \"too complex for compilation\", and only OpenAI Chat Completions needs\n * it (re-applied there). Honor an explicit override; else leave unset.\n */\n strict: preparedOptions?.modelSettings?.strict,\n });\n }\n\n /**\n * Bind tools to the model if they are not already bound.\n */\n const modelWithTools = await bindTools(model, allTools, {\n ...options,\n ...preparedOptions?.modelSettings,\n tool_choice: toolChoice,\n });\n\n /**\n * Create a model runnable with the prompt and agent name\n * Use current SystemMessage state (which may have been modified by middleware)\n */\n const modelRunnable =\n this.#options.includeAgentName === \"inline\"\n ? withAgentName(modelWithTools, this.#options.includeAgentName)\n : modelWithTools;\n\n return modelRunnable;\n }\n\n /**\n * Returns internal bookkeeping state for StateManager, not graph output.\n * The return shape differs from the node's output type (Command).\n */\n // @ts-expect-error Internal state shape differs from graph output type\n getState(): { messages: BaseMessage[] } {\n const state = super.getState();\n const origState = state && !isCommand(state) ? state : {};\n\n return {\n messages: [],\n ...origState,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA8EA,SAAS,wBACP,UAC6D;CAC7D,OACEA,yBAAAA,UAAU,WAAW,QAAQ,MAAA,GAC7BC,qBAAAA,UAAAA,CAAU,QAAQ,KACjB,OAAO,aAAa,YACnB,aAAa,QACb,wBAAwB,YACxB,cAAc;AAEpB;;;;AAK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U,OAAO,UAAU;GACtD,GAAG;GACH,GAAG,iBAAiB;GACpB,aAAa;EACf,CAAC;EAWD,OAJE,KAAK,SAAS,qBAAqB,WAC/BC,sBAAAA,cAAc,gBAAgB,KAAK,SAAS,gBAAgB,IAC5D;CAGR;;;;;CAOA,WAAwC;EACtC,MAAM,QAAQ,MAAM,SAAS;EAG7B,OAAO;GACL,UAAU,CAAC;GACX,GAJgB,SAAS,EAAA,GAACrB,qBAAAA,UAAAA,CAAU,KAAK,IAAI,QAAQ,CAAC;EAKxD;CACF;AACF"}
@@ -171,7 +171,10 @@ var AgentNode = class extends RunnableCallable {
171
171
  * agent loop continues and a subsequent terminal step will get
172
172
  * another chance to produce a valid structured response.
173
173
  */
174
- if (!response.tool_calls || response.tool_calls.length === 0) throw new StructuredOutputParsingError(typeof structuredResponseFormat.strategy.schema?.title === "string" ? structuredResponseFormat.strategy.schema.title : "providerStrategy", ["Model output did not satisfy the provided response schema."]);
174
+ if (!response.tool_calls || response.tool_calls.length === 0) {
175
+ const schemaTitle = typeof structuredResponseFormat.strategy.schema?.title === "string" ? structuredResponseFormat.strategy.schema.title : "providerStrategy";
176
+ throw new StructuredOutputParsingError(schemaTitle, ["Model output did not satisfy the provided response schema."]);
177
+ }
175
178
  return response;
176
179
  }
177
180
  if (!structuredResponseFormat || !response.tool_calls) return response;