langchain 1.0.0-alpha.6 → 1.0.0-alpha.7

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 (185) hide show
  1. package/dist/agents/ReactAgent.cjs.map +1 -1
  2. package/dist/agents/ReactAgent.d.cts +1 -2
  3. package/dist/agents/ReactAgent.d.cts.map +1 -1
  4. package/dist/agents/ReactAgent.d.ts +1 -2
  5. package/dist/agents/ReactAgent.d.ts.map +1 -1
  6. package/dist/agents/ReactAgent.js.map +1 -1
  7. package/dist/agents/annotation.cjs.map +1 -1
  8. package/dist/agents/annotation.d.cts +12 -5
  9. package/dist/agents/annotation.d.cts.map +1 -1
  10. package/dist/agents/annotation.d.ts +12 -5
  11. package/dist/agents/annotation.d.ts.map +1 -1
  12. package/dist/agents/annotation.js.map +1 -1
  13. package/dist/agents/createAgent.cjs.map +1 -1
  14. package/dist/agents/createAgent.js.map +1 -1
  15. package/dist/agents/index.cjs.map +1 -1
  16. package/dist/agents/index.d.cts +3 -3
  17. package/dist/agents/index.d.cts.map +1 -1
  18. package/dist/agents/index.d.ts +3 -3
  19. package/dist/agents/index.d.ts.map +1 -1
  20. package/dist/agents/index.js.map +1 -1
  21. package/dist/agents/interrupt.d.cts +14 -1
  22. package/dist/agents/interrupt.d.cts.map +1 -1
  23. package/dist/agents/interrupt.d.ts +14 -1
  24. package/dist/agents/interrupt.d.ts.map +1 -1
  25. package/dist/agents/middlewareAgent/ReactAgent.cjs +262 -55
  26. package/dist/agents/middlewareAgent/ReactAgent.cjs.map +1 -1
  27. package/dist/agents/middlewareAgent/ReactAgent.d.cts +97 -10
  28. package/dist/agents/middlewareAgent/ReactAgent.d.cts.map +1 -1
  29. package/dist/agents/middlewareAgent/ReactAgent.d.ts +97 -10
  30. package/dist/agents/middlewareAgent/ReactAgent.d.ts.map +1 -1
  31. package/dist/agents/middlewareAgent/ReactAgent.js +264 -57
  32. package/dist/agents/middlewareAgent/ReactAgent.js.map +1 -1
  33. package/dist/agents/middlewareAgent/annotation.cjs +10 -4
  34. package/dist/agents/middlewareAgent/annotation.cjs.map +1 -1
  35. package/dist/agents/middlewareAgent/annotation.js +10 -4
  36. package/dist/agents/middlewareAgent/annotation.js.map +1 -1
  37. package/dist/agents/middlewareAgent/constants.d.cts +5 -0
  38. package/dist/agents/middlewareAgent/constants.d.cts.map +1 -0
  39. package/dist/agents/middlewareAgent/constants.d.ts +5 -0
  40. package/dist/agents/middlewareAgent/constants.d.ts.map +1 -0
  41. package/dist/agents/middlewareAgent/index.cjs.map +1 -1
  42. package/dist/agents/middlewareAgent/index.js.map +1 -1
  43. package/dist/agents/middlewareAgent/middleware/bigTool.cjs +162 -0
  44. package/dist/agents/middlewareAgent/middleware/bigTool.cjs.map +1 -0
  45. package/dist/agents/middlewareAgent/middleware/bigTool.d.cts +113 -0
  46. package/dist/agents/middlewareAgent/middleware/bigTool.d.cts.map +1 -0
  47. package/dist/agents/middlewareAgent/middleware/bigTool.d.ts +113 -0
  48. package/dist/agents/middlewareAgent/middleware/bigTool.d.ts.map +1 -0
  49. package/dist/agents/middlewareAgent/middleware/bigTool.js +161 -0
  50. package/dist/agents/middlewareAgent/middleware/bigTool.js.map +1 -0
  51. package/dist/agents/middlewareAgent/middleware/dynamicSystemPrompt.cjs +58 -0
  52. package/dist/agents/middlewareAgent/middleware/dynamicSystemPrompt.cjs.map +1 -0
  53. package/dist/agents/middlewareAgent/middleware/dynamicSystemPrompt.d.cts +46 -0
  54. package/dist/agents/middlewareAgent/middleware/dynamicSystemPrompt.d.cts.map +1 -0
  55. package/dist/agents/middlewareAgent/middleware/dynamicSystemPrompt.d.ts +46 -0
  56. package/dist/agents/middlewareAgent/middleware/dynamicSystemPrompt.d.ts.map +1 -0
  57. package/dist/agents/middlewareAgent/middleware/dynamicSystemPrompt.js +58 -0
  58. package/dist/agents/middlewareAgent/middleware/dynamicSystemPrompt.js.map +1 -0
  59. package/dist/agents/middlewareAgent/middleware/hitl.cjs +160 -84
  60. package/dist/agents/middlewareAgent/middleware/hitl.cjs.map +1 -1
  61. package/dist/agents/middlewareAgent/middleware/hitl.d.cts +271 -51
  62. package/dist/agents/middlewareAgent/middleware/hitl.d.cts.map +1 -1
  63. package/dist/agents/middlewareAgent/middleware/hitl.d.ts +271 -51
  64. package/dist/agents/middlewareAgent/middleware/hitl.d.ts.map +1 -1
  65. package/dist/agents/middlewareAgent/middleware/hitl.js +161 -85
  66. package/dist/agents/middlewareAgent/middleware/hitl.js.map +1 -1
  67. package/dist/agents/middlewareAgent/middleware/index.cjs +6 -0
  68. package/dist/agents/middlewareAgent/middleware/index.cjs.map +1 -1
  69. package/dist/agents/middlewareAgent/middleware/index.d.cts +6 -4
  70. package/dist/agents/middlewareAgent/middleware/index.d.ts +6 -4
  71. package/dist/agents/middlewareAgent/middleware/index.js +5 -1
  72. package/dist/agents/middlewareAgent/middleware/index.js.map +1 -1
  73. package/dist/agents/middlewareAgent/middleware/promptCaching.cjs +24 -8
  74. package/dist/agents/middlewareAgent/middleware/promptCaching.cjs.map +1 -1
  75. package/dist/agents/middlewareAgent/middleware/promptCaching.d.cts +51 -6
  76. package/dist/agents/middlewareAgent/middleware/promptCaching.d.cts.map +1 -1
  77. package/dist/agents/middlewareAgent/middleware/promptCaching.d.ts +51 -6
  78. package/dist/agents/middlewareAgent/middleware/promptCaching.d.ts.map +1 -1
  79. package/dist/agents/middlewareAgent/middleware/promptCaching.js +24 -8
  80. package/dist/agents/middlewareAgent/middleware/promptCaching.js.map +1 -1
  81. package/dist/agents/middlewareAgent/middleware/summarization.cjs +24 -12
  82. package/dist/agents/middlewareAgent/middleware/summarization.cjs.map +1 -1
  83. package/dist/agents/middlewareAgent/middleware/summarization.d.cts +5 -3
  84. package/dist/agents/middlewareAgent/middleware/summarization.d.cts.map +1 -1
  85. package/dist/agents/middlewareAgent/middleware/summarization.d.ts +11 -9
  86. package/dist/agents/middlewareAgent/middleware/summarization.d.ts.map +1 -1
  87. package/dist/agents/middlewareAgent/middleware/summarization.js +25 -13
  88. package/dist/agents/middlewareAgent/middleware/summarization.js.map +1 -1
  89. package/dist/agents/middlewareAgent/middleware.cjs +8 -5
  90. package/dist/agents/middlewareAgent/middleware.cjs.map +1 -1
  91. package/dist/agents/middlewareAgent/middleware.d.cts +67 -7
  92. package/dist/agents/middlewareAgent/middleware.d.cts.map +1 -1
  93. package/dist/agents/middlewareAgent/middleware.d.ts +67 -7
  94. package/dist/agents/middlewareAgent/middleware.d.ts.map +1 -1
  95. package/dist/agents/middlewareAgent/middleware.js +8 -5
  96. package/dist/agents/middlewareAgent/middleware.js.map +1 -1
  97. package/dist/agents/middlewareAgent/nodes/AfterModalNode.cjs +2 -2
  98. package/dist/agents/middlewareAgent/nodes/AfterModalNode.cjs.map +1 -1
  99. package/dist/agents/middlewareAgent/nodes/AfterModalNode.js +2 -2
  100. package/dist/agents/middlewareAgent/nodes/AfterModalNode.js.map +1 -1
  101. package/dist/agents/middlewareAgent/nodes/AgentNode.cjs +117 -68
  102. package/dist/agents/middlewareAgent/nodes/AgentNode.cjs.map +1 -1
  103. package/dist/agents/middlewareAgent/nodes/AgentNode.js +121 -72
  104. package/dist/agents/middlewareAgent/nodes/AgentNode.js.map +1 -1
  105. package/dist/agents/middlewareAgent/nodes/BeforeModalNode.cjs +2 -2
  106. package/dist/agents/middlewareAgent/nodes/BeforeModalNode.cjs.map +1 -1
  107. package/dist/agents/middlewareAgent/nodes/BeforeModalNode.js +2 -2
  108. package/dist/agents/middlewareAgent/nodes/BeforeModalNode.js.map +1 -1
  109. package/dist/agents/middlewareAgent/nodes/middleware.cjs +42 -17
  110. package/dist/agents/middlewareAgent/nodes/middleware.cjs.map +1 -1
  111. package/dist/agents/middlewareAgent/nodes/middleware.js +42 -18
  112. package/dist/agents/middlewareAgent/nodes/middleware.js.map +1 -1
  113. package/dist/agents/middlewareAgent/nodes/utils.cjs +25 -11
  114. package/dist/agents/middlewareAgent/nodes/utils.cjs.map +1 -1
  115. package/dist/agents/middlewareAgent/nodes/utils.js +26 -12
  116. package/dist/agents/middlewareAgent/nodes/utils.js.map +1 -1
  117. package/dist/agents/middlewareAgent/types.d.cts +153 -66
  118. package/dist/agents/middlewareAgent/types.d.cts.map +1 -1
  119. package/dist/agents/middlewareAgent/types.d.ts +153 -66
  120. package/dist/agents/middlewareAgent/types.d.ts.map +1 -1
  121. package/dist/agents/model.cjs +13 -0
  122. package/dist/agents/model.cjs.map +1 -0
  123. package/dist/agents/model.js +11 -0
  124. package/dist/agents/model.js.map +1 -0
  125. package/dist/agents/nodes/AgentNode.cjs +56 -28
  126. package/dist/agents/nodes/AgentNode.cjs.map +1 -1
  127. package/dist/agents/nodes/AgentNode.js +57 -29
  128. package/dist/agents/nodes/AgentNode.js.map +1 -1
  129. package/dist/agents/nodes/ToolNode.cjs +1 -1
  130. package/dist/agents/nodes/ToolNode.cjs.map +1 -1
  131. package/dist/agents/nodes/ToolNode.d.cts +1 -1
  132. package/dist/agents/nodes/ToolNode.js +1 -1
  133. package/dist/agents/nodes/ToolNode.js.map +1 -1
  134. package/dist/agents/responses.cjs +52 -10
  135. package/dist/agents/responses.cjs.map +1 -1
  136. package/dist/agents/responses.d.cts +12 -20
  137. package/dist/agents/responses.d.cts.map +1 -1
  138. package/dist/agents/responses.d.ts +12 -20
  139. package/dist/agents/responses.d.ts.map +1 -1
  140. package/dist/agents/responses.js +52 -11
  141. package/dist/agents/responses.js.map +1 -1
  142. package/dist/agents/types.d.cts +2 -3
  143. package/dist/agents/types.d.cts.map +1 -1
  144. package/dist/agents/types.d.ts +2 -3
  145. package/dist/agents/types.d.ts.map +1 -1
  146. package/dist/agents/utils.cjs +5 -23
  147. package/dist/agents/utils.cjs.map +1 -1
  148. package/dist/agents/utils.js +2 -19
  149. package/dist/agents/utils.js.map +1 -1
  150. package/dist/chains/query_constructor/index.d.cts +1 -1
  151. package/dist/chains/summarization/load.d.ts +2 -2
  152. package/dist/chains/summarization/load.d.ts.map +1 -1
  153. package/dist/embeddings/cache_backed.d.ts +1 -1
  154. package/dist/evaluation/comparison/pairwise.d.cts.map +1 -1
  155. package/dist/evaluation/comparison/pairwise.d.ts.map +1 -1
  156. package/dist/evaluation/criteria/criteria.d.cts.map +1 -1
  157. package/dist/evaluation/criteria/criteria.d.ts.map +1 -1
  158. package/dist/index.cjs +38 -6
  159. package/dist/index.cjs.map +1 -1
  160. package/dist/index.d.cts +11 -4
  161. package/dist/index.d.ts +11 -4
  162. package/dist/index.js +18 -4
  163. package/dist/index.js.map +1 -1
  164. package/dist/langchain-core/dist/messages/base.d.cts.map +1 -1
  165. package/dist/langchain-core/dist/messages/content/index.d.cts +20 -1
  166. package/dist/langchain-core/dist/messages/content/index.d.cts.map +1 -1
  167. package/dist/langchain-core/dist/messages/content/tools.d.cts +67 -6
  168. package/dist/langchain-core/dist/messages/content/tools.d.cts.map +1 -1
  169. package/dist/langchain-core/dist/messages/message.d.cts +6 -6
  170. package/dist/langchain-core/dist/messages/message.d.cts.map +1 -1
  171. package/dist/langchain-core/dist/utils/types/index.d.cts.map +1 -1
  172. package/dist/libs/langchain-core/dist/messages/base.d.ts.map +1 -1
  173. package/dist/libs/langchain-core/dist/messages/content/index.d.ts +20 -1
  174. package/dist/libs/langchain-core/dist/messages/content/index.d.ts.map +1 -1
  175. package/dist/libs/langchain-core/dist/messages/content/tools.d.ts +67 -6
  176. package/dist/libs/langchain-core/dist/messages/content/tools.d.ts.map +1 -1
  177. package/dist/libs/langchain-core/dist/messages/message.d.ts +6 -6
  178. package/dist/libs/langchain-core/dist/messages/message.d.ts.map +1 -1
  179. package/dist/libs/langchain-core/dist/utils/types/index.d.ts.map +1 -1
  180. package/dist/load/import_map.cjs +1 -1
  181. package/dist/load/import_map.js +1 -1
  182. package/dist/output_parsers/structured.d.cts +1 -1
  183. package/dist/tools/fs.d.cts +1 -1
  184. package/dist/tools/retriever.d.cts +1 -1
  185. package/package.json +7 -7
@@ -1 +1 @@
1
- {"version":3,"file":"ToolNode.cjs","names":["input: unknown","isBaseMessage","RunnableCallable","tools: (StructuredToolInterface | DynamicTool | RunnableToolLike)[]","options?: ToolNodeOptions","call: ToolCall","config: RunnableConfig","tool","mergeAbortSignals","ToolMessage","e: unknown","ToolInputParsingException","ToolInvocationError","state: ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"]","outputs: (ToolMessage | Command)[]","messages: BaseMessage[]","toolMessageIds: Set<string>","aiMessage: AIMessage | undefined","AIMessage","isCommand","combinedOutputs: (\n | { messages: BaseMessage[] }\n | BaseMessage[]\n | Command\n )[]","parentCommand: Command | null","Command","x: unknown","Send"],"sources":["../../../src/agents/nodes/ToolNode.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable no-instanceof/no-instanceof */\nimport {\n BaseMessage,\n ToolMessage,\n AIMessage,\n isBaseMessage,\n isToolMessage,\n} from \"@langchain/core/messages\";\nimport { RunnableConfig, RunnableToolLike } from \"@langchain/core/runnables\";\nimport {\n DynamicTool,\n StructuredToolInterface,\n ToolInputParsingException,\n} from \"@langchain/core/tools\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\nimport type { InteropZodObject } from \"@langchain/core/utils/types\";\nimport {\n isCommand,\n Command,\n Send,\n isGraphInterrupt,\n} from \"@langchain/langgraph\";\n\nimport { RunnableCallable } from \"../RunnableCallable.js\";\nimport {\n PreHookAnnotation,\n AnyAnnotationRoot,\n ToAnnotationRoot,\n} from \"../annotation.js\";\nimport { mergeAbortSignals } from \"./utils.js\";\nimport { ToolInvocationError } from \"../errors.js\";\n\nexport interface ToolNodeOptions {\n /**\n * The name of the tool node.\n */\n name?: string;\n /**\n * The tags to add to the tool call.\n */\n tags?: string[];\n /**\n * The abort signal to cancel the tool call.\n */\n signal?: AbortSignal;\n /**\n * Whether to throw the error immediately if the tool fails or handle it by the `onToolError` function or via ToolMessage.\n *\n * If `true` (default):\n * - a tool message with the error will be returned to the LLM\n *\n * If `false`:\n * - the error will be thrown immediately\n *\n * If a function is provided:\n * - returns a custom {@link ToolMessage} as result\n * - throws an error otherwise\n *\n * @default true\n */\n handleToolErrors?:\n | boolean\n | ((error: unknown, toolCall: ToolCall) => ToolMessage | undefined);\n}\n\nconst isBaseMessageArray = (input: unknown): input is BaseMessage[] =>\n Array.isArray(input) && input.every(isBaseMessage);\n\nconst isMessagesState = (\n input: unknown\n): input is { messages: BaseMessage[] } =>\n typeof input === \"object\" &&\n input != null &&\n \"messages\" in input &&\n isBaseMessageArray(input.messages);\n\nconst isSendInput = (input: unknown): input is { lg_tool_call: ToolCall } =>\n typeof input === \"object\" && input != null && \"lg_tool_call\" in input;\n\n/**\n * `ToolNode` is a built-in LangGraph component that handles tool calls within an agent's workflow.\n * It works seamlessly with `createAgent`, offering advanced tool execution control, built\n * in parallelism, and error handling.\n *\n * @example\n * ```ts\n * import { ToolNode, tool, AIMessage } from \"langchain\";\n * import { z } from \"zod/v3\";\n *\n * const getWeather = tool((input) => {\n * if ([\"sf\", \"san francisco\"].includes(input.location.toLowerCase())) {\n * return \"It's 60 degrees and foggy.\";\n * } else {\n * return \"It's 90 degrees and sunny.\";\n * }\n * }, {\n * name: \"get_weather\",\n * description: \"Call to get the current weather.\",\n * schema: z.object({\n * location: z.string().describe(\"Location to get the weather for.\"),\n * }),\n * });\n *\n * const tools = [getWeather];\n * const toolNode = new ToolNode(tools);\n *\n * const messageWithSingleToolCall = new AIMessage({\n * content: \"\",\n * tool_calls: [\n * {\n * name: \"get_weather\",\n * args: { location: \"sf\" },\n * id: \"tool_call_id\",\n * type: \"tool_call\",\n * }\n * ]\n * })\n *\n * await toolNode.invoke({ messages: [messageWithSingleToolCall] });\n * // Returns tool invocation responses as:\n * // { messages: ToolMessage[] }\n * ```\n */\nexport class ToolNode<\n StateSchema extends AnyAnnotationRoot | InteropZodObject = any,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = any\n> extends RunnableCallable<StateSchema, ContextSchema> {\n tools: (StructuredToolInterface | DynamicTool | RunnableToolLike)[];\n\n trace = false;\n\n signal?: AbortSignal;\n\n handleToolErrors:\n | boolean\n | ((error: unknown, toolCall: ToolCall) => ToolMessage | undefined) = true;\n\n constructor(\n tools: (StructuredToolInterface | DynamicTool | RunnableToolLike)[],\n public options?: ToolNodeOptions\n ) {\n const { name, tags, handleToolErrors } = options ?? {};\n super({\n name,\n tags,\n func: (state, config) =>\n this.run(\n state as ToAnnotationRoot<StateSchema>[\"State\"] &\n PreHookAnnotation[\"State\"],\n config as RunnableConfig\n ),\n });\n this.tools = tools;\n this.handleToolErrors = handleToolErrors ?? this.handleToolErrors;\n this.signal = options?.signal;\n }\n\n protected async runTool(\n call: ToolCall,\n config: RunnableConfig\n ): Promise<ToolMessage | Command> {\n const tool = this.tools.find((tool) => tool.name === call.name);\n try {\n if (tool === undefined) {\n throw new Error(`Tool \"${call.name}\" not found.`);\n }\n\n const output = await tool.invoke(\n { ...call, type: \"tool_call\" },\n {\n ...config,\n signal: mergeAbortSignals(this.signal, config.signal),\n }\n );\n\n if (\n (isBaseMessage(output) && output.getType() === \"tool\") ||\n isCommand(output)\n ) {\n return output as ToolMessage | Command;\n }\n\n return new ToolMessage({\n name: tool.name,\n content: typeof output === \"string\" ? output : JSON.stringify(output),\n tool_call_id: call.id!,\n });\n } catch (e: unknown) {\n /**\n * If tool invocation fails due to input parsing error, throw a {@link ToolInvocationError}\n */\n if (e instanceof ToolInputParsingException) {\n throw new ToolInvocationError(e, call);\n }\n\n /**\n * throw the error if user prefers not to handle tool errors\n */\n if (!this.handleToolErrors) {\n throw e;\n }\n\n if (isGraphInterrupt(e)) {\n /**\n * {@link NodeInterrupt} errors are a breakpoint to bring a human into the loop.\n * As such, they are not recoverable by the agent and shouldn't be fed\n * back. Instead, re-throw these errors even when `handleToolErrors = true`.\n */\n throw e;\n }\n\n /**\n * If the signal is aborted, we want to bubble up the error to the invoke caller.\n */\n if (this.signal?.aborted) {\n throw e;\n }\n\n /**\n * if the user provides a function, call it with the error and tool call\n * and return the result if it is a {@link ToolMessage}\n */\n if (typeof this.handleToolErrors === \"function\") {\n const result = this.handleToolErrors(e, call);\n if (result && isToolMessage(result)) {\n return result;\n }\n } else if (this.handleToolErrors) {\n return new ToolMessage({\n name: call.name,\n content: `${e}\\n Please fix your mistakes.`,\n tool_call_id: call.id!,\n });\n }\n\n /**\n * If the user doesn't handle the error, throw it\n */\n throw e;\n }\n }\n\n protected async run(\n state: ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"],\n config: RunnableConfig\n ): Promise<ContextSchema> {\n let outputs: (ToolMessage | Command)[];\n\n if (isSendInput(state)) {\n outputs = [await this.runTool(state.lg_tool_call, config)];\n } else {\n let messages: BaseMessage[];\n if (isBaseMessageArray(state)) {\n messages = state;\n } else if (isMessagesState(state)) {\n messages = state.messages;\n } else {\n throw new Error(\n \"ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.\"\n );\n }\n\n const toolMessageIds: Set<string> = new Set(\n messages\n .filter((msg) => msg.getType() === \"tool\")\n .map((msg) => (msg as ToolMessage).tool_call_id)\n );\n\n let aiMessage: AIMessage | undefined;\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n const message = messages[i];\n if (AIMessage.isInstance(message)) {\n aiMessage = message;\n break;\n }\n }\n\n if (!AIMessage.isInstance(aiMessage)) {\n throw new Error(\"ToolNode only accepts AIMessages as input.\");\n }\n\n outputs = await Promise.all(\n aiMessage.tool_calls\n ?.filter((call) => call.id == null || !toolMessageIds.has(call.id))\n .map((call) => this.runTool(call, config)) ?? []\n );\n }\n\n // Preserve existing behavior for non-command tool outputs for backwards compatibility\n if (!outputs.some(isCommand)) {\n return (Array.isArray(state)\n ? outputs\n : { messages: outputs }) as unknown as ContextSchema;\n }\n\n // Handle mixed Command and non-Command outputs\n const combinedOutputs: (\n | { messages: BaseMessage[] }\n | BaseMessage[]\n | Command\n )[] = [];\n let parentCommand: Command | null = null;\n\n for (const output of outputs) {\n if (isCommand(output)) {\n if (\n output.graph === Command.PARENT &&\n Array.isArray(output.goto) &&\n output.goto.every((send) => isSend(send))\n ) {\n if (parentCommand) {\n (parentCommand.goto as Send[]).push(...(output.goto as Send[]));\n } else {\n parentCommand = new Command({\n graph: Command.PARENT,\n goto: output.goto,\n });\n }\n } else {\n combinedOutputs.push(output);\n }\n } else {\n combinedOutputs.push(\n Array.isArray(state) ? [output] : { messages: [output] }\n );\n }\n }\n\n if (parentCommand) {\n combinedOutputs.push(parentCommand);\n }\n\n return combinedOutputs as unknown as ContextSchema;\n }\n}\n\nexport function isSend(x: unknown): x is Send {\n return x instanceof Send;\n}\n"],"mappings":";;;;;;;;;AAkEA,MAAM,qBAAqB,CAACA,UAC1B,MAAM,QAAQ,MAAM,IAAI,MAAM,MAAMC,wCAAc;AAEpD,MAAM,kBAAkB,CACtBD,UAEA,OAAO,UAAU,YACjB,SAAS,QACT,cAAc,SACd,mBAAmB,MAAM,SAAS;AAEpC,MAAM,cAAc,CAACA,UACnB,OAAO,UAAU,YAAY,SAAS,QAAQ,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8ClE,IAAa,WAAb,cAGUE,0CAA6C;CACrD;CAEA,QAAQ;CAER;CAEA,mBAEwE;CAExE,YACEC,OACOC,SACP;EACA,MAAM,EAAE,MAAM,MAAM,kBAAkB,GAAG,WAAW,CAAE;EACtD,MAAM;GACJ;GACA;GACA,MAAM,CAAC,OAAO,WACZ,KAAK,IACH,OAEA,OACD;EACJ,EAAC;EAZK;EAaP,KAAK,QAAQ;EACb,KAAK,mBAAmB,oBAAoB,KAAK;EACjD,KAAK,SAAS,SAAS;CACxB;CAED,MAAgB,QACdC,MACAC,QACgC;EAChC,MAAM,OAAO,KAAK,MAAM,KAAK,CAACC,WAASA,OAAK,SAAS,KAAK,KAAK;AAC/D,MAAI;AACF,OAAI,SAAS,OACX,OAAM,IAAI,MAAM,CAAC,MAAM,EAAE,KAAK,KAAK,YAAY,CAAC;GAGlD,MAAM,SAAS,MAAM,KAAK,OACxB;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,UAAU,SAAS;AACzB,QAAIC,oCAAU,WAAW,QAAQ,EAAE;KACjC,YAAY;AACZ;IACD;GACF;AAED,OAAI,CAACA,oCAAU,WAAW,UAAU,CAClC,OAAM,IAAI,MAAM;GAGlB,UAAU,MAAM,QAAQ,IACtB,UAAU,YACN,OAAO,CAAC,SAAS,KAAK,MAAM,QAAQ,CAAC,eAAe,IAAI,KAAK,GAAG,CAAC,CAClE,IAAI,CAAC,SAAS,KAAK,QAAQ,MAAM,OAAO,CAAC,IAAI,CAAE,EACnD;EACF;AAGD,MAAI,CAAC,QAAQ,KAAKC,gCAAU,CAC1B,QAAQ,MAAM,QAAQ,MAAM,GACxB,UACA,EAAE,UAAU,QAAS;EAI3B,MAAMC,kBAIA,CAAE;EACR,IAAIC,gBAAgC;AAEpC,OAAK,MAAM,UAAU,QACnB,0CAAc,OAAO,CACnB,KACE,OAAO,UAAUC,8BAAQ,UACzB,MAAM,QAAQ,OAAO,KAAK,IAC1B,OAAO,KAAK,MAAM,CAAC,SAAS,OAAO,KAAK,CAAC,CAEzC,KAAI,eACD,cAAc,KAAgB,KAAK,GAAI,OAAO,KAAgB;OAE/D,gBAAgB,IAAIA,8BAAQ;GAC1B,OAAOA,8BAAQ;GACf,MAAM,OAAO;EACd;OAGH,gBAAgB,KAAK,OAAO;OAG9B,gBAAgB,KACd,MAAM,QAAQ,MAAM,GAAG,CAAC,MAAO,IAAG,EAAE,UAAU,CAAC,MAAO,EAAE,EACzD;AAIL,MAAI,eACF,gBAAgB,KAAK,cAAc;AAGrC,SAAO;CACR;AACF;AAED,SAAgB,OAAOC,GAAuB;AAC5C,QAAO,aAAaC;AACrB"}
1
+ {"version":3,"file":"ToolNode.cjs","names":["input: unknown","isBaseMessage","RunnableCallable","tools: (StructuredToolInterface | DynamicTool | RunnableToolLike)[]","options?: ToolNodeOptions","call: ToolCall","config: RunnableConfig","tool","mergeAbortSignals","ToolMessage","e: unknown","ToolInputParsingException","ToolInvocationError","state: ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"]","outputs: (ToolMessage | Command)[]","messages: BaseMessage[]","toolMessageIds: Set<string>","aiMessage: AIMessage | undefined","AIMessage","isCommand","combinedOutputs: (\n | { messages: BaseMessage[] }\n | BaseMessage[]\n | Command\n )[]","parentCommand: Command | null","Command","x: unknown","Send"],"sources":["../../../src/agents/nodes/ToolNode.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable no-instanceof/no-instanceof */\nimport {\n BaseMessage,\n ToolMessage,\n AIMessage,\n isBaseMessage,\n isToolMessage,\n} from \"@langchain/core/messages\";\nimport { RunnableConfig, RunnableToolLike } from \"@langchain/core/runnables\";\nimport {\n DynamicTool,\n StructuredToolInterface,\n ToolInputParsingException,\n} from \"@langchain/core/tools\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\nimport type { InteropZodObject } from \"@langchain/core/utils/types\";\nimport {\n isCommand,\n Command,\n Send,\n isGraphInterrupt,\n} from \"@langchain/langgraph\";\n\nimport { RunnableCallable } from \"../RunnableCallable.js\";\nimport {\n PreHookAnnotation,\n AnyAnnotationRoot,\n ToAnnotationRoot,\n} from \"../annotation.js\";\nimport { mergeAbortSignals } from \"./utils.js\";\nimport { ToolInvocationError } from \"../errors.js\";\n\nexport interface ToolNodeOptions {\n /**\n * The name of the tool node.\n */\n name?: string;\n /**\n * The tags to add to the tool call.\n */\n tags?: string[];\n /**\n * The abort signal to cancel the tool call.\n */\n signal?: AbortSignal;\n /**\n * Whether to throw the error immediately if the tool fails or handle it by the `onToolError` function or via ToolMessage.\n *\n * If `true` (default):\n * - a tool message with the error will be returned to the LLM\n *\n * If `false`:\n * - the error will be thrown immediately\n *\n * If a function is provided:\n * - returns a custom {@link ToolMessage} as result\n * - throws an error otherwise\n *\n * @default true\n */\n handleToolErrors?:\n | boolean\n | ((error: unknown, toolCall: ToolCall) => ToolMessage | undefined);\n}\n\nconst isBaseMessageArray = (input: unknown): input is BaseMessage[] =>\n Array.isArray(input) && input.every(isBaseMessage);\n\nconst isMessagesState = (\n input: unknown\n): input is { messages: BaseMessage[] } =>\n typeof input === \"object\" &&\n input != null &&\n \"messages\" in input &&\n isBaseMessageArray(input.messages);\n\nconst isSendInput = (input: unknown): input is { lg_tool_call: ToolCall } =>\n typeof input === \"object\" && input != null && \"lg_tool_call\" in input;\n\n/**\n * `ToolNode` is a built-in LangGraph component that handles tool calls within an agent's workflow.\n * It works seamlessly with `createAgent`, offering advanced tool execution control, built\n * in parallelism, and error handling.\n *\n * @example\n * ```ts\n * import { ToolNode, tool, AIMessage } from \"langchain\";\n * import { z } from \"zod/v3\";\n *\n * const getWeather = tool((input) => {\n * if ([\"sf\", \"san francisco\"].includes(input.location.toLowerCase())) {\n * return \"It's 60 degrees and foggy.\";\n * } else {\n * return \"It's 90 degrees and sunny.\";\n * }\n * }, {\n * name: \"get_weather\",\n * description: \"Call to get the current weather.\",\n * schema: z.object({\n * location: z.string().describe(\"Location to get the weather for.\"),\n * }),\n * });\n *\n * const tools = [getWeather];\n * const toolNode = new ToolNode(tools);\n *\n * const messageWithSingleToolCall = new AIMessage({\n * content: \"\",\n * tool_calls: [\n * {\n * name: \"get_weather\",\n * args: { location: \"sf\" },\n * id: \"tool_call_id\",\n * type: \"tool_call\",\n * }\n * ]\n * })\n *\n * await toolNode.invoke({ messages: [messageWithSingleToolCall] });\n * // Returns tool invocation responses as:\n * // { messages: ToolMessage[] }\n * ```\n */\nexport class ToolNode<\n StateSchema extends AnyAnnotationRoot | InteropZodObject = any,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = any\n> extends RunnableCallable<StateSchema, ContextSchema> {\n tools: (StructuredToolInterface | DynamicTool | RunnableToolLike)[];\n\n trace = false;\n\n signal?: AbortSignal;\n\n handleToolErrors:\n | boolean\n | ((error: unknown, toolCall: ToolCall) => ToolMessage | undefined) = true;\n\n constructor(\n tools: (StructuredToolInterface | DynamicTool | RunnableToolLike)[],\n public options?: ToolNodeOptions\n ) {\n const { name, tags, handleToolErrors } = options ?? {};\n super({\n name,\n tags,\n func: (state, config) =>\n this.run(\n state as ToAnnotationRoot<StateSchema>[\"State\"] &\n PreHookAnnotation[\"State\"],\n config as RunnableConfig\n ),\n });\n this.tools = tools;\n this.handleToolErrors = handleToolErrors ?? this.handleToolErrors;\n this.signal = options?.signal;\n }\n\n protected async runTool(\n call: ToolCall,\n config: RunnableConfig\n ): Promise<ToolMessage | Command> {\n const tool = this.tools.find((tool) => tool.name === call.name);\n try {\n if (tool === undefined) {\n throw new Error(`Tool \"${call.name}\" not found.`);\n }\n\n const output = await tool.invoke(\n { ...call, type: \"tool_call\" },\n {\n ...config,\n signal: mergeAbortSignals(this.signal, config.signal),\n }\n );\n\n if (ToolMessage.isInstance(output) || isCommand(output)) {\n return output as ToolMessage | Command;\n }\n\n return new ToolMessage({\n name: tool.name,\n content: typeof output === \"string\" ? output : JSON.stringify(output),\n tool_call_id: call.id!,\n });\n } catch (e: unknown) {\n /**\n * If tool invocation fails due to input parsing error, throw a {@link ToolInvocationError}\n */\n if (e instanceof ToolInputParsingException) {\n throw new ToolInvocationError(e, call);\n }\n\n /**\n * throw the error if user prefers not to handle tool errors\n */\n if (!this.handleToolErrors) {\n throw e;\n }\n\n if (isGraphInterrupt(e)) {\n /**\n * {@link NodeInterrupt} errors are a breakpoint to bring a human into the loop.\n * As such, they are not recoverable by the agent and shouldn't be fed\n * back. Instead, re-throw these errors even when `handleToolErrors = true`.\n */\n throw e;\n }\n\n /**\n * If the signal is aborted, we want to bubble up the error to the invoke caller.\n */\n if (this.signal?.aborted) {\n throw e;\n }\n\n /**\n * if the user provides a function, call it with the error and tool call\n * and return the result if it is a {@link ToolMessage}\n */\n if (typeof this.handleToolErrors === \"function\") {\n const result = this.handleToolErrors(e, call);\n if (result && isToolMessage(result)) {\n return result;\n }\n } else if (this.handleToolErrors) {\n return new ToolMessage({\n name: call.name,\n content: `${e}\\n Please fix your mistakes.`,\n tool_call_id: call.id!,\n });\n }\n\n /**\n * If the user doesn't handle the error, throw it\n */\n throw e;\n }\n }\n\n protected async run(\n state: ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"],\n config: RunnableConfig\n ): Promise<ContextSchema> {\n let outputs: (ToolMessage | Command)[];\n\n if (isSendInput(state)) {\n outputs = [await this.runTool(state.lg_tool_call, config)];\n } else {\n let messages: BaseMessage[];\n if (isBaseMessageArray(state)) {\n messages = state;\n } else if (isMessagesState(state)) {\n messages = state.messages;\n } else {\n throw new Error(\n \"ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.\"\n );\n }\n\n const toolMessageIds: Set<string> = new Set(\n messages\n .filter((msg) => msg.getType() === \"tool\")\n .map((msg) => (msg as ToolMessage).tool_call_id)\n );\n\n let aiMessage: AIMessage | undefined;\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n const message = messages[i];\n if (AIMessage.isInstance(message)) {\n aiMessage = message;\n break;\n }\n }\n\n if (!AIMessage.isInstance(aiMessage)) {\n throw new Error(\"ToolNode only accepts AIMessages as input.\");\n }\n\n outputs = await Promise.all(\n aiMessage.tool_calls\n ?.filter((call) => call.id == null || !toolMessageIds.has(call.id))\n .map((call) => this.runTool(call, config)) ?? []\n );\n }\n\n // Preserve existing behavior for non-command tool outputs for backwards compatibility\n if (!outputs.some(isCommand)) {\n return (Array.isArray(state)\n ? outputs\n : { messages: outputs }) as unknown as ContextSchema;\n }\n\n // Handle mixed Command and non-Command outputs\n const combinedOutputs: (\n | { messages: BaseMessage[] }\n | BaseMessage[]\n | Command\n )[] = [];\n let parentCommand: Command | null = null;\n\n for (const output of outputs) {\n if (isCommand(output)) {\n if (\n output.graph === Command.PARENT &&\n Array.isArray(output.goto) &&\n output.goto.every((send) => isSend(send))\n ) {\n if (parentCommand) {\n (parentCommand.goto as Send[]).push(...(output.goto as Send[]));\n } else {\n parentCommand = new Command({\n graph: Command.PARENT,\n goto: output.goto,\n });\n }\n } else {\n combinedOutputs.push(output);\n }\n } else {\n combinedOutputs.push(\n Array.isArray(state) ? [output] : { messages: [output] }\n );\n }\n }\n\n if (parentCommand) {\n combinedOutputs.push(parentCommand);\n }\n\n return combinedOutputs as unknown as ContextSchema;\n }\n}\n\nexport function isSend(x: unknown): x is Send {\n return x instanceof Send;\n}\n"],"mappings":";;;;;;;;;AAkEA,MAAM,qBAAqB,CAACA,UAC1B,MAAM,QAAQ,MAAM,IAAI,MAAM,MAAMC,wCAAc;AAEpD,MAAM,kBAAkB,CACtBD,UAEA,OAAO,UAAU,YACjB,SAAS,QACT,cAAc,SACd,mBAAmB,MAAM,SAAS;AAEpC,MAAM,cAAc,CAACA,UACnB,OAAO,UAAU,YAAY,SAAS,QAAQ,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8ClE,IAAa,WAAb,cAGUE,0CAA6C;CACrD;CAEA,QAAQ;CAER;CAEA,mBAEwE;CAExE,YACEC,OACOC,SACP;EACA,MAAM,EAAE,MAAM,MAAM,kBAAkB,GAAG,WAAW,CAAE;EACtD,MAAM;GACJ;GACA;GACA,MAAM,CAAC,OAAO,WACZ,KAAK,IACH,OAEA,OACD;EACJ,EAAC;EAZK;EAaP,KAAK,QAAQ;EACb,KAAK,mBAAmB,oBAAoB,KAAK;EACjD,KAAK,SAAS,SAAS;CACxB;CAED,MAAgB,QACdC,MACAC,QACgC;EAChC,MAAM,OAAO,KAAK,MAAM,KAAK,CAACC,WAASA,OAAK,SAAS,KAAK,KAAK;AAC/D,MAAI;AACF,OAAI,SAAS,OACX,OAAM,IAAI,MAAM,CAAC,MAAM,EAAE,KAAK,KAAK,YAAY,CAAC;GAGlD,MAAM,SAAS,MAAM,KAAK,OACxB;IAAE,GAAG;IAAM,MAAM;GAAa,GAC9B;IACE,GAAG;IACH,QAAQC,gCAAkB,KAAK,QAAQ,OAAO,OAAO;GACtD,EACF;AAED,OAAIC,sCAAY,WAAW,OAAO,yCAAc,OAAO,CACrD,QAAO;AAGT,UAAO,IAAIA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AAC,SAAS,KAAK,MAAM,QAAQ,CAAC,eAAe,IAAI,KAAK,GAAG,CAAC,CAClE,IAAI,CAAC,SAAS,KAAK,QAAQ,MAAM,OAAO,CAAC,IAAI,CAAE,EACnD;EACF;AAGD,MAAI,CAAC,QAAQ,KAAKC,gCAAU,CAC1B,QAAQ,MAAM,QAAQ,MAAM,GACxB,UACA,EAAE,UAAU,QAAS;EAI3B,MAAMC,kBAIA,CAAE;EACR,IAAIC,gBAAgC;AAEpC,OAAK,MAAM,UAAU,QACnB,0CAAc,OAAO,CACnB,KACE,OAAO,UAAUC,8BAAQ,UACzB,MAAM,QAAQ,OAAO,KAAK,IAC1B,OAAO,KAAK,MAAM,CAAC,SAAS,OAAO,KAAK,CAAC,CAEzC,KAAI,eACD,cAAc,KAAgB,KAAK,GAAI,OAAO,KAAgB;OAE/D,gBAAgB,IAAIA,8BAAQ;GAC1B,OAAOA,8BAAQ;GACf,MAAM,OAAO;EACd;OAGH,gBAAgB,KAAK,OAAO;OAG9B,gBAAgB,KACd,MAAM,QAAQ,MAAM,GAAG,CAAC,MAAO,IAAG,EAAE,UAAU,CAAC,MAAO,EAAE,EACzD;AAIL,MAAI,eACF,gBAAgB,KAAK,cAAc;AAGrC,SAAO;CACR;AACF;AAED,SAAgB,OAAOC,GAAuB;AAC5C,QAAO,aAAaC;AACrB"}
@@ -3,8 +3,8 @@ import { RunnableCallable } from "../RunnableCallable.cjs";
3
3
  import { InteropZodObject } from "@langchain/core/utils/types";
4
4
  import { Command } from "@langchain/langgraph";
5
5
  import { ToolMessage } from "@langchain/core/messages";
6
- import { RunnableConfig, RunnableToolLike } from "@langchain/core/runnables";
7
6
  import { ToolCall } from "@langchain/core/messages/tool";
7
+ import { RunnableConfig, RunnableToolLike } from "@langchain/core/runnables";
8
8
  import { DynamicTool, StructuredToolInterface } from "@langchain/core/tools";
9
9
 
10
10
  //#region src/agents/nodes/ToolNode.d.ts
@@ -81,7 +81,7 @@ var ToolNode = class extends RunnableCallable {
81
81
  ...config,
82
82
  signal: mergeAbortSignals(this.signal, config.signal)
83
83
  });
84
- if (isBaseMessage(output) && output.getType() === "tool" || isCommand(output)) return output;
84
+ if (ToolMessage.isInstance(output) || isCommand(output)) return output;
85
85
  return new ToolMessage({
86
86
  name: tool.name,
87
87
  content: typeof output === "string" ? output : JSON.stringify(output),
@@ -1 +1 @@
1
- {"version":3,"file":"ToolNode.js","names":["input: unknown","tools: (StructuredToolInterface | DynamicTool | RunnableToolLike)[]","options?: ToolNodeOptions","call: ToolCall","config: RunnableConfig","tool","e: unknown","state: ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"]","outputs: (ToolMessage | Command)[]","messages: BaseMessage[]","toolMessageIds: Set<string>","aiMessage: AIMessage | undefined","combinedOutputs: (\n | { messages: BaseMessage[] }\n | BaseMessage[]\n | Command\n )[]","parentCommand: Command | null","x: unknown"],"sources":["../../../src/agents/nodes/ToolNode.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable no-instanceof/no-instanceof */\nimport {\n BaseMessage,\n ToolMessage,\n AIMessage,\n isBaseMessage,\n isToolMessage,\n} from \"@langchain/core/messages\";\nimport { RunnableConfig, RunnableToolLike } from \"@langchain/core/runnables\";\nimport {\n DynamicTool,\n StructuredToolInterface,\n ToolInputParsingException,\n} from \"@langchain/core/tools\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\nimport type { InteropZodObject } from \"@langchain/core/utils/types\";\nimport {\n isCommand,\n Command,\n Send,\n isGraphInterrupt,\n} from \"@langchain/langgraph\";\n\nimport { RunnableCallable } from \"../RunnableCallable.js\";\nimport {\n PreHookAnnotation,\n AnyAnnotationRoot,\n ToAnnotationRoot,\n} from \"../annotation.js\";\nimport { mergeAbortSignals } from \"./utils.js\";\nimport { ToolInvocationError } from \"../errors.js\";\n\nexport interface ToolNodeOptions {\n /**\n * The name of the tool node.\n */\n name?: string;\n /**\n * The tags to add to the tool call.\n */\n tags?: string[];\n /**\n * The abort signal to cancel the tool call.\n */\n signal?: AbortSignal;\n /**\n * Whether to throw the error immediately if the tool fails or handle it by the `onToolError` function or via ToolMessage.\n *\n * If `true` (default):\n * - a tool message with the error will be returned to the LLM\n *\n * If `false`:\n * - the error will be thrown immediately\n *\n * If a function is provided:\n * - returns a custom {@link ToolMessage} as result\n * - throws an error otherwise\n *\n * @default true\n */\n handleToolErrors?:\n | boolean\n | ((error: unknown, toolCall: ToolCall) => ToolMessage | undefined);\n}\n\nconst isBaseMessageArray = (input: unknown): input is BaseMessage[] =>\n Array.isArray(input) && input.every(isBaseMessage);\n\nconst isMessagesState = (\n input: unknown\n): input is { messages: BaseMessage[] } =>\n typeof input === \"object\" &&\n input != null &&\n \"messages\" in input &&\n isBaseMessageArray(input.messages);\n\nconst isSendInput = (input: unknown): input is { lg_tool_call: ToolCall } =>\n typeof input === \"object\" && input != null && \"lg_tool_call\" in input;\n\n/**\n * `ToolNode` is a built-in LangGraph component that handles tool calls within an agent's workflow.\n * It works seamlessly with `createAgent`, offering advanced tool execution control, built\n * in parallelism, and error handling.\n *\n * @example\n * ```ts\n * import { ToolNode, tool, AIMessage } from \"langchain\";\n * import { z } from \"zod/v3\";\n *\n * const getWeather = tool((input) => {\n * if ([\"sf\", \"san francisco\"].includes(input.location.toLowerCase())) {\n * return \"It's 60 degrees and foggy.\";\n * } else {\n * return \"It's 90 degrees and sunny.\";\n * }\n * }, {\n * name: \"get_weather\",\n * description: \"Call to get the current weather.\",\n * schema: z.object({\n * location: z.string().describe(\"Location to get the weather for.\"),\n * }),\n * });\n *\n * const tools = [getWeather];\n * const toolNode = new ToolNode(tools);\n *\n * const messageWithSingleToolCall = new AIMessage({\n * content: \"\",\n * tool_calls: [\n * {\n * name: \"get_weather\",\n * args: { location: \"sf\" },\n * id: \"tool_call_id\",\n * type: \"tool_call\",\n * }\n * ]\n * })\n *\n * await toolNode.invoke({ messages: [messageWithSingleToolCall] });\n * // Returns tool invocation responses as:\n * // { messages: ToolMessage[] }\n * ```\n */\nexport class ToolNode<\n StateSchema extends AnyAnnotationRoot | InteropZodObject = any,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = any\n> extends RunnableCallable<StateSchema, ContextSchema> {\n tools: (StructuredToolInterface | DynamicTool | RunnableToolLike)[];\n\n trace = false;\n\n signal?: AbortSignal;\n\n handleToolErrors:\n | boolean\n | ((error: unknown, toolCall: ToolCall) => ToolMessage | undefined) = true;\n\n constructor(\n tools: (StructuredToolInterface | DynamicTool | RunnableToolLike)[],\n public options?: ToolNodeOptions\n ) {\n const { name, tags, handleToolErrors } = options ?? {};\n super({\n name,\n tags,\n func: (state, config) =>\n this.run(\n state as ToAnnotationRoot<StateSchema>[\"State\"] &\n PreHookAnnotation[\"State\"],\n config as RunnableConfig\n ),\n });\n this.tools = tools;\n this.handleToolErrors = handleToolErrors ?? this.handleToolErrors;\n this.signal = options?.signal;\n }\n\n protected async runTool(\n call: ToolCall,\n config: RunnableConfig\n ): Promise<ToolMessage | Command> {\n const tool = this.tools.find((tool) => tool.name === call.name);\n try {\n if (tool === undefined) {\n throw new Error(`Tool \"${call.name}\" not found.`);\n }\n\n const output = await tool.invoke(\n { ...call, type: \"tool_call\" },\n {\n ...config,\n signal: mergeAbortSignals(this.signal, config.signal),\n }\n );\n\n if (\n (isBaseMessage(output) && output.getType() === \"tool\") ||\n isCommand(output)\n ) {\n return output as ToolMessage | Command;\n }\n\n return new ToolMessage({\n name: tool.name,\n content: typeof output === \"string\" ? output : JSON.stringify(output),\n tool_call_id: call.id!,\n });\n } catch (e: unknown) {\n /**\n * If tool invocation fails due to input parsing error, throw a {@link ToolInvocationError}\n */\n if (e instanceof ToolInputParsingException) {\n throw new ToolInvocationError(e, call);\n }\n\n /**\n * throw the error if user prefers not to handle tool errors\n */\n if (!this.handleToolErrors) {\n throw e;\n }\n\n if (isGraphInterrupt(e)) {\n /**\n * {@link NodeInterrupt} errors are a breakpoint to bring a human into the loop.\n * As such, they are not recoverable by the agent and shouldn't be fed\n * back. Instead, re-throw these errors even when `handleToolErrors = true`.\n */\n throw e;\n }\n\n /**\n * If the signal is aborted, we want to bubble up the error to the invoke caller.\n */\n if (this.signal?.aborted) {\n throw e;\n }\n\n /**\n * if the user provides a function, call it with the error and tool call\n * and return the result if it is a {@link ToolMessage}\n */\n if (typeof this.handleToolErrors === \"function\") {\n const result = this.handleToolErrors(e, call);\n if (result && isToolMessage(result)) {\n return result;\n }\n } else if (this.handleToolErrors) {\n return new ToolMessage({\n name: call.name,\n content: `${e}\\n Please fix your mistakes.`,\n tool_call_id: call.id!,\n });\n }\n\n /**\n * If the user doesn't handle the error, throw it\n */\n throw e;\n }\n }\n\n protected async run(\n state: ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"],\n config: RunnableConfig\n ): Promise<ContextSchema> {\n let outputs: (ToolMessage | Command)[];\n\n if (isSendInput(state)) {\n outputs = [await this.runTool(state.lg_tool_call, config)];\n } else {\n let messages: BaseMessage[];\n if (isBaseMessageArray(state)) {\n messages = state;\n } else if (isMessagesState(state)) {\n messages = state.messages;\n } else {\n throw new Error(\n \"ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.\"\n );\n }\n\n const toolMessageIds: Set<string> = new Set(\n messages\n .filter((msg) => msg.getType() === \"tool\")\n .map((msg) => (msg as ToolMessage).tool_call_id)\n );\n\n let aiMessage: AIMessage | undefined;\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n const message = messages[i];\n if (AIMessage.isInstance(message)) {\n aiMessage = message;\n break;\n }\n }\n\n if (!AIMessage.isInstance(aiMessage)) {\n throw new Error(\"ToolNode only accepts AIMessages as input.\");\n }\n\n outputs = await Promise.all(\n aiMessage.tool_calls\n ?.filter((call) => call.id == null || !toolMessageIds.has(call.id))\n .map((call) => this.runTool(call, config)) ?? []\n );\n }\n\n // Preserve existing behavior for non-command tool outputs for backwards compatibility\n if (!outputs.some(isCommand)) {\n return (Array.isArray(state)\n ? outputs\n : { messages: outputs }) as unknown as ContextSchema;\n }\n\n // Handle mixed Command and non-Command outputs\n const combinedOutputs: (\n | { messages: BaseMessage[] }\n | BaseMessage[]\n | Command\n )[] = [];\n let parentCommand: Command | null = null;\n\n for (const output of outputs) {\n if (isCommand(output)) {\n if (\n output.graph === Command.PARENT &&\n Array.isArray(output.goto) &&\n output.goto.every((send) => isSend(send))\n ) {\n if (parentCommand) {\n (parentCommand.goto as Send[]).push(...(output.goto as Send[]));\n } else {\n parentCommand = new Command({\n graph: Command.PARENT,\n goto: output.goto,\n });\n }\n } else {\n combinedOutputs.push(output);\n }\n } else {\n combinedOutputs.push(\n Array.isArray(state) ? [output] : { messages: [output] }\n );\n }\n }\n\n if (parentCommand) {\n combinedOutputs.push(parentCommand);\n }\n\n return combinedOutputs as unknown as ContextSchema;\n }\n}\n\nexport function isSend(x: unknown): x is Send {\n return x instanceof Send;\n}\n"],"mappings":";;;;;;;;AAkEA,MAAM,qBAAqB,CAACA,UAC1B,MAAM,QAAQ,MAAM,IAAI,MAAM,MAAM,cAAc;AAEpD,MAAM,kBAAkB,CACtBA,UAEA,OAAO,UAAU,YACjB,SAAS,QACT,cAAc,SACd,mBAAmB,MAAM,SAAS;AAEpC,MAAM,cAAc,CAACA,UACnB,OAAO,UAAU,YAAY,SAAS,QAAQ,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8ClE,IAAa,WAAb,cAGU,iBAA6C;CACrD;CAEA,QAAQ;CAER;CAEA,mBAEwE;CAExE,YACEC,OACOC,SACP;EACA,MAAM,EAAE,MAAM,MAAM,kBAAkB,GAAG,WAAW,CAAE;EACtD,MAAM;GACJ;GACA;GACA,MAAM,CAAC,OAAO,WACZ,KAAK,IACH,OAEA,OACD;EACJ,EAAC;EAZK;EAaP,KAAK,QAAQ;EACb,KAAK,mBAAmB,oBAAoB,KAAK;EACjD,KAAK,SAAS,SAAS;CACxB;CAED,MAAgB,QACdC,MACAC,QACgC;EAChC,MAAM,OAAO,KAA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","names":["input: unknown","tools: (StructuredToolInterface | DynamicTool | RunnableToolLike)[]","options?: ToolNodeOptions","call: ToolCall","config: RunnableConfig","tool","e: unknown","state: ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"]","outputs: (ToolMessage | Command)[]","messages: BaseMessage[]","toolMessageIds: Set<string>","aiMessage: AIMessage | undefined","combinedOutputs: (\n | { messages: BaseMessage[] }\n | BaseMessage[]\n | Command\n )[]","parentCommand: Command | null","x: unknown"],"sources":["../../../src/agents/nodes/ToolNode.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable no-instanceof/no-instanceof */\nimport {\n BaseMessage,\n ToolMessage,\n AIMessage,\n isBaseMessage,\n isToolMessage,\n} from \"@langchain/core/messages\";\nimport { RunnableConfig, RunnableToolLike } from \"@langchain/core/runnables\";\nimport {\n DynamicTool,\n StructuredToolInterface,\n ToolInputParsingException,\n} from \"@langchain/core/tools\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\nimport type { InteropZodObject } from \"@langchain/core/utils/types\";\nimport {\n isCommand,\n Command,\n Send,\n isGraphInterrupt,\n} from \"@langchain/langgraph\";\n\nimport { RunnableCallable } from \"../RunnableCallable.js\";\nimport {\n PreHookAnnotation,\n AnyAnnotationRoot,\n ToAnnotationRoot,\n} from \"../annotation.js\";\nimport { mergeAbortSignals } from \"./utils.js\";\nimport { ToolInvocationError } from \"../errors.js\";\n\nexport interface ToolNodeOptions {\n /**\n * The name of the tool node.\n */\n name?: string;\n /**\n * The tags to add to the tool call.\n */\n tags?: string[];\n /**\n * The abort signal to cancel the tool call.\n */\n signal?: AbortSignal;\n /**\n * Whether to throw the error immediately if the tool fails or handle it by the `onToolError` function or via ToolMessage.\n *\n * If `true` (default):\n * - a tool message with the error will be returned to the LLM\n *\n * If `false`:\n * - the error will be thrown immediately\n *\n * If a function is provided:\n * - returns a custom {@link ToolMessage} as result\n * - throws an error otherwise\n *\n * @default true\n */\n handleToolErrors?:\n | boolean\n | ((error: unknown, toolCall: ToolCall) => ToolMessage | undefined);\n}\n\nconst isBaseMessageArray = (input: unknown): input is BaseMessage[] =>\n Array.isArray(input) && input.every(isBaseMessage);\n\nconst isMessagesState = (\n input: unknown\n): input is { messages: BaseMessage[] } =>\n typeof input === \"object\" &&\n input != null &&\n \"messages\" in input &&\n isBaseMessageArray(input.messages);\n\nconst isSendInput = (input: unknown): input is { lg_tool_call: ToolCall } =>\n typeof input === \"object\" && input != null && \"lg_tool_call\" in input;\n\n/**\n * `ToolNode` is a built-in LangGraph component that handles tool calls within an agent's workflow.\n * It works seamlessly with `createAgent`, offering advanced tool execution control, built\n * in parallelism, and error handling.\n *\n * @example\n * ```ts\n * import { ToolNode, tool, AIMessage } from \"langchain\";\n * import { z } from \"zod/v3\";\n *\n * const getWeather = tool((input) => {\n * if ([\"sf\", \"san francisco\"].includes(input.location.toLowerCase())) {\n * return \"It's 60 degrees and foggy.\";\n * } else {\n * return \"It's 90 degrees and sunny.\";\n * }\n * }, {\n * name: \"get_weather\",\n * description: \"Call to get the current weather.\",\n * schema: z.object({\n * location: z.string().describe(\"Location to get the weather for.\"),\n * }),\n * });\n *\n * const tools = [getWeather];\n * const toolNode = new ToolNode(tools);\n *\n * const messageWithSingleToolCall = new AIMessage({\n * content: \"\",\n * tool_calls: [\n * {\n * name: \"get_weather\",\n * args: { location: \"sf\" },\n * id: \"tool_call_id\",\n * type: \"tool_call\",\n * }\n * ]\n * })\n *\n * await toolNode.invoke({ messages: [messageWithSingleToolCall] });\n * // Returns tool invocation responses as:\n * // { messages: ToolMessage[] }\n * ```\n */\nexport class ToolNode<\n StateSchema extends AnyAnnotationRoot | InteropZodObject = any,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = any\n> extends RunnableCallable<StateSchema, ContextSchema> {\n tools: (StructuredToolInterface | DynamicTool | RunnableToolLike)[];\n\n trace = false;\n\n signal?: AbortSignal;\n\n handleToolErrors:\n | boolean\n | ((error: unknown, toolCall: ToolCall) => ToolMessage | undefined) = true;\n\n constructor(\n tools: (StructuredToolInterface | DynamicTool | RunnableToolLike)[],\n public options?: ToolNodeOptions\n ) {\n const { name, tags, handleToolErrors } = options ?? {};\n super({\n name,\n tags,\n func: (state, config) =>\n this.run(\n state as ToAnnotationRoot<StateSchema>[\"State\"] &\n PreHookAnnotation[\"State\"],\n config as RunnableConfig\n ),\n });\n this.tools = tools;\n this.handleToolErrors = handleToolErrors ?? this.handleToolErrors;\n this.signal = options?.signal;\n }\n\n protected async runTool(\n call: ToolCall,\n config: RunnableConfig\n ): Promise<ToolMessage | Command> {\n const tool = this.tools.find((tool) => tool.name === call.name);\n try {\n if (tool === undefined) {\n throw new Error(`Tool \"${call.name}\" not found.`);\n }\n\n const output = await tool.invoke(\n { ...call, type: \"tool_call\" },\n {\n ...config,\n signal: mergeAbortSignals(this.signal, config.signal),\n }\n );\n\n if (ToolMessage.isInstance(output) || isCommand(output)) {\n return output as ToolMessage | Command;\n }\n\n return new ToolMessage({\n name: tool.name,\n content: typeof output === \"string\" ? output : JSON.stringify(output),\n tool_call_id: call.id!,\n });\n } catch (e: unknown) {\n /**\n * If tool invocation fails due to input parsing error, throw a {@link ToolInvocationError}\n */\n if (e instanceof ToolInputParsingException) {\n throw new ToolInvocationError(e, call);\n }\n\n /**\n * throw the error if user prefers not to handle tool errors\n */\n if (!this.handleToolErrors) {\n throw e;\n }\n\n if (isGraphInterrupt(e)) {\n /**\n * {@link NodeInterrupt} errors are a breakpoint to bring a human into the loop.\n * As such, they are not recoverable by the agent and shouldn't be fed\n * back. Instead, re-throw these errors even when `handleToolErrors = true`.\n */\n throw e;\n }\n\n /**\n * If the signal is aborted, we want to bubble up the error to the invoke caller.\n */\n if (this.signal?.aborted) {\n throw e;\n }\n\n /**\n * if the user provides a function, call it with the error and tool call\n * and return the result if it is a {@link ToolMessage}\n */\n if (typeof this.handleToolErrors === \"function\") {\n const result = this.handleToolErrors(e, call);\n if (result && isToolMessage(result)) {\n return result;\n }\n } else if (this.handleToolErrors) {\n return new ToolMessage({\n name: call.name,\n content: `${e}\\n Please fix your mistakes.`,\n tool_call_id: call.id!,\n });\n }\n\n /**\n * If the user doesn't handle the error, throw it\n */\n throw e;\n }\n }\n\n protected async run(\n state: ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"],\n config: RunnableConfig\n ): Promise<ContextSchema> {\n let outputs: (ToolMessage | Command)[];\n\n if (isSendInput(state)) {\n outputs = [await this.runTool(state.lg_tool_call, config)];\n } else {\n let messages: BaseMessage[];\n if (isBaseMessageArray(state)) {\n messages = state;\n } else if (isMessagesState(state)) {\n messages = state.messages;\n } else {\n throw new Error(\n \"ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.\"\n );\n }\n\n const toolMessageIds: Set<string> = new Set(\n messages\n .filter((msg) => msg.getType() === \"tool\")\n .map((msg) => (msg as ToolMessage).tool_call_id)\n );\n\n let aiMessage: AIMessage | undefined;\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n const message = messages[i];\n if (AIMessage.isInstance(message)) {\n aiMessage = message;\n break;\n }\n }\n\n if (!AIMessage.isInstance(aiMessage)) {\n throw new Error(\"ToolNode only accepts AIMessages as input.\");\n }\n\n outputs = await Promise.all(\n aiMessage.tool_calls\n ?.filter((call) => call.id == null || !toolMessageIds.has(call.id))\n .map((call) => this.runTool(call, config)) ?? []\n );\n }\n\n // Preserve existing behavior for non-command tool outputs for backwards compatibility\n if (!outputs.some(isCommand)) {\n return (Array.isArray(state)\n ? outputs\n : { messages: outputs }) as unknown as ContextSchema;\n }\n\n // Handle mixed Command and non-Command outputs\n const combinedOutputs: (\n | { messages: BaseMessage[] }\n | BaseMessage[]\n | Command\n )[] = [];\n let parentCommand: Command | null = null;\n\n for (const output of outputs) {\n if (isCommand(output)) {\n if (\n output.graph === Command.PARENT &&\n Array.isArray(output.goto) &&\n output.goto.every((send) => isSend(send))\n ) {\n if (parentCommand) {\n (parentCommand.goto as Send[]).push(...(output.goto as Send[]));\n } else {\n parentCommand = new Command({\n graph: Command.PARENT,\n goto: output.goto,\n });\n }\n } else {\n combinedOutputs.push(output);\n }\n } else {\n combinedOutputs.push(\n Array.isArray(state) ? [output] : { messages: [output] }\n );\n }\n }\n\n if (parentCommand) {\n combinedOutputs.push(parentCommand);\n }\n\n return combinedOutputs as unknown as ContextSchema;\n }\n}\n\nexport function isSend(x: unknown): x is Send {\n return x instanceof Send;\n}\n"],"mappings":";;;;;;;;AAkEA,MAAM,qBAAqB,CAACA,UAC1B,MAAM,QAAQ,MAAM,IAAI,MAAM,MAAM,cAAc;AAEpD,MAAM,kBAAkB,CACtBA,UAEA,OAAO,UAAU,YACjB,SAAS,QACT,cAAc,SACd,mBAAmB,MAAM,SAAS;AAEpC,MAAM,cAAc,CAACA,UACnB,OAAO,UAAU,YAAY,SAAS,QAAQ,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8ClE,IAAa,WAAb,cAGU,iBAA6C;CACrD;CAEA,QAAQ;CAER;CAEA,mBAEwE;CAExE,YACEC,OACOC,SACP;EACA,MAAM,EAAE,MAAM,MAAM,kBAAkB,GAAG,WAAW,CAAE;EACtD,MAAM;GACJ;GACA;GACA,MAAM,CAAC,OAAO,WACZ,KAAK,IACH,OAEA,OACD;EACJ,EAAC;EAZK;EAaP,KAAK,QAAQ;EACb,KAAK,mBAAmB,oBAAoB,KAAK;EACjD,KAAK,SAAS,SAAS;CACxB;CAED,MAAgB,QACdC,MACAC,QACgC;EAChC,MAAM,OAAO,KAAK,MAAM,KAAK,CAACC,WAASA,OAAK,SAAS,KAAK,KAAK;AAC/D,MAAI;AACF,OAAI,SAAS,OACX,OAAM,IAAI,MAAM,CAAC,MAAM,EAAE,KAAK,KAAK,YAAY,CAAC;GAGlD,MAAM,SAAS,MAAM,KAAK,OACxB;IAAE,GAAG;IAAM,MAAM;GAAa,GAC9B;IACE,GAAG;IACH,QAAQ,kBAAkB,KAAK,QAAQ,OAAO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AAU,WAAW,UAAU,CAClC,OAAM,IAAI,MAAM;GAGlB,UAAU,MAAM,QAAQ,IACtB,UAAU,YACN,OAAO,CAAC,SAAS,KAAK,MAAM,QAAQ,CAAC,eAAe,IAAI,KAAK,GAAG,CAAC,CAClE,IAAI,CAAC,SAAS,KAAK,QAAQ,MAAM,OAAO,CAAC,IAAI,CAAE,EACnD;EACF;AAGD,MAAI,CAAC,QAAQ,KAAK,UAAU,CAC1B,QAAQ,MAAM,QAAQ,MAAM,GACxB,UACA,EAAE,UAAU,QAAS;EAI3B,MAAMC,kBAIA,CAAE;EACR,IAAIC,gBAAgC;AAEpC,OAAK,MAAM,UAAU,QACnB,KAAI,UAAU,OAAO,CACnB,KACE,OAAO,UAAU,QAAQ,UACzB,MAAM,QAAQ,OAAO,KAAK,IAC1B,OAAO,KAAK,MAAM,CAAC,SAAS,OAAO,KAAK,CAAC,CAEzC,KAAI,eACD,cAAc,KAAgB,KAAK,GAAI,OAAO,KAAgB;OAE/D,gBAAgB,IAAI,QAAQ;GAC1B,OAAO,QAAQ;GACf,MAAM,OAAO;EACd;OAGH,gBAAgB,KAAK,OAAO;OAG9B,gBAAgB,KACd,MAAM,QAAQ,MAAM,GAAG,CAAC,MAAO,IAAG,EAAE,UAAU,CAAC,MAAO,EAAE,EACzD;AAIL,MAAI,eACF,gBAAgB,KAAK,cAAc;AAGrC,SAAO;CACR;AACF;AAED,SAAgB,OAAOC,GAAuB;AAC5C,QAAO,aAAa;AACrB"}
@@ -1,5 +1,6 @@
1
1
  const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
2
2
  const require_errors = require('./errors.cjs');
3
+ const require_model = require('./model.cjs');
3
4
  const __langchain_core_utils_types = require_rolldown_runtime.__toESM(require("@langchain/core/utils/types"));
4
5
  const __langchain_core_utils_json_schema = require_rolldown_runtime.__toESM(require("@langchain/core/utils/json_schema"));
5
6
 
@@ -23,13 +24,13 @@ var ToolStrategy = class ToolStrategy {
23
24
  get name() {
24
25
  return this.tool.function.name;
25
26
  }
26
- static fromSchema(schema, options, outputOptions) {
27
+ static fromSchema(schema, outputOptions) {
27
28
  /**
28
29
  * It is required for tools to have a name so we can map the tool call to the correct tool
29
30
  * when parsing the response.
30
31
  */
31
32
  function getFunctionName(name) {
32
- return name ?? options?.name ?? `extract-${++bindingIdentifier}`;
33
+ return name ?? `extract-${++bindingIdentifier}`;
33
34
  }
34
35
  if ((0, __langchain_core_utils_types.isInteropZodSchema)(schema)) {
35
36
  const asJsonSchema$1 = (0, __langchain_core_utils_json_schema.toJsonSchema)(schema);
@@ -37,8 +38,8 @@ var ToolStrategy = class ToolStrategy {
37
38
  type: "function",
38
39
  function: {
39
40
  name: getFunctionName(),
40
- strict: options?.strict,
41
- description: options?.description ?? asJsonSchema$1.description ?? "Tool for extracting structured output from the model's response.",
41
+ strict: false,
42
+ description: asJsonSchema$1.description ?? "Tool for extracting structured output from the model's response.",
42
43
  parameters: asJsonSchema$1
43
44
  }
44
45
  };
@@ -109,10 +110,12 @@ var ProviderStrategy = class ProviderStrategy {
109
110
  * - if value is a JSON schema, default to structured output via tool calling
110
111
  * - if value is a custom response format, return it as is
111
112
  * - if value is an array, ensure all array elements are instance of `ToolStrategy`
112
- * @param responseFormat
113
+ * @param responseFormat - The response format to transform, provided by the user
114
+ * @param options - The response format options for tool strategy
115
+ * @param model - The model to check if it supports JSON schema output
113
116
  * @returns
114
117
  */
115
- function transformResponseFormat(responseFormat, options) {
118
+ function transformResponseFormat(responseFormat, options, model) {
116
119
  if (!responseFormat) return [];
117
120
  if (typeof responseFormat === "object" && responseFormat !== null && "__responseFormatUndefined" in responseFormat) return [];
118
121
  /**
@@ -127,19 +130,23 @@ function transformResponseFormat(responseFormat, options) {
127
130
  /**
128
131
  * Check if all items are Zod schemas
129
132
  */
130
- if (responseFormat.every((item) => (0, __langchain_core_utils_types.isInteropZodObject)(item))) return responseFormat.map((item) => ToolStrategy.fromSchema(item, void 0, options));
133
+ if (responseFormat.every((item) => (0, __langchain_core_utils_types.isInteropZodObject)(item))) return responseFormat.map((item) => ToolStrategy.fromSchema(item, options));
131
134
  /**
132
135
  * Check if all items are plain objects (JSON schema)
133
136
  */
134
- if (responseFormat.every((item) => typeof item === "object" && item !== null && !(0, __langchain_core_utils_types.isInteropZodObject)(item))) return responseFormat.map((item) => ToolStrategy.fromSchema(item, void 0, options));
137
+ if (responseFormat.every((item) => typeof item === "object" && item !== null && !(0, __langchain_core_utils_types.isInteropZodObject)(item))) return responseFormat.map((item) => ToolStrategy.fromSchema(item, options));
135
138
  throw new Error("Invalid response format: list contains mixed types.\nAll items must be either InteropZodObject or plain JSON schema objects.");
136
139
  }
137
- if ((0, __langchain_core_utils_types.isInteropZodObject)(responseFormat)) return [ToolStrategy.fromSchema(responseFormat, void 0, options)];
138
140
  if (responseFormat instanceof ToolStrategy || responseFormat instanceof ProviderStrategy) return [responseFormat];
141
+ const useProviderStrategy = hasSupportForJsonSchemaOutput(model);
142
+ /**
143
+ * `responseFormat` is a Zod schema
144
+ */
145
+ if ((0, __langchain_core_utils_types.isInteropZodObject)(responseFormat)) return useProviderStrategy ? [ProviderStrategy.fromSchema(responseFormat)] : [ToolStrategy.fromSchema(responseFormat, options)];
139
146
  /**
140
147
  * Handle plain object (JSON schema)
141
148
  */
142
- if (typeof responseFormat === "object" && responseFormat !== null && "properties" in responseFormat) return [ToolStrategy.fromSchema(responseFormat, void 0, options)];
149
+ if (typeof responseFormat === "object" && responseFormat !== null && "properties" in responseFormat) return useProviderStrategy ? [ProviderStrategy.fromSchema(responseFormat)] : [ToolStrategy.fromSchema(responseFormat, options)];
143
150
  throw new Error(`Invalid response format: ${String(responseFormat)}`);
144
151
  }
145
152
  /**
@@ -156,10 +163,45 @@ function toolStrategy(responseFormat, options) {
156
163
  function providerStrategy(responseFormat) {
157
164
  return ProviderStrategy.fromSchema(responseFormat);
158
165
  }
166
+ const CHAT_MODELS_THAT_SUPPORT_JSON_SCHEMA_OUTPUT = ["ChatOpenAI", "ChatXAI"];
167
+ const MODEL_NAMES_THAT_SUPPORT_JSON_SCHEMA_OUTPUT = [
168
+ "grok",
169
+ "gpt-5",
170
+ "gpt-4.1",
171
+ "gpt-4o",
172
+ "gpt-oss",
173
+ "o3-pro",
174
+ "o3-mini"
175
+ ];
176
+ /**
177
+ * Identifies the models that support JSON schema output
178
+ * @param model - The model to check
179
+ * @returns True if the model supports JSON schema output, false otherwise
180
+ */
181
+ function hasSupportForJsonSchemaOutput(model) {
182
+ if (!model) return false;
183
+ if (typeof model === "string") {
184
+ const modelName = model.split(":").pop();
185
+ return MODEL_NAMES_THAT_SUPPORT_JSON_SCHEMA_OUTPUT.some((modelNameSnippet) => modelName.includes(modelNameSnippet));
186
+ }
187
+ if (require_model.isConfigurableModel(model)) {
188
+ const configurableModel = model;
189
+ return hasSupportForJsonSchemaOutput(configurableModel._defaultConfig.model);
190
+ }
191
+ if (!require_model.isBaseChatModel(model)) return false;
192
+ const chatModelClass = model.getName();
193
+ /**
194
+ * for testing purposes only
195
+ */
196
+ if (chatModelClass === "FakeToolCallingChatModel") return true;
197
+ if (CHAT_MODELS_THAT_SUPPORT_JSON_SCHEMA_OUTPUT.includes(chatModelClass) && ("model" in model && MODEL_NAMES_THAT_SUPPORT_JSON_SCHEMA_OUTPUT.some((modelNameSnippet) => typeof model.model === "string" && model.model.includes(modelNameSnippet)) || chatModelClass === "FakeToolCallingModel" && "structuredResponse" in model)) return true;
198
+ return false;
199
+ }
159
200
 
160
201
  //#endregion
161
202
  exports.ProviderStrategy = ProviderStrategy;
162
203
  exports.ToolStrategy = ToolStrategy;
204
+ exports.hasSupportForJsonSchemaOutput = hasSupportForJsonSchemaOutput;
163
205
  exports.providerStrategy = providerStrategy;
164
206
  exports.toolStrategy = toolStrategy;
165
207
  exports.transformResponseFormat = transformResponseFormat;
@@ -1 +1 @@
1
- {"version":3,"file":"responses.cjs","names":["schema: Record<string, unknown>","tool: {\n type: \"function\";\n function: FunctionDefinition;\n }","options?: ToolStrategyOptions","schema: InteropZodObject | Record<string, unknown>","options?: {\n name?: string;\n description?: string;\n strict?: boolean;\n }","outputOptions?: ToolStrategyOptions","name?: string","asJsonSchema","tool","functionDefinition: FunctionDefinition","toolArgs: Record<string, unknown>","Validator","StructuredOutputParsingError","schema: InteropZodType<T> | Record<string, unknown>","response: AIMessage","responseFormat?:\n | InteropZodType<any>\n | InteropZodType<any>[]\n | JsonSchemaFormat\n | JsonSchemaFormat[]\n | ResponseFormat\n | ToolStrategy<any>[]\n | ResponseFormatUndefined","responseFormat:\n | InteropZodType<any>\n | InteropZodType<any>[]\n | JsonSchemaFormat\n | JsonSchemaFormat[]","responseFormat: InteropZodType<any> | JsonSchemaFormat"],"sources":["../../src/agents/responses.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable no-instanceof/no-instanceof */\nimport {\n InteropZodObject,\n isInteropZodSchema,\n InteropZodType,\n isInteropZodObject,\n} from \"@langchain/core/utils/types\";\nimport { type AIMessage } from \"@langchain/core/messages\";\nimport { toJsonSchema, Validator } from \"@langchain/core/utils/json_schema\";\nimport { type FunctionDefinition } from \"@langchain/core/language_models/base\";\n\nimport {\n StructuredOutputParsingError,\n MultipleStructuredOutputsError,\n} from \"./errors.js\";\n\n/**\n * This is a global counter for generating unique names for tools.\n */\nlet bindingIdentifier = 0;\n\n/**\n * Information for tracking structured output tool metadata.\n * This contains all necessary information to handle structured responses generated\n * via tool calls, including the original schema, its type classification, and the\n * corresponding tool implementation used by the tools strategy.\n */\nexport class ToolStrategy<_T = unknown> {\n private constructor(\n /**\n * The original JSON Schema provided for structured output\n */\n public readonly schema: Record<string, unknown>,\n\n /**\n * The tool that will be used to parse the tool call arguments.\n */\n public readonly tool: {\n type: \"function\";\n function: FunctionDefinition;\n },\n\n /**\n * The options to use for the tool output.\n */\n public readonly options?: ToolStrategyOptions\n ) {}\n\n get name() {\n return this.tool.function.name;\n }\n\n static fromSchema<S extends InteropZodObject>(\n schema: S,\n options?: {\n name?: string;\n description?: string;\n strict?: boolean;\n },\n outputOptions?: ToolStrategyOptions\n ): ToolStrategy<S extends InteropZodType<infer U> ? U : unknown>;\n\n static fromSchema(\n schema: Record<string, unknown>,\n options?: {\n name?: string;\n description?: string;\n strict?: boolean;\n },\n outputOptions?: ToolStrategyOptions\n ): ToolStrategy<Record<string, unknown>>;\n\n static fromSchema(\n schema: InteropZodObject | Record<string, unknown>,\n options?: {\n name?: string;\n description?: string;\n strict?: boolean;\n },\n outputOptions?: ToolStrategyOptions\n ): ToolStrategy<any> {\n /**\n * It is required for tools to have a name so we can map the tool call to the correct tool\n * when parsing the response.\n */\n function getFunctionName(name?: string) {\n return name ?? options?.name ?? `extract-${++bindingIdentifier}`;\n }\n\n if (isInteropZodSchema(schema)) {\n const asJsonSchema = toJsonSchema(schema);\n const tool = {\n type: \"function\" as const,\n function: {\n name: getFunctionName(),\n strict: options?.strict,\n description:\n options?.description ??\n asJsonSchema.description ??\n \"Tool for extracting structured output from the model's response.\",\n parameters: asJsonSchema,\n },\n };\n return new ToolStrategy(asJsonSchema, tool, outputOptions);\n }\n\n let functionDefinition: FunctionDefinition;\n if (\n typeof schema.name === \"string\" &&\n typeof schema.parameters === \"object\" &&\n schema.parameters != null\n ) {\n functionDefinition = schema as unknown as FunctionDefinition;\n } else {\n functionDefinition = {\n name: getFunctionName(schema.title as string),\n description: (schema.description as string) ?? \"\",\n parameters: schema.schema || (schema as Record<string, unknown>),\n };\n }\n const asJsonSchema = toJsonSchema(schema);\n const tool = {\n type: \"function\" as const,\n function: functionDefinition,\n };\n return new ToolStrategy(asJsonSchema, tool, outputOptions);\n }\n\n /**\n * Parse tool arguments according to the schema.\n *\n * @throws {StructuredOutputParsingError} if the response is not valid\n * @param toolArgs - The arguments from the tool call\n * @returns The parsed response according to the schema type\n */\n parse(toolArgs: Record<string, unknown>): Record<string, unknown> {\n const validator = new Validator(this.schema);\n const result = validator.validate(toolArgs);\n if (!result.valid) {\n throw new StructuredOutputParsingError(\n this.name,\n result.errors.map((e) => e.error)\n );\n }\n return toolArgs;\n }\n}\n\nexport class ProviderStrategy<T = unknown> {\n // @ts-expect-error - _schemaType is used only for type inference\n private _schemaType?: T;\n\n private constructor(public readonly schema: Record<string, unknown>) {}\n\n static fromSchema<T>(schema: InteropZodType<T>): ProviderStrategy<T>;\n\n static fromSchema(\n schema: Record<string, unknown>\n ): ProviderStrategy<Record<string, unknown>>;\n\n static fromSchema<T = unknown>(\n schema: InteropZodType<T> | Record<string, unknown>\n ): ProviderStrategy<T> | ProviderStrategy<Record<string, unknown>> {\n const asJsonSchema = toJsonSchema(schema);\n return new ProviderStrategy(asJsonSchema) as\n | ProviderStrategy<T>\n | ProviderStrategy<Record<string, unknown>>;\n }\n\n /**\n * Parse tool arguments according to the schema. If the response is not valid, return undefined.\n *\n * @param toolArgs - The arguments from the tool call\n * @returns The parsed response according to the schema type\n */\n parse(response: AIMessage) {\n /**\n * return if the response doesn't contain valid content\n */\n if (typeof response.content !== \"string\" || response.content === \"\") {\n return;\n }\n\n try {\n const content = JSON.parse(response.content);\n const validator = new Validator(this.schema);\n const result = validator.validate(content);\n if (!result.valid) {\n return;\n }\n\n return content;\n } catch {\n // no-op\n }\n }\n}\n\nexport type ResponseFormat = ToolStrategy<any> | ProviderStrategy<any>;\n\n/**\n * Handle user input for `responseFormat` parameter of `CreateAgentParams`.\n * This function defines the default behavior for the `responseFormat` parameter, which is:\n *\n * - if value is a Zod schema, default to structured output via tool calling\n * - if value is a JSON schema, default to structured output via tool calling\n * - if value is a custom response format, return it as is\n * - if value is an array, ensure all array elements are instance of `ToolStrategy`\n * @param responseFormat\n * @returns\n */\nexport function transformResponseFormat(\n responseFormat?:\n | InteropZodType<any>\n | InteropZodType<any>[]\n | JsonSchemaFormat\n | JsonSchemaFormat[]\n | ResponseFormat\n | ToolStrategy<any>[]\n | ResponseFormatUndefined,\n options?: ToolStrategyOptions\n): ResponseFormat[] {\n if (!responseFormat) {\n return [];\n }\n\n // Handle ResponseFormatUndefined case\n if (\n typeof responseFormat === \"object\" &&\n responseFormat !== null &&\n \"__responseFormatUndefined\" in responseFormat\n ) {\n return [];\n }\n\n /**\n * If users provide an array, it should only contain raw schemas (Zod or JSON schema),\n * not ToolStrategy or ProviderStrategy instances.\n */\n if (Array.isArray(responseFormat)) {\n /**\n * if every entry is a ToolStrategy or ProviderStrategy instance, return the array as is\n */\n if (\n responseFormat.every(\n (item) =>\n item instanceof ToolStrategy || item instanceof ProviderStrategy\n )\n ) {\n return responseFormat as unknown as ResponseFormat[];\n }\n\n /**\n * Check if all items are Zod schemas\n */\n if (responseFormat.every((item) => isInteropZodObject(item))) {\n return responseFormat.map((item) =>\n ToolStrategy.fromSchema(item as InteropZodObject, undefined, options)\n );\n }\n\n /**\n * Check if all items are plain objects (JSON schema)\n */\n if (\n responseFormat.every(\n (item) =>\n typeof item === \"object\" && item !== null && !isInteropZodObject(item)\n )\n ) {\n return responseFormat.map((item) =>\n ToolStrategy.fromSchema(item as JsonSchemaFormat, undefined, options)\n );\n }\n\n throw new Error(\n `Invalid response format: list contains mixed types.\\n` +\n `All items must be either InteropZodObject or plain JSON schema objects.`\n );\n }\n\n if (isInteropZodObject(responseFormat)) {\n return [ToolStrategy.fromSchema(responseFormat, undefined, options)];\n }\n\n if (\n responseFormat instanceof ToolStrategy ||\n responseFormat instanceof ProviderStrategy\n ) {\n return [responseFormat];\n }\n\n /**\n * Handle plain object (JSON schema)\n */\n if (\n typeof responseFormat === \"object\" &&\n responseFormat !== null &&\n \"properties\" in responseFormat\n ) {\n return [\n ToolStrategy.fromSchema(\n responseFormat as JsonSchemaFormat,\n undefined,\n options\n ),\n ];\n }\n\n throw new Error(`Invalid response format: ${String(responseFormat)}`);\n}\n\n/**\n * Branded type for ToolStrategy arrays that preserves type information\n */\nexport interface TypedToolStrategy<T = unknown>\n extends Array<ToolStrategy<any>> {\n _schemaType?: T;\n}\nexport type ToolStrategyError =\n | StructuredOutputParsingError\n | MultipleStructuredOutputsError;\nexport interface ToolStrategyOptions {\n /**\n * Allows you to customize the message that appears in the conversation history when structured\n * output is generated.\n */\n toolMessageContent?: string;\n /**\n * Handle errors from the structured output tool call. Using tools to generate structured output\n * can cause errors, e.g. if:\n * - you provide multiple structured output schemas and the model calls multiple structured output tools\n * - if the structured output generated by the tool call doesn't match provided schema\n *\n * This property allows to handle these errors in different ways:\n * - `true` - retry the tool call\n * - `false` - throw an error\n * - `string` - retry the tool call with the provided message\n * - `(error: ToolStrategyError) => Promise<string> | string` - retry with the provided message or throw the error\n */\n handleError?:\n | boolean\n | string\n | ((error: ToolStrategyError) => Promise<string> | string);\n}\n\nexport function toolStrategy<T extends InteropZodType<any>>(\n responseFormat: T,\n options?: ToolStrategyOptions\n): TypedToolStrategy<T extends InteropZodType<infer U> ? U : never>;\nexport function toolStrategy<T extends readonly InteropZodType<any>[]>(\n responseFormat: T,\n options?: ToolStrategyOptions\n): TypedToolStrategy<\n { [K in keyof T]: T[K] extends InteropZodType<infer U> ? U : never }[number]\n>;\nexport function toolStrategy(\n responseFormat: JsonSchemaFormat,\n options?: ToolStrategyOptions\n): TypedToolStrategy<Record<string, unknown>>;\nexport function toolStrategy(\n responseFormat: JsonSchemaFormat[],\n options?: ToolStrategyOptions\n): TypedToolStrategy<Record<string, unknown>>;\n\n/**\n * Define how to transform the response format from a tool call.\n *\n * @param responseFormat - The response format to transform\n * @param options - The options to use for the transformation\n * @param options.handleError - Whether to handle errors from the tool call\n * @returns The transformed response format\n */\nexport function toolStrategy(\n responseFormat:\n | InteropZodType<any>\n | InteropZodType<any>[]\n | JsonSchemaFormat\n | JsonSchemaFormat[],\n options?: ToolStrategyOptions\n): TypedToolStrategy {\n return transformResponseFormat(responseFormat, options) as TypedToolStrategy;\n}\n\nexport function providerStrategy<T extends InteropZodType<any>>(\n responseFormat: T\n): ProviderStrategy<T extends InteropZodType<infer U> ? U : never>;\nexport function providerStrategy(\n responseFormat: JsonSchemaFormat\n): ProviderStrategy<Record<string, unknown>>;\nexport function providerStrategy(\n responseFormat: InteropZodType<any> | JsonSchemaFormat\n): ProviderStrategy<any> {\n return ProviderStrategy.fromSchema(\n responseFormat as any\n ) as ProviderStrategy<any>;\n}\n\n/**\n * Special type to indicate that no response format is provided.\n * When this type is used, the structuredResponse property should not be present in the result.\n */\nexport type ResponseFormatUndefined = {\n __responseFormatUndefined: true;\n};\n\n/**\n * Type representing a JSON Schema object format.\n * This is a strict type that excludes ToolStrategy and ProviderStrategy instances.\n */\nexport type JsonSchemaFormat = {\n type:\n | \"null\"\n | \"boolean\"\n | \"object\"\n | \"array\"\n | \"number\"\n | \"string\"\n | \"integer\";\n properties?: Record<string, unknown>;\n required?: string[];\n additionalProperties?: boolean;\n [key: string]: unknown;\n} & {\n // Brand to ensure this is not a ToolStrategy or ProviderStrategy\n __brand?: never;\n};\n"],"mappings":";;;;;;;;;AAoBA,IAAI,oBAAoB;;;;;;;AAQxB,IAAa,eAAb,MAAa,aAA2B;CACtC,AAAQ,YAIUA,QAKAC,MAQAC,SAChB;EAdgB;EAKA;EAQA;CACd;CAEJ,IAAI,OAAO;AACT,SAAO,KAAK,KAAK,SAAS;CAC3B;CAsBD,OAAO,WACLC,QACAC,SAKAC,eACmB;;;;;EAKnB,SAAS,gBAAgBC,MAAe;AACtC,UAAO,QAAQ,SAAS,QAAQ,CAAC,QAAQ,EAAE,EAAE,mBAAmB;EACjE;AAED,2DAAuB,OAAO,EAAE;GAC9B,MAAMC,sEAA4B,OAAO;GACzC,MAAMC,SAAO;IACX,MAAM;IACN,UAAU;KACR,MAAM,iBAAiB;KACvB,QAAQ,SAAS;KACjB,aACE,SAAS,eACTD,eAAa,eACb;KACF,YAAYA;IACb;GACF;AACD,UAAO,IAAI,aAAaA,gBAAcC,QAAM;EAC7C;EAED,IAAIC;AACJ,MACE,OAAO,OAAO,SAAS,YACvB,OAAO,OAAO,eAAe,YAC7B,OAAO,cAAc,MAErB,qBAAqB;OAErB,qBAAqB;GACnB,MAAM,gBAAgB,OAAO,MAAgB;GAC7C,aAAc,OAAO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0B,QAAW,QAAQ,CACtE;;;;AAMH,MACE,eAAe,MACb,CAAC,SACC,OAAO,SAAS,YAAY,SAAS,QAAQ,sDAAoB,KAAK,CACzE,CAED,QAAO,eAAe,IAAI,CAAC,SACzB,aAAa,WAAW,MAA0B,QAAW,QAAQ,CACtE;AAGH,QAAM,IAAI,MACR;CAGH;AAED,0DAAuB,eAAe,CACpC,QAAO,CAAC,aAAa,WAAW,gBAAgB,QAAW,QAAQ,AAAC;AAGtE,KACE,0BAA0B,gBAC1B,0BAA0B,iBAE1B,QAAO,CAAC,cAAe;;;;AAMzB,KACE,OAAO,mBAAmB,YAC1B,mBAAmB,QACnB,gBAAgB,eAEhB,QAAO,CACL,aAAa,WACX,gBACA,QACA,QACD,AACF;AAGH,OAAM,IAAI,MAAM,CAAC,yBAAyB,EAAE,OAAO,eAAe,EAAE;AACrE;;;;;;;;;AA+DD,SAAgB,aACdc,gBAKAd,SACmB;AACnB,QAAO,wBAAwB,gBAAgB,QAAQ;AACxD;AAQD,SAAgB,iBACde,gBACuB;AACvB,QAAO,iBAAiB,WACtB,eACD;AACF"}
1
+ {"version":3,"file":"responses.cjs","names":["schema: Record<string, unknown>","tool: {\n type: \"function\";\n function: FunctionDefinition;\n }","options?: ToolStrategyOptions","schema: InteropZodObject | Record<string, unknown>","outputOptions?: ToolStrategyOptions","name?: string","asJsonSchema","tool","functionDefinition: FunctionDefinition","toolArgs: Record<string, unknown>","Validator","StructuredOutputParsingError","schema: InteropZodType<T> | Record<string, unknown>","response: AIMessage","responseFormat?:\n | InteropZodType<any>\n | InteropZodType<any>[]\n | JsonSchemaFormat\n | JsonSchemaFormat[]\n | ResponseFormat\n | ToolStrategy<any>[]\n | ResponseFormatUndefined","model?: LanguageModelLike | string","responseFormat:\n | InteropZodType<any>\n | InteropZodType<any>[]\n | JsonSchemaFormat\n | JsonSchemaFormat[]","responseFormat: InteropZodType<any> | JsonSchemaFormat","isConfigurableModel","isBaseChatModel"],"sources":["../../src/agents/responses.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable no-instanceof/no-instanceof */\nimport {\n InteropZodObject,\n isInteropZodSchema,\n InteropZodType,\n isInteropZodObject,\n} from \"@langchain/core/utils/types\";\nimport { type AIMessage } from \"@langchain/core/messages\";\nimport { type LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { toJsonSchema, Validator } from \"@langchain/core/utils/json_schema\";\nimport { type FunctionDefinition } from \"@langchain/core/language_models/base\";\n\nimport {\n StructuredOutputParsingError,\n MultipleStructuredOutputsError,\n} from \"./errors.js\";\nimport type { ResponseFormatUndefined } from \"./annotation.js\";\nimport { isConfigurableModel, isBaseChatModel } from \"./model.js\";\n\n/**\n * This is a global counter for generating unique names for tools.\n */\nlet bindingIdentifier = 0;\n\n/**\n * Information for tracking structured output tool metadata.\n * This contains all necessary information to handle structured responses generated\n * via tool calls, including the original schema, its type classification, and the\n * corresponding tool implementation used by the tools strategy.\n */\nexport class ToolStrategy<_T = unknown> {\n private constructor(\n /**\n * The original JSON Schema provided for structured output\n */\n public readonly schema: Record<string, unknown>,\n\n /**\n * The tool that will be used to parse the tool call arguments.\n */\n public readonly tool: {\n type: \"function\";\n function: FunctionDefinition;\n },\n\n /**\n * The options to use for the tool output.\n */\n public readonly options?: ToolStrategyOptions\n ) {}\n\n get name() {\n return this.tool.function.name;\n }\n\n static fromSchema<S extends InteropZodObject>(\n schema: S,\n outputOptions?: ToolStrategyOptions\n ): ToolStrategy<S extends InteropZodType<infer U> ? U : unknown>;\n\n static fromSchema(\n schema: Record<string, unknown>,\n outputOptions?: ToolStrategyOptions\n ): ToolStrategy<Record<string, unknown>>;\n\n static fromSchema(\n schema: InteropZodObject | Record<string, unknown>,\n outputOptions?: ToolStrategyOptions\n ): ToolStrategy<any> {\n /**\n * It is required for tools to have a name so we can map the tool call to the correct tool\n * when parsing the response.\n */\n function getFunctionName(name?: string) {\n return name ?? `extract-${++bindingIdentifier}`;\n }\n\n if (isInteropZodSchema(schema)) {\n const asJsonSchema = toJsonSchema(schema);\n const tool = {\n type: \"function\" as const,\n function: {\n name: getFunctionName(),\n strict: false,\n description:\n asJsonSchema.description ??\n \"Tool for extracting structured output from the model's response.\",\n parameters: asJsonSchema,\n },\n };\n return new ToolStrategy(asJsonSchema, tool, outputOptions);\n }\n\n let functionDefinition: FunctionDefinition;\n if (\n typeof schema.name === \"string\" &&\n typeof schema.parameters === \"object\" &&\n schema.parameters != null\n ) {\n functionDefinition = schema as unknown as FunctionDefinition;\n } else {\n functionDefinition = {\n name: getFunctionName(schema.title as string),\n description: (schema.description as string) ?? \"\",\n parameters: schema.schema || (schema as Record<string, unknown>),\n };\n }\n const asJsonSchema = toJsonSchema(schema);\n const tool = {\n type: \"function\" as const,\n function: functionDefinition,\n };\n return new ToolStrategy(asJsonSchema, tool, outputOptions);\n }\n\n /**\n * Parse tool arguments according to the schema.\n *\n * @throws {StructuredOutputParsingError} if the response is not valid\n * @param toolArgs - The arguments from the tool call\n * @returns The parsed response according to the schema type\n */\n parse(toolArgs: Record<string, unknown>): Record<string, unknown> {\n const validator = new Validator(this.schema);\n const result = validator.validate(toolArgs);\n if (!result.valid) {\n throw new StructuredOutputParsingError(\n this.name,\n result.errors.map((e) => e.error)\n );\n }\n return toolArgs;\n }\n}\n\nexport class ProviderStrategy<T = unknown> {\n // @ts-expect-error - _schemaType is used only for type inference\n private _schemaType?: T;\n\n private constructor(public readonly schema: Record<string, unknown>) {}\n\n static fromSchema<T>(schema: InteropZodType<T>): ProviderStrategy<T>;\n\n static fromSchema(\n schema: Record<string, unknown>\n ): ProviderStrategy<Record<string, unknown>>;\n\n static fromSchema<T = unknown>(\n schema: InteropZodType<T> | Record<string, unknown>\n ): ProviderStrategy<T> | ProviderStrategy<Record<string, unknown>> {\n const asJsonSchema = toJsonSchema(schema);\n return new ProviderStrategy(asJsonSchema) as\n | ProviderStrategy<T>\n | ProviderStrategy<Record<string, unknown>>;\n }\n\n /**\n * Parse tool arguments according to the schema. If the response is not valid, return undefined.\n *\n * @param toolArgs - The arguments from the tool call\n * @returns The parsed response according to the schema type\n */\n parse(response: AIMessage) {\n /**\n * return if the response doesn't contain valid content\n */\n if (typeof response.content !== \"string\" || response.content === \"\") {\n return;\n }\n\n try {\n const content = JSON.parse(response.content);\n const validator = new Validator(this.schema);\n const result = validator.validate(content);\n if (!result.valid) {\n return;\n }\n\n return content;\n } catch {\n // no-op\n }\n }\n}\n\nexport type ResponseFormat = ToolStrategy<any> | ProviderStrategy<any>;\n\n/**\n * Handle user input for `responseFormat` parameter of `CreateAgentParams`.\n * This function defines the default behavior for the `responseFormat` parameter, which is:\n *\n * - if value is a Zod schema, default to structured output via tool calling\n * - if value is a JSON schema, default to structured output via tool calling\n * - if value is a custom response format, return it as is\n * - if value is an array, ensure all array elements are instance of `ToolStrategy`\n * @param responseFormat - The response format to transform, provided by the user\n * @param options - The response format options for tool strategy\n * @param model - The model to check if it supports JSON schema output\n * @returns\n */\nexport function transformResponseFormat(\n responseFormat?:\n | InteropZodType<any>\n | InteropZodType<any>[]\n | JsonSchemaFormat\n | JsonSchemaFormat[]\n | ResponseFormat\n | ToolStrategy<any>[]\n | ResponseFormatUndefined,\n options?: ToolStrategyOptions,\n model?: LanguageModelLike | string\n): ResponseFormat[] {\n if (!responseFormat) {\n return [];\n }\n\n // Handle ResponseFormatUndefined case\n if (\n typeof responseFormat === \"object\" &&\n responseFormat !== null &&\n \"__responseFormatUndefined\" in responseFormat\n ) {\n return [];\n }\n\n /**\n * If users provide an array, it should only contain raw schemas (Zod or JSON schema),\n * not ToolStrategy or ProviderStrategy instances.\n */\n if (Array.isArray(responseFormat)) {\n /**\n * if every entry is a ToolStrategy or ProviderStrategy instance, return the array as is\n */\n if (\n responseFormat.every(\n (item) =>\n item instanceof ToolStrategy || item instanceof ProviderStrategy\n )\n ) {\n return responseFormat as unknown as ResponseFormat[];\n }\n\n /**\n * Check if all items are Zod schemas\n */\n if (responseFormat.every((item) => isInteropZodObject(item))) {\n return responseFormat.map((item) =>\n ToolStrategy.fromSchema(item as InteropZodObject, options)\n );\n }\n\n /**\n * Check if all items are plain objects (JSON schema)\n */\n if (\n responseFormat.every(\n (item) =>\n typeof item === \"object\" && item !== null && !isInteropZodObject(item)\n )\n ) {\n return responseFormat.map((item) =>\n ToolStrategy.fromSchema(item as JsonSchemaFormat, options)\n );\n }\n\n throw new Error(\n `Invalid response format: list contains mixed types.\\n` +\n `All items must be either InteropZodObject or plain JSON schema objects.`\n );\n }\n\n if (\n responseFormat instanceof ToolStrategy ||\n responseFormat instanceof ProviderStrategy\n ) {\n return [responseFormat];\n }\n\n const useProviderStrategy = hasSupportForJsonSchemaOutput(model);\n\n /**\n * `responseFormat` is a Zod schema\n */\n if (isInteropZodObject(responseFormat)) {\n return useProviderStrategy\n ? [ProviderStrategy.fromSchema(responseFormat)]\n : [ToolStrategy.fromSchema(responseFormat, options)];\n }\n\n /**\n * Handle plain object (JSON schema)\n */\n if (\n typeof responseFormat === \"object\" &&\n responseFormat !== null &&\n \"properties\" in responseFormat\n ) {\n return useProviderStrategy\n ? [ProviderStrategy.fromSchema(responseFormat as JsonSchemaFormat)]\n : [ToolStrategy.fromSchema(responseFormat as JsonSchemaFormat, options)];\n }\n\n throw new Error(`Invalid response format: ${String(responseFormat)}`);\n}\n\n/**\n * Branded type for ToolStrategy arrays that preserves type information\n */\nexport interface TypedToolStrategy<T = unknown>\n extends Array<ToolStrategy<any>> {\n _schemaType?: T;\n}\nexport type ToolStrategyError =\n | StructuredOutputParsingError\n | MultipleStructuredOutputsError;\nexport interface ToolStrategyOptions {\n /**\n * Allows you to customize the message that appears in the conversation history when structured\n * output is generated.\n */\n toolMessageContent?: string;\n /**\n * Handle errors from the structured output tool call. Using tools to generate structured output\n * can cause errors, e.g. if:\n * - you provide multiple structured output schemas and the model calls multiple structured output tools\n * - if the structured output generated by the tool call doesn't match provided schema\n *\n * This property allows to handle these errors in different ways:\n * - `true` - retry the tool call\n * - `false` - throw an error\n * - `string` - retry the tool call with the provided message\n * - `(error: ToolStrategyError) => Promise<string> | string` - retry with the provided message or throw the error\n */\n handleError?:\n | boolean\n | string\n | ((error: ToolStrategyError) => Promise<string> | string);\n}\n\nexport function toolStrategy<T extends InteropZodType<any>>(\n responseFormat: T,\n options?: ToolStrategyOptions\n): TypedToolStrategy<T extends InteropZodType<infer U> ? U : never>;\nexport function toolStrategy<T extends readonly InteropZodType<any>[]>(\n responseFormat: T,\n options?: ToolStrategyOptions\n): TypedToolStrategy<\n { [K in keyof T]: T[K] extends InteropZodType<infer U> ? U : never }[number]\n>;\nexport function toolStrategy(\n responseFormat: JsonSchemaFormat,\n options?: ToolStrategyOptions\n): TypedToolStrategy<Record<string, unknown>>;\nexport function toolStrategy(\n responseFormat: JsonSchemaFormat[],\n options?: ToolStrategyOptions\n): TypedToolStrategy<Record<string, unknown>>;\n\n/**\n * Define how to transform the response format from a tool call.\n *\n * @param responseFormat - The response format to transform\n * @param options - The options to use for the transformation\n * @param options.handleError - Whether to handle errors from the tool call\n * @returns The transformed response format\n */\nexport function toolStrategy(\n responseFormat:\n | InteropZodType<any>\n | InteropZodType<any>[]\n | JsonSchemaFormat\n | JsonSchemaFormat[],\n options?: ToolStrategyOptions\n): TypedToolStrategy {\n return transformResponseFormat(responseFormat, options) as TypedToolStrategy;\n}\n\nexport function providerStrategy<T extends InteropZodType<any>>(\n responseFormat: T\n): ProviderStrategy<T extends InteropZodType<infer U> ? U : never>;\nexport function providerStrategy(\n responseFormat: JsonSchemaFormat\n): ProviderStrategy<Record<string, unknown>>;\nexport function providerStrategy(\n responseFormat: InteropZodType<any> | JsonSchemaFormat\n): ProviderStrategy<any> {\n return ProviderStrategy.fromSchema(\n responseFormat as any\n ) as ProviderStrategy<any>;\n}\n\n/**\n * Type representing a JSON Schema object format.\n * This is a strict type that excludes ToolStrategy and ProviderStrategy instances.\n */\nexport type JsonSchemaFormat = {\n type:\n | \"null\"\n | \"boolean\"\n | \"object\"\n | \"array\"\n | \"number\"\n | \"string\"\n | \"integer\";\n properties?: Record<string, unknown>;\n required?: string[];\n additionalProperties?: boolean;\n [key: string]: unknown;\n} & {\n // Brand to ensure this is not a ToolStrategy or ProviderStrategy\n __brand?: never;\n};\n\nconst CHAT_MODELS_THAT_SUPPORT_JSON_SCHEMA_OUTPUT = [\"ChatOpenAI\", \"ChatXAI\"];\nconst MODEL_NAMES_THAT_SUPPORT_JSON_SCHEMA_OUTPUT = [\n \"grok\",\n \"gpt-5\",\n \"gpt-4.1\",\n \"gpt-4o\",\n \"gpt-oss\",\n \"o3-pro\",\n \"o3-mini\",\n];\n\n/**\n * Identifies the models that support JSON schema output\n * @param model - The model to check\n * @returns True if the model supports JSON schema output, false otherwise\n */\nexport function hasSupportForJsonSchemaOutput(\n model?: LanguageModelLike | string\n): boolean {\n if (!model) {\n return false;\n }\n\n if (typeof model === \"string\") {\n const modelName = model.split(\":\").pop() as string;\n return MODEL_NAMES_THAT_SUPPORT_JSON_SCHEMA_OUTPUT.some(\n (modelNameSnippet) => modelName.includes(modelNameSnippet)\n );\n }\n\n if (isConfigurableModel(model)) {\n const configurableModel = model as unknown as {\n _defaultConfig: { model: string };\n };\n return hasSupportForJsonSchemaOutput(\n configurableModel._defaultConfig.model\n );\n }\n\n if (!isBaseChatModel(model)) {\n return false;\n }\n\n const chatModelClass = model.getName();\n\n /**\n * for testing purposes only\n */\n if (chatModelClass === \"FakeToolCallingChatModel\") {\n return true;\n }\n\n if (\n CHAT_MODELS_THAT_SUPPORT_JSON_SCHEMA_OUTPUT.includes(chatModelClass) &&\n /**\n * OpenAI models\n */ ((\"model\" in model &&\n MODEL_NAMES_THAT_SUPPORT_JSON_SCHEMA_OUTPUT.some(\n (modelNameSnippet) =>\n typeof model.model === \"string\" &&\n model.model.includes(modelNameSnippet)\n )) ||\n /**\n * for testing purposes only\n */\n (chatModelClass === \"FakeToolCallingModel\" &&\n \"structuredResponse\" in model))\n ) {\n return true;\n }\n\n return false;\n}\n"],"mappings":";;;;;;;;;;AAuBA,IAA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aAAa,WAAW,gBAAoC,QAAQ,AAAC;AAG5E,OAAM,IAAI,MAAM,CAAC,yBAAyB,EAAE,OAAO,eAAe,EAAE;AACrE;;;;;;;;;AA+DD,SAAgB,aACdC,gBAKAd,SACmB;AACnB,QAAO,wBAAwB,gBAAgB,QAAQ;AACxD;AAQD,SAAgB,iBACde,gBACuB;AACvB,QAAO,iBAAiB,WACtB,eACD;AACF;AAwBD,MAAM,8CAA8C,CAAC,cAAc,SAAU;AAC7E,MAAM,8CAA8C;CAClD;CACA;CACA;CACA;CACA;CACA;CACA;AACD;;;;;;AAOD,SAAgB,8BACdF,OACS;AACT,KAAI,CAAC,MACH,QAAO;AAGT,KAAI,OAAO,UAAU,UAAU;EAC7B,MAAM,YAAY,MAAM,MAAM,IAAI,CAAC,KAAK;AACxC,SAAO,4CAA4C,KACjD,CAAC,qBAAqB,UAAU,SAAS,iBAAiB,CAC3D;CACF;AAED,KAAIG,kCAAoB,MAAM,EAAE;EAC9B,MAAM,oBAAoB;AAG1B,SAAO,8BACL,kBAAkB,eAAe,MAClC;CACF;AAED,KAAI,CAACC,8BAAgB,MAAM,CACzB,QAAO;CAGT,MAAM,iBAAiB,MAAM,SAAS;;;;AAKtC,KAAI,mBAAmB,2BACrB,QAAO;AAGT,KACE,4CAA4C,SAAS,eAAe,KAG9D,WAAW,SACf,4CAA4C,KAC1C,CAAC,qBACC,OAAO,MAAM,UAAU,YACvB,MAAM,MAAM,SAAS,iBAAiB,CACzC,IAIA,mBAAmB,0BAClB,wBAAwB,OAE5B,QAAO;AAGT,QAAO;AACR"}
@@ -1,5 +1,5 @@
1
1
  import { MultipleStructuredOutputsError, StructuredOutputParsingError } from "./errors.cjs";
2
- import { FunctionDefinition } from "@langchain/core/language_models/base";
2
+ import { FunctionDefinition, LanguageModelLike } from "@langchain/core/language_models/base";
3
3
  import { InteropZodObject, InteropZodType } from "@langchain/core/utils/types";
4
4
  import { AIMessage } from "@langchain/core/messages";
5
5
 
@@ -20,16 +20,8 @@ declare class ToolStrategy<_T = unknown> {
20
20
  readonly options?: ToolStrategyOptions | undefined;
21
21
  private constructor();
22
22
  get name(): string;
23
- static fromSchema<S extends InteropZodObject>(schema: S, options?: {
24
- name?: string;
25
- description?: string;
26
- strict?: boolean;
27
- }, outputOptions?: ToolStrategyOptions): ToolStrategy<S extends InteropZodType<infer U> ? U : unknown>;
28
- static fromSchema(schema: Record<string, unknown>, options?: {
29
- name?: string;
30
- description?: string;
31
- strict?: boolean;
32
- }, outputOptions?: ToolStrategyOptions): ToolStrategy<Record<string, unknown>>;
23
+ static fromSchema<S extends InteropZodObject>(schema: S, outputOptions?: ToolStrategyOptions): ToolStrategy<S extends InteropZodType<infer U> ? U : unknown>;
24
+ static fromSchema(schema: Record<string, unknown>, outputOptions?: ToolStrategyOptions): ToolStrategy<Record<string, unknown>>;
33
25
  /**
34
26
  * Parse tool arguments according to the schema.
35
27
  *
@@ -63,7 +55,9 @@ type ResponseFormat = ToolStrategy<any> | ProviderStrategy<any>;
63
55
  * - if value is a JSON schema, default to structured output via tool calling
64
56
  * - if value is a custom response format, return it as is
65
57
  * - if value is an array, ensure all array elements are instance of `ToolStrategy`
66
- * @param responseFormat
58
+ * @param responseFormat - The response format to transform, provided by the user
59
+ * @param options - The response format options for tool strategy
60
+ * @param model - The model to check if it supports JSON schema output
67
61
  * @returns
68
62
  */
69
63
 
@@ -100,13 +94,6 @@ declare function toolStrategy(responseFormat: JsonSchemaFormat, options?: ToolSt
100
94
  declare function toolStrategy(responseFormat: JsonSchemaFormat[], options?: ToolStrategyOptions): TypedToolStrategy<Record<string, unknown>>;
101
95
  declare function providerStrategy<T extends InteropZodType<any>>(responseFormat: T): ProviderStrategy<T extends InteropZodType<infer U> ? U : never>;
102
96
  declare function providerStrategy(responseFormat: JsonSchemaFormat): ProviderStrategy<Record<string, unknown>>;
103
- /**
104
- * Special type to indicate that no response format is provided.
105
- * When this type is used, the structuredResponse property should not be present in the result.
106
- */
107
- type ResponseFormatUndefined = {
108
- __responseFormatUndefined: true;
109
- };
110
97
  /**
111
98
  * Type representing a JSON Schema object format.
112
99
  * This is a strict type that excludes ToolStrategy and ProviderStrategy instances.
@@ -121,6 +108,11 @@ type JsonSchemaFormat = {
121
108
  // Brand to ensure this is not a ToolStrategy or ProviderStrategy
122
109
  __brand?: never;
123
110
  };
111
+ /**
112
+ * Identifies the models that support JSON schema output
113
+ * @param model - The model to check
114
+ * @returns True if the model supports JSON schema output, false otherwise
115
+ */
124
116
  //#endregion
125
- export { JsonSchemaFormat, ProviderStrategy, ResponseFormat, ResponseFormatUndefined, ToolStrategy, TypedToolStrategy, providerStrategy, toolStrategy };
117
+ export { JsonSchemaFormat, ProviderStrategy, ResponseFormat, ToolStrategy, TypedToolStrategy, providerStrategy, toolStrategy };
126
118
  //# sourceMappingURL=responses.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"responses.d.cts","names":["InteropZodObject","InteropZodType","AIMessage","FunctionDefinition","StructuredOutputParsingError","MultipleStructuredOutputsError","ToolStrategy","Record","ToolStrategyOptions","S","U","ProviderStrategy","T","ResponseFormat","transformResponseFormat","JsonSchemaFormat","ResponseFormatUndefined","TypedToolStrategy","Array","ToolStrategyError","Promise","toolStrategy","K","providerStrategy"],"sources":["../../src/agents/responses.d.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable no-instanceof/no-instanceof */\nimport { InteropZodObject, InteropZodType } from \"@langchain/core/utils/types\";\nimport { type AIMessage } from \"@langchain/core/messages\";\nimport { type FunctionDefinition } from \"@langchain/core/language_models/base\";\nimport { StructuredOutputParsingError, MultipleStructuredOutputsError } from \"./errors.js\";\n/**\n * Information for tracking structured output tool metadata.\n * This contains all necessary information to handle structured responses generated\n * via tool calls, including the original schema, its type classification, and the\n * corresponding tool implementation used by the tools strategy.\n */\nexport declare class ToolStrategy<_T = unknown> {\n readonly schema: Record<string, unknown>;\n readonly tool: {\n type: \"function\";\n function: FunctionDefinition;\n };\n readonly options?: ToolStrategyOptions | undefined;\n private constructor();\n get name(): string;\n static fromSchema<S extends InteropZodObject>(schema: S, options?: {\n name?: string;\n description?: string;\n strict?: boolean;\n }, outputOptions?: ToolStrategyOptions): ToolStrategy<S extends InteropZodType<infer U> ? U : unknown>;\n static fromSchema(schema: Record<string, unknown>, options?: {\n name?: string;\n description?: string;\n strict?: boolean;\n }, outputOptions?: ToolStrategyOptions): ToolStrategy<Record<string, unknown>>;\n /**\n * Parse tool arguments according to the schema.\n *\n * @throws {StructuredOutputParsingError} if the response is not valid\n * @param toolArgs - The arguments from the tool call\n * @returns The parsed response according to the schema type\n */\n parse(toolArgs: Record<string, unknown>): Record<string, unknown>;\n}\nexport declare class ProviderStrategy<T = unknown> {\n readonly schema: Record<string, unknown>;\n // @ts-expect-error - _schemaType is used only for type inference\n private _schemaType?;\n private constructor();\n static fromSchema<T>(schema: InteropZodType<T>): ProviderStrategy<T>;\n static fromSchema(schema: Record<string, unknown>): ProviderStrategy<Record<string, unknown>>;\n /**\n * Parse tool arguments according to the schema. If the response is not valid, return undefined.\n *\n * @param toolArgs - The arguments from the tool call\n * @returns The parsed response according to the schema type\n */\n parse(response: AIMessage): any;\n}\nexport type ResponseFormat = ToolStrategy<any> | ProviderStrategy<any>;\n/**\n * Handle user input for `responseFormat` parameter of `CreateAgentParams`.\n * This function defines the default behavior for the `responseFormat` parameter, which is:\n *\n * - if value is a Zod schema, default to structured output via tool calling\n * - if value is a JSON schema, default to structured output via tool calling\n * - if value is a custom response format, return it as is\n * - if value is an array, ensure all array elements are instance of `ToolStrategy`\n * @param responseFormat\n * @returns\n */\nexport declare function transformResponseFormat(responseFormat?: InteropZodType<any> | InteropZodType<any>[] | JsonSchemaFormat | JsonSchemaFormat[] | ResponseFormat | ToolStrategy<any>[] | ResponseFormatUndefined, options?: ToolStrategyOptions): ResponseFormat[];\n/**\n * Branded type for ToolStrategy arrays that preserves type information\n */\nexport interface TypedToolStrategy<T = unknown> extends Array<ToolStrategy<any>> {\n _schemaType?: T;\n}\nexport type ToolStrategyError = StructuredOutputParsingError | MultipleStructuredOutputsError;\nexport interface ToolStrategyOptions {\n /**\n * Allows you to customize the message that appears in the conversation history when structured\n * output is generated.\n */\n toolMessageContent?: string;\n /**\n * Handle errors from the structured output tool call. Using tools to generate structured output\n * can cause errors, e.g. if:\n * - you provide multiple structured output schemas and the model calls multiple structured output tools\n * - if the structured output generated by the tool call doesn't match provided schema\n *\n * This property allows to handle these errors in different ways:\n * - `true` - retry the tool call\n * - `false` - throw an error\n * - `string` - retry the tool call with the provided message\n * - `(error: ToolStrategyError) => Promise<string> | string` - retry with the provided message or throw the error\n */\n handleError?: boolean | string | ((error: ToolStrategyError) => Promise<string> | string);\n}\nexport declare function toolStrategy<T extends InteropZodType<any>>(responseFormat: T, options?: ToolStrategyOptions): TypedToolStrategy<T extends InteropZodType<infer U> ? U : never>;\nexport declare function toolStrategy<T extends readonly InteropZodType<any>[]>(responseFormat: T, options?: ToolStrategyOptions): TypedToolStrategy<{\n [K in keyof T]: T[K] extends InteropZodType<infer U> ? U : never;\n}[number]>;\nexport declare function toolStrategy(responseFormat: JsonSchemaFormat, options?: ToolStrategyOptions): TypedToolStrategy<Record<string, unknown>>;\nexport declare function toolStrategy(responseFormat: JsonSchemaFormat[], options?: ToolStrategyOptions): TypedToolStrategy<Record<string, unknown>>;\nexport declare function providerStrategy<T extends InteropZodType<any>>(responseFormat: T): ProviderStrategy<T extends InteropZodType<infer U> ? U : never>;\nexport declare function providerStrategy(responseFormat: JsonSchemaFormat): ProviderStrategy<Record<string, unknown>>;\n/**\n * Special type to indicate that no response format is provided.\n * When this type is used, the structuredResponse property should not be present in the result.\n */\nexport type ResponseFormatUndefined = {\n __responseFormatUndefined: true;\n};\n/**\n * Type representing a JSON Schema object format.\n * This is a strict type that excludes ToolStrategy and ProviderStrategy instances.\n */\nexport type JsonSchemaFormat = {\n type: \"null\" | \"boolean\" | \"object\" | \"array\" | \"number\" | \"string\" | \"integer\";\n properties?: Record<string, unknown>;\n required?: string[];\n additionalProperties?: boolean;\n [key: string]: unknown;\n} & {\n // Brand to ensure this is not a ToolStrategy or ProviderStrategy\n __brand?: never;\n};\n"],"mappings":";;;;;;;AAYA;;;;;;AAS0DS,cATrCH,YASqCG,CAAAA,KAAAA,OAAAA,CAAAA,CAAAA;EAAC,SAIpCD,MAAAA,EAZFD,MAYEC,CAAAA,MAAAA,EAAAA,OAAAA,CAAAA;EAAmB,SAAgBC,IAAAA,EAAAA;IAAUR,IAAAA,EAAAA,UAAAA;IAA0BS,QAAAA,EAT5EP,kBAS4EO;EAAC,CAAA;EAAtC,SAC3BH,OAAAA,CAAAA,EARPC,mBAQOD,GAAAA,SAAAA;EAAM,QAIbC,WAAAA,CAAAA;EAAmB,IAAgBD,IAAAA,CAAAA,CAAAA,EAAAA,MAAAA;EAAM,OAAnBD,UAAAA,CAAAA,UATbN,gBASaM,CAAAA,CAAAA,MAAAA,EATaG,CASbH,EAAAA,OAUxBK,CAVwBL,EAAAA;IAQzBC,IAAAA,CAAAA,EAAAA,MAAAA;IAA0BA,WAAAA,CAAAA,EAAAA,MAAAA;IAAM,MAAA,CAAA,EAAA,OAAA;EAE/BI,CAAAA,EAAAA,aAAgB,CAAhBA,EAfEH,mBAec,CAAA,EAfQF,YAeR,CAfqBG,CAerB,SAf+BR,cAe/B,CAAA,KAAA,EAAA,CAAA,GAfyDS,CAezD,GAAA,OAAA,CAAA;EAAA,OAAA,UAAA,CAAA,MAAA,EAdPH,MAcO,CAAA,MAAA,EAAA,OAAA,CAAA,EAAA,OAKU,CALV,EAAA;IAChBA,IAAAA,CAAAA,EAAAA,MAAAA;IAI2BK,WAAAA,CAAAA,EAAAA,MAAAA;IAAfX,MAAAA,CAAAA,EAAAA,OAAAA;EAAc,CAAA,EAAuBW,aAAAA,CAAAA,EAf/CJ,mBAe+CI,CAAAA,EAfzBN,YAeyBM,CAfZL,MAeYK,CAAAA,MAAAA,EAAAA,OAAAA,CAAAA,CAAAA;EAAC;;;;;AAQ1C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JC,CAAID,CAAAA,EAAAA,gBAAAA,CAAiBC,CAAjBD,SAA2BV,cAA3BU,CAAAA,KAAAA,EAAAA,CAAAA,GAAqDD,CAArDC,GAAAA,KAAAA,CAAAA;AAAgB,iBACpFY,gBAAAA,CADoF,cAAA,EACnDR,gBADmD,CAAA,EAChCJ,gBADgC,CACfJ,MADe,CAAA,MAAA,EAAA,OAAA,CAAA,CAAA;AAC5G;;;;AAA4EI,KAKhEK,uBAAAA,GALgEL;EAAgB,yBAAA,EAAA,IAAA;AAK5F,CAAA;AAOA;;;;KAAYI,gBAAAA;;eAEKR"}
1
+ {"version":3,"file":"responses.d.cts","names":["InteropZodObject","InteropZodType","AIMessage","LanguageModelLike","FunctionDefinition","StructuredOutputParsingError","MultipleStructuredOutputsError","ResponseFormatUndefined","ToolStrategy","Record","ToolStrategyOptions","S","U","ProviderStrategy","T","ResponseFormat","transformResponseFormat","JsonSchemaFormat","TypedToolStrategy","Array","ToolStrategyError","Promise","toolStrategy","K","providerStrategy","hasSupportForJsonSchemaOutput"],"sources":["../../src/agents/responses.d.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable no-instanceof/no-instanceof */\nimport { InteropZodObject, InteropZodType } from \"@langchain/core/utils/types\";\nimport { type AIMessage } from \"@langchain/core/messages\";\nimport { type LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { type FunctionDefinition } from \"@langchain/core/language_models/base\";\nimport { StructuredOutputParsingError, MultipleStructuredOutputsError } from \"./errors.js\";\nimport type { ResponseFormatUndefined } from \"./annotation.js\";\n/**\n * Information for tracking structured output tool metadata.\n * This contains all necessary information to handle structured responses generated\n * via tool calls, including the original schema, its type classification, and the\n * corresponding tool implementation used by the tools strategy.\n */\nexport declare class ToolStrategy<_T = unknown> {\n readonly schema: Record<string, unknown>;\n readonly tool: {\n type: \"function\";\n function: FunctionDefinition;\n };\n readonly options?: ToolStrategyOptions | undefined;\n private constructor();\n get name(): string;\n static fromSchema<S extends InteropZodObject>(schema: S, outputOptions?: ToolStrategyOptions): ToolStrategy<S extends InteropZodType<infer U> ? U : unknown>;\n static fromSchema(schema: Record<string, unknown>, outputOptions?: ToolStrategyOptions): ToolStrategy<Record<string, unknown>>;\n /**\n * Parse tool arguments according to the schema.\n *\n * @throws {StructuredOutputParsingError} if the response is not valid\n * @param toolArgs - The arguments from the tool call\n * @returns The parsed response according to the schema type\n */\n parse(toolArgs: Record<string, unknown>): Record<string, unknown>;\n}\nexport declare class ProviderStrategy<T = unknown> {\n readonly schema: Record<string, unknown>;\n // @ts-expect-error - _schemaType is used only for type inference\n private _schemaType?;\n private constructor();\n static fromSchema<T>(schema: InteropZodType<T>): ProviderStrategy<T>;\n static fromSchema(schema: Record<string, unknown>): ProviderStrategy<Record<string, unknown>>;\n /**\n * Parse tool arguments according to the schema. If the response is not valid, return undefined.\n *\n * @param toolArgs - The arguments from the tool call\n * @returns The parsed response according to the schema type\n */\n parse(response: AIMessage): any;\n}\nexport type ResponseFormat = ToolStrategy<any> | ProviderStrategy<any>;\n/**\n * Handle user input for `responseFormat` parameter of `CreateAgentParams`.\n * This function defines the default behavior for the `responseFormat` parameter, which is:\n *\n * - if value is a Zod schema, default to structured output via tool calling\n * - if value is a JSON schema, default to structured output via tool calling\n * - if value is a custom response format, return it as is\n * - if value is an array, ensure all array elements are instance of `ToolStrategy`\n * @param responseFormat - The response format to transform, provided by the user\n * @param options - The response format options for tool strategy\n * @param model - The model to check if it supports JSON schema output\n * @returns\n */\nexport declare function transformResponseFormat(responseFormat?: InteropZodType<any> | InteropZodType<any>[] | JsonSchemaFormat | JsonSchemaFormat[] | ResponseFormat | ToolStrategy<any>[] | ResponseFormatUndefined, options?: ToolStrategyOptions, model?: LanguageModelLike | string): ResponseFormat[];\n/**\n * Branded type for ToolStrategy arrays that preserves type information\n */\nexport interface TypedToolStrategy<T = unknown> extends Array<ToolStrategy<any>> {\n _schemaType?: T;\n}\nexport type ToolStrategyError = StructuredOutputParsingError | MultipleStructuredOutputsError;\nexport interface ToolStrategyOptions {\n /**\n * Allows you to customize the message that appears in the conversation history when structured\n * output is generated.\n */\n toolMessageContent?: string;\n /**\n * Handle errors from the structured output tool call. Using tools to generate structured output\n * can cause errors, e.g. if:\n * - you provide multiple structured output schemas and the model calls multiple structured output tools\n * - if the structured output generated by the tool call doesn't match provided schema\n *\n * This property allows to handle these errors in different ways:\n * - `true` - retry the tool call\n * - `false` - throw an error\n * - `string` - retry the tool call with the provided message\n * - `(error: ToolStrategyError) => Promise<string> | string` - retry with the provided message or throw the error\n */\n handleError?: boolean | string | ((error: ToolStrategyError) => Promise<string> | string);\n}\nexport declare function toolStrategy<T extends InteropZodType<any>>(responseFormat: T, options?: ToolStrategyOptions): TypedToolStrategy<T extends InteropZodType<infer U> ? U : never>;\nexport declare function toolStrategy<T extends readonly InteropZodType<any>[]>(responseFormat: T, options?: ToolStrategyOptions): TypedToolStrategy<{\n [K in keyof T]: T[K] extends InteropZodType<infer U> ? U : never;\n}[number]>;\nexport declare function toolStrategy(responseFormat: JsonSchemaFormat, options?: ToolStrategyOptions): TypedToolStrategy<Record<string, unknown>>;\nexport declare function toolStrategy(responseFormat: JsonSchemaFormat[], options?: ToolStrategyOptions): TypedToolStrategy<Record<string, unknown>>;\nexport declare function providerStrategy<T extends InteropZodType<any>>(responseFormat: T): ProviderStrategy<T extends InteropZodType<infer U> ? U : never>;\nexport declare function providerStrategy(responseFormat: JsonSchemaFormat): ProviderStrategy<Record<string, unknown>>;\n/**\n * Type representing a JSON Schema object format.\n * This is a strict type that excludes ToolStrategy and ProviderStrategy instances.\n */\nexport type JsonSchemaFormat = {\n type: \"null\" | \"boolean\" | \"object\" | \"array\" | \"number\" | \"string\" | \"integer\";\n properties?: Record<string, unknown>;\n required?: string[];\n additionalProperties?: boolean;\n [key: string]: unknown;\n} & {\n // Brand to ensure this is not a ToolStrategy or ProviderStrategy\n __brand?: never;\n};\n/**\n * Identifies the models that support JSON schema output\n * @param model - The model to check\n * @returns True if the model supports JSON schema output, false otherwise\n */\nexport declare function hasSupportForJsonSchemaOutput(model?: LanguageModelLike | string): boolean;\n"],"mappings":";;;;;;;;;;;;;AAuBgHW,cAT3FH,YAS2FG,CAAAA,KAAAA,OAAAA,CAAAA,CAAAA;EAAC,SAASV,MAAAA,EARrGQ,MAQqGR,CAAAA,MAAAA,EAAAA,OAAAA,CAAAA;EAAc,SAAYW,IAAAA,EAAAA;IAAjDJ,IAAAA,EAAAA,UAAAA;IACrEC,QAAAA,EANZL,kBAMYK;EAAM,CAAA;EAAsD,SAAgBA,OAAAA,CAAAA,EAJnFC,mBAImFD,GAAAA,SAAAA;EAAM,QAAnBD,WAAAA,CAAAA;EAAY,IAQrFC,IAAAA,CAAAA,CAAAA,EAAAA,MAAAA;EAAM,OAAoBA,UAAAA,CAAAA,UATdT,gBAScS,CAAAA,CAAAA,MAAAA,EATYE,CASZF,EAAAA,aAAAA,CAAAA,EAT+BC,mBAS/BD,CAAAA,EATqDD,YASrDC,CATkEE,CASlEF,SAT4ER,cAS5EQ,CAAAA,KAAAA,EAAAA,CAAAA,GATsGG,CAStGH,GAAAA,OAAAA,CAAAA;EAAM,OAAA,UAAA,CAAA,MAAA,EARtBA,MAQsB,CAAA,MAAA,EAAA,OAAA,CAAA,EAAA,aAAA,CAAA,EARmBC,mBAQnB,CAAA,EARyCF,YAQzC,CARsDC,MAQtD,CAAA,MAAA,EAAA,OAAA,CAAA,CAAA;EAE/BI;;;;;;;EAKgD,KACvCJ,CAAAA,QAAAA,EARVA,MAQUA,CAAAA,MAAAA,EAAAA,OAAAA,CAAAA,CAAAA,EARgBA,MAQhBA,CAAAA,MAAAA,EAAAA,OAAAA,CAAAA;;AAA0BI,cANnCA,gBAMmCA,CAAAA,IAAAA,OAAAA,CAAAA,CAAAA;EAAgB,SAOpDX,MAAAA,EAZCO,MAYDP,CAAAA,MAAAA,EAAAA,OAAAA,CAAAA;EAAS;EAEjBa,QAAAA,WAAc;EAAA,QAAA,WAAA,CAAA;EAA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,GAAA,QAAA,GAAA,OAAA,GAAA,QAAA,GAAA,QAAA,GAAA,SAAA;EAAA,UAAiBA,CAAAA,EAOxCR,MAPwCQ,CAAAA,MAAAA,EAAAA,OAAAA,CAAAA;EAAgB,QAAoBR,CAAAA,EAAAA,MAAAA,EAAAA;EAAM,oBAAvBI,CAAAA,EAAAA,OAAAA;EAAgB,CAAA,GAAA,EAAA,MAAA,CAAA,EAAA,OAAA;AAK5F,CAAA,GAAYI"}
@@ -1,7 +1,7 @@
1
1
  import { MultipleStructuredOutputsError, StructuredOutputParsingError } from "./errors.js";
2
2
  import { AIMessage } from "@langchain/core/messages";
3
3
  import { InteropZodObject, InteropZodType } from "@langchain/core/utils/types";
4
- import { FunctionDefinition } from "@langchain/core/language_models/base";
4
+ import { FunctionDefinition, LanguageModelLike } from "@langchain/core/language_models/base";
5
5
 
6
6
  //#region src/agents/responses.d.ts
7
7
 
@@ -20,16 +20,8 @@ declare class ToolStrategy<_T = unknown> {
20
20
  readonly options?: ToolStrategyOptions | undefined;
21
21
  private constructor();
22
22
  get name(): string;
23
- static fromSchema<S extends InteropZodObject>(schema: S, options?: {
24
- name?: string;
25
- description?: string;
26
- strict?: boolean;
27
- }, outputOptions?: ToolStrategyOptions): ToolStrategy<S extends InteropZodType<infer U> ? U : unknown>;
28
- static fromSchema(schema: Record<string, unknown>, options?: {
29
- name?: string;
30
- description?: string;
31
- strict?: boolean;
32
- }, outputOptions?: ToolStrategyOptions): ToolStrategy<Record<string, unknown>>;
23
+ static fromSchema<S extends InteropZodObject>(schema: S, outputOptions?: ToolStrategyOptions): ToolStrategy<S extends InteropZodType<infer U> ? U : unknown>;
24
+ static fromSchema(schema: Record<string, unknown>, outputOptions?: ToolStrategyOptions): ToolStrategy<Record<string, unknown>>;
33
25
  /**
34
26
  * Parse tool arguments according to the schema.
35
27
  *
@@ -63,7 +55,9 @@ type ResponseFormat = ToolStrategy<any> | ProviderStrategy<any>;
63
55
  * - if value is a JSON schema, default to structured output via tool calling
64
56
  * - if value is a custom response format, return it as is
65
57
  * - if value is an array, ensure all array elements are instance of `ToolStrategy`
66
- * @param responseFormat
58
+ * @param responseFormat - The response format to transform, provided by the user
59
+ * @param options - The response format options for tool strategy
60
+ * @param model - The model to check if it supports JSON schema output
67
61
  * @returns
68
62
  */
69
63
 
@@ -100,13 +94,6 @@ declare function toolStrategy(responseFormat: JsonSchemaFormat, options?: ToolSt
100
94
  declare function toolStrategy(responseFormat: JsonSchemaFormat[], options?: ToolStrategyOptions): TypedToolStrategy<Record<string, unknown>>;
101
95
  declare function providerStrategy<T extends InteropZodType<any>>(responseFormat: T): ProviderStrategy<T extends InteropZodType<infer U> ? U : never>;
102
96
  declare function providerStrategy(responseFormat: JsonSchemaFormat): ProviderStrategy<Record<string, unknown>>;
103
- /**
104
- * Special type to indicate that no response format is provided.
105
- * When this type is used, the structuredResponse property should not be present in the result.
106
- */
107
- type ResponseFormatUndefined = {
108
- __responseFormatUndefined: true;
109
- };
110
97
  /**
111
98
  * Type representing a JSON Schema object format.
112
99
  * This is a strict type that excludes ToolStrategy and ProviderStrategy instances.
@@ -121,6 +108,11 @@ type JsonSchemaFormat = {
121
108
  // Brand to ensure this is not a ToolStrategy or ProviderStrategy
122
109
  __brand?: never;
123
110
  };
111
+ /**
112
+ * Identifies the models that support JSON schema output
113
+ * @param model - The model to check
114
+ * @returns True if the model supports JSON schema output, false otherwise
115
+ */
124
116
  //#endregion
125
- export { JsonSchemaFormat, ProviderStrategy, ResponseFormat, ResponseFormatUndefined, ToolStrategy, TypedToolStrategy, providerStrategy, toolStrategy };
117
+ export { JsonSchemaFormat, ProviderStrategy, ResponseFormat, ToolStrategy, TypedToolStrategy, providerStrategy, toolStrategy };
126
118
  //# sourceMappingURL=responses.d.ts.map