langchain 1.5.19 → 1.6.0

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 (42) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/agents/middleware/index.cjs +4 -0
  3. package/dist/agents/middleware/index.d.cts +4 -1
  4. package/dist/agents/middleware/index.d.ts +4 -1
  5. package/dist/agents/middleware/index.js +3 -1
  6. package/dist/agents/middleware/provider/openai/autoMode.cjs +51 -0
  7. package/dist/agents/middleware/provider/openai/autoMode.cjs.map +1 -0
  8. package/dist/agents/middleware/provider/openai/autoMode.d.cts +23 -0
  9. package/dist/agents/middleware/provider/openai/autoMode.d.cts.map +1 -0
  10. package/dist/agents/middleware/provider/openai/autoMode.d.ts +23 -0
  11. package/dist/agents/middleware/provider/openai/autoMode.d.ts.map +1 -0
  12. package/dist/agents/middleware/provider/openai/autoMode.js +51 -0
  13. package/dist/agents/middleware/provider/openai/autoMode.js.map +1 -0
  14. package/dist/agents/middleware/provider/openai/decisions.cjs +15 -0
  15. package/dist/agents/middleware/provider/openai/decisions.cjs.map +1 -0
  16. package/dist/agents/middleware/provider/openai/decisions.d.cts +36 -0
  17. package/dist/agents/middleware/provider/openai/decisions.d.cts.map +1 -0
  18. package/dist/agents/middleware/provider/openai/decisions.d.ts +36 -0
  19. package/dist/agents/middleware/provider/openai/decisions.d.ts.map +1 -0
  20. package/dist/agents/middleware/provider/openai/decisions.js +15 -0
  21. package/dist/agents/middleware/provider/openai/decisions.js.map +1 -0
  22. package/dist/agents/middleware/provider/openai/modelRouter.cjs +72 -0
  23. package/dist/agents/middleware/provider/openai/modelRouter.cjs.map +1 -0
  24. package/dist/agents/middleware/provider/openai/modelRouter.d.cts +39 -0
  25. package/dist/agents/middleware/provider/openai/modelRouter.d.cts.map +1 -0
  26. package/dist/agents/middleware/provider/openai/modelRouter.d.ts +39 -0
  27. package/dist/agents/middleware/provider/openai/modelRouter.d.ts.map +1 -0
  28. package/dist/agents/middleware/provider/openai/modelRouter.js +72 -0
  29. package/dist/agents/middleware/provider/openai/modelRouter.js.map +1 -0
  30. package/dist/agents/nodes/ToolNode.cjs +5 -4
  31. package/dist/agents/nodes/ToolNode.cjs.map +1 -1
  32. package/dist/agents/nodes/ToolNode.js +6 -5
  33. package/dist/agents/nodes/ToolNode.js.map +1 -1
  34. package/dist/browser.cjs +6 -0
  35. package/dist/browser.d.cts +4 -1
  36. package/dist/browser.d.ts +4 -1
  37. package/dist/browser.js +5 -1
  38. package/dist/index.cjs +6 -0
  39. package/dist/index.d.cts +4 -1
  40. package/dist/index.d.ts +4 -1
  41. package/dist/index.js +5 -1
  42. package/package.json +7 -7
@@ -0,0 +1,72 @@
1
+ import { initChatModel } from "../../../../chat_models/universal.js";
2
+ import { createMiddleware } from "../../../middleware.js";
3
+ import { decider } from "./decisions.js";
4
+ import { HumanMessage } from "@langchain/core/messages";
5
+ import { z } from "zod/v4";
6
+ //#region src/agents/middleware/provider/openai/modelRouter.ts
7
+ const routeSchema = z.object({
8
+ choice: z.string(),
9
+ confidence: z.number(),
10
+ probabilities: z.array(z.object({
11
+ value: z.string(),
12
+ probability: z.number()
13
+ }))
14
+ });
15
+ /**
16
+ * Routes each agent run to one of several models with the OpenAI Decisions API
17
+ * (beta).
18
+ *
19
+ * Classifies the latest human message once per run and stores the answer in
20
+ * `modelRoute`, then uses the chosen model for every model call in that run. With
21
+ * no human message, or a refusal, the agent's own model is used.
22
+ */
23
+ function openAIModelRouterMiddleware(options) {
24
+ const routes = Object.keys(options.choices);
25
+ if (!routes.length) throw new Error("openAIModelRouterMiddleware requires at least one choice.");
26
+ if (!options.instructions.trim()) throw new Error("openAIModelRouterMiddleware instructions must not be empty.");
27
+ const decide = decider(options.model, { model_route: {
28
+ type: "choice",
29
+ instructions: options.instructions,
30
+ choices: Object.fromEntries(routes.map((route) => [route, options.choices[route].criteria]))
31
+ } });
32
+ const models = /* @__PURE__ */ new Map();
33
+ const modelFor = (route) => {
34
+ if (!Object.hasOwn(options.choices, route)) throw new Error(`Unknown model route "${route}".`);
35
+ if (!models.has(route)) {
36
+ const choice = options.choices[route];
37
+ const pending = Promise.resolve(typeof choice.model === "string" ? initChatModel(choice.model) : choice.model);
38
+ pending.catch(() => models.delete(route));
39
+ models.set(route, pending);
40
+ }
41
+ return models.get(route);
42
+ };
43
+ return createMiddleware({
44
+ name: "OpenAIModelRouterMiddleware",
45
+ stateSchema: z.object({ modelRoute: routeSchema.nullable().optional() }),
46
+ async beforeAgent(state, runtime) {
47
+ const message = [...state.messages].reverse().find((message) => HumanMessage.isInstance(message));
48
+ if (!message) return { modelRoute: null };
49
+ const answer = await decide(message, runtime.signal);
50
+ if (answer?.type !== "choice") return { modelRoute: null };
51
+ if (!Object.hasOwn(options.choices, answer.choice)) throw new Error(`OpenAI Decisions selected unknown model route "${answer.choice}".`);
52
+ const { choice, confidence, probabilities } = answer;
53
+ return { modelRoute: {
54
+ choice,
55
+ confidence,
56
+ probabilities
57
+ } };
58
+ },
59
+ async wrapModelCall(request, handler) {
60
+ const route = request.state.modelRoute;
61
+ if (!route) return handler(request);
62
+ return handler({
63
+ ...request,
64
+ model: await modelFor(route.choice)
65
+ });
66
+ }
67
+ });
68
+ }
69
+ //#endregion
70
+ export { openAIModelRouterMiddleware };
71
+
72
+ //# sourceMappingURL=modelRouter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"modelRouter.js","names":[],"sources":["../../../../../src/agents/middleware/provider/openai/modelRouter.ts"],"sourcesContent":["import { z } from \"zod/v4\";\nimport { HumanMessage } from \"@langchain/core/messages\";\nimport { createMiddleware } from \"../../../middleware.js\";\nimport { initChatModel } from \"../../../../chat_models/universal.js\";\nimport type { AgentLanguageModelLike } from \"../../../model.js\";\nimport { decider, type OpenAIDecisionsLike } from \"./decisions.js\";\n\nexport interface ModelChoice {\n /** A chat model, or a model string accepted by `initChatModel`. */\n model: string | AgentLanguageModelLike;\n /** When to pick this model. */\n criteria: string;\n}\n\nexport interface OpenAIModelRouterMiddlewareOptions {\n /** Named models and the criterion for choosing each. */\n choices: Record<string, ModelChoice>;\n /** The routing question, e.g. \"Choose the least costly model for the task.\" */\n instructions: string;\n /** An `OpenAIDecisions` instance from `@langchain/openai`. */\n model: OpenAIDecisionsLike;\n}\n\nconst routeSchema = z.object({\n choice: z.string(),\n confidence: z.number(),\n probabilities: z.array(\n z.object({ value: z.string(), probability: z.number() })\n ),\n});\n\n/**\n * Routes each agent run to one of several models with the OpenAI Decisions API\n * (beta).\n *\n * Classifies the latest human message once per run and stores the answer in\n * `modelRoute`, then uses the chosen model for every model call in that run. With\n * no human message, or a refusal, the agent's own model is used.\n */\nexport function openAIModelRouterMiddleware(\n options: OpenAIModelRouterMiddlewareOptions\n) {\n const routes = Object.keys(options.choices);\n if (!routes.length)\n throw new Error(\n \"openAIModelRouterMiddleware requires at least one choice.\"\n );\n if (!options.instructions.trim())\n throw new Error(\n \"openAIModelRouterMiddleware instructions must not be empty.\"\n );\n const decide = decider(options.model, {\n model_route: {\n type: \"choice\",\n instructions: options.instructions,\n choices: Object.fromEntries(\n routes.map((route) => [route, options.choices[route].criteria])\n ),\n },\n });\n const models = new Map<string, Promise<AgentLanguageModelLike>>();\n const modelFor = (route: string) => {\n if (!Object.hasOwn(options.choices, route))\n throw new Error(`Unknown model route \"${route}\".`);\n if (!models.has(route)) {\n const choice = options.choices[route];\n const pending = Promise.resolve(\n typeof choice.model === \"string\"\n ? initChatModel(choice.model)\n : choice.model\n );\n pending.catch(() => models.delete(route));\n models.set(route, pending);\n }\n return models.get(route)!;\n };\n\n return createMiddleware({\n name: \"OpenAIModelRouterMiddleware\",\n stateSchema: z.object({ modelRoute: routeSchema.nullable().optional() }),\n async beforeAgent(state, runtime) {\n const message = [...state.messages]\n .reverse()\n .find((message) => HumanMessage.isInstance(message));\n if (!message) return { modelRoute: null };\n const answer = await decide(message, runtime.signal);\n if (answer?.type !== \"choice\") return { modelRoute: null };\n if (!Object.hasOwn(options.choices, answer.choice))\n throw new Error(\n `OpenAI Decisions selected unknown model route \"${answer.choice}\".`\n );\n const { choice, confidence, probabilities } = answer;\n return { modelRoute: { choice, confidence, probabilities } };\n },\n async wrapModelCall(request, handler) {\n const route = request.state.modelRoute;\n if (!route) return handler(request);\n return handler({ ...request, model: await modelFor(route.choice) });\n },\n });\n}\n"],"mappings":";;;;;;AAuBA,MAAM,cAAc,EAAE,OAAO;CAC3B,QAAQ,EAAE,OAAO;CACjB,YAAY,EAAE,OAAO;CACrB,eAAe,EAAE,MACf,EAAE,OAAO;EAAE,OAAO,EAAE,OAAO;EAAG,aAAa,EAAE,OAAO;CAAE,CAAC,CACzD;AACF,CAAC;;;;;;;;;AAUD,SAAgB,4BACd,SACA;CACA,MAAM,SAAS,OAAO,KAAK,QAAQ,OAAO;CAC1C,IAAI,CAAC,OAAO,QACV,MAAM,IAAI,MACR,2DACF;CACF,IAAI,CAAC,QAAQ,aAAa,KAAK,GAC7B,MAAM,IAAI,MACR,6DACF;CACF,MAAM,SAAS,QAAQ,QAAQ,OAAO,EACpC,aAAa;EACX,MAAM;EACN,cAAc,QAAQ;EACtB,SAAS,OAAO,YACd,OAAO,KAAK,UAAU,CAAC,OAAO,QAAQ,QAAQ,MAAM,CAAC,QAAQ,CAAC,CAChE;CACF,EACF,CAAC;CACD,MAAM,yBAAS,IAAI,IAA6C;CAChE,MAAM,YAAY,UAAkB;EAClC,IAAI,CAAC,OAAO,OAAO,QAAQ,SAAS,KAAK,GACvC,MAAM,IAAI,MAAM,wBAAwB,MAAM,GAAG;EACnD,IAAI,CAAC,OAAO,IAAI,KAAK,GAAG;GACtB,MAAM,SAAS,QAAQ,QAAQ;GAC/B,MAAM,UAAU,QAAQ,QACtB,OAAO,OAAO,UAAU,WACpB,cAAc,OAAO,KAAK,IAC1B,OAAO,KACb;GACA,QAAQ,YAAY,OAAO,OAAO,KAAK,CAAC;GACxC,OAAO,IAAI,OAAO,OAAO;EAC3B;EACA,OAAO,OAAO,IAAI,KAAK;CACzB;CAEA,OAAO,iBAAiB;EACtB,MAAM;EACN,aAAa,EAAE,OAAO,EAAE,YAAY,YAAY,SAAS,CAAC,CAAC,SAAS,EAAE,CAAC;EACvE,MAAM,YAAY,OAAO,SAAS;GAChC,MAAM,UAAU,CAAC,GAAG,MAAM,QAAQ,CAAC,CAChC,QAAQ,CAAC,CACT,MAAM,YAAY,aAAa,WAAW,OAAO,CAAC;GACrD,IAAI,CAAC,SAAS,OAAO,EAAE,YAAY,KAAK;GACxC,MAAM,SAAS,MAAM,OAAO,SAAS,QAAQ,MAAM;GACnD,IAAI,QAAQ,SAAS,UAAU,OAAO,EAAE,YAAY,KAAK;GACzD,IAAI,CAAC,OAAO,OAAO,QAAQ,SAAS,OAAO,MAAM,GAC/C,MAAM,IAAI,MACR,kDAAkD,OAAO,OAAO,GAClE;GACF,MAAM,EAAE,QAAQ,YAAY,kBAAkB;GAC9C,OAAO,EAAE,YAAY;IAAE;IAAQ;IAAY;GAAc,EAAE;EAC7D;EACA,MAAM,cAAc,SAAS,SAAS;GACpC,MAAM,QAAQ,QAAQ,MAAM;GAC5B,IAAI,CAAC,OAAO,OAAO,QAAQ,OAAO;GAClC,OAAO,QAAQ;IAAE,GAAG;IAAS,OAAO,MAAM,SAAS,MAAM,MAAM;GAAE,CAAC;EACpE;CACF,CAAC;AACH"}
@@ -118,11 +118,12 @@ var ToolNode = class extends require_RunnableCallable.RunnableCallable {
118
118
  */
119
119
  #handleError(error, call, isMiddlewareError) {
120
120
  /**
121
- * {@link NodeInterrupt} errors are a breakpoint to bring a human into the loop.
122
- * As such, they are not recoverable by the agent and shouldn't be fed
123
- * back. Instead, re-throw these errors even when `handleToolErrors = true`.
121
+ * {@link NodeInterrupt} errors are a breakpoint to bring a human into the loop,
122
+ * and a drain stops the run to resume it later. Neither is recoverable
123
+ * by the agent, so neither is fed back: re-throw them even when
124
+ * `handleToolErrors = true`.
124
125
  */
125
- if ((0, _langchain_langgraph.isGraphInterrupt)(error)) throw error;
126
+ if ((0, _langchain_langgraph.isGraphInterrupt)(error) || (0, _langchain_langgraph.isGraphDrained)(error)) throw error;
126
127
  /**
127
128
  * If the signal is aborted, we want to bubble up the error to the invoke caller.
128
129
  */
@@ -1 +1 @@
1
- {"version":3,"file":"ToolNode.cjs","names":["BaseMessage","ToolInvocationError","ToolMessage","RunnableCallable","isGraphInterrupt","MiddlewareError","mergeAbortSignals","isCommand","ToolInputParsingException","AIMessage","Command","Send"],"sources":["../../../src/agents/nodes/ToolNode.ts"],"sourcesContent":["/* oxlint-disable @typescript-eslint/no-explicit-any */\n/* oxlint-disable no-instanceof/no-instanceof */\nimport { BaseMessage, ToolMessage, AIMessage } 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 type LangGraphRunnableConfig,\n StateDefinitionInit,\n} from \"@langchain/langgraph\";\n\nimport { RunnableCallable } from \"../RunnableCallable.js\";\nimport { mergeAbortSignals } from \"./utils.js\";\nimport { MiddlewareError, ToolInvocationError } from \"../errors.js\";\nimport type {\n WrapToolCallHook,\n ToolCallRequest,\n ToAnnotationRoot,\n} from \"../middleware/types.js\";\nimport type { AgentBuiltInState } from \"../runtime.js\";\n\n/**\n * Error message template for when middleware adds tools that can't be executed.\n * This happens when middleware modifies tools in wrapModelCall but doesn't provide\n * a wrapToolCall handler to execute them.\n */\nconst getInvalidToolError = (\n toolName: string,\n availableTools: string[]\n): string =>\n `Error: ${toolName} is not a valid tool, try one of [${availableTools.join(\", \")}].`;\n\n/**\n * The name of the tool node in the state graph.\n */\nexport const TOOLS_NODE_NAME = \"tools\";\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 * **Default behavior** (matches Python):\n * - Catches only `ToolInvocationError` (invalid arguments from model) and converts to ToolMessage\n * - Re-raises all other errors including errors from `wrapToolCall` middleware\n *\n * If `true`:\n * - Catches all errors and returns a ToolMessage with the error\n *\n * If `false`:\n * - All errors are thrown immediately\n *\n * If a function is provided:\n * - If function returns a `ToolMessage`, use it as the result\n * - If function returns `undefined`, re-raise the error\n *\n * @default A function that only catches ToolInvocationError\n */\n handleToolErrors?:\n | boolean\n | ((error: unknown, toolCall: ToolCall) => ToolMessage | undefined);\n /**\n * Optional wrapper function for tool execution.\n * Allows middleware to intercept and modify tool calls before execution.\n * The wrapper receives the tool call request and a handler function to execute the tool.\n */\n wrapToolCall?: WrapToolCallHook;\n /** Graph channels to read for tool-call-only Send inputs. */\n stateKeys?: string[];\n}\n\nconst isBaseMessageArray = (input: unknown): input is BaseMessage[] =>\n Array.isArray(input) && input.every(BaseMessage.isInstance);\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 = (\n input: unknown\n): input is { lg_tool_call: ToolCall; jumpTo?: string } =>\n typeof input === \"object\" && input != null && \"lg_tool_call\" in input;\n\n/**\n * Default error handler for tool errors.\n *\n * This is applied to errors from baseHandler (tool execution).\n * For errors from wrapToolCall middleware, those are handled separately\n * and will bubble up by default.\n *\n * Catches all tool execution errors and converts them to ToolMessage.\n * This allows the LLM to see the error and potentially retry with different arguments.\n */\nfunction defaultHandleToolErrors(\n error: unknown,\n toolCall: ToolCall\n): ToolMessage | undefined {\n if (ToolInvocationError.isInstance(error)) {\n return new ToolMessage({\n content: error.message,\n tool_call_id: toolCall.id!,\n name: toolCall.name,\n status: \"error\",\n });\n }\n /**\n * Catch all other tool errors and convert to ToolMessage\n */\n return new ToolMessage({\n content: `${error}\\n Please fix your mistakes.`,\n tool_call_id: toolCall.id!,\n name: toolCall.name,\n status: \"error\",\n });\n}\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 StateDefinitionInit = any,\n ContextSchema extends 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) =\n defaultHandleToolErrors;\n\n wrapToolCall: WrapToolCallHook | undefined;\n\n constructor(\n tools: (StructuredToolInterface | DynamicTool | RunnableToolLike)[],\n public options?: ToolNodeOptions\n ) {\n const { name, tags, handleToolErrors, signal, wrapToolCall } =\n options ?? {};\n super({\n name,\n tags,\n func: (state, config) =>\n this.run(\n state as ToAnnotationRoot<StateDefinitionInit>[\"State\"] &\n AgentBuiltInState,\n config as RunnableConfig\n ),\n });\n this.tools = tools;\n this.handleToolErrors = handleToolErrors ?? this.handleToolErrors;\n this.signal = signal;\n this.wrapToolCall = wrapToolCall;\n }\n\n /**\n * Handle errors from tool execution or middleware.\n * @param error - The error to handle\n * @param call - The tool call that caused the error\n * @param isMiddlewareError - Whether the error came from wrapToolCall middleware\n * @returns ToolMessage if error is handled, otherwise re-throws\n */\n #handleError(\n error: unknown,\n call: ToolCall,\n isMiddlewareError: boolean\n ): ToolMessage {\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 if (isGraphInterrupt(error)) {\n throw error;\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 error;\n }\n\n /**\n * A recoverable tool error (e.g. tool-input schema validation) can be\n * rewrapped as a {@link MiddlewareError} with the original error on `.cause`\n * — once per `wrapToolCall` middleware, so it may be nested several layers\n * deep. Walk the cause chain to the root; if it's a {@link ToolInvocationError},\n * unwrap it so the intended `handleToolErrors` self-correction path still\n * applies. Genuine middleware errors stay fatal by default.\n */\n let effectiveError = error;\n let errorFromMiddleware = isMiddlewareError;\n if (isMiddlewareError) {\n let unwrapped: unknown = error;\n while (MiddlewareError.isInstance(unwrapped)) {\n unwrapped = unwrapped.cause;\n }\n if (ToolInvocationError.isInstance(unwrapped)) {\n effectiveError = unwrapped;\n errorFromMiddleware = false;\n }\n }\n\n /**\n * If error is from middleware and handleToolErrors is not true, bubble up\n * (default handler and false both re-raise middleware errors)\n */\n if (errorFromMiddleware && this.handleToolErrors !== true) {\n throw effectiveError;\n }\n\n /**\n * If handleToolErrors is false, throw all errors\n */\n if (!this.handleToolErrors) {\n throw effectiveError;\n }\n\n /**\n * Apply handleToolErrors to the error\n */\n if (typeof this.handleToolErrors === \"function\") {\n const result = this.handleToolErrors(effectiveError, call);\n if (result && ToolMessage.isInstance(result)) {\n result.status ??= \"error\";\n return result;\n }\n\n /**\n * `handleToolErrors` returned undefined - re-raise\n */\n throw effectiveError;\n } else if (this.handleToolErrors) {\n return new ToolMessage({\n name: call.name,\n content: `${effectiveError}\\n Please fix your mistakes.`,\n tool_call_id: call.id!,\n status: \"error\",\n });\n }\n\n /**\n * Shouldn't reach here, but throw as fallback\n */\n throw effectiveError;\n }\n\n protected async runTool(\n call: ToolCall,\n config: RunnableConfig,\n state: AgentBuiltInState\n ): Promise<ToolMessage | Command> {\n /**\n * Build runtime from LangGraph config\n */\n const lgConfig = config as LangGraphRunnableConfig;\n const runtime = {\n context: lgConfig?.context,\n store: lgConfig?.store,\n configurable: lgConfig?.configurable,\n writer: lgConfig?.writer,\n interrupt: lgConfig?.interrupt,\n signal: lgConfig?.signal,\n };\n\n /**\n * Find the tool instance to include in the request.\n * For dynamically registered tools, this may be undefined.\n */\n const registeredTool = this.tools.find((t) => t.name === call.name);\n\n /**\n * Define the base handler that executes the tool.\n * When wrapToolCall middleware is present, this handler does NOT catch errors\n * so the middleware can handle them.\n * When no middleware, errors are caught and handled here.\n *\n * The handler now accepts an overridden tool from the request, allowing\n * middleware to provide tool implementations for dynamically registered tools.\n */\n const baseHandler = async (\n request: ToolCallRequest\n ): Promise<ToolMessage | Command> => {\n const { toolCall, tool: requestTool } = request;\n\n /**\n * Use the tool from the request (which may be overridden via spread syntax)\n * or fall back to finding it in registered tools.\n * This allows middleware to provide dynamic tool implementations.\n */\n const tool =\n requestTool ?? this.tools.find((t) => t.name === toolCall.name);\n\n if (tool === undefined) {\n /**\n * Tool not found - return a graceful error message rather than throwing.\n * This allows the LLM to see the error and potentially retry.\n */\n const availableTools = this.tools.map((t) => t.name);\n return new ToolMessage({\n content: getInvalidToolError(toolCall.name, availableTools),\n tool_call_id: toolCall.id!,\n name: toolCall.name,\n status: \"error\",\n });\n }\n\n /**\n * Cast tool to a common invokable type.\n * The tool can be from registered tools (StructuredToolInterface | DynamicTool | RunnableToolLike)\n * or from middleware override (ClientTool | ServerTool).\n */\n const invokableTool = tool as\n | StructuredToolInterface\n | DynamicTool\n | RunnableToolLike;\n\n try {\n const output = await invokableTool.invoke(\n { ...toolCall, type: \"tool_call\" },\n {\n ...config,\n /**\n * extend to match ToolRuntime\n */\n config,\n toolCallId: toolCall.id!,\n state,\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: invokableTool.name,\n content: typeof output === \"string\" ? output : JSON.stringify(output),\n tool_call_id: toolCall.id!,\n });\n } catch (e: unknown) {\n /**\n * Handle errors from tool execution (not from wrapToolCall)\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, toolCall);\n }\n /**\n * Re-throw to be handled by caller\n */\n throw e;\n }\n };\n\n /**\n * Create request object for middleware\n * Cast to ToolCallRequest<AgentBuiltInState> to satisfy type constraints\n * of wrapToolCall which expects AgentBuiltInState\n */\n const request: ToolCallRequest<AgentBuiltInState> = {\n toolCall: call,\n tool: registeredTool,\n state,\n runtime,\n };\n\n /**\n * If wrapToolCall is provided, use it to wrap the tool execution\n */\n if (this.wrapToolCall) {\n try {\n return await this.wrapToolCall(request, baseHandler);\n } catch (e: unknown) {\n /**\n * Handle middleware errors\n */\n return this.#handleError(e, call, true);\n }\n }\n\n /**\n * No wrapToolCall - if tool wasn't found, return graceful error\n */\n if (!registeredTool) {\n const availableTools = this.tools.map((t) => t.name);\n return new ToolMessage({\n content: getInvalidToolError(call.name, availableTools),\n tool_call_id: call.id!,\n name: call.name,\n status: \"error\",\n });\n }\n\n /**\n * No wrapToolCall - execute tool directly and handle errors here\n */\n try {\n return await baseHandler(request);\n } catch (e: unknown) {\n /**\n * Handle tool errors when no middleware provided\n */\n return this.#handleError(e, call, false);\n }\n }\n\n protected async run(\n state: ToAnnotationRoot<StateSchema>[\"State\"] & AgentBuiltInState,\n config: RunnableConfig\n ): Promise<ContextSchema> {\n let outputs: (ToolMessage | Command)[];\n\n if (isSendInput(state)) {\n const { lg_tool_call: _, jumpTo: __, ...newState } = state;\n let toolState = newState;\n if (Object.keys(newState).length === 0 && this.options?.stateKeys) {\n const read = config.configurable?.__pregel_read;\n if (typeof read !== \"function\") {\n throw new Error(\n \"ToolNode requires a graph state reader for compact Send inputs.\"\n );\n }\n toolState = read(this.options.stateKeys, true);\n if (!isMessagesState(toolState)) {\n throw new Error(\"ToolNode could not read messages from graph state.\");\n }\n const scratchpad = config.configurable?.__pregel_scratchpad;\n if (scratchpad) {\n scratchpad.currentTaskInput = { ...toolState, ...state };\n }\n }\n outputs = [await this.runTool(state.lg_tool_call, config, toolState)];\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, state)) ?? []\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":";;;;;;;;;;;;AAmCA,MAAM,uBACJ,UACA,mBAEA,UAAU,SAAS,oCAAoC,eAAe,KAAK,IAAI,EAAE;;;;AAKnF,MAAa,kBAAkB;AA+C/B,MAAM,sBAAsB,UAC1B,MAAM,QAAQ,KAAK,KAAK,MAAM,MAAMA,yBAAAA,YAAY,UAAU;AAE5D,MAAM,mBACJ,UAEA,OAAO,UAAU,YACjB,SAAS,QACT,cAAc,SACd,mBAAmB,MAAM,QAAQ;AAEnC,MAAM,eACJ,UAEA,OAAO,UAAU,YAAY,SAAS,QAAQ,kBAAkB;;;;;;;;;;;AAYlE,SAAS,wBACP,OACA,UACyB;CACzB,IAAIC,eAAAA,oBAAoB,WAAW,KAAK,GACtC,OAAO,IAAIC,yBAAAA,YAAY;EACrB,SAAS,MAAM;EACf,cAAc,SAAS;EACvB,MAAM,SAAS;EACf,QAAQ;CACV,CAAC;;;;CAKH,OAAO,IAAIA,yBAAAA,YAAY;EACrB,SAAS,GAAG,MAAM;EAClB,cAAc,SAAS;EACvB,MAAM,SAAS;EACf,QAAQ;CACV,CAAC;AACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,I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aAAa;EAGpC,OAAO;CACT;AACF;AAEA,SAAgB,OAAO,GAAuB;CAC5C,OAAO,aAAaC,qBAAAA;AACtB"}
1
+ {"version":3,"file":"ToolNode.cjs","names":["BaseMessage","ToolInvocationError","ToolMessage","RunnableCallable","isGraphInterrupt","isGraphDrained","MiddlewareError","mergeAbortSignals","isCommand","ToolInputParsingException","AIMessage","Command","Send"],"sources":["../../../src/agents/nodes/ToolNode.ts"],"sourcesContent":["/* oxlint-disable @typescript-eslint/no-explicit-any */\n/* oxlint-disable no-instanceof/no-instanceof */\nimport { BaseMessage, ToolMessage, AIMessage } 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 isGraphDrained,\n isGraphInterrupt,\n type LangGraphRunnableConfig,\n StateDefinitionInit,\n} from \"@langchain/langgraph\";\n\nimport { RunnableCallable } from \"../RunnableCallable.js\";\nimport { mergeAbortSignals } from \"./utils.js\";\nimport { MiddlewareError, ToolInvocationError } from \"../errors.js\";\nimport type {\n WrapToolCallHook,\n ToolCallRequest,\n ToAnnotationRoot,\n} from \"../middleware/types.js\";\nimport type { AgentBuiltInState } from \"../runtime.js\";\n\n/**\n * Error message template for when middleware adds tools that can't be executed.\n * This happens when middleware modifies tools in wrapModelCall but doesn't provide\n * a wrapToolCall handler to execute them.\n */\nconst getInvalidToolError = (\n toolName: string,\n availableTools: string[]\n): string =>\n `Error: ${toolName} is not a valid tool, try one of [${availableTools.join(\", \")}].`;\n\n/**\n * The name of the tool node in the state graph.\n */\nexport const TOOLS_NODE_NAME = \"tools\";\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 * **Default behavior** (matches Python):\n * - Catches only `ToolInvocationError` (invalid arguments from model) and converts to ToolMessage\n * - Re-raises all other errors including errors from `wrapToolCall` middleware\n *\n * If `true`:\n * - Catches all errors and returns a ToolMessage with the error\n *\n * If `false`:\n * - All errors are thrown immediately\n *\n * If a function is provided:\n * - If function returns a `ToolMessage`, use it as the result\n * - If function returns `undefined`, re-raise the error\n *\n * @default A function that only catches ToolInvocationError\n */\n handleToolErrors?:\n | boolean\n | ((error: unknown, toolCall: ToolCall) => ToolMessage | undefined);\n /**\n * Optional wrapper function for tool execution.\n * Allows middleware to intercept and modify tool calls before execution.\n * The wrapper receives the tool call request and a handler function to execute the tool.\n */\n wrapToolCall?: WrapToolCallHook;\n /** Graph channels to read for tool-call-only Send inputs. */\n stateKeys?: string[];\n}\n\nconst isBaseMessageArray = (input: unknown): input is BaseMessage[] =>\n Array.isArray(input) && input.every(BaseMessage.isInstance);\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 = (\n input: unknown\n): input is { lg_tool_call: ToolCall; jumpTo?: string } =>\n typeof input === \"object\" && input != null && \"lg_tool_call\" in input;\n\n/**\n * Default error handler for tool errors.\n *\n * This is applied to errors from baseHandler (tool execution).\n * For errors from wrapToolCall middleware, those are handled separately\n * and will bubble up by default.\n *\n * Catches all tool execution errors and converts them to ToolMessage.\n * This allows the LLM to see the error and potentially retry with different arguments.\n */\nfunction defaultHandleToolErrors(\n error: unknown,\n toolCall: ToolCall\n): ToolMessage | undefined {\n if (ToolInvocationError.isInstance(error)) {\n return new ToolMessage({\n content: error.message,\n tool_call_id: toolCall.id!,\n name: toolCall.name,\n status: \"error\",\n });\n }\n /**\n * Catch all other tool errors and convert to ToolMessage\n */\n return new ToolMessage({\n content: `${error}\\n Please fix your mistakes.`,\n tool_call_id: toolCall.id!,\n name: toolCall.name,\n status: \"error\",\n });\n}\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 StateDefinitionInit = any,\n ContextSchema extends 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) =\n defaultHandleToolErrors;\n\n wrapToolCall: WrapToolCallHook | undefined;\n\n constructor(\n tools: (StructuredToolInterface | DynamicTool | RunnableToolLike)[],\n public options?: ToolNodeOptions\n ) {\n const { name, tags, handleToolErrors, signal, wrapToolCall } =\n options ?? {};\n super({\n name,\n tags,\n func: (state, config) =>\n this.run(\n state as ToAnnotationRoot<StateDefinitionInit>[\"State\"] &\n AgentBuiltInState,\n config as RunnableConfig\n ),\n });\n this.tools = tools;\n this.handleToolErrors = handleToolErrors ?? this.handleToolErrors;\n this.signal = signal;\n this.wrapToolCall = wrapToolCall;\n }\n\n /**\n * Handle errors from tool execution or middleware.\n * @param error - The error to handle\n * @param call - The tool call that caused the error\n * @param isMiddlewareError - Whether the error came from wrapToolCall middleware\n * @returns ToolMessage if error is handled, otherwise re-throws\n */\n #handleError(\n error: unknown,\n call: ToolCall,\n isMiddlewareError: boolean\n ): ToolMessage {\n /**\n * {@link NodeInterrupt} errors are a breakpoint to bring a human into the loop,\n * and a drain stops the run to resume it later. Neither is recoverable\n * by the agent, so neither is fed back: re-throw them even when\n * `handleToolErrors = true`.\n */\n if (isGraphInterrupt(error) || isGraphDrained(error)) {\n throw error;\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 error;\n }\n\n /**\n * A recoverable tool error (e.g. tool-input schema validation) can be\n * rewrapped as a {@link MiddlewareError} with the original error on `.cause`\n * — once per `wrapToolCall` middleware, so it may be nested several layers\n * deep. Walk the cause chain to the root; if it's a {@link ToolInvocationError},\n * unwrap it so the intended `handleToolErrors` self-correction path still\n * applies. Genuine middleware errors stay fatal by default.\n */\n let effectiveError = error;\n let errorFromMiddleware = isMiddlewareError;\n if (isMiddlewareError) {\n let unwrapped: unknown = error;\n while (MiddlewareError.isInstance(unwrapped)) {\n unwrapped = unwrapped.cause;\n }\n if (ToolInvocationError.isInstance(unwrapped)) {\n effectiveError = unwrapped;\n errorFromMiddleware = false;\n }\n }\n\n /**\n * If error is from middleware and handleToolErrors is not true, bubble up\n * (default handler and false both re-raise middleware errors)\n */\n if (errorFromMiddleware && this.handleToolErrors !== true) {\n throw effectiveError;\n }\n\n /**\n * If handleToolErrors is false, throw all errors\n */\n if (!this.handleToolErrors) {\n throw effectiveError;\n }\n\n /**\n * Apply handleToolErrors to the error\n */\n if (typeof this.handleToolErrors === \"function\") {\n const result = this.handleToolErrors(effectiveError, call);\n if (result && ToolMessage.isInstance(result)) {\n result.status ??= \"error\";\n return result;\n }\n\n /**\n * `handleToolErrors` returned undefined - re-raise\n */\n throw effectiveError;\n } else if (this.handleToolErrors) {\n return new ToolMessage({\n name: call.name,\n content: `${effectiveError}\\n Please fix your mistakes.`,\n tool_call_id: call.id!,\n status: \"error\",\n });\n }\n\n /**\n * Shouldn't reach here, but throw as fallback\n */\n throw effectiveError;\n }\n\n protected async runTool(\n call: ToolCall,\n config: RunnableConfig,\n state: AgentBuiltInState\n ): Promise<ToolMessage | Command> {\n /**\n * Build runtime from LangGraph config\n */\n const lgConfig = config as LangGraphRunnableConfig;\n const runtime = {\n context: lgConfig?.context,\n store: lgConfig?.store,\n configurable: lgConfig?.configurable,\n writer: lgConfig?.writer,\n interrupt: lgConfig?.interrupt,\n signal: lgConfig?.signal,\n };\n\n /**\n * Find the tool instance to include in the request.\n * For dynamically registered tools, this may be undefined.\n */\n const registeredTool = this.tools.find((t) => t.name === call.name);\n\n /**\n * Define the base handler that executes the tool.\n * When wrapToolCall middleware is present, this handler does NOT catch errors\n * so the middleware can handle them.\n * When no middleware, errors are caught and handled here.\n *\n * The handler now accepts an overridden tool from the request, allowing\n * middleware to provide tool implementations for dynamically registered tools.\n */\n const baseHandler = async (\n request: ToolCallRequest\n ): Promise<ToolMessage | Command> => {\n const { toolCall, tool: requestTool } = request;\n\n /**\n * Use the tool from the request (which may be overridden via spread syntax)\n * or fall back to finding it in registered tools.\n * This allows middleware to provide dynamic tool implementations.\n */\n const tool =\n requestTool ?? this.tools.find((t) => t.name === toolCall.name);\n\n if (tool === undefined) {\n /**\n * Tool not found - return a graceful error message rather than throwing.\n * This allows the LLM to see the error and potentially retry.\n */\n const availableTools = this.tools.map((t) => t.name);\n return new ToolMessage({\n content: getInvalidToolError(toolCall.name, availableTools),\n tool_call_id: toolCall.id!,\n name: toolCall.name,\n status: \"error\",\n });\n }\n\n /**\n * Cast tool to a common invokable type.\n * The tool can be from registered tools (StructuredToolInterface | DynamicTool | RunnableToolLike)\n * or from middleware override (ClientTool | ServerTool).\n */\n const invokableTool = tool as\n | StructuredToolInterface\n | DynamicTool\n | RunnableToolLike;\n\n try {\n const output = await invokableTool.invoke(\n { ...toolCall, type: \"tool_call\" },\n {\n ...config,\n /**\n * extend to match ToolRuntime\n */\n config,\n toolCallId: toolCall.id!,\n state,\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: invokableTool.name,\n content: typeof output === \"string\" ? output : JSON.stringify(output),\n tool_call_id: toolCall.id!,\n });\n } catch (e: unknown) {\n /**\n * Handle errors from tool execution (not from wrapToolCall)\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, toolCall);\n }\n /**\n * Re-throw to be handled by caller\n */\n throw e;\n }\n };\n\n /**\n * Create request object for middleware\n * Cast to ToolCallRequest<AgentBuiltInState> to satisfy type constraints\n * of wrapToolCall which expects AgentBuiltInState\n */\n const request: ToolCallRequest<AgentBuiltInState> = {\n toolCall: call,\n tool: registeredTool,\n state,\n runtime,\n };\n\n /**\n * If wrapToolCall is provided, use it to wrap the tool execution\n */\n if (this.wrapToolCall) {\n try {\n return await this.wrapToolCall(request, baseHandler);\n } catch (e: unknown) {\n /**\n * Handle middleware errors\n */\n return this.#handleError(e, call, true);\n }\n }\n\n /**\n * No wrapToolCall - if tool wasn't found, return graceful error\n */\n if (!registeredTool) {\n const availableTools = this.tools.map((t) => t.name);\n return new ToolMessage({\n content: getInvalidToolError(call.name, availableTools),\n tool_call_id: call.id!,\n name: call.name,\n status: \"error\",\n });\n }\n\n /**\n * No wrapToolCall - execute tool directly and handle errors here\n */\n try {\n return await baseHandler(request);\n } catch (e: unknown) {\n /**\n * Handle tool errors when no middleware provided\n */\n return this.#handleError(e, call, false);\n }\n }\n\n protected async run(\n state: ToAnnotationRoot<StateSchema>[\"State\"] & AgentBuiltInState,\n config: RunnableConfig\n ): Promise<ContextSchema> {\n let outputs: (ToolMessage | Command)[];\n\n if (isSendInput(state)) {\n const { lg_tool_call: _, jumpTo: __, ...newState } = state;\n let toolState = newState;\n if (Object.keys(newState).length === 0 && this.options?.stateKeys) {\n const read = config.configurable?.__pregel_read;\n if (typeof read !== \"function\") {\n throw new Error(\n \"ToolNode requires a graph state reader for compact Send inputs.\"\n );\n }\n toolState = read(this.options.stateKeys, true);\n if (!isMessagesState(toolState)) {\n throw new Error(\"ToolNode could not read messages from graph state.\");\n }\n const scratchpad = config.configurable?.__pregel_scratchpad;\n if (scratchpad) {\n scratchpad.currentTaskInput = { ...toolState, ...state };\n }\n }\n outputs = [await this.runTool(state.lg_tool_call, config, toolState)];\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, state)) ?? []\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":";;;;;;;;;;;;AAoCA,MAAM,uBACJ,UACA,mBAEA,UAAU,SAAS,oCAAoC,eAAe,KAAK,IAAI,EAAE;;;;AAKnF,MAAa,kBAAkB;AA+C/B,MAAM,sBAAsB,UAC1B,MAAM,QAAQ,KAAK,KAAK,MAAM,MAAMA,yBAAAA,YAAY,UAAU;AAE5D,MAAM,mBACJ,UAEA,OAAO,UAAU,YACjB,SAAS,QACT,cAAc,SACd,mBAAmB,MAAM,QAAQ;AAEnC,MAAM,eACJ,UAEA,OAAO,UAAU,YAAY,SAAS,QAAQ,kBAAkB;;;;;;;;;;;AAYlE,SAAS,wBACP,OACA,UACyB;CACzB,IAAIC,eAAAA,oBAAoB,WAAW,KAAK,GACtC,OAAO,IAAIC,yBAAAA,YAAY;EACrB,SAAS,MAAM;EACf,cAAc,SAAS;EACvB,MAAM,SAAS;EACf,QAAQ;CACV,CAAC;;;;CAKH,OAAO,IAAIA,yBAAAA,YAAY;EACrB,SAAS,GAAG,MAAM;EAClB,cAAc,SAAS;EACvB,MAAM,SAAS;EACf,QAAQ;CACV,CAAC;AACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA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AAE,CACzD;EAIJ,IAAI,eACF,gBAAgB,KAAK,aAAa;EAGpC,OAAO;CACT;AACF;AAEA,SAAgB,OAAO,GAAuB;CAC5C,OAAO,aAAaC,qBAAAA;AACtB"}
@@ -3,7 +3,7 @@ import { RunnableCallable } from "../RunnableCallable.js";
3
3
  import { mergeAbortSignals } from "./utils.js";
4
4
  import { AIMessage, BaseMessage, ToolMessage } from "@langchain/core/messages";
5
5
  import { ToolInputParsingException } from "@langchain/core/tools";
6
- import { Command, Send, isCommand, isGraphInterrupt } from "@langchain/langgraph";
6
+ import { Command, Send, isCommand, isGraphDrained, isGraphInterrupt } from "@langchain/langgraph";
7
7
  //#region src/agents/nodes/ToolNode.ts
8
8
  /**
9
9
  * Error message template for when middleware adds tools that can't be executed.
@@ -118,11 +118,12 @@ var ToolNode = class extends RunnableCallable {
118
118
  */
119
119
  #handleError(error, call, isMiddlewareError) {
120
120
  /**
121
- * {@link NodeInterrupt} errors are a breakpoint to bring a human into the loop.
122
- * As such, they are not recoverable by the agent and shouldn't be fed
123
- * back. Instead, re-throw these errors even when `handleToolErrors = true`.
121
+ * {@link NodeInterrupt} errors are a breakpoint to bring a human into the loop,
122
+ * and a drain stops the run to resume it later. Neither is recoverable
123
+ * by the agent, so neither is fed back: re-throw them even when
124
+ * `handleToolErrors = true`.
124
125
  */
125
- if (isGraphInterrupt(error)) throw error;
126
+ if (isGraphInterrupt(error) || isGraphDrained(error)) throw error;
126
127
  /**
127
128
  * If the signal is aborted, we want to bubble up the error to the invoke caller.
128
129
  */
@@ -1 +1 @@
1
- {"version":3,"file":"ToolNode.js","names":[],"sources":["../../../src/agents/nodes/ToolNode.ts"],"sourcesContent":["/* oxlint-disable @typescript-eslint/no-explicit-any */\n/* oxlint-disable no-instanceof/no-instanceof */\nimport { BaseMessage, ToolMessage, AIMessage } 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 type LangGraphRunnableConfig,\n StateDefinitionInit,\n} from \"@langchain/langgraph\";\n\nimport { RunnableCallable } from \"../RunnableCallable.js\";\nimport { mergeAbortSignals } from \"./utils.js\";\nimport { MiddlewareError, ToolInvocationError } from \"../errors.js\";\nimport type {\n WrapToolCallHook,\n ToolCallRequest,\n ToAnnotationRoot,\n} from \"../middleware/types.js\";\nimport type { AgentBuiltInState } from \"../runtime.js\";\n\n/**\n * Error message template for when middleware adds tools that can't be executed.\n * This happens when middleware modifies tools in wrapModelCall but doesn't provide\n * a wrapToolCall handler to execute them.\n */\nconst getInvalidToolError = (\n toolName: string,\n availableTools: string[]\n): string =>\n `Error: ${toolName} is not a valid tool, try one of [${availableTools.join(\", \")}].`;\n\n/**\n * The name of the tool node in the state graph.\n */\nexport const TOOLS_NODE_NAME = \"tools\";\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 * **Default behavior** (matches Python):\n * - Catches only `ToolInvocationError` (invalid arguments from model) and converts to ToolMessage\n * - Re-raises all other errors including errors from `wrapToolCall` middleware\n *\n * If `true`:\n * - Catches all errors and returns a ToolMessage with the error\n *\n * If `false`:\n * - All errors are thrown immediately\n *\n * If a function is provided:\n * - If function returns a `ToolMessage`, use it as the result\n * - If function returns `undefined`, re-raise the error\n *\n * @default A function that only catches ToolInvocationError\n */\n handleToolErrors?:\n | boolean\n | ((error: unknown, toolCall: ToolCall) => ToolMessage | undefined);\n /**\n * Optional wrapper function for tool execution.\n * Allows middleware to intercept and modify tool calls before execution.\n * The wrapper receives the tool call request and a handler function to execute the tool.\n */\n wrapToolCall?: WrapToolCallHook;\n /** Graph channels to read for tool-call-only Send inputs. */\n stateKeys?: string[];\n}\n\nconst isBaseMessageArray = (input: unknown): input is BaseMessage[] =>\n Array.isArray(input) && input.every(BaseMessage.isInstance);\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 = (\n input: unknown\n): input is { lg_tool_call: ToolCall; jumpTo?: string } =>\n typeof input === \"object\" && input != null && \"lg_tool_call\" in input;\n\n/**\n * Default error handler for tool errors.\n *\n * This is applied to errors from baseHandler (tool execution).\n * For errors from wrapToolCall middleware, those are handled separately\n * and will bubble up by default.\n *\n * Catches all tool execution errors and converts them to ToolMessage.\n * This allows the LLM to see the error and potentially retry with different arguments.\n */\nfunction defaultHandleToolErrors(\n error: unknown,\n toolCall: ToolCall\n): ToolMessage | undefined {\n if (ToolInvocationError.isInstance(error)) {\n return new ToolMessage({\n content: error.message,\n tool_call_id: toolCall.id!,\n name: toolCall.name,\n status: \"error\",\n });\n }\n /**\n * Catch all other tool errors and convert to ToolMessage\n */\n return new ToolMessage({\n content: `${error}\\n Please fix your mistakes.`,\n tool_call_id: toolCall.id!,\n name: toolCall.name,\n status: \"error\",\n });\n}\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 StateDefinitionInit = any,\n ContextSchema extends 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) =\n defaultHandleToolErrors;\n\n wrapToolCall: WrapToolCallHook | undefined;\n\n constructor(\n tools: (StructuredToolInterface | DynamicTool | RunnableToolLike)[],\n public options?: ToolNodeOptions\n ) {\n const { name, tags, handleToolErrors, signal, wrapToolCall } =\n options ?? {};\n super({\n name,\n tags,\n func: (state, config) =>\n this.run(\n state as ToAnnotationRoot<StateDefinitionInit>[\"State\"] &\n AgentBuiltInState,\n config as RunnableConfig\n ),\n });\n this.tools = tools;\n this.handleToolErrors = handleToolErrors ?? this.handleToolErrors;\n this.signal = signal;\n this.wrapToolCall = wrapToolCall;\n }\n\n /**\n * Handle errors from tool execution or middleware.\n * @param error - The error to handle\n * @param call - The tool call that caused the error\n * @param isMiddlewareError - Whether the error came from wrapToolCall middleware\n * @returns ToolMessage if error is handled, otherwise re-throws\n */\n #handleError(\n error: unknown,\n call: ToolCall,\n isMiddlewareError: boolean\n ): ToolMessage {\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 if (isGraphInterrupt(error)) {\n throw error;\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 error;\n }\n\n /**\n * A recoverable tool error (e.g. tool-input schema validation) can be\n * rewrapped as a {@link MiddlewareError} with the original error on `.cause`\n * — once per `wrapToolCall` middleware, so it may be nested several layers\n * deep. Walk the cause chain to the root; if it's a {@link ToolInvocationError},\n * unwrap it so the intended `handleToolErrors` self-correction path still\n * applies. Genuine middleware errors stay fatal by default.\n */\n let effectiveError = error;\n let errorFromMiddleware = isMiddlewareError;\n if (isMiddlewareError) {\n let unwrapped: unknown = error;\n while (MiddlewareError.isInstance(unwrapped)) {\n unwrapped = unwrapped.cause;\n }\n if (ToolInvocationError.isInstance(unwrapped)) {\n effectiveError = unwrapped;\n errorFromMiddleware = false;\n }\n }\n\n /**\n * If error is from middleware and handleToolErrors is not true, bubble up\n * (default handler and false both re-raise middleware errors)\n */\n if (errorFromMiddleware && this.handleToolErrors !== true) {\n throw effectiveError;\n }\n\n /**\n * If handleToolErrors is false, throw all errors\n */\n if (!this.handleToolErrors) {\n throw effectiveError;\n }\n\n /**\n * Apply handleToolErrors to the error\n */\n if (typeof this.handleToolErrors === \"function\") {\n const result = this.handleToolErrors(effectiveError, call);\n if (result && ToolMessage.isInstance(result)) {\n result.status ??= \"error\";\n return result;\n }\n\n /**\n * `handleToolErrors` returned undefined - re-raise\n */\n throw effectiveError;\n } else if (this.handleToolErrors) {\n return new ToolMessage({\n name: call.name,\n content: `${effectiveError}\\n Please fix your mistakes.`,\n tool_call_id: call.id!,\n status: \"error\",\n });\n }\n\n /**\n * Shouldn't reach here, but throw as fallback\n */\n throw effectiveError;\n }\n\n protected async runTool(\n call: ToolCall,\n config: RunnableConfig,\n state: AgentBuiltInState\n ): Promise<ToolMessage | Command> {\n /**\n * Build runtime from LangGraph config\n */\n const lgConfig = config as LangGraphRunnableConfig;\n const runtime = {\n context: lgConfig?.context,\n store: lgConfig?.store,\n configurable: lgConfig?.configurable,\n writer: lgConfig?.writer,\n interrupt: lgConfig?.interrupt,\n signal: lgConfig?.signal,\n };\n\n /**\n * Find the tool instance to include in the request.\n * For dynamically registered tools, this may be undefined.\n */\n const registeredTool = this.tools.find((t) => t.name === call.name);\n\n /**\n * Define the base handler that executes the tool.\n * When wrapToolCall middleware is present, this handler does NOT catch errors\n * so the middleware can handle them.\n * When no middleware, errors are caught and handled here.\n *\n * The handler now accepts an overridden tool from the request, allowing\n * middleware to provide tool implementations for dynamically registered tools.\n */\n const baseHandler = async (\n request: ToolCallRequest\n ): Promise<ToolMessage | Command> => {\n const { toolCall, tool: requestTool } = request;\n\n /**\n * Use the tool from the request (which may be overridden via spread syntax)\n * or fall back to finding it in registered tools.\n * This allows middleware to provide dynamic tool implementations.\n */\n const tool =\n requestTool ?? this.tools.find((t) => t.name === toolCall.name);\n\n if (tool === undefined) {\n /**\n * Tool not found - return a graceful error message rather than throwing.\n * This allows the LLM to see the error and potentially retry.\n */\n const availableTools = this.tools.map((t) => t.name);\n return new ToolMessage({\n content: getInvalidToolError(toolCall.name, availableTools),\n tool_call_id: toolCall.id!,\n name: toolCall.name,\n status: \"error\",\n });\n }\n\n /**\n * Cast tool to a common invokable type.\n * The tool can be from registered tools (StructuredToolInterface | DynamicTool | RunnableToolLike)\n * or from middleware override (ClientTool | ServerTool).\n */\n const invokableTool = tool as\n | StructuredToolInterface\n | DynamicTool\n | RunnableToolLike;\n\n try {\n const output = await invokableTool.invoke(\n { ...toolCall, type: \"tool_call\" },\n {\n ...config,\n /**\n * extend to match ToolRuntime\n */\n config,\n toolCallId: toolCall.id!,\n state,\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: invokableTool.name,\n content: typeof output === \"string\" ? output : JSON.stringify(output),\n tool_call_id: toolCall.id!,\n });\n } catch (e: unknown) {\n /**\n * Handle errors from tool execution (not from wrapToolCall)\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, toolCall);\n }\n /**\n * Re-throw to be handled by caller\n */\n throw e;\n }\n };\n\n /**\n * Create request object for middleware\n * Cast to ToolCallRequest<AgentBuiltInState> to satisfy type constraints\n * of wrapToolCall which expects AgentBuiltInState\n */\n const request: ToolCallRequest<AgentBuiltInState> = {\n toolCall: call,\n tool: registeredTool,\n state,\n runtime,\n };\n\n /**\n * If wrapToolCall is provided, use it to wrap the tool execution\n */\n if (this.wrapToolCall) {\n try {\n return await this.wrapToolCall(request, baseHandler);\n } catch (e: unknown) {\n /**\n * Handle middleware errors\n */\n return this.#handleError(e, call, true);\n }\n }\n\n /**\n * No wrapToolCall - if tool wasn't found, return graceful error\n */\n if (!registeredTool) {\n const availableTools = this.tools.map((t) => t.name);\n return new ToolMessage({\n content: getInvalidToolError(call.name, availableTools),\n tool_call_id: call.id!,\n name: call.name,\n status: \"error\",\n });\n }\n\n /**\n * No wrapToolCall - execute tool directly and handle errors here\n */\n try {\n return await baseHandler(request);\n } catch (e: unknown) {\n /**\n * Handle tool errors when no middleware provided\n */\n return this.#handleError(e, call, false);\n }\n }\n\n protected async run(\n state: ToAnnotationRoot<StateSchema>[\"State\"] & AgentBuiltInState,\n config: RunnableConfig\n ): Promise<ContextSchema> {\n let outputs: (ToolMessage | Command)[];\n\n if (isSendInput(state)) {\n const { lg_tool_call: _, jumpTo: __, ...newState } = state;\n let toolState = newState;\n if (Object.keys(newState).length === 0 && this.options?.stateKeys) {\n const read = config.configurable?.__pregel_read;\n if (typeof read !== \"function\") {\n throw new Error(\n \"ToolNode requires a graph state reader for compact Send inputs.\"\n );\n }\n toolState = read(this.options.stateKeys, true);\n if (!isMessagesState(toolState)) {\n throw new Error(\"ToolNode could not read messages from graph state.\");\n }\n const scratchpad = config.configurable?.__pregel_scratchpad;\n if (scratchpad) {\n scratchpad.currentTaskInput = { ...toolState, ...state };\n }\n }\n outputs = [await this.runTool(state.lg_tool_call, config, toolState)];\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, state)) ?? []\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":";;;;;;;;;;;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UAAU,SACnB,IAAI,UAAU,MAAM,GAAG;GACrB,IACE,OAAO,UAAU,QAAQ,UACzB,MAAM,QAAQ,OAAO,IAAI,KACzB,OAAO,KAAK,OAAO,SAAS,OAAO,IAAI,CAAC,GACxC;IACA,IAAI,eACF,cAAe,KAAgB,KAAK,GAAI,OAAO,IAAe;SAE9D,gBAAgB,IAAI,QAAQ;KAC1B,OAAO,QAAQ;KACf,MAAM,OAAO;IACf,CAAC;GAEL,OACE,gBAAgB,KAAK,MAAM;EAE/B,OACE,gBAAgB,KACd,MAAM,QAAQ,KAAK,IAAI,CAAC,MAAM,IAAI,EAAE,UAAU,CAAC,MAAM,EAAE,CACzD;EAIJ,IAAI,eACF,gBAAgB,KAAK,aAAa;EAGpC,OAAO;CACT;AACF;AAEA,SAAgB,OAAO,GAAuB;CAC5C,OAAO,aAAa;AACtB"}
1
+ {"version":3,"file":"ToolNode.js","names":[],"sources":["../../../src/agents/nodes/ToolNode.ts"],"sourcesContent":["/* oxlint-disable @typescript-eslint/no-explicit-any */\n/* oxlint-disable no-instanceof/no-instanceof */\nimport { BaseMessage, ToolMessage, AIMessage } 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 isGraphDrained,\n isGraphInterrupt,\n type LangGraphRunnableConfig,\n StateDefinitionInit,\n} from \"@langchain/langgraph\";\n\nimport { RunnableCallable } from \"../RunnableCallable.js\";\nimport { mergeAbortSignals } from \"./utils.js\";\nimport { MiddlewareError, ToolInvocationError } from \"../errors.js\";\nimport type {\n WrapToolCallHook,\n ToolCallRequest,\n ToAnnotationRoot,\n} from \"../middleware/types.js\";\nimport type { AgentBuiltInState } from \"../runtime.js\";\n\n/**\n * Error message template for when middleware adds tools that can't be executed.\n * This happens when middleware modifies tools in wrapModelCall but doesn't provide\n * a wrapToolCall handler to execute them.\n */\nconst getInvalidToolError = (\n toolName: string,\n availableTools: string[]\n): string =>\n `Error: ${toolName} is not a valid tool, try one of [${availableTools.join(\", \")}].`;\n\n/**\n * The name of the tool node in the state graph.\n */\nexport const TOOLS_NODE_NAME = \"tools\";\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 * **Default behavior** (matches Python):\n * - Catches only `ToolInvocationError` (invalid arguments from model) and converts to ToolMessage\n * - Re-raises all other errors including errors from `wrapToolCall` middleware\n *\n * If `true`:\n * - Catches all errors and returns a ToolMessage with the error\n *\n * If `false`:\n * - All errors are thrown immediately\n *\n * If a function is provided:\n * - If function returns a `ToolMessage`, use it as the result\n * - If function returns `undefined`, re-raise the error\n *\n * @default A function that only catches ToolInvocationError\n */\n handleToolErrors?:\n | boolean\n | ((error: unknown, toolCall: ToolCall) => ToolMessage | undefined);\n /**\n * Optional wrapper function for tool execution.\n * Allows middleware to intercept and modify tool calls before execution.\n * The wrapper receives the tool call request and a handler function to execute the tool.\n */\n wrapToolCall?: WrapToolCallHook;\n /** Graph channels to read for tool-call-only Send inputs. */\n stateKeys?: string[];\n}\n\nconst isBaseMessageArray = (input: unknown): input is BaseMessage[] =>\n Array.isArray(input) && input.every(BaseMessage.isInstance);\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 = (\n input: unknown\n): input is { lg_tool_call: ToolCall; jumpTo?: string } =>\n typeof input === \"object\" && input != null && \"lg_tool_call\" in input;\n\n/**\n * Default error handler for tool errors.\n *\n * This is applied to errors from baseHandler (tool execution).\n * For errors from wrapToolCall middleware, those are handled separately\n * and will bubble up by default.\n *\n * Catches all tool execution errors and converts them to ToolMessage.\n * This allows the LLM to see the error and potentially retry with different arguments.\n */\nfunction defaultHandleToolErrors(\n error: unknown,\n toolCall: ToolCall\n): ToolMessage | undefined {\n if (ToolInvocationError.isInstance(error)) {\n return new ToolMessage({\n content: error.message,\n tool_call_id: toolCall.id!,\n name: toolCall.name,\n status: \"error\",\n });\n }\n /**\n * Catch all other tool errors and convert to ToolMessage\n */\n return new ToolMessage({\n content: `${error}\\n Please fix your mistakes.`,\n tool_call_id: toolCall.id!,\n name: toolCall.name,\n status: \"error\",\n });\n}\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 StateDefinitionInit = any,\n ContextSchema extends 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) =\n defaultHandleToolErrors;\n\n wrapToolCall: WrapToolCallHook | undefined;\n\n constructor(\n tools: (StructuredToolInterface | DynamicTool | RunnableToolLike)[],\n public options?: ToolNodeOptions\n ) {\n const { name, tags, handleToolErrors, signal, wrapToolCall } =\n options ?? {};\n super({\n name,\n tags,\n func: (state, config) =>\n this.run(\n state as ToAnnotationRoot<StateDefinitionInit>[\"State\"] &\n AgentBuiltInState,\n config as RunnableConfig\n ),\n });\n this.tools = tools;\n this.handleToolErrors = handleToolErrors ?? this.handleToolErrors;\n this.signal = signal;\n this.wrapToolCall = wrapToolCall;\n }\n\n /**\n * Handle errors from tool execution or middleware.\n * @param error - The error to handle\n * @param call - The tool call that caused the error\n * @param isMiddlewareError - Whether the error came from wrapToolCall middleware\n * @returns ToolMessage if error is handled, otherwise re-throws\n */\n #handleError(\n error: unknown,\n call: ToolCall,\n isMiddlewareError: boolean\n ): ToolMessage {\n /**\n * {@link NodeInterrupt} errors are a breakpoint to bring a human into the loop,\n * and a drain stops the run to resume it later. Neither is recoverable\n * by the agent, so neither is fed back: re-throw them even when\n * `handleToolErrors = true`.\n */\n if (isGraphInterrupt(error) || isGraphDrained(error)) {\n throw error;\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 error;\n }\n\n /**\n * A recoverable tool error (e.g. tool-input schema validation) can be\n * rewrapped as a {@link MiddlewareError} with the original error on `.cause`\n * — once per `wrapToolCall` middleware, so it may be nested several layers\n * deep. Walk the cause chain to the root; if it's a {@link ToolInvocationError},\n * unwrap it so the intended `handleToolErrors` self-correction path still\n * applies. Genuine middleware errors stay fatal by default.\n */\n let effectiveError = error;\n let errorFromMiddleware = isMiddlewareError;\n if (isMiddlewareError) {\n let unwrapped: unknown = error;\n while (MiddlewareError.isInstance(unwrapped)) {\n unwrapped = unwrapped.cause;\n }\n if (ToolInvocationError.isInstance(unwrapped)) {\n effectiveError = unwrapped;\n errorFromMiddleware = false;\n }\n }\n\n /**\n * If error is from middleware and handleToolErrors is not true, bubble up\n * (default handler and false both re-raise middleware errors)\n */\n if (errorFromMiddleware && this.handleToolErrors !== true) {\n throw effectiveError;\n }\n\n /**\n * If handleToolErrors is false, throw all errors\n */\n if (!this.handleToolErrors) {\n throw effectiveError;\n }\n\n /**\n * Apply handleToolErrors to the error\n */\n if (typeof this.handleToolErrors === \"function\") {\n const result = this.handleToolErrors(effectiveError, call);\n if (result && ToolMessage.isInstance(result)) {\n result.status ??= \"error\";\n return result;\n }\n\n /**\n * `handleToolErrors` returned undefined - re-raise\n */\n throw effectiveError;\n } else if (this.handleToolErrors) {\n return new ToolMessage({\n name: call.name,\n content: `${effectiveError}\\n Please fix your mistakes.`,\n tool_call_id: call.id!,\n status: \"error\",\n });\n }\n\n /**\n * Shouldn't reach here, but throw as fallback\n */\n throw effectiveError;\n }\n\n protected async runTool(\n call: ToolCall,\n config: RunnableConfig,\n state: AgentBuiltInState\n ): Promise<ToolMessage | Command> {\n /**\n * Build runtime from LangGraph config\n */\n const lgConfig = config as LangGraphRunnableConfig;\n const runtime = {\n context: lgConfig?.context,\n store: lgConfig?.store,\n configurable: lgConfig?.configurable,\n writer: lgConfig?.writer,\n interrupt: lgConfig?.interrupt,\n signal: lgConfig?.signal,\n };\n\n /**\n * Find the tool instance to include in the request.\n * For dynamically registered tools, this may be undefined.\n */\n const registeredTool = this.tools.find((t) => t.name === call.name);\n\n /**\n * Define the base handler that executes the tool.\n * When wrapToolCall middleware is present, this handler does NOT catch errors\n * so the middleware can handle them.\n * When no middleware, errors are caught and handled here.\n *\n * The handler now accepts an overridden tool from the request, allowing\n * middleware to provide tool implementations for dynamically registered tools.\n */\n const baseHandler = async (\n request: ToolCallRequest\n ): Promise<ToolMessage | Command> => {\n const { toolCall, tool: requestTool } = request;\n\n /**\n * Use the tool from the request (which may be overridden via spread syntax)\n * or fall back to finding it in registered tools.\n * This allows middleware to provide dynamic tool implementations.\n */\n const tool =\n requestTool ?? this.tools.find((t) => t.name === toolCall.name);\n\n if (tool === undefined) {\n /**\n * Tool not found - return a graceful error message rather than throwing.\n * This allows the LLM to see the error and potentially retry.\n */\n const availableTools = this.tools.map((t) => t.name);\n return new ToolMessage({\n content: getInvalidToolError(toolCall.name, availableTools),\n tool_call_id: toolCall.id!,\n name: toolCall.name,\n status: \"error\",\n });\n }\n\n /**\n * Cast tool to a common invokable type.\n * The tool can be from registered tools (StructuredToolInterface | DynamicTool | RunnableToolLike)\n * or from middleware override (ClientTool | ServerTool).\n */\n const invokableTool = tool as\n | StructuredToolInterface\n | DynamicTool\n | RunnableToolLike;\n\n try {\n const output = await invokableTool.invoke(\n { ...toolCall, type: \"tool_call\" },\n {\n ...config,\n /**\n * extend to match ToolRuntime\n */\n config,\n toolCallId: toolCall.id!,\n state,\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: invokableTool.name,\n content: typeof output === \"string\" ? output : JSON.stringify(output),\n tool_call_id: toolCall.id!,\n });\n } catch (e: unknown) {\n /**\n * Handle errors from tool execution (not from wrapToolCall)\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, toolCall);\n }\n /**\n * Re-throw to be handled by caller\n */\n throw e;\n }\n };\n\n /**\n * Create request object for middleware\n * Cast to ToolCallRequest<AgentBuiltInState> to satisfy type constraints\n * of wrapToolCall which expects AgentBuiltInState\n */\n const request: ToolCallRequest<AgentBuiltInState> = {\n toolCall: call,\n tool: registeredTool,\n state,\n runtime,\n };\n\n /**\n * If wrapToolCall is provided, use it to wrap the tool execution\n */\n if (this.wrapToolCall) {\n try {\n return await this.wrapToolCall(request, baseHandler);\n } catch (e: unknown) {\n /**\n * Handle middleware errors\n */\n return this.#handleError(e, call, true);\n }\n }\n\n /**\n * No wrapToolCall - if tool wasn't found, return graceful error\n */\n if (!registeredTool) {\n const availableTools = this.tools.map((t) => t.name);\n return new ToolMessage({\n content: getInvalidToolError(call.name, availableTools),\n tool_call_id: call.id!,\n name: call.name,\n status: \"error\",\n });\n }\n\n /**\n * No wrapToolCall - execute tool directly and handle errors here\n */\n try {\n return await baseHandler(request);\n } catch (e: unknown) {\n /**\n * Handle tool errors when no middleware provided\n */\n return this.#handleError(e, call, false);\n }\n }\n\n protected async run(\n state: ToAnnotationRoot<StateSchema>[\"State\"] & AgentBuiltInState,\n config: RunnableConfig\n ): Promise<ContextSchema> {\n let outputs: (ToolMessage | Command)[];\n\n if (isSendInput(state)) {\n const { lg_tool_call: _, jumpTo: __, ...newState } = state;\n let toolState = newState;\n if (Object.keys(newState).length === 0 && this.options?.stateKeys) {\n const read = config.configurable?.__pregel_read;\n if (typeof read !== \"function\") {\n throw new Error(\n \"ToolNode requires a graph state reader for compact Send inputs.\"\n );\n }\n toolState = read(this.options.stateKeys, true);\n if (!isMessagesState(toolState)) {\n throw new Error(\"ToolNode could not read messages from graph state.\");\n }\n const scratchpad = config.configurable?.__pregel_scratchpad;\n if (scratchpad) {\n scratchpad.currentTaskInput = { ...toolState, ...state };\n }\n }\n outputs = [await this.runTool(state.lg_tool_call, config, toolState)];\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, state)) ?? []\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":";;;;;;;;;;;;AAoCA,MAAM,uBACJ,UACA,mBAEA,UAAU,SAAS,oCAAoC,eAAe,KAAK,IAAI,EAAE;;;;AAKnF,MAAa,kBAAkB;AA+C/B,MAAM,sBAAsB,UAC1B,MAAM,QAAQ,KAAK,KAAK,MAAM,MAAM,YAAY,UAAU;AAE5D,MAAM,mBACJ,UAEA,OAAO,UAAU,YACjB,SAAS,QACT,cAAc,SACd,mBAAmB,MAAM,QAAQ;AAEnC,MAAM,eACJ,UAEA,OAAO,UAAU,YAAY,SAAS,QAAQ,kBAAkB;;;;;;;;;;;AAYlE,SAAS,wBACP,OACA,UACyB;CACzB,IAAI,oBAAoB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AI,EAAE,UAAU,CAAC,MAAM,EAAE,CACzD;EAIJ,IAAI,eACF,gBAAgB,KAAK,aAAa;EAGpC,OAAO;CACT;AACF;AAEA,SAAgB,OAAO,GAAuB;CAC5C,OAAO,aAAa;AACtB"}
package/dist/browser.cjs CHANGED
@@ -30,6 +30,8 @@ const require_providerToolSearch = require("./agents/middleware/providerToolSear
30
30
  const require_moderation = require("./agents/middleware/provider/openai/moderation.cjs");
31
31
  const require_promptCaching = require("./agents/middleware/provider/anthropic/promptCaching.cjs");
32
32
  const require_promptCaching$1 = require("./agents/middleware/provider/aws/promptCaching.cjs");
33
+ const require_autoMode = require("./agents/middleware/provider/openai/autoMode.cjs");
34
+ const require_modelRouter = require("./agents/middleware/provider/openai/modelRouter.cjs");
33
35
  require("./agents/middleware/index.cjs");
34
36
  let _langchain_core_messages = require("@langchain/core/messages");
35
37
  let _langchain_core_tools = require("@langchain/core/tools");
@@ -94,6 +96,8 @@ var browser_exports = /* @__PURE__ */ require_runtime.__exportAll({
94
96
  modelCallLimitMiddleware: () => require_modelCallLimit.modelCallLimitMiddleware,
95
97
  modelFallbackMiddleware: () => require_modelFallback.modelFallbackMiddleware,
96
98
  modelRetryMiddleware: () => require_modelRetry.modelRetryMiddleware,
99
+ openAIAutoModeMiddleware: () => require_autoMode.openAIAutoModeMiddleware,
100
+ openAIModelRouterMiddleware: () => require_modelRouter.openAIModelRouterMiddleware,
97
101
  openAIModerationMiddleware: () => require_moderation.openAIModerationMiddleware,
98
102
  piiMiddleware: () => require_pii.piiMiddleware,
99
103
  piiRedactionMiddleware: () => require_piiRedaction.piiRedactionMiddleware,
@@ -272,6 +276,8 @@ exports.llmToolSelectorMiddleware = require_llmToolSelector.llmToolSelectorMiddl
272
276
  exports.modelCallLimitMiddleware = require_modelCallLimit.modelCallLimitMiddleware;
273
277
  exports.modelFallbackMiddleware = require_modelFallback.modelFallbackMiddleware;
274
278
  exports.modelRetryMiddleware = require_modelRetry.modelRetryMiddleware;
279
+ exports.openAIAutoModeMiddleware = require_autoMode.openAIAutoModeMiddleware;
280
+ exports.openAIModelRouterMiddleware = require_modelRouter.openAIModelRouterMiddleware;
275
281
  exports.openAIModerationMiddleware = require_moderation.openAIModerationMiddleware;
276
282
  exports.piiMiddleware = require_pii.piiMiddleware;
277
283
  exports.piiRedactionMiddleware = require_piiRedaction.piiRedactionMiddleware;
@@ -34,6 +34,9 @@ import { OpenAIModerationMiddlewareOptions, openAIModerationMiddleware } from ".
34
34
  import { PromptCachingMiddlewareConfig, anthropicPromptCachingMiddleware } from "./agents/middleware/provider/anthropic/promptCaching.cjs";
35
35
  import { BedrockConversePromptCachingMiddlewareConfig, bedrockPromptCachingMiddleware } from "./agents/middleware/provider/aws/promptCaching.cjs";
36
36
  import { countTokensApproximately } from "./agents/middleware/utils.cjs";
37
+ import { OpenAIDecisionsLike } from "./agents/middleware/provider/openai/decisions.cjs";
38
+ import { OpenAIAutoModeMiddlewareOptions, openAIAutoModeMiddleware } from "./agents/middleware/provider/openai/autoMode.cjs";
39
+ import { ModelChoice, OpenAIModelRouterMiddlewareOptions, openAIModelRouterMiddleware } from "./agents/middleware/provider/openai/modelRouter.cjs";
37
40
  import "./agents/middleware/index.cjs";
38
41
  import { AIMessage, AIMessageChunk, BaseMessage, BaseMessageChunk, ContentBlock, HumanMessage, HumanMessageChunk, SystemMessage, SystemMessageChunk, ToolMessage, ToolMessageChunk, filterMessages, trimMessages } from "@langchain/core/messages";
39
42
  import { DynamicStructuredTool, DynamicTool, StructuredTool, Tool, ToolRuntime } from "@langchain/core/tools";
@@ -41,4 +44,4 @@ import { context } from "@langchain/core/utils/context";
41
44
  import { InMemoryStore } from "@langchain/core/stores";
42
45
  import { Document, DocumentInput } from "@langchain/core/documents";
43
46
  import { LangChainMatchers, fakeModel, langchainMatchers } from "@langchain/core/testing";
44
- export { AIMessage, AIMessageChunk, Action, ActionRequest, type AfterAgentHook, type AfterModelHook, type AgentMiddleware, type AgentRunStream, AgentTypeConfig, type AnyAgentMiddleware, type AnyAnnotationRoot, ApproveDecision, BaseMessage, BaseMessageChunk, type BedrockConversePromptCachingMiddlewareConfig, type BeforeAgentHook, type BeforeModelHook, type BuiltInPIIType, BuiltInState, ClearToolUsesEdit, type ClearToolUsesEditConfig, CombineStreamTransformers, CombineTools, type ContentBlock, type ContextEdit, type ContextEditingMiddlewareConfig, CreateAgentParams, Decision, DecisionType, DefaultAgentTypeConfig, type DefaultMiddlewareTypeConfig, DescriptionFactory, Document, type DocumentInput, DynamicStructuredTool, type DynamicSystemPromptMiddlewareConfig, DynamicTool, EditDecision, ExecutedToolCall, ExtractZodArrayTypes, FakeToolCallingModel, HITLRequest, HITLResponse, type HeadlessTool, type HeadlessToolFields, type HeadlessToolImplementation, HumanInTheLoopMiddlewareConfig, HumanMessage, HumanMessageChunk, InMemoryStore, InferAgentContext, InferAgentContextSchema, InferAgentMiddleware, InferAgentResponse, InferAgentState, InferAgentStateSchema, InferAgentStreamTransformers, InferAgentTools, InferAgentType, type InferChannelType, type InferContextInput, type InferMergedInputState, type InferMergedState, type InferMiddlewareContext, type InferMiddlewareContextInput, type InferMiddlewareContextInputs, type InferMiddlewareContextSchema, type InferMiddlewareContexts, type InferMiddlewareFullContext, type InferMiddlewareInputState, type InferMiddlewareInputStates, type InferMiddlewareSchema, type InferMiddlewareState, type InferMiddlewareStates, InferMiddlewareStreamTransformers, InferMiddlewareStreamTransformersArray, type InferMiddlewareStreamTransformersFromConfig, InferMiddlewareTools, InferMiddlewareToolsArray, type InferMiddlewareToolsFromConfig, type InferMiddlewareType, type InferSchemaInput, type InferSchemaUpdateType, type InferSchemaValue, type InferSchemaValueType, Interrupt, InterruptOnConfig, JumpTo, type JumpToTarget, type LLMToolSelectorConfig, type LangChainMatchers, MIDDLEWARE_BRAND, MiddlewareError, type MiddlewareResult, type MiddlewareTypeConfig, type ModelCallLimitMiddlewareConfig, ModelRequest, type ModelRetryMiddlewareConfig, MultipleStructuredOutputsError, MultipleToolsBoundError, N, type NormalizedSchemaInput, type NormalizedSchemaUpdate, type OpenAIModerationMiddlewareOptions, PIIDetectionError, type PIIDetector, type PIIMatch, type PIIMiddlewareConfig, type PIIRedactionMiddlewareConfig, type PIIStrategy, type PromptCachingMiddlewareConfig, ProviderStrategy, type ProviderToolSearchMiddlewareConfig, type ReactAgent, type RedactionRuleConfig, RejectDecision, ResolveAgentTypeConfig, type ResolveMiddlewareTypeConfig, type ResolvedRedactionRule, RespondDecision, type ResponseFormat, type ResponseFormatUndefined, ReviewConfig, type Runtime, StructuredOutputParsingError, StructuredTool, type SubagentRunStream, type SummarizationMiddlewareConfig, SystemMessage, SystemMessageChunk, TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, type ToAnnotationRoot, type Todo, type TodoListMiddlewareOptions, type TokenCounter, Tool, ToolApprovalDecision, ToolApprovalRequest, ToolCall, type ToolCallHandler, type ToolCallLimitConfig, ToolCallLimitExceededError, type ToolCallRequest, type ToolCallStreamUnion, type ToolEmulatorOptions, type ToolErrorHandler, type ToolErrorMiddlewareConfig, ToolInvocationError, ToolMessage, ToolMessageChunk, ToolResult, type ToolRetryMiddlewareConfig, type ToolRuntime, ToolStrategy, ToolsToMessageToolSet, type TypedToolStrategy, UserInput, WhenPredicate, WithStateGraphNodes, type WrapModelCallHandler, type WrapModelCallHook, type WrapToolCallHook, anthropicPromptCachingMiddleware, applyStrategy, bedrockPromptCachingMiddleware, context, contextEditingMiddleware, countTokensApproximately, createAgent, createMiddleware, createSubagentTransformer, createToolCallTransformer, detectCreditCard, detectEmail, detectIP, detectMacAddress, detectUrl, dynamicSystemPromptMiddleware, fakeModel, filterMessages, humanInTheLoopMiddleware, initChatModel, isToolApprovalInterrupt, langchainMatchers, llmToolSelectorMiddleware, modelCallLimitMiddleware, modelFallbackMiddleware, modelRetryMiddleware, openAIModerationMiddleware, piiMiddleware, piiRedactionMiddleware, providerStrategy, providerToolSearchMiddleware, resolveRedactionRule, summarizationMiddleware, todoListMiddleware, tool, toolCallLimitMiddleware, toolEmulatorMiddleware, toolErrorMiddleware, toolRetryMiddleware, toolStrategy, trimMessages };
47
+ export { AIMessage, AIMessageChunk, Action, ActionRequest, type AfterAgentHook, type AfterModelHook, type AgentMiddleware, type AgentRunStream, AgentTypeConfig, type AnyAgentMiddleware, type AnyAnnotationRoot, ApproveDecision, BaseMessage, BaseMessageChunk, type BedrockConversePromptCachingMiddlewareConfig, type BeforeAgentHook, type BeforeModelHook, type BuiltInPIIType, BuiltInState, ClearToolUsesEdit, type ClearToolUsesEditConfig, CombineStreamTransformers, CombineTools, type ContentBlock, type ContextEdit, type ContextEditingMiddlewareConfig, CreateAgentParams, Decision, DecisionType, DefaultAgentTypeConfig, type DefaultMiddlewareTypeConfig, DescriptionFactory, Document, type DocumentInput, DynamicStructuredTool, type DynamicSystemPromptMiddlewareConfig, DynamicTool, EditDecision, ExecutedToolCall, ExtractZodArrayTypes, FakeToolCallingModel, HITLRequest, HITLResponse, type HeadlessTool, type HeadlessToolFields, type HeadlessToolImplementation, HumanInTheLoopMiddlewareConfig, HumanMessage, HumanMessageChunk, InMemoryStore, InferAgentContext, InferAgentContextSchema, InferAgentMiddleware, InferAgentResponse, InferAgentState, InferAgentStateSchema, InferAgentStreamTransformers, InferAgentTools, InferAgentType, type InferChannelType, type InferContextInput, type InferMergedInputState, type InferMergedState, type InferMiddlewareContext, type InferMiddlewareContextInput, type InferMiddlewareContextInputs, type InferMiddlewareContextSchema, type InferMiddlewareContexts, type InferMiddlewareFullContext, type InferMiddlewareInputState, type InferMiddlewareInputStates, type InferMiddlewareSchema, type InferMiddlewareState, type InferMiddlewareStates, InferMiddlewareStreamTransformers, InferMiddlewareStreamTransformersArray, type InferMiddlewareStreamTransformersFromConfig, InferMiddlewareTools, InferMiddlewareToolsArray, type InferMiddlewareToolsFromConfig, type InferMiddlewareType, type InferSchemaInput, type InferSchemaUpdateType, type InferSchemaValue, type InferSchemaValueType, Interrupt, InterruptOnConfig, JumpTo, type JumpToTarget, type LLMToolSelectorConfig, type LangChainMatchers, MIDDLEWARE_BRAND, MiddlewareError, type MiddlewareResult, type MiddlewareTypeConfig, type ModelCallLimitMiddlewareConfig, type ModelChoice, ModelRequest, type ModelRetryMiddlewareConfig, MultipleStructuredOutputsError, MultipleToolsBoundError, N, type NormalizedSchemaInput, type NormalizedSchemaUpdate, type OpenAIAutoModeMiddlewareOptions, type OpenAIDecisionsLike, type OpenAIModelRouterMiddlewareOptions, type OpenAIModerationMiddlewareOptions, PIIDetectionError, type PIIDetector, type PIIMatch, type PIIMiddlewareConfig, type PIIRedactionMiddlewareConfig, type PIIStrategy, type PromptCachingMiddlewareConfig, ProviderStrategy, type ProviderToolSearchMiddlewareConfig, type ReactAgent, type RedactionRuleConfig, RejectDecision, ResolveAgentTypeConfig, type ResolveMiddlewareTypeConfig, type ResolvedRedactionRule, RespondDecision, type ResponseFormat, type ResponseFormatUndefined, ReviewConfig, type Runtime, StructuredOutputParsingError, StructuredTool, type SubagentRunStream, type SummarizationMiddlewareConfig, SystemMessage, SystemMessageChunk, TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, type ToAnnotationRoot, type Todo, type TodoListMiddlewareOptions, type TokenCounter, Tool, ToolApprovalDecision, ToolApprovalRequest, ToolCall, type ToolCallHandler, type ToolCallLimitConfig, ToolCallLimitExceededError, type ToolCallRequest, type ToolCallStreamUnion, type ToolEmulatorOptions, type ToolErrorHandler, type ToolErrorMiddlewareConfig, ToolInvocationError, ToolMessage, ToolMessageChunk, ToolResult, type ToolRetryMiddlewareConfig, type ToolRuntime, ToolStrategy, ToolsToMessageToolSet, type TypedToolStrategy, UserInput, WhenPredicate, WithStateGraphNodes, type WrapModelCallHandler, type WrapModelCallHook, type WrapToolCallHook, anthropicPromptCachingMiddleware, applyStrategy, bedrockPromptCachingMiddleware, context, contextEditingMiddleware, countTokensApproximately, createAgent, createMiddleware, createSubagentTransformer, createToolCallTransformer, detectCreditCard, detectEmail, detectIP, detectMacAddress, detectUrl, dynamicSystemPromptMiddleware, fakeModel, filterMessages, humanInTheLoopMiddleware, initChatModel, isToolApprovalInterrupt, langchainMatchers, llmToolSelectorMiddleware, modelCallLimitMiddleware, modelFallbackMiddleware, modelRetryMiddleware, openAIAutoModeMiddleware, openAIModelRouterMiddleware, openAIModerationMiddleware, piiMiddleware, piiRedactionMiddleware, providerStrategy, providerToolSearchMiddleware, resolveRedactionRule, summarizationMiddleware, todoListMiddleware, tool, toolCallLimitMiddleware, toolEmulatorMiddleware, toolErrorMiddleware, toolRetryMiddleware, toolStrategy, trimMessages };
package/dist/browser.d.ts CHANGED
@@ -34,6 +34,9 @@ import { OpenAIModerationMiddlewareOptions, openAIModerationMiddleware } from ".
34
34
  import { PromptCachingMiddlewareConfig, anthropicPromptCachingMiddleware } from "./agents/middleware/provider/anthropic/promptCaching.js";
35
35
  import { BedrockConversePromptCachingMiddlewareConfig, bedrockPromptCachingMiddleware } from "./agents/middleware/provider/aws/promptCaching.js";
36
36
  import { countTokensApproximately } from "./agents/middleware/utils.js";
37
+ import { OpenAIDecisionsLike } from "./agents/middleware/provider/openai/decisions.js";
38
+ import { OpenAIAutoModeMiddlewareOptions, openAIAutoModeMiddleware } from "./agents/middleware/provider/openai/autoMode.js";
39
+ import { ModelChoice, OpenAIModelRouterMiddlewareOptions, openAIModelRouterMiddleware } from "./agents/middleware/provider/openai/modelRouter.js";
37
40
  import "./agents/middleware/index.js";
38
41
  import { AIMessage, AIMessageChunk, BaseMessage, BaseMessageChunk, ContentBlock, HumanMessage, HumanMessageChunk, SystemMessage, SystemMessageChunk, ToolMessage, ToolMessageChunk, filterMessages, trimMessages } from "@langchain/core/messages";
39
42
  import { DynamicStructuredTool, DynamicTool, StructuredTool, Tool, ToolRuntime } from "@langchain/core/tools";
@@ -41,4 +44,4 @@ import { context } from "@langchain/core/utils/context";
41
44
  import { InMemoryStore } from "@langchain/core/stores";
42
45
  import { Document, DocumentInput } from "@langchain/core/documents";
43
46
  import { LangChainMatchers, fakeModel, langchainMatchers } from "@langchain/core/testing";
44
- export { AIMessage, AIMessageChunk, Action, ActionRequest, type AfterAgentHook, type AfterModelHook, type AgentMiddleware, type AgentRunStream, AgentTypeConfig, type AnyAgentMiddleware, type AnyAnnotationRoot, ApproveDecision, BaseMessage, BaseMessageChunk, type BedrockConversePromptCachingMiddlewareConfig, type BeforeAgentHook, type BeforeModelHook, type BuiltInPIIType, BuiltInState, ClearToolUsesEdit, type ClearToolUsesEditConfig, CombineStreamTransformers, CombineTools, type ContentBlock, type ContextEdit, type ContextEditingMiddlewareConfig, CreateAgentParams, Decision, DecisionType, DefaultAgentTypeConfig, type DefaultMiddlewareTypeConfig, DescriptionFactory, Document, type DocumentInput, DynamicStructuredTool, type DynamicSystemPromptMiddlewareConfig, DynamicTool, EditDecision, ExecutedToolCall, ExtractZodArrayTypes, FakeToolCallingModel, HITLRequest, HITLResponse, type HeadlessTool, type HeadlessToolFields, type HeadlessToolImplementation, HumanInTheLoopMiddlewareConfig, HumanMessage, HumanMessageChunk, InMemoryStore, InferAgentContext, InferAgentContextSchema, InferAgentMiddleware, InferAgentResponse, InferAgentState, InferAgentStateSchema, InferAgentStreamTransformers, InferAgentTools, InferAgentType, type InferChannelType, type InferContextInput, type InferMergedInputState, type InferMergedState, type InferMiddlewareContext, type InferMiddlewareContextInput, type InferMiddlewareContextInputs, type InferMiddlewareContextSchema, type InferMiddlewareContexts, type InferMiddlewareFullContext, type InferMiddlewareInputState, type InferMiddlewareInputStates, type InferMiddlewareSchema, type InferMiddlewareState, type InferMiddlewareStates, InferMiddlewareStreamTransformers, InferMiddlewareStreamTransformersArray, type InferMiddlewareStreamTransformersFromConfig, InferMiddlewareTools, InferMiddlewareToolsArray, type InferMiddlewareToolsFromConfig, type InferMiddlewareType, type InferSchemaInput, type InferSchemaUpdateType, type InferSchemaValue, type InferSchemaValueType, Interrupt, InterruptOnConfig, JumpTo, type JumpToTarget, type LLMToolSelectorConfig, type LangChainMatchers, MIDDLEWARE_BRAND, MiddlewareError, type MiddlewareResult, type MiddlewareTypeConfig, type ModelCallLimitMiddlewareConfig, ModelRequest, type ModelRetryMiddlewareConfig, MultipleStructuredOutputsError, MultipleToolsBoundError, N, type NormalizedSchemaInput, type NormalizedSchemaUpdate, type OpenAIModerationMiddlewareOptions, PIIDetectionError, type PIIDetector, type PIIMatch, type PIIMiddlewareConfig, type PIIRedactionMiddlewareConfig, type PIIStrategy, type PromptCachingMiddlewareConfig, ProviderStrategy, type ProviderToolSearchMiddlewareConfig, type ReactAgent, type RedactionRuleConfig, RejectDecision, ResolveAgentTypeConfig, type ResolveMiddlewareTypeConfig, type ResolvedRedactionRule, RespondDecision, type ResponseFormat, type ResponseFormatUndefined, ReviewConfig, type Runtime, StructuredOutputParsingError, StructuredTool, type SubagentRunStream, type SummarizationMiddlewareConfig, SystemMessage, SystemMessageChunk, TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, type ToAnnotationRoot, type Todo, type TodoListMiddlewareOptions, type TokenCounter, Tool, ToolApprovalDecision, ToolApprovalRequest, ToolCall, type ToolCallHandler, type ToolCallLimitConfig, ToolCallLimitExceededError, type ToolCallRequest, type ToolCallStreamUnion, type ToolEmulatorOptions, type ToolErrorHandler, type ToolErrorMiddlewareConfig, ToolInvocationError, ToolMessage, ToolMessageChunk, ToolResult, type ToolRetryMiddlewareConfig, type ToolRuntime, ToolStrategy, ToolsToMessageToolSet, type TypedToolStrategy, UserInput, WhenPredicate, WithStateGraphNodes, type WrapModelCallHandler, type WrapModelCallHook, type WrapToolCallHook, anthropicPromptCachingMiddleware, applyStrategy, bedrockPromptCachingMiddleware, context, contextEditingMiddleware, countTokensApproximately, createAgent, createMiddleware, createSubagentTransformer, createToolCallTransformer, detectCreditCard, detectEmail, detectIP, detectMacAddress, detectUrl, dynamicSystemPromptMiddleware, fakeModel, filterMessages, humanInTheLoopMiddleware, initChatModel, isToolApprovalInterrupt, langchainMatchers, llmToolSelectorMiddleware, modelCallLimitMiddleware, modelFallbackMiddleware, modelRetryMiddleware, openAIModerationMiddleware, piiMiddleware, piiRedactionMiddleware, providerStrategy, providerToolSearchMiddleware, resolveRedactionRule, summarizationMiddleware, todoListMiddleware, tool, toolCallLimitMiddleware, toolEmulatorMiddleware, toolErrorMiddleware, toolRetryMiddleware, toolStrategy, trimMessages };
47
+ export { AIMessage, AIMessageChunk, Action, ActionRequest, type AfterAgentHook, type AfterModelHook, type AgentMiddleware, type AgentRunStream, AgentTypeConfig, type AnyAgentMiddleware, type AnyAnnotationRoot, ApproveDecision, BaseMessage, BaseMessageChunk, type BedrockConversePromptCachingMiddlewareConfig, type BeforeAgentHook, type BeforeModelHook, type BuiltInPIIType, BuiltInState, ClearToolUsesEdit, type ClearToolUsesEditConfig, CombineStreamTransformers, CombineTools, type ContentBlock, type ContextEdit, type ContextEditingMiddlewareConfig, CreateAgentParams, Decision, DecisionType, DefaultAgentTypeConfig, type DefaultMiddlewareTypeConfig, DescriptionFactory, Document, type DocumentInput, DynamicStructuredTool, type DynamicSystemPromptMiddlewareConfig, DynamicTool, EditDecision, ExecutedToolCall, ExtractZodArrayTypes, FakeToolCallingModel, HITLRequest, HITLResponse, type HeadlessTool, type HeadlessToolFields, type HeadlessToolImplementation, HumanInTheLoopMiddlewareConfig, HumanMessage, HumanMessageChunk, InMemoryStore, InferAgentContext, InferAgentContextSchema, InferAgentMiddleware, InferAgentResponse, InferAgentState, InferAgentStateSchema, InferAgentStreamTransformers, InferAgentTools, InferAgentType, type InferChannelType, type InferContextInput, type InferMergedInputState, type InferMergedState, type InferMiddlewareContext, type InferMiddlewareContextInput, type InferMiddlewareContextInputs, type InferMiddlewareContextSchema, type InferMiddlewareContexts, type InferMiddlewareFullContext, type InferMiddlewareInputState, type InferMiddlewareInputStates, type InferMiddlewareSchema, type InferMiddlewareState, type InferMiddlewareStates, InferMiddlewareStreamTransformers, InferMiddlewareStreamTransformersArray, type InferMiddlewareStreamTransformersFromConfig, InferMiddlewareTools, InferMiddlewareToolsArray, type InferMiddlewareToolsFromConfig, type InferMiddlewareType, type InferSchemaInput, type InferSchemaUpdateType, type InferSchemaValue, type InferSchemaValueType, Interrupt, InterruptOnConfig, JumpTo, type JumpToTarget, type LLMToolSelectorConfig, type LangChainMatchers, MIDDLEWARE_BRAND, MiddlewareError, type MiddlewareResult, type MiddlewareTypeConfig, type ModelCallLimitMiddlewareConfig, type ModelChoice, ModelRequest, type ModelRetryMiddlewareConfig, MultipleStructuredOutputsError, MultipleToolsBoundError, N, type NormalizedSchemaInput, type NormalizedSchemaUpdate, type OpenAIAutoModeMiddlewareOptions, type OpenAIDecisionsLike, type OpenAIModelRouterMiddlewareOptions, type OpenAIModerationMiddlewareOptions, PIIDetectionError, type PIIDetector, type PIIMatch, type PIIMiddlewareConfig, type PIIRedactionMiddlewareConfig, type PIIStrategy, type PromptCachingMiddlewareConfig, ProviderStrategy, type ProviderToolSearchMiddlewareConfig, type ReactAgent, type RedactionRuleConfig, RejectDecision, ResolveAgentTypeConfig, type ResolveMiddlewareTypeConfig, type ResolvedRedactionRule, RespondDecision, type ResponseFormat, type ResponseFormatUndefined, ReviewConfig, type Runtime, StructuredOutputParsingError, StructuredTool, type SubagentRunStream, type SummarizationMiddlewareConfig, SystemMessage, SystemMessageChunk, TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, type ToAnnotationRoot, type Todo, type TodoListMiddlewareOptions, type TokenCounter, Tool, ToolApprovalDecision, ToolApprovalRequest, ToolCall, type ToolCallHandler, type ToolCallLimitConfig, ToolCallLimitExceededError, type ToolCallRequest, type ToolCallStreamUnion, type ToolEmulatorOptions, type ToolErrorHandler, type ToolErrorMiddlewareConfig, ToolInvocationError, ToolMessage, ToolMessageChunk, ToolResult, type ToolRetryMiddlewareConfig, type ToolRuntime, ToolStrategy, ToolsToMessageToolSet, type TypedToolStrategy, UserInput, WhenPredicate, WithStateGraphNodes, type WrapModelCallHandler, type WrapModelCallHook, type WrapToolCallHook, anthropicPromptCachingMiddleware, applyStrategy, bedrockPromptCachingMiddleware, context, contextEditingMiddleware, countTokensApproximately, createAgent, createMiddleware, createSubagentTransformer, createToolCallTransformer, detectCreditCard, detectEmail, detectIP, detectMacAddress, detectUrl, dynamicSystemPromptMiddleware, fakeModel, filterMessages, humanInTheLoopMiddleware, initChatModel, isToolApprovalInterrupt, langchainMatchers, llmToolSelectorMiddleware, modelCallLimitMiddleware, modelFallbackMiddleware, modelRetryMiddleware, openAIAutoModeMiddleware, openAIModelRouterMiddleware, openAIModerationMiddleware, piiMiddleware, piiRedactionMiddleware, providerStrategy, providerToolSearchMiddleware, resolveRedactionRule, summarizationMiddleware, todoListMiddleware, tool, toolCallLimitMiddleware, toolEmulatorMiddleware, toolErrorMiddleware, toolRetryMiddleware, toolStrategy, trimMessages };
package/dist/browser.js CHANGED
@@ -29,6 +29,8 @@ import { providerToolSearchMiddleware } from "./agents/middleware/providerToolSe
29
29
  import { openAIModerationMiddleware } from "./agents/middleware/provider/openai/moderation.js";
30
30
  import { anthropicPromptCachingMiddleware } from "./agents/middleware/provider/anthropic/promptCaching.js";
31
31
  import { bedrockPromptCachingMiddleware } from "./agents/middleware/provider/aws/promptCaching.js";
32
+ import { openAIAutoModeMiddleware } from "./agents/middleware/provider/openai/autoMode.js";
33
+ import { openAIModelRouterMiddleware } from "./agents/middleware/provider/openai/modelRouter.js";
32
34
  import "./agents/middleware/index.js";
33
35
  import { AIMessage, AIMessageChunk, BaseMessage, BaseMessageChunk, HumanMessage, HumanMessageChunk, SystemMessage, SystemMessageChunk, ToolMessage, ToolMessageChunk, filterMessages, trimMessages } from "@langchain/core/messages";
34
36
  import { DynamicStructuredTool, DynamicTool, StructuredTool, Tool } from "@langchain/core/tools";
@@ -93,6 +95,8 @@ var browser_exports = /* @__PURE__ */ __exportAll({
93
95
  modelCallLimitMiddleware: () => modelCallLimitMiddleware,
94
96
  modelFallbackMiddleware: () => modelFallbackMiddleware,
95
97
  modelRetryMiddleware: () => modelRetryMiddleware,
98
+ openAIAutoModeMiddleware: () => openAIAutoModeMiddleware,
99
+ openAIModelRouterMiddleware: () => openAIModelRouterMiddleware,
96
100
  openAIModerationMiddleware: () => openAIModerationMiddleware,
97
101
  piiMiddleware: () => piiMiddleware,
98
102
  piiRedactionMiddleware: () => piiRedactionMiddleware,
@@ -110,6 +114,6 @@ var browser_exports = /* @__PURE__ */ __exportAll({
110
114
  trimMessages: () => trimMessages
111
115
  });
112
116
  //#endregion
113
- export { AIMessage, AIMessageChunk, BaseMessage, BaseMessageChunk, ClearToolUsesEdit, Document, DynamicStructuredTool, DynamicTool, FakeToolCallingModel, HumanMessage, HumanMessageChunk, InMemoryStore, MIDDLEWARE_BRAND, MiddlewareError, MultipleStructuredOutputsError, MultipleToolsBoundError, PIIDetectionError, ProviderStrategy, StructuredOutputParsingError, StructuredTool, SystemMessage, SystemMessageChunk, TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, Tool, ToolCallLimitExceededError, ToolInvocationError, ToolMessage, ToolMessageChunk, ToolStrategy, anthropicPromptCachingMiddleware, applyStrategy, bedrockPromptCachingMiddleware, browser_exports, context, contextEditingMiddleware, countTokensApproximately, createAgent, createMiddleware, createSubagentTransformer, createToolCallTransformer, detectCreditCard, detectEmail, detectIP, detectMacAddress, detectUrl, dynamicSystemPromptMiddleware, fakeModel, filterMessages, humanInTheLoopMiddleware, initChatModel, isToolApprovalInterrupt, langchainMatchers, llmToolSelectorMiddleware, modelCallLimitMiddleware, modelFallbackMiddleware, modelRetryMiddleware, openAIModerationMiddleware, piiMiddleware, piiRedactionMiddleware, providerStrategy, providerToolSearchMiddleware, resolveRedactionRule, summarizationMiddleware, todoListMiddleware, tool, toolCallLimitMiddleware, toolEmulatorMiddleware, toolErrorMiddleware, toolRetryMiddleware, toolStrategy, trimMessages };
117
+ export { AIMessage, AIMessageChunk, BaseMessage, BaseMessageChunk, ClearToolUsesEdit, Document, DynamicStructuredTool, DynamicTool, FakeToolCallingModel, HumanMessage, HumanMessageChunk, InMemoryStore, MIDDLEWARE_BRAND, MiddlewareError, MultipleStructuredOutputsError, MultipleToolsBoundError, PIIDetectionError, ProviderStrategy, StructuredOutputParsingError, StructuredTool, SystemMessage, SystemMessageChunk, TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, Tool, ToolCallLimitExceededError, ToolInvocationError, ToolMessage, ToolMessageChunk, ToolStrategy, anthropicPromptCachingMiddleware, applyStrategy, bedrockPromptCachingMiddleware, browser_exports, context, contextEditingMiddleware, countTokensApproximately, createAgent, createMiddleware, createSubagentTransformer, createToolCallTransformer, detectCreditCard, detectEmail, detectIP, detectMacAddress, detectUrl, dynamicSystemPromptMiddleware, fakeModel, filterMessages, humanInTheLoopMiddleware, initChatModel, isToolApprovalInterrupt, langchainMatchers, llmToolSelectorMiddleware, modelCallLimitMiddleware, modelFallbackMiddleware, modelRetryMiddleware, openAIAutoModeMiddleware, openAIModelRouterMiddleware, openAIModerationMiddleware, piiMiddleware, piiRedactionMiddleware, providerStrategy, providerToolSearchMiddleware, resolveRedactionRule, summarizationMiddleware, todoListMiddleware, tool, toolCallLimitMiddleware, toolEmulatorMiddleware, toolErrorMiddleware, toolRetryMiddleware, toolStrategy, trimMessages };
114
118
 
115
119
  //# sourceMappingURL=browser.js.map
package/dist/index.cjs CHANGED
@@ -30,6 +30,8 @@ const require_providerToolSearch = require("./agents/middleware/providerToolSear
30
30
  const require_moderation = require("./agents/middleware/provider/openai/moderation.cjs");
31
31
  const require_promptCaching = require("./agents/middleware/provider/anthropic/promptCaching.cjs");
32
32
  const require_promptCaching$1 = require("./agents/middleware/provider/aws/promptCaching.cjs");
33
+ const require_autoMode = require("./agents/middleware/provider/openai/autoMode.cjs");
34
+ const require_modelRouter = require("./agents/middleware/provider/openai/modelRouter.cjs");
33
35
  require("./agents/middleware/index.cjs");
34
36
  let _langchain_core_messages = require("@langchain/core/messages");
35
37
  let _langchain_core_tools = require("@langchain/core/tools");
@@ -94,6 +96,8 @@ var src_exports = /* @__PURE__ */ require_runtime.__exportAll({
94
96
  modelCallLimitMiddleware: () => require_modelCallLimit.modelCallLimitMiddleware,
95
97
  modelFallbackMiddleware: () => require_modelFallback.modelFallbackMiddleware,
96
98
  modelRetryMiddleware: () => require_modelRetry.modelRetryMiddleware,
99
+ openAIAutoModeMiddleware: () => require_autoMode.openAIAutoModeMiddleware,
100
+ openAIModelRouterMiddleware: () => require_modelRouter.openAIModelRouterMiddleware,
97
101
  openAIModerationMiddleware: () => require_moderation.openAIModerationMiddleware,
98
102
  piiMiddleware: () => require_pii.piiMiddleware,
99
103
  piiRedactionMiddleware: () => require_piiRedaction.piiRedactionMiddleware,
@@ -266,6 +270,8 @@ exports.llmToolSelectorMiddleware = require_llmToolSelector.llmToolSelectorMiddl
266
270
  exports.modelCallLimitMiddleware = require_modelCallLimit.modelCallLimitMiddleware;
267
271
  exports.modelFallbackMiddleware = require_modelFallback.modelFallbackMiddleware;
268
272
  exports.modelRetryMiddleware = require_modelRetry.modelRetryMiddleware;
273
+ exports.openAIAutoModeMiddleware = require_autoMode.openAIAutoModeMiddleware;
274
+ exports.openAIModelRouterMiddleware = require_modelRouter.openAIModelRouterMiddleware;
269
275
  exports.openAIModerationMiddleware = require_moderation.openAIModerationMiddleware;
270
276
  exports.piiMiddleware = require_pii.piiMiddleware;
271
277
  exports.piiRedactionMiddleware = require_piiRedaction.piiRedactionMiddleware;
package/dist/index.d.cts CHANGED
@@ -34,6 +34,9 @@ import { OpenAIModerationMiddlewareOptions, openAIModerationMiddleware } from ".
34
34
  import { PromptCachingMiddlewareConfig, anthropicPromptCachingMiddleware } from "./agents/middleware/provider/anthropic/promptCaching.cjs";
35
35
  import { BedrockConversePromptCachingMiddlewareConfig, bedrockPromptCachingMiddleware } from "./agents/middleware/provider/aws/promptCaching.cjs";
36
36
  import { countTokensApproximately } from "./agents/middleware/utils.cjs";
37
+ import { OpenAIDecisionsLike } from "./agents/middleware/provider/openai/decisions.cjs";
38
+ import { OpenAIAutoModeMiddlewareOptions, openAIAutoModeMiddleware } from "./agents/middleware/provider/openai/autoMode.cjs";
39
+ import { ModelChoice, OpenAIModelRouterMiddlewareOptions, openAIModelRouterMiddleware } from "./agents/middleware/provider/openai/modelRouter.cjs";
37
40
  import "./agents/middleware/index.cjs";
38
41
  import { AIMessage, AIMessageChunk, BaseMessage, BaseMessageChunk, ContentBlock, HumanMessage, HumanMessageChunk, SystemMessage, SystemMessageChunk, ToolMessage, ToolMessageChunk, filterMessages, trimMessages } from "@langchain/core/messages";
39
42
  import { DynamicStructuredTool, DynamicTool, StructuredTool, Tool, ToolRuntime } from "@langchain/core/tools";
@@ -41,4 +44,4 @@ import { context } from "@langchain/core/utils/context";
41
44
  import { InMemoryStore } from "@langchain/core/stores";
42
45
  import { Document, DocumentInput } from "@langchain/core/documents";
43
46
  import { LangChainMatchers, fakeModel, langchainMatchers } from "@langchain/core/testing";
44
- export { AIMessage, AIMessageChunk, Action, ActionRequest, type AfterAgentHook, type AfterModelHook, type AgentMiddleware, type AgentRunStream, AgentTypeConfig, type AnyAgentMiddleware, type AnyAnnotationRoot, ApproveDecision, BaseMessage, BaseMessageChunk, type BedrockConversePromptCachingMiddlewareConfig, type BeforeAgentHook, type BeforeModelHook, type BuiltInPIIType, BuiltInState, ClearToolUsesEdit, type ClearToolUsesEditConfig, CombineStreamTransformers, CombineTools, type ContentBlock, type ContextEdit, type ContextEditingMiddlewareConfig, CreateAgentParams, Decision, DecisionType, DefaultAgentTypeConfig, type DefaultMiddlewareTypeConfig, DescriptionFactory, Document, type DocumentInput, DynamicStructuredTool, type DynamicSystemPromptMiddlewareConfig, DynamicTool, EditDecision, ExecutedToolCall, ExtractZodArrayTypes, FakeToolCallingModel, HITLRequest, HITLResponse, type HeadlessTool, type HeadlessToolFields, type HeadlessToolImplementation, HumanInTheLoopMiddlewareConfig, HumanMessage, HumanMessageChunk, InMemoryStore, InferAgentContext, InferAgentContextSchema, InferAgentMiddleware, InferAgentResponse, InferAgentState, InferAgentStateSchema, InferAgentStreamTransformers, InferAgentTools, InferAgentType, type InferChannelType, type InferContextInput, type InferMergedInputState, type InferMergedState, type InferMiddlewareContext, type InferMiddlewareContextInput, type InferMiddlewareContextInputs, type InferMiddlewareContextSchema, type InferMiddlewareContexts, type InferMiddlewareFullContext, type InferMiddlewareInputState, type InferMiddlewareInputStates, type InferMiddlewareSchema, type InferMiddlewareState, type InferMiddlewareStates, InferMiddlewareStreamTransformers, InferMiddlewareStreamTransformersArray, type InferMiddlewareStreamTransformersFromConfig, InferMiddlewareTools, InferMiddlewareToolsArray, type InferMiddlewareToolsFromConfig, type InferMiddlewareType, type InferSchemaInput, type InferSchemaUpdateType, type InferSchemaValue, type InferSchemaValueType, Interrupt, InterruptOnConfig, JumpTo, type JumpToTarget, type LLMToolSelectorConfig, type LangChainMatchers, MIDDLEWARE_BRAND, MiddlewareError, type MiddlewareResult, type MiddlewareTypeConfig, type ModelCallLimitMiddlewareConfig, ModelRequest, type ModelRetryMiddlewareConfig, MultipleStructuredOutputsError, MultipleToolsBoundError, N, type NormalizedSchemaInput, type NormalizedSchemaUpdate, type OpenAIModerationMiddlewareOptions, PIIDetectionError, type PIIDetector, type PIIMatch, type PIIMiddlewareConfig, type PIIRedactionMiddlewareConfig, type PIIStrategy, type PromptCachingMiddlewareConfig, ProviderStrategy, type ProviderToolSearchMiddlewareConfig, type ReactAgent, type RedactionRuleConfig, RejectDecision, ResolveAgentTypeConfig, type ResolveMiddlewareTypeConfig, type ResolvedRedactionRule, RespondDecision, type ResponseFormat, type ResponseFormatUndefined, ReviewConfig, type Runtime, StructuredOutputParsingError, StructuredTool, type SubagentRunStream, type SummarizationMiddlewareConfig, SystemMessage, SystemMessageChunk, TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, type ToAnnotationRoot, type Todo, type TodoListMiddlewareOptions, type TokenCounter, Tool, ToolApprovalDecision, ToolApprovalRequest, ToolCall, type ToolCallHandler, type ToolCallLimitConfig, ToolCallLimitExceededError, type ToolCallRequest, type ToolCallStreamUnion, type ToolEmulatorOptions, type ToolErrorHandler, type ToolErrorMiddlewareConfig, ToolInvocationError, ToolMessage, ToolMessageChunk, ToolResult, type ToolRetryMiddlewareConfig, type ToolRuntime, ToolStrategy, ToolsToMessageToolSet, type TypedToolStrategy, UserInput, WhenPredicate, WithStateGraphNodes, type WrapModelCallHandler, type WrapModelCallHook, type WrapToolCallHook, anthropicPromptCachingMiddleware, applyStrategy, bedrockPromptCachingMiddleware, context, contextEditingMiddleware, countTokensApproximately, createAgent, createMiddleware, createSubagentTransformer, createToolCallTransformer, detectCreditCard, detectEmail, detectIP, detectMacAddress, detectUrl, dynamicSystemPromptMiddleware, fakeModel, filterMessages, humanInTheLoopMiddleware, initChatModel, isToolApprovalInterrupt, langchainMatchers, llmToolSelectorMiddleware, modelCallLimitMiddleware, modelFallbackMiddleware, modelRetryMiddleware, openAIModerationMiddleware, piiMiddleware, piiRedactionMiddleware, providerStrategy, providerToolSearchMiddleware, resolveRedactionRule, summarizationMiddleware, todoListMiddleware, tool, toolCallLimitMiddleware, toolEmulatorMiddleware, toolErrorMiddleware, toolRetryMiddleware, toolStrategy, trimMessages };
47
+ export { AIMessage, AIMessageChunk, Action, ActionRequest, type AfterAgentHook, type AfterModelHook, type AgentMiddleware, type AgentRunStream, AgentTypeConfig, type AnyAgentMiddleware, type AnyAnnotationRoot, ApproveDecision, BaseMessage, BaseMessageChunk, type BedrockConversePromptCachingMiddlewareConfig, type BeforeAgentHook, type BeforeModelHook, type BuiltInPIIType, BuiltInState, ClearToolUsesEdit, type ClearToolUsesEditConfig, CombineStreamTransformers, CombineTools, type ContentBlock, type ContextEdit, type ContextEditingMiddlewareConfig, CreateAgentParams, Decision, DecisionType, DefaultAgentTypeConfig, type DefaultMiddlewareTypeConfig, DescriptionFactory, Document, type DocumentInput, DynamicStructuredTool, type DynamicSystemPromptMiddlewareConfig, DynamicTool, EditDecision, ExecutedToolCall, ExtractZodArrayTypes, FakeToolCallingModel, HITLRequest, HITLResponse, type HeadlessTool, type HeadlessToolFields, type HeadlessToolImplementation, HumanInTheLoopMiddlewareConfig, HumanMessage, HumanMessageChunk, InMemoryStore, InferAgentContext, InferAgentContextSchema, InferAgentMiddleware, InferAgentResponse, InferAgentState, InferAgentStateSchema, InferAgentStreamTransformers, InferAgentTools, InferAgentType, type InferChannelType, type InferContextInput, type InferMergedInputState, type InferMergedState, type InferMiddlewareContext, type InferMiddlewareContextInput, type InferMiddlewareContextInputs, type InferMiddlewareContextSchema, type InferMiddlewareContexts, type InferMiddlewareFullContext, type InferMiddlewareInputState, type InferMiddlewareInputStates, type InferMiddlewareSchema, type InferMiddlewareState, type InferMiddlewareStates, InferMiddlewareStreamTransformers, InferMiddlewareStreamTransformersArray, type InferMiddlewareStreamTransformersFromConfig, InferMiddlewareTools, InferMiddlewareToolsArray, type InferMiddlewareToolsFromConfig, type InferMiddlewareType, type InferSchemaInput, type InferSchemaUpdateType, type InferSchemaValue, type InferSchemaValueType, Interrupt, InterruptOnConfig, JumpTo, type JumpToTarget, type LLMToolSelectorConfig, type LangChainMatchers, MIDDLEWARE_BRAND, MiddlewareError, type MiddlewareResult, type MiddlewareTypeConfig, type ModelCallLimitMiddlewareConfig, type ModelChoice, ModelRequest, type ModelRetryMiddlewareConfig, MultipleStructuredOutputsError, MultipleToolsBoundError, N, type NormalizedSchemaInput, type NormalizedSchemaUpdate, type OpenAIAutoModeMiddlewareOptions, type OpenAIDecisionsLike, type OpenAIModelRouterMiddlewareOptions, type OpenAIModerationMiddlewareOptions, PIIDetectionError, type PIIDetector, type PIIMatch, type PIIMiddlewareConfig, type PIIRedactionMiddlewareConfig, type PIIStrategy, type PromptCachingMiddlewareConfig, ProviderStrategy, type ProviderToolSearchMiddlewareConfig, type ReactAgent, type RedactionRuleConfig, RejectDecision, ResolveAgentTypeConfig, type ResolveMiddlewareTypeConfig, type ResolvedRedactionRule, RespondDecision, type ResponseFormat, type ResponseFormatUndefined, ReviewConfig, type Runtime, StructuredOutputParsingError, StructuredTool, type SubagentRunStream, type SummarizationMiddlewareConfig, SystemMessage, SystemMessageChunk, TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, type ToAnnotationRoot, type Todo, type TodoListMiddlewareOptions, type TokenCounter, Tool, ToolApprovalDecision, ToolApprovalRequest, ToolCall, type ToolCallHandler, type ToolCallLimitConfig, ToolCallLimitExceededError, type ToolCallRequest, type ToolCallStreamUnion, type ToolEmulatorOptions, type ToolErrorHandler, type ToolErrorMiddlewareConfig, ToolInvocationError, ToolMessage, ToolMessageChunk, ToolResult, type ToolRetryMiddlewareConfig, type ToolRuntime, ToolStrategy, ToolsToMessageToolSet, type TypedToolStrategy, UserInput, WhenPredicate, WithStateGraphNodes, type WrapModelCallHandler, type WrapModelCallHook, type WrapToolCallHook, anthropicPromptCachingMiddleware, applyStrategy, bedrockPromptCachingMiddleware, context, contextEditingMiddleware, countTokensApproximately, createAgent, createMiddleware, createSubagentTransformer, createToolCallTransformer, detectCreditCard, detectEmail, detectIP, detectMacAddress, detectUrl, dynamicSystemPromptMiddleware, fakeModel, filterMessages, humanInTheLoopMiddleware, initChatModel, isToolApprovalInterrupt, langchainMatchers, llmToolSelectorMiddleware, modelCallLimitMiddleware, modelFallbackMiddleware, modelRetryMiddleware, openAIAutoModeMiddleware, openAIModelRouterMiddleware, openAIModerationMiddleware, piiMiddleware, piiRedactionMiddleware, providerStrategy, providerToolSearchMiddleware, resolveRedactionRule, summarizationMiddleware, todoListMiddleware, tool, toolCallLimitMiddleware, toolEmulatorMiddleware, toolErrorMiddleware, toolRetryMiddleware, toolStrategy, trimMessages };