langchain 1.1.6-dev-1765433794876 → 1.1.6
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 +21 -0
- package/chat_models/universal.cjs +1 -0
- package/chat_models/universal.d.cts +1 -0
- package/chat_models/universal.d.ts +1 -0
- package/chat_models/universal.js +1 -0
- package/dist/agents/index.cjs +1 -0
- package/dist/agents/index.cjs.map +1 -1
- package/dist/agents/index.d.cts +1 -1
- package/dist/agents/index.d.cts.map +1 -1
- package/dist/agents/index.d.ts +1 -1
- package/dist/agents/index.d.ts.map +1 -1
- package/dist/agents/index.js +1 -0
- package/dist/agents/index.js.map +1 -1
- package/dist/agents/middleware/dynamicSystemPrompt.d.ts.map +1 -1
- package/dist/agents/middleware/hitl.d.ts.map +1 -1
- package/dist/agents/middleware/llmToolSelector.d.cts +4 -4
- package/dist/agents/middleware/llmToolSelector.d.cts.map +1 -1
- package/dist/agents/middleware/summarization.cjs +10 -2
- package/dist/agents/middleware/summarization.cjs.map +1 -1
- package/dist/agents/middleware/summarization.d.cts +7 -7
- package/dist/agents/middleware/summarization.d.cts.map +1 -1
- package/dist/agents/middleware/summarization.d.ts.map +1 -1
- package/dist/agents/middleware/summarization.js +10 -2
- package/dist/agents/middleware/summarization.js.map +1 -1
- package/dist/agents/middleware/todoListMiddleware.d.ts.map +1 -1
- package/dist/agents/middleware/toolCallLimit.d.ts.map +1 -1
- package/dist/agents/middleware/types.cjs +12 -0
- package/dist/agents/middleware/types.cjs.map +1 -0
- package/dist/agents/middleware/types.d.cts +12 -1
- package/dist/agents/middleware/types.d.cts.map +1 -1
- package/dist/agents/middleware/types.d.ts +12 -1
- package/dist/agents/middleware/types.d.ts.map +1 -1
- package/dist/agents/middleware/types.js +11 -0
- package/dist/agents/middleware/types.js.map +1 -0
- package/dist/agents/middleware.cjs +2 -0
- package/dist/agents/middleware.cjs.map +1 -1
- package/dist/agents/middleware.d.cts.map +1 -1
- package/dist/agents/middleware.d.ts.map +1 -1
- package/dist/agents/middleware.js +3 -0
- package/dist/agents/middleware.js.map +1 -1
- package/dist/agents/nodes/AgentNode.cjs +3 -2
- package/dist/agents/nodes/AgentNode.cjs.map +1 -1
- package/dist/agents/nodes/AgentNode.js +3 -2
- package/dist/agents/nodes/AgentNode.js.map +1 -1
- package/dist/agents/responses.cjs +94 -14
- package/dist/agents/responses.cjs.map +1 -1
- package/dist/agents/responses.d.cts +67 -6
- package/dist/agents/responses.d.cts.map +1 -1
- package/dist/agents/responses.d.ts +67 -6
- package/dist/agents/responses.d.ts.map +1 -1
- package/dist/agents/responses.js +94 -14
- package/dist/agents/responses.js.map +1 -1
- package/dist/agents/tests/utils.cjs.map +1 -1
- package/dist/agents/tests/utils.js.map +1 -1
- package/dist/index.cjs +3 -0
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +3 -1
- package/hub/node.cjs +1 -0
- package/hub/node.d.cts +1 -0
- package/hub/node.d.ts +1 -0
- package/hub/node.js +1 -0
- package/hub.cjs +1 -0
- package/hub.d.cts +1 -0
- package/hub.d.ts +1 -0
- package/hub.js +1 -0
- package/load/serializable.cjs +1 -0
- package/load/serializable.d.cts +1 -0
- package/load/serializable.d.ts +1 -0
- package/load/serializable.js +1 -0
- package/load.cjs +1 -0
- package/load.d.cts +1 -0
- package/load.d.ts +1 -0
- package/load.js +1 -0
- package/package.json +5 -5
- package/storage/encoder_backed.cjs +1 -0
- package/storage/encoder_backed.d.cts +1 -0
- package/storage/encoder_backed.d.ts +1 -0
- package/storage/encoder_backed.js +1 -0
- package/storage/file_system.cjs +1 -0
- package/storage/file_system.d.cts +1 -0
- package/storage/file_system.d.ts +1 -0
- package/storage/file_system.js +1 -0
- package/storage/in_memory.cjs +1 -0
- package/storage/in_memory.d.cts +1 -0
- package/storage/in_memory.d.ts +1 -0
- package/storage/in_memory.js +1 -0
|
@@ -39,15 +39,23 @@ declare class ToolStrategy<_T = unknown> {
|
|
|
39
39
|
parse(toolArgs: Record<string, unknown>): Record<string, unknown>;
|
|
40
40
|
}
|
|
41
41
|
declare class ProviderStrategy<T = unknown> {
|
|
42
|
-
readonly schema: Record<string, unknown>;
|
|
43
42
|
private _schemaType?;
|
|
43
|
+
/**
|
|
44
|
+
* The schema to use for the provider strategy
|
|
45
|
+
*/
|
|
46
|
+
readonly schema: Record<string, unknown>;
|
|
47
|
+
/**
|
|
48
|
+
* Whether to use strict mode for the provider strategy
|
|
49
|
+
*/
|
|
50
|
+
readonly strict: boolean;
|
|
51
|
+
private constructor();
|
|
44
52
|
private constructor();
|
|
45
|
-
static fromSchema<T>(schema: InteropZodType<T
|
|
46
|
-
static fromSchema(schema: Record<string, unknown
|
|
53
|
+
static fromSchema<T>(schema: InteropZodType<T>, strict?: boolean): ProviderStrategy<T>;
|
|
54
|
+
static fromSchema(schema: Record<string, unknown>, strict?: boolean): ProviderStrategy<Record<string, unknown>>;
|
|
47
55
|
/**
|
|
48
56
|
* Parse tool arguments according to the schema. If the response is not valid, return undefined.
|
|
49
57
|
*
|
|
50
|
-
* @param
|
|
58
|
+
* @param response - The AI message response to parse
|
|
51
59
|
* @returns The parsed response according to the schema type
|
|
52
60
|
*/
|
|
53
61
|
parse(response: AIMessage): any;
|
|
@@ -86,8 +94,61 @@ declare function toolStrategy<T extends InteropZodType<any>>(responseFormat: T,
|
|
|
86
94
|
declare function toolStrategy<T extends readonly InteropZodType<any>[]>(responseFormat: T, options?: ToolStrategyOptions): TypedToolStrategy<{ [K in keyof T]: T[K] extends InteropZodType<infer U> ? U : never }[number]>;
|
|
87
95
|
declare function toolStrategy(responseFormat: JsonSchemaFormat, options?: ToolStrategyOptions): TypedToolStrategy<Record<string, unknown>>;
|
|
88
96
|
declare function toolStrategy(responseFormat: JsonSchemaFormat[], options?: ToolStrategyOptions): TypedToolStrategy<Record<string, unknown>>;
|
|
89
|
-
|
|
90
|
-
|
|
97
|
+
/**
|
|
98
|
+
* Creates a provider strategy for structured output using native JSON schema support.
|
|
99
|
+
*
|
|
100
|
+
* This function is used to configure structured output for agents when the underlying model
|
|
101
|
+
* supports native JSON schema output (e.g., OpenAI's `gpt-4o`, `gpt-4o-mini`, and newer models).
|
|
102
|
+
* Unlike `toolStrategy`, which uses function calling to extract structured output, `providerStrategy`
|
|
103
|
+
* leverages the provider's native structured output capabilities, resulting in more efficient
|
|
104
|
+
* and reliable schema enforcement.
|
|
105
|
+
*
|
|
106
|
+
* When used with a model that supports JSON schema output, the model will return responses
|
|
107
|
+
* that directly conform to the provided schema without requiring tool calls. This is the
|
|
108
|
+
* recommended approach for structured output when your model supports it.
|
|
109
|
+
*
|
|
110
|
+
* @param responseFormat - The schema to enforce, either a Zod schema, a JSON schema object, or an options object with `schema` and optional `strict` flag
|
|
111
|
+
* @returns A `ProviderStrategy` instance that can be used as the `responseFormat` in `createAgent`
|
|
112
|
+
*
|
|
113
|
+
* @example
|
|
114
|
+
* ```ts
|
|
115
|
+
* import { providerStrategy, createAgent } from "langchain";
|
|
116
|
+
* import { z } from "zod";
|
|
117
|
+
*
|
|
118
|
+
* const agent = createAgent({
|
|
119
|
+
* model: "claude-haiku-4-5",
|
|
120
|
+
* responseFormat: providerStrategy(
|
|
121
|
+
* z.object({
|
|
122
|
+
* answer: z.string().describe("The answer to the question"),
|
|
123
|
+
* confidence: z.number().min(0).max(1),
|
|
124
|
+
* })
|
|
125
|
+
* ),
|
|
126
|
+
* });
|
|
127
|
+
* ```
|
|
128
|
+
*
|
|
129
|
+
* @example
|
|
130
|
+
* ```ts
|
|
131
|
+
* // Using strict mode for stricter schema enforcement
|
|
132
|
+
* const agent = createAgent({
|
|
133
|
+
* model: "claude-haiku-4-5",
|
|
134
|
+
* responseFormat: providerStrategy({
|
|
135
|
+
* schema: z.object({
|
|
136
|
+
* name: z.string(),
|
|
137
|
+
* age: z.number(),
|
|
138
|
+
* }),
|
|
139
|
+
* strict: true
|
|
140
|
+
* }),
|
|
141
|
+
* });
|
|
142
|
+
* ```
|
|
143
|
+
*/
|
|
144
|
+
declare function providerStrategy<T extends InteropZodType<unknown>>(responseFormat: T | {
|
|
145
|
+
schema: T;
|
|
146
|
+
strict?: boolean;
|
|
147
|
+
}): ProviderStrategy<T extends InteropZodType<infer U> ? U : never>;
|
|
148
|
+
declare function providerStrategy(responseFormat: JsonSchemaFormat | {
|
|
149
|
+
schema: JsonSchemaFormat;
|
|
150
|
+
strict?: boolean;
|
|
151
|
+
}): ProviderStrategy<Record<string, unknown>>;
|
|
91
152
|
/**
|
|
92
153
|
* Type representing a JSON Schema object format.
|
|
93
154
|
* This is a strict type that excludes ToolStrategy and ProviderStrategy instances.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"responses.d.ts","names":["InteropZodObject","InteropZodType","AIMessage","LanguageModelLike","FunctionDefinition","StructuredOutputParsingError","MultipleStructuredOutputsError","ResponseFormatUndefined","ToolStrategy","S","_T","Record","ToolStrategyOptions","U","ProviderStrategy","T","ResponseFormat","transformResponseFormat","JsonSchemaFormat","TypedToolStrategy","Array","ToolStrategyError","Promise","toolStrategy","K","providerStrategy","hasSupportForJsonSchemaOutput"],"sources":["../../src/agents/responses.d.ts"],"sourcesContent":["import { InteropZodObject, InteropZodType } from \"@langchain/core/utils/types\";\nimport { type AIMessage } from \"@langchain/core/messages\";\nimport { type LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { type FunctionDefinition } from \"@langchain/core/language_models/base\";\nimport { StructuredOutputParsingError, MultipleStructuredOutputsError } from \"./errors.js\";\n/**\n * Special type to indicate that no response format is provided.\n * When this type is used, the structuredResponse property should not be present in the result.\n */\nexport type ResponseFormatUndefined = {\n __responseFormatUndefined: true;\n};\n/**\n * Information for tracking structured output tool metadata.\n * This contains all necessary information to handle structured responses generated\n * via tool calls, including the original schema, its type classification, and the\n * corresponding tool implementation used by the tools strategy.\n */\nexport declare class ToolStrategy<_T = unknown> {\n readonly schema: Record<string, unknown>;\n readonly tool: {\n type: \"function\";\n function: FunctionDefinition;\n };\n readonly options?: ToolStrategyOptions | undefined;\n private constructor();\n get name(): string;\n static fromSchema<S extends InteropZodObject>(schema: S, outputOptions?: ToolStrategyOptions): ToolStrategy<S extends InteropZodType<infer U> ? U : unknown>;\n static fromSchema(schema: Record<string, unknown>, outputOptions?: ToolStrategyOptions): ToolStrategy<Record<string, unknown>>;\n /**\n * Parse tool arguments according to the schema.\n *\n * @throws {StructuredOutputParsingError} if the response is not valid\n * @param toolArgs - The arguments from the tool call\n * @returns The parsed response according to the schema type\n */\n parse(toolArgs: Record<string, unknown>): Record<string, unknown>;\n}\nexport declare class ProviderStrategy<T = unknown> {\n readonly schema: Record<string, unknown>;\n private _schemaType?;\n private constructor();\n static fromSchema<T>(schema: InteropZodType<T>): ProviderStrategy<T>;\n static fromSchema(schema: Record<string, unknown>): ProviderStrategy<Record<string, unknown>>;\n /**\n * Parse tool arguments according to the schema. If the response is not valid, return undefined.\n *\n * @param toolArgs - The arguments from the tool call\n * @returns The parsed response according to the schema type\n */\n parse(response: AIMessage): any;\n}\nexport type ResponseFormat = ToolStrategy<any> | ProviderStrategy<any>;\n/**\n * Handle user input for `responseFormat` parameter of `CreateAgentParams`.\n * This function defines the default behavior for the `responseFormat` parameter, which is:\n *\n * - if value is a Zod schema, default to structured output via tool calling\n * - if value is a JSON schema, default to structured output via tool calling\n * - if value is a custom response format, return it as is\n * - if value is an array, ensure all array elements are instance of `ToolStrategy`\n * @param responseFormat - The response format to transform, provided by the user\n * @param options - The response format options for tool strategy\n * @param model - The model to check if it supports JSON schema output\n * @returns\n */\nexport declare function transformResponseFormat(responseFormat?: InteropZodType<any> | InteropZodType<any>[] | JsonSchemaFormat | JsonSchemaFormat[] | ResponseFormat | ToolStrategy<any>[] | ResponseFormatUndefined, options?: ToolStrategyOptions, model?: LanguageModelLike | string): ResponseFormat[];\n/**\n * Branded type for ToolStrategy arrays that preserves type information\n */\nexport interface TypedToolStrategy<T = unknown> extends Array<ToolStrategy<any>> {\n _schemaType?: T;\n}\nexport type ToolStrategyError = StructuredOutputParsingError | MultipleStructuredOutputsError;\nexport interface ToolStrategyOptions {\n /**\n * Allows you to customize the message that appears in the conversation history when structured\n * output is generated.\n */\n toolMessageContent?: string;\n /**\n * Handle errors from the structured output tool call. Using tools to generate structured output\n * can cause errors, e.g. if:\n * - you provide multiple structured output schemas and the model calls multiple structured output tools\n * - if the structured output generated by the tool call doesn't match provided schema\n *\n * This property allows to handle these errors in different ways:\n * - `true` - retry the tool call\n * - `false` - throw an error\n * - `string` - retry the tool call with the provided message\n * - `(error: ToolStrategyError) => Promise<string> | string` - retry with the provided message or throw the error\n *\n * @default true\n */\n handleError?: boolean | string | ((error: ToolStrategyError) => Promise<string> | string);\n}\nexport declare function toolStrategy<T extends InteropZodType<any>>(responseFormat: T, options?: ToolStrategyOptions): TypedToolStrategy<T extends InteropZodType<infer U> ? U : never>;\nexport declare function toolStrategy<T extends readonly InteropZodType<any>[]>(responseFormat: T, options?: ToolStrategyOptions): TypedToolStrategy<{\n [K in keyof T]: T[K] extends InteropZodType<infer U> ? U : never;\n}[number]>;\nexport declare function toolStrategy(responseFormat: JsonSchemaFormat, options?: ToolStrategyOptions): TypedToolStrategy<Record<string, unknown>>;\nexport declare function toolStrategy(responseFormat: JsonSchemaFormat[], options?: ToolStrategyOptions): TypedToolStrategy<Record<string, unknown>>;\nexport declare function providerStrategy<T extends InteropZodType<any>>(responseFormat: T): ProviderStrategy<T extends InteropZodType<infer U> ? U : never>;\nexport declare function providerStrategy(responseFormat: JsonSchemaFormat): ProviderStrategy<Record<string, unknown>>;\n/**\n * Type representing a JSON Schema object format.\n * This is a strict type that excludes ToolStrategy and ProviderStrategy instances.\n */\nexport type JsonSchemaFormat = {\n type: \"null\" | \"boolean\" | \"object\" | \"array\" | \"number\" | \"string\" | \"integer\";\n properties?: Record<string, unknown>;\n required?: string[];\n additionalProperties?: boolean;\n [key: string]: unknown;\n} & {\n __brand?: never;\n};\n/**\n * Identifies the models that support JSON schema output\n * @param model - The model to check\n * @returns True if the model supports JSON schema output, false otherwise\n */\nexport declare function hasSupportForJsonSchemaOutput(model?: LanguageModelLike | string): boolean;\n//# sourceMappingURL=responses.d.ts.map"],"mappings":";;;;;;;;AASA;AASA;;AAIkBI,KAbNG,uBAAAA,GAaMH;EAEKQ,yBAAAA,EAAAA,IAAAA;CAGSZ;;;;;;;AACFW,cAVTH,YAUSG,CAAAA,KAAAA,OAAAA,CAAAA,CAAAA;EAAyCC,SAAAA,MAAAA,EATlDD,MASkDC,CAAAA,MAAAA,EAAAA,OAAAA,CAAAA;EAAmCD,SAAAA,IAAAA,EAAAA;IAAbH,IAAAA,EAAAA,UAAAA;IAQzEG,QAAAA,EAdFP,kBAcEO;EAA0BA,CAAAA;EAAM,SAAA,OAAA,CAAA,EAZ7BC,mBAY6B,GAAA,SAAA;EAE/BE,QAAAA,WAAgB,CAAA;EAChBH,IAAAA,IAAAA,CAAAA,CAAAA,EAAAA,MAAAA;EAG2BI,OAAAA,UAAAA,CAAAA,UAfhBf,gBAegBe,CAAAA,CAAAA,MAAAA,EAfUN,CAeVM,EAAAA,aAAAA,CAAAA,EAf6BH,mBAe7BG,CAAAA,EAfmDP,YAenDO,CAfgEN,CAehEM,SAf0Ed,cAe1Ec,CAAAA,KAAAA,EAAAA,CAAAA,GAfoGF,CAepGE,GAAAA,OAAAA,CAAAA;EAAfd,OAAAA,UAAAA,CAAAA,MAAAA,EAdHU,MAcGV,CAAAA,MAAAA,EAAAA,OAAAA,CAAAA,EAAAA,aAAAA,CAAAA,EAdsCW,mBActCX,CAAAA,EAd4DO,YAc5DP,CAdyEU,MAczEV,CAAAA,MAAAA,EAAAA,OAAAA,CAAAA,CAAAA;EAAqCc;;;;;;AAQzC;EAEjBC,KAAAA,CAAAA,QAAAA,EAhBQL,MAgBM,CAAA,MAAA,EAAGH,OAAAA,CAAAA,CAAAA,EAhBiBG,MAgBGG,CAAAA,MAAAA,EAAAA,OAAgB,CAAA;AAkBjE;AAA8DN,cAhCzCM,gBAgCyCN,C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,iBAA6BL,4BAA4BN,sBAAsBO,kBAAkBR;iBACjGY,YAAAA,iBAA6BL,8BAA8BN,sBAAsBO,kBAAkBR;iBACnGc,2BAA2BxB,qCAAqCc,IAAID,iBAAiBC,UAAUd,0BAA0BY;iBACzHY,gBAAAA,iBAAiCP,mBAAmBJ,iBAAiBH;;;;;KAKjFO,gBAAAA;;eAEKP"}
|
|
1
|
+
{"version":3,"file":"responses.d.ts","names":["InteropZodObject","InteropZodType","AIMessage","LanguageModelLike","FunctionDefinition","StructuredOutputParsingError","MultipleStructuredOutputsError","ResponseFormatUndefined","ToolStrategy","S","_T","Record","ToolStrategyOptions","U","ProviderStrategy","T","ResponseFormat","transformResponseFormat","JsonSchemaFormat","TypedToolStrategy","Array","ToolStrategyError","Promise","toolStrategy","K","providerStrategy","hasSupportForJsonSchemaOutput"],"sources":["../../src/agents/responses.d.ts"],"sourcesContent":["import { InteropZodObject, InteropZodType } from \"@langchain/core/utils/types\";\nimport { type AIMessage } from \"@langchain/core/messages\";\nimport { type LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { type FunctionDefinition } from \"@langchain/core/language_models/base\";\nimport { StructuredOutputParsingError, MultipleStructuredOutputsError } from \"./errors.js\";\n/**\n * Special type to indicate that no response format is provided.\n * When this type is used, the structuredResponse property should not be present in the result.\n */\nexport type ResponseFormatUndefined = {\n __responseFormatUndefined: true;\n};\n/**\n * Information for tracking structured output tool metadata.\n * This contains all necessary information to handle structured responses generated\n * via tool calls, including the original schema, its type classification, and the\n * corresponding tool implementation used by the tools strategy.\n */\nexport declare class ToolStrategy<_T = unknown> {\n readonly schema: Record<string, unknown>;\n readonly tool: {\n type: \"function\";\n function: FunctionDefinition;\n };\n readonly options?: ToolStrategyOptions | undefined;\n private constructor();\n get name(): string;\n static fromSchema<S extends InteropZodObject>(schema: S, outputOptions?: ToolStrategyOptions): ToolStrategy<S extends InteropZodType<infer U> ? U : unknown>;\n static fromSchema(schema: Record<string, unknown>, outputOptions?: ToolStrategyOptions): ToolStrategy<Record<string, unknown>>;\n /**\n * Parse tool arguments according to the schema.\n *\n * @throws {StructuredOutputParsingError} if the response is not valid\n * @param toolArgs - The arguments from the tool call\n * @returns The parsed response according to the schema type\n */\n parse(toolArgs: Record<string, unknown>): Record<string, unknown>;\n}\nexport declare class ProviderStrategy<T = unknown> {\n private _schemaType?;\n /**\n * The schema to use for the provider strategy\n */\n readonly schema: Record<string, unknown>;\n /**\n * Whether to use strict mode for the provider strategy\n */\n readonly strict: boolean;\n private constructor();\n private constructor();\n static fromSchema<T>(schema: InteropZodType<T>, strict?: boolean): ProviderStrategy<T>;\n static fromSchema(schema: Record<string, unknown>, strict?: boolean): ProviderStrategy<Record<string, unknown>>;\n /**\n * Parse tool arguments according to the schema. If the response is not valid, return undefined.\n *\n * @param response - The AI message response to parse\n * @returns The parsed response according to the schema type\n */\n parse(response: AIMessage): any;\n}\nexport type ResponseFormat = ToolStrategy<any> | ProviderStrategy<any>;\n/**\n * Handle user input for `responseFormat` parameter of `CreateAgentParams`.\n * This function defines the default behavior for the `responseFormat` parameter, which is:\n *\n * - if value is a Zod schema, default to structured output via tool calling\n * - if value is a JSON schema, default to structured output via tool calling\n * - if value is a custom response format, return it as is\n * - if value is an array, ensure all array elements are instance of `ToolStrategy`\n * @param responseFormat - The response format to transform, provided by the user\n * @param options - The response format options for tool strategy\n * @param model - The model to check if it supports JSON schema output\n * @returns\n */\nexport declare function transformResponseFormat(responseFormat?: InteropZodType<any> | InteropZodType<any>[] | JsonSchemaFormat | JsonSchemaFormat[] | ResponseFormat | ToolStrategy<any>[] | ResponseFormatUndefined, options?: ToolStrategyOptions, model?: LanguageModelLike | string): ResponseFormat[];\n/**\n * Branded type for ToolStrategy arrays that preserves type information\n */\nexport interface TypedToolStrategy<T = unknown> extends Array<ToolStrategy<any>> {\n _schemaType?: T;\n}\nexport type ToolStrategyError = StructuredOutputParsingError | MultipleStructuredOutputsError;\nexport interface ToolStrategyOptions {\n /**\n * Allows you to customize the message that appears in the conversation history when structured\n * output is generated.\n */\n toolMessageContent?: string;\n /**\n * Handle errors from the structured output tool call. Using tools to generate structured output\n * can cause errors, e.g. if:\n * - you provide multiple structured output schemas and the model calls multiple structured output tools\n * - if the structured output generated by the tool call doesn't match provided schema\n *\n * This property allows to handle these errors in different ways:\n * - `true` - retry the tool call\n * - `false` - throw an error\n * - `string` - retry the tool call with the provided message\n * - `(error: ToolStrategyError) => Promise<string> | string` - retry with the provided message or throw the error\n *\n * @default true\n */\n handleError?: boolean | string | ((error: ToolStrategyError) => Promise<string> | string);\n}\nexport declare function toolStrategy<T extends InteropZodType<any>>(responseFormat: T, options?: ToolStrategyOptions): TypedToolStrategy<T extends InteropZodType<infer U> ? U : never>;\nexport declare function toolStrategy<T extends readonly InteropZodType<any>[]>(responseFormat: T, options?: ToolStrategyOptions): TypedToolStrategy<{\n [K in keyof T]: T[K] extends InteropZodType<infer U> ? U : never;\n}[number]>;\nexport declare function toolStrategy(responseFormat: JsonSchemaFormat, options?: ToolStrategyOptions): TypedToolStrategy<Record<string, unknown>>;\nexport declare function toolStrategy(responseFormat: JsonSchemaFormat[], options?: ToolStrategyOptions): TypedToolStrategy<Record<string, unknown>>;\n/**\n * Creates a provider strategy for structured output using native JSON schema support.\n *\n * This function is used to configure structured output for agents when the underlying model\n * supports native JSON schema output (e.g., OpenAI's `gpt-4o`, `gpt-4o-mini`, and newer models).\n * Unlike `toolStrategy`, which uses function calling to extract structured output, `providerStrategy`\n * leverages the provider's native structured output capabilities, resulting in more efficient\n * and reliable schema enforcement.\n *\n * When used with a model that supports JSON schema output, the model will return responses\n * that directly conform to the provided schema without requiring tool calls. This is the\n * recommended approach for structured output when your model supports it.\n *\n * @param responseFormat - The schema to enforce, either a Zod schema, a JSON schema object, or an options object with `schema` and optional `strict` flag\n * @returns A `ProviderStrategy` instance that can be used as the `responseFormat` in `createAgent`\n *\n * @example\n * ```ts\n * import { providerStrategy, createAgent } from \"langchain\";\n * import { z } from \"zod\";\n *\n * const agent = createAgent({\n * model: \"claude-haiku-4-5\",\n * responseFormat: providerStrategy(\n * z.object({\n * answer: z.string().describe(\"The answer to the question\"),\n * confidence: z.number().min(0).max(1),\n * })\n * ),\n * });\n * ```\n *\n * @example\n * ```ts\n * // Using strict mode for stricter schema enforcement\n * const agent = createAgent({\n * model: \"claude-haiku-4-5\",\n * responseFormat: providerStrategy({\n * schema: z.object({\n * name: z.string(),\n * age: z.number(),\n * }),\n * strict: true\n * }),\n * });\n * ```\n */\nexport declare function providerStrategy<T extends InteropZodType<unknown>>(responseFormat: T | {\n schema: T;\n strict?: boolean;\n}): ProviderStrategy<T extends InteropZodType<infer U> ? U : never>;\nexport declare function providerStrategy(responseFormat: JsonSchemaFormat | {\n schema: JsonSchemaFormat;\n strict?: boolean;\n}): ProviderStrategy<Record<string, unknown>>;\n/**\n * Type representing a JSON Schema object format.\n * This is a strict type that excludes ToolStrategy and ProviderStrategy instances.\n */\nexport type JsonSchemaFormat = {\n type: \"null\" | \"boolean\" | \"object\" | \"array\" | \"number\" | \"string\" | \"integer\";\n properties?: Record<string, unknown>;\n required?: string[];\n additionalProperties?: boolean;\n [key: string]: unknown;\n} & {\n __brand?: never;\n};\n/**\n * Identifies the models that support JSON schema output\n * @param model - The model to check\n * @returns True if the model supports JSON schema output, false otherwise\n */\nexport declare function hasSupportForJsonSchemaOutput(model?: LanguageModelLike | string): boolean;\n//# sourceMappingURL=responses.d.ts.map"],"mappings":";;;;;;;;AASA;AASA;;AAIkBI,KAbNG,uBAAAA,GAaMH;EAEKQ,yBAAAA,EAAAA,IAAAA;CAGSZ;;;;;;;AACFW,cAVTH,YAUSG,CAAAA,KAAAA,OAAAA,CAAAA,CAAAA;EAAyCC,SAAAA,MAAAA,EATlDD,MASkDC,CAAAA,MAAAA,EAAAA,OAAAA,CAAAA;EAAmCD,SAAAA,IAAAA,EAAAA;IAAbH,IAAAA,EAAAA,UAAAA;IAQzEG,QAAAA,EAdFP,kBAcEO;EAA0BA,CAAAA;EAAM,SAAA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AAUd,0BAA0BY;iBACjCY,gBAAAA,iBAAiCP;UAC7CA;;IAERJ,iBAAiBH;;;;;KAKTO,gBAAAA;;eAEKP"}
|
package/dist/agents/responses.js
CHANGED
|
@@ -74,26 +74,54 @@ var ToolStrategy = class ToolStrategy {
|
|
|
74
74
|
};
|
|
75
75
|
var ProviderStrategy = class ProviderStrategy {
|
|
76
76
|
_schemaType;
|
|
77
|
-
|
|
78
|
-
|
|
77
|
+
/**
|
|
78
|
+
* The schema to use for the provider strategy
|
|
79
|
+
*/
|
|
80
|
+
schema;
|
|
81
|
+
/**
|
|
82
|
+
* Whether to use strict mode for the provider strategy
|
|
83
|
+
*/
|
|
84
|
+
strict;
|
|
85
|
+
constructor(schemaOrOptions, strict) {
|
|
86
|
+
if ("schema" in schemaOrOptions && typeof schemaOrOptions.schema === "object" && schemaOrOptions.schema !== null && !("type" in schemaOrOptions)) {
|
|
87
|
+
const options = schemaOrOptions;
|
|
88
|
+
this.schema = options.schema;
|
|
89
|
+
this.strict = options.strict ?? false;
|
|
90
|
+
} else {
|
|
91
|
+
this.schema = schemaOrOptions;
|
|
92
|
+
this.strict = strict ?? false;
|
|
93
|
+
}
|
|
79
94
|
}
|
|
80
|
-
static fromSchema(schema) {
|
|
95
|
+
static fromSchema(schema, strict = false) {
|
|
81
96
|
const asJsonSchema = toJsonSchema(schema);
|
|
82
|
-
return new ProviderStrategy(asJsonSchema);
|
|
97
|
+
return new ProviderStrategy(asJsonSchema, strict);
|
|
83
98
|
}
|
|
84
99
|
/**
|
|
85
100
|
* Parse tool arguments according to the schema. If the response is not valid, return undefined.
|
|
86
101
|
*
|
|
87
|
-
* @param
|
|
102
|
+
* @param response - The AI message response to parse
|
|
88
103
|
* @returns The parsed response according to the schema type
|
|
89
104
|
*/
|
|
90
105
|
parse(response) {
|
|
91
106
|
/**
|
|
92
|
-
*
|
|
107
|
+
* Extract text content from the response.
|
|
108
|
+
* Handles both string content and array content (e.g., from thinking models).
|
|
93
109
|
*/
|
|
94
|
-
|
|
110
|
+
let textContent;
|
|
111
|
+
if (typeof response.content === "string") textContent = response.content;
|
|
112
|
+
else if (Array.isArray(response.content)) {
|
|
113
|
+
/**
|
|
114
|
+
* For thinking models, content is an array with thinking blocks and text blocks.
|
|
115
|
+
* Extract the text from text blocks.
|
|
116
|
+
*/
|
|
117
|
+
for (const block of response.content) if (typeof block === "object" && block !== null && "type" in block && block.type === "text" && "text" in block && typeof block.text === "string") {
|
|
118
|
+
textContent = block.text;
|
|
119
|
+
break;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
if (!textContent || textContent === "") return;
|
|
95
123
|
try {
|
|
96
|
-
const content = JSON.parse(
|
|
124
|
+
const content = JSON.parse(textContent);
|
|
97
125
|
const validator = new Validator(this.schema);
|
|
98
126
|
const result = validator.validate(content);
|
|
99
127
|
if (!result.valid) return;
|
|
@@ -149,18 +177,70 @@ function transformResponseFormat(responseFormat, options, model) {
|
|
|
149
177
|
throw new Error(`Invalid response format: ${String(responseFormat)}`);
|
|
150
178
|
}
|
|
151
179
|
/**
|
|
152
|
-
*
|
|
180
|
+
* Creates a tool strategy for structured output using function calling.
|
|
181
|
+
*
|
|
182
|
+
* This function configures structured output by converting schemas into function tools that
|
|
183
|
+
* the model calls. Unlike `providerStrategy`, which uses native JSON schema support,
|
|
184
|
+
* `toolStrategy` works with any model that supports function calling, making it more
|
|
185
|
+
* widely compatible across providers and model versions.
|
|
153
186
|
*
|
|
154
|
-
*
|
|
155
|
-
*
|
|
156
|
-
*
|
|
157
|
-
*
|
|
187
|
+
* The model will call a function with arguments matching your schema, and the agent will
|
|
188
|
+
* extract and validate the structured output from the tool call. This approach is automatically
|
|
189
|
+
* used when your model doesn't support native JSON schema output.
|
|
190
|
+
*
|
|
191
|
+
* @param responseFormat - The schema(s) to enforce. Can be a single Zod schema, an array of Zod schemas,
|
|
192
|
+
* a JSON schema object, or an array of JSON schema objects.
|
|
193
|
+
* @param options - Optional configuration for the tool strategy
|
|
194
|
+
* @param options.handleError - How to handle errors when the model calls multiple structured output tools
|
|
195
|
+
* or when the output doesn't match the schema. Defaults to `true` (auto-retry). Can be `false` (throw),
|
|
196
|
+
* a `string` (retry with message), or a `function` (custom handler).
|
|
197
|
+
* @param options.toolMessageContent - Custom message content to include in conversation history
|
|
198
|
+
* when structured output is generated via tool call
|
|
199
|
+
* @returns A `TypedToolStrategy` instance that can be used as the `responseFormat` in `createAgent`
|
|
200
|
+
*
|
|
201
|
+
* @example
|
|
202
|
+
* ```ts
|
|
203
|
+
* import { toolStrategy, createAgent } from "langchain";
|
|
204
|
+
* import { z } from "zod";
|
|
205
|
+
*
|
|
206
|
+
* const agent = createAgent({
|
|
207
|
+
* model: "claude-haiku-4-5",
|
|
208
|
+
* responseFormat: toolStrategy(
|
|
209
|
+
* z.object({
|
|
210
|
+
* answer: z.string(),
|
|
211
|
+
* confidence: z.number().min(0).max(1),
|
|
212
|
+
* })
|
|
213
|
+
* ),
|
|
214
|
+
* });
|
|
215
|
+
* ```
|
|
216
|
+
*
|
|
217
|
+
* @example
|
|
218
|
+
* ```ts
|
|
219
|
+
* // Multiple schemas - model can choose which one to use
|
|
220
|
+
* const agent = createAgent({
|
|
221
|
+
* model: "claude-haiku-4-5",
|
|
222
|
+
* responseFormat: toolStrategy([
|
|
223
|
+
* z.object({ name: z.string(), age: z.number() }),
|
|
224
|
+
* z.object({ email: z.string(), phone: z.string() }),
|
|
225
|
+
* ]),
|
|
226
|
+
* });
|
|
227
|
+
* ```
|
|
158
228
|
*/
|
|
159
229
|
function toolStrategy(responseFormat, options) {
|
|
160
230
|
return transformResponseFormat(responseFormat, options);
|
|
161
231
|
}
|
|
162
232
|
function providerStrategy(responseFormat) {
|
|
163
|
-
|
|
233
|
+
/**
|
|
234
|
+
* Handle options object format
|
|
235
|
+
*/
|
|
236
|
+
if (typeof responseFormat === "object" && responseFormat !== null && "schema" in responseFormat && !isInteropZodSchema(responseFormat) && !("type" in responseFormat)) {
|
|
237
|
+
const { schema, strict: strictFlag } = responseFormat;
|
|
238
|
+
return ProviderStrategy.fromSchema(schema, strictFlag ?? false);
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* Handle direct schema format
|
|
242
|
+
*/
|
|
243
|
+
return ProviderStrategy.fromSchema(responseFormat, false);
|
|
164
244
|
}
|
|
165
245
|
const CHAT_MODELS_THAT_SUPPORT_JSON_SCHEMA_OUTPUT = ["ChatOpenAI", "ChatXAI"];
|
|
166
246
|
const MODEL_NAMES_THAT_SUPPORT_JSON_SCHEMA_OUTPUT = [
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"responses.js","names":["schema: Record<string, unknown>","tool: {\n type: \"function\";\n function: FunctionDefinition;\n }","options?: ToolStrategyOptions","schema: InteropZodObject | Record<string, unknown>","outputOptions?: ToolStrategyOptions","name?: string","asJsonSchema","tool","functionDefinition: FunctionDefinition","toolArgs: Record<string, unknown>","schema: InteropZodType<T> | Record<string, unknown>","response: AIMessage","responseFormat?:\n | InteropZodType<any>\n | InteropZodType<any>[]\n | JsonSchemaFormat\n | JsonSchemaFormat[]\n | ResponseFormat\n | ToolStrategy<any>[]\n | ResponseFormatUndefined","model?: LanguageModelLike | string","responseFormat:\n | InteropZodType<any>\n | InteropZodType<any>[]\n | JsonSchemaFormat\n | JsonSchemaFormat[]","responseFormat: InteropZodType<any> | JsonSchemaFormat"],"sources":["../../src/agents/responses.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable no-instanceof/no-instanceof */\nimport {\n InteropZodObject,\n isInteropZodSchema,\n InteropZodType,\n isInteropZodObject,\n} from \"@langchain/core/utils/types\";\nimport { type AIMessage } from \"@langchain/core/messages\";\nimport { type LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { toJsonSchema, Validator } from \"@langchain/core/utils/json_schema\";\nimport { type FunctionDefinition } from \"@langchain/core/language_models/base\";\n\nimport {\n StructuredOutputParsingError,\n MultipleStructuredOutputsError,\n} from \"./errors.js\";\nimport { isConfigurableModel, isBaseChatModel } from \"./model.js\";\n\n/**\n * Special type to indicate that no response format is provided.\n * When this type is used, the structuredResponse property should not be present in the result.\n */\nexport type ResponseFormatUndefined = {\n __responseFormatUndefined: true;\n};\n\n/**\n * This is a global counter for generating unique names for tools.\n */\nlet bindingIdentifier = 0;\n\n/**\n * Information for tracking structured output tool metadata.\n * This contains all necessary information to handle structured responses generated\n * via tool calls, including the original schema, its type classification, and the\n * corresponding tool implementation used by the tools strategy.\n */\nexport class ToolStrategy<_T = unknown> {\n private constructor(\n /**\n * The original JSON Schema provided for structured output\n */\n public readonly schema: Record<string, unknown>,\n\n /**\n * The tool that will be used to parse the tool call arguments.\n */\n public readonly tool: {\n type: \"function\";\n function: FunctionDefinition;\n },\n\n /**\n * The options to use for the tool output.\n */\n public readonly options?: ToolStrategyOptions\n ) {}\n\n get name() {\n return this.tool.function.name;\n }\n\n static fromSchema<S extends InteropZodObject>(\n schema: S,\n outputOptions?: ToolStrategyOptions\n ): ToolStrategy<S extends InteropZodType<infer U> ? U : unknown>;\n\n static fromSchema(\n schema: Record<string, unknown>,\n outputOptions?: ToolStrategyOptions\n ): ToolStrategy<Record<string, unknown>>;\n\n static fromSchema(\n schema: InteropZodObject | Record<string, unknown>,\n outputOptions?: ToolStrategyOptions\n ): ToolStrategy<any> {\n /**\n * It is required for tools to have a name so we can map the tool call to the correct tool\n * when parsing the response.\n */\n function getFunctionName(name?: string) {\n return name ?? `extract-${++bindingIdentifier}`;\n }\n\n if (isInteropZodSchema(schema)) {\n const asJsonSchema = toJsonSchema(schema);\n const tool = {\n type: \"function\" as const,\n function: {\n name: getFunctionName(),\n strict: false,\n description:\n asJsonSchema.description ??\n \"Tool for extracting structured output from the model's response.\",\n parameters: asJsonSchema,\n },\n };\n return new ToolStrategy(asJsonSchema, tool, outputOptions);\n }\n\n let functionDefinition: FunctionDefinition;\n if (\n typeof schema.name === \"string\" &&\n typeof schema.parameters === \"object\" &&\n schema.parameters != null\n ) {\n functionDefinition = schema as unknown as FunctionDefinition;\n } else {\n functionDefinition = {\n name: getFunctionName(schema.title as string),\n description: (schema.description as string) ?? \"\",\n parameters: schema.schema || (schema as Record<string, unknown>),\n };\n }\n const asJsonSchema = toJsonSchema(schema);\n const tool = {\n type: \"function\" as const,\n function: functionDefinition,\n };\n return new ToolStrategy(asJsonSchema, tool, outputOptions);\n }\n\n /**\n * Parse tool arguments according to the schema.\n *\n * @throws {StructuredOutputParsingError} if the response is not valid\n * @param toolArgs - The arguments from the tool call\n * @returns The parsed response according to the schema type\n */\n parse(toolArgs: Record<string, unknown>): Record<string, unknown> {\n const validator = new Validator(this.schema);\n const result = validator.validate(toolArgs);\n if (!result.valid) {\n throw new StructuredOutputParsingError(\n this.name,\n result.errors.map((e) => e.error)\n );\n }\n return toolArgs;\n }\n}\n\nexport class ProviderStrategy<T = unknown> {\n // @ts-expect-error - _schemaType is used only for type inference\n private _schemaType?: T;\n\n private constructor(public readonly schema: Record<string, unknown>) {}\n\n static fromSchema<T>(schema: InteropZodType<T>): ProviderStrategy<T>;\n\n static fromSchema(\n schema: Record<string, unknown>\n ): ProviderStrategy<Record<string, unknown>>;\n\n static fromSchema<T = unknown>(\n schema: InteropZodType<T> | Record<string, unknown>\n ): ProviderStrategy<T> | ProviderStrategy<Record<string, unknown>> {\n const asJsonSchema = toJsonSchema(schema);\n return new ProviderStrategy(asJsonSchema) as\n | ProviderStrategy<T>\n | ProviderStrategy<Record<string, unknown>>;\n }\n\n /**\n * Parse tool arguments according to the schema. If the response is not valid, return undefined.\n *\n * @param toolArgs - The arguments from the tool call\n * @returns The parsed response according to the schema type\n */\n parse(response: AIMessage) {\n /**\n * return if the response doesn't contain valid content\n */\n if (typeof response.content !== \"string\" || response.content === \"\") {\n return;\n }\n\n try {\n const content = JSON.parse(response.content);\n const validator = new Validator(this.schema);\n const result = validator.validate(content);\n if (!result.valid) {\n return;\n }\n\n return content;\n } catch {\n // no-op\n }\n }\n}\n\nexport type ResponseFormat = ToolStrategy<any> | ProviderStrategy<any>;\n\n/**\n * Handle user input for `responseFormat` parameter of `CreateAgentParams`.\n * This function defines the default behavior for the `responseFormat` parameter, which is:\n *\n * - if value is a Zod schema, default to structured output via tool calling\n * - if value is a JSON schema, default to structured output via tool calling\n * - if value is a custom response format, return it as is\n * - if value is an array, ensure all array elements are instance of `ToolStrategy`\n * @param responseFormat - The response format to transform, provided by the user\n * @param options - The response format options for tool strategy\n * @param model - The model to check if it supports JSON schema output\n * @returns\n */\nexport function transformResponseFormat(\n responseFormat?:\n | InteropZodType<any>\n | InteropZodType<any>[]\n | JsonSchemaFormat\n | JsonSchemaFormat[]\n | ResponseFormat\n | ToolStrategy<any>[]\n | ResponseFormatUndefined,\n options?: ToolStrategyOptions,\n model?: LanguageModelLike | string\n): ResponseFormat[] {\n if (!responseFormat) {\n return [];\n }\n\n // Handle ResponseFormatUndefined case\n if (\n typeof responseFormat === \"object\" &&\n responseFormat !== null &&\n \"__responseFormatUndefined\" in responseFormat\n ) {\n return [];\n }\n\n /**\n * If users provide an array, it should only contain raw schemas (Zod or JSON schema),\n * not ToolStrategy or ProviderStrategy instances.\n */\n if (Array.isArray(responseFormat)) {\n /**\n * if every entry is a ToolStrategy or ProviderStrategy instance, return the array as is\n */\n if (\n responseFormat.every(\n (item) =>\n item instanceof ToolStrategy || item instanceof ProviderStrategy\n )\n ) {\n return responseFormat as unknown as ResponseFormat[];\n }\n\n /**\n * Check if all items are Zod schemas\n */\n if (responseFormat.every((item) => isInteropZodObject(item))) {\n return responseFormat.map((item) =>\n ToolStrategy.fromSchema(item as InteropZodObject, options)\n );\n }\n\n /**\n * Check if all items are plain objects (JSON schema)\n */\n if (\n responseFormat.every(\n (item) =>\n typeof item === \"object\" && item !== null && !isInteropZodObject(item)\n )\n ) {\n return responseFormat.map((item) =>\n ToolStrategy.fromSchema(item as JsonSchemaFormat, options)\n );\n }\n\n throw new Error(\n `Invalid response format: list contains mixed types.\\n` +\n `All items must be either InteropZodObject or plain JSON schema objects.`\n );\n }\n\n if (\n responseFormat instanceof ToolStrategy ||\n responseFormat instanceof ProviderStrategy\n ) {\n return [responseFormat];\n }\n\n const useProviderStrategy = hasSupportForJsonSchemaOutput(model);\n\n /**\n * `responseFormat` is a Zod schema\n */\n if (isInteropZodObject(responseFormat)) {\n return useProviderStrategy\n ? [ProviderStrategy.fromSchema(responseFormat)]\n : [ToolStrategy.fromSchema(responseFormat, options)];\n }\n\n /**\n * Handle plain object (JSON schema)\n */\n if (\n typeof responseFormat === \"object\" &&\n responseFormat !== null &&\n \"properties\" in responseFormat\n ) {\n return useProviderStrategy\n ? [ProviderStrategy.fromSchema(responseFormat as JsonSchemaFormat)]\n : [ToolStrategy.fromSchema(responseFormat as JsonSchemaFormat, options)];\n }\n\n throw new Error(`Invalid response format: ${String(responseFormat)}`);\n}\n\n/**\n * Branded type for ToolStrategy arrays that preserves type information\n */\nexport interface TypedToolStrategy<T = unknown>\n extends Array<ToolStrategy<any>> {\n _schemaType?: T;\n}\nexport type ToolStrategyError =\n | StructuredOutputParsingError\n | MultipleStructuredOutputsError;\nexport interface ToolStrategyOptions {\n /**\n * Allows you to customize the message that appears in the conversation history when structured\n * output is generated.\n */\n toolMessageContent?: string;\n /**\n * Handle errors from the structured output tool call. Using tools to generate structured output\n * can cause errors, e.g. if:\n * - you provide multiple structured output schemas and the model calls multiple structured output tools\n * - if the structured output generated by the tool call doesn't match provided schema\n *\n * This property allows to handle these errors in different ways:\n * - `true` - retry the tool call\n * - `false` - throw an error\n * - `string` - retry the tool call with the provided message\n * - `(error: ToolStrategyError) => Promise<string> | string` - retry with the provided message or throw the error\n *\n * @default true\n */\n handleError?:\n | boolean\n | string\n | ((error: ToolStrategyError) => Promise<string> | string);\n}\n\nexport function toolStrategy<T extends InteropZodType<any>>(\n responseFormat: T,\n options?: ToolStrategyOptions\n): TypedToolStrategy<T extends InteropZodType<infer U> ? U : never>;\nexport function toolStrategy<T extends readonly InteropZodType<any>[]>(\n responseFormat: T,\n options?: ToolStrategyOptions\n): TypedToolStrategy<\n { [K in keyof T]: T[K] extends InteropZodType<infer U> ? U : never }[number]\n>;\nexport function toolStrategy(\n responseFormat: JsonSchemaFormat,\n options?: ToolStrategyOptions\n): TypedToolStrategy<Record<string, unknown>>;\nexport function toolStrategy(\n responseFormat: JsonSchemaFormat[],\n options?: ToolStrategyOptions\n): TypedToolStrategy<Record<string, unknown>>;\n\n/**\n * Define how to transform the response format from a tool call.\n *\n * @param responseFormat - The response format to transform\n * @param options - The options to use for the transformation\n * @param options.handleError - Whether to handle errors from the tool call\n * @returns The transformed response format\n */\nexport function toolStrategy(\n responseFormat:\n | InteropZodType<any>\n | InteropZodType<any>[]\n | JsonSchemaFormat\n | JsonSchemaFormat[],\n options?: ToolStrategyOptions\n): TypedToolStrategy {\n return transformResponseFormat(responseFormat, options) as TypedToolStrategy;\n}\n\nexport function providerStrategy<T extends InteropZodType<any>>(\n responseFormat: T\n): ProviderStrategy<T extends InteropZodType<infer U> ? U : never>;\nexport function providerStrategy(\n responseFormat: JsonSchemaFormat\n): ProviderStrategy<Record<string, unknown>>;\nexport function providerStrategy(\n responseFormat: InteropZodType<any> | JsonSchemaFormat\n): ProviderStrategy<any> {\n return ProviderStrategy.fromSchema(\n responseFormat as any\n ) as ProviderStrategy<any>;\n}\n\n/**\n * Type representing a JSON Schema object format.\n * This is a strict type that excludes ToolStrategy and ProviderStrategy instances.\n */\nexport type JsonSchemaFormat = {\n type:\n | \"null\"\n | \"boolean\"\n | \"object\"\n | \"array\"\n | \"number\"\n | \"string\"\n | \"integer\";\n properties?: Record<string, unknown>;\n required?: string[];\n additionalProperties?: boolean;\n [key: string]: unknown;\n} & {\n // Brand to ensure this is not a ToolStrategy or ProviderStrategy\n __brand?: never;\n};\n\nconst CHAT_MODELS_THAT_SUPPORT_JSON_SCHEMA_OUTPUT = [\"ChatOpenAI\", \"ChatXAI\"];\nconst MODEL_NAMES_THAT_SUPPORT_JSON_SCHEMA_OUTPUT = [\n \"grok\",\n \"gpt-5\",\n \"gpt-4.1\",\n \"gpt-4o\",\n \"gpt-oss\",\n \"o3-pro\",\n \"o3-mini\",\n];\n\n/**\n * Identifies the models that support JSON schema output\n * @param model - The model to check\n * @returns True if the model supports JSON schema output, false otherwise\n */\nexport function hasSupportForJsonSchemaOutput(\n model?: LanguageModelLike | string\n): boolean {\n if (!model) {\n return false;\n }\n\n if (typeof model === \"string\") {\n const modelName = model.split(\":\").pop() as string;\n return MODEL_NAMES_THAT_SUPPORT_JSON_SCHEMA_OUTPUT.some(\n (modelNameSnippet) => modelName.includes(modelNameSnippet)\n );\n }\n\n if (isConfigurableModel(model)) {\n const configurableModel = model as unknown as {\n _defaultConfig: { model: string };\n };\n return hasSupportForJsonSchemaOutput(\n configurableModel._defaultConfig.model\n );\n }\n\n if (!isBaseChatModel(model)) {\n return false;\n }\n\n const chatModelClass = model.getName();\n\n /**\n * for testing purposes only\n */\n if (chatModelClass === \"FakeToolCallingChatModel\") {\n return true;\n }\n\n if (\n CHAT_MODELS_THAT_SUPPORT_JSON_SCHEMA_OUTPUT.includes(chatModelClass) &&\n /**\n * OpenAI models\n */ ((\"model\" in model &&\n MODEL_NAMES_THAT_SUPPORT_JSON_SCHEMA_OUTPUT.some(\n (modelNameSnippet) =>\n typeof model.model === \"string\" &&\n model.model.includes(modelNameSnippet)\n )) ||\n /**\n * for testing purposes only\n */\n (chatModelClass === \"FakeToolCallingModel\" &&\n \"structuredResponse\" in model))\n ) {\n return true;\n }\n\n return false;\n}\n"],"mappings":";;;;;;;;;AA8BA,IAAI,oBAAoB;;;;;;;AAQxB,IAAa,eAAb,MAAa,aAA2B;CACtC,AAAQ,YAIUA,QAKAC,MAQAC,SAChB;EAdgB;EAKA;EAQA;CACd;CAEJ,IAAI,OAAO;AACT,SAAO,KAAK,KAAK,SAAS;CAC3B;CAYD,OAAO,WACLC,QACAC,eACmB;;;;;EAKnB,SAAS,gBAAgBC,MAAe;AACtC,UAAO,QAAQ,CAAC,QAAQ,EAAE,EAAE,mB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AAwBD,MAAM,8CAA8C,CAAC,cAAc,SAAU;AAC7E,MAAM,8CAA8C;CAClD;CACA;CACA;CACA;CACA;CACA;CACA;AACD;;;;;;AAOD,SAAgB,8BACdF,OACS;AACT,KAAI,CAAC,MACH,QAAO;AAGT,KAAI,OAAO,UAAU,UAAU;EAC7B,MAAM,YAAY,MAAM,MAAM,IAAI,CAAC,KAAK;AACxC,SAAO,4CAA4C,KACjD,CAAC,qBAAqB,UAAU,SAAS,iBAAiB,CAC3D;CACF;AAED,KAAI,oBAAoB,MAAM,EAAE;EAC9B,MAAM,oBAAoB;AAG1B,SAAO,8BACL,kBAAkB,eAAe,MAClC;CACF;AAED,KAAI,CAAC,gBAAgB,MAAM,CACzB,QAAO;CAGT,MAAM,iBAAiB,MAAM,SAAS;;;;AAKtC,KAAI,mBAAmB,2BACrB,QAAO;AAGT,KACE,4CAA4C,SAAS,eAAe,KAG9D,WAAW,SACf,4CAA4C,KAC1C,CAAC,qBACC,OAAO,MAAM,UAAU,YACvB,MAAM,MAAM,SAAS,iBAAiB,CACzC,IAIA,mBAAmB,0BAClB,wBAAwB,OAE5B,QAAO;AAGT,QAAO;AACR"}
|
|
1
|
+
{"version":3,"file":"responses.js","names":["schema: Record<string, unknown>","tool: {\n type: \"function\";\n function: FunctionDefinition;\n }","options?: ToolStrategyOptions","schema: InteropZodObject | Record<string, unknown>","outputOptions?: ToolStrategyOptions","name?: string","asJsonSchema","tool","functionDefinition: FunctionDefinition","toolArgs: Record<string, unknown>","schemaOrOptions:\n | Record<string, unknown>\n | { schema: Record<string, unknown>; strict?: boolean }","strict?: boolean","schema: InteropZodType<T> | Record<string, unknown>","strict: boolean","response: AIMessage","textContent: string | undefined","responseFormat?:\n | InteropZodType<any>\n | InteropZodType<any>[]\n | JsonSchemaFormat\n | JsonSchemaFormat[]\n | ResponseFormat\n | ToolStrategy<any>[]\n | ResponseFormatUndefined","model?: LanguageModelLike | string","responseFormat:\n | InteropZodType<any>\n | InteropZodType<any>[]\n | JsonSchemaFormat\n | JsonSchemaFormat[]","responseFormat:\n | InteropZodType<unknown>\n | JsonSchemaFormat\n | { schema: InteropZodType<unknown> | JsonSchemaFormat; strict?: boolean }"],"sources":["../../src/agents/responses.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable no-instanceof/no-instanceof */\nimport {\n InteropZodObject,\n isInteropZodSchema,\n InteropZodType,\n isInteropZodObject,\n} from \"@langchain/core/utils/types\";\nimport { type AIMessage } from \"@langchain/core/messages\";\nimport { type LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { toJsonSchema, Validator } from \"@langchain/core/utils/json_schema\";\nimport { type FunctionDefinition } from \"@langchain/core/language_models/base\";\n\nimport {\n StructuredOutputParsingError,\n MultipleStructuredOutputsError,\n} from \"./errors.js\";\nimport { isConfigurableModel, isBaseChatModel } from \"./model.js\";\n\n/**\n * Special type to indicate that no response format is provided.\n * When this type is used, the structuredResponse property should not be present in the result.\n */\nexport type ResponseFormatUndefined = {\n __responseFormatUndefined: true;\n};\n\n/**\n * This is a global counter for generating unique names for tools.\n */\nlet bindingIdentifier = 0;\n\n/**\n * Information for tracking structured output tool metadata.\n * This contains all necessary information to handle structured responses generated\n * via tool calls, including the original schema, its type classification, and the\n * corresponding tool implementation used by the tools strategy.\n */\nexport class ToolStrategy<_T = unknown> {\n private constructor(\n /**\n * The original JSON Schema provided for structured output\n */\n public readonly schema: Record<string, unknown>,\n\n /**\n * The tool that will be used to parse the tool call arguments.\n */\n public readonly tool: {\n type: \"function\";\n function: FunctionDefinition;\n },\n\n /**\n * The options to use for the tool output.\n */\n public readonly options?: ToolStrategyOptions\n ) {}\n\n get name() {\n return this.tool.function.name;\n }\n\n static fromSchema<S extends InteropZodObject>(\n schema: S,\n outputOptions?: ToolStrategyOptions\n ): ToolStrategy<S extends InteropZodType<infer U> ? U : unknown>;\n\n static fromSchema(\n schema: Record<string, unknown>,\n outputOptions?: ToolStrategyOptions\n ): ToolStrategy<Record<string, unknown>>;\n\n static fromSchema(\n schema: InteropZodObject | Record<string, unknown>,\n outputOptions?: ToolStrategyOptions\n ): ToolStrategy<any> {\n /**\n * It is required for tools to have a name so we can map the tool call to the correct tool\n * when parsing the response.\n */\n function getFunctionName(name?: string) {\n return name ?? `extract-${++bindingIdentifier}`;\n }\n\n if (isInteropZodSchema(schema)) {\n const asJsonSchema = toJsonSchema(schema);\n const tool = {\n type: \"function\" as const,\n function: {\n name: getFunctionName(),\n strict: false,\n description:\n asJsonSchema.description ??\n \"Tool for extracting structured output from the model's response.\",\n parameters: asJsonSchema,\n },\n };\n return new ToolStrategy(asJsonSchema, tool, outputOptions);\n }\n\n let functionDefinition: FunctionDefinition;\n if (\n typeof schema.name === \"string\" &&\n typeof schema.parameters === \"object\" &&\n schema.parameters != null\n ) {\n functionDefinition = schema as unknown as FunctionDefinition;\n } else {\n functionDefinition = {\n name: getFunctionName(schema.title as string),\n description: (schema.description as string) ?? \"\",\n parameters: schema.schema || (schema as Record<string, unknown>),\n };\n }\n const asJsonSchema = toJsonSchema(schema);\n const tool = {\n type: \"function\" as const,\n function: functionDefinition,\n };\n return new ToolStrategy(asJsonSchema, tool, outputOptions);\n }\n\n /**\n * Parse tool arguments according to the schema.\n *\n * @throws {StructuredOutputParsingError} if the response is not valid\n * @param toolArgs - The arguments from the tool call\n * @returns The parsed response according to the schema type\n */\n parse(toolArgs: Record<string, unknown>): Record<string, unknown> {\n const validator = new Validator(this.schema);\n const result = validator.validate(toolArgs);\n if (!result.valid) {\n throw new StructuredOutputParsingError(\n this.name,\n result.errors.map((e) => e.error)\n );\n }\n return toolArgs;\n }\n}\n\nexport class ProviderStrategy<T = unknown> {\n // @ts-expect-error - _schemaType is used only for type inference\n private _schemaType?: T;\n\n /**\n * The schema to use for the provider strategy\n */\n public readonly schema: Record<string, unknown>;\n\n /**\n * Whether to use strict mode for the provider strategy\n */\n public readonly strict: boolean;\n\n private constructor(options: {\n schema: Record<string, unknown>;\n strict?: boolean;\n });\n private constructor(schema: Record<string, unknown>, strict?: boolean);\n private constructor(\n schemaOrOptions:\n | Record<string, unknown>\n | { schema: Record<string, unknown>; strict?: boolean },\n strict?: boolean\n ) {\n if (\n \"schema\" in schemaOrOptions &&\n typeof schemaOrOptions.schema === \"object\" &&\n schemaOrOptions.schema !== null &&\n !(\"type\" in schemaOrOptions)\n ) {\n const options = schemaOrOptions as {\n schema: Record<string, unknown>;\n strict?: boolean;\n };\n this.schema = options.schema;\n this.strict = options.strict ?? false;\n } else {\n this.schema = schemaOrOptions as Record<string, unknown>;\n this.strict = strict ?? false;\n }\n }\n\n static fromSchema<T>(\n schema: InteropZodType<T>,\n strict?: boolean\n ): ProviderStrategy<T>;\n\n static fromSchema(\n schema: Record<string, unknown>,\n strict?: boolean\n ): ProviderStrategy<Record<string, unknown>>;\n\n static fromSchema<T = unknown>(\n schema: InteropZodType<T> | Record<string, unknown>,\n strict: boolean = false\n ): ProviderStrategy<T> | ProviderStrategy<Record<string, unknown>> {\n const asJsonSchema = toJsonSchema(schema);\n return new ProviderStrategy(asJsonSchema, strict) as\n | ProviderStrategy<T>\n | ProviderStrategy<Record<string, unknown>>;\n }\n\n /**\n * Parse tool arguments according to the schema. If the response is not valid, return undefined.\n *\n * @param response - The AI message response to parse\n * @returns The parsed response according to the schema type\n */\n parse(response: AIMessage) {\n /**\n * Extract text content from the response.\n * Handles both string content and array content (e.g., from thinking models).\n */\n let textContent: string | undefined;\n\n if (typeof response.content === \"string\") {\n textContent = response.content;\n } else if (Array.isArray(response.content)) {\n /**\n * For thinking models, content is an array with thinking blocks and text blocks.\n * Extract the text from text blocks.\n */\n for (const block of response.content) {\n if (\n typeof block === \"object\" &&\n block !== null &&\n \"type\" in block &&\n block.type === \"text\" &&\n \"text\" in block &&\n typeof block.text === \"string\"\n ) {\n textContent = block.text;\n break; // Use the first text block found\n }\n }\n }\n\n // Return if no valid text content found\n if (!textContent || textContent === \"\") {\n return;\n }\n\n try {\n const content = JSON.parse(textContent);\n const validator = new Validator(this.schema);\n const result = validator.validate(content);\n if (!result.valid) {\n return;\n }\n\n return content;\n } catch {\n // no-op\n }\n }\n}\n\nexport type ResponseFormat = ToolStrategy<any> | ProviderStrategy<any>;\n\n/**\n * Handle user input for `responseFormat` parameter of `CreateAgentParams`.\n * This function defines the default behavior for the `responseFormat` parameter, which is:\n *\n * - if value is a Zod schema, default to structured output via tool calling\n * - if value is a JSON schema, default to structured output via tool calling\n * - if value is a custom response format, return it as is\n * - if value is an array, ensure all array elements are instance of `ToolStrategy`\n * @param responseFormat - The response format to transform, provided by the user\n * @param options - The response format options for tool strategy\n * @param model - The model to check if it supports JSON schema output\n * @returns\n */\nexport function transformResponseFormat(\n responseFormat?:\n | InteropZodType<any>\n | InteropZodType<any>[]\n | JsonSchemaFormat\n | JsonSchemaFormat[]\n | ResponseFormat\n | ToolStrategy<any>[]\n | ResponseFormatUndefined,\n options?: ToolStrategyOptions,\n model?: LanguageModelLike | string\n): ResponseFormat[] {\n if (!responseFormat) {\n return [];\n }\n\n // Handle ResponseFormatUndefined case\n if (\n typeof responseFormat === \"object\" &&\n responseFormat !== null &&\n \"__responseFormatUndefined\" in responseFormat\n ) {\n return [];\n }\n\n /**\n * If users provide an array, it should only contain raw schemas (Zod or JSON schema),\n * not ToolStrategy or ProviderStrategy instances.\n */\n if (Array.isArray(responseFormat)) {\n /**\n * if every entry is a ToolStrategy or ProviderStrategy instance, return the array as is\n */\n if (\n responseFormat.every(\n (item) =>\n item instanceof ToolStrategy || item instanceof ProviderStrategy\n )\n ) {\n return responseFormat as unknown as ResponseFormat[];\n }\n\n /**\n * Check if all items are Zod schemas\n */\n if (responseFormat.every((item) => isInteropZodObject(item))) {\n return responseFormat.map((item) =>\n ToolStrategy.fromSchema(item as InteropZodObject, options)\n );\n }\n\n /**\n * Check if all items are plain objects (JSON schema)\n */\n if (\n responseFormat.every(\n (item) =>\n typeof item === \"object\" && item !== null && !isInteropZodObject(item)\n )\n ) {\n return responseFormat.map((item) =>\n ToolStrategy.fromSchema(item as JsonSchemaFormat, options)\n );\n }\n\n throw new Error(\n `Invalid response format: list contains mixed types.\\n` +\n `All items must be either InteropZodObject or plain JSON schema objects.`\n );\n }\n\n if (\n responseFormat instanceof ToolStrategy ||\n responseFormat instanceof ProviderStrategy\n ) {\n return [responseFormat];\n }\n\n const useProviderStrategy = hasSupportForJsonSchemaOutput(model);\n\n /**\n * `responseFormat` is a Zod schema\n */\n if (isInteropZodObject(responseFormat)) {\n return useProviderStrategy\n ? [ProviderStrategy.fromSchema(responseFormat)]\n : [ToolStrategy.fromSchema(responseFormat, options)];\n }\n\n /**\n * Handle plain object (JSON schema)\n */\n if (\n typeof responseFormat === \"object\" &&\n responseFormat !== null &&\n \"properties\" in responseFormat\n ) {\n return useProviderStrategy\n ? [ProviderStrategy.fromSchema(responseFormat as JsonSchemaFormat)]\n : [ToolStrategy.fromSchema(responseFormat as JsonSchemaFormat, options)];\n }\n\n throw new Error(`Invalid response format: ${String(responseFormat)}`);\n}\n\n/**\n * Branded type for ToolStrategy arrays that preserves type information\n */\nexport interface TypedToolStrategy<T = unknown>\n extends Array<ToolStrategy<any>> {\n _schemaType?: T;\n}\nexport type ToolStrategyError =\n | StructuredOutputParsingError\n | MultipleStructuredOutputsError;\nexport interface ToolStrategyOptions {\n /**\n * Allows you to customize the message that appears in the conversation history when structured\n * output is generated.\n */\n toolMessageContent?: string;\n /**\n * Handle errors from the structured output tool call. Using tools to generate structured output\n * can cause errors, e.g. if:\n * - you provide multiple structured output schemas and the model calls multiple structured output tools\n * - if the structured output generated by the tool call doesn't match provided schema\n *\n * This property allows to handle these errors in different ways:\n * - `true` - retry the tool call\n * - `false` - throw an error\n * - `string` - retry the tool call with the provided message\n * - `(error: ToolStrategyError) => Promise<string> | string` - retry with the provided message or throw the error\n *\n * @default true\n */\n handleError?:\n | boolean\n | string\n | ((error: ToolStrategyError) => Promise<string> | string);\n}\n\nexport function toolStrategy<T extends InteropZodType<any>>(\n responseFormat: T,\n options?: ToolStrategyOptions\n): TypedToolStrategy<T extends InteropZodType<infer U> ? U : never>;\nexport function toolStrategy<T extends readonly InteropZodType<any>[]>(\n responseFormat: T,\n options?: ToolStrategyOptions\n): TypedToolStrategy<\n { [K in keyof T]: T[K] extends InteropZodType<infer U> ? U : never }[number]\n>;\nexport function toolStrategy(\n responseFormat: JsonSchemaFormat,\n options?: ToolStrategyOptions\n): TypedToolStrategy<Record<string, unknown>>;\nexport function toolStrategy(\n responseFormat: JsonSchemaFormat[],\n options?: ToolStrategyOptions\n): TypedToolStrategy<Record<string, unknown>>;\n\n/**\n * Creates a tool strategy for structured output using function calling.\n *\n * This function configures structured output by converting schemas into function tools that\n * the model calls. Unlike `providerStrategy`, which uses native JSON schema support,\n * `toolStrategy` works with any model that supports function calling, making it more\n * widely compatible across providers and model versions.\n *\n * The model will call a function with arguments matching your schema, and the agent will\n * extract and validate the structured output from the tool call. This approach is automatically\n * used when your model doesn't support native JSON schema output.\n *\n * @param responseFormat - The schema(s) to enforce. Can be a single Zod schema, an array of Zod schemas,\n * a JSON schema object, or an array of JSON schema objects.\n * @param options - Optional configuration for the tool strategy\n * @param options.handleError - How to handle errors when the model calls multiple structured output tools\n * or when the output doesn't match the schema. Defaults to `true` (auto-retry). Can be `false` (throw),\n * a `string` (retry with message), or a `function` (custom handler).\n * @param options.toolMessageContent - Custom message content to include in conversation history\n * when structured output is generated via tool call\n * @returns A `TypedToolStrategy` instance that can be used as the `responseFormat` in `createAgent`\n *\n * @example\n * ```ts\n * import { toolStrategy, createAgent } from \"langchain\";\n * import { z } from \"zod\";\n *\n * const agent = createAgent({\n * model: \"claude-haiku-4-5\",\n * responseFormat: toolStrategy(\n * z.object({\n * answer: z.string(),\n * confidence: z.number().min(0).max(1),\n * })\n * ),\n * });\n * ```\n *\n * @example\n * ```ts\n * // Multiple schemas - model can choose which one to use\n * const agent = createAgent({\n * model: \"claude-haiku-4-5\",\n * responseFormat: toolStrategy([\n * z.object({ name: z.string(), age: z.number() }),\n * z.object({ email: z.string(), phone: z.string() }),\n * ]),\n * });\n * ```\n */\nexport function toolStrategy(\n responseFormat:\n | InteropZodType<any>\n | InteropZodType<any>[]\n | JsonSchemaFormat\n | JsonSchemaFormat[],\n options?: ToolStrategyOptions\n): TypedToolStrategy {\n return transformResponseFormat(responseFormat, options) as TypedToolStrategy;\n}\n\n/**\n * Creates a provider strategy for structured output using native JSON schema support.\n *\n * This function is used to configure structured output for agents when the underlying model\n * supports native JSON schema output (e.g., OpenAI's `gpt-4o`, `gpt-4o-mini`, and newer models).\n * Unlike `toolStrategy`, which uses function calling to extract structured output, `providerStrategy`\n * leverages the provider's native structured output capabilities, resulting in more efficient\n * and reliable schema enforcement.\n *\n * When used with a model that supports JSON schema output, the model will return responses\n * that directly conform to the provided schema without requiring tool calls. This is the\n * recommended approach for structured output when your model supports it.\n *\n * @param responseFormat - The schema to enforce, either a Zod schema, a JSON schema object, or an options object with `schema` and optional `strict` flag\n * @returns A `ProviderStrategy` instance that can be used as the `responseFormat` in `createAgent`\n *\n * @example\n * ```ts\n * import { providerStrategy, createAgent } from \"langchain\";\n * import { z } from \"zod\";\n *\n * const agent = createAgent({\n * model: \"claude-haiku-4-5\",\n * responseFormat: providerStrategy(\n * z.object({\n * answer: z.string().describe(\"The answer to the question\"),\n * confidence: z.number().min(0).max(1),\n * })\n * ),\n * });\n * ```\n *\n * @example\n * ```ts\n * // Using strict mode for stricter schema enforcement\n * const agent = createAgent({\n * model: \"claude-haiku-4-5\",\n * responseFormat: providerStrategy({\n * schema: z.object({\n * name: z.string(),\n * age: z.number(),\n * }),\n * strict: true\n * }),\n * });\n * ```\n */\nexport function providerStrategy<T extends InteropZodType<unknown>>(\n responseFormat: T | { schema: T; strict?: boolean }\n): ProviderStrategy<T extends InteropZodType<infer U> ? U : never>;\nexport function providerStrategy(\n responseFormat:\n | JsonSchemaFormat\n | { schema: JsonSchemaFormat; strict?: boolean }\n): ProviderStrategy<Record<string, unknown>>;\nexport function providerStrategy(\n responseFormat:\n | InteropZodType<unknown>\n | JsonSchemaFormat\n | { schema: InteropZodType<unknown> | JsonSchemaFormat; strict?: boolean }\n): ProviderStrategy<unknown> {\n /**\n * Handle options object format\n */\n if (\n typeof responseFormat === \"object\" &&\n responseFormat !== null &&\n \"schema\" in responseFormat &&\n !isInteropZodSchema(responseFormat) &&\n !(\"type\" in responseFormat)\n ) {\n const { schema, strict: strictFlag } = responseFormat as {\n schema: InteropZodType<unknown> | JsonSchemaFormat;\n strict?: boolean;\n };\n return ProviderStrategy.fromSchema(\n schema as InteropZodType<unknown>,\n strictFlag ?? false\n ) as ProviderStrategy<unknown>;\n }\n\n /**\n * Handle direct schema format\n */\n return ProviderStrategy.fromSchema(\n responseFormat as InteropZodType<unknown>,\n false\n ) as ProviderStrategy<unknown>;\n}\n\n/**\n * Type representing a JSON Schema object format.\n * This is a strict type that excludes ToolStrategy and ProviderStrategy instances.\n */\nexport type JsonSchemaFormat = {\n type:\n | \"null\"\n | \"boolean\"\n | \"object\"\n | \"array\"\n | \"number\"\n | \"string\"\n | \"integer\";\n properties?: Record<string, unknown>;\n required?: string[];\n additionalProperties?: boolean;\n [key: string]: unknown;\n} & {\n // Brand to ensure this is not a ToolStrategy or ProviderStrategy\n __brand?: never;\n};\n\nconst CHAT_MODELS_THAT_SUPPORT_JSON_SCHEMA_OUTPUT = [\"ChatOpenAI\", \"ChatXAI\"];\nconst MODEL_NAMES_THAT_SUPPORT_JSON_SCHEMA_OUTPUT = [\n \"grok\",\n \"gpt-5\",\n \"gpt-4.1\",\n \"gpt-4o\",\n \"gpt-oss\",\n \"o3-pro\",\n \"o3-mini\",\n];\n\n/**\n * Identifies the models that support JSON schema output\n * @param model - The model to check\n * @returns True if the model supports JSON schema output, false otherwise\n */\nexport function hasSupportForJsonSchemaOutput(\n model?: LanguageModelLike | string\n): boolean {\n if (!model) {\n return false;\n }\n\n if (typeof model === \"string\") {\n const modelName = model.split(\":\").pop() as string;\n return MODEL_NAMES_THAT_SUPPORT_JSON_SCHEMA_OUTPUT.some(\n (modelNameSnippet) => modelName.includes(modelNameSnippet)\n );\n }\n\n if (isConfigurableModel(model)) {\n const configurableModel = model as unknown as {\n _defaultConfig: { model: string };\n };\n return hasSupportForJsonSchemaOutput(\n configurableModel._defaultConfig.model\n );\n }\n\n if (!isBaseChatModel(model)) {\n return false;\n }\n\n const chatModelClass = model.getName();\n\n /**\n * for testing purposes only\n */\n if (chatModelClass === \"FakeToolCallingChatModel\") {\n return true;\n }\n\n if (\n CHAT_MODELS_THAT_SUPPORT_JSON_SCHEMA_OUTPUT.includes(chatModelClass) &&\n /**\n * OpenAI models\n */ ((\"model\" in model &&\n MODEL_NAMES_THAT_SUPPORT_JSON_SCHEMA_OUTPUT.some(\n (modelNameSnippet) =>\n typeof model.model === \"string\" &&\n model.model.includes(modelNameSnippet)\n )) ||\n /**\n * for testing purposes only\n */\n (chatModelClass === \"FakeToolCallingModel\" &&\n \"structuredResponse\" in model))\n ) {\n return true;\n }\n\n return false;\n}\n"],"mappings":";;;;;;;;;AA8BA,IAAI,oBAAoB;;;;;;;AAQxB,IAAa,eAAb,MAAa,aAA2B;CACtC,AAAQ,YAIUA,QAKAC,MAQAC,SAChB;EAdgB;EAKA;EAQA;CACd;CAEJ,IAAI,OAAO;AACT,SAAO,KAAK,KAAK,SAAS;CAC3B;CAYD,OAAO,WACLC,QACAC,eACmB;;;;;EAKnB,SAAS,gBAAgBC,MAAe;AACtC,UAAO,QAAQ,CAAC,QAAQ,EAAE,EAAE,mBAAmB;EAChD;AAED,MAAI,mBAAmB,OAAO,EAAE;GAC9B,MAAMC,iBAAe,aAAa,OAAO;GACzC,MAAMC,SAAO;IACX,MAAM;IACN,UAAU;KACR,MAAM,iBAAiB;KACvB,QAAQ;KACR,aACED,eAAa,eACb;KACF,YAAYA;IACb;GACF;AACD,UAAO,IAAI,aAAaA,gBAAcC,QAAM;EAC7C;EAED,IAAIC;AACJ,MACE,OAAO,OAAO,SAAS,YACvB,OAAO,OAAO,eAAe,YAC7B,OAA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"file":"utils.cjs","names":["BaseChatModel","value: number","tools: StructuredTool[]","_schema: any","RunnableLambda","messages: BaseMessage[]","_options?: this[\"ParsedCallOptions\"]","_runManager?: CallbackManagerForLLMRun","HumanMessage","AIMessage"],"sources":["../../../src/agents/tests/utils.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable import/no-extraneous-dependencies */\nimport { expect } from \"vitest\";\nimport { CallbackManagerForLLMRun } from \"@langchain/core/callbacks/manager\";\nimport {\n BaseChatModel,\n BaseChatModelParams,\n BaseChatModelCallOptions,\n BindToolsInput,\n ToolChoice,\n} from \"@langchain/core/language_models/chat_models\";\nimport { StructuredTool } from \"@langchain/core/tools\";\nimport {\n BaseMessage,\n AIMessage,\n HumanMessage,\n BaseMessageFields,\n AIMessageFields,\n ToolMessage,\n ToolMessageFields,\n} from \"@langchain/core/messages\";\nimport { ChatResult } from \"@langchain/core/outputs\";\nimport {\n Runnable,\n RunnableConfig,\n RunnableLambda,\n RunnableBinding,\n} from \"@langchain/core/runnables\";\nimport {\n MemorySaver,\n Checkpoint,\n CheckpointMetadata,\n type BaseCheckpointSaver,\n} from \"@langchain/langgraph-checkpoint\";\nimport { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { z } from \"zod/v3\";\n\nexport class _AnyIdAIMessage extends AIMessage {\n get lc_id() {\n return [\"langchain_core\", \"messages\", \"AIMessage\"];\n }\n\n constructor(fields: AIMessageFields | string) {\n let fieldsWithJestMatcher: Partial<AIMessageFields> = {\n id: expect.any(String) as unknown as string,\n };\n if (typeof fields === \"string\") {\n fieldsWithJestMatcher = {\n content: fields,\n ...fieldsWithJestMatcher,\n };\n } else {\n fieldsWithJestMatcher = {\n ...fields,\n ...fieldsWithJestMatcher,\n };\n }\n super(fieldsWithJestMatcher as AIMessageFields);\n }\n}\n\nexport class _AnyIdHumanMessage extends HumanMessage {\n get lc_id() {\n return [\"langchain_core\", \"messages\", \"HumanMessage\"];\n }\n\n constructor(fields: BaseMessageFields | string) {\n let fieldsWithJestMatcher: Partial<BaseMessageFields> = {\n id: expect.any(String) as unknown as string,\n };\n if (typeof fields === \"string\") {\n fieldsWithJestMatcher = {\n content: fields,\n ...fieldsWithJestMatcher,\n };\n } else {\n fieldsWithJestMatcher = {\n ...fields,\n ...fieldsWithJestMatcher,\n };\n }\n super(fieldsWithJestMatcher as BaseMessageFields);\n }\n}\n\nexport class _AnyIdToolMessage extends ToolMessage {\n get lc_id() {\n return [\"langchain_core\", \"messages\", \"ToolMessage\"];\n }\n\n constructor(fields: ToolMessageFields) {\n const fieldsWithJestMatcher: Partial<ToolMessageFields> = {\n id: expect.any(String) as unknown as string,\n ...fields,\n };\n super(fieldsWithJestMatcher as ToolMessageFields);\n }\n}\n\nexport class FakeConfigurableModel extends BaseChatModel {\n _queuedMethodOperations: Record<string, any> = {};\n\n _chatModel: LanguageModelLike;\n\n constructor(\n fields: {\n model: LanguageModelLike;\n } & BaseChatModelParams\n ) {\n super(fields);\n this._chatModel = fields.model;\n }\n\n _llmType() {\n return \"fake_configurable\";\n }\n\n async _generate(\n _messages: BaseMessage[],\n _options: this[\"ParsedCallOptions\"],\n _runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n throw new Error(\"Not implemented\");\n }\n\n async _model() {\n return this._chatModel;\n }\n\n bindTools(tools: BindToolsInput[]) {\n const modelWithTools = new FakeConfigurableModel({\n model: (this._chatModel as FakeToolCallingChatModel).bindTools(tools),\n });\n modelWithTools._queuedMethodOperations.bindTools = tools;\n return modelWithTools;\n }\n}\n\nexport class FakeToolCallingChatModel extends BaseChatModel {\n sleep?: number = 50;\n\n responses?: BaseMessage[];\n\n thrownErrorString?: string;\n\n idx: number;\n\n toolStyle: \"openai\" | \"anthropic\" | \"bedrock\" | \"google\" = \"openai\";\n\n structuredResponse?: Record<string, unknown>;\n\n // Track messages passed to structured output calls\n structuredOutputMessages: BaseMessage[][] = [];\n\n constructor(\n fields: {\n sleep?: number;\n responses?: BaseMessage[];\n thrownErrorString?: string;\n toolStyle?: \"openai\" | \"anthropic\" | \"bedrock\" | \"google\";\n structuredResponse?: Record<string, unknown>;\n } & BaseChatModelParams\n ) {\n super(fields);\n this.sleep = fields.sleep ?? this.sleep;\n this.responses = fields.responses;\n this.thrownErrorString = fields.thrownErrorString;\n this.idx = 0;\n this.toolStyle = fields.toolStyle ?? this.toolStyle;\n this.structuredResponse = fields.structuredResponse;\n this.structuredOutputMessages = [];\n }\n\n _llmType() {\n return \"fake\";\n }\n\n async _generate(\n messages: BaseMessage[],\n _options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n if (this.thrownErrorString) {\n throw new Error(this.thrownErrorString);\n }\n if (this.sleep !== undefined) {\n await new Promise((resolve) => setTimeout(resolve, this.sleep));\n }\n const responses = this.responses?.length ? this.responses : messages;\n const msg = responses[this.idx % responses.length];\n const generation: ChatResult = {\n generations: [\n {\n text: \"\",\n message: msg,\n },\n ],\n };\n this.idx += 1;\n\n if (typeof msg.content === \"string\") {\n await runManager?.handleLLMNewToken(msg.content);\n }\n return generation;\n }\n\n bindTools(tools: BindToolsInput[]): Runnable<any> {\n const toolDicts = [];\n const serverTools = [];\n for (const tool of tools) {\n if (!(\"name\" in tool)) {\n serverTools.push(tool);\n continue;\n }\n\n // NOTE: this is a simplified tool spec for testing purposes only\n if (this.toolStyle === \"openai\") {\n toolDicts.push({\n type: \"function\",\n function: {\n name: tool.name,\n },\n });\n } else if ([\"anthropic\", \"google\"].includes(this.toolStyle)) {\n toolDicts.push({\n name: tool.name,\n });\n } else if (this.toolStyle === \"bedrock\") {\n toolDicts.push({\n toolSpec: {\n name: tool.name,\n },\n });\n }\n }\n let toolsToBind: BindToolsInput[] = toolDicts;\n if (this.toolStyle === \"google\") {\n toolsToBind = [{ functionDeclarations: toolDicts }];\n }\n return this.withConfig({\n tools: [...toolsToBind, ...serverTools],\n } as BaseChatModelCallOptions);\n }\n\n withStructuredOutput<\n RunOutput extends Record<string, any> = Record<string, any>\n >(_: unknown): Runnable<any> {\n if (!this.structuredResponse) {\n throw new Error(\"No structured response provided\");\n }\n // Create a runnable that returns the proper structured format\n return RunnableLambda.from(async (messages: BaseMessage[]) => {\n if (this.sleep) {\n await new Promise((resolve) => setTimeout(resolve, this.sleep));\n }\n\n // Store the messages that were sent to generate structured output\n this.structuredOutputMessages.push([...messages]);\n\n // Return in the format expected: { raw: BaseMessage, parsed: RunOutput }\n return this.structuredResponse as RunOutput;\n });\n }\n}\n\nexport class MemorySaverAssertImmutable extends MemorySaver {\n storageForCopies: Record<string, Record<string, Uint8Array>> = {};\n\n constructor() {\n super();\n this.storageForCopies = {};\n }\n\n async put(\n config: RunnableConfig,\n checkpoint: Checkpoint,\n metadata: CheckpointMetadata\n ): Promise<RunnableConfig> {\n const thread_id = config.configurable?.thread_id;\n this.storageForCopies[thread_id] ??= {};\n\n // assert checkpoint hasn't been modified since last written\n const saved = await this.get(config);\n if (saved) {\n const savedId = saved.id;\n if (this.storageForCopies[thread_id][savedId]) {\n const loaded = await this.serde.loadsTyped(\n \"json\",\n this.storageForCopies[thread_id][savedId]\n );\n\n expect(\n saved,\n `Checkpoint [${savedId}] has been modified since last written`\n ).toEqual(loaded);\n }\n }\n const [, serializedCheckpoint] = await this.serde.dumpsTyped(checkpoint);\n // save a copy of the checkpoint\n this.storageForCopies[thread_id][checkpoint.id] = serializedCheckpoint;\n\n return super.put(config, checkpoint, metadata);\n }\n}\n\ninterface ToolCall {\n name: string;\n args: Record<string, any>;\n id: string;\n type?: \"tool_call\";\n}\n\ninterface FakeToolCallingModelFields {\n toolCalls?: ToolCall[][];\n toolStyle?: \"openai\" | \"anthropic\";\n index?: number;\n structuredResponse?: any;\n}\n\n// Helper function to create checkpointer\nexport function createCheckpointer(): BaseCheckpointSaver {\n return new MemorySaver();\n}\n\n/**\n * Fake chat model for testing tool calling functionality\n */\nexport class FakeToolCallingModel extends BaseChatModel {\n toolCalls: ToolCall[][];\n\n toolStyle: \"openai\" | \"anthropic\";\n\n // Use a shared reference object so the index persists across bindTools calls\n private indexRef: { current: number };\n\n structuredResponse?: any;\n\n private tools: StructuredTool[] = [];\n\n constructor({\n toolCalls = [],\n toolStyle = \"openai\",\n index = 0,\n structuredResponse,\n indexRef,\n ...rest\n }: FakeToolCallingModelFields & { indexRef?: { current: number } } = {}) {\n super(rest);\n this.toolCalls = toolCalls;\n this.toolStyle = toolStyle;\n // Share the same index reference across instances\n this.indexRef = indexRef ?? { current: index };\n this.structuredResponse = structuredResponse;\n }\n\n // Getter/setter for backwards compatibility\n get index(): number {\n return this.indexRef.current;\n }\n\n set index(value: number) {\n this.indexRef.current = value;\n }\n\n _llmType(): string {\n return \"fake-tool-calling\";\n }\n\n _combineLLMOutput() {\n return [];\n }\n\n bindTools(\n tools: StructuredTool[]\n ):\n | FakeToolCallingModel\n | RunnableBinding<\n any,\n any,\n any & { tool_choice?: ToolChoice | undefined }\n > {\n const newInstance = new FakeToolCallingModel({\n toolCalls: this.toolCalls,\n toolStyle: this.toolStyle,\n structuredResponse: this.structuredResponse,\n // Pass the same indexRef so all instances share the same index state\n indexRef: this.indexRef,\n });\n newInstance.tools = [...this.tools, ...tools];\n return newInstance;\n }\n\n withStructuredOutput(_schema: any) {\n return new RunnableLambda({\n func: async () => {\n return this.structuredResponse;\n },\n });\n }\n\n async _generate(\n messages: BaseMessage[],\n _options?: this[\"ParsedCallOptions\"],\n _runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n const lastMessage = messages[messages.length - 1];\n let content = lastMessage.content as string;\n\n // Handle prompt concatenation\n if (messages.length > 1) {\n const parts = messages.map((m) => m.content).filter(Boolean);\n content = parts\n .map((part) => {\n if (typeof part === \"string\") {\n return part;\n } else if (typeof part === \"object\" && \"text\" in part) {\n return part.text;\n } else if (Array.isArray(part)) {\n return part\n .map((p) => {\n if (typeof p === \"string\") {\n return p;\n } else if (typeof p === \"object\" && \"text\" in p) {\n return p.text;\n }\n return \"\";\n })\n .join(\"-\");\n } else {\n return JSON.stringify(part);\n }\n })\n .join(\"-\");\n }\n\n // Reset index at the start of a new conversation (only human message)\n // This allows the model to be reused across multiple agent.invoke() calls\n const isStartOfConversation =\n messages.length === 1 ||\n (messages.length === 2 && messages.every(HumanMessage.isInstance));\n if (isStartOfConversation && this.index !== 0) {\n this.index = 0;\n }\n\n const currentToolCalls = this.toolCalls[this.index] || [];\n const messageId = this.index.toString();\n\n // Move to next set of tool calls for subsequent invocations\n this.index = (this.index + 1) % Math.max(1, this.toolCalls.length);\n\n const message = new AIMessage({\n content,\n id: messageId,\n tool_calls:\n currentToolCalls.length > 0\n ? currentToolCalls.map((tc) => ({\n ...tc,\n type: \"tool_call\" as const,\n }))\n : undefined,\n });\n\n return {\n generations: [\n {\n text: content,\n message,\n },\n ],\n llmOutput: {},\n };\n }\n}\n\nexport class SearchAPI extends StructuredTool {\n name = \"search_api\";\n\n description = \"A simple API that returns the input string.\";\n\n schema = z.object({\n query: z.string().describe(\"The query to search for.\"),\n });\n\n async _call(input: z.infer<typeof this.schema>) {\n if (input?.query === \"error\") {\n throw new Error(\"Error\");\n }\n return `result for ${input?.query}`;\n }\n}\n"],"mappings":";;;;;;;;;;;;AAuUA,IAAa,uBAAb,MAAa,6BAA6BA,2DAAc;CACtD;CAEA;CAGA,AAAQ;CAER;CAEA,AAAQ,QAA0B,CAAE;CAEpC,YAAY,EACV,YAAY,CAAE,GACd,YAAY,UACZ,QAAQ,GACR,oBACA,SACA,GAAG,MAC6D,GAAG,CAAE,GAAE;EACvE,MAAM,KAAK;EACX,KAAK,YAAY;EACjB,KAAK,YAAY;EAEjB,KAAK,WAAW,YAAY,EAAE,SAAS,MAAO;EAC9C,KAAK,qBAAqB;CAC3B;CAGD,IAAI,QAAgB;AAClB,SAAO,KAAK,SAAS;CACtB;CAED,IAAI,MAAMC,OAAe;EACvB,KAAK,SAAS,UAAU;CACzB;CAED,WAAmB;AACjB,SAAO;CACR;CAED,oBAAoB;AAClB,SAAO,CAAE;C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,iBAAiB,SAAS,IACtB,iBAAiB,IAAI,CAAC,QAAQ;IAC5B,GAAG;IACH,MAAM;GACP,GAAE,GACH;EACP;AAED,SAAO;GACL,aAAa,CACX;IACE,MAAM;IACN;GACD,CACF;GACD,WAAW,CAAE;EACd;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"utils.cjs","names":["BaseChatModel","value: number","tools: StructuredTool[]","_schema: any","RunnableLambda","messages: BaseMessage[]","_options?: this[\"ParsedCallOptions\"]","_runManager?: CallbackManagerForLLMRun","HumanMessage","AIMessage"],"sources":["../../../src/agents/tests/utils.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { CallbackManagerForLLMRun } from \"@langchain/core/callbacks/manager\";\nimport {\n BaseChatModel,\n BaseChatModelParams,\n BaseChatModelCallOptions,\n BindToolsInput,\n ToolChoice,\n} from \"@langchain/core/language_models/chat_models\";\nimport { StructuredTool } from \"@langchain/core/tools\";\nimport {\n BaseMessage,\n AIMessage,\n HumanMessage,\n BaseMessageFields,\n AIMessageFields,\n ToolMessage,\n ToolMessageFields,\n} from \"@langchain/core/messages\";\nimport { ChatResult } from \"@langchain/core/outputs\";\nimport {\n Runnable,\n RunnableConfig,\n RunnableLambda,\n RunnableBinding,\n} from \"@langchain/core/runnables\";\nimport {\n MemorySaver,\n Checkpoint,\n CheckpointMetadata,\n type BaseCheckpointSaver,\n} from \"@langchain/langgraph-checkpoint\";\nimport { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { z } from \"zod/v3\";\n\n/**\n * Custom asymmetric matcher that matches any string value.\n * Works with both Jest and Vitest's toEqual() assertions.\n */\nclass AnyString {\n asymmetricMatch(other: unknown): boolean {\n return typeof other === \"string\";\n }\n\n toString(): string {\n return \"Any<String>\";\n }\n\n toAsymmetricMatcher(): string {\n return \"Any<String>\";\n }\n}\n\nexport class _AnyIdAIMessage extends AIMessage {\n get lc_id() {\n return [\"langchain_core\", \"messages\", \"AIMessage\"];\n }\n\n constructor(fields: AIMessageFields | string) {\n let fieldsWithJestMatcher: Partial<AIMessageFields> = {\n id: new AnyString() as unknown as string,\n };\n if (typeof fields === \"string\") {\n fieldsWithJestMatcher = {\n content: fields,\n ...fieldsWithJestMatcher,\n };\n } else {\n fieldsWithJestMatcher = {\n ...fields,\n ...fieldsWithJestMatcher,\n };\n }\n super(fieldsWithJestMatcher as AIMessageFields);\n }\n}\n\nexport class _AnyIdHumanMessage extends HumanMessage {\n get lc_id() {\n return [\"langchain_core\", \"messages\", \"HumanMessage\"];\n }\n\n constructor(fields: BaseMessageFields | string) {\n let fieldsWithJestMatcher: Partial<BaseMessageFields> = {\n id: new AnyString() as unknown as string,\n };\n if (typeof fields === \"string\") {\n fieldsWithJestMatcher = {\n content: fields,\n ...fieldsWithJestMatcher,\n };\n } else {\n fieldsWithJestMatcher = {\n ...fields,\n ...fieldsWithJestMatcher,\n };\n }\n super(fieldsWithJestMatcher as BaseMessageFields);\n }\n}\n\nexport class _AnyIdToolMessage extends ToolMessage {\n get lc_id() {\n return [\"langchain_core\", \"messages\", \"ToolMessage\"];\n }\n\n constructor(fields: ToolMessageFields) {\n const fieldsWithJestMatcher: Partial<ToolMessageFields> = {\n id: new AnyString() as unknown as string,\n ...fields,\n };\n super(fieldsWithJestMatcher as ToolMessageFields);\n }\n}\n\nexport class FakeConfigurableModel extends BaseChatModel {\n _queuedMethodOperations: Record<string, any> = {};\n\n _chatModel: LanguageModelLike;\n\n constructor(\n fields: {\n model: LanguageModelLike;\n } & BaseChatModelParams\n ) {\n super(fields);\n this._chatModel = fields.model;\n }\n\n _llmType() {\n return \"fake_configurable\";\n }\n\n async _generate(\n _messages: BaseMessage[],\n _options: this[\"ParsedCallOptions\"],\n _runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n throw new Error(\"Not implemented\");\n }\n\n async _model() {\n return this._chatModel;\n }\n\n bindTools(tools: BindToolsInput[]) {\n const modelWithTools = new FakeConfigurableModel({\n model: (this._chatModel as FakeToolCallingChatModel).bindTools(tools),\n });\n modelWithTools._queuedMethodOperations.bindTools = tools;\n return modelWithTools;\n }\n}\n\nexport class FakeToolCallingChatModel extends BaseChatModel {\n sleep?: number = 50;\n\n responses?: BaseMessage[];\n\n thrownErrorString?: string;\n\n idx: number;\n\n toolStyle: \"openai\" | \"anthropic\" | \"bedrock\" | \"google\" = \"openai\";\n\n structuredResponse?: Record<string, unknown>;\n\n // Track messages passed to structured output calls\n structuredOutputMessages: BaseMessage[][] = [];\n\n constructor(\n fields: {\n sleep?: number;\n responses?: BaseMessage[];\n thrownErrorString?: string;\n toolStyle?: \"openai\" | \"anthropic\" | \"bedrock\" | \"google\";\n structuredResponse?: Record<string, unknown>;\n } & BaseChatModelParams\n ) {\n super(fields);\n this.sleep = fields.sleep ?? this.sleep;\n this.responses = fields.responses;\n this.thrownErrorString = fields.thrownErrorString;\n this.idx = 0;\n this.toolStyle = fields.toolStyle ?? this.toolStyle;\n this.structuredResponse = fields.structuredResponse;\n this.structuredOutputMessages = [];\n }\n\n _llmType() {\n return \"fake\";\n }\n\n async _generate(\n messages: BaseMessage[],\n _options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n if (this.thrownErrorString) {\n throw new Error(this.thrownErrorString);\n }\n if (this.sleep !== undefined) {\n await new Promise((resolve) => setTimeout(resolve, this.sleep));\n }\n const responses = this.responses?.length ? this.responses : messages;\n const msg = responses[this.idx % responses.length];\n const generation: ChatResult = {\n generations: [\n {\n text: \"\",\n message: msg,\n },\n ],\n };\n this.idx += 1;\n\n if (typeof msg.content === \"string\") {\n await runManager?.handleLLMNewToken(msg.content);\n }\n return generation;\n }\n\n bindTools(tools: BindToolsInput[]): Runnable<any> {\n const toolDicts = [];\n const serverTools = [];\n for (const tool of tools) {\n if (!(\"name\" in tool)) {\n serverTools.push(tool);\n continue;\n }\n\n // NOTE: this is a simplified tool spec for testing purposes only\n if (this.toolStyle === \"openai\") {\n toolDicts.push({\n type: \"function\",\n function: {\n name: tool.name,\n },\n });\n } else if ([\"anthropic\", \"google\"].includes(this.toolStyle)) {\n toolDicts.push({\n name: tool.name,\n });\n } else if (this.toolStyle === \"bedrock\") {\n toolDicts.push({\n toolSpec: {\n name: tool.name,\n },\n });\n }\n }\n let toolsToBind: BindToolsInput[] = toolDicts;\n if (this.toolStyle === \"google\") {\n toolsToBind = [{ functionDeclarations: toolDicts }];\n }\n return this.withConfig({\n tools: [...toolsToBind, ...serverTools],\n } as BaseChatModelCallOptions);\n }\n\n withStructuredOutput<\n RunOutput extends Record<string, any> = Record<string, any>\n >(_: unknown): Runnable<any> {\n if (!this.structuredResponse) {\n throw new Error(\"No structured response provided\");\n }\n // Create a runnable that returns the proper structured format\n return RunnableLambda.from(async (messages: BaseMessage[]) => {\n if (this.sleep) {\n await new Promise((resolve) => setTimeout(resolve, this.sleep));\n }\n\n // Store the messages that were sent to generate structured output\n this.structuredOutputMessages.push([...messages]);\n\n // Return in the format expected: { raw: BaseMessage, parsed: RunOutput }\n return this.structuredResponse as RunOutput;\n });\n }\n}\n\nexport class MemorySaverAssertImmutable extends MemorySaver {\n storageForCopies: Record<string, Record<string, Uint8Array>> = {};\n\n constructor() {\n super();\n this.storageForCopies = {};\n }\n\n async put(\n config: RunnableConfig,\n checkpoint: Checkpoint,\n metadata: CheckpointMetadata\n ): Promise<RunnableConfig> {\n const thread_id = config.configurable?.thread_id;\n this.storageForCopies[thread_id] ??= {};\n\n // assert checkpoint hasn't been modified since last written\n const saved = await this.get(config);\n if (saved) {\n const savedId = saved.id;\n if (this.storageForCopies[thread_id][savedId]) {\n const [, serializedSaved] = await this.serde.dumpsTyped(saved);\n const serializedCopy = this.storageForCopies[thread_id][savedId];\n\n // Compare Uint8Array contents by converting to string\n const savedStr = new TextDecoder().decode(serializedSaved);\n const copyStr = new TextDecoder().decode(serializedCopy);\n if (savedStr !== copyStr) {\n throw new Error(\n `Checkpoint [${savedId}] has been modified since last written`\n );\n }\n }\n }\n const [, serializedCheckpoint] = await this.serde.dumpsTyped(checkpoint);\n // save a copy of the checkpoint\n this.storageForCopies[thread_id][checkpoint.id] = serializedCheckpoint;\n\n return super.put(config, checkpoint, metadata);\n }\n}\n\ninterface ToolCall {\n name: string;\n args: Record<string, any>;\n id: string;\n type?: \"tool_call\";\n}\n\ninterface FakeToolCallingModelFields {\n toolCalls?: ToolCall[][];\n toolStyle?: \"openai\" | \"anthropic\";\n index?: number;\n structuredResponse?: any;\n}\n\n// Helper function to create checkpointer\nexport function createCheckpointer(): BaseCheckpointSaver {\n return new MemorySaver();\n}\n\n/**\n * Fake chat model for testing tool calling functionality\n */\nexport class FakeToolCallingModel extends BaseChatModel {\n toolCalls: ToolCall[][];\n\n toolStyle: \"openai\" | \"anthropic\";\n\n // Use a shared reference object so the index persists across bindTools calls\n private indexRef: { current: number };\n\n structuredResponse?: any;\n\n private tools: StructuredTool[] = [];\n\n constructor({\n toolCalls = [],\n toolStyle = \"openai\",\n index = 0,\n structuredResponse,\n indexRef,\n ...rest\n }: FakeToolCallingModelFields & { indexRef?: { current: number } } = {}) {\n super(rest);\n this.toolCalls = toolCalls;\n this.toolStyle = toolStyle;\n // Share the same index reference across instances\n this.indexRef = indexRef ?? { current: index };\n this.structuredResponse = structuredResponse;\n }\n\n // Getter/setter for backwards compatibility\n get index(): number {\n return this.indexRef.current;\n }\n\n set index(value: number) {\n this.indexRef.current = value;\n }\n\n _llmType(): string {\n return \"fake-tool-calling\";\n }\n\n _combineLLMOutput() {\n return [];\n }\n\n bindTools(\n tools: StructuredTool[]\n ):\n | FakeToolCallingModel\n | RunnableBinding<\n any,\n any,\n any & { tool_choice?: ToolChoice | undefined }\n > {\n const newInstance = new FakeToolCallingModel({\n toolCalls: this.toolCalls,\n toolStyle: this.toolStyle,\n structuredResponse: this.structuredResponse,\n // Pass the same indexRef so all instances share the same index state\n indexRef: this.indexRef,\n });\n newInstance.tools = [...this.tools, ...tools];\n return newInstance;\n }\n\n withStructuredOutput(_schema: any) {\n return new RunnableLambda({\n func: async () => {\n return this.structuredResponse;\n },\n });\n }\n\n async _generate(\n messages: BaseMessage[],\n _options?: this[\"ParsedCallOptions\"],\n _runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n const lastMessage = messages[messages.length - 1];\n let content = lastMessage.content as string;\n\n // Handle prompt concatenation\n if (messages.length > 1) {\n const parts = messages.map((m) => m.content).filter(Boolean);\n content = parts\n .map((part) => {\n if (typeof part === \"string\") {\n return part;\n } else if (typeof part === \"object\" && \"text\" in part) {\n return part.text;\n } else if (Array.isArray(part)) {\n return part\n .map((p) => {\n if (typeof p === \"string\") {\n return p;\n } else if (typeof p === \"object\" && \"text\" in p) {\n return p.text;\n }\n return \"\";\n })\n .join(\"-\");\n } else {\n return JSON.stringify(part);\n }\n })\n .join(\"-\");\n }\n\n // Reset index at the start of a new conversation (only human message)\n // This allows the model to be reused across multiple agent.invoke() calls\n const isStartOfConversation =\n messages.length === 1 ||\n (messages.length === 2 && messages.every(HumanMessage.isInstance));\n if (isStartOfConversation && this.index !== 0) {\n this.index = 0;\n }\n\n const currentToolCalls = this.toolCalls[this.index] || [];\n const messageId = this.index.toString();\n\n // Move to next set of tool calls for subsequent invocations\n this.index = (this.index + 1) % Math.max(1, this.toolCalls.length);\n\n const message = new AIMessage({\n content,\n id: messageId,\n tool_calls:\n currentToolCalls.length > 0\n ? currentToolCalls.map((tc) => ({\n ...tc,\n type: \"tool_call\" as const,\n }))\n : undefined,\n });\n\n return {\n generations: [\n {\n text: content,\n message,\n },\n ],\n llmOutput: {},\n };\n }\n}\n\nexport class SearchAPI extends StructuredTool {\n name = \"search_api\";\n\n description = \"A simple API that returns the input string.\";\n\n schema = z.object({\n query: z.string().describe(\"The query to search for.\"),\n });\n\n async _call(input: z.infer<typeof this.schema>) {\n if (input?.query === \"error\") {\n throw new Error(\"Error\");\n }\n return `result for ${input?.query}`;\n }\n}\n"],"mappings":";;;;;;;;;;;;AAyVA,IAAa,uBAAb,MAAa,6BAA6BA,2DAAc;C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R,EAAC,CACD,KAAK,IAAI;QAEZ,QAAO,KAAK,UAAU,KAAK;GAE9B,EAAC,CACD,KAAK,IAAI;EACb;EAID,MAAM,wBACJ,SAAS,WAAW,KACnB,SAAS,WAAW,KAAK,SAAS,MAAMC,uCAAa,WAAW;AACnE,MAAI,yBAAyB,KAAK,UAAU,GAC1C,KAAK,QAAQ;EAGf,MAAM,mBAAmB,KAAK,UAAU,KAAK,UAAU,CAAE;EACzD,MAAM,YAAY,KAAK,MAAM,UAAU;EAGvC,KAAK,SAAS,KAAK,QAAQ,KAAK,KAAK,IAAI,GAAG,KAAK,UAAU,OAAO;EAElE,MAAM,UAAU,IAAIC,oCAAU;GAC5B;GACA,IAAI;GACJ,YACE,iBAAiB,SAAS,IACtB,iBAAiB,IAAI,CAAC,QAAQ;IAC5B,GAAG;IACH,MAAM;GACP,GAAE,GACH;EACP;AAED,SAAO;GACL,aAAa,CACX;IACE,MAAM;IACN;GACD,CACF;GACD,WAAW,CAAE;EACd;CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","names":["value: number","tools: StructuredTool[]","_schema: any","messages: BaseMessage[]","_options?: this[\"ParsedCallOptions\"]","_runManager?: CallbackManagerForLLMRun"],"sources":["../../../src/agents/tests/utils.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable import/no-extraneous-dependencies */\nimport { expect } from \"vitest\";\nimport { CallbackManagerForLLMRun } from \"@langchain/core/callbacks/manager\";\nimport {\n BaseChatModel,\n BaseChatModelParams,\n BaseChatModelCallOptions,\n BindToolsInput,\n ToolChoice,\n} from \"@langchain/core/language_models/chat_models\";\nimport { StructuredTool } from \"@langchain/core/tools\";\nimport {\n BaseMessage,\n AIMessage,\n HumanMessage,\n BaseMessageFields,\n AIMessageFields,\n ToolMessage,\n ToolMessageFields,\n} from \"@langchain/core/messages\";\nimport { ChatResult } from \"@langchain/core/outputs\";\nimport {\n Runnable,\n RunnableConfig,\n RunnableLambda,\n RunnableBinding,\n} from \"@langchain/core/runnables\";\nimport {\n MemorySaver,\n Checkpoint,\n CheckpointMetadata,\n type BaseCheckpointSaver,\n} from \"@langchain/langgraph-checkpoint\";\nimport { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { z } from \"zod/v3\";\n\nexport class _AnyIdAIMessage extends AIMessage {\n get lc_id() {\n return [\"langchain_core\", \"messages\", \"AIMessage\"];\n }\n\n constructor(fields: AIMessageFields | string) {\n let fieldsWithJestMatcher: Partial<AIMessageFields> = {\n id: expect.any(String) as unknown as string,\n };\n if (typeof fields === \"string\") {\n fieldsWithJestMatcher = {\n content: fields,\n ...fieldsWithJestMatcher,\n };\n } else {\n fieldsWithJestMatcher = {\n ...fields,\n ...fieldsWithJestMatcher,\n };\n }\n super(fieldsWithJestMatcher as AIMessageFields);\n }\n}\n\nexport class _AnyIdHumanMessage extends HumanMessage {\n get lc_id() {\n return [\"langchain_core\", \"messages\", \"HumanMessage\"];\n }\n\n constructor(fields: BaseMessageFields | string) {\n let fieldsWithJestMatcher: Partial<BaseMessageFields> = {\n id: expect.any(String) as unknown as string,\n };\n if (typeof fields === \"string\") {\n fieldsWithJestMatcher = {\n content: fields,\n ...fieldsWithJestMatcher,\n };\n } else {\n fieldsWithJestMatcher = {\n ...fields,\n ...fieldsWithJestMatcher,\n };\n }\n super(fieldsWithJestMatcher as BaseMessageFields);\n }\n}\n\nexport class _AnyIdToolMessage extends ToolMessage {\n get lc_id() {\n return [\"langchain_core\", \"messages\", \"ToolMessage\"];\n }\n\n constructor(fields: ToolMessageFields) {\n const fieldsWithJestMatcher: Partial<ToolMessageFields> = {\n id: expect.any(String) as unknown as string,\n ...fields,\n };\n super(fieldsWithJestMatcher as ToolMessageFields);\n }\n}\n\nexport class FakeConfigurableModel extends BaseChatModel {\n _queuedMethodOperations: Record<string, any> = {};\n\n _chatModel: LanguageModelLike;\n\n constructor(\n fields: {\n model: LanguageModelLike;\n } & BaseChatModelParams\n ) {\n super(fields);\n this._chatModel = fields.model;\n }\n\n _llmType() {\n return \"fake_configurable\";\n }\n\n async _generate(\n _messages: BaseMessage[],\n _options: this[\"ParsedCallOptions\"],\n _runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n throw new Error(\"Not implemented\");\n }\n\n async _model() {\n return this._chatModel;\n }\n\n bindTools(tools: BindToolsInput[]) {\n const modelWithTools = new FakeConfigurableModel({\n model: (this._chatModel as FakeToolCallingChatModel).bindTools(tools),\n });\n modelWithTools._queuedMethodOperations.bindTools = tools;\n return modelWithTools;\n }\n}\n\nexport class FakeToolCallingChatModel extends BaseChatModel {\n sleep?: number = 50;\n\n responses?: BaseMessage[];\n\n thrownErrorString?: string;\n\n idx: number;\n\n toolStyle: \"openai\" | \"anthropic\" | \"bedrock\" | \"google\" = \"openai\";\n\n structuredResponse?: Record<string, unknown>;\n\n // Track messages passed to structured output calls\n structuredOutputMessages: BaseMessage[][] = [];\n\n constructor(\n fields: {\n sleep?: number;\n responses?: BaseMessage[];\n thrownErrorString?: string;\n toolStyle?: \"openai\" | \"anthropic\" | \"bedrock\" | \"google\";\n structuredResponse?: Record<string, unknown>;\n } & BaseChatModelParams\n ) {\n super(fields);\n this.sleep = fields.sleep ?? this.sleep;\n this.responses = fields.responses;\n this.thrownErrorString = fields.thrownErrorString;\n this.idx = 0;\n this.toolStyle = fields.toolStyle ?? this.toolStyle;\n this.structuredResponse = fields.structuredResponse;\n this.structuredOutputMessages = [];\n }\n\n _llmType() {\n return \"fake\";\n }\n\n async _generate(\n messages: BaseMessage[],\n _options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n if (this.thrownErrorString) {\n throw new Error(this.thrownErrorString);\n }\n if (this.sleep !== undefined) {\n await new Promise((resolve) => setTimeout(resolve, this.sleep));\n }\n const responses = this.responses?.length ? this.responses : messages;\n const msg = responses[this.idx % responses.length];\n const generation: ChatResult = {\n generations: [\n {\n text: \"\",\n message: msg,\n },\n ],\n };\n this.idx += 1;\n\n if (typeof msg.content === \"string\") {\n await runManager?.handleLLMNewToken(msg.content);\n }\n return generation;\n }\n\n bindTools(tools: BindToolsInput[]): Runnable<any> {\n const toolDicts = [];\n const serverTools = [];\n for (const tool of tools) {\n if (!(\"name\" in tool)) {\n serverTools.push(tool);\n continue;\n }\n\n // NOTE: this is a simplified tool spec for testing purposes only\n if (this.toolStyle === \"openai\") {\n toolDicts.push({\n type: \"function\",\n function: {\n name: tool.name,\n },\n });\n } else if ([\"anthropic\", \"google\"].includes(this.toolStyle)) {\n toolDicts.push({\n name: tool.name,\n });\n } else if (this.toolStyle === \"bedrock\") {\n toolDicts.push({\n toolSpec: {\n name: tool.name,\n },\n });\n }\n }\n let toolsToBind: BindToolsInput[] = toolDicts;\n if (this.toolStyle === \"google\") {\n toolsToBind = [{ functionDeclarations: toolDicts }];\n }\n return this.withConfig({\n tools: [...toolsToBind, ...serverTools],\n } as BaseChatModelCallOptions);\n }\n\n withStructuredOutput<\n RunOutput extends Record<string, any> = Record<string, any>\n >(_: unknown): Runnable<any> {\n if (!this.structuredResponse) {\n throw new Error(\"No structured response provided\");\n }\n // Create a runnable that returns the proper structured format\n return RunnableLambda.from(async (messages: BaseMessage[]) => {\n if (this.sleep) {\n await new Promise((resolve) => setTimeout(resolve, this.sleep));\n }\n\n // Store the messages that were sent to generate structured output\n this.structuredOutputMessages.push([...messages]);\n\n // Return in the format expected: { raw: BaseMessage, parsed: RunOutput }\n return this.structuredResponse as RunOutput;\n });\n }\n}\n\nexport class MemorySaverAssertImmutable extends MemorySaver {\n storageForCopies: Record<string, Record<string, Uint8Array>> = {};\n\n constructor() {\n super();\n this.storageForCopies = {};\n }\n\n async put(\n config: RunnableConfig,\n checkpoint: Checkpoint,\n metadata: CheckpointMetadata\n ): Promise<RunnableConfig> {\n const thread_id = config.configurable?.thread_id;\n this.storageForCopies[thread_id] ??= {};\n\n // assert checkpoint hasn't been modified since last written\n const saved = await this.get(config);\n if (saved) {\n const savedId = saved.id;\n if (this.storageForCopies[thread_id][savedId]) {\n const loaded = await this.serde.loadsTyped(\n \"json\",\n this.storageForCopies[thread_id][savedId]\n );\n\n expect(\n saved,\n `Checkpoint [${savedId}] has been modified since last written`\n ).toEqual(loaded);\n }\n }\n const [, serializedCheckpoint] = await this.serde.dumpsTyped(checkpoint);\n // save a copy of the checkpoint\n this.storageForCopies[thread_id][checkpoint.id] = serializedCheckpoint;\n\n return super.put(config, checkpoint, metadata);\n }\n}\n\ninterface ToolCall {\n name: string;\n args: Record<string, any>;\n id: string;\n type?: \"tool_call\";\n}\n\ninterface FakeToolCallingModelFields {\n toolCalls?: ToolCall[][];\n toolStyle?: \"openai\" | \"anthropic\";\n index?: number;\n structuredResponse?: any;\n}\n\n// Helper function to create checkpointer\nexport function createCheckpointer(): BaseCheckpointSaver {\n return new MemorySaver();\n}\n\n/**\n * Fake chat model for testing tool calling functionality\n */\nexport class FakeToolCallingModel extends BaseChatModel {\n toolCalls: ToolCall[][];\n\n toolStyle: \"openai\" | \"anthropic\";\n\n // Use a shared reference object so the index persists across bindTools calls\n private indexRef: { current: number };\n\n structuredResponse?: any;\n\n private tools: StructuredTool[] = [];\n\n constructor({\n toolCalls = [],\n toolStyle = \"openai\",\n index = 0,\n structuredResponse,\n indexRef,\n ...rest\n }: FakeToolCallingModelFields & { indexRef?: { current: number } } = {}) {\n super(rest);\n this.toolCalls = toolCalls;\n this.toolStyle = toolStyle;\n // Share the same index reference across instances\n this.indexRef = indexRef ?? { current: index };\n this.structuredResponse = structuredResponse;\n }\n\n // Getter/setter for backwards compatibility\n get index(): number {\n return this.indexRef.current;\n }\n\n set index(value: number) {\n this.indexRef.current = value;\n }\n\n _llmType(): string {\n return \"fake-tool-calling\";\n }\n\n _combineLLMOutput() {\n return [];\n }\n\n bindTools(\n tools: StructuredTool[]\n ):\n | FakeToolCallingModel\n | RunnableBinding<\n any,\n any,\n any & { tool_choice?: ToolChoice | undefined }\n > {\n const newInstance = new FakeToolCallingModel({\n toolCalls: this.toolCalls,\n toolStyle: this.toolStyle,\n structuredResponse: this.structuredResponse,\n // Pass the same indexRef so all instances share the same index state\n indexRef: this.indexRef,\n });\n newInstance.tools = [...this.tools, ...tools];\n return newInstance;\n }\n\n withStructuredOutput(_schema: any) {\n return new RunnableLambda({\n func: async () => {\n return this.structuredResponse;\n },\n });\n }\n\n async _generate(\n messages: BaseMessage[],\n _options?: this[\"ParsedCallOptions\"],\n _runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n const lastMessage = messages[messages.length - 1];\n let content = lastMessage.content as string;\n\n // Handle prompt concatenation\n if (messages.length > 1) {\n const parts = messages.map((m) => m.content).filter(Boolean);\n content = parts\n .map((part) => {\n if (typeof part === \"string\") {\n return part;\n } else if (typeof part === \"object\" && \"text\" in part) {\n return part.text;\n } else if (Array.isArray(part)) {\n return part\n .map((p) => {\n if (typeof p === \"string\") {\n return p;\n } else if (typeof p === \"object\" && \"text\" in p) {\n return p.text;\n }\n return \"\";\n })\n .join(\"-\");\n } else {\n return JSON.stringify(part);\n }\n })\n .join(\"-\");\n }\n\n // Reset index at the start of a new conversation (only human message)\n // This allows the model to be reused across multiple agent.invoke() calls\n const isStartOfConversation =\n messages.length === 1 ||\n (messages.length === 2 && messages.every(HumanMessage.isInstance));\n if (isStartOfConversation && this.index !== 0) {\n this.index = 0;\n }\n\n const currentToolCalls = this.toolCalls[this.index] || [];\n const messageId = this.index.toString();\n\n // Move to next set of tool calls for subsequent invocations\n this.index = (this.index + 1) % Math.max(1, this.toolCalls.length);\n\n const message = new AIMessage({\n content,\n id: messageId,\n tool_calls:\n currentToolCalls.length > 0\n ? currentToolCalls.map((tc) => ({\n ...tc,\n type: \"tool_call\" as const,\n }))\n : undefined,\n });\n\n return {\n generations: [\n {\n text: content,\n message,\n },\n ],\n llmOutput: {},\n };\n }\n}\n\nexport class SearchAPI extends StructuredTool {\n name = \"search_api\";\n\n description = \"A simple API that returns the input string.\";\n\n schema = z.object({\n query: z.string().describe(\"The query to search for.\"),\n });\n\n async _call(input: z.infer<typeof this.schema>) {\n if (input?.query === \"error\") {\n throw new Error(\"Error\");\n }\n return `result for ${input?.query}`;\n }\n}\n"],"mappings":";;;;;;;;;;;AAuUA,IAAa,uBAAb,MAAa,6BAA6B,cAAc;CACtD;CAEA;CAGA,AAAQ;CAER;CAEA,AAAQ,QAA0B,CAAE;CAEpC,YAAY,EACV,YAAY,CAAE,GACd,YAAY,UACZ,QAAQ,GACR,oBACA,SACA,GAAG,MAC6D,GAAG,CAAE,GAAE;EACvE,MAAM,KAAK;EACX,KAAK,YAAY;EACjB,KAAK,YAAY;EAEjB,KAAK,WAAW,YAAY,EAAE,SAAS,MAAO;EAC9C,KAAK,qBAAqB;CAC3B;CAGD,IAAI,QAAgB;AAClB,SAAO,KAAK,SAAS;CACtB;CAED,IAAI,MAAMA,OAAe;EACvB,KAAK,SAAS,UAAU;CACzB;CAED,WAAmB;AACjB,SAAO;CACR;CAED,oBAAoB;AAClB,SAAO,CAAE;CACV;CAED,UACEC,OAOI;EACJ,MAAM,cAAc,IAAI,qBAAqB;GAC3C,WAAW,KAAK;GAChB,WAAW,KAAK;GAChB,oBAAoB,KAAK;GAEzB,UAAU,KAAK;EAChB;EACD,YAAY,QAAQ,CAAC,GAAG,KAAK,OAAO,GAAG,KAAM;AAC7C,SAAO;CACR;CAED,qBAAqBC,SAAc;AACjC,SAAO,IAAI,eAAe,EACxB,MAAM,YAAY;AAChB,UAAO,KAAK;EACb,EACF;CACF;CAED,MAAM,UACJC,UACAC,UACAC,aACqB;EACrB,MAAM,cAAc,SAAS,SAAS,SAAS;EAC/C,IAAI,UAAU,YAAY;AAG1B,MAAI,SAAS,SAAS,GAAG;GACvB,MAAM,QAAQ,SAAS,IAAI,CAAC,MAAM,EAAE,QAAQ,CAAC,OAAO,QAAQ;GAC5D,UAAU,MACP,IAAI,CAAC,SAAS;AACb,QAAI,OAAO,SAAS,SAClB,QAAO;aACE,OAAO,SAAS,YAAY,UAAU,KAC/C,QAAO,KAAK;aACH,MAAM,QAAQ,KAAK,CAC5B,QAAO,KACJ,IAAI,CAAC,MAAM;AACV,SAAI,OAAO,MAAM,SACf,QAAO;cACE,OAAO,MAAM,YAAY,UAAU,EAC5C,QAAO,EAAE;AAEX,YAAO;IACR,EAAC,CACD,KAAK,IAAI;QAEZ,QAAO,KAAK,UAAU,KAAK;GAE9B,EAAC,CACD,KAAK,IAAI;EACb;EAID,MAAM,wBACJ,SAAS,WAAW,KACnB,SAAS,WAAW,KAAK,SAAS,MAAM,aAAa,WAAW;AACnE,MAAI,yBAAyB,KAAK,UAAU,GAC1C,KAAK,QAAQ;EAGf,MAAM,mBAAmB,KAAK,UAAU,KAAK,UAAU,CAAE;EACzD,MAAM,YAAY,KAAK,MAAM,UAAU;EAGvC,KAAK,SAAS,KAAK,QAAQ,KAAK,KAAK,IAAI,GAAG,KAAK,UAAU,OAAO;EAElE,MAAM,UAAU,IAAI,UAAU;GAC5B;GACA,IAAI;GACJ,YACE,iBAAiB,SAAS,IACtB,iBAAiB,IAAI,CAAC,QAAQ;IAC5B,GAAG;IACH,MAAM;GACP,GAAE,GACH;EACP;AAED,SAAO;GACL,aAAa,CACX;IACE,MAAM;IACN;GACD,CACF;GACD,WAAW,CAAE;EACd;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"utils.js","names":["value: number","tools: StructuredTool[]","_schema: any","messages: BaseMessage[]","_options?: this[\"ParsedCallOptions\"]","_runManager?: CallbackManagerForLLMRun"],"sources":["../../../src/agents/tests/utils.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { CallbackManagerForLLMRun } from \"@langchain/core/callbacks/manager\";\nimport {\n BaseChatModel,\n BaseChatModelParams,\n BaseChatModelCallOptions,\n BindToolsInput,\n ToolChoice,\n} from \"@langchain/core/language_models/chat_models\";\nimport { StructuredTool } from \"@langchain/core/tools\";\nimport {\n BaseMessage,\n AIMessage,\n HumanMessage,\n BaseMessageFields,\n AIMessageFields,\n ToolMessage,\n ToolMessageFields,\n} from \"@langchain/core/messages\";\nimport { ChatResult } from \"@langchain/core/outputs\";\nimport {\n Runnable,\n RunnableConfig,\n RunnableLambda,\n RunnableBinding,\n} from \"@langchain/core/runnables\";\nimport {\n MemorySaver,\n Checkpoint,\n CheckpointMetadata,\n type BaseCheckpointSaver,\n} from \"@langchain/langgraph-checkpoint\";\nimport { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { z } from \"zod/v3\";\n\n/**\n * Custom asymmetric matcher that matches any string value.\n * Works with both Jest and Vitest's toEqual() assertions.\n */\nclass AnyString {\n asymmetricMatch(other: unknown): boolean {\n return typeof other === \"string\";\n }\n\n toString(): string {\n return \"Any<String>\";\n }\n\n toAsymmetricMatcher(): string {\n return \"Any<String>\";\n }\n}\n\nexport class _AnyIdAIMessage extends AIMessage {\n get lc_id() {\n return [\"langchain_core\", \"messages\", \"AIMessage\"];\n }\n\n constructor(fields: AIMessageFields | string) {\n let fieldsWithJestMatcher: Partial<AIMessageFields> = {\n id: new AnyString() as unknown as string,\n };\n if (typeof fields === \"string\") {\n fieldsWithJestMatcher = {\n content: fields,\n ...fieldsWithJestMatcher,\n };\n } else {\n fieldsWithJestMatcher = {\n ...fields,\n ...fieldsWithJestMatcher,\n };\n }\n super(fieldsWithJestMatcher as AIMessageFields);\n }\n}\n\nexport class _AnyIdHumanMessage extends HumanMessage {\n get lc_id() {\n return [\"langchain_core\", \"messages\", \"HumanMessage\"];\n }\n\n constructor(fields: BaseMessageFields | string) {\n let fieldsWithJestMatcher: Partial<BaseMessageFields> = {\n id: new AnyString() as unknown as string,\n };\n if (typeof fields === \"string\") {\n fieldsWithJestMatcher = {\n content: fields,\n ...fieldsWithJestMatcher,\n };\n } else {\n fieldsWithJestMatcher = {\n ...fields,\n ...fieldsWithJestMatcher,\n };\n }\n super(fieldsWithJestMatcher as BaseMessageFields);\n }\n}\n\nexport class _AnyIdToolMessage extends ToolMessage {\n get lc_id() {\n return [\"langchain_core\", \"messages\", \"ToolMessage\"];\n }\n\n constructor(fields: ToolMessageFields) {\n const fieldsWithJestMatcher: Partial<ToolMessageFields> = {\n id: new AnyString() as unknown as string,\n ...fields,\n };\n super(fieldsWithJestMatcher as ToolMessageFields);\n }\n}\n\nexport class FakeConfigurableModel extends BaseChatModel {\n _queuedMethodOperations: Record<string, any> = {};\n\n _chatModel: LanguageModelLike;\n\n constructor(\n fields: {\n model: LanguageModelLike;\n } & BaseChatModelParams\n ) {\n super(fields);\n this._chatModel = fields.model;\n }\n\n _llmType() {\n return \"fake_configurable\";\n }\n\n async _generate(\n _messages: BaseMessage[],\n _options: this[\"ParsedCallOptions\"],\n _runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n throw new Error(\"Not implemented\");\n }\n\n async _model() {\n return this._chatModel;\n }\n\n bindTools(tools: BindToolsInput[]) {\n const modelWithTools = new FakeConfigurableModel({\n model: (this._chatModel as FakeToolCallingChatModel).bindTools(tools),\n });\n modelWithTools._queuedMethodOperations.bindTools = tools;\n return modelWithTools;\n }\n}\n\nexport class FakeToolCallingChatModel extends BaseChatModel {\n sleep?: number = 50;\n\n responses?: BaseMessage[];\n\n thrownErrorString?: string;\n\n idx: number;\n\n toolStyle: \"openai\" | \"anthropic\" | \"bedrock\" | \"google\" = \"openai\";\n\n structuredResponse?: Record<string, unknown>;\n\n // Track messages passed to structured output calls\n structuredOutputMessages: BaseMessage[][] = [];\n\n constructor(\n fields: {\n sleep?: number;\n responses?: BaseMessage[];\n thrownErrorString?: string;\n toolStyle?: \"openai\" | \"anthropic\" | \"bedrock\" | \"google\";\n structuredResponse?: Record<string, unknown>;\n } & BaseChatModelParams\n ) {\n super(fields);\n this.sleep = fields.sleep ?? this.sleep;\n this.responses = fields.responses;\n this.thrownErrorString = fields.thrownErrorString;\n this.idx = 0;\n this.toolStyle = fields.toolStyle ?? this.toolStyle;\n this.structuredResponse = fields.structuredResponse;\n this.structuredOutputMessages = [];\n }\n\n _llmType() {\n return \"fake\";\n }\n\n async _generate(\n messages: BaseMessage[],\n _options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n if (this.thrownErrorString) {\n throw new Error(this.thrownErrorString);\n }\n if (this.sleep !== undefined) {\n await new Promise((resolve) => setTimeout(resolve, this.sleep));\n }\n const responses = this.responses?.length ? this.responses : messages;\n const msg = responses[this.idx % responses.length];\n const generation: ChatResult = {\n generations: [\n {\n text: \"\",\n message: msg,\n },\n ],\n };\n this.idx += 1;\n\n if (typeof msg.content === \"string\") {\n await runManager?.handleLLMNewToken(msg.content);\n }\n return generation;\n }\n\n bindTools(tools: BindToolsInput[]): Runnable<any> {\n const toolDicts = [];\n const serverTools = [];\n for (const tool of tools) {\n if (!(\"name\" in tool)) {\n serverTools.push(tool);\n continue;\n }\n\n // NOTE: this is a simplified tool spec for testing purposes only\n if (this.toolStyle === \"openai\") {\n toolDicts.push({\n type: \"function\",\n function: {\n name: tool.name,\n },\n });\n } else if ([\"anthropic\", \"google\"].includes(this.toolStyle)) {\n toolDicts.push({\n name: tool.name,\n });\n } else if (this.toolStyle === \"bedrock\") {\n toolDicts.push({\n toolSpec: {\n name: tool.name,\n },\n });\n }\n }\n let toolsToBind: BindToolsInput[] = toolDicts;\n if (this.toolStyle === \"google\") {\n toolsToBind = [{ functionDeclarations: toolDicts }];\n }\n return this.withConfig({\n tools: [...toolsToBind, ...serverTools],\n } as BaseChatModelCallOptions);\n }\n\n withStructuredOutput<\n RunOutput extends Record<string, any> = Record<string, any>\n >(_: unknown): Runnable<any> {\n if (!this.structuredResponse) {\n throw new Error(\"No structured response provided\");\n }\n // Create a runnable that returns the proper structured format\n return RunnableLambda.from(async (messages: BaseMessage[]) => {\n if (this.sleep) {\n await new Promise((resolve) => setTimeout(resolve, this.sleep));\n }\n\n // Store the messages that were sent to generate structured output\n this.structuredOutputMessages.push([...messages]);\n\n // Return in the format expected: { raw: BaseMessage, parsed: RunOutput }\n return this.structuredResponse as RunOutput;\n });\n }\n}\n\nexport class MemorySaverAssertImmutable extends MemorySaver {\n storageForCopies: Record<string, Record<string, Uint8Array>> = {};\n\n constructor() {\n super();\n this.storageForCopies = {};\n }\n\n async put(\n config: RunnableConfig,\n checkpoint: Checkpoint,\n metadata: CheckpointMetadata\n ): Promise<RunnableConfig> {\n const thread_id = config.configurable?.thread_id;\n this.storageForCopies[thread_id] ??= {};\n\n // assert checkpoint hasn't been modified since last written\n const saved = await this.get(config);\n if (saved) {\n const savedId = saved.id;\n if (this.storageForCopies[thread_id][savedId]) {\n const [, serializedSaved] = await this.serde.dumpsTyped(saved);\n const serializedCopy = this.storageForCopies[thread_id][savedId];\n\n // Compare Uint8Array contents by converting to string\n const savedStr = new TextDecoder().decode(serializedSaved);\n const copyStr = new TextDecoder().decode(serializedCopy);\n if (savedStr !== copyStr) {\n throw new Error(\n `Checkpoint [${savedId}] has been modified since last written`\n );\n }\n }\n }\n const [, serializedCheckpoint] = await this.serde.dumpsTyped(checkpoint);\n // save a copy of the checkpoint\n this.storageForCopies[thread_id][checkpoint.id] = serializedCheckpoint;\n\n return super.put(config, checkpoint, metadata);\n }\n}\n\ninterface ToolCall {\n name: string;\n args: Record<string, any>;\n id: string;\n type?: \"tool_call\";\n}\n\ninterface FakeToolCallingModelFields {\n toolCalls?: ToolCall[][];\n toolStyle?: \"openai\" | \"anthropic\";\n index?: number;\n structuredResponse?: any;\n}\n\n// Helper function to create checkpointer\nexport function createCheckpointer(): BaseCheckpointSaver {\n return new MemorySaver();\n}\n\n/**\n * Fake chat model for testing tool calling functionality\n */\nexport class FakeToolCallingModel extends BaseChatModel {\n toolCalls: ToolCall[][];\n\n toolStyle: \"openai\" | \"anthropic\";\n\n // Use a shared reference object so the index persists across bindTools calls\n private indexRef: { current: number };\n\n structuredResponse?: any;\n\n private tools: StructuredTool[] = [];\n\n constructor({\n toolCalls = [],\n toolStyle = \"openai\",\n index = 0,\n structuredResponse,\n indexRef,\n ...rest\n }: FakeToolCallingModelFields & { indexRef?: { current: number } } = {}) {\n super(rest);\n this.toolCalls = toolCalls;\n this.toolStyle = toolStyle;\n // Share the same index reference across instances\n this.indexRef = indexRef ?? { current: index };\n this.structuredResponse = structuredResponse;\n }\n\n // Getter/setter for backwards compatibility\n get index(): number {\n return this.indexRef.current;\n }\n\n set index(value: number) {\n this.indexRef.current = value;\n }\n\n _llmType(): string {\n return \"fake-tool-calling\";\n }\n\n _combineLLMOutput() {\n return [];\n }\n\n bindTools(\n tools: StructuredTool[]\n ):\n | FakeToolCallingModel\n | RunnableBinding<\n any,\n any,\n any & { tool_choice?: ToolChoice | undefined }\n > {\n const newInstance = new FakeToolCallingModel({\n toolCalls: this.toolCalls,\n toolStyle: this.toolStyle,\n structuredResponse: this.structuredResponse,\n // Pass the same indexRef so all instances share the same index state\n indexRef: this.indexRef,\n });\n newInstance.tools = [...this.tools, ...tools];\n return newInstance;\n }\n\n withStructuredOutput(_schema: any) {\n return new RunnableLambda({\n func: async () => {\n return this.structuredResponse;\n },\n });\n }\n\n async _generate(\n messages: BaseMessage[],\n _options?: this[\"ParsedCallOptions\"],\n _runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n const lastMessage = messages[messages.length - 1];\n let content = lastMessage.content as string;\n\n // Handle prompt concatenation\n if (messages.length > 1) {\n const parts = messages.map((m) => m.content).filter(Boolean);\n content = parts\n .map((part) => {\n if (typeof part === \"string\") {\n return part;\n } else if (typeof part === \"object\" && \"text\" in part) {\n return part.text;\n } else if (Array.isArray(part)) {\n return part\n .map((p) => {\n if (typeof p === \"string\") {\n return p;\n } else if (typeof p === \"object\" && \"text\" in p) {\n return p.text;\n }\n return \"\";\n })\n .join(\"-\");\n } else {\n return JSON.stringify(part);\n }\n })\n .join(\"-\");\n }\n\n // Reset index at the start of a new conversation (only human message)\n // This allows the model to be reused across multiple agent.invoke() calls\n const isStartOfConversation =\n messages.length === 1 ||\n (messages.length === 2 && messages.every(HumanMessage.isInstance));\n if (isStartOfConversation && this.index !== 0) {\n this.index = 0;\n }\n\n const currentToolCalls = this.toolCalls[this.index] || [];\n const messageId = this.index.toString();\n\n // Move to next set of tool calls for subsequent invocations\n this.index = (this.index + 1) % Math.max(1, this.toolCalls.length);\n\n const message = new AIMessage({\n content,\n id: messageId,\n tool_calls:\n currentToolCalls.length > 0\n ? currentToolCalls.map((tc) => ({\n ...tc,\n type: \"tool_call\" as const,\n }))\n : undefined,\n });\n\n return {\n generations: [\n {\n text: content,\n message,\n },\n ],\n llmOutput: {},\n };\n }\n}\n\nexport class SearchAPI extends StructuredTool {\n name = \"search_api\";\n\n description = \"A simple API that returns the input string.\";\n\n schema = z.object({\n query: z.string().describe(\"The query to search for.\"),\n });\n\n async _call(input: z.infer<typeof this.schema>) {\n if (input?.query === \"error\") {\n throw new Error(\"Error\");\n }\n return `result for ${input?.query}`;\n }\n}\n"],"mappings":";;;;;;;;;;;AAyVA,IAAa,uBAAb,MAAa,6BAA6B,cAAc;CACtD;CAEA;CAGA,AAAQ;CAER;CAEA,AAAQ,QAA0B,CAAE;CAEpC,YAAY,EACV,YAAY,CAAE,GACd,YAAY,UACZ,QAAQ,GACR,oBACA,SACA,GAAG,MAC6D,GAAG,CAAE,GAAE;EACvE,MAAM,KAAK;EACX,KAAK,YAAY;EACjB,KAAK,YAAY;EAEjB,KAAK,WAAW,YAAY,EAAE,SAAS,MAAO;EAC9C,KAAK,qBAAqB;CAC3B;CAGD,IAAI,QAAgB;AAClB,SAAO,KAAK,SAAS;CACtB;CAED,IAAI,MAAMA,OAAe;EACvB,KAAK,SAAS,UAAU;CACzB;CAED,WAAmB;AACjB,SAAO;CACR;CAED,oBAAoB;AAClB,SAAO,CAAE;CACV;CAED,UACEC,OAOI;EACJ,MAAM,cAAc,IAAI,qBAAqB;GAC3C,WAAW,KAAK;GAChB,WAAW,KAAK;GAChB,oBAAoB,KAAK;GAEzB,UAAU,KAAK;EAChB;EACD,YAAY,QAAQ,CAAC,GAAG,KAAK,OAAO,GAAG,KAAM;AAC7C,SAAO;CACR;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3,7 @@ const require_chat_models_universal = require('./chat_models/universal.cjs');
|
|
|
3
3
|
const require_errors = require('./agents/errors.cjs');
|
|
4
4
|
const require_responses = require('./agents/responses.cjs');
|
|
5
5
|
const require_utils = require('./agents/middleware/utils.cjs');
|
|
6
|
+
const require_types = require('./agents/middleware/types.cjs');
|
|
6
7
|
const require_middleware = require('./agents/middleware.cjs');
|
|
7
8
|
const require_utils$1 = require('./agents/tests/utils.cjs');
|
|
8
9
|
const require_index = require('./agents/index.cjs');
|
|
@@ -43,6 +44,7 @@ require_rolldown_runtime.__export(src_exports, {
|
|
|
43
44
|
HumanMessage: () => __langchain_core_messages.HumanMessage,
|
|
44
45
|
HumanMessageChunk: () => __langchain_core_messages.HumanMessageChunk,
|
|
45
46
|
InMemoryStore: () => __langchain_core_stores.InMemoryStore,
|
|
47
|
+
MIDDLEWARE_BRAND: () => require_types.MIDDLEWARE_BRAND,
|
|
46
48
|
MultipleStructuredOutputsError: () => require_errors.MultipleStructuredOutputsError,
|
|
47
49
|
MultipleToolsBoundError: () => require_errors.MultipleToolsBoundError,
|
|
48
50
|
PIIDetectionError: () => require_pii.PIIDetectionError,
|
|
@@ -155,6 +157,7 @@ Object.defineProperty(exports, 'InMemoryStore', {
|
|
|
155
157
|
return __langchain_core_stores.InMemoryStore;
|
|
156
158
|
}
|
|
157
159
|
});
|
|
160
|
+
exports.MIDDLEWARE_BRAND = require_types.MIDDLEWARE_BRAND;
|
|
158
161
|
exports.MultipleStructuredOutputsError = require_errors.MultipleStructuredOutputsError;
|
|
159
162
|
exports.MultipleToolsBoundError = require_errors.MultipleToolsBoundError;
|
|
160
163
|
exports.PIIDetectionError = require_pii.PIIDetectionError;
|