langchain 1.0.2 → 1.0.4
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.
- package/CHANGELOG.md +18 -0
- package/dist/agents/ReactAgent.cjs +21 -41
- package/dist/agents/ReactAgent.cjs.map +1 -1
- package/dist/agents/ReactAgent.js +21 -41
- package/dist/agents/ReactAgent.js.map +1 -1
- package/dist/agents/annotation.cjs +7 -4
- package/dist/agents/annotation.cjs.map +1 -1
- package/dist/agents/annotation.js +8 -5
- package/dist/agents/annotation.js.map +1 -1
- package/dist/agents/middleware/contextEditing.d.cts.map +1 -1
- package/dist/agents/middleware/contextEditing.d.ts.map +1 -1
- package/dist/agents/middleware/dynamicSystemPrompt.d.cts.map +1 -1
- package/dist/agents/middleware/dynamicSystemPrompt.d.ts.map +1 -1
- package/dist/agents/middleware/hitl.cjs +7 -2
- package/dist/agents/middleware/hitl.cjs.map +1 -1
- package/dist/agents/middleware/hitl.d.cts.map +1 -1
- package/dist/agents/middleware/hitl.d.ts.map +1 -1
- package/dist/agents/middleware/hitl.js +7 -2
- package/dist/agents/middleware/hitl.js.map +1 -1
- package/dist/agents/middleware/index.cjs +2 -1
- package/dist/agents/middleware/index.js +2 -1
- package/dist/agents/middleware/llmToolSelector.d.cts +4 -4
- package/dist/agents/middleware/llmToolSelector.d.cts.map +1 -1
- package/dist/agents/middleware/{callLimit.cjs → modelCallLimit.cjs} +22 -7
- package/dist/agents/middleware/modelCallLimit.cjs.map +1 -0
- package/dist/agents/middleware/{callLimit.d.cts → modelCallLimit.d.cts} +12 -3
- package/dist/agents/middleware/modelCallLimit.d.cts.map +1 -0
- package/dist/agents/middleware/{callLimit.d.ts → modelCallLimit.d.ts} +12 -3
- package/dist/agents/middleware/modelCallLimit.d.ts.map +1 -0
- package/dist/agents/middleware/{callLimit.js → modelCallLimit.js} +22 -7
- package/dist/agents/middleware/modelCallLimit.js.map +1 -0
- package/dist/agents/middleware/promptCaching.d.cts.map +1 -1
- package/dist/agents/middleware/promptCaching.d.ts.map +1 -1
- package/dist/agents/middleware/summarization.cjs +274 -52
- package/dist/agents/middleware/summarization.cjs.map +1 -1
- package/dist/agents/middleware/summarization.d.cts +326 -30
- package/dist/agents/middleware/summarization.d.cts.map +1 -1
- package/dist/agents/middleware/summarization.d.ts +325 -29
- package/dist/agents/middleware/summarization.d.ts.map +1 -1
- package/dist/agents/middleware/summarization.js +276 -54
- package/dist/agents/middleware/summarization.js.map +1 -1
- package/dist/agents/middleware/todoListMiddleware.d.cts.map +1 -1
- package/dist/agents/middleware/todoListMiddleware.d.ts.map +1 -1
- package/dist/agents/middleware/toolCallLimit.cjs +215 -93
- package/dist/agents/middleware/toolCallLimit.cjs.map +1 -1
- package/dist/agents/middleware/toolCallLimit.d.cts +48 -37
- package/dist/agents/middleware/toolCallLimit.d.cts.map +1 -1
- package/dist/agents/middleware/toolCallLimit.d.ts +48 -37
- package/dist/agents/middleware/toolCallLimit.d.ts.map +1 -1
- package/dist/agents/middleware/toolCallLimit.js +216 -94
- package/dist/agents/middleware/toolCallLimit.js.map +1 -1
- package/dist/agents/middleware/toolRetry.cjs +224 -0
- package/dist/agents/middleware/toolRetry.cjs.map +1 -0
- package/dist/agents/middleware/toolRetry.d.cts +179 -0
- package/dist/agents/middleware/toolRetry.d.cts.map +1 -0
- package/dist/agents/middleware/toolRetry.d.ts +179 -0
- package/dist/agents/middleware/toolRetry.d.ts.map +1 -0
- package/dist/agents/middleware/toolRetry.js +223 -0
- package/dist/agents/middleware/toolRetry.js.map +1 -0
- package/dist/agents/middleware/types.d.cts +21 -19
- package/dist/agents/middleware/types.d.cts.map +1 -1
- package/dist/agents/middleware/types.d.ts +21 -19
- package/dist/agents/middleware/types.d.ts.map +1 -1
- package/dist/agents/middleware/utils.cjs +7 -0
- package/dist/agents/middleware/utils.cjs.map +1 -1
- package/dist/agents/middleware/utils.d.cts.map +1 -1
- package/dist/agents/middleware/utils.d.ts.map +1 -1
- package/dist/agents/middleware/utils.js +7 -1
- package/dist/agents/middleware/utils.js.map +1 -1
- package/dist/agents/middleware.cjs.map +1 -1
- package/dist/agents/middleware.d.cts +4 -4
- package/dist/agents/middleware.d.cts.map +1 -1
- package/dist/agents/middleware.d.ts +4 -4
- package/dist/agents/middleware.d.ts.map +1 -1
- package/dist/agents/middleware.js.map +1 -1
- package/dist/agents/nodes/AgentNode.cjs +21 -51
- package/dist/agents/nodes/AgentNode.cjs.map +1 -1
- package/dist/agents/nodes/AgentNode.js +23 -53
- package/dist/agents/nodes/AgentNode.js.map +1 -1
- package/dist/agents/nodes/ToolNode.cjs +12 -18
- package/dist/agents/nodes/ToolNode.cjs.map +1 -1
- package/dist/agents/nodes/ToolNode.js +12 -18
- package/dist/agents/nodes/ToolNode.js.map +1 -1
- package/dist/agents/nodes/middleware.cjs +9 -7
- package/dist/agents/nodes/middleware.cjs.map +1 -1
- package/dist/agents/nodes/middleware.js +10 -8
- package/dist/agents/nodes/middleware.js.map +1 -1
- package/dist/agents/nodes/types.d.cts +1 -1
- package/dist/agents/nodes/types.d.cts.map +1 -1
- package/dist/agents/nodes/types.d.ts +1 -1
- package/dist/agents/nodes/types.d.ts.map +1 -1
- package/dist/agents/nodes/utils.cjs +5 -1
- package/dist/agents/nodes/utils.cjs.map +1 -1
- package/dist/agents/nodes/utils.js +5 -1
- package/dist/agents/nodes/utils.js.map +1 -1
- package/dist/agents/responses.cjs +0 -1
- package/dist/agents/responses.js +1 -1
- package/dist/agents/runtime.d.cts +11 -27
- package/dist/agents/runtime.d.cts.map +1 -1
- package/dist/agents/runtime.d.ts +11 -27
- package/dist/agents/runtime.d.ts.map +1 -1
- package/dist/agents/state.cjs +45 -0
- package/dist/agents/state.cjs.map +1 -0
- package/dist/agents/state.js +44 -0
- package/dist/agents/state.js.map +1 -0
- package/dist/agents/types.d.cts +1 -1
- package/dist/agents/types.d.cts.map +1 -1
- package/dist/agents/types.d.ts +1 -1
- package/dist/agents/types.d.ts.map +1 -1
- package/dist/agents/utils.cjs +10 -2
- package/dist/agents/utils.cjs.map +1 -1
- package/dist/agents/utils.js +10 -2
- package/dist/agents/utils.js.map +1 -1
- package/dist/chat_models/universal.cjs +2 -2
- package/dist/chat_models/universal.cjs.map +1 -1
- package/dist/chat_models/universal.js +2 -2
- package/dist/chat_models/universal.js.map +1 -1
- package/dist/index.cjs +6 -18
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +4 -5
- package/dist/index.js.map +1 -1
- package/package.json +7 -7
- package/dist/agents/middleware/callLimit.cjs.map +0 -1
- package/dist/agents/middleware/callLimit.d.cts.map +0 -1
- package/dist/agents/middleware/callLimit.d.ts.map +0 -1
- package/dist/agents/middleware/callLimit.js.map +0 -1
- package/dist/agents/tools.d.cts +0 -9
- package/dist/agents/tools.d.cts.map +0 -1
- package/dist/agents/tools.d.ts +0 -9
- package/dist/agents/tools.d.ts.map +0 -1
package/dist/agents/types.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { JsonSchemaFormat, ProviderStrategy, ResponseFormat, ResponseFormatUndefined, ToolStrategy, TypedToolStrategy } from "./responses.js";
|
|
2
2
|
import { JumpToTarget } from "./constants.js";
|
|
3
|
-
import { ClientTool, ServerTool } from "./tools.js";
|
|
4
3
|
import { AgentMiddleware, AnyAnnotationRoot, InferSchemaInput } from "./middleware/types.js";
|
|
5
4
|
import { BaseMessage } from "@langchain/core/messages";
|
|
5
|
+
import { ClientTool, ServerTool } from "@langchain/core/tools";
|
|
6
6
|
import { END, START, StateGraph } from "@langchain/langgraph";
|
|
7
7
|
import { InteropZodObject, InteropZodType } from "@langchain/core/utils/types";
|
|
8
8
|
import { BaseCheckpointSaver, BaseStore } from "@langchain/langgraph-checkpoint";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","names":["InteropZodObject","InteropZodType","START","END","StateGraph","LanguageModelLike","BaseMessage","BaseCheckpointSaver","BaseStore","Messages","ResponseFormat","ToolStrategy","TypedToolStrategy","ProviderStrategy","JsonSchemaFormat","ResponseFormatUndefined","AgentMiddleware","AnyAnnotationRoot","InferSchemaInput","ServerTool","ClientTool","JumpToTarget","N","Interrupt","TValue","BuiltInState","UserInput","TStateSchema","ToolCall","Record","ToolResult","JumpTo","ExecutedToolCall","CreateAgentParams","StructuredResponseType","StateSchema","ContextSchema","ResponseFormatType","AbortSignal","ExtractZodArrayTypes","T","Rest","A","WithStateGraphNodes","Graph","SD","S","U","K","I","O","C"],"sources":["../../src/agents/types.d.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { InteropZodObject, InteropZodType } from \"@langchain/core/utils/types\";\nimport type { START, END, StateGraph } from \"@langchain/langgraph\";\nimport type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport type { BaseMessage } from \"@langchain/core/messages\";\nimport type { BaseCheckpointSaver, BaseStore } from \"@langchain/langgraph-checkpoint\";\nimport type { Messages } from \"@langchain/langgraph/\";\nimport type { ResponseFormat, ToolStrategy, TypedToolStrategy, ProviderStrategy, JsonSchemaFormat, ResponseFormatUndefined } from \"./responses.js\";\nimport type { AgentMiddleware, AnyAnnotationRoot, InferSchemaInput } from \"./middleware/types.js\";\nimport type { ServerTool, ClientTool } from \"./tools.js\";\nimport type { JumpToTarget } from \"./constants.js\";\nexport type N = typeof START | \"model_request\" | \"tools\";\n/**\n * Represents information about an interrupt.\n */\nexport interface Interrupt<TValue = unknown> {\n /**\n * The ID of the interrupt.\n */\n id: string;\n /**\n * The requests for human input.\n */\n value: TValue;\n}\nexport interface BuiltInState {\n messages: BaseMessage[];\n __interrupt__?: Interrupt[];\n /**\n * Optional property to control routing after afterModel middleware execution.\n * When set by middleware, the agent will jump to the specified node instead of\n * following normal routing logic. The property is automatically cleared after use.\n *\n * - \"model_request\": Jump back to the model for another LLM call\n * - \"tools\": Jump to tool execution (requires tools to be available)\n */\n jumpTo?: JumpToTarget;\n}\n/**\n * Base input type for `.invoke` and `.stream` methods.\n */\nexport type UserInput<TStateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined> = InferSchemaInput<TStateSchema> & {\n messages: Messages;\n};\n/**\n * Information about a tool call that has been executed.\n */\nexport interface ToolCall {\n /**\n * The ID of the tool call.\n */\n id: string;\n /**\n * The name of the tool that was called.\n */\n name: string;\n /**\n * The arguments that were passed to the tool.\n */\n args: Record<string, any>;\n /**\n * The result of the tool call.\n */\n result?: unknown;\n /**\n * An optional error message if the tool call failed.\n */\n error?: string;\n}\n/**\n * Information about a tool result from a tool execution.\n */\nexport interface ToolResult {\n /**\n * The ID of the tool call.\n */\n id: string;\n /**\n * The result of the tool call.\n */\n result: any;\n /**\n * An optional error message if the tool call failed.\n */\n error?: string;\n}\n/**\n * jump targets (internal)\n */\nexport type JumpTo = \"model_request\" | \"tools\" | typeof END;\n/**\n * Information about a tool call that has been executed.\n */\nexport interface ExecutedToolCall {\n /**\n * The name of the tool that was called.\n */\n name: string;\n /**\n * The arguments that were passed to the tool.\n */\n args: Record<string, unknown>;\n /**\n * The ID of the tool call.\n */\n tool_id: string;\n /**\n * The result of the tool call (if available).\n */\n result?: unknown;\n}\nexport type CreateAgentParams<StructuredResponseType extends Record<string, any> = Record<string, any>, StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ResponseFormatType = InteropZodType<StructuredResponseType> | InteropZodType<unknown>[] | JsonSchemaFormat | JsonSchemaFormat[] | ResponseFormat | TypedToolStrategy<StructuredResponseType> | ToolStrategy<StructuredResponseType> | ProviderStrategy<StructuredResponseType> | ResponseFormatUndefined> = {\n /**\n * Defines a model to use for the agent. You can either pass in an instance of a LangChain chat model\n * or a string. If a string is provided the agent initializes a ChatModel based on the provided model name and provider.\n * It supports various model providers and allows for runtime configuration of model parameters.\n *\n * @uses {@link initChatModel}\n * @example\n * ```ts\n * const agent = createAgent({\n * model: \"anthropic:claude-3-7-sonnet-latest\",\n * // ...\n * });\n * ```\n *\n * @example\n * ```ts\n * import { ChatOpenAI } from \"@langchain/openai\";\n * const agent = createAgent({\n * model: new ChatOpenAI({ model: \"gpt-4o\" }),\n * // ...\n * });\n * ```\n */\n model: string | LanguageModelLike;\n /**\n * A list of tools or a ToolNode.\n *\n * @example\n * ```ts\n * import { tool } from \"langchain\";\n *\n * const weatherTool = tool(() => \"Sunny!\", {\n * name: \"get_weather\",\n * description: \"Get the weather for a location\",\n * schema: z.object({\n * location: z.string().describe(\"The location to get weather for\"),\n * }),\n * });\n *\n * const agent = createAgent({\n * tools: [weatherTool],\n * // ...\n * });\n * ```\n */\n tools?: (ServerTool | ClientTool)[];\n /**\n * An optional system message for the model.\n */\n systemPrompt?: string;\n /**\n * An optional schema for the agent state. It allows you to define custom state properties that persist\n * across agent invocations and can be accessed in hooks, middleware, and throughout the agent's execution.\n * The state is persisted when using a checkpointer and can be updated by middleware or during execution.\n *\n * As opposed to the context (defined in `contextSchema`), the state is persisted between agent invocations\n * when using a checkpointer, making it suitable for maintaining conversation history, user preferences,\n * or any other data that should persist across multiple interactions.\n *\n * @example\n * ```ts\n * import { z } from \"zod\";\n * import { createAgent } from \"@langchain/langgraph\";\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * tools: [getWeather],\n * stateSchema: z.object({\n * userPreferences: z.object({\n * temperatureUnit: z.enum([\"celsius\", \"fahrenheit\"]).default(\"celsius\"),\n * location: z.string().optional(),\n * }).optional(),\n * conversationCount: z.number().default(0),\n * }),\n * prompt: (state, config) => {\n * const unit = state.userPreferences?.temperatureUnit || \"celsius\";\n * return [\n * new SystemMessage(`You are a helpful assistant. Use ${unit} for temperature.`),\n * ];\n * },\n * });\n *\n * const result = await agent.invoke({\n * messages: [\n * new HumanMessage(\"What's the weather like?\"),\n * ],\n * userPreferences: {\n * temperatureUnit: \"fahrenheit\",\n * location: \"New York\",\n * },\n * conversationCount: 1,\n * });\n * ```\n */\n stateSchema?: StateSchema;\n /**\n * An optional schema for the context. It allows to pass in a typed context object into the agent\n * invocation and allows to access it in hooks such as `prompt` and middleware.\n * As opposed to the agent state, defined in `stateSchema`, the context is not persisted between\n * agent invocations.\n *\n * @example\n * ```ts\n * const agent = createAgent({\n * llm: model,\n * tools: [getWeather],\n * contextSchema: z.object({\n * capital: z.string(),\n * }),\n * prompt: (state, config) => {\n * return [\n * new SystemMessage(`You are a helpful assistant. The capital of France is ${config.context.capital}.`),\n * ];\n * },\n * });\n *\n * const result = await agent.invoke({\n * messages: [\n * new SystemMessage(\"You are a helpful assistant.\"),\n * new HumanMessage(\"What is the capital of France?\"),\n * ],\n * }, {\n * context: {\n * capital: \"Paris\",\n * },\n * });\n * ```\n */\n contextSchema?: ContextSchema;\n /**\n * An optional checkpoint saver to persist the agent's state.\n * @see {@link https://docs.langchain.com/oss/javascript/langgraph/persistence | Checkpointing}\n */\n checkpointer?: BaseCheckpointSaver | boolean;\n /**\n * An optional store to persist the agent's state.\n * @see {@link https://docs.langchain.com/oss/javascript/langgraph/memory#memory-storage | Long-term memory}\n */\n store?: BaseStore;\n /**\n * An optional schema for the final agent output.\n *\n * If provided, output will be formatted to match the given schema and returned in the 'structuredResponse' state key.\n * If not provided, `structuredResponse` will not be present in the output state.\n *\n * Can be passed in as:\n * - Zod schema\n * ```ts\n * const agent = createAgent({\n * responseFormat: z.object({\n * capital: z.string(),\n * }),\n * // ...\n * });\n * ```\n * - JSON schema\n * ```ts\n * const agent = createAgent({\n * responseFormat: {\n * type: \"json_schema\",\n * schema: {\n * type: \"object\",\n * properties: {\n * capital: { type: \"string\" },\n * },\n * required: [\"capital\"],\n * },\n * },\n * // ...\n * });\n * ```\n * - Create React Agent ResponseFormat\n * ```ts\n * import { providerStrategy, toolStrategy } from \"langchain\";\n * const agent = createAgent({\n * responseFormat: providerStrategy(\n * z.object({\n * capital: z.string(),\n * })\n * ),\n * // or\n * responseFormat: [\n * toolStrategy({ ... }),\n * toolStrategy({ ... }),\n * ]\n * // ...\n * });\n * ```\n *\n * **Note**: The graph will make a separate call to the LLM to generate the structured response after the agent loop is finished.\n * This is not the only strategy to get structured responses, see more options in [this guide](https://langchain-ai.github.io/langgraph/how-tos/react-agent-structured-output/).\n */\n responseFormat?: ResponseFormatType;\n /**\n * Middleware instances to run during agent execution.\n * Each middleware can define its own state schema and hook into the agent lifecycle.\n *\n * @see {@link https://docs.langchain.com/oss/javascript/langchain/middleware | Middleware}\n */\n middleware?: readonly AgentMiddleware<any, any, any>[];\n /**\n * An optional name for the agent.\n */\n name?: string;\n /**\n * An optional description for the agent.\n * This can be used to describe the agent to the underlying supervisor LLM.\n */\n description?: string;\n /**\n * Use to specify how to expose the agent name to the underlying supervisor LLM.\n * - `undefined`: Relies on the LLM provider {@link AIMessage#name}. Currently, only OpenAI supports this.\n * - `\"inline\"`: Add the agent name directly into the content field of the {@link AIMessage} using XML-style tags.\n * Example: `\"How can I help you\"` -> `\"<name>agent_name</name><content>How can I help you?</content>\"`\n */\n includeAgentName?: \"inline\" | undefined;\n /**\n * An optional abort signal that indicates that the overall operation should be aborted.\n */\n signal?: AbortSignal;\n /**\n * Determines the version of the graph to create.\n *\n * Can be one of\n * - `\"v1\"`: The tool node processes a single message. All tool calls in the message are\n * executed in parallel within the tool node.\n * - `\"v2\"`: The tool node processes a single tool call. Tool calls are distributed across\n * multiple instances of the tool node using the Send API.\n *\n * @default `\"v2\"`\n */\n version?: \"v1\" | \"v2\";\n};\n/**\n * Type helper to extract union type from an array of Zod schemas\n */\nexport type ExtractZodArrayTypes<T extends readonly InteropZodType<any>[]> = T extends readonly [InteropZodType<infer A>, ...infer Rest] ? Rest extends readonly InteropZodType<any>[] ? A | ExtractZodArrayTypes<Rest> : A : never;\nexport type WithStateGraphNodes<K extends string, Graph> = Graph extends StateGraph<infer SD, infer S, infer U, infer N, infer I, infer O, infer C> ? StateGraph<SD, S, U, N | K, I, O, C> : never;\n"],"mappings":";;;;;;;;;;;;KAWYsB,CAAAA,UAAWpB;AAAvB;AA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,oBAAoBjB,mBAAmBiB,wCAAwChB,eAAeiC,0BAA0BjC,4BAA4Ba,mBAAmBA,qBAAqBJ,iBAAiBE,kBAAkBsB,0BAA0BvB,aAAauB,0BAA0BrB,iBAAiBqB,0BAA0BnB;;;;;;;;;;;;;;;;;;;;;;;;kBAwBvgBV;;;;;;;;;;;;;;;;;;;;;;WAsBPc,aAAaC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;gBAiDRe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAkCEC;;;;;iBAKD7B;;;;;UAKPC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;mBAsDS6B;;;;;;;wBAOKrB;;;;;;;;;;;;;;;;;;;;WAoBbsB;;;;;;;;;;;;;;;;;KAiBDC,wCAAwCtC,yBAAyBuC,oBAAoBvC,0CAA0CwC,sBAAsBxC,wBAAwByC,IAAIH,qBAAqBE,QAAQC;KAC9MC,+CAA+CC,cAAcxC,6EAA6EA,WAAWyC,IAAIC,GAAGC,GAAGzB,IAAI0B,GAAGC,GAAGC,GAAGC"}
|
|
1
|
+
{"version":3,"file":"types.d.ts","names":["InteropZodObject","InteropZodType","START","END","StateGraph","LanguageModelLike","BaseMessage","BaseCheckpointSaver","BaseStore","Messages","ClientTool","ServerTool","ResponseFormat","ToolStrategy","TypedToolStrategy","ProviderStrategy","JsonSchemaFormat","ResponseFormatUndefined","AgentMiddleware","AnyAnnotationRoot","InferSchemaInput","JumpToTarget","N","Interrupt","TValue","BuiltInState","UserInput","TStateSchema","ToolCall","Record","ToolResult","JumpTo","ExecutedToolCall","CreateAgentParams","StructuredResponseType","StateSchema","ContextSchema","ResponseFormatType","AbortSignal","ExtractZodArrayTypes","T","Rest","A","WithStateGraphNodes","Graph","SD","S","U","K","I","O","C"],"sources":["../../src/agents/types.d.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { InteropZodObject, InteropZodType } from \"@langchain/core/utils/types\";\nimport type { START, END, StateGraph } from \"@langchain/langgraph\";\nimport type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport type { BaseMessage } from \"@langchain/core/messages\";\nimport type { BaseCheckpointSaver, BaseStore } from \"@langchain/langgraph-checkpoint\";\nimport type { Messages } from \"@langchain/langgraph/\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\nimport type { ResponseFormat, ToolStrategy, TypedToolStrategy, ProviderStrategy, JsonSchemaFormat, ResponseFormatUndefined } from \"./responses.js\";\nimport type { AgentMiddleware, AnyAnnotationRoot, InferSchemaInput } from \"./middleware/types.js\";\nimport type { JumpToTarget } from \"./constants.js\";\nexport type N = typeof START | \"model_request\" | \"tools\";\n/**\n * Represents information about an interrupt.\n */\nexport interface Interrupt<TValue = unknown> {\n /**\n * The ID of the interrupt.\n */\n id: string;\n /**\n * The requests for human input.\n */\n value: TValue;\n}\nexport interface BuiltInState {\n messages: BaseMessage[];\n __interrupt__?: Interrupt[];\n /**\n * Optional property to control routing after afterModel middleware execution.\n * When set by middleware, the agent will jump to the specified node instead of\n * following normal routing logic. The property is automatically cleared after use.\n *\n * - \"model_request\": Jump back to the model for another LLM call\n * - \"tools\": Jump to tool execution (requires tools to be available)\n */\n jumpTo?: JumpToTarget;\n}\n/**\n * Base input type for `.invoke` and `.stream` methods.\n */\nexport type UserInput<TStateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined> = InferSchemaInput<TStateSchema> & {\n messages: Messages;\n};\n/**\n * Information about a tool call that has been executed.\n */\nexport interface ToolCall {\n /**\n * The ID of the tool call.\n */\n id: string;\n /**\n * The name of the tool that was called.\n */\n name: string;\n /**\n * The arguments that were passed to the tool.\n */\n args: Record<string, any>;\n /**\n * The result of the tool call.\n */\n result?: unknown;\n /**\n * An optional error message if the tool call failed.\n */\n error?: string;\n}\n/**\n * Information about a tool result from a tool execution.\n */\nexport interface ToolResult {\n /**\n * The ID of the tool call.\n */\n id: string;\n /**\n * The result of the tool call.\n */\n result: any;\n /**\n * An optional error message if the tool call failed.\n */\n error?: string;\n}\n/**\n * jump targets (internal)\n */\nexport type JumpTo = \"model_request\" | \"tools\" | typeof END;\n/**\n * Information about a tool call that has been executed.\n */\nexport interface ExecutedToolCall {\n /**\n * The name of the tool that was called.\n */\n name: string;\n /**\n * The arguments that were passed to the tool.\n */\n args: Record<string, unknown>;\n /**\n * The ID of the tool call.\n */\n tool_id: string;\n /**\n * The result of the tool call (if available).\n */\n result?: unknown;\n}\nexport type CreateAgentParams<StructuredResponseType extends Record<string, any> = Record<string, any>, StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ResponseFormatType = InteropZodType<StructuredResponseType> | InteropZodType<unknown>[] | JsonSchemaFormat | JsonSchemaFormat[] | ResponseFormat | TypedToolStrategy<StructuredResponseType> | ToolStrategy<StructuredResponseType> | ProviderStrategy<StructuredResponseType> | ResponseFormatUndefined> = {\n /**\n * Defines a model to use for the agent. You can either pass in an instance of a LangChain chat model\n * or a string. If a string is provided the agent initializes a ChatModel based on the provided model name and provider.\n * It supports various model providers and allows for runtime configuration of model parameters.\n *\n * @uses {@link initChatModel}\n * @example\n * ```ts\n * const agent = createAgent({\n * model: \"anthropic:claude-3-7-sonnet-latest\",\n * // ...\n * });\n * ```\n *\n * @example\n * ```ts\n * import { ChatOpenAI } from \"@langchain/openai\";\n * const agent = createAgent({\n * model: new ChatOpenAI({ model: \"gpt-4o\" }),\n * // ...\n * });\n * ```\n */\n model: string | LanguageModelLike;\n /**\n * A list of tools or a ToolNode.\n *\n * @example\n * ```ts\n * import { tool } from \"langchain\";\n *\n * const weatherTool = tool(() => \"Sunny!\", {\n * name: \"get_weather\",\n * description: \"Get the weather for a location\",\n * schema: z.object({\n * location: z.string().describe(\"The location to get weather for\"),\n * }),\n * });\n *\n * const agent = createAgent({\n * tools: [weatherTool],\n * // ...\n * });\n * ```\n */\n tools?: (ServerTool | ClientTool)[];\n /**\n * An optional system message for the model.\n */\n systemPrompt?: string;\n /**\n * An optional schema for the agent state. It allows you to define custom state properties that persist\n * across agent invocations and can be accessed in hooks, middleware, and throughout the agent's execution.\n * The state is persisted when using a checkpointer and can be updated by middleware or during execution.\n *\n * As opposed to the context (defined in `contextSchema`), the state is persisted between agent invocations\n * when using a checkpointer, making it suitable for maintaining conversation history, user preferences,\n * or any other data that should persist across multiple interactions.\n *\n * @example\n * ```ts\n * import { z } from \"zod\";\n * import { createAgent } from \"@langchain/langgraph\";\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * tools: [getWeather],\n * stateSchema: z.object({\n * userPreferences: z.object({\n * temperatureUnit: z.enum([\"celsius\", \"fahrenheit\"]).default(\"celsius\"),\n * location: z.string().optional(),\n * }).optional(),\n * conversationCount: z.number().default(0),\n * }),\n * prompt: (state, config) => {\n * const unit = state.userPreferences?.temperatureUnit || \"celsius\";\n * return [\n * new SystemMessage(`You are a helpful assistant. Use ${unit} for temperature.`),\n * ];\n * },\n * });\n *\n * const result = await agent.invoke({\n * messages: [\n * new HumanMessage(\"What's the weather like?\"),\n * ],\n * userPreferences: {\n * temperatureUnit: \"fahrenheit\",\n * location: \"New York\",\n * },\n * conversationCount: 1,\n * });\n * ```\n */\n stateSchema?: StateSchema;\n /**\n * An optional schema for the context. It allows to pass in a typed context object into the agent\n * invocation and allows to access it in hooks such as `prompt` and middleware.\n * As opposed to the agent state, defined in `stateSchema`, the context is not persisted between\n * agent invocations.\n *\n * @example\n * ```ts\n * const agent = createAgent({\n * llm: model,\n * tools: [getWeather],\n * contextSchema: z.object({\n * capital: z.string(),\n * }),\n * prompt: (state, config) => {\n * return [\n * new SystemMessage(`You are a helpful assistant. The capital of France is ${config.context.capital}.`),\n * ];\n * },\n * });\n *\n * const result = await agent.invoke({\n * messages: [\n * new SystemMessage(\"You are a helpful assistant.\"),\n * new HumanMessage(\"What is the capital of France?\"),\n * ],\n * }, {\n * context: {\n * capital: \"Paris\",\n * },\n * });\n * ```\n */\n contextSchema?: ContextSchema;\n /**\n * An optional checkpoint saver to persist the agent's state.\n * @see {@link https://docs.langchain.com/oss/javascript/langgraph/persistence | Checkpointing}\n */\n checkpointer?: BaseCheckpointSaver | boolean;\n /**\n * An optional store to persist the agent's state.\n * @see {@link https://docs.langchain.com/oss/javascript/langgraph/memory#memory-storage | Long-term memory}\n */\n store?: BaseStore;\n /**\n * An optional schema for the final agent output.\n *\n * If provided, output will be formatted to match the given schema and returned in the 'structuredResponse' state key.\n * If not provided, `structuredResponse` will not be present in the output state.\n *\n * Can be passed in as:\n * - Zod schema\n * ```ts\n * const agent = createAgent({\n * responseFormat: z.object({\n * capital: z.string(),\n * }),\n * // ...\n * });\n * ```\n * - JSON schema\n * ```ts\n * const agent = createAgent({\n * responseFormat: {\n * type: \"json_schema\",\n * schema: {\n * type: \"object\",\n * properties: {\n * capital: { type: \"string\" },\n * },\n * required: [\"capital\"],\n * },\n * },\n * // ...\n * });\n * ```\n * - Create React Agent ResponseFormat\n * ```ts\n * import { providerStrategy, toolStrategy } from \"langchain\";\n * const agent = createAgent({\n * responseFormat: providerStrategy(\n * z.object({\n * capital: z.string(),\n * })\n * ),\n * // or\n * responseFormat: [\n * toolStrategy({ ... }),\n * toolStrategy({ ... }),\n * ]\n * // ...\n * });\n * ```\n *\n * **Note**: The graph will make a separate call to the LLM to generate the structured response after the agent loop is finished.\n * This is not the only strategy to get structured responses, see more options in [this guide](https://langchain-ai.github.io/langgraph/how-tos/react-agent-structured-output/).\n */\n responseFormat?: ResponseFormatType;\n /**\n * Middleware instances to run during agent execution.\n * Each middleware can define its own state schema and hook into the agent lifecycle.\n *\n * @see {@link https://docs.langchain.com/oss/javascript/langchain/middleware | Middleware}\n */\n middleware?: readonly AgentMiddleware<any, any, any>[];\n /**\n * An optional name for the agent.\n */\n name?: string;\n /**\n * An optional description for the agent.\n * This can be used to describe the agent to the underlying supervisor LLM.\n */\n description?: string;\n /**\n * Use to specify how to expose the agent name to the underlying supervisor LLM.\n * - `undefined`: Relies on the LLM provider {@link AIMessage#name}. Currently, only OpenAI supports this.\n * - `\"inline\"`: Add the agent name directly into the content field of the {@link AIMessage} using XML-style tags.\n * Example: `\"How can I help you\"` -> `\"<name>agent_name</name><content>How can I help you?</content>\"`\n */\n includeAgentName?: \"inline\" | undefined;\n /**\n * An optional abort signal that indicates that the overall operation should be aborted.\n */\n signal?: AbortSignal;\n /**\n * Determines the version of the graph to create.\n *\n * Can be one of\n * - `\"v1\"`: The tool node processes a single message. All tool calls in the message are\n * executed in parallel within the tool node.\n * - `\"v2\"`: The tool node processes a single tool call. Tool calls are distributed across\n * multiple instances of the tool node using the Send API.\n *\n * @default `\"v2\"`\n */\n version?: \"v1\" | \"v2\";\n};\n/**\n * Type helper to extract union type from an array of Zod schemas\n */\nexport type ExtractZodArrayTypes<T extends readonly InteropZodType<any>[]> = T extends readonly [InteropZodType<infer A>, ...infer Rest] ? Rest extends readonly InteropZodType<any>[] ? A | ExtractZodArrayTypes<Rest> : A : never;\nexport type WithStateGraphNodes<K extends string, Graph> = Graph extends StateGraph<infer SD, infer S, infer U, infer N, infer I, infer O, infer C> ? StateGraph<SD, S, U, N | K, I, O, C> : never;\n"],"mappings":";;;;;;;;;;;;KAWYsB,CAAAA,UAAWpB;AAAvB;AAIA;AAUA;AAA6B,UAVZqB,SAUY,CAAA,SAAA,OAAA,CAAA,CAAA;EAAA;;;EAWJ,EAAA,EAAA,MAAA;EAKbG;;;EAAgD,KAAG1B,EAlBpDwB,MAkBoDxB;;AAA4CoB,UAhB1FK,YAAAA,CAgB0FL;EAAgB,QAC7GX,EAhBAH,WAgBAG,EAAAA;EAAQ,aAAA,CAAA,EAfFc,SAeE,EAAA;EAKLK;AAyBjB;AAiBA;AAIA;AAkBA;;;;EAAyF,MAAmCT,CAAAA,EA3E/GE,YA2E+GF;;;;;AAAkLe,KAtElSR,SAsEkSQ,CAAAA,qBAtEnQf,iBAsEmQe,G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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;mBAsDS6B;;;;;;;wBAOKnB;;;;;;;;;;;;;;;;;;;;WAoBboB;;;;;;;;;;;;;;;;;KAiBDC,wCAAwCtC,yBAAyBuC,oBAAoBvC,0CAA0CwC,sBAAsBxC,wBAAwByC,IAAIH,qBAAqBE,QAAQC;KAC9MC,+CAA+CC,cAAcxC,6EAA6EA,WAAWyC,IAAIC,GAAGC,GAAGzB,IAAI0B,GAAGC,GAAGC,GAAGC"}
|
package/dist/agents/utils.cjs
CHANGED
|
@@ -5,6 +5,7 @@ const require_constants = require('./constants.cjs');
|
|
|
5
5
|
const __langchain_core_messages = require_rolldown_runtime.__toESM(require("@langchain/core/messages"));
|
|
6
6
|
const __langchain_core_runnables = require_rolldown_runtime.__toESM(require("@langchain/core/runnables"));
|
|
7
7
|
const __langchain_langgraph = require_rolldown_runtime.__toESM(require("@langchain/langgraph"));
|
|
8
|
+
const __langchain_core_utils_types = require_rolldown_runtime.__toESM(require("@langchain/core/utils/types"));
|
|
8
9
|
|
|
9
10
|
//#region src/agents/utils.ts
|
|
10
11
|
const NAME_PATTERN = /<name>(.*?)<\/name>/s;
|
|
@@ -284,7 +285,7 @@ function chainToolCallHandlers(handlers) {
|
|
|
284
285
|
if (handlers.length === 1) return handlers[0];
|
|
285
286
|
function composeTwo(outer, inner) {
|
|
286
287
|
return async (request, handler) => {
|
|
287
|
-
const innerHandler = async (
|
|
288
|
+
const innerHandler = async () => inner(request, async () => handler(request));
|
|
288
289
|
return outer(request, innerHandler);
|
|
289
290
|
};
|
|
290
291
|
}
|
|
@@ -297,6 +298,7 @@ function chainToolCallHandlers(handlers) {
|
|
|
297
298
|
* the error message.
|
|
298
299
|
*
|
|
299
300
|
* @param middleware list of middleware passed to the agent
|
|
301
|
+
* @param state state of the agent
|
|
300
302
|
* @returns single wrap function
|
|
301
303
|
*/
|
|
302
304
|
function wrapToolCall(middleware) {
|
|
@@ -309,7 +311,13 @@ function wrapToolCall(middleware) {
|
|
|
309
311
|
*/
|
|
310
312
|
const wrappedHandler = async (request, handler) => {
|
|
311
313
|
try {
|
|
312
|
-
const result = await originalHandler(
|
|
314
|
+
const result = await originalHandler({
|
|
315
|
+
...request,
|
|
316
|
+
state: {
|
|
317
|
+
messages: request.state.messages,
|
|
318
|
+
...m.stateSchema ? (0, __langchain_core_utils_types.interopParse)(m.stateSchema, { ...request.state }) : {}
|
|
319
|
+
}
|
|
320
|
+
}, handler);
|
|
313
321
|
/**
|
|
314
322
|
* Validate return type
|
|
315
323
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.cjs","names":["message: T","AIMessage","AIMessageChunk","updatedContent: MessageContent","updatedName: string | undefined","tool: ClientTool | ServerTool","Runnable","llm: LanguageModelLike","isBaseChatModel","toolClasses: (ClientTool | ServerTool)[]","options: Partial<BaseChatModelCallOptions>","RunnableBinding","RunnableSequence","step: RunnableLike","isConfigurableModel","MultipleToolsBoundError","message?: BaseMessage","prompt?: Prompt","promptRunnable: Runnable","RunnableLambda","state: typeof MessagesAnnotation.State","PROMPT_RUNNABLE_NAME","SystemMessage","model","nextSteps: unknown[]","handlers: WrapToolCallHook[]","outer: WrapToolCallHook","inner: WrapToolCallHook","innerHandler: ToolCallHandler","middleware: readonly AgentMiddleware[]","wrappedHandler: WrapToolCallHook","ToolMessage"],"sources":["../../src/agents/utils.ts"],"sourcesContent":["import {\n AIMessage,\n AIMessageChunk,\n BaseMessage,\n BaseMessageLike,\n SystemMessage,\n MessageContent,\n ToolMessage,\n} from \"@langchain/core/messages\";\nimport { MessagesAnnotation, isCommand } from \"@langchain/langgraph\";\nimport {\n BaseChatModel,\n type BaseChatModelCallOptions,\n} from \"@langchain/core/language_models/chat_models\";\nimport {\n LanguageModelLike,\n BaseLanguageModelInput,\n} from \"@langchain/core/language_models/base\";\nimport {\n Runnable,\n RunnableLike,\n RunnableConfig,\n RunnableLambda,\n RunnableSequence,\n RunnableBinding,\n} from \"@langchain/core/runnables\";\n\nimport { isBaseChatModel, isConfigurableModel } from \"./model.js\";\nimport type { ClientTool, ServerTool } from \"./tools.js\";\nimport { MultipleToolsBoundError } from \"./errors.js\";\nimport { PROMPT_RUNNABLE_NAME } from \"./constants.js\";\nimport type { AgentBuiltInState } from \"./runtime.js\";\nimport type {\n ToolCallHandler,\n AgentMiddleware,\n ToolCallRequest,\n WrapToolCallHook,\n} from \"./middleware/types.js\";\n\nconst NAME_PATTERN = /<name>(.*?)<\\/name>/s;\nconst CONTENT_PATTERN = /<content>(.*?)<\\/content>/s;\n\nexport type AgentNameMode = \"inline\";\n\n/**\n * Attach formatted agent names to the messages passed to and from a language model.\n *\n * This is useful for making a message history with multiple agents more coherent.\n *\n * NOTE: agent name is consumed from the message.name field.\n * If you're using an agent built with createAgent, name is automatically set.\n * If you're building a custom agent, make sure to set the name on the AI message returned by the LLM.\n *\n * @param message - Message to add agent name formatting to\n * @returns Message with agent name formatting\n *\n * @internal\n */\nexport function _addInlineAgentName<T extends BaseMessageLike>(\n message: T\n): T | AIMessage {\n if (!AIMessage.isInstance(message) || AIMessageChunk.isInstance(message)) {\n return message;\n }\n\n if (!message.name) {\n return message;\n }\n\n const { name } = message;\n\n if (typeof message.content === \"string\") {\n return new AIMessage({\n ...message.lc_kwargs,\n content: `<name>${name}</name><content>${message.content}</content>`,\n name: undefined,\n });\n }\n\n const updatedContent = [];\n let textBlockCount = 0;\n\n for (const contentBlock of message.content) {\n if (typeof contentBlock === \"string\") {\n textBlockCount += 1;\n updatedContent.push(\n `<name>${name}</name><content>${contentBlock}</content>`\n );\n } else if (\n typeof contentBlock === \"object\" &&\n \"type\" in contentBlock &&\n contentBlock.type === \"text\"\n ) {\n textBlockCount += 1;\n updatedContent.push({\n ...contentBlock,\n text: `<name>${name}</name><content>${contentBlock.text}</content>`,\n });\n } else {\n updatedContent.push(contentBlock);\n }\n }\n\n if (!textBlockCount) {\n updatedContent.unshift({\n type: \"text\",\n text: `<name>${name}</name><content></content>`,\n });\n }\n return new AIMessage({\n ...message.lc_kwargs,\n content: updatedContent as MessageContent,\n name: undefined,\n });\n}\n\n/**\n * Remove explicit name and content XML tags from the AI message content.\n *\n * Examples:\n *\n * @example\n * ```typescript\n * removeInlineAgentName(new AIMessage({ content: \"<name>assistant</name><content>Hello</content>\", name: \"assistant\" }))\n * // AIMessage with content: \"Hello\"\n *\n * removeInlineAgentName(new AIMessage({ content: [{type: \"text\", text: \"<name>assistant</name><content>Hello</content>\"}], name: \"assistant\" }))\n * // AIMessage with content: [{type: \"text\", text: \"Hello\"}]\n * ```\n *\n * @internal\n */\nexport function _removeInlineAgentName<T extends BaseMessage>(message: T): T {\n if (!AIMessage.isInstance(message) || !message.content) {\n return message;\n }\n\n let updatedContent: MessageContent = [];\n let updatedName: string | undefined;\n\n if (Array.isArray(message.content)) {\n updatedContent = message.content\n .filter((block) => {\n if (block.type === \"text\" && typeof block.text === \"string\") {\n const nameMatch = block.text.match(NAME_PATTERN);\n const contentMatch = block.text.match(CONTENT_PATTERN);\n // don't include empty content blocks that were added because there was no text block to modify\n if (nameMatch && (!contentMatch || contentMatch[1] === \"\")) {\n // capture name from text block\n updatedName = nameMatch[1];\n return false;\n }\n return true;\n }\n return true;\n })\n .map((block) => {\n if (block.type === \"text\" && typeof block.text === \"string\") {\n const nameMatch = block.text.match(NAME_PATTERN);\n const contentMatch = block.text.match(CONTENT_PATTERN);\n\n if (!nameMatch || !contentMatch) {\n return block;\n }\n\n // capture name from text block\n updatedName = nameMatch[1];\n\n return {\n ...block,\n text: contentMatch[1],\n };\n }\n return block;\n });\n } else {\n const content = message.content as string;\n const nameMatch = content.match(NAME_PATTERN);\n const contentMatch = content.match(CONTENT_PATTERN);\n\n if (!nameMatch || !contentMatch) {\n return message;\n }\n\n updatedName = nameMatch[1];\n updatedContent = contentMatch[1];\n }\n\n return new AIMessage({\n ...(Object.keys(message.lc_kwargs ?? {}).length > 0\n ? message.lc_kwargs\n : message),\n content: updatedContent,\n name: updatedName,\n }) as T;\n}\n\nexport function isClientTool(\n tool: ClientTool | ServerTool\n): tool is ClientTool {\n return Runnable.isRunnable(tool);\n}\n\n/**\n * Helper function to check if a language model has a bindTools method.\n * @param llm - The language model to check if it has a bindTools method.\n * @returns True if the language model has a bindTools method, false otherwise.\n */\nfunction _isChatModelWithBindTools(\n llm: LanguageModelLike\n): llm is BaseChatModel & Required<Pick<BaseChatModel, \"bindTools\">> {\n if (!isBaseChatModel(llm)) return false;\n return \"bindTools\" in llm && typeof llm.bindTools === \"function\";\n}\n\n/**\n * Helper function to bind tools to a language model.\n * @param llm - The language model to bind tools to.\n * @param toolClasses - The tools to bind to the language model.\n * @param options - The options to pass to the language model.\n * @returns The language model with the tools bound to it.\n */\nconst _simpleBindTools = (\n llm: LanguageModelLike,\n toolClasses: (ClientTool | ServerTool)[],\n options: Partial<BaseChatModelCallOptions> = {}\n) => {\n if (_isChatModelWithBindTools(llm)) {\n return llm.bindTools(toolClasses, options);\n }\n\n if (\n RunnableBinding.isRunnableBinding(llm) &&\n _isChatModelWithBindTools(llm.bound)\n ) {\n const newBound = llm.bound.bindTools(toolClasses, options);\n\n if (RunnableBinding.isRunnableBinding(newBound)) {\n return new RunnableBinding({\n bound: newBound.bound,\n config: { ...llm.config, ...newBound.config },\n kwargs: { ...llm.kwargs, ...newBound.kwargs },\n configFactories: newBound.configFactories ?? llm.configFactories,\n });\n }\n\n return new RunnableBinding({\n bound: newBound,\n config: llm.config,\n kwargs: llm.kwargs,\n configFactories: llm.configFactories,\n });\n }\n\n return null;\n};\n\n/**\n * Check if the LLM already has bound tools and throw if it does.\n *\n * @param llm - The LLM to check.\n * @returns void\n */\nexport function validateLLMHasNoBoundTools(llm: LanguageModelLike): void {\n /**\n * If llm is a function, we can't validate until runtime, so skip\n */\n if (typeof llm === \"function\") {\n return;\n }\n\n let model = llm;\n\n /**\n * If model is a RunnableSequence, find a RunnableBinding in its steps\n */\n if (RunnableSequence.isRunnableSequence(model)) {\n model =\n model.steps.find((step: RunnableLike) =>\n RunnableBinding.isRunnableBinding(step)\n ) || model;\n }\n\n /**\n * If model is configurable, get the underlying model\n */\n if (isConfigurableModel(model)) {\n /**\n * Can't validate async model retrieval in constructor\n */\n return;\n }\n\n /**\n * Check if model is a RunnableBinding with bound tools\n */\n if (RunnableBinding.isRunnableBinding(model)) {\n const hasToolsInKwargs =\n model.kwargs != null &&\n typeof model.kwargs === \"object\" &&\n \"tools\" in model.kwargs &&\n Array.isArray(model.kwargs.tools) &&\n model.kwargs.tools.length > 0;\n\n const hasToolsInConfig =\n model.config != null &&\n typeof model.config === \"object\" &&\n \"tools\" in model.config &&\n Array.isArray(model.config.tools) &&\n model.config.tools.length > 0;\n\n if (hasToolsInKwargs || hasToolsInConfig) {\n throw new MultipleToolsBoundError();\n }\n }\n\n /**\n * Also check if model has tools property directly (e.g., FakeToolCallingModel)\n */\n if (\n \"tools\" in model &&\n model.tools !== undefined &&\n Array.isArray(model.tools) &&\n model.tools.length > 0\n ) {\n throw new MultipleToolsBoundError();\n }\n}\n\n/**\n * Check if the last message in the messages array has tool calls.\n *\n * @param messages - The messages to check.\n * @returns True if the last message has tool calls, false otherwise.\n */\nexport function hasToolCalls(message?: BaseMessage): boolean {\n return Boolean(\n AIMessage.isInstance(message) &&\n message.tool_calls &&\n message.tool_calls.length > 0\n );\n}\n\ntype Prompt = string | SystemMessage;\n\nexport function getPromptRunnable(prompt?: Prompt): Runnable {\n let promptRunnable: Runnable;\n\n if (prompt == null) {\n promptRunnable = RunnableLambda.from(\n (state: typeof MessagesAnnotation.State) => state.messages\n ).withConfig({ runName: PROMPT_RUNNABLE_NAME });\n } else if (typeof prompt === \"string\") {\n const systemMessage = new SystemMessage(prompt);\n promptRunnable = RunnableLambda.from(\n (state: typeof MessagesAnnotation.State) => {\n return [systemMessage, ...(state.messages ?? [])];\n }\n ).withConfig({ runName: PROMPT_RUNNABLE_NAME });\n } else {\n throw new Error(`Got unexpected type for 'prompt': ${typeof prompt}`);\n }\n\n return promptRunnable;\n}\n\n/**\n * Helper function to bind tools to a language model.\n * @param llm - The language model to bind tools to.\n * @param toolClasses - The tools to bind to the language model.\n * @param options - The options to pass to the language model.\n * @returns The language model with the tools bound to it.\n */\nexport async function bindTools(\n llm: LanguageModelLike,\n toolClasses: (ClientTool | ServerTool)[],\n options: Partial<BaseChatModelCallOptions> = {}\n): Promise<\n | RunnableSequence<unknown, unknown>\n | RunnableBinding<unknown, unknown, RunnableConfig<Record<string, unknown>>>\n | Runnable<BaseLanguageModelInput, AIMessageChunk, BaseChatModelCallOptions>\n> {\n const model = _simpleBindTools(llm, toolClasses, options);\n if (model) return model;\n\n if (isConfigurableModel(llm)) {\n const model = _simpleBindTools(await llm._model(), toolClasses, options);\n if (model) return model;\n }\n\n if (RunnableSequence.isRunnableSequence(llm)) {\n const modelStep = llm.steps.findIndex(\n (step) =>\n RunnableBinding.isRunnableBinding(step) ||\n isBaseChatModel(step) ||\n isConfigurableModel(step)\n );\n\n if (modelStep >= 0) {\n const model = _simpleBindTools(\n llm.steps[modelStep],\n toolClasses,\n options\n );\n if (model) {\n const nextSteps: unknown[] = llm.steps.slice();\n nextSteps.splice(modelStep, 1, model);\n\n return RunnableSequence.from(\n nextSteps as [RunnableLike, ...RunnableLike[], RunnableLike]\n );\n }\n }\n }\n\n throw new Error(`llm ${llm} must define bindTools method.`);\n}\n\n/**\n * Compose multiple wrapToolCall handlers into a single middleware stack.\n *\n * Composes handlers so the first in the list becomes the outermost layer.\n * Each handler receives a handler callback to execute inner layers.\n *\n * @param handlers - List of handlers. First handler wraps all others.\n * @returns Composed handler, or undefined if handlers array is empty.\n *\n * @example\n * ```typescript\n * // handlers=[auth, retry] means: auth wraps retry\n * // Flow: auth calls retry, retry calls base handler\n * const auth: ToolCallWrapper = async (request, handler) => {\n * try {\n * return await handler(request);\n * } catch (error) {\n * if (error.message === \"Unauthorized\") {\n * await refreshToken();\n * return await handler(request);\n * }\n * throw error;\n * }\n * };\n *\n * const retry: ToolCallWrapper = async (request, handler) => {\n * for (let attempt = 0; attempt < 3; attempt++) {\n * try {\n * return await handler(request);\n * } catch (error) {\n * if (attempt === 2) throw error;\n * }\n * }\n * throw new Error(\"Unreachable\");\n * };\n *\n * const composedHandler = chainToolCallHandlers([auth, retry]);\n * ```\n */\nfunction chainToolCallHandlers(\n handlers: WrapToolCallHook[]\n): WrapToolCallHook | undefined {\n if (handlers.length === 0) {\n return undefined;\n }\n\n if (handlers.length === 1) {\n return handlers[0];\n }\n\n // Compose two handlers where outer wraps inner\n function composeTwo(\n outer: WrapToolCallHook,\n inner: WrapToolCallHook\n ): WrapToolCallHook {\n return async (request, handler) => {\n // Create a wrapper that calls inner with the base handler\n const innerHandler: ToolCallHandler = async (req) =>\n inner(req, async (innerReq) => handler(innerReq));\n\n // Call outer with the wrapped inner as its handler\n return outer(request, innerHandler);\n };\n }\n\n // Compose right-to-left: outer(inner(innermost(handler)))\n let result = handlers[handlers.length - 1];\n for (let i = handlers.length - 2; i >= 0; i--) {\n result = composeTwo(handlers[i], result);\n }\n\n return result;\n}\n\n/**\n * Wrapping `wrapToolCall` invocation so we can inject middleware name into\n * the error message.\n *\n * @param middleware list of middleware passed to the agent\n * @returns single wrap function\n */\nexport function wrapToolCall(middleware: readonly AgentMiddleware[]) {\n const middlewareWithWrapToolCall = middleware.filter((m) => m.wrapToolCall);\n\n if (middlewareWithWrapToolCall.length === 0) {\n return;\n }\n\n return chainToolCallHandlers(\n middlewareWithWrapToolCall.map((m) => {\n const originalHandler = m.wrapToolCall!;\n /**\n * Wrap with error handling and validation\n */\n const wrappedHandler: WrapToolCallHook = async (request, handler) => {\n try {\n const result = await originalHandler(\n request as ToolCallRequest<AgentBuiltInState, unknown>,\n handler\n );\n\n /**\n * Validate return type\n */\n if (!ToolMessage.isInstance(result) && !isCommand(result)) {\n throw new Error(\n `Invalid response from \"wrapToolCall\" in middleware \"${m.name}\": ` +\n `expected ToolMessage or Command, got ${typeof result}`\n );\n }\n\n return result;\n } catch (error) {\n /**\n * Add middleware context to error if not already added\n */\n if (\n // eslint-disable-next-line no-instanceof/no-instanceof\n error instanceof Error &&\n !error.message.includes(`middleware \"${m.name}\"`)\n ) {\n error.message = `Error in middleware \"${m.name}\": ${error.message}`;\n }\n throw error;\n }\n };\n return wrappedHandler;\n })\n );\n}\n"],"mappings":";;;;;;;;;AAuCA,MAAM,eAAe;AACrB,MAAM,kBAAkB;;;;;;;;;;;;;;;AAkBxB,SAAgB,oBACdA,SACe;AACf,KAAI,CAACC,oCAAU,WAAW,QAAQ,IAAIC,yCAAe,WAAW,QAAQ,CACtE,QAAO;AAGT,KAAI,CAAC,QAAQ,KACX,QAAO;CAGT,MAAM,EAAE,MAAM,GAAG;AAEjB,KAAI,OAAO,QAAQ,YAAY,SAC7B,QAAO,IAAID,oCAAU;EACnB,GAAG,QAAQ;EACX,SAAS,CAAC,MAAM,EAAE,KAAK,gBAAgB,EAAE,QAAQ,QAAQ,UAAU,CAAC;EACpE,MAAM;CACP;CAGH,MAAM,iBAAiB,CAAE;CACzB,IAAI,iBAAiB;AAErB,MAAK,MAAM,gBAAgB,QAAQ,QACjC,KAAI,OAAO,iBAAiB,UAAU;EACpC,kBAAkB;EAClB,eAAe,KACb,CAAC,MAAM,EAAE,KAAK,gBAAgB,EAAE,aAAa,UAAU,CAAC,CACzD;CACF,WACC,OAAO,iBAAiB,YACxB,UAAU,gBACV,aAAa,SAAS,QACtB;EACA,kBAAkB;EAClB,eAAe,KAAK;GAClB,GAAG;GACH,MAAM,CAAC,MAAM,EAAE,KAAK,gBAAgB,EAAE,aAAa,KAAK,UAAU,CAAC;EACpE,EAAC;CACH,OACC,eAAe,KAAK,aAAa;AAIrC,KAAI,CAAC,gBACH,eAAe,QAAQ;EACrB,MAAM;EACN,MAAM,CAAC,MAAM,EAAE,KAAK,0BAA0B,CAAC;CAChD,EAAC;AAEJ,QAAO,IAAIA,oCAAU;EACnB,GAAG,QAAQ;EACX,SAAS;EACT,MAAM;CACP;AACF;;;;;;;;;;;;;;;;;AAkBD,SAA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CAAC,MAAM,QAAQ,SAAS,CAAC,YAAY,EAAE,EAAE,KAAK,CAAC,CAAC,CAAC,EAEjD,MAAM,UAAU,CAAC,qBAAqB,EAAE,EAAE,KAAK,GAAG,EAAE,MAAM,SAAS;AAErE,UAAM;GACP;EACF;AACD,SAAO;CACR,EAAC,CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"utils.cjs","names":["message: T","AIMessage","AIMessageChunk","updatedContent: MessageContent","updatedName: string | undefined","tool: ClientTool | ServerTool","Runnable","llm: LanguageModelLike","isBaseChatModel","toolClasses: (ClientTool | ServerTool)[]","options: Partial<BaseChatModelCallOptions>","RunnableBinding","RunnableSequence","step: RunnableLike","isConfigurableModel","MultipleToolsBoundError","message?: BaseMessage","prompt?: Prompt","promptRunnable: Runnable","RunnableLambda","state: typeof MessagesAnnotation.State","PROMPT_RUNNABLE_NAME","SystemMessage","model","nextSteps: unknown[]","handlers: WrapToolCallHook[]","outer: WrapToolCallHook","inner: WrapToolCallHook","innerHandler: ToolCallHandler","middleware: readonly AgentMiddleware<InteropZodObject | undefined>[]","wrappedHandler: WrapToolCallHook","ToolMessage"],"sources":["../../src/agents/utils.ts"],"sourcesContent":["import {\n AIMessage,\n AIMessageChunk,\n BaseMessage,\n BaseMessageLike,\n SystemMessage,\n MessageContent,\n ToolMessage,\n} from \"@langchain/core/messages\";\nimport { MessagesAnnotation, isCommand } from \"@langchain/langgraph\";\nimport {\n type InteropZodObject,\n interopParse,\n} from \"@langchain/core/utils/types\";\nimport {\n BaseChatModel,\n type BaseChatModelCallOptions,\n} from \"@langchain/core/language_models/chat_models\";\nimport {\n LanguageModelLike,\n BaseLanguageModelInput,\n} from \"@langchain/core/language_models/base\";\nimport {\n Runnable,\n RunnableLike,\n RunnableConfig,\n RunnableLambda,\n RunnableSequence,\n RunnableBinding,\n} from \"@langchain/core/runnables\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport { isBaseChatModel, isConfigurableModel } from \"./model.js\";\nimport { MultipleToolsBoundError } from \"./errors.js\";\nimport { PROMPT_RUNNABLE_NAME } from \"./constants.js\";\nimport type { AgentBuiltInState } from \"./runtime.js\";\nimport type {\n ToolCallHandler,\n AgentMiddleware,\n ToolCallRequest,\n WrapToolCallHook,\n} from \"./middleware/types.js\";\n\nconst NAME_PATTERN = /<name>(.*?)<\\/name>/s;\nconst CONTENT_PATTERN = /<content>(.*?)<\\/content>/s;\n\nexport type AgentNameMode = \"inline\";\n\n/**\n * Attach formatted agent names to the messages passed to and from a language model.\n *\n * This is useful for making a message history with multiple agents more coherent.\n *\n * NOTE: agent name is consumed from the message.name field.\n * If you're using an agent built with createAgent, name is automatically set.\n * If you're building a custom agent, make sure to set the name on the AI message returned by the LLM.\n *\n * @param message - Message to add agent name formatting to\n * @returns Message with agent name formatting\n *\n * @internal\n */\nexport function _addInlineAgentName<T extends BaseMessageLike>(\n message: T\n): T | AIMessage {\n if (!AIMessage.isInstance(message) || AIMessageChunk.isInstance(message)) {\n return message;\n }\n\n if (!message.name) {\n return message;\n }\n\n const { name } = message;\n\n if (typeof message.content === \"string\") {\n return new AIMessage({\n ...message.lc_kwargs,\n content: `<name>${name}</name><content>${message.content}</content>`,\n name: undefined,\n });\n }\n\n const updatedContent = [];\n let textBlockCount = 0;\n\n for (const contentBlock of message.content) {\n if (typeof contentBlock === \"string\") {\n textBlockCount += 1;\n updatedContent.push(\n `<name>${name}</name><content>${contentBlock}</content>`\n );\n } else if (\n typeof contentBlock === \"object\" &&\n \"type\" in contentBlock &&\n contentBlock.type === \"text\"\n ) {\n textBlockCount += 1;\n updatedContent.push({\n ...contentBlock,\n text: `<name>${name}</name><content>${contentBlock.text}</content>`,\n });\n } else {\n updatedContent.push(contentBlock);\n }\n }\n\n if (!textBlockCount) {\n updatedContent.unshift({\n type: \"text\",\n text: `<name>${name}</name><content></content>`,\n });\n }\n return new AIMessage({\n ...message.lc_kwargs,\n content: updatedContent as MessageContent,\n name: undefined,\n });\n}\n\n/**\n * Remove explicit name and content XML tags from the AI message content.\n *\n * Examples:\n *\n * @example\n * ```typescript\n * removeInlineAgentName(new AIMessage({ content: \"<name>assistant</name><content>Hello</content>\", name: \"assistant\" }))\n * // AIMessage with content: \"Hello\"\n *\n * removeInlineAgentName(new AIMessage({ content: [{type: \"text\", text: \"<name>assistant</name><content>Hello</content>\"}], name: \"assistant\" }))\n * // AIMessage with content: [{type: \"text\", text: \"Hello\"}]\n * ```\n *\n * @internal\n */\nexport function _removeInlineAgentName<T extends BaseMessage>(message: T): T {\n if (!AIMessage.isInstance(message) || !message.content) {\n return message;\n }\n\n let updatedContent: MessageContent = [];\n let updatedName: string | undefined;\n\n if (Array.isArray(message.content)) {\n updatedContent = message.content\n .filter((block) => {\n if (block.type === \"text\" && typeof block.text === \"string\") {\n const nameMatch = block.text.match(NAME_PATTERN);\n const contentMatch = block.text.match(CONTENT_PATTERN);\n // don't include empty content blocks that were added because there was no text block to modify\n if (nameMatch && (!contentMatch || contentMatch[1] === \"\")) {\n // capture name from text block\n updatedName = nameMatch[1];\n return false;\n }\n return true;\n }\n return true;\n })\n .map((block) => {\n if (block.type === \"text\" && typeof block.text === \"string\") {\n const nameMatch = block.text.match(NAME_PATTERN);\n const contentMatch = block.text.match(CONTENT_PATTERN);\n\n if (!nameMatch || !contentMatch) {\n return block;\n }\n\n // capture name from text block\n updatedName = nameMatch[1];\n\n return {\n ...block,\n text: contentMatch[1],\n };\n }\n return block;\n });\n } else {\n const content = message.content as string;\n const nameMatch = content.match(NAME_PATTERN);\n const contentMatch = content.match(CONTENT_PATTERN);\n\n if (!nameMatch || !contentMatch) {\n return message;\n }\n\n updatedName = nameMatch[1];\n updatedContent = contentMatch[1];\n }\n\n return new AIMessage({\n ...(Object.keys(message.lc_kwargs ?? {}).length > 0\n ? message.lc_kwargs\n : message),\n content: updatedContent,\n name: updatedName,\n }) as T;\n}\n\nexport function isClientTool(\n tool: ClientTool | ServerTool\n): tool is ClientTool {\n return Runnable.isRunnable(tool);\n}\n\n/**\n * Helper function to check if a language model has a bindTools method.\n * @param llm - The language model to check if it has a bindTools method.\n * @returns True if the language model has a bindTools method, false otherwise.\n */\nfunction _isChatModelWithBindTools(\n llm: LanguageModelLike\n): llm is BaseChatModel & Required<Pick<BaseChatModel, \"bindTools\">> {\n if (!isBaseChatModel(llm)) return false;\n return \"bindTools\" in llm && typeof llm.bindTools === \"function\";\n}\n\n/**\n * Helper function to bind tools to a language model.\n * @param llm - The language model to bind tools to.\n * @param toolClasses - The tools to bind to the language model.\n * @param options - The options to pass to the language model.\n * @returns The language model with the tools bound to it.\n */\nconst _simpleBindTools = (\n llm: LanguageModelLike,\n toolClasses: (ClientTool | ServerTool)[],\n options: Partial<BaseChatModelCallOptions> = {}\n) => {\n if (_isChatModelWithBindTools(llm)) {\n return llm.bindTools(toolClasses, options);\n }\n\n if (\n RunnableBinding.isRunnableBinding(llm) &&\n _isChatModelWithBindTools(llm.bound)\n ) {\n const newBound = llm.bound.bindTools(toolClasses, options);\n\n if (RunnableBinding.isRunnableBinding(newBound)) {\n return new RunnableBinding({\n bound: newBound.bound,\n config: { ...llm.config, ...newBound.config },\n kwargs: { ...llm.kwargs, ...newBound.kwargs },\n configFactories: newBound.configFactories ?? llm.configFactories,\n });\n }\n\n return new RunnableBinding({\n bound: newBound,\n config: llm.config,\n kwargs: llm.kwargs,\n configFactories: llm.configFactories,\n });\n }\n\n return null;\n};\n\n/**\n * Check if the LLM already has bound tools and throw if it does.\n *\n * @param llm - The LLM to check.\n * @returns void\n */\nexport function validateLLMHasNoBoundTools(llm: LanguageModelLike): void {\n /**\n * If llm is a function, we can't validate until runtime, so skip\n */\n if (typeof llm === \"function\") {\n return;\n }\n\n let model = llm;\n\n /**\n * If model is a RunnableSequence, find a RunnableBinding in its steps\n */\n if (RunnableSequence.isRunnableSequence(model)) {\n model =\n model.steps.find((step: RunnableLike) =>\n RunnableBinding.isRunnableBinding(step)\n ) || model;\n }\n\n /**\n * If model is configurable, get the underlying model\n */\n if (isConfigurableModel(model)) {\n /**\n * Can't validate async model retrieval in constructor\n */\n return;\n }\n\n /**\n * Check if model is a RunnableBinding with bound tools\n */\n if (RunnableBinding.isRunnableBinding(model)) {\n const hasToolsInKwargs =\n model.kwargs != null &&\n typeof model.kwargs === \"object\" &&\n \"tools\" in model.kwargs &&\n Array.isArray(model.kwargs.tools) &&\n model.kwargs.tools.length > 0;\n\n const hasToolsInConfig =\n model.config != null &&\n typeof model.config === \"object\" &&\n \"tools\" in model.config &&\n Array.isArray(model.config.tools) &&\n model.config.tools.length > 0;\n\n if (hasToolsInKwargs || hasToolsInConfig) {\n throw new MultipleToolsBoundError();\n }\n }\n\n /**\n * Also check if model has tools property directly (e.g., FakeToolCallingModel)\n */\n if (\n \"tools\" in model &&\n model.tools !== undefined &&\n Array.isArray(model.tools) &&\n model.tools.length > 0\n ) {\n throw new MultipleToolsBoundError();\n }\n}\n\n/**\n * Check if the last message in the messages array has tool calls.\n *\n * @param messages - The messages to check.\n * @returns True if the last message has tool calls, false otherwise.\n */\nexport function hasToolCalls(message?: BaseMessage): boolean {\n return Boolean(\n AIMessage.isInstance(message) &&\n message.tool_calls &&\n message.tool_calls.length > 0\n );\n}\n\ntype Prompt = string | SystemMessage;\n\nexport function getPromptRunnable(prompt?: Prompt): Runnable {\n let promptRunnable: Runnable;\n\n if (prompt == null) {\n promptRunnable = RunnableLambda.from(\n (state: typeof MessagesAnnotation.State) => state.messages\n ).withConfig({ runName: PROMPT_RUNNABLE_NAME });\n } else if (typeof prompt === \"string\") {\n const systemMessage = new SystemMessage(prompt);\n promptRunnable = RunnableLambda.from(\n (state: typeof MessagesAnnotation.State) => {\n return [systemMessage, ...(state.messages ?? [])];\n }\n ).withConfig({ runName: PROMPT_RUNNABLE_NAME });\n } else {\n throw new Error(`Got unexpected type for 'prompt': ${typeof prompt}`);\n }\n\n return promptRunnable;\n}\n\n/**\n * Helper function to bind tools to a language model.\n * @param llm - The language model to bind tools to.\n * @param toolClasses - The tools to bind to the language model.\n * @param options - The options to pass to the language model.\n * @returns The language model with the tools bound to it.\n */\nexport async function bindTools(\n llm: LanguageModelLike,\n toolClasses: (ClientTool | ServerTool)[],\n options: Partial<BaseChatModelCallOptions> = {}\n): Promise<\n | RunnableSequence<unknown, unknown>\n | RunnableBinding<unknown, unknown, RunnableConfig<Record<string, unknown>>>\n | Runnable<BaseLanguageModelInput, AIMessageChunk, BaseChatModelCallOptions>\n> {\n const model = _simpleBindTools(llm, toolClasses, options);\n if (model) return model;\n\n if (isConfigurableModel(llm)) {\n const model = _simpleBindTools(await llm._model(), toolClasses, options);\n if (model) return model;\n }\n\n if (RunnableSequence.isRunnableSequence(llm)) {\n const modelStep = llm.steps.findIndex(\n (step) =>\n RunnableBinding.isRunnableBinding(step) ||\n isBaseChatModel(step) ||\n isConfigurableModel(step)\n );\n\n if (modelStep >= 0) {\n const model = _simpleBindTools(\n llm.steps[modelStep],\n toolClasses,\n options\n );\n if (model) {\n const nextSteps: unknown[] = llm.steps.slice();\n nextSteps.splice(modelStep, 1, model);\n\n return RunnableSequence.from(\n nextSteps as [RunnableLike, ...RunnableLike[], RunnableLike]\n );\n }\n }\n }\n\n throw new Error(`llm ${llm} must define bindTools method.`);\n}\n\n/**\n * Compose multiple wrapToolCall handlers into a single middleware stack.\n *\n * Composes handlers so the first in the list becomes the outermost layer.\n * Each handler receives a handler callback to execute inner layers.\n *\n * @param handlers - List of handlers. First handler wraps all others.\n * @returns Composed handler, or undefined if handlers array is empty.\n *\n * @example\n * ```typescript\n * // handlers=[auth, retry] means: auth wraps retry\n * // Flow: auth calls retry, retry calls base handler\n * const auth: ToolCallWrapper = async (request, handler) => {\n * try {\n * return await handler(request);\n * } catch (error) {\n * if (error.message === \"Unauthorized\") {\n * await refreshToken();\n * return await handler(request);\n * }\n * throw error;\n * }\n * };\n *\n * const retry: ToolCallWrapper = async (request, handler) => {\n * for (let attempt = 0; attempt < 3; attempt++) {\n * try {\n * return await handler(request);\n * } catch (error) {\n * if (attempt === 2) throw error;\n * }\n * }\n * throw new Error(\"Unreachable\");\n * };\n *\n * const composedHandler = chainToolCallHandlers([auth, retry]);\n * ```\n */\nfunction chainToolCallHandlers(\n handlers: WrapToolCallHook[]\n): WrapToolCallHook | undefined {\n if (handlers.length === 0) {\n return undefined;\n }\n\n if (handlers.length === 1) {\n return handlers[0];\n }\n\n // Compose two handlers where outer wraps inner\n function composeTwo(\n outer: WrapToolCallHook,\n inner: WrapToolCallHook\n ): WrapToolCallHook {\n return async (request, handler) => {\n // Create a wrapper that calls inner with the base handler\n const innerHandler: ToolCallHandler = async () =>\n inner(request, async () => handler(request));\n\n // Call outer with the wrapped inner as its handler\n return outer(request, innerHandler);\n };\n }\n\n // Compose right-to-left: outer(inner(innermost(handler)))\n let result = handlers[handlers.length - 1];\n for (let i = handlers.length - 2; i >= 0; i--) {\n result = composeTwo(handlers[i], result);\n }\n\n return result;\n}\n\n/**\n * Wrapping `wrapToolCall` invocation so we can inject middleware name into\n * the error message.\n *\n * @param middleware list of middleware passed to the agent\n * @param state state of the agent\n * @returns single wrap function\n */\nexport function wrapToolCall(\n middleware: readonly AgentMiddleware<InteropZodObject | undefined>[]\n) {\n const middlewareWithWrapToolCall = middleware.filter((m) => m.wrapToolCall);\n\n if (middlewareWithWrapToolCall.length === 0) {\n return;\n }\n\n return chainToolCallHandlers(\n middlewareWithWrapToolCall.map((m) => {\n const originalHandler = m.wrapToolCall!;\n /**\n * Wrap with error handling and validation\n */\n const wrappedHandler: WrapToolCallHook = async (request, handler) => {\n try {\n const result = await originalHandler(\n {\n ...request,\n /**\n * override state with the state from the specific middleware\n */\n state: {\n messages: request.state.messages,\n ...(m.stateSchema\n ? interopParse(m.stateSchema, { ...request.state })\n : {}),\n },\n } as ToolCallRequest<AgentBuiltInState, unknown>,\n handler\n );\n\n /**\n * Validate return type\n */\n if (!ToolMessage.isInstance(result) && !isCommand(result)) {\n throw new Error(\n `Invalid response from \"wrapToolCall\" in middleware \"${m.name}\": ` +\n `expected ToolMessage or Command, got ${typeof result}`\n );\n }\n\n return result;\n } catch (error) {\n /**\n * Add middleware context to error if not already added\n */\n if (\n // eslint-disable-next-line no-instanceof/no-instanceof\n error instanceof Error &&\n !error.message.includes(`middleware \"${m.name}\"`)\n ) {\n error.message = `Error in middleware \"${m.name}\": ${error.message}`;\n }\n throw error;\n }\n };\n return wrappedHandler;\n })\n );\n}\n"],"mappings":";;;;;;;;;;AA2CA,MAAM,eAAe;AACrB,MAAM,kBAAkB;;;;;;;;;;;;;;;AAkBxB,SAAgB,oBACdA,SACe;AACf,KAAI,CAACC,oCAAU,WAAW,QAAQ,IAAIC,yCAAe,WAAW,QAAQ,CACtE,QAAO;AAGT,KAAI,CAAC,QAAQ,KACX,QAAO;CAGT,MAAM,EAAE,MAAM,GAAG;AAEjB,KAAI,OAAO,QAAQ,YAAY,SAC7B,QAAO,IAAID,oCAAU;EACnB,GAAG,QAAQ;EACX,SAAS,CAAC,MAAM,EAAE,KAAK,gBAAgB,EAAE,QAAQ,QAAQ,UAAU,CAAC;EACpE,MAAM;CACP;CAGH,MAAM,iBAAiB,CAAE;CACzB,IAAI,iBAAiB;AAErB,MAAK,MAAM,gBAAgB,QAAQ,QACjC,KAAI,OAAO,iBAAiB,UAAU;EACpC,kBAAkB;EAClB,eAAe,KACb,CAAC,MAAM,EAAE,KAAK,gBAAgB,EAAE,aAAa,UAAU,CAAC,CACzD;CACF,WACC,OAAO,iBAAiB,YACxB,UAAU,gBACV,aAAa,SAAS,QACtB;EACA,kBAAkB;EAClB,eAAe,KAAK;GAClB,GAAG;GACH,MAAM,CAAC,MAAM,EAAE,KAAK,gBAAgB,EAAE,aAAa,KAAK,UAAU,CAAC;EACpE,EAAC;CACH,OACC,eAAe,KAAK,aAAa;AAIrC,KAAI,CAAC,gBACH,eAAe,QAAQ;EACrB,MAAM;EACN,MAAM,CAAC,MAAM,EAAE,KAAK,0BAA0B,CAAC;CAChD,EAAC;AAEJ,QAAO,IAAIA,oCAAU;EACnB,GAAG,QAAQ;EACX,SAAS;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AAW,OAAO,IAAI,sCAAW,OAAO,CACvD,OAAM,IAAI,MACR,CAAC,oDAAoD,EAAE,EAAE,KAAK,wCAAG,EACvB,OAAO,QAAQ;AAI7D,WAAO;GACR,SAAQ,OAAO;;;;AAId,QAEE,iBAAiB,SACjB,CAAC,MAAM,QAAQ,SAAS,CAAC,YAAY,EAAE,EAAE,KAAK,CAAC,CAAC,CAAC,EAEjD,MAAM,UAAU,CAAC,qBAAqB,EAAE,EAAE,KAAK,GAAG,EAAE,MAAM,SAAS;AAErE,UAAM;GACP;EACF;AACD,SAAO;CACR,EAAC,CACH;AACF"}
|
package/dist/agents/utils.js
CHANGED
|
@@ -4,6 +4,7 @@ import { PROMPT_RUNNABLE_NAME } from "./constants.js";
|
|
|
4
4
|
import { AIMessage, AIMessageChunk, SystemMessage, ToolMessage } from "@langchain/core/messages";
|
|
5
5
|
import { Runnable, RunnableBinding, RunnableLambda, RunnableSequence } from "@langchain/core/runnables";
|
|
6
6
|
import { isCommand } from "@langchain/langgraph";
|
|
7
|
+
import { interopParse } from "@langchain/core/utils/types";
|
|
7
8
|
|
|
8
9
|
//#region src/agents/utils.ts
|
|
9
10
|
const NAME_PATTERN = /<name>(.*?)<\/name>/s;
|
|
@@ -283,7 +284,7 @@ function chainToolCallHandlers(handlers) {
|
|
|
283
284
|
if (handlers.length === 1) return handlers[0];
|
|
284
285
|
function composeTwo(outer, inner) {
|
|
285
286
|
return async (request, handler) => {
|
|
286
|
-
const innerHandler = async (
|
|
287
|
+
const innerHandler = async () => inner(request, async () => handler(request));
|
|
287
288
|
return outer(request, innerHandler);
|
|
288
289
|
};
|
|
289
290
|
}
|
|
@@ -296,6 +297,7 @@ function chainToolCallHandlers(handlers) {
|
|
|
296
297
|
* the error message.
|
|
297
298
|
*
|
|
298
299
|
* @param middleware list of middleware passed to the agent
|
|
300
|
+
* @param state state of the agent
|
|
299
301
|
* @returns single wrap function
|
|
300
302
|
*/
|
|
301
303
|
function wrapToolCall(middleware) {
|
|
@@ -308,7 +310,13 @@ function wrapToolCall(middleware) {
|
|
|
308
310
|
*/
|
|
309
311
|
const wrappedHandler = async (request, handler) => {
|
|
310
312
|
try {
|
|
311
|
-
const result = await originalHandler(
|
|
313
|
+
const result = await originalHandler({
|
|
314
|
+
...request,
|
|
315
|
+
state: {
|
|
316
|
+
messages: request.state.messages,
|
|
317
|
+
...m.stateSchema ? interopParse(m.stateSchema, { ...request.state }) : {}
|
|
318
|
+
}
|
|
319
|
+
}, handler);
|
|
312
320
|
/**
|
|
313
321
|
* Validate return type
|
|
314
322
|
*/
|
package/dist/agents/utils.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","names":["message: T","updatedContent: MessageContent","updatedName: string | undefined","tool: ClientTool | ServerTool","llm: LanguageModelLike","toolClasses: (ClientTool | ServerTool)[]","options: Partial<BaseChatModelCallOptions>","step: RunnableLike","message?: BaseMessage","prompt?: Prompt","promptRunnable: Runnable","state: typeof MessagesAnnotation.State","model","nextSteps: unknown[]","handlers: WrapToolCallHook[]","outer: WrapToolCallHook","inner: WrapToolCallHook","innerHandler: ToolCallHandler","middleware: readonly AgentMiddleware[]","wrappedHandler: WrapToolCallHook"],"sources":["../../src/agents/utils.ts"],"sourcesContent":["import {\n AIMessage,\n AIMessageChunk,\n BaseMessage,\n BaseMessageLike,\n SystemMessage,\n MessageContent,\n ToolMessage,\n} from \"@langchain/core/messages\";\nimport { MessagesAnnotation, isCommand } from \"@langchain/langgraph\";\nimport {\n BaseChatModel,\n type BaseChatModelCallOptions,\n} from \"@langchain/core/language_models/chat_models\";\nimport {\n LanguageModelLike,\n BaseLanguageModelInput,\n} from \"@langchain/core/language_models/base\";\nimport {\n Runnable,\n RunnableLike,\n RunnableConfig,\n RunnableLambda,\n RunnableSequence,\n RunnableBinding,\n} from \"@langchain/core/runnables\";\n\nimport { isBaseChatModel, isConfigurableModel } from \"./model.js\";\nimport type { ClientTool, ServerTool } from \"./tools.js\";\nimport { MultipleToolsBoundError } from \"./errors.js\";\nimport { PROMPT_RUNNABLE_NAME } from \"./constants.js\";\nimport type { AgentBuiltInState } from \"./runtime.js\";\nimport type {\n ToolCallHandler,\n AgentMiddleware,\n ToolCallRequest,\n WrapToolCallHook,\n} from \"./middleware/types.js\";\n\nconst NAME_PATTERN = /<name>(.*?)<\\/name>/s;\nconst CONTENT_PATTERN = /<content>(.*?)<\\/content>/s;\n\nexport type AgentNameMode = \"inline\";\n\n/**\n * Attach formatted agent names to the messages passed to and from a language model.\n *\n * This is useful for making a message history with multiple agents more coherent.\n *\n * NOTE: agent name is consumed from the message.name field.\n * If you're using an agent built with createAgent, name is automatically set.\n * If you're building a custom agent, make sure to set the name on the AI message returned by the LLM.\n *\n * @param message - Message to add agent name formatting to\n * @returns Message with agent name formatting\n *\n * @internal\n */\nexport function _addInlineAgentName<T extends BaseMessageLike>(\n message: T\n): T | AIMessage {\n if (!AIMessage.isInstance(message) || AIMessageChunk.isInstance(message)) {\n return message;\n }\n\n if (!message.name) {\n return message;\n }\n\n const { name } = message;\n\n if (typeof message.content === \"string\") {\n return new AIMessage({\n ...message.lc_kwargs,\n content: `<name>${name}</name><content>${message.content}</content>`,\n name: undefined,\n });\n }\n\n const updatedContent = [];\n let textBlockCount = 0;\n\n for (const contentBlock of message.content) {\n if (typeof contentBlock === \"string\") {\n textBlockCount += 1;\n updatedContent.push(\n `<name>${name}</name><content>${contentBlock}</content>`\n );\n } else if (\n typeof contentBlock === \"object\" &&\n \"type\" in contentBlock &&\n contentBlock.type === \"text\"\n ) {\n textBlockCount += 1;\n updatedContent.push({\n ...contentBlock,\n text: `<name>${name}</name><content>${contentBlock.text}</content>`,\n });\n } else {\n updatedContent.push(contentBlock);\n }\n }\n\n if (!textBlockCount) {\n updatedContent.unshift({\n type: \"text\",\n text: `<name>${name}</name><content></content>`,\n });\n }\n return new AIMessage({\n ...message.lc_kwargs,\n content: updatedContent as MessageContent,\n name: undefined,\n });\n}\n\n/**\n * Remove explicit name and content XML tags from the AI message content.\n *\n * Examples:\n *\n * @example\n * ```typescript\n * removeInlineAgentName(new AIMessage({ content: \"<name>assistant</name><content>Hello</content>\", name: \"assistant\" }))\n * // AIMessage with content: \"Hello\"\n *\n * removeInlineAgentName(new AIMessage({ content: [{type: \"text\", text: \"<name>assistant</name><content>Hello</content>\"}], name: \"assistant\" }))\n * // AIMessage with content: [{type: \"text\", text: \"Hello\"}]\n * ```\n *\n * @internal\n */\nexport function _removeInlineAgentName<T extends BaseMessage>(message: T): T {\n if (!AIMessage.isInstance(message) || !message.content) {\n return message;\n }\n\n let updatedContent: MessageContent = [];\n let updatedName: string | undefined;\n\n if (Array.isArray(message.content)) {\n updatedContent = message.content\n .filter((block) => {\n if (block.type === \"text\" && typeof block.text === \"string\") {\n const nameMatch = block.text.match(NAME_PATTERN);\n const contentMatch = block.text.match(CONTENT_PATTERN);\n // don't include empty content blocks that were added because there was no text block to modify\n if (nameMatch && (!contentMatch || contentMatch[1] === \"\")) {\n // capture name from text block\n updatedName = nameMatch[1];\n return false;\n }\n return true;\n }\n return true;\n })\n .map((block) => {\n if (block.type === \"text\" && typeof block.text === \"string\") {\n const nameMatch = block.text.match(NAME_PATTERN);\n const contentMatch = block.text.match(CONTENT_PATTERN);\n\n if (!nameMatch || !contentMatch) {\n return block;\n }\n\n // capture name from text block\n updatedName = nameMatch[1];\n\n return {\n ...block,\n text: contentMatch[1],\n };\n }\n return block;\n });\n } else {\n const content = message.content as string;\n const nameMatch = content.match(NAME_PATTERN);\n const contentMatch = content.match(CONTENT_PATTERN);\n\n if (!nameMatch || !contentMatch) {\n return message;\n }\n\n updatedName = nameMatch[1];\n updatedContent = contentMatch[1];\n }\n\n return new AIMessage({\n ...(Object.keys(message.lc_kwargs ?? {}).length > 0\n ? message.lc_kwargs\n : message),\n content: updatedContent,\n name: updatedName,\n }) as T;\n}\n\nexport function isClientTool(\n tool: ClientTool | ServerTool\n): tool is ClientTool {\n return Runnable.isRunnable(tool);\n}\n\n/**\n * Helper function to check if a language model has a bindTools method.\n * @param llm - The language model to check if it has a bindTools method.\n * @returns True if the language model has a bindTools method, false otherwise.\n */\nfunction _isChatModelWithBindTools(\n llm: LanguageModelLike\n): llm is BaseChatModel & Required<Pick<BaseChatModel, \"bindTools\">> {\n if (!isBaseChatModel(llm)) return false;\n return \"bindTools\" in llm && typeof llm.bindTools === \"function\";\n}\n\n/**\n * Helper function to bind tools to a language model.\n * @param llm - The language model to bind tools to.\n * @param toolClasses - The tools to bind to the language model.\n * @param options - The options to pass to the language model.\n * @returns The language model with the tools bound to it.\n */\nconst _simpleBindTools = (\n llm: LanguageModelLike,\n toolClasses: (ClientTool | ServerTool)[],\n options: Partial<BaseChatModelCallOptions> = {}\n) => {\n if (_isChatModelWithBindTools(llm)) {\n return llm.bindTools(toolClasses, options);\n }\n\n if (\n RunnableBinding.isRunnableBinding(llm) &&\n _isChatModelWithBindTools(llm.bound)\n ) {\n const newBound = llm.bound.bindTools(toolClasses, options);\n\n if (RunnableBinding.isRunnableBinding(newBound)) {\n return new RunnableBinding({\n bound: newBound.bound,\n config: { ...llm.config, ...newBound.config },\n kwargs: { ...llm.kwargs, ...newBound.kwargs },\n configFactories: newBound.configFactories ?? llm.configFactories,\n });\n }\n\n return new RunnableBinding({\n bound: newBound,\n config: llm.config,\n kwargs: llm.kwargs,\n configFactories: llm.configFactories,\n });\n }\n\n return null;\n};\n\n/**\n * Check if the LLM already has bound tools and throw if it does.\n *\n * @param llm - The LLM to check.\n * @returns void\n */\nexport function validateLLMHasNoBoundTools(llm: LanguageModelLike): void {\n /**\n * If llm is a function, we can't validate until runtime, so skip\n */\n if (typeof llm === \"function\") {\n return;\n }\n\n let model = llm;\n\n /**\n * If model is a RunnableSequence, find a RunnableBinding in its steps\n */\n if (RunnableSequence.isRunnableSequence(model)) {\n model =\n model.steps.find((step: RunnableLike) =>\n RunnableBinding.isRunnableBinding(step)\n ) || model;\n }\n\n /**\n * If model is configurable, get the underlying model\n */\n if (isConfigurableModel(model)) {\n /**\n * Can't validate async model retrieval in constructor\n */\n return;\n }\n\n /**\n * Check if model is a RunnableBinding with bound tools\n */\n if (RunnableBinding.isRunnableBinding(model)) {\n const hasToolsInKwargs =\n model.kwargs != null &&\n typeof model.kwargs === \"object\" &&\n \"tools\" in model.kwargs &&\n Array.isArray(model.kwargs.tools) &&\n model.kwargs.tools.length > 0;\n\n const hasToolsInConfig =\n model.config != null &&\n typeof model.config === \"object\" &&\n \"tools\" in model.config &&\n Array.isArray(model.config.tools) &&\n model.config.tools.length > 0;\n\n if (hasToolsInKwargs || hasToolsInConfig) {\n throw new MultipleToolsBoundError();\n }\n }\n\n /**\n * Also check if model has tools property directly (e.g., FakeToolCallingModel)\n */\n if (\n \"tools\" in model &&\n model.tools !== undefined &&\n Array.isArray(model.tools) &&\n model.tools.length > 0\n ) {\n throw new MultipleToolsBoundError();\n }\n}\n\n/**\n * Check if the last message in the messages array has tool calls.\n *\n * @param messages - The messages to check.\n * @returns True if the last message has tool calls, false otherwise.\n */\nexport function hasToolCalls(message?: BaseMessage): boolean {\n return Boolean(\n AIMessage.isInstance(message) &&\n message.tool_calls &&\n message.tool_calls.length > 0\n );\n}\n\ntype Prompt = string | SystemMessage;\n\nexport function getPromptRunnable(prompt?: Prompt): Runnable {\n let promptRunnable: Runnable;\n\n if (prompt == null) {\n promptRunnable = RunnableLambda.from(\n (state: typeof MessagesAnnotation.State) => state.messages\n ).withConfig({ runName: PROMPT_RUNNABLE_NAME });\n } else if (typeof prompt === \"string\") {\n const systemMessage = new SystemMessage(prompt);\n promptRunnable = RunnableLambda.from(\n (state: typeof MessagesAnnotation.State) => {\n return [systemMessage, ...(state.messages ?? [])];\n }\n ).withConfig({ runName: PROMPT_RUNNABLE_NAME });\n } else {\n throw new Error(`Got unexpected type for 'prompt': ${typeof prompt}`);\n }\n\n return promptRunnable;\n}\n\n/**\n * Helper function to bind tools to a language model.\n * @param llm - The language model to bind tools to.\n * @param toolClasses - The tools to bind to the language model.\n * @param options - The options to pass to the language model.\n * @returns The language model with the tools bound to it.\n */\nexport async function bindTools(\n llm: LanguageModelLike,\n toolClasses: (ClientTool | ServerTool)[],\n options: Partial<BaseChatModelCallOptions> = {}\n): Promise<\n | RunnableSequence<unknown, unknown>\n | RunnableBinding<unknown, unknown, RunnableConfig<Record<string, unknown>>>\n | Runnable<BaseLanguageModelInput, AIMessageChunk, BaseChatModelCallOptions>\n> {\n const model = _simpleBindTools(llm, toolClasses, options);\n if (model) return model;\n\n if (isConfigurableModel(llm)) {\n const model = _simpleBindTools(await llm._model(), toolClasses, options);\n if (model) return model;\n }\n\n if (RunnableSequence.isRunnableSequence(llm)) {\n const modelStep = llm.steps.findIndex(\n (step) =>\n RunnableBinding.isRunnableBinding(step) ||\n isBaseChatModel(step) ||\n isConfigurableModel(step)\n );\n\n if (modelStep >= 0) {\n const model = _simpleBindTools(\n llm.steps[modelStep],\n toolClasses,\n options\n );\n if (model) {\n const nextSteps: unknown[] = llm.steps.slice();\n nextSteps.splice(modelStep, 1, model);\n\n return RunnableSequence.from(\n nextSteps as [RunnableLike, ...RunnableLike[], RunnableLike]\n );\n }\n }\n }\n\n throw new Error(`llm ${llm} must define bindTools method.`);\n}\n\n/**\n * Compose multiple wrapToolCall handlers into a single middleware stack.\n *\n * Composes handlers so the first in the list becomes the outermost layer.\n * Each handler receives a handler callback to execute inner layers.\n *\n * @param handlers - List of handlers. First handler wraps all others.\n * @returns Composed handler, or undefined if handlers array is empty.\n *\n * @example\n * ```typescript\n * // handlers=[auth, retry] means: auth wraps retry\n * // Flow: auth calls retry, retry calls base handler\n * const auth: ToolCallWrapper = async (request, handler) => {\n * try {\n * return await handler(request);\n * } catch (error) {\n * if (error.message === \"Unauthorized\") {\n * await refreshToken();\n * return await handler(request);\n * }\n * throw error;\n * }\n * };\n *\n * const retry: ToolCallWrapper = async (request, handler) => {\n * for (let attempt = 0; attempt < 3; attempt++) {\n * try {\n * return await handler(request);\n * } catch (error) {\n * if (attempt === 2) throw error;\n * }\n * }\n * throw new Error(\"Unreachable\");\n * };\n *\n * const composedHandler = chainToolCallHandlers([auth, retry]);\n * ```\n */\nfunction chainToolCallHandlers(\n handlers: WrapToolCallHook[]\n): WrapToolCallHook | undefined {\n if (handlers.length === 0) {\n return undefined;\n }\n\n if (handlers.length === 1) {\n return handlers[0];\n }\n\n // Compose two handlers where outer wraps inner\n function composeTwo(\n outer: WrapToolCallHook,\n inner: WrapToolCallHook\n ): WrapToolCallHook {\n return async (request, handler) => {\n // Create a wrapper that calls inner with the base handler\n const innerHandler: ToolCallHandler = async (req) =>\n inner(req, async (innerReq) => handler(innerReq));\n\n // Call outer with the wrapped inner as its handler\n return outer(request, innerHandler);\n };\n }\n\n // Compose right-to-left: outer(inner(innermost(handler)))\n let result = handlers[handlers.length - 1];\n for (let i = handlers.length - 2; i >= 0; i--) {\n result = composeTwo(handlers[i], result);\n }\n\n return result;\n}\n\n/**\n * Wrapping `wrapToolCall` invocation so we can inject middleware name into\n * the error message.\n *\n * @param middleware list of middleware passed to the agent\n * @returns single wrap function\n */\nexport function wrapToolCall(middleware: readonly AgentMiddleware[]) {\n const middlewareWithWrapToolCall = middleware.filter((m) => m.wrapToolCall);\n\n if (middlewareWithWrapToolCall.length === 0) {\n return;\n }\n\n return chainToolCallHandlers(\n middlewareWithWrapToolCall.map((m) => {\n const originalHandler = m.wrapToolCall!;\n /**\n * Wrap with error handling and validation\n */\n const wrappedHandler: WrapToolCallHook = async (request, handler) => {\n try {\n const result = await originalHandler(\n request as ToolCallRequest<AgentBuiltInState, unknown>,\n handler\n );\n\n /**\n * Validate return type\n */\n if (!ToolMessage.isInstance(result) && !isCommand(result)) {\n throw new Error(\n `Invalid response from \"wrapToolCall\" in middleware \"${m.name}\": ` +\n `expected ToolMessage or Command, got ${typeof result}`\n );\n }\n\n return result;\n } catch (error) {\n /**\n * Add middleware context to error if not already added\n */\n if (\n // eslint-disable-next-line no-instanceof/no-instanceof\n error instanceof Error &&\n !error.message.includes(`middleware \"${m.name}\"`)\n ) {\n error.message = `Error in middleware \"${m.name}\": ${error.message}`;\n }\n throw error;\n }\n };\n return wrappedHandler;\n })\n );\n}\n"],"mappings":";;;;;;;;AAuCA,MAAM,eAAe;AACrB,MAAM,kBAAkB;;;;;;;;;;;;;;;AAkBxB,SAAgB,oBACdA,SACe;AACf,KAAI,CAAC,UAAU,WAAW,QAAQ,IAAI,eAAe,WAAW,QAAQ,CACtE,QAAO;AAGT,KAAI,CAAC,QAAQ,KACX,QAAO;CAGT,MAAM,EAAE,MAAM,GAAG;AAEjB,KAAI,OAAO,QAAQ,YAAY,SAC7B,QAAO,IAAI,UAAU;EACnB,GAAG,QAAQ;EACX,SAAS,CAAC,MAAM,EAAE,KAAK,gBAAgB,EAAE,QAAQ,QAAQ,UAAU,CAAC;EACpE,MAAM;CACP;CAGH,MAAM,iBAAiB,CAAE;CACzB,IAAI,iBAAiB;AAErB,MAAK,MAAM,gBAAgB,QAAQ,QACjC,KAAI,OAAO,iBAAiB,UAAU;EACpC,kBAAkB;EAClB,eAAe,KACb,CAAC,MAAM,EAAE,KAAK,gBAAgB,EAAE,aAAa,UAAU,CAAC,CACzD;CACF,WACC,OAAO,iBAAiB,YACxB,UAAU,gBACV,aAAa,SAAS,QACtB;EACA,kBAAkB;EAClB,eAAe,KAAK;GAClB,GAAG;GACH,MAAM,CAAC,MAAM,EAAE,KAAK,gBAAgB,EAAE,aAAa,KAAK,UAAU,CAAC;EACpE,EAAC;CACH,OACC,eAAe,KAAK,aAAa;AAIrC,KAAI,CAAC,gBACH,eAAe,QAAQ;EACrB,MAAM;EACN,MAAM,CAAC,MAAM,EAAE,KAAK,0BAA0B,CAAC;CAChD,EAAC;AAEJ,QAAO,IAAI,UAAU;EACnB,GAAG,QAAQ;EACX,SAAS;EACT,MAAM;CACP;AACF;;;;;;;;;;;;;;;;;AAkBD,SAAgB,uBAA8CA,SAAe;AAC3E,KAAI,CAAC,UAAU,WAAW,QAAQ,IAAI,CAAC,QAAQ,QAC7C,QAAO;CAGT,IAA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EAAE,MAAM,SAAS;AAErE,UAAM;GACP;EACF;AACD,SAAO;CACR,EAAC,CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"utils.js","names":["message: T","updatedContent: MessageContent","updatedName: string | undefined","tool: ClientTool | ServerTool","llm: LanguageModelLike","toolClasses: (ClientTool | ServerTool)[]","options: Partial<BaseChatModelCallOptions>","step: RunnableLike","message?: BaseMessage","prompt?: Prompt","promptRunnable: Runnable","state: typeof MessagesAnnotation.State","model","nextSteps: unknown[]","handlers: WrapToolCallHook[]","outer: WrapToolCallHook","inner: WrapToolCallHook","innerHandler: ToolCallHandler","middleware: readonly AgentMiddleware<InteropZodObject | undefined>[]","wrappedHandler: WrapToolCallHook"],"sources":["../../src/agents/utils.ts"],"sourcesContent":["import {\n AIMessage,\n AIMessageChunk,\n BaseMessage,\n BaseMessageLike,\n SystemMessage,\n MessageContent,\n ToolMessage,\n} from \"@langchain/core/messages\";\nimport { MessagesAnnotation, isCommand } from \"@langchain/langgraph\";\nimport {\n type InteropZodObject,\n interopParse,\n} from \"@langchain/core/utils/types\";\nimport {\n BaseChatModel,\n type BaseChatModelCallOptions,\n} from \"@langchain/core/language_models/chat_models\";\nimport {\n LanguageModelLike,\n BaseLanguageModelInput,\n} from \"@langchain/core/language_models/base\";\nimport {\n Runnable,\n RunnableLike,\n RunnableConfig,\n RunnableLambda,\n RunnableSequence,\n RunnableBinding,\n} from \"@langchain/core/runnables\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport { isBaseChatModel, isConfigurableModel } from \"./model.js\";\nimport { MultipleToolsBoundError } from \"./errors.js\";\nimport { PROMPT_RUNNABLE_NAME } from \"./constants.js\";\nimport type { AgentBuiltInState } from \"./runtime.js\";\nimport type {\n ToolCallHandler,\n AgentMiddleware,\n ToolCallRequest,\n WrapToolCallHook,\n} from \"./middleware/types.js\";\n\nconst NAME_PATTERN = /<name>(.*?)<\\/name>/s;\nconst CONTENT_PATTERN = /<content>(.*?)<\\/content>/s;\n\nexport type AgentNameMode = \"inline\";\n\n/**\n * Attach formatted agent names to the messages passed to and from a language model.\n *\n * This is useful for making a message history with multiple agents more coherent.\n *\n * NOTE: agent name is consumed from the message.name field.\n * If you're using an agent built with createAgent, name is automatically set.\n * If you're building a custom agent, make sure to set the name on the AI message returned by the LLM.\n *\n * @param message - Message to add agent name formatting to\n * @returns Message with agent name formatting\n *\n * @internal\n */\nexport function _addInlineAgentName<T extends BaseMessageLike>(\n message: T\n): T | AIMessage {\n if (!AIMessage.isInstance(message) || AIMessageChunk.isInstance(message)) {\n return message;\n }\n\n if (!message.name) {\n return message;\n }\n\n const { name } = message;\n\n if (typeof message.content === \"string\") {\n return new AIMessage({\n ...message.lc_kwargs,\n content: `<name>${name}</name><content>${message.content}</content>`,\n name: undefined,\n });\n }\n\n const updatedContent = [];\n let textBlockCount = 0;\n\n for (const contentBlock of message.content) {\n if (typeof contentBlock === \"string\") {\n textBlockCount += 1;\n updatedContent.push(\n `<name>${name}</name><content>${contentBlock}</content>`\n );\n } else if (\n typeof contentBlock === \"object\" &&\n \"type\" in contentBlock &&\n contentBlock.type === \"text\"\n ) {\n textBlockCount += 1;\n updatedContent.push({\n ...contentBlock,\n text: `<name>${name}</name><content>${contentBlock.text}</content>`,\n });\n } else {\n updatedContent.push(contentBlock);\n }\n }\n\n if (!textBlockCount) {\n updatedContent.unshift({\n type: \"text\",\n text: `<name>${name}</name><content></content>`,\n });\n }\n return new AIMessage({\n ...message.lc_kwargs,\n content: updatedContent as MessageContent,\n name: undefined,\n });\n}\n\n/**\n * Remove explicit name and content XML tags from the AI message content.\n *\n * Examples:\n *\n * @example\n * ```typescript\n * removeInlineAgentName(new AIMessage({ content: \"<name>assistant</name><content>Hello</content>\", name: \"assistant\" }))\n * // AIMessage with content: \"Hello\"\n *\n * removeInlineAgentName(new AIMessage({ content: [{type: \"text\", text: \"<name>assistant</name><content>Hello</content>\"}], name: \"assistant\" }))\n * // AIMessage with content: [{type: \"text\", text: \"Hello\"}]\n * ```\n *\n * @internal\n */\nexport function _removeInlineAgentName<T extends BaseMessage>(message: T): T {\n if (!AIMessage.isInstance(message) || !message.content) {\n return message;\n }\n\n let updatedContent: MessageContent = [];\n let updatedName: string | undefined;\n\n if (Array.isArray(message.content)) {\n updatedContent = message.content\n .filter((block) => {\n if (block.type === \"text\" && typeof block.text === \"string\") {\n const nameMatch = block.text.match(NAME_PATTERN);\n const contentMatch = block.text.match(CONTENT_PATTERN);\n // don't include empty content blocks that were added because there was no text block to modify\n if (nameMatch && (!contentMatch || contentMatch[1] === \"\")) {\n // capture name from text block\n updatedName = nameMatch[1];\n return false;\n }\n return true;\n }\n return true;\n })\n .map((block) => {\n if (block.type === \"text\" && typeof block.text === \"string\") {\n const nameMatch = block.text.match(NAME_PATTERN);\n const contentMatch = block.text.match(CONTENT_PATTERN);\n\n if (!nameMatch || !contentMatch) {\n return block;\n }\n\n // capture name from text block\n updatedName = nameMatch[1];\n\n return {\n ...block,\n text: contentMatch[1],\n };\n }\n return block;\n });\n } else {\n const content = message.content as string;\n const nameMatch = content.match(NAME_PATTERN);\n const contentMatch = content.match(CONTENT_PATTERN);\n\n if (!nameMatch || !contentMatch) {\n return message;\n }\n\n updatedName = nameMatch[1];\n updatedContent = contentMatch[1];\n }\n\n return new AIMessage({\n ...(Object.keys(message.lc_kwargs ?? {}).length > 0\n ? message.lc_kwargs\n : message),\n content: updatedContent,\n name: updatedName,\n }) as T;\n}\n\nexport function isClientTool(\n tool: ClientTool | ServerTool\n): tool is ClientTool {\n return Runnable.isRunnable(tool);\n}\n\n/**\n * Helper function to check if a language model has a bindTools method.\n * @param llm - The language model to check if it has a bindTools method.\n * @returns True if the language model has a bindTools method, false otherwise.\n */\nfunction _isChatModelWithBindTools(\n llm: LanguageModelLike\n): llm is BaseChatModel & Required<Pick<BaseChatModel, \"bindTools\">> {\n if (!isBaseChatModel(llm)) return false;\n return \"bindTools\" in llm && typeof llm.bindTools === \"function\";\n}\n\n/**\n * Helper function to bind tools to a language model.\n * @param llm - The language model to bind tools to.\n * @param toolClasses - The tools to bind to the language model.\n * @param options - The options to pass to the language model.\n * @returns The language model with the tools bound to it.\n */\nconst _simpleBindTools = (\n llm: LanguageModelLike,\n toolClasses: (ClientTool | ServerTool)[],\n options: Partial<BaseChatModelCallOptions> = {}\n) => {\n if (_isChatModelWithBindTools(llm)) {\n return llm.bindTools(toolClasses, options);\n }\n\n if (\n RunnableBinding.isRunnableBinding(llm) &&\n _isChatModelWithBindTools(llm.bound)\n ) {\n const newBound = llm.bound.bindTools(toolClasses, options);\n\n if (RunnableBinding.isRunnableBinding(newBound)) {\n return new RunnableBinding({\n bound: newBound.bound,\n config: { ...llm.config, ...newBound.config },\n kwargs: { ...llm.kwargs, ...newBound.kwargs },\n configFactories: newBound.configFactories ?? llm.configFactories,\n });\n }\n\n return new RunnableBinding({\n bound: newBound,\n config: llm.config,\n kwargs: llm.kwargs,\n configFactories: llm.configFactories,\n });\n }\n\n return null;\n};\n\n/**\n * Check if the LLM already has bound tools and throw if it does.\n *\n * @param llm - The LLM to check.\n * @returns void\n */\nexport function validateLLMHasNoBoundTools(llm: LanguageModelLike): void {\n /**\n * If llm is a function, we can't validate until runtime, so skip\n */\n if (typeof llm === \"function\") {\n return;\n }\n\n let model = llm;\n\n /**\n * If model is a RunnableSequence, find a RunnableBinding in its steps\n */\n if (RunnableSequence.isRunnableSequence(model)) {\n model =\n model.steps.find((step: RunnableLike) =>\n RunnableBinding.isRunnableBinding(step)\n ) || model;\n }\n\n /**\n * If model is configurable, get the underlying model\n */\n if (isConfigurableModel(model)) {\n /**\n * Can't validate async model retrieval in constructor\n */\n return;\n }\n\n /**\n * Check if model is a RunnableBinding with bound tools\n */\n if (RunnableBinding.isRunnableBinding(model)) {\n const hasToolsInKwargs =\n model.kwargs != null &&\n typeof model.kwargs === \"object\" &&\n \"tools\" in model.kwargs &&\n Array.isArray(model.kwargs.tools) &&\n model.kwargs.tools.length > 0;\n\n const hasToolsInConfig =\n model.config != null &&\n typeof model.config === \"object\" &&\n \"tools\" in model.config &&\n Array.isArray(model.config.tools) &&\n model.config.tools.length > 0;\n\n if (hasToolsInKwargs || hasToolsInConfig) {\n throw new MultipleToolsBoundError();\n }\n }\n\n /**\n * Also check if model has tools property directly (e.g., FakeToolCallingModel)\n */\n if (\n \"tools\" in model &&\n model.tools !== undefined &&\n Array.isArray(model.tools) &&\n model.tools.length > 0\n ) {\n throw new MultipleToolsBoundError();\n }\n}\n\n/**\n * Check if the last message in the messages array has tool calls.\n *\n * @param messages - The messages to check.\n * @returns True if the last message has tool calls, false otherwise.\n */\nexport function hasToolCalls(message?: BaseMessage): boolean {\n return Boolean(\n AIMessage.isInstance(message) &&\n message.tool_calls &&\n message.tool_calls.length > 0\n );\n}\n\ntype Prompt = string | SystemMessage;\n\nexport function getPromptRunnable(prompt?: Prompt): Runnable {\n let promptRunnable: Runnable;\n\n if (prompt == null) {\n promptRunnable = RunnableLambda.from(\n (state: typeof MessagesAnnotation.State) => state.messages\n ).withConfig({ runName: PROMPT_RUNNABLE_NAME });\n } else if (typeof prompt === \"string\") {\n const systemMessage = new SystemMessage(prompt);\n promptRunnable = RunnableLambda.from(\n (state: typeof MessagesAnnotation.State) => {\n return [systemMessage, ...(state.messages ?? [])];\n }\n ).withConfig({ runName: PROMPT_RUNNABLE_NAME });\n } else {\n throw new Error(`Got unexpected type for 'prompt': ${typeof prompt}`);\n }\n\n return promptRunnable;\n}\n\n/**\n * Helper function to bind tools to a language model.\n * @param llm - The language model to bind tools to.\n * @param toolClasses - The tools to bind to the language model.\n * @param options - The options to pass to the language model.\n * @returns The language model with the tools bound to it.\n */\nexport async function bindTools(\n llm: LanguageModelLike,\n toolClasses: (ClientTool | ServerTool)[],\n options: Partial<BaseChatModelCallOptions> = {}\n): Promise<\n | RunnableSequence<unknown, unknown>\n | RunnableBinding<unknown, unknown, RunnableConfig<Record<string, unknown>>>\n | Runnable<BaseLanguageModelInput, AIMessageChunk, BaseChatModelCallOptions>\n> {\n const model = _simpleBindTools(llm, toolClasses, options);\n if (model) return model;\n\n if (isConfigurableModel(llm)) {\n const model = _simpleBindTools(await llm._model(), toolClasses, options);\n if (model) return model;\n }\n\n if (RunnableSequence.isRunnableSequence(llm)) {\n const modelStep = llm.steps.findIndex(\n (step) =>\n RunnableBinding.isRunnableBinding(step) ||\n isBaseChatModel(step) ||\n isConfigurableModel(step)\n );\n\n if (modelStep >= 0) {\n const model = _simpleBindTools(\n llm.steps[modelStep],\n toolClasses,\n options\n );\n if (model) {\n const nextSteps: unknown[] = llm.steps.slice();\n nextSteps.splice(modelStep, 1, model);\n\n return RunnableSequence.from(\n nextSteps as [RunnableLike, ...RunnableLike[], RunnableLike]\n );\n }\n }\n }\n\n throw new Error(`llm ${llm} must define bindTools method.`);\n}\n\n/**\n * Compose multiple wrapToolCall handlers into a single middleware stack.\n *\n * Composes handlers so the first in the list becomes the outermost layer.\n * Each handler receives a handler callback to execute inner layers.\n *\n * @param handlers - List of handlers. First handler wraps all others.\n * @returns Composed handler, or undefined if handlers array is empty.\n *\n * @example\n * ```typescript\n * // handlers=[auth, retry] means: auth wraps retry\n * // Flow: auth calls retry, retry calls base handler\n * const auth: ToolCallWrapper = async (request, handler) => {\n * try {\n * return await handler(request);\n * } catch (error) {\n * if (error.message === \"Unauthorized\") {\n * await refreshToken();\n * return await handler(request);\n * }\n * throw error;\n * }\n * };\n *\n * const retry: ToolCallWrapper = async (request, handler) => {\n * for (let attempt = 0; attempt < 3; attempt++) {\n * try {\n * return await handler(request);\n * } catch (error) {\n * if (attempt === 2) throw error;\n * }\n * }\n * throw new Error(\"Unreachable\");\n * };\n *\n * const composedHandler = chainToolCallHandlers([auth, retry]);\n * ```\n */\nfunction chainToolCallHandlers(\n handlers: WrapToolCallHook[]\n): WrapToolCallHook | undefined {\n if (handlers.length === 0) {\n return undefined;\n }\n\n if (handlers.length === 1) {\n return handlers[0];\n }\n\n // Compose two handlers where outer wraps inner\n function composeTwo(\n outer: WrapToolCallHook,\n inner: WrapToolCallHook\n ): WrapToolCallHook {\n return async (request, handler) => {\n // Create a wrapper that calls inner with the base handler\n const innerHandler: ToolCallHandler = async () =>\n inner(request, async () => handler(request));\n\n // Call outer with the wrapped inner as its handler\n return outer(request, innerHandler);\n };\n }\n\n // Compose right-to-left: outer(inner(innermost(handler)))\n let result = handlers[handlers.length - 1];\n for (let i = handlers.length - 2; i >= 0; i--) {\n result = composeTwo(handlers[i], result);\n }\n\n return result;\n}\n\n/**\n * Wrapping `wrapToolCall` invocation so we can inject middleware name into\n * the error message.\n *\n * @param middleware list of middleware passed to the agent\n * @param state state of the agent\n * @returns single wrap function\n */\nexport function wrapToolCall(\n middleware: readonly AgentMiddleware<InteropZodObject | undefined>[]\n) {\n const middlewareWithWrapToolCall = middleware.filter((m) => m.wrapToolCall);\n\n if (middlewareWithWrapToolCall.length === 0) {\n return;\n }\n\n return chainToolCallHandlers(\n middlewareWithWrapToolCall.map((m) => {\n const originalHandler = m.wrapToolCall!;\n /**\n * Wrap with error handling and validation\n */\n const wrappedHandler: WrapToolCallHook = async (request, handler) => {\n try {\n const result = await originalHandler(\n {\n ...request,\n /**\n * override state with the state from the specific middleware\n */\n state: {\n messages: request.state.messages,\n ...(m.stateSchema\n ? interopParse(m.stateSchema, { ...request.state })\n : {}),\n },\n } as ToolCallRequest<AgentBuiltInState, unknown>,\n handler\n );\n\n /**\n * Validate return type\n */\n if (!ToolMessage.isInstance(result) && !isCommand(result)) {\n throw new Error(\n `Invalid response from \"wrapToolCall\" in middleware \"${m.name}\": ` +\n `expected ToolMessage or Command, got ${typeof result}`\n );\n }\n\n return result;\n } catch (error) {\n /**\n * Add middleware context to error if not already added\n */\n if (\n // eslint-disable-next-line no-instanceof/no-instanceof\n error instanceof Error &&\n !error.message.includes(`middleware \"${m.name}\"`)\n ) {\n error.message = `Error in middleware \"${m.name}\": ${error.message}`;\n }\n throw error;\n }\n };\n return wrappedHandler;\n })\n );\n}\n"],"mappings":";;;;;;;;;AA2CA,MAAM,eAAe;AAC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,GAAG,EAAE,MAAM,SAAS;AAErE,UAAM;GACP;EACF;AACD,SAAO;CACR,EAAC,CACH;AACF"}
|
|
@@ -104,7 +104,7 @@ async function getChatModelByClassName(className) {
|
|
|
104
104
|
return module$1[config.className];
|
|
105
105
|
} catch (e) {
|
|
106
106
|
const err = e;
|
|
107
|
-
if ("code" in err && err.code?.toString().includes("ERR_MODULE_NOT_FOUND")) {
|
|
107
|
+
if ("code" in err && err.code?.toString().includes("ERR_MODULE_NOT_FOUND") && "message" in err) {
|
|
108
108
|
const attemptedPackage = err.message.split("Error: Cannot find package '")[1].split("'")[0];
|
|
109
109
|
throw new Error(`Unable to import ${attemptedPackage}. Please install with \`npm install ${attemptedPackage}\` or \`pnpm install ${attemptedPackage}\``);
|
|
110
110
|
}
|
|
@@ -138,7 +138,7 @@ async function _initChatModelHelper(model, modelProvider, params = {}) {
|
|
|
138
138
|
* _inferModelProvider("unknown-model"); // returns undefined
|
|
139
139
|
*/
|
|
140
140
|
function _inferModelProvider(modelName) {
|
|
141
|
-
if (modelName.startsWith("gpt-3") || modelName.startsWith("gpt-4") || modelName.startsWith("o1") || modelName.startsWith("o3") || modelName.startsWith("o4")) return "openai";
|
|
141
|
+
if (modelName.startsWith("gpt-3") || modelName.startsWith("gpt-4") || modelName.startsWith("gpt-5") || modelName.startsWith("o1") || modelName.startsWith("o3") || modelName.startsWith("o4")) return "openai";
|
|
142
142
|
else if (modelName.startsWith("claude")) return "anthropic";
|
|
143
143
|
else if (modelName.startsWith("command")) return "cohere";
|
|
144
144
|
else if (modelName.startsWith("accounts/fireworks")) return "fireworks";
|