langchain 1.1.2 → 1.1.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 +20 -0
- package/dist/agents/ReactAgent.cjs +30 -14
- package/dist/agents/ReactAgent.cjs.map +1 -1
- package/dist/agents/ReactAgent.d.cts +5 -3
- package/dist/agents/ReactAgent.d.ts +5 -3
- package/dist/agents/ReactAgent.js +30 -14
- package/dist/agents/ReactAgent.js.map +1 -1
- package/dist/agents/annotation.cjs +32 -24
- package/dist/agents/annotation.cjs.map +1 -1
- package/dist/agents/annotation.js +34 -26
- package/dist/agents/annotation.js.map +1 -1
- package/dist/agents/index.cjs.map +1 -1
- package/dist/agents/index.d.cts +1 -12
- package/dist/agents/index.d.ts +1 -12
- package/dist/agents/index.js.map +1 -1
- package/dist/agents/middleware/types.d.cts +18 -1
- package/dist/agents/middleware/types.d.ts +18 -1
- package/dist/agents/model.cjs +1 -1
- package/dist/agents/model.cjs.map +1 -1
- package/dist/agents/model.js +1 -1
- package/dist/agents/model.js.map +1 -1
- package/dist/agents/nodes/AgentNode.cjs +14 -1
- package/dist/agents/nodes/AgentNode.cjs.map +1 -1
- package/dist/agents/nodes/AgentNode.js +14 -1
- package/dist/agents/nodes/AgentNode.js.map +1 -1
- package/dist/agents/nodes/ToolNode.cjs.map +1 -1
- package/dist/agents/nodes/ToolNode.js.map +1 -1
- package/dist/agents/responses.d.cts +0 -2
- package/dist/agents/responses.d.ts +0 -2
- package/dist/agents/runtime.d.cts +1 -3
- package/dist/agents/runtime.d.ts +1 -3
- package/dist/agents/tests/utils.d.cts +0 -4
- package/dist/agents/tests/utils.d.ts +0 -4
- package/dist/agents/utils.cjs +1 -1
- package/dist/agents/utils.cjs.map +1 -1
- package/dist/agents/utils.js +1 -1
- package/dist/agents/utils.js.map +1 -1
- package/dist/chat_models/universal.d.cts +4 -21
- package/dist/chat_models/universal.d.ts +4 -21
- package/dist/hub/index.d.cts +0 -1
- package/dist/hub/index.d.ts +0 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/load/import_type.d.cts +0 -1
- package/dist/load/import_type.d.ts +0 -1
- package/dist/load/index.d.cts +1 -7
- package/dist/load/index.d.ts +1 -7
- package/dist/storage/encoder_backed.d.cts +0 -1
- package/dist/storage/encoder_backed.d.ts +0 -1
- package/package.json +4 -4
package/dist/agents/index.d.cts
CHANGED
|
@@ -2,7 +2,7 @@ import { MultipleStructuredOutputsError, MultipleToolsBoundError, StructuredOutp
|
|
|
2
2
|
import { JsonSchemaFormat, ProviderStrategy, ResponseFormat, ResponseFormatUndefined, ToolStrategy, TypedToolStrategy, providerStrategy, toolStrategy } from "./responses.cjs";
|
|
3
3
|
import { JumpToTarget } from "./constants.cjs";
|
|
4
4
|
import { Runtime } from "./runtime.cjs";
|
|
5
|
-
import { AgentMiddleware, AnyAnnotationRoot, ToolCallHandler, ToolCallRequest, WrapToolCallHook } from "./middleware/types.cjs";
|
|
5
|
+
import { AfterAgentHook, AfterModelHook, AgentMiddleware, AnyAnnotationRoot, BeforeAgentHook, BeforeModelHook, InferChannelType, InferContextInput, InferMergedInputState, InferMergedState, InferMiddlewareContext, InferMiddlewareContextInput, InferMiddlewareContextInputs, InferMiddlewareContexts, InferMiddlewareInputState, InferMiddlewareInputStates, InferMiddlewareState, InferMiddlewareStates, InferSchemaInput, MiddlewareResult, NormalizedSchemaInput, ToAnnotationRoot, ToolCallHandler, ToolCallRequest, WrapModelCallHandler, WrapModelCallHook, WrapToolCallHook } from "./middleware/types.cjs";
|
|
6
6
|
import { BuiltInState, CreateAgentParams, ExecutedToolCall, ExtractZodArrayTypes, Interrupt, JumpTo, N, ToolCall, ToolResult, UserInput, WithStateGraphNodes } from "./types.cjs";
|
|
7
7
|
import { ReactAgent } from "./ReactAgent.cjs";
|
|
8
8
|
import { createMiddleware } from "./middleware.cjs";
|
|
@@ -130,56 +130,45 @@ import { InteropZodObject, InteropZodType } from "@langchain/core/utils/types";
|
|
|
130
130
|
* }
|
|
131
131
|
* ```
|
|
132
132
|
*/
|
|
133
|
-
// Overload 1: With responseFormat as single InteropZodType
|
|
134
133
|
declare function createAgent<T extends Record<string, any> = Record<string, any>, StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]>(params: CreateAgentParams<T, StateSchema, ContextSchema, InteropZodType<T>> & {
|
|
135
134
|
responseFormat: InteropZodType<T>;
|
|
136
135
|
middleware?: TMiddleware;
|
|
137
136
|
}): ReactAgent<T, StateSchema, ContextSchema, TMiddleware>;
|
|
138
|
-
// Overload 2: With responseFormat as array of InteropZodTypes (infers union type)
|
|
139
137
|
declare function createAgent<T extends readonly InteropZodType<any>[], StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]>(params: CreateAgentParams<ExtractZodArrayTypes<T> extends Record<string, any> ? ExtractZodArrayTypes<T> : Record<string, any>, StateSchema, ContextSchema, T> & {
|
|
140
138
|
responseFormat: T;
|
|
141
139
|
middleware?: TMiddleware;
|
|
142
140
|
}): ReactAgent<ExtractZodArrayTypes<T> extends Record<string, any> ? ExtractZodArrayTypes<T> : Record<string, any>, StateSchema, ContextSchema, TMiddleware>;
|
|
143
|
-
// Overload 3: With responseFormat as JsonSchemaFormat (JSON schema object)
|
|
144
141
|
declare function createAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]>(params: CreateAgentParams<Record<string, unknown>, StateSchema, ContextSchema, JsonSchemaFormat> & {
|
|
145
142
|
responseFormat: JsonSchemaFormat;
|
|
146
143
|
middleware?: TMiddleware;
|
|
147
144
|
}): ReactAgent<Record<string, unknown>, StateSchema, ContextSchema, TMiddleware>;
|
|
148
|
-
// Overload 4: With responseFormat as array of JsonSchemaFormat (JSON schema objects)
|
|
149
145
|
declare function createAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]>(params: CreateAgentParams<Record<string, unknown>, StateSchema, ContextSchema, JsonSchemaFormat[]> & {
|
|
150
146
|
responseFormat: JsonSchemaFormat[];
|
|
151
147
|
middleware?: TMiddleware;
|
|
152
148
|
}): ReactAgent<Record<string, unknown>, StateSchema, ContextSchema, TMiddleware>;
|
|
153
|
-
// Overload 4.5: With responseFormat as union of JsonSchemaFormat | JsonSchemaFormat[]
|
|
154
149
|
declare function createAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]>(params: CreateAgentParams<Record<string, unknown>, StateSchema, ContextSchema, JsonSchemaFormat | JsonSchemaFormat[]> & {
|
|
155
150
|
responseFormat: JsonSchemaFormat | JsonSchemaFormat[];
|
|
156
151
|
middleware?: TMiddleware;
|
|
157
152
|
}): ReactAgent<Record<string, unknown>, StateSchema, ContextSchema, TMiddleware>;
|
|
158
|
-
// Overload 5: With responseFormat as TypedToolStrategy (for union types from toolStrategy)
|
|
159
153
|
declare function createAgent<T extends Record<string, any> = Record<string, any>, StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]>(params: CreateAgentParams<T, StateSchema, ContextSchema, TypedToolStrategy<T>> & {
|
|
160
154
|
responseFormat: TypedToolStrategy<T>;
|
|
161
155
|
middleware?: TMiddleware;
|
|
162
156
|
}): ReactAgent<T, StateSchema, ContextSchema, TMiddleware>;
|
|
163
|
-
// Overload 6: With responseFormat as single ToolStrategy instance
|
|
164
157
|
declare function createAgent<T extends Record<string, any> = Record<string, any>, StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]>(params: CreateAgentParams<T, StateSchema, ContextSchema, ToolStrategy<T>> & {
|
|
165
158
|
responseFormat: ToolStrategy<T>;
|
|
166
159
|
middleware?: TMiddleware;
|
|
167
160
|
}): ReactAgent<T, StateSchema, ContextSchema, TMiddleware>;
|
|
168
|
-
// Overload 7: With responseFormat as ProviderStrategy
|
|
169
161
|
declare function createAgent<T extends Record<string, any> = Record<string, any>, StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]>(params: CreateAgentParams<T, StateSchema, ContextSchema, ProviderStrategy<T>> & {
|
|
170
162
|
responseFormat: ProviderStrategy<T>;
|
|
171
163
|
middleware?: TMiddleware;
|
|
172
164
|
}): ReactAgent<T, StateSchema, ContextSchema, TMiddleware>;
|
|
173
|
-
// Overload 8: Without responseFormat property at all - with proper middleware state typing
|
|
174
165
|
declare function createAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]>(params: Omit<CreateAgentParams<ResponseFormatUndefined, StateSchema, ContextSchema, never>, "responseFormat"> & {
|
|
175
166
|
middleware?: TMiddleware;
|
|
176
167
|
}): ReactAgent<ResponseFormatUndefined, StateSchema, ContextSchema, TMiddleware>;
|
|
177
|
-
// Overload 9: With responseFormat explicitly undefined
|
|
178
168
|
declare function createAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]>(params: Omit<CreateAgentParams<ResponseFormatUndefined, StateSchema, ContextSchema, never>, "responseFormat"> & {
|
|
179
169
|
responseFormat?: undefined;
|
|
180
170
|
middleware?: TMiddleware;
|
|
181
171
|
}): ReactAgent<ResponseFormatUndefined, StateSchema, ContextSchema, TMiddleware>;
|
|
182
|
-
// Overload 10: For other ResponseFormat values (failsafe)
|
|
183
172
|
declare function createAgent<StructuredResponseFormat extends Record<string, any> = Record<string, any>, StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]>(params: CreateAgentParams<StructuredResponseFormat, StateSchema, ContextSchema, ResponseFormat> & {
|
|
184
173
|
responseFormat: ResponseFormat;
|
|
185
174
|
middleware?: TMiddleware;
|
package/dist/agents/index.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { MultipleStructuredOutputsError, MultipleToolsBoundError, StructuredOutp
|
|
|
2
2
|
import { JsonSchemaFormat, ProviderStrategy, ResponseFormat, ResponseFormatUndefined, ToolStrategy, TypedToolStrategy, providerStrategy, toolStrategy } from "./responses.js";
|
|
3
3
|
import { JumpToTarget } from "./constants.js";
|
|
4
4
|
import { Runtime } from "./runtime.js";
|
|
5
|
-
import { AgentMiddleware, AnyAnnotationRoot, ToolCallHandler, ToolCallRequest, WrapToolCallHook } from "./middleware/types.js";
|
|
5
|
+
import { AfterAgentHook, AfterModelHook, AgentMiddleware, AnyAnnotationRoot, BeforeAgentHook, BeforeModelHook, InferChannelType, InferContextInput, InferMergedInputState, InferMergedState, InferMiddlewareContext, InferMiddlewareContextInput, InferMiddlewareContextInputs, InferMiddlewareContexts, InferMiddlewareInputState, InferMiddlewareInputStates, InferMiddlewareState, InferMiddlewareStates, InferSchemaInput, MiddlewareResult, NormalizedSchemaInput, ToAnnotationRoot, ToolCallHandler, ToolCallRequest, WrapModelCallHandler, WrapModelCallHook, WrapToolCallHook } from "./middleware/types.js";
|
|
6
6
|
import { BuiltInState, CreateAgentParams, ExecutedToolCall, ExtractZodArrayTypes, Interrupt, JumpTo, N, ToolCall, ToolResult, UserInput, WithStateGraphNodes } from "./types.js";
|
|
7
7
|
import { ReactAgent } from "./ReactAgent.js";
|
|
8
8
|
import { createMiddleware } from "./middleware.js";
|
|
@@ -130,56 +130,45 @@ import { InteropZodObject, InteropZodType } from "@langchain/core/utils/types";
|
|
|
130
130
|
* }
|
|
131
131
|
* ```
|
|
132
132
|
*/
|
|
133
|
-
// Overload 1: With responseFormat as single InteropZodType
|
|
134
133
|
declare function createAgent<T extends Record<string, any> = Record<string, any>, StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]>(params: CreateAgentParams<T, StateSchema, ContextSchema, InteropZodType<T>> & {
|
|
135
134
|
responseFormat: InteropZodType<T>;
|
|
136
135
|
middleware?: TMiddleware;
|
|
137
136
|
}): ReactAgent<T, StateSchema, ContextSchema, TMiddleware>;
|
|
138
|
-
// Overload 2: With responseFormat as array of InteropZodTypes (infers union type)
|
|
139
137
|
declare function createAgent<T extends readonly InteropZodType<any>[], StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]>(params: CreateAgentParams<ExtractZodArrayTypes<T> extends Record<string, any> ? ExtractZodArrayTypes<T> : Record<string, any>, StateSchema, ContextSchema, T> & {
|
|
140
138
|
responseFormat: T;
|
|
141
139
|
middleware?: TMiddleware;
|
|
142
140
|
}): ReactAgent<ExtractZodArrayTypes<T> extends Record<string, any> ? ExtractZodArrayTypes<T> : Record<string, any>, StateSchema, ContextSchema, TMiddleware>;
|
|
143
|
-
// Overload 3: With responseFormat as JsonSchemaFormat (JSON schema object)
|
|
144
141
|
declare function createAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]>(params: CreateAgentParams<Record<string, unknown>, StateSchema, ContextSchema, JsonSchemaFormat> & {
|
|
145
142
|
responseFormat: JsonSchemaFormat;
|
|
146
143
|
middleware?: TMiddleware;
|
|
147
144
|
}): ReactAgent<Record<string, unknown>, StateSchema, ContextSchema, TMiddleware>;
|
|
148
|
-
// Overload 4: With responseFormat as array of JsonSchemaFormat (JSON schema objects)
|
|
149
145
|
declare function createAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]>(params: CreateAgentParams<Record<string, unknown>, StateSchema, ContextSchema, JsonSchemaFormat[]> & {
|
|
150
146
|
responseFormat: JsonSchemaFormat[];
|
|
151
147
|
middleware?: TMiddleware;
|
|
152
148
|
}): ReactAgent<Record<string, unknown>, StateSchema, ContextSchema, TMiddleware>;
|
|
153
|
-
// Overload 4.5: With responseFormat as union of JsonSchemaFormat | JsonSchemaFormat[]
|
|
154
149
|
declare function createAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]>(params: CreateAgentParams<Record<string, unknown>, StateSchema, ContextSchema, JsonSchemaFormat | JsonSchemaFormat[]> & {
|
|
155
150
|
responseFormat: JsonSchemaFormat | JsonSchemaFormat[];
|
|
156
151
|
middleware?: TMiddleware;
|
|
157
152
|
}): ReactAgent<Record<string, unknown>, StateSchema, ContextSchema, TMiddleware>;
|
|
158
|
-
// Overload 5: With responseFormat as TypedToolStrategy (for union types from toolStrategy)
|
|
159
153
|
declare function createAgent<T extends Record<string, any> = Record<string, any>, StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]>(params: CreateAgentParams<T, StateSchema, ContextSchema, TypedToolStrategy<T>> & {
|
|
160
154
|
responseFormat: TypedToolStrategy<T>;
|
|
161
155
|
middleware?: TMiddleware;
|
|
162
156
|
}): ReactAgent<T, StateSchema, ContextSchema, TMiddleware>;
|
|
163
|
-
// Overload 6: With responseFormat as single ToolStrategy instance
|
|
164
157
|
declare function createAgent<T extends Record<string, any> = Record<string, any>, StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]>(params: CreateAgentParams<T, StateSchema, ContextSchema, ToolStrategy<T>> & {
|
|
165
158
|
responseFormat: ToolStrategy<T>;
|
|
166
159
|
middleware?: TMiddleware;
|
|
167
160
|
}): ReactAgent<T, StateSchema, ContextSchema, TMiddleware>;
|
|
168
|
-
// Overload 7: With responseFormat as ProviderStrategy
|
|
169
161
|
declare function createAgent<T extends Record<string, any> = Record<string, any>, StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]>(params: CreateAgentParams<T, StateSchema, ContextSchema, ProviderStrategy<T>> & {
|
|
170
162
|
responseFormat: ProviderStrategy<T>;
|
|
171
163
|
middleware?: TMiddleware;
|
|
172
164
|
}): ReactAgent<T, StateSchema, ContextSchema, TMiddleware>;
|
|
173
|
-
// Overload 8: Without responseFormat property at all - with proper middleware state typing
|
|
174
165
|
declare function createAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]>(params: Omit<CreateAgentParams<ResponseFormatUndefined, StateSchema, ContextSchema, never>, "responseFormat"> & {
|
|
175
166
|
middleware?: TMiddleware;
|
|
176
167
|
}): ReactAgent<ResponseFormatUndefined, StateSchema, ContextSchema, TMiddleware>;
|
|
177
|
-
// Overload 9: With responseFormat explicitly undefined
|
|
178
168
|
declare function createAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]>(params: Omit<CreateAgentParams<ResponseFormatUndefined, StateSchema, ContextSchema, never>, "responseFormat"> & {
|
|
179
169
|
responseFormat?: undefined;
|
|
180
170
|
middleware?: TMiddleware;
|
|
181
171
|
}): ReactAgent<ResponseFormatUndefined, StateSchema, ContextSchema, TMiddleware>;
|
|
182
|
-
// Overload 10: For other ResponseFormat values (failsafe)
|
|
183
172
|
declare function createAgent<StructuredResponseFormat extends Record<string, any> = Record<string, any>, StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]>(params: CreateAgentParams<StructuredResponseFormat, StateSchema, ContextSchema, ResponseFormat> & {
|
|
184
173
|
responseFormat: ResponseFormat;
|
|
185
174
|
middleware?: TMiddleware;
|
package/dist/agents/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["params: CreateAgentParams<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema,\n any\n >"],"sources":["../../src/agents/index.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type {\n InteropZodObject,\n InteropZodType,\n} from \"@langchain/core/utils/types\";\n\nimport type { ResponseFormatUndefined } from \"./responses.js\";\nimport type { CreateAgentParams } from \"./types.js\";\nimport type { AgentMiddleware, AnyAnnotationRoot } from \"./middleware/types.js\";\nimport type { ExtractZodArrayTypes } from \"./types.js\";\nimport type {\n ToolStrategy,\n TypedToolStrategy,\n ProviderStrategy,\n ResponseFormat,\n JsonSchemaFormat,\n} from \"./responses.js\";\nimport { ReactAgent } from \"./ReactAgent.js\";\n\n/**\n * Creates a production-ready ReAct (Reasoning + Acting) agent that combines language models with tools\n * and middleware to create systems that can reason about tasks, decide which tools to use, and iteratively\n * work towards solutions.\n *\n * The agent follows the ReAct pattern, interleaving reasoning steps with tool calls to iteratively\n * work towards solutions. It can handle multiple tool calls in sequence or parallel, maintain state\n * across interactions, and provide auditable decision processes.\n *\n * ## Core Components\n *\n * ### Model\n * The reasoning engine can be specified as:\n * - **String identifier**: `\"openai:gpt-4o\"` for simple setup\n * - **Model instance**: Configured model object for full control\n * - **Dynamic function**: Select models at runtime based on state\n *\n * ### Tools\n * Tools give agents the ability to take actions:\n * - Pass an array of tools created with the `tool` function\n * - Or provide a configured `ToolNode` for custom error handling\n *\n * ### Prompt\n * Shape how your agent approaches tasks:\n * - String for simple instructions\n * - SystemMessage for structured prompts\n * - Function for dynamic prompts based on state\n *\n * ### Middleware\n * Middleware allows you to extend the agent's behavior:\n * - Add pre/post-model processing for context injection or validation\n * - Add dynamic control flows, e.g. terminate invocation or retries\n * - Add human-in-the-loop capabilities\n * - Add tool calls to the agent\n * - Add tool results to the agent\n *\n * ## Advanced Features\n *\n * - **Structured Output**: Use `responseFormat` with a Zod schema to get typed responses\n * - **Memory**: Extend the state schema to remember information across interactions\n * - **Streaming**: Get real-time updates as the agent processes\n *\n * @param options - Configuration options for the agent\n * @param options.llm - The language model as an instance of a chat model\n * @param options.model - The language model as a string identifier, see more in {@link https://docs.langchain.com/oss/javascript/langchain/models#basic-usage | Models}.\n * @param options.tools - Array of tools or configured ToolNode\n * @param options.prompt - System instructions (string, SystemMessage, or function)\n * @param options.responseFormat - Zod schema for structured output\n * @param options.stateSchema - Custom state schema for memory\n * @param options.middleware - Array of middleware for extending agent behavior, see more in {@link https://docs.langchain.com/oss/javascript/langchain/middleware | Middleware}.\n *\n * @returns A ReactAgent instance with `invoke` and `stream` methods\n *\n * @example Basic agent with tools\n * ```ts\n * import { createAgent, tool } from \"langchain\";\n * import { z } from \"zod\";\n *\n * const search = tool(\n * ({ query }) => `Results for: ${query}`,\n * {\n * name: \"search\",\n * description: \"Search for information\",\n * schema: z.object({\n * query: z.string().describe(\"The search query\"),\n * })\n * }\n * );\n *\n * const agent = createAgent({\n * llm: \"openai:gpt-4o\",\n * tools: [search],\n * });\n *\n * const result = await agent.invoke({\n * messages: [{ role: \"user\", content: \"Search for ReAct agents\" }],\n * });\n * ```\n *\n * @example Structured output\n * ```ts\n * import { createAgent } from \"langchain\";\n * import { z } from \"zod\";\n *\n * const ContactInfo = z.object({\n * name: z.string(),\n * email: z.string(),\n * phone: z.string(),\n * });\n *\n * const agent = createAgent({\n * llm: \"openai:gpt-4o\",\n * tools: [],\n * responseFormat: ContactInfo,\n * });\n *\n * const result = await agent.invoke({\n * messages: [{\n * role: \"user\",\n * content: \"Extract: John Doe, john@example.com, (555) 123-4567\"\n * }],\n * });\n *\n * console.log(result.structuredResponse);\n * // { name: 'John Doe', email: 'john@example.com', phone: '(555) 123-4567' }\n * ```\n *\n * @example Streaming responses\n * ```ts\n * const stream = await agent.stream(\n * { messages: [{ role: \"user\", content: \"What's the weather?\" }] },\n * { streamMode: \"values\" }\n * );\n *\n * for await (const chunk of stream) {\n * // ...\n * }\n * ```\n */\n// Overload 1: With responseFormat as single InteropZodType\nexport function createAgent<\n T extends Record<string, any> = Record<string, any>,\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n T,\n StateSchema,\n ContextSchema,\n InteropZodType<T>\n > & {\n responseFormat: InteropZodType<T>;\n middleware?: TMiddleware;\n }\n): ReactAgent<T, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 2: With responseFormat as array of InteropZodTypes (infers union type)\nexport function createAgent<\n T extends readonly InteropZodType<any>[],\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n ExtractZodArrayTypes<T> extends Record<string, any>\n ? ExtractZodArrayTypes<T>\n : Record<string, any>,\n StateSchema,\n ContextSchema,\n T\n > & {\n responseFormat: T;\n middleware?: TMiddleware;\n }\n): ReactAgent<\n ExtractZodArrayTypes<T> extends Record<string, any>\n ? ExtractZodArrayTypes<T>\n : Record<string, any>,\n StateSchema,\n ContextSchema,\n TMiddleware\n>;\n\n// Overload 3: With responseFormat as JsonSchemaFormat (JSON schema object)\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n Record<string, unknown>,\n StateSchema,\n ContextSchema,\n JsonSchemaFormat\n > & {\n responseFormat: JsonSchemaFormat;\n middleware?: TMiddleware;\n }\n): ReactAgent<Record<string, unknown>, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 4: With responseFormat as array of JsonSchemaFormat (JSON schema objects)\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n Record<string, unknown>,\n StateSchema,\n ContextSchema,\n JsonSchemaFormat[]\n > & {\n responseFormat: JsonSchemaFormat[];\n middleware?: TMiddleware;\n }\n): ReactAgent<Record<string, unknown>, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 4.5: With responseFormat as union of JsonSchemaFormat | JsonSchemaFormat[]\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n Record<string, unknown>,\n StateSchema,\n ContextSchema,\n JsonSchemaFormat | JsonSchemaFormat[]\n > & {\n responseFormat: JsonSchemaFormat | JsonSchemaFormat[];\n middleware?: TMiddleware;\n }\n): ReactAgent<Record<string, unknown>, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 5: With responseFormat as TypedToolStrategy (for union types from toolStrategy)\nexport function createAgent<\n T extends Record<string, any> = Record<string, any>,\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n T,\n StateSchema,\n ContextSchema,\n TypedToolStrategy<T>\n > & {\n responseFormat: TypedToolStrategy<T>;\n middleware?: TMiddleware;\n }\n): ReactAgent<T, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 6: With responseFormat as single ToolStrategy instance\nexport function createAgent<\n T extends Record<string, any> = Record<string, any>,\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<T, StateSchema, ContextSchema, ToolStrategy<T>> & {\n responseFormat: ToolStrategy<T>;\n middleware?: TMiddleware;\n }\n): ReactAgent<T, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 7: With responseFormat as ProviderStrategy\nexport function createAgent<\n T extends Record<string, any> = Record<string, any>,\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n T,\n StateSchema,\n ContextSchema,\n ProviderStrategy<T>\n > & {\n responseFormat: ProviderStrategy<T>;\n middleware?: TMiddleware;\n }\n): ReactAgent<T, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 8: Without responseFormat property at all - with proper middleware state typing\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: Omit<\n CreateAgentParams<\n ResponseFormatUndefined,\n StateSchema,\n ContextSchema,\n never\n >,\n \"responseFormat\"\n > & { middleware?: TMiddleware }\n): ReactAgent<ResponseFormatUndefined, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 9: With responseFormat explicitly undefined\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: Omit<\n CreateAgentParams<\n ResponseFormatUndefined,\n StateSchema,\n ContextSchema,\n never\n >,\n \"responseFormat\"\n > & {\n responseFormat?: undefined;\n middleware?: TMiddleware;\n }\n): ReactAgent<ResponseFormatUndefined, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 10: For other ResponseFormat values (failsafe)\nexport function createAgent<\n StructuredResponseFormat extends Record<string, any> = Record<string, any>,\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema,\n ResponseFormat\n > & {\n responseFormat: ResponseFormat;\n middleware?: TMiddleware;\n }\n): ReactAgent<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema,\n TMiddleware\n>;\n\n// Implementation\nexport function createAgent<\n StructuredResponseFormat extends Record<string, any>,\n StateSchema extends AnyAnnotationRoot | InteropZodObject,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject,\n TMiddleware extends readonly AgentMiddleware[] = []\n>(\n params: CreateAgentParams<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema,\n any\n >\n): ReactAgent<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema,\n TMiddleware\n> {\n return new ReactAgent(params);\n}\n\n// Re-export types and utilities\nexport * from \"./types.js\";\nexport * from \"./errors.js\";\nexport type { JumpToTarget } from \"./constants.js\";\nexport type { Runtime } from \"./runtime.js\";\nexport {\n toolStrategy,\n providerStrategy,\n ToolStrategy,\n ProviderStrategy,\n type ResponseFormat,\n type ResponseFormatUndefined,\n} from \"./responses.js\";\nexport { createMiddleware } from \"./middleware.js\";\nexport type {\n ToolCallRequest,\n ToolCallHandler,\n WrapToolCallHook,\n} from \"./middleware/types.js\";\nexport { FakeToolCallingModel } from \"./tests/utils.js\";\nexport type { ReactAgent } from \"./ReactAgent.js\";\n"],"mappings":";;;;;;;AA+YA,SAAgB,YAMdA,QAWA;AACA,QAAO,IAAI,WAAW;AACvB"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["params: CreateAgentParams<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema,\n any\n >"],"sources":["../../src/agents/index.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type {\n InteropZodObject,\n InteropZodType,\n} from \"@langchain/core/utils/types\";\n\nimport type { ResponseFormatUndefined } from \"./responses.js\";\nimport type { CreateAgentParams } from \"./types.js\";\nimport type { AgentMiddleware, AnyAnnotationRoot } from \"./middleware/types.js\";\nimport type { ExtractZodArrayTypes } from \"./types.js\";\nimport type {\n ToolStrategy,\n TypedToolStrategy,\n ProviderStrategy,\n ResponseFormat,\n JsonSchemaFormat,\n} from \"./responses.js\";\nimport { ReactAgent } from \"./ReactAgent.js\";\n\n/**\n * Creates a production-ready ReAct (Reasoning + Acting) agent that combines language models with tools\n * and middleware to create systems that can reason about tasks, decide which tools to use, and iteratively\n * work towards solutions.\n *\n * The agent follows the ReAct pattern, interleaving reasoning steps with tool calls to iteratively\n * work towards solutions. It can handle multiple tool calls in sequence or parallel, maintain state\n * across interactions, and provide auditable decision processes.\n *\n * ## Core Components\n *\n * ### Model\n * The reasoning engine can be specified as:\n * - **String identifier**: `\"openai:gpt-4o\"` for simple setup\n * - **Model instance**: Configured model object for full control\n * - **Dynamic function**: Select models at runtime based on state\n *\n * ### Tools\n * Tools give agents the ability to take actions:\n * - Pass an array of tools created with the `tool` function\n * - Or provide a configured `ToolNode` for custom error handling\n *\n * ### Prompt\n * Shape how your agent approaches tasks:\n * - String for simple instructions\n * - SystemMessage for structured prompts\n * - Function for dynamic prompts based on state\n *\n * ### Middleware\n * Middleware allows you to extend the agent's behavior:\n * - Add pre/post-model processing for context injection or validation\n * - Add dynamic control flows, e.g. terminate invocation or retries\n * - Add human-in-the-loop capabilities\n * - Add tool calls to the agent\n * - Add tool results to the agent\n *\n * ## Advanced Features\n *\n * - **Structured Output**: Use `responseFormat` with a Zod schema to get typed responses\n * - **Memory**: Extend the state schema to remember information across interactions\n * - **Streaming**: Get real-time updates as the agent processes\n *\n * @param options - Configuration options for the agent\n * @param options.llm - The language model as an instance of a chat model\n * @param options.model - The language model as a string identifier, see more in {@link https://docs.langchain.com/oss/javascript/langchain/models#basic-usage | Models}.\n * @param options.tools - Array of tools or configured ToolNode\n * @param options.prompt - System instructions (string, SystemMessage, or function)\n * @param options.responseFormat - Zod schema for structured output\n * @param options.stateSchema - Custom state schema for memory\n * @param options.middleware - Array of middleware for extending agent behavior, see more in {@link https://docs.langchain.com/oss/javascript/langchain/middleware | Middleware}.\n *\n * @returns A ReactAgent instance with `invoke` and `stream` methods\n *\n * @example Basic agent with tools\n * ```ts\n * import { createAgent, tool } from \"langchain\";\n * import { z } from \"zod\";\n *\n * const search = tool(\n * ({ query }) => `Results for: ${query}`,\n * {\n * name: \"search\",\n * description: \"Search for information\",\n * schema: z.object({\n * query: z.string().describe(\"The search query\"),\n * })\n * }\n * );\n *\n * const agent = createAgent({\n * llm: \"openai:gpt-4o\",\n * tools: [search],\n * });\n *\n * const result = await agent.invoke({\n * messages: [{ role: \"user\", content: \"Search for ReAct agents\" }],\n * });\n * ```\n *\n * @example Structured output\n * ```ts\n * import { createAgent } from \"langchain\";\n * import { z } from \"zod\";\n *\n * const ContactInfo = z.object({\n * name: z.string(),\n * email: z.string(),\n * phone: z.string(),\n * });\n *\n * const agent = createAgent({\n * llm: \"openai:gpt-4o\",\n * tools: [],\n * responseFormat: ContactInfo,\n * });\n *\n * const result = await agent.invoke({\n * messages: [{\n * role: \"user\",\n * content: \"Extract: John Doe, john@example.com, (555) 123-4567\"\n * }],\n * });\n *\n * console.log(result.structuredResponse);\n * // { name: 'John Doe', email: 'john@example.com', phone: '(555) 123-4567' }\n * ```\n *\n * @example Streaming responses\n * ```ts\n * const stream = await agent.stream(\n * { messages: [{ role: \"user\", content: \"What's the weather?\" }] },\n * { streamMode: \"values\" }\n * );\n *\n * for await (const chunk of stream) {\n * // ...\n * }\n * ```\n */\n// Overload 1: With responseFormat as single InteropZodType\nexport function createAgent<\n T extends Record<string, any> = Record<string, any>,\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n T,\n StateSchema,\n ContextSchema,\n InteropZodType<T>\n > & {\n responseFormat: InteropZodType<T>;\n middleware?: TMiddleware;\n }\n): ReactAgent<T, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 2: With responseFormat as array of InteropZodTypes (infers union type)\nexport function createAgent<\n T extends readonly InteropZodType<any>[],\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n ExtractZodArrayTypes<T> extends Record<string, any>\n ? ExtractZodArrayTypes<T>\n : Record<string, any>,\n StateSchema,\n ContextSchema,\n T\n > & {\n responseFormat: T;\n middleware?: TMiddleware;\n }\n): ReactAgent<\n ExtractZodArrayTypes<T> extends Record<string, any>\n ? ExtractZodArrayTypes<T>\n : Record<string, any>,\n StateSchema,\n ContextSchema,\n TMiddleware\n>;\n\n// Overload 3: With responseFormat as JsonSchemaFormat (JSON schema object)\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n Record<string, unknown>,\n StateSchema,\n ContextSchema,\n JsonSchemaFormat\n > & {\n responseFormat: JsonSchemaFormat;\n middleware?: TMiddleware;\n }\n): ReactAgent<Record<string, unknown>, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 4: With responseFormat as array of JsonSchemaFormat (JSON schema objects)\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n Record<string, unknown>,\n StateSchema,\n ContextSchema,\n JsonSchemaFormat[]\n > & {\n responseFormat: JsonSchemaFormat[];\n middleware?: TMiddleware;\n }\n): ReactAgent<Record<string, unknown>, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 4.5: With responseFormat as union of JsonSchemaFormat | JsonSchemaFormat[]\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n Record<string, unknown>,\n StateSchema,\n ContextSchema,\n JsonSchemaFormat | JsonSchemaFormat[]\n > & {\n responseFormat: JsonSchemaFormat | JsonSchemaFormat[];\n middleware?: TMiddleware;\n }\n): ReactAgent<Record<string, unknown>, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 5: With responseFormat as TypedToolStrategy (for union types from toolStrategy)\nexport function createAgent<\n T extends Record<string, any> = Record<string, any>,\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n T,\n StateSchema,\n ContextSchema,\n TypedToolStrategy<T>\n > & {\n responseFormat: TypedToolStrategy<T>;\n middleware?: TMiddleware;\n }\n): ReactAgent<T, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 6: With responseFormat as single ToolStrategy instance\nexport function createAgent<\n T extends Record<string, any> = Record<string, any>,\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<T, StateSchema, ContextSchema, ToolStrategy<T>> & {\n responseFormat: ToolStrategy<T>;\n middleware?: TMiddleware;\n }\n): ReactAgent<T, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 7: With responseFormat as ProviderStrategy\nexport function createAgent<\n T extends Record<string, any> = Record<string, any>,\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n T,\n StateSchema,\n ContextSchema,\n ProviderStrategy<T>\n > & {\n responseFormat: ProviderStrategy<T>;\n middleware?: TMiddleware;\n }\n): ReactAgent<T, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 8: Without responseFormat property at all - with proper middleware state typing\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: Omit<\n CreateAgentParams<\n ResponseFormatUndefined,\n StateSchema,\n ContextSchema,\n never\n >,\n \"responseFormat\"\n > & { middleware?: TMiddleware }\n): ReactAgent<ResponseFormatUndefined, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 9: With responseFormat explicitly undefined\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: Omit<\n CreateAgentParams<\n ResponseFormatUndefined,\n StateSchema,\n ContextSchema,\n never\n >,\n \"responseFormat\"\n > & {\n responseFormat?: undefined;\n middleware?: TMiddleware;\n }\n): ReactAgent<ResponseFormatUndefined, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 10: For other ResponseFormat values (failsafe)\nexport function createAgent<\n StructuredResponseFormat extends Record<string, any> = Record<string, any>,\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema,\n ResponseFormat\n > & {\n responseFormat: ResponseFormat;\n middleware?: TMiddleware;\n }\n): ReactAgent<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema,\n TMiddleware\n>;\n\n// Implementation\nexport function createAgent<\n StructuredResponseFormat extends Record<string, any>,\n StateSchema extends AnyAnnotationRoot | InteropZodObject,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject,\n TMiddleware extends readonly AgentMiddleware[] = []\n>(\n params: CreateAgentParams<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema,\n any\n >\n): ReactAgent<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema,\n TMiddleware\n> {\n return new ReactAgent(params);\n}\n\n// Re-export types and utilities\nexport * from \"./types.js\";\nexport * from \"./errors.js\";\nexport type { JumpToTarget } from \"./constants.js\";\nexport type { Runtime } from \"./runtime.js\";\nexport {\n toolStrategy,\n providerStrategy,\n ToolStrategy,\n ProviderStrategy,\n type ResponseFormat,\n type ResponseFormatUndefined,\n} from \"./responses.js\";\nexport { createMiddleware } from \"./middleware.js\";\nexport type * from \"./middleware/types.js\";\nexport { FakeToolCallingModel } from \"./tests/utils.js\";\nexport type { ReactAgent } from \"./ReactAgent.js\";\n"],"mappings":";;;;;;;AA+YA,SAAgB,YAMdA,QAWA;AACA,QAAO,IAAI,WAAW;AACvB"}
|
|
@@ -314,6 +314,7 @@ interface AgentMiddleware<TSchema extends InteropZodObject | undefined = any, TC
|
|
|
314
314
|
* Helper type to filter out properties that start with underscore (private properties)
|
|
315
315
|
*/
|
|
316
316
|
type FilterPrivateProps<T> = { [K in keyof T as K extends `_${string}` ? never : K]: T[K] };
|
|
317
|
+
type InferChannelType<T extends AnyAnnotationRoot | InteropZodObject> = T extends AnyAnnotationRoot ? ToAnnotationRoot<T>["State"] : T extends InteropZodObject ? InferInteropZodInput<T> : {};
|
|
317
318
|
/**
|
|
318
319
|
* Helper type to infer the state schema type from a middleware
|
|
319
320
|
* This filters out private properties (those starting with underscore)
|
|
@@ -332,10 +333,26 @@ type InferMiddlewareStates<T = AgentMiddleware[]> = T extends readonly [] ? {} :
|
|
|
332
333
|
* Helper type to infer merged input state from an array of middleware (with optional defaults)
|
|
333
334
|
*/
|
|
334
335
|
type InferMiddlewareInputStates<T extends readonly AgentMiddleware[]> = T extends readonly [] ? {} : T extends readonly [infer First, ...infer Rest] ? First extends AgentMiddleware ? Rest extends readonly AgentMiddleware[] ? InferMiddlewareInputState<First> & InferMiddlewareInputStates<Rest> : InferMiddlewareInputState<First> : {} : {};
|
|
336
|
+
/**
|
|
337
|
+
* Helper type to infer merged state from an array of middleware (includes built-in state)
|
|
338
|
+
*/
|
|
339
|
+
type InferMergedState<T extends readonly AgentMiddleware[]> = InferMiddlewareStates<T> & AgentBuiltInState;
|
|
340
|
+
/**
|
|
341
|
+
* Helper type to infer merged input state from an array of middleware (includes built-in state)
|
|
342
|
+
*/
|
|
343
|
+
type InferMergedInputState<T extends readonly AgentMiddleware[]> = InferMiddlewareInputStates<T> & AgentBuiltInState;
|
|
344
|
+
/**
|
|
345
|
+
* Helper type to infer the context schema type from a middleware
|
|
346
|
+
*/
|
|
347
|
+
type InferMiddlewareContext<T extends AgentMiddleware> = T extends AgentMiddleware<any, infer C, any> ? C extends InteropZodObject ? InferInteropZodInput<C> : {} : {};
|
|
335
348
|
/**
|
|
336
349
|
* Helper type to infer the input context schema type from a middleware (with optional defaults)
|
|
337
350
|
*/
|
|
338
351
|
type InferMiddlewareContextInput<T extends AgentMiddleware> = T extends AgentMiddleware<any, infer C, any> ? C extends InteropZodOptional<infer Inner> ? InferInteropZodInput<Inner> | undefined : C extends InteropZodObject ? InferInteropZodInput<C> : {} : {};
|
|
352
|
+
/**
|
|
353
|
+
* Helper type to infer merged context from an array of middleware
|
|
354
|
+
*/
|
|
355
|
+
type InferMiddlewareContexts<T extends readonly AgentMiddleware[]> = T extends readonly [] ? {} : T extends readonly [infer First, ...infer Rest] ? First extends AgentMiddleware ? Rest extends readonly AgentMiddleware[] ? InferMiddlewareContext<First> & InferMiddlewareContexts<Rest> : InferMiddlewareContext<First> : {} : {};
|
|
339
356
|
/**
|
|
340
357
|
* Helper to merge two context types, preserving undefined unions
|
|
341
358
|
*/
|
|
@@ -351,5 +368,5 @@ type InferContextInput<ContextSchema extends AnyAnnotationRoot | InteropZodObjec
|
|
|
351
368
|
type ToAnnotationRoot<A extends AnyAnnotationRoot | InteropZodObject> = A extends AnyAnnotationRoot ? A : A extends InteropZodObject ? AnnotationRoot<InteropZodToStateDefinition<A>> : never;
|
|
352
369
|
type InferSchemaInput<A extends AnyAnnotationRoot | InteropZodObject | undefined> = A extends AnyAnnotationRoot | InteropZodObject ? ToAnnotationRoot<A>["State"] : {};
|
|
353
370
|
//#endregion
|
|
354
|
-
export { AfterAgentHook, AfterModelHook, AgentMiddleware, AnyAnnotationRoot, BeforeAgentHook, BeforeModelHook, InferContextInput, InferMiddlewareContextInputs, InferMiddlewareInputStates, InferMiddlewareStates, InferSchemaInput, ToAnnotationRoot, ToolCallHandler, ToolCallRequest, WrapModelCallHook, WrapToolCallHook };
|
|
371
|
+
export { AfterAgentHook, AfterModelHook, AgentMiddleware, AnyAnnotationRoot, BeforeAgentHook, BeforeModelHook, InferChannelType, InferContextInput, InferMergedInputState, InferMergedState, InferMiddlewareContext, InferMiddlewareContextInput, InferMiddlewareContextInputs, InferMiddlewareContexts, InferMiddlewareInputState, InferMiddlewareInputStates, InferMiddlewareState, InferMiddlewareStates, InferSchemaInput, MiddlewareResult, NormalizedSchemaInput, ToAnnotationRoot, ToolCallHandler, ToolCallRequest, WrapModelCallHandler, WrapModelCallHook, WrapToolCallHook };
|
|
355
372
|
//# sourceMappingURL=types.d.cts.map
|
|
@@ -314,6 +314,7 @@ interface AgentMiddleware<TSchema extends InteropZodObject | undefined = any, TC
|
|
|
314
314
|
* Helper type to filter out properties that start with underscore (private properties)
|
|
315
315
|
*/
|
|
316
316
|
type FilterPrivateProps<T> = { [K in keyof T as K extends `_${string}` ? never : K]: T[K] };
|
|
317
|
+
type InferChannelType<T extends AnyAnnotationRoot | InteropZodObject> = T extends AnyAnnotationRoot ? ToAnnotationRoot<T>["State"] : T extends InteropZodObject ? InferInteropZodInput<T> : {};
|
|
317
318
|
/**
|
|
318
319
|
* Helper type to infer the state schema type from a middleware
|
|
319
320
|
* This filters out private properties (those starting with underscore)
|
|
@@ -332,10 +333,26 @@ type InferMiddlewareStates<T = AgentMiddleware[]> = T extends readonly [] ? {} :
|
|
|
332
333
|
* Helper type to infer merged input state from an array of middleware (with optional defaults)
|
|
333
334
|
*/
|
|
334
335
|
type InferMiddlewareInputStates<T extends readonly AgentMiddleware[]> = T extends readonly [] ? {} : T extends readonly [infer First, ...infer Rest] ? First extends AgentMiddleware ? Rest extends readonly AgentMiddleware[] ? InferMiddlewareInputState<First> & InferMiddlewareInputStates<Rest> : InferMiddlewareInputState<First> : {} : {};
|
|
336
|
+
/**
|
|
337
|
+
* Helper type to infer merged state from an array of middleware (includes built-in state)
|
|
338
|
+
*/
|
|
339
|
+
type InferMergedState<T extends readonly AgentMiddleware[]> = InferMiddlewareStates<T> & AgentBuiltInState;
|
|
340
|
+
/**
|
|
341
|
+
* Helper type to infer merged input state from an array of middleware (includes built-in state)
|
|
342
|
+
*/
|
|
343
|
+
type InferMergedInputState<T extends readonly AgentMiddleware[]> = InferMiddlewareInputStates<T> & AgentBuiltInState;
|
|
344
|
+
/**
|
|
345
|
+
* Helper type to infer the context schema type from a middleware
|
|
346
|
+
*/
|
|
347
|
+
type InferMiddlewareContext<T extends AgentMiddleware> = T extends AgentMiddleware<any, infer C, any> ? C extends InteropZodObject ? InferInteropZodInput<C> : {} : {};
|
|
335
348
|
/**
|
|
336
349
|
* Helper type to infer the input context schema type from a middleware (with optional defaults)
|
|
337
350
|
*/
|
|
338
351
|
type InferMiddlewareContextInput<T extends AgentMiddleware> = T extends AgentMiddleware<any, infer C, any> ? C extends InteropZodOptional<infer Inner> ? InferInteropZodInput<Inner> | undefined : C extends InteropZodObject ? InferInteropZodInput<C> : {} : {};
|
|
352
|
+
/**
|
|
353
|
+
* Helper type to infer merged context from an array of middleware
|
|
354
|
+
*/
|
|
355
|
+
type InferMiddlewareContexts<T extends readonly AgentMiddleware[]> = T extends readonly [] ? {} : T extends readonly [infer First, ...infer Rest] ? First extends AgentMiddleware ? Rest extends readonly AgentMiddleware[] ? InferMiddlewareContext<First> & InferMiddlewareContexts<Rest> : InferMiddlewareContext<First> : {} : {};
|
|
339
356
|
/**
|
|
340
357
|
* Helper to merge two context types, preserving undefined unions
|
|
341
358
|
*/
|
|
@@ -351,5 +368,5 @@ type InferContextInput<ContextSchema extends AnyAnnotationRoot | InteropZodObjec
|
|
|
351
368
|
type ToAnnotationRoot<A extends AnyAnnotationRoot | InteropZodObject> = A extends AnyAnnotationRoot ? A : A extends InteropZodObject ? AnnotationRoot<InteropZodToStateDefinition<A>> : never;
|
|
352
369
|
type InferSchemaInput<A extends AnyAnnotationRoot | InteropZodObject | undefined> = A extends AnyAnnotationRoot | InteropZodObject ? ToAnnotationRoot<A>["State"] : {};
|
|
353
370
|
//#endregion
|
|
354
|
-
export { AfterAgentHook, AfterModelHook, AgentMiddleware, AnyAnnotationRoot, BeforeAgentHook, BeforeModelHook, InferContextInput, InferMiddlewareContextInputs, InferMiddlewareInputStates, InferMiddlewareStates, InferSchemaInput, ToAnnotationRoot, ToolCallHandler, ToolCallRequest, WrapModelCallHook, WrapToolCallHook };
|
|
371
|
+
export { AfterAgentHook, AfterModelHook, AgentMiddleware, AnyAnnotationRoot, BeforeAgentHook, BeforeModelHook, InferChannelType, InferContextInput, InferMergedInputState, InferMergedState, InferMiddlewareContext, InferMiddlewareContextInput, InferMiddlewareContextInputs, InferMiddlewareContexts, InferMiddlewareInputState, InferMiddlewareInputStates, InferMiddlewareState, InferMiddlewareStates, InferSchemaInput, MiddlewareResult, NormalizedSchemaInput, ToAnnotationRoot, ToolCallHandler, ToolCallRequest, WrapModelCallHandler, WrapModelCallHook, WrapToolCallHook };
|
|
355
372
|
//# sourceMappingURL=types.d.ts.map
|
package/dist/agents/model.cjs
CHANGED
|
@@ -4,7 +4,7 @@ function isBaseChatModel(model) {
|
|
|
4
4
|
return "invoke" in model && typeof model.invoke === "function" && "_streamResponseChunks" in model;
|
|
5
5
|
}
|
|
6
6
|
function isConfigurableModel(model) {
|
|
7
|
-
return typeof model === "object" && model != null && "_queuedMethodOperations" in model && "
|
|
7
|
+
return typeof model === "object" && model != null && "_queuedMethodOperations" in model && "_getModelInstance" in model && typeof model._getModelInstance === "function";
|
|
8
8
|
}
|
|
9
9
|
|
|
10
10
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model.cjs","names":["model: LanguageModelLike","model: unknown"],"sources":["../../src/agents/model.ts"],"sourcesContent":["import type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport type { BaseChatModel } from \"@langchain/core/language_models/chat_models\";\n\nexport interface ConfigurableModelInterface {\n _queuedMethodOperations: Record<string, unknown>;\n
|
|
1
|
+
{"version":3,"file":"model.cjs","names":["model: LanguageModelLike","model: unknown"],"sources":["../../src/agents/model.ts"],"sourcesContent":["import type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport type { BaseChatModel } from \"@langchain/core/language_models/chat_models\";\n\nexport interface ConfigurableModelInterface {\n _queuedMethodOperations: Record<string, unknown>;\n _getModelInstance: () => Promise<BaseChatModel>;\n}\n\nexport function isBaseChatModel(\n model: LanguageModelLike\n): model is BaseChatModel {\n return (\n \"invoke\" in model &&\n typeof model.invoke === \"function\" &&\n \"_streamResponseChunks\" in model\n );\n}\n\nexport function isConfigurableModel(\n model: unknown\n): model is ConfigurableModelInterface {\n return (\n typeof model === \"object\" &&\n model != null &&\n \"_queuedMethodOperations\" in model &&\n \"_getModelInstance\" in model &&\n typeof (model as { _getModelInstance: unknown })._getModelInstance ===\n \"function\"\n );\n}\n"],"mappings":";;AAQA,SAAgB,gBACdA,OACwB;AACxB,QACE,YAAY,SACZ,OAAO,MAAM,WAAW,cACxB,2BAA2B;AAE9B;AAED,SAAgB,oBACdC,OACqC;AACrC,QACE,OAAO,UAAU,YACjB,SAAS,QACT,6BAA6B,SAC7B,uBAAuB,SACvB,OAAQ,MAAyC,sBAC/C;AAEL"}
|
package/dist/agents/model.js
CHANGED
|
@@ -3,7 +3,7 @@ function isBaseChatModel(model) {
|
|
|
3
3
|
return "invoke" in model && typeof model.invoke === "function" && "_streamResponseChunks" in model;
|
|
4
4
|
}
|
|
5
5
|
function isConfigurableModel(model) {
|
|
6
|
-
return typeof model === "object" && model != null && "_queuedMethodOperations" in model && "
|
|
6
|
+
return typeof model === "object" && model != null && "_queuedMethodOperations" in model && "_getModelInstance" in model && typeof model._getModelInstance === "function";
|
|
7
7
|
}
|
|
8
8
|
|
|
9
9
|
//#endregion
|
package/dist/agents/model.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model.js","names":["model: LanguageModelLike","model: unknown"],"sources":["../../src/agents/model.ts"],"sourcesContent":["import type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport type { BaseChatModel } from \"@langchain/core/language_models/chat_models\";\n\nexport interface ConfigurableModelInterface {\n _queuedMethodOperations: Record<string, unknown>;\n
|
|
1
|
+
{"version":3,"file":"model.js","names":["model: LanguageModelLike","model: unknown"],"sources":["../../src/agents/model.ts"],"sourcesContent":["import type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport type { BaseChatModel } from \"@langchain/core/language_models/chat_models\";\n\nexport interface ConfigurableModelInterface {\n _queuedMethodOperations: Record<string, unknown>;\n _getModelInstance: () => Promise<BaseChatModel>;\n}\n\nexport function isBaseChatModel(\n model: LanguageModelLike\n): model is BaseChatModel {\n return (\n \"invoke\" in model &&\n typeof model.invoke === \"function\" &&\n \"_streamResponseChunks\" in model\n );\n}\n\nexport function isConfigurableModel(\n model: unknown\n): model is ConfigurableModelInterface {\n return (\n typeof model === \"object\" &&\n model != null &&\n \"_queuedMethodOperations\" in model &&\n \"_getModelInstance\" in model &&\n typeof (model as { _getModelInstance: unknown })._getModelInstance ===\n \"function\"\n );\n}\n"],"mappings":";AAQA,SAAgB,gBACdA,OACwB;AACxB,QACE,YAAY,SACZ,OAAO,MAAM,WAAW,cACxB,2BAA2B;AAE9B;AAED,SAAgB,oBACdC,OACqC;AACrC,QACE,OAAO,UAAU,YACjB,SAAS,QACT,6BAA6B,SAC7B,uBAAuB,SACvB,OAAQ,MAAyC,sBAC/C;AAEL"}
|
|
@@ -13,6 +13,14 @@ const __langchain_core_utils_types = require_rolldown_runtime.__toESM(require("@
|
|
|
13
13
|
|
|
14
14
|
//#region src/agents/nodes/AgentNode.ts
|
|
15
15
|
/**
|
|
16
|
+
* Check if the response is an internal model response.
|
|
17
|
+
* @param response - The response to check.
|
|
18
|
+
* @returns True if the response is an internal model response, false otherwise.
|
|
19
|
+
*/
|
|
20
|
+
function isInternalModelResponse(response) {
|
|
21
|
+
return __langchain_core_messages.AIMessage.isInstance(response) || typeof response === "object" && response !== null && "structuredResponse" in response && "messages" in response;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
16
24
|
* The name of the agent node in the state graph.
|
|
17
25
|
*/
|
|
18
26
|
const AGENT_NODE_NAME = "model_request";
|
|
@@ -245,7 +253,7 @@ var AgentNode = class extends require_RunnableCallable.RunnableCallable {
|
|
|
245
253
|
/**
|
|
246
254
|
* Validate that this specific middleware returned a valid AIMessage
|
|
247
255
|
*/
|
|
248
|
-
if (!
|
|
256
|
+
if (!isInternalModelResponse(middlewareResponse)) throw new Error(`Invalid response from "wrapModelCall" in middleware "${currentMiddleware.name}": expected AIMessage, got ${typeof middlewareResponse}`);
|
|
249
257
|
return middlewareResponse;
|
|
250
258
|
} catch (error) {
|
|
251
259
|
/**
|
|
@@ -407,6 +415,11 @@ var AgentNode = class extends require_RunnableCallable.RunnableCallable {
|
|
|
407
415
|
type: "json_schema",
|
|
408
416
|
json_schema: jsonSchemaParams
|
|
409
417
|
},
|
|
418
|
+
output_format: {
|
|
419
|
+
type: "json_schema",
|
|
420
|
+
schema: structuredResponseFormat.strategy.schema
|
|
421
|
+
},
|
|
422
|
+
headers: { "anthropic-beta": "structured-outputs-2025-11-13" },
|
|
410
423
|
ls_structured_output_format: {
|
|
411
424
|
kwargs: { method: "json_schema" },
|
|
412
425
|
schema: structuredResponseFormat.strategy.schema
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AgentNode.cjs","names":["RunnableCallable","options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>","#run","#options","#systemMessage","model: string | LanguageModelLike","transformResponseFormat","ProviderStrategy","ToolStrategy","state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"]","config: RunnableConfig","ToolMessage","#invokeModel","Command","#areMoreStepsNeeded","AIMessage","initChatModel","options: {\n lastMessage?: string;\n }","#deriveModel","request: ModelRequest","validateLLMHasNoBoundTools","#getResponseFormat","#bindTools","#currentSystemMessage","mergeAbortSignals","#handleMultipleStructuredOutputs","#handleSingleStructuredOutput","wrappedHandler: (\n request: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n >\n ) => Promise<InternalModelResponse<StructuredResponseFormat>>","request: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n >","runtime: Runtime<unknown>","requestWithStateAndRuntime: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n >","req: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n >","isClientTool","SystemMessage","initialRequest: ModelRequest<\n InternalAgentState<StructuredResponseFormat> & PreHookAnnotation[\"State\"],\n unknown\n >","response: AIMessage","toolCalls: ToolCall[]","responseFormat: ToolResponseFormat","MultipleStructuredOutputsError","#handleToolStrategyError","toolCall: ToolCall","lastMessage?: string","error: ToolStrategyError","response: BaseMessage","hasToolCalls","model: LanguageModelLike","preparedOptions: ModelRequest | undefined","structuredResponseFormat: ResponseFormat | undefined","options: Partial<BaseChatModelCallOptions>","bindTools","withAgentName"],"sources":["../../../src/agents/nodes/AgentNode.ts"],"sourcesContent":["/* eslint-disable no-instanceof/no-instanceof */\nimport { Runnable, RunnableConfig } from \"@langchain/core/runnables\";\nimport {\n BaseMessage,\n AIMessage,\n ToolMessage,\n SystemMessage,\n} from \"@langchain/core/messages\";\nimport { Command, type LangGraphRunnableConfig } from \"@langchain/langgraph\";\nimport { type LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { type BaseChatModelCallOptions } from \"@langchain/core/language_models/chat_models\";\nimport {\n InteropZodObject,\n getSchemaDescription,\n interopParse,\n interopZodObjectPartial,\n} from \"@langchain/core/utils/types\";\nimport { raceWithSignal } from \"@langchain/core/runnables\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport { initChatModel } from \"../../chat_models/universal.js\";\nimport { MultipleStructuredOutputsError } from \"../errors.js\";\nimport { RunnableCallable } from \"../RunnableCallable.js\";\nimport { PreHookAnnotation } from \"../annotation.js\";\nimport {\n bindTools,\n validateLLMHasNoBoundTools,\n hasToolCalls,\n isClientTool,\n} from \"../utils.js\";\nimport { mergeAbortSignals } from \"../nodes/utils.js\";\nimport { CreateAgentParams } from \"../types.js\";\nimport type { InternalAgentState, Runtime } from \"../runtime.js\";\nimport type {\n AgentMiddleware,\n AnyAnnotationRoot,\n WrapModelCallHandler,\n} from \"../middleware/types.js\";\nimport type { ModelRequest } from \"./types.js\";\nimport { withAgentName } from \"../withAgentName.js\";\nimport {\n ToolStrategy,\n ProviderStrategy,\n transformResponseFormat,\n ToolStrategyError,\n} from \"../responses.js\";\n\ntype ResponseHandlerResult<StructuredResponseFormat> =\n | {\n structuredResponse: StructuredResponseFormat;\n messages: BaseMessage[];\n }\n | Promise<Command>;\n\n/**\n * Wrap the base handler with middleware wrapModelCall hooks\n * Middleware are composed so the first middleware is the outermost wrapper\n * Example: [auth, retry, cache] means auth wraps retry wraps cache wraps baseHandler\n */\ntype InternalModelResponse<StructuredResponseFormat> =\n | AIMessage\n | ResponseHandlerResult<StructuredResponseFormat>;\n\n/**\n * The name of the agent node in the state graph.\n */\nexport const AGENT_NODE_NAME = \"model_request\";\n\nexport interface AgentNodeOptions<\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> extends Pick<\n CreateAgentParams<StructuredResponseFormat, StateSchema, ContextSchema>,\n \"model\" | \"includeAgentName\" | \"name\" | \"responseFormat\" | \"middleware\"\n > {\n toolClasses: (ClientTool | ServerTool)[];\n shouldReturnDirect: Set<string>;\n signal?: AbortSignal;\n systemMessage: SystemMessage;\n wrapModelCallHookMiddleware?: [\n AgentMiddleware,\n () => Record<string, unknown>\n ][];\n}\n\ninterface NativeResponseFormat {\n type: \"native\";\n strategy: ProviderStrategy;\n}\n\ninterface ToolResponseFormat {\n type: \"tool\";\n tools: Record<string, ToolStrategy>;\n}\n\ntype ResponseFormat = NativeResponseFormat | ToolResponseFormat;\n\nexport class AgentNode<\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> extends RunnableCallable<\n InternalAgentState<StructuredResponseFormat> & PreHookAnnotation[\"State\"],\n | (\n | { messages: BaseMessage[] }\n | { structuredResponse: StructuredResponseFormat }\n )\n | Command\n> {\n #options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>;\n #systemMessage: SystemMessage;\n #currentSystemMessage: SystemMessage;\n\n constructor(\n options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>\n ) {\n super({\n name: options.name ?? \"model\",\n func: (input, config) => this.#run(input, config as RunnableConfig),\n });\n\n this.#options = options;\n this.#systemMessage = options.systemMessage;\n }\n\n /**\n * Returns response format primtivies based on given model and response format provided by the user.\n *\n * If the user selects a tool output:\n * - return a record of tools to extract structured output from the model's response\n *\n * if the the user selects a native schema output or if the model supports JSON schema output:\n * - return a provider strategy to extract structured output from the model's response\n *\n * @param model - The model to get the response format for.\n * @returns The response format.\n */\n #getResponseFormat(\n model: string | LanguageModelLike\n ): ResponseFormat | undefined {\n if (!this.#options.responseFormat) {\n return undefined;\n }\n\n const strategies = transformResponseFormat(\n this.#options.responseFormat,\n undefined,\n model\n );\n\n /**\n * we either define a list of provider strategies or a list of tool strategies\n */\n const isProviderStrategy = strategies.every(\n (format) => format instanceof ProviderStrategy\n );\n\n /**\n * Populate a list of structured tool info.\n */\n if (!isProviderStrategy) {\n return {\n type: \"tool\",\n tools: (\n strategies.filter(\n (format) => format instanceof ToolStrategy\n ) as ToolStrategy[]\n ).reduce((acc, format) => {\n acc[format.name] = format;\n return acc;\n }, {} as Record<string, ToolStrategy>),\n };\n }\n\n return {\n type: \"native\",\n /**\n * there can only be one provider strategy\n */\n strategy: strategies[0] as ProviderStrategy,\n };\n }\n\n async #run(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig\n ) {\n /**\n * Check if we just executed a returnDirect tool\n * If so, we should generate structured response (if needed) and stop\n */\n const lastMessage = state.messages.at(-1);\n if (\n lastMessage &&\n ToolMessage.isInstance(lastMessage) &&\n lastMessage.name &&\n this.#options.shouldReturnDirect.has(lastMessage.name)\n ) {\n /**\n * return directly without invoking the model again\n */\n return { messages: [] };\n }\n\n const response = await this.#invokeModel(state, config);\n\n /**\n * if we were able to generate a structured response, return it\n */\n if (\"structuredResponse\" in response) {\n return {\n messages: [...state.messages, ...(response.messages || [])],\n structuredResponse: response.structuredResponse,\n };\n }\n\n /**\n * if we need to direct the agent to the model, return the update\n */\n if (response instanceof Command) {\n return response;\n }\n\n response.name = this.name;\n response.lc_kwargs.name = this.name;\n\n if (this.#areMoreStepsNeeded(state, response)) {\n return {\n messages: [\n new AIMessage({\n content: \"Sorry, need more steps to process this request.\",\n name: this.name,\n id: response.id,\n }),\n ],\n };\n }\n\n return { messages: [response] };\n }\n\n /**\n * Derive the model from the options.\n * @param state - The state of the agent.\n * @param config - The config of the agent.\n * @returns The model.\n */\n #deriveModel() {\n if (typeof this.#options.model === \"string\") {\n return initChatModel(this.#options.model);\n }\n\n if (this.#options.model) {\n return this.#options.model;\n }\n\n throw new Error(\"No model option was provided, either via `model` option.\");\n }\n\n async #invokeModel(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig,\n options: {\n lastMessage?: string;\n } = {}\n ): Promise<AIMessage | ResponseHandlerResult<StructuredResponseFormat>> {\n const model = await this.#deriveModel();\n const lgConfig = config as LangGraphRunnableConfig;\n\n /**\n * Create the base handler that performs the actual model invocation\n */\n const baseHandler = async (\n request: ModelRequest\n ): Promise<AIMessage | ResponseHandlerResult<StructuredResponseFormat>> => {\n /**\n * Check if the LLM already has bound tools and throw if it does.\n */\n validateLLMHasNoBoundTools(request.model);\n\n const structuredResponseFormat = this.#getResponseFormat(request.model);\n const modelWithTools = await this.#bindTools(\n request.model,\n request,\n structuredResponseFormat\n );\n\n /**\n * prepend the system message to the messages if it is not empty\n */\n const messages = [\n ...(this.#currentSystemMessage.text === \"\"\n ? []\n : [this.#currentSystemMessage]),\n ...request.messages,\n ];\n\n const signal = mergeAbortSignals(this.#options.signal, config.signal);\n const response = (await raceWithSignal(\n modelWithTools.invoke(messages, {\n ...config,\n signal,\n }),\n signal\n )) as AIMessage;\n\n /**\n * if the user requests a native schema output, try to parse the response\n * and return the structured response if it is valid\n */\n if (structuredResponseFormat?.type === \"native\") {\n const structuredResponse =\n structuredResponseFormat.strategy.parse(response);\n if (structuredResponse) {\n return { structuredResponse, messages: [response] };\n }\n\n return response;\n }\n\n if (!structuredResponseFormat || !response.tool_calls) {\n return response;\n }\n\n const toolCalls = response.tool_calls.filter(\n (call) => call.name in structuredResponseFormat.tools\n );\n\n /**\n * if there were not structured tool calls, we can return the response\n */\n if (toolCalls.length === 0) {\n return response;\n }\n\n /**\n * if there were multiple structured tool calls, we should throw an error as this\n * scenario is not defined/supported.\n */\n if (toolCalls.length > 1) {\n return this.#handleMultipleStructuredOutputs(\n response,\n toolCalls,\n structuredResponseFormat\n );\n }\n\n const toolStrategy = structuredResponseFormat.tools[toolCalls[0].name];\n const toolMessageContent = toolStrategy?.options?.toolMessageContent;\n return this.#handleSingleStructuredOutput(\n response,\n toolCalls[0],\n structuredResponseFormat,\n toolMessageContent ?? options.lastMessage\n );\n };\n\n const wrapperMiddleware = this.#options.wrapModelCallHookMiddleware ?? [];\n let wrappedHandler: (\n request: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n >\n ) => Promise<InternalModelResponse<StructuredResponseFormat>> = baseHandler;\n\n /**\n * Build composed handler from last to first so first middleware becomes outermost\n */\n for (let i = wrapperMiddleware.length - 1; i >= 0; i--) {\n const [middleware, getMiddlewareState] = wrapperMiddleware[i];\n if (middleware.wrapModelCall) {\n const innerHandler = wrappedHandler;\n const currentMiddleware = middleware;\n const currentGetState = getMiddlewareState;\n\n wrappedHandler = async (\n request: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n >\n ): Promise<InternalModelResponse<StructuredResponseFormat>> => {\n /**\n * Merge context with default context of middleware\n */\n const context = currentMiddleware.contextSchema\n ? interopParse(\n currentMiddleware.contextSchema,\n lgConfig?.context || {}\n )\n : lgConfig?.context;\n\n /**\n * Create runtime\n */\n const runtime: Runtime<unknown> = Object.freeze({\n context,\n writer: lgConfig.writer,\n interrupt: lgConfig.interrupt,\n signal: lgConfig.signal,\n });\n\n /**\n * Create the request with state and runtime\n */\n const requestWithStateAndRuntime: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n > = {\n ...request,\n state: {\n ...(middleware.stateSchema\n ? interopParse(\n interopZodObjectPartial(middleware.stateSchema),\n state\n )\n : {}),\n ...currentGetState(),\n messages: state.messages,\n } as InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n runtime,\n };\n\n /**\n * Create handler that validates tools and calls the inner handler\n */\n const handlerWithValidation = async (\n req: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n >\n ): Promise<InternalModelResponse<StructuredResponseFormat>> => {\n /**\n * Verify that the user didn't add any new tools.\n * We can't allow this as the ToolNode is already initiated with given tools.\n */\n const modifiedTools = req.tools ?? [];\n const newTools = modifiedTools.filter(\n (tool) =>\n isClientTool(tool) &&\n !this.#options.toolClasses.some((t) => t.name === tool.name)\n );\n if (newTools.length > 0) {\n throw new Error(\n `You have added a new tool in \"wrapModelCall\" hook of middleware \"${\n currentMiddleware.name\n }\": ${newTools\n .map((tool) => tool.name)\n .join(\", \")}. This is not supported.`\n );\n }\n\n /**\n * Verify that user has not added or modified a tool with the same name.\n * We can't allow this as the ToolNode is already initiated with given tools.\n */\n const invalidTools = modifiedTools.filter(\n (tool) =>\n isClientTool(tool) &&\n this.#options.toolClasses.every((t) => t !== tool)\n );\n if (invalidTools.length > 0) {\n throw new Error(\n `You have modified a tool in \"wrapModelCall\" hook of middleware \"${\n currentMiddleware.name\n }\": ${invalidTools\n .map((tool) => tool.name)\n .join(\", \")}. This is not supported.`\n );\n }\n\n let normalizedReq = req;\n const hasSystemPromptChanged =\n req.systemPrompt !== this.#currentSystemMessage.text;\n const hasSystemMessageChanged =\n req.systemMessage !== this.#currentSystemMessage;\n if (hasSystemPromptChanged && hasSystemMessageChanged) {\n throw new Error(\n \"Cannot change both systemPrompt and systemMessage in the same request.\"\n );\n }\n\n /**\n * Check if systemPrompt is a string was changed, if so create a new SystemMessage\n */\n if (hasSystemPromptChanged) {\n this.#currentSystemMessage = new SystemMessage({\n content: [{ type: \"text\", text: req.systemPrompt }],\n });\n normalizedReq = {\n ...req,\n systemPrompt: this.#currentSystemMessage.text,\n systemMessage: this.#currentSystemMessage,\n };\n }\n /**\n * If the systemMessage was changed, update the current system message\n */\n if (hasSystemMessageChanged) {\n this.#currentSystemMessage = new SystemMessage({\n ...req.systemMessage,\n });\n normalizedReq = {\n ...req,\n systemPrompt: this.#currentSystemMessage.text,\n systemMessage: this.#currentSystemMessage,\n };\n }\n\n return innerHandler(normalizedReq);\n };\n\n // Call middleware's wrapModelCall with the validation handler\n if (!currentMiddleware.wrapModelCall) {\n return handlerWithValidation(requestWithStateAndRuntime);\n }\n\n try {\n const middlewareResponse = await currentMiddleware.wrapModelCall(\n requestWithStateAndRuntime,\n handlerWithValidation as WrapModelCallHandler\n );\n\n /**\n * Validate that this specific middleware returned a valid AIMessage\n */\n if (!AIMessage.isInstance(middlewareResponse)) {\n throw new Error(\n `Invalid response from \"wrapModelCall\" in middleware \"${\n currentMiddleware.name\n }\": expected AIMessage, got ${typeof middlewareResponse}`\n );\n }\n\n return middlewareResponse;\n } catch (error) {\n /**\n * Add middleware context to error if not already added\n */\n if (\n error instanceof Error &&\n !error.message.includes(`middleware \"${currentMiddleware.name}\"`)\n ) {\n error.message = `Error in middleware \"${currentMiddleware.name}\": ${error.message}`;\n }\n throw error;\n }\n };\n }\n }\n\n /**\n * Execute the wrapped handler with the initial request\n * Reset current system prompt to initial state and convert to string using .text getter\n * for backwards compatibility with ModelRequest\n */\n this.#currentSystemMessage = this.#systemMessage;\n const initialRequest: ModelRequest<\n InternalAgentState<StructuredResponseFormat> & PreHookAnnotation[\"State\"],\n unknown\n > = {\n model,\n systemPrompt: this.#currentSystemMessage?.text,\n systemMessage: this.#currentSystemMessage,\n messages: state.messages,\n tools: this.#options.toolClasses,\n state,\n runtime: Object.freeze({\n context: lgConfig?.context,\n writer: lgConfig.writer,\n interrupt: lgConfig.interrupt,\n signal: lgConfig.signal,\n }) as Runtime<unknown>,\n };\n\n return wrappedHandler(initialRequest);\n }\n\n /**\n * If the model returns multiple structured outputs, we need to handle it.\n * @param response - The response from the model\n * @param toolCalls - The tool calls that were made\n * @returns The response from the model\n */\n #handleMultipleStructuredOutputs(\n response: AIMessage,\n toolCalls: ToolCall[],\n responseFormat: ToolResponseFormat\n ): Promise<Command> {\n const multipleStructuredOutputsError = new MultipleStructuredOutputsError(\n toolCalls.map((call) => call.name)\n );\n\n return this.#handleToolStrategyError(\n multipleStructuredOutputsError,\n response,\n toolCalls[0],\n responseFormat\n );\n }\n\n /**\n * If the model returns a single structured output, we need to handle it.\n * @param toolCall - The tool call that was made\n * @returns The structured response and a message to the LLM if needed\n */\n #handleSingleStructuredOutput(\n response: AIMessage,\n toolCall: ToolCall,\n responseFormat: ToolResponseFormat,\n lastMessage?: string\n ): ResponseHandlerResult<StructuredResponseFormat> {\n const tool = responseFormat.tools[toolCall.name];\n\n try {\n const structuredResponse = tool.parse(\n toolCall.args\n ) as StructuredResponseFormat;\n\n return {\n structuredResponse,\n messages: [\n response,\n new ToolMessage({\n tool_call_id: toolCall.id ?? \"\",\n content: JSON.stringify(structuredResponse),\n name: toolCall.name,\n }),\n new AIMessage(\n lastMessage ??\n `Returning structured response: ${JSON.stringify(\n structuredResponse\n )}`\n ),\n ],\n };\n } catch (error) {\n return this.#handleToolStrategyError(\n error as ToolStrategyError,\n response,\n toolCall,\n responseFormat\n );\n }\n }\n\n async #handleToolStrategyError(\n error: ToolStrategyError,\n response: AIMessage,\n toolCall: ToolCall,\n responseFormat: ToolResponseFormat\n ): Promise<Command> {\n /**\n * Using the `errorHandler` option of the first `ToolStrategy` entry is sufficient here.\n * There is technically only one `ToolStrategy` entry in `structuredToolInfo` if the user\n * uses `toolStrategy` to define the response format. If the user applies a list of json\n * schema objects, these will be transformed into multiple `ToolStrategy` entries but all\n * with the same `handleError` option.\n */\n const errorHandler = Object.values(responseFormat.tools).at(0)?.options\n ?.handleError;\n\n const toolCallId = toolCall.id;\n if (!toolCallId) {\n throw new Error(\n \"Tool call ID is required to handle tool output errors. Please provide a tool call ID.\"\n );\n }\n\n /**\n * Default behavior: retry if `errorHandler` is undefined or truthy.\n * Only throw if explicitly set to `false`.\n */\n if (errorHandler === false) {\n throw error;\n }\n\n /**\n * retry if:\n */\n if (\n /**\n * if the user has provided truthy value as the `errorHandler`, return a new AIMessage\n * with the error message and retry the tool call.\n */\n errorHandler === undefined ||\n (typeof errorHandler === \"boolean\" && errorHandler) ||\n /**\n * if `errorHandler` is an array and contains MultipleStructuredOutputsError\n */\n (Array.isArray(errorHandler) &&\n errorHandler.some((h) => h instanceof MultipleStructuredOutputsError))\n ) {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: error.message,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: AGENT_NODE_NAME,\n });\n }\n\n /**\n * if `errorHandler` is a string, retry the tool call with given string\n */\n if (typeof errorHandler === \"string\") {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: errorHandler,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: AGENT_NODE_NAME,\n });\n }\n\n /**\n * if `errorHandler` is a function, retry the tool call with the function\n */\n if (typeof errorHandler === \"function\") {\n const content = await errorHandler(error);\n if (typeof content !== \"string\") {\n throw new Error(\"Error handler must return a string.\");\n }\n\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: AGENT_NODE_NAME,\n });\n }\n\n /**\n * Default: retry if we reach here\n */\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: error.message,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: AGENT_NODE_NAME,\n });\n }\n\n #areMoreStepsNeeded(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n response: BaseMessage\n ): boolean {\n const allToolsReturnDirect =\n AIMessage.isInstance(response) &&\n response.tool_calls?.every((call) =>\n this.#options.shouldReturnDirect.has(call.name)\n );\n const remainingSteps =\n \"remainingSteps\" in state ? (state.remainingSteps as number) : undefined;\n return Boolean(\n remainingSteps &&\n ((remainingSteps < 1 && allToolsReturnDirect) ||\n (remainingSteps < 2 && hasToolCalls(state.messages.at(-1))))\n );\n }\n\n async #bindTools(\n model: LanguageModelLike,\n preparedOptions: ModelRequest | undefined,\n structuredResponseFormat: ResponseFormat | undefined\n ): Promise<Runnable> {\n const options: Partial<BaseChatModelCallOptions> = {};\n const structuredTools = Object.values(\n structuredResponseFormat && \"tools\" in structuredResponseFormat\n ? structuredResponseFormat.tools\n : {}\n );\n\n /**\n * Use tools from preparedOptions if provided, otherwise use default tools\n */\n const allTools = [\n ...(preparedOptions?.tools ?? this.#options.toolClasses),\n ...structuredTools.map((toolStrategy) => toolStrategy.tool),\n ];\n\n /**\n * If there are structured tools, we need to set the tool choice to \"any\"\n * so that the model can choose to use a structured tool or not.\n */\n const toolChoice =\n preparedOptions?.toolChoice ||\n (structuredTools.length > 0 ? \"any\" : undefined);\n\n /**\n * check if the user requests a native schema output\n */\n if (structuredResponseFormat?.type === \"native\") {\n const jsonSchemaParams = {\n name: structuredResponseFormat.strategy.schema?.name ?? \"extract\",\n description: getSchemaDescription(\n structuredResponseFormat.strategy.schema\n ),\n schema: structuredResponseFormat.strategy.schema,\n strict: true,\n };\n\n Object.assign(options, {\n response_format: {\n type: \"json_schema\",\n json_schema: jsonSchemaParams,\n },\n ls_structured_output_format: {\n kwargs: { method: \"json_schema\" },\n schema: structuredResponseFormat.strategy.schema,\n },\n strict: true,\n });\n }\n\n /**\n * Bind tools to the model if they are not already bound.\n */\n const modelWithTools = await bindTools(model, allTools, {\n ...options,\n ...(preparedOptions?.modelSettings ?? {}),\n tool_choice: toolChoice,\n });\n\n /**\n * Create a model runnable with the prompt and agent name\n * Use current SystemMessage state (which may have been modified by middleware)\n */\n const modelRunnable =\n this.#options.includeAgentName === \"inline\"\n ? withAgentName(modelWithTools, this.#options.includeAgentName)\n : modelWithTools;\n\n return modelRunnable;\n }\n\n getState(): {\n messages: BaseMessage[];\n } {\n const state = super.getState();\n const origState = state && !(state instanceof Command) ? state : {};\n\n return {\n messages: [],\n ...origState,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAmEA,MAAa,kBAAkB;AAmC/B,IAAa,YAAb,cAMUA,0CAOR;CACA;CACA;CACA;CAEA,YACEC,SACA;EACA,MAAM;GACJ,MAAM,QAAQ,QAAQ;GACtB,MAAM,CAAC,OAAO,WAAW,KAAKC,KAAK,OAAO,OAAyB;EACpE,EAAC;EAEF,KAAKC,WAAW;EAChB,KAAKC,iBAAiB,QAAQ;CAC/B;;;;;;;;;;;;;CAcD,mBACEC,OAC4B;AAC5B,MAAI,CAAC,KAAKF,SAAS,eACjB,QAAO;EAGT,MAAM,aAAaG,0CACjB,KAAKH,SAAS,gBACd,QACA,MACD;;;;EAKD,MAAM,qBAAqB,WAAW,MACpC,CAAC,WAAW,kBAAkBI,mCAC/B;;;;AAKD,MAAI,CAAC,mBACH,QAAO;GACL,MAAM;GACN,OACE,WAAW,OACT,CAAC,WAAW,kBAAkBC,+BAC/B,CACD,OAAO,CAAC,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IACD,QAAQ;GACT,EAAC;EACH;;;;EAKD,MAAM,iBAAiB,MAAM8C,wBAAU,OAAO,UAAU;GACtD,GAAG;GACH,GAAI,iBAAiB,iBAAiB,CAAE;GACxC,aAAa;EACd,EAAC;;;;;EAMF,MAAM,gBACJ,KAAK9C,SAAS,qBAAqB,WAC/B+C,oCAAc,gBAAgB,KAAK/C,SAAS,iBAAiB,GAC7D;AAEN,SAAO;CACR;CAED,WAEE;EACA,MAAM,QAAQ,MAAM,UAAU;EAC9B,MAAM,YAAY,SAAS,EAAE,iBAAiBU,iCAAW,QAAQ,CAAE;AAEnE,SAAO;GACL,UAAU,CAAE;GACZ,GAAG;EACJ;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"AgentNode.cjs","names":["response: unknown","AIMessage","RunnableCallable","options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>","#run","#options","#systemMessage","model: string | LanguageModelLike","transformResponseFormat","ProviderStrategy","ToolStrategy","state: InternalAgentState<StructuredResponseFormat>","config: RunnableConfig","ToolMessage","#invokeModel","Command","#areMoreStepsNeeded","initChatModel","options: {\n lastMessage?: string;\n }","#deriveModel","request: ModelRequest","validateLLMHasNoBoundTools","#getResponseFormat","#bindTools","#currentSystemMessage","mergeAbortSignals","#handleMultipleStructuredOutputs","#handleSingleStructuredOutput","wrappedHandler: (\n request: ModelRequest<\n InternalAgentState<StructuredResponseFormat>,\n unknown\n >\n ) => Promise<InternalModelResponse<StructuredResponseFormat>>","request: ModelRequest<\n InternalAgentState<StructuredResponseFormat>,\n unknown\n >","runtime: Runtime<unknown>","requestWithStateAndRuntime: ModelRequest<\n InternalAgentState<StructuredResponseFormat>,\n unknown\n >","req: ModelRequest<\n InternalAgentState<StructuredResponseFormat>,\n unknown\n >","isClientTool","SystemMessage","initialRequest: ModelRequest<\n InternalAgentState<StructuredResponseFormat>,\n unknown\n >","response: AIMessage","toolCalls: ToolCall[]","responseFormat: ToolResponseFormat","MultipleStructuredOutputsError","#handleToolStrategyError","toolCall: ToolCall","lastMessage?: string","error: ToolStrategyError","response: BaseMessage","hasToolCalls","model: LanguageModelLike","preparedOptions: ModelRequest | undefined","structuredResponseFormat: ResponseFormat | undefined","options: Partial<BaseChatModelCallOptions>","bindTools","withAgentName"],"sources":["../../../src/agents/nodes/AgentNode.ts"],"sourcesContent":["/* eslint-disable no-instanceof/no-instanceof */\nimport { Runnable, RunnableConfig } from \"@langchain/core/runnables\";\nimport {\n BaseMessage,\n AIMessage,\n ToolMessage,\n SystemMessage,\n} from \"@langchain/core/messages\";\nimport { Command, type LangGraphRunnableConfig } from \"@langchain/langgraph\";\nimport { type LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { type BaseChatModelCallOptions } from \"@langchain/core/language_models/chat_models\";\nimport {\n InteropZodObject,\n getSchemaDescription,\n interopParse,\n interopZodObjectPartial,\n} from \"@langchain/core/utils/types\";\nimport { raceWithSignal } from \"@langchain/core/runnables\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport { initChatModel } from \"../../chat_models/universal.js\";\nimport { MultipleStructuredOutputsError } from \"../errors.js\";\nimport { RunnableCallable } from \"../RunnableCallable.js\";\nimport {\n bindTools,\n validateLLMHasNoBoundTools,\n hasToolCalls,\n isClientTool,\n} from \"../utils.js\";\nimport { mergeAbortSignals } from \"../nodes/utils.js\";\nimport { CreateAgentParams } from \"../types.js\";\nimport type { InternalAgentState, Runtime } from \"../runtime.js\";\nimport type {\n AgentMiddleware,\n AnyAnnotationRoot,\n WrapModelCallHandler,\n} from \"../middleware/types.js\";\nimport type { ModelRequest } from \"./types.js\";\nimport { withAgentName } from \"../withAgentName.js\";\nimport {\n ToolStrategy,\n ProviderStrategy,\n transformResponseFormat,\n ToolStrategyError,\n} from \"../responses.js\";\n\ntype ResponseHandlerResult<StructuredResponseFormat> =\n | {\n structuredResponse: StructuredResponseFormat;\n messages: BaseMessage[];\n }\n | Promise<Command>;\n\n/**\n * Wrap the base handler with middleware wrapModelCall hooks\n * Middleware are composed so the first middleware is the outermost wrapper\n * Example: [auth, retry, cache] means auth wraps retry wraps cache wraps baseHandler\n */\ntype InternalModelResponse<StructuredResponseFormat> =\n | AIMessage\n | ResponseHandlerResult<StructuredResponseFormat>;\n\n/**\n * Check if the response is an internal model response.\n * @param response - The response to check.\n * @returns True if the response is an internal model response, false otherwise.\n */\nfunction isInternalModelResponse<StructuredResponseFormat>(\n response: unknown\n): response is InternalModelResponse<StructuredResponseFormat> {\n return (\n AIMessage.isInstance(response) ||\n (typeof response === \"object\" &&\n response !== null &&\n \"structuredResponse\" in response &&\n \"messages\" in response)\n );\n}\n\n/**\n * The name of the agent node in the state graph.\n */\nexport const AGENT_NODE_NAME = \"model_request\";\n\nexport interface AgentNodeOptions<\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> extends Pick<\n CreateAgentParams<StructuredResponseFormat, StateSchema, ContextSchema>,\n \"model\" | \"includeAgentName\" | \"name\" | \"responseFormat\" | \"middleware\"\n > {\n toolClasses: (ClientTool | ServerTool)[];\n shouldReturnDirect: Set<string>;\n signal?: AbortSignal;\n systemMessage: SystemMessage;\n wrapModelCallHookMiddleware?: [\n AgentMiddleware,\n () => Record<string, unknown>\n ][];\n}\n\ninterface NativeResponseFormat {\n type: \"native\";\n strategy: ProviderStrategy;\n}\n\ninterface ToolResponseFormat {\n type: \"tool\";\n tools: Record<string, ToolStrategy>;\n}\n\ntype ResponseFormat = NativeResponseFormat | ToolResponseFormat;\n\nexport class AgentNode<\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> extends RunnableCallable<\n InternalAgentState<StructuredResponseFormat>,\n | (\n | { messages: BaseMessage[] }\n | { structuredResponse: StructuredResponseFormat }\n )\n | Command\n> {\n #options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>;\n #systemMessage: SystemMessage;\n #currentSystemMessage: SystemMessage;\n\n constructor(\n options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>\n ) {\n super({\n name: options.name ?? \"model\",\n func: (input, config) => this.#run(input, config as RunnableConfig),\n });\n\n this.#options = options;\n this.#systemMessage = options.systemMessage;\n }\n\n /**\n * Returns response format primtivies based on given model and response format provided by the user.\n *\n * If the user selects a tool output:\n * - return a record of tools to extract structured output from the model's response\n *\n * if the the user selects a native schema output or if the model supports JSON schema output:\n * - return a provider strategy to extract structured output from the model's response\n *\n * @param model - The model to get the response format for.\n * @returns The response format.\n */\n #getResponseFormat(\n model: string | LanguageModelLike\n ): ResponseFormat | undefined {\n if (!this.#options.responseFormat) {\n return undefined;\n }\n\n const strategies = transformResponseFormat(\n this.#options.responseFormat,\n undefined,\n model\n );\n\n /**\n * we either define a list of provider strategies or a list of tool strategies\n */\n const isProviderStrategy = strategies.every(\n (format) => format instanceof ProviderStrategy\n );\n\n /**\n * Populate a list of structured tool info.\n */\n if (!isProviderStrategy) {\n return {\n type: \"tool\",\n tools: (\n strategies.filter(\n (format) => format instanceof ToolStrategy\n ) as ToolStrategy[]\n ).reduce((acc, format) => {\n acc[format.name] = format;\n return acc;\n }, {} as Record<string, ToolStrategy>),\n };\n }\n\n return {\n type: \"native\",\n /**\n * there can only be one provider strategy\n */\n strategy: strategies[0] as ProviderStrategy,\n };\n }\n\n async #run(\n state: InternalAgentState<StructuredResponseFormat>,\n config: RunnableConfig\n ) {\n /**\n * Check if we just executed a returnDirect tool\n * If so, we should generate structured response (if needed) and stop\n */\n const lastMessage = state.messages.at(-1);\n if (\n lastMessage &&\n ToolMessage.isInstance(lastMessage) &&\n lastMessage.name &&\n this.#options.shouldReturnDirect.has(lastMessage.name)\n ) {\n /**\n * return directly without invoking the model again\n */\n return { messages: [] };\n }\n\n const response = await this.#invokeModel(state, config);\n\n /**\n * if we were able to generate a structured response, return it\n */\n if (\"structuredResponse\" in response) {\n return {\n messages: [...state.messages, ...(response.messages || [])],\n structuredResponse: response.structuredResponse,\n };\n }\n\n /**\n * if we need to direct the agent to the model, return the update\n */\n if (response instanceof Command) {\n return response;\n }\n\n response.name = this.name;\n response.lc_kwargs.name = this.name;\n\n if (this.#areMoreStepsNeeded(state, response)) {\n return {\n messages: [\n new AIMessage({\n content: \"Sorry, need more steps to process this request.\",\n name: this.name,\n id: response.id,\n }),\n ],\n };\n }\n\n return { messages: [response] };\n }\n\n /**\n * Derive the model from the options.\n * @param state - The state of the agent.\n * @param config - The config of the agent.\n * @returns The model.\n */\n #deriveModel() {\n if (typeof this.#options.model === \"string\") {\n return initChatModel(this.#options.model);\n }\n\n if (this.#options.model) {\n return this.#options.model;\n }\n\n throw new Error(\"No model option was provided, either via `model` option.\");\n }\n\n async #invokeModel(\n state: InternalAgentState<StructuredResponseFormat>,\n config: RunnableConfig,\n options: {\n lastMessage?: string;\n } = {}\n ): Promise<AIMessage | ResponseHandlerResult<StructuredResponseFormat>> {\n const model = await this.#deriveModel();\n const lgConfig = config as LangGraphRunnableConfig;\n\n /**\n * Create the base handler that performs the actual model invocation\n */\n const baseHandler = async (\n request: ModelRequest\n ): Promise<AIMessage | ResponseHandlerResult<StructuredResponseFormat>> => {\n /**\n * Check if the LLM already has bound tools and throw if it does.\n */\n validateLLMHasNoBoundTools(request.model);\n\n const structuredResponseFormat = this.#getResponseFormat(request.model);\n const modelWithTools = await this.#bindTools(\n request.model,\n request,\n structuredResponseFormat\n );\n\n /**\n * prepend the system message to the messages if it is not empty\n */\n const messages = [\n ...(this.#currentSystemMessage.text === \"\"\n ? []\n : [this.#currentSystemMessage]),\n ...request.messages,\n ];\n\n const signal = mergeAbortSignals(this.#options.signal, config.signal);\n const response = (await raceWithSignal(\n modelWithTools.invoke(messages, {\n ...config,\n signal,\n }),\n signal\n )) as AIMessage;\n\n /**\n * if the user requests a native schema output, try to parse the response\n * and return the structured response if it is valid\n */\n if (structuredResponseFormat?.type === \"native\") {\n const structuredResponse =\n structuredResponseFormat.strategy.parse(response);\n if (structuredResponse) {\n return { structuredResponse, messages: [response] };\n }\n\n return response;\n }\n\n if (!structuredResponseFormat || !response.tool_calls) {\n return response;\n }\n\n const toolCalls = response.tool_calls.filter(\n (call) => call.name in structuredResponseFormat.tools\n );\n\n /**\n * if there were not structured tool calls, we can return the response\n */\n if (toolCalls.length === 0) {\n return response;\n }\n\n /**\n * if there were multiple structured tool calls, we should throw an error as this\n * scenario is not defined/supported.\n */\n if (toolCalls.length > 1) {\n return this.#handleMultipleStructuredOutputs(\n response,\n toolCalls,\n structuredResponseFormat\n );\n }\n\n const toolStrategy = structuredResponseFormat.tools[toolCalls[0].name];\n const toolMessageContent = toolStrategy?.options?.toolMessageContent;\n return this.#handleSingleStructuredOutput(\n response,\n toolCalls[0],\n structuredResponseFormat,\n toolMessageContent ?? options.lastMessage\n );\n };\n\n const wrapperMiddleware = this.#options.wrapModelCallHookMiddleware ?? [];\n let wrappedHandler: (\n request: ModelRequest<\n InternalAgentState<StructuredResponseFormat>,\n unknown\n >\n ) => Promise<InternalModelResponse<StructuredResponseFormat>> = baseHandler;\n\n /**\n * Build composed handler from last to first so first middleware becomes outermost\n */\n for (let i = wrapperMiddleware.length - 1; i >= 0; i--) {\n const [middleware, getMiddlewareState] = wrapperMiddleware[i];\n if (middleware.wrapModelCall) {\n const innerHandler = wrappedHandler;\n const currentMiddleware = middleware;\n const currentGetState = getMiddlewareState;\n\n wrappedHandler = async (\n request: ModelRequest<\n InternalAgentState<StructuredResponseFormat>,\n unknown\n >\n ): Promise<InternalModelResponse<StructuredResponseFormat>> => {\n /**\n * Merge context with default context of middleware\n */\n const context = currentMiddleware.contextSchema\n ? interopParse(\n currentMiddleware.contextSchema,\n lgConfig?.context || {}\n )\n : lgConfig?.context;\n\n /**\n * Create runtime\n */\n const runtime: Runtime<unknown> = Object.freeze({\n context,\n writer: lgConfig.writer,\n interrupt: lgConfig.interrupt,\n signal: lgConfig.signal,\n });\n\n /**\n * Create the request with state and runtime\n */\n const requestWithStateAndRuntime: ModelRequest<\n InternalAgentState<StructuredResponseFormat>,\n unknown\n > = {\n ...request,\n state: {\n ...(middleware.stateSchema\n ? interopParse(\n interopZodObjectPartial(middleware.stateSchema),\n state\n )\n : {}),\n ...currentGetState(),\n messages: state.messages,\n } as InternalAgentState<StructuredResponseFormat>,\n runtime,\n };\n\n /**\n * Create handler that validates tools and calls the inner handler\n */\n const handlerWithValidation = async (\n req: ModelRequest<\n InternalAgentState<StructuredResponseFormat>,\n unknown\n >\n ): Promise<InternalModelResponse<StructuredResponseFormat>> => {\n /**\n * Verify that the user didn't add any new tools.\n * We can't allow this as the ToolNode is already initiated with given tools.\n */\n const modifiedTools = req.tools ?? [];\n const newTools = modifiedTools.filter(\n (tool) =>\n isClientTool(tool) &&\n !this.#options.toolClasses.some((t) => t.name === tool.name)\n );\n if (newTools.length > 0) {\n throw new Error(\n `You have added a new tool in \"wrapModelCall\" hook of middleware \"${\n currentMiddleware.name\n }\": ${newTools\n .map((tool) => tool.name)\n .join(\", \")}. This is not supported.`\n );\n }\n\n /**\n * Verify that user has not added or modified a tool with the same name.\n * We can't allow this as the ToolNode is already initiated with given tools.\n */\n const invalidTools = modifiedTools.filter(\n (tool) =>\n isClientTool(tool) &&\n this.#options.toolClasses.every((t) => t !== tool)\n );\n if (invalidTools.length > 0) {\n throw new Error(\n `You have modified a tool in \"wrapModelCall\" hook of middleware \"${\n currentMiddleware.name\n }\": ${invalidTools\n .map((tool) => tool.name)\n .join(\", \")}. This is not supported.`\n );\n }\n\n let normalizedReq = req;\n const hasSystemPromptChanged =\n req.systemPrompt !== this.#currentSystemMessage.text;\n const hasSystemMessageChanged =\n req.systemMessage !== this.#currentSystemMessage;\n if (hasSystemPromptChanged && hasSystemMessageChanged) {\n throw new Error(\n \"Cannot change both systemPrompt and systemMessage in the same request.\"\n );\n }\n\n /**\n * Check if systemPrompt is a string was changed, if so create a new SystemMessage\n */\n if (hasSystemPromptChanged) {\n this.#currentSystemMessage = new SystemMessage({\n content: [{ type: \"text\", text: req.systemPrompt }],\n });\n normalizedReq = {\n ...req,\n systemPrompt: this.#currentSystemMessage.text,\n systemMessage: this.#currentSystemMessage,\n };\n }\n /**\n * If the systemMessage was changed, update the current system message\n */\n if (hasSystemMessageChanged) {\n this.#currentSystemMessage = new SystemMessage({\n ...req.systemMessage,\n });\n normalizedReq = {\n ...req,\n systemPrompt: this.#currentSystemMessage.text,\n systemMessage: this.#currentSystemMessage,\n };\n }\n\n return innerHandler(normalizedReq);\n };\n\n // Call middleware's wrapModelCall with the validation handler\n if (!currentMiddleware.wrapModelCall) {\n return handlerWithValidation(requestWithStateAndRuntime);\n }\n\n try {\n const middlewareResponse = await currentMiddleware.wrapModelCall(\n requestWithStateAndRuntime,\n handlerWithValidation as WrapModelCallHandler\n );\n\n /**\n * Validate that this specific middleware returned a valid AIMessage\n */\n if (!isInternalModelResponse(middlewareResponse)) {\n throw new Error(\n `Invalid response from \"wrapModelCall\" in middleware \"${\n currentMiddleware.name\n }\": expected AIMessage, got ${typeof middlewareResponse}`\n );\n }\n\n return middlewareResponse;\n } catch (error) {\n /**\n * Add middleware context to error if not already added\n */\n if (\n error instanceof Error &&\n !error.message.includes(`middleware \"${currentMiddleware.name}\"`)\n ) {\n error.message = `Error in middleware \"${currentMiddleware.name}\": ${error.message}`;\n }\n throw error;\n }\n };\n }\n }\n\n /**\n * Execute the wrapped handler with the initial request\n * Reset current system prompt to initial state and convert to string using .text getter\n * for backwards compatibility with ModelRequest\n */\n this.#currentSystemMessage = this.#systemMessage;\n const initialRequest: ModelRequest<\n InternalAgentState<StructuredResponseFormat>,\n unknown\n > = {\n model,\n systemPrompt: this.#currentSystemMessage?.text,\n systemMessage: this.#currentSystemMessage,\n messages: state.messages,\n tools: this.#options.toolClasses,\n state,\n runtime: Object.freeze({\n context: lgConfig?.context,\n writer: lgConfig.writer,\n interrupt: lgConfig.interrupt,\n signal: lgConfig.signal,\n }) as Runtime<unknown>,\n };\n\n return wrappedHandler(initialRequest);\n }\n\n /**\n * If the model returns multiple structured outputs, we need to handle it.\n * @param response - The response from the model\n * @param toolCalls - The tool calls that were made\n * @returns The response from the model\n */\n #handleMultipleStructuredOutputs(\n response: AIMessage,\n toolCalls: ToolCall[],\n responseFormat: ToolResponseFormat\n ): Promise<Command> {\n const multipleStructuredOutputsError = new MultipleStructuredOutputsError(\n toolCalls.map((call) => call.name)\n );\n\n return this.#handleToolStrategyError(\n multipleStructuredOutputsError,\n response,\n toolCalls[0],\n responseFormat\n );\n }\n\n /**\n * If the model returns a single structured output, we need to handle it.\n * @param toolCall - The tool call that was made\n * @returns The structured response and a message to the LLM if needed\n */\n #handleSingleStructuredOutput(\n response: AIMessage,\n toolCall: ToolCall,\n responseFormat: ToolResponseFormat,\n lastMessage?: string\n ): ResponseHandlerResult<StructuredResponseFormat> {\n const tool = responseFormat.tools[toolCall.name];\n\n try {\n const structuredResponse = tool.parse(\n toolCall.args\n ) as StructuredResponseFormat;\n\n return {\n structuredResponse,\n messages: [\n response,\n new ToolMessage({\n tool_call_id: toolCall.id ?? \"\",\n content: JSON.stringify(structuredResponse),\n name: toolCall.name,\n }),\n new AIMessage(\n lastMessage ??\n `Returning structured response: ${JSON.stringify(\n structuredResponse\n )}`\n ),\n ],\n };\n } catch (error) {\n return this.#handleToolStrategyError(\n error as ToolStrategyError,\n response,\n toolCall,\n responseFormat\n );\n }\n }\n\n async #handleToolStrategyError(\n error: ToolStrategyError,\n response: AIMessage,\n toolCall: ToolCall,\n responseFormat: ToolResponseFormat\n ): Promise<Command> {\n /**\n * Using the `errorHandler` option of the first `ToolStrategy` entry is sufficient here.\n * There is technically only one `ToolStrategy` entry in `structuredToolInfo` if the user\n * uses `toolStrategy` to define the response format. If the user applies a list of json\n * schema objects, these will be transformed into multiple `ToolStrategy` entries but all\n * with the same `handleError` option.\n */\n const errorHandler = Object.values(responseFormat.tools).at(0)?.options\n ?.handleError;\n\n const toolCallId = toolCall.id;\n if (!toolCallId) {\n throw new Error(\n \"Tool call ID is required to handle tool output errors. Please provide a tool call ID.\"\n );\n }\n\n /**\n * Default behavior: retry if `errorHandler` is undefined or truthy.\n * Only throw if explicitly set to `false`.\n */\n if (errorHandler === false) {\n throw error;\n }\n\n /**\n * retry if:\n */\n if (\n /**\n * if the user has provided truthy value as the `errorHandler`, return a new AIMessage\n * with the error message and retry the tool call.\n */\n errorHandler === undefined ||\n (typeof errorHandler === \"boolean\" && errorHandler) ||\n /**\n * if `errorHandler` is an array and contains MultipleStructuredOutputsError\n */\n (Array.isArray(errorHandler) &&\n errorHandler.some((h) => h instanceof MultipleStructuredOutputsError))\n ) {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: error.message,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: AGENT_NODE_NAME,\n });\n }\n\n /**\n * if `errorHandler` is a string, retry the tool call with given string\n */\n if (typeof errorHandler === \"string\") {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: errorHandler,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: AGENT_NODE_NAME,\n });\n }\n\n /**\n * if `errorHandler` is a function, retry the tool call with the function\n */\n if (typeof errorHandler === \"function\") {\n const content = await errorHandler(error);\n if (typeof content !== \"string\") {\n throw new Error(\"Error handler must return a string.\");\n }\n\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: AGENT_NODE_NAME,\n });\n }\n\n /**\n * Default: retry if we reach here\n */\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: error.message,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: AGENT_NODE_NAME,\n });\n }\n\n #areMoreStepsNeeded(\n state: InternalAgentState<StructuredResponseFormat>,\n response: BaseMessage\n ): boolean {\n const allToolsReturnDirect =\n AIMessage.isInstance(response) &&\n response.tool_calls?.every((call) =>\n this.#options.shouldReturnDirect.has(call.name)\n );\n const remainingSteps =\n \"remainingSteps\" in state ? (state.remainingSteps as number) : undefined;\n return Boolean(\n remainingSteps &&\n ((remainingSteps < 1 && allToolsReturnDirect) ||\n (remainingSteps < 2 && hasToolCalls(state.messages.at(-1))))\n );\n }\n\n async #bindTools(\n model: LanguageModelLike,\n preparedOptions: ModelRequest | undefined,\n structuredResponseFormat: ResponseFormat | undefined\n ): Promise<Runnable> {\n const options: Partial<BaseChatModelCallOptions> = {};\n const structuredTools = Object.values(\n structuredResponseFormat && \"tools\" in structuredResponseFormat\n ? structuredResponseFormat.tools\n : {}\n );\n\n /**\n * Use tools from preparedOptions if provided, otherwise use default tools\n */\n const allTools = [\n ...(preparedOptions?.tools ?? this.#options.toolClasses),\n ...structuredTools.map((toolStrategy) => toolStrategy.tool),\n ];\n\n /**\n * If there are structured tools, we need to set the tool choice to \"any\"\n * so that the model can choose to use a structured tool or not.\n */\n const toolChoice =\n preparedOptions?.toolChoice ||\n (structuredTools.length > 0 ? \"any\" : undefined);\n\n /**\n * check if the user requests a native schema output\n */\n if (structuredResponseFormat?.type === \"native\") {\n const jsonSchemaParams = {\n name: structuredResponseFormat.strategy.schema?.name ?? \"extract\",\n description: getSchemaDescription(\n structuredResponseFormat.strategy.schema\n ),\n schema: structuredResponseFormat.strategy.schema,\n strict: true,\n };\n\n Object.assign(options, {\n response_format: {\n type: \"json_schema\",\n json_schema: jsonSchemaParams,\n },\n output_format: {\n type: \"json_schema\",\n schema: structuredResponseFormat.strategy.schema,\n },\n headers: {\n \"anthropic-beta\": \"structured-outputs-2025-11-13\",\n },\n ls_structured_output_format: {\n kwargs: { method: \"json_schema\" },\n schema: structuredResponseFormat.strategy.schema,\n },\n strict: true,\n });\n }\n\n /**\n * Bind tools to the model if they are not already bound.\n */\n const modelWithTools = await bindTools(model, allTools, {\n ...options,\n ...(preparedOptions?.modelSettings ?? {}),\n tool_choice: toolChoice,\n });\n\n /**\n * Create a model runnable with the prompt and agent name\n * Use current SystemMessage state (which may have been modified by middleware)\n */\n const modelRunnable =\n this.#options.includeAgentName === \"inline\"\n ? withAgentName(modelWithTools, this.#options.includeAgentName)\n : modelWithTools;\n\n return modelRunnable;\n }\n\n getState(): {\n messages: BaseMessage[];\n } {\n const state = super.getState();\n const origState = state && !(state instanceof Command) ? state : {};\n\n return {\n messages: [],\n ...origState,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAoEA,SAAS,wBACPA,UAC6D;AAC7D,QACEC,oCAAU,WAAW,SAAS,IAC7B,OAAO,aAAa,YACnB,aAAa,QACb,wBAAwB,YACxB,cAAc;AAEnB;;;;AAKD,MAAa,kBAAkB;AAmC/B,IAAa,YAAb,cAMUC,0CAOR;CACA;CACA;CACA;CAEA,YACEC,SACA;EACA,MAAM;GACJ,MAAM,QAAQ,QAAQ;GACtB,MAAM,CAAC,OAAO,WAAW,KAAKC,KAAK,OAAO,OAAyB;EACpE,EAAC;EAEF,KAAKC,WAAW;EAChB,KAAKC,iBAAiB,QAAQ;CAC/B;;;;;;;;;;;;;CAcD,mBACEC,OAC4B;AAC5B,MAAI,CAAC,KAAKF,SAAS,eACjB,QAAO;EAGT,MAAM,aAAaG,0CACjB,KAAKH,SAAS,gBACd,QACA,MACD;;;;EAKD,MAAM,qBAAqB,WAAW,MACpC,CAAC,WAAW,kBAAkBI,mCAC/B;;;;AAKD,MAAI,CAAC,mBACH,QAAO;GACL,MAAM;GACN,OACE,WAAW,OACT,CAAC,WAAW,kBAAkBC,+BAC/B,CACD,OAAO,CAAC,KAAK,WAAW;IACxB,IAAI,OAAO,QAAQ;AACnB,WAAO;GACR,GAAE,CAAE,EAAiC;EACvC;AAGH,SAAO;GACL,MAAM;GAIN,UAAU,WAAW;EACtB;CACF;CAED,MAAMN,KACJO,OACAC,QACA;;;;;EAKA,MAAM,cAAc,MAAM,SAAS,GAAG,GAAG;AACzC,MACE,eACAC,sCAAY,WAAW,YAAY,IACnC,YAAY,QACZ,KAAKR,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