langchain 1.0.0-alpha.2 → 1.0.0-alpha.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agents/ReactAgent.cjs +1 -1
- package/dist/agents/ReactAgent.cjs.map +1 -1
- package/dist/agents/ReactAgent.d.cts +3 -3
- package/dist/agents/ReactAgent.d.cts.map +1 -1
- package/dist/agents/ReactAgent.d.ts +3 -3
- package/dist/agents/ReactAgent.d.ts.map +1 -1
- package/dist/agents/ReactAgent.js +2 -2
- package/dist/agents/ReactAgent.js.map +1 -1
- package/dist/agents/annotation.cjs +122 -2
- package/dist/agents/annotation.cjs.map +1 -1
- package/dist/agents/annotation.d.cts +18 -14
- package/dist/agents/annotation.d.cts.map +1 -1
- package/dist/agents/annotation.d.ts +18 -14
- package/dist/agents/annotation.d.ts.map +1 -1
- package/dist/agents/annotation.js +121 -2
- package/dist/agents/annotation.js.map +1 -1
- package/dist/agents/errors.cjs +1 -1
- package/dist/agents/errors.cjs.map +1 -1
- package/dist/agents/errors.js +1 -1
- package/dist/agents/errors.js.map +1 -1
- package/dist/agents/index.cjs +2 -2
- package/dist/agents/index.cjs.map +1 -1
- package/dist/agents/index.d.cts +15 -15
- package/dist/agents/index.d.cts.map +1 -1
- package/dist/agents/index.d.ts +15 -15
- package/dist/agents/index.d.ts.map +1 -1
- package/dist/agents/index.js +2 -2
- package/dist/agents/index.js.map +1 -1
- package/dist/agents/nodes/AgentNode.cjs +8 -3
- package/dist/agents/nodes/AgentNode.cjs.map +1 -1
- package/dist/agents/nodes/AgentNode.js +8 -3
- package/dist/agents/nodes/AgentNode.js.map +1 -1
- package/dist/agents/nodes/ToolNode.cjs +2 -2
- package/dist/agents/nodes/ToolNode.cjs.map +1 -1
- package/dist/agents/nodes/ToolNode.d.cts +1 -1
- package/dist/agents/nodes/ToolNode.d.cts.map +1 -1
- package/dist/agents/nodes/ToolNode.d.ts +1 -1
- package/dist/agents/nodes/ToolNode.d.ts.map +1 -1
- package/dist/agents/nodes/ToolNode.js +2 -2
- package/dist/agents/nodes/ToolNode.js.map +1 -1
- package/dist/agents/responses.cjs +2 -3
- package/dist/agents/responses.cjs.map +1 -1
- package/dist/agents/responses.d.cts +6 -1
- package/dist/agents/responses.d.cts.map +1 -1
- package/dist/agents/responses.d.ts +6 -1
- package/dist/agents/responses.d.ts.map +1 -1
- package/dist/agents/responses.js +2 -3
- package/dist/agents/responses.js.map +1 -1
- package/dist/agents/types.d.cts +28 -10
- package/dist/agents/types.d.cts.map +1 -1
- package/dist/agents/types.d.ts +28 -10
- package/dist/agents/types.d.ts.map +1 -1
- package/dist/agents/utils.cjs +1 -1
- package/dist/agents/utils.cjs.map +1 -1
- package/dist/agents/utils.js +1 -1
- package/dist/agents/utils.js.map +1 -1
- package/dist/agents/withAgentName.cjs +1 -1
- package/dist/agents/withAgentName.cjs.map +1 -1
- package/dist/agents/withAgentName.js +1 -1
- package/dist/agents/withAgentName.js.map +1 -1
- package/dist/evaluation/agents/trajectory.d.cts.map +1 -1
- package/dist/evaluation/agents/trajectory.d.ts.map +1 -1
- package/dist/evaluation/comparison/pairwise.d.cts.map +1 -1
- package/dist/evaluation/comparison/pairwise.d.ts.map +1 -1
- package/dist/evaluation/criteria/criteria.d.cts.map +1 -1
- package/dist/evaluation/criteria/criteria.d.ts.map +1 -1
- package/dist/index.cjs +52 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +12 -5
- package/dist/index.js.map +1 -1
- package/package.json +6 -6
package/dist/agents/index.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { MultipleStructuredOutputsError, StructuredOutputParsingError } from "./
|
|
|
2
2
|
import { JsonSchemaFormat, ProviderStrategy, ResponseFormat, ResponseFormatUndefined, ToolStrategy, TypedToolStrategy, providerStrategy, toolStrategy } from "./responses.js";
|
|
3
3
|
import { AnyAnnotationRoot } from "./annotation.js";
|
|
4
4
|
import { ToolNode } from "./nodes/ToolNode.js";
|
|
5
|
-
import { AgentState, ClientTool,
|
|
5
|
+
import { AgentRuntime, AgentState, ClientTool, CreateAgentParams, ExtractZodArrayTypes, N, Prompt, ServerTool } from "./types.js";
|
|
6
6
|
import { ReactAgent } from "./ReactAgent.js";
|
|
7
7
|
import { ActionRequest, HumanInterrupt, HumanInterruptConfig, HumanResponse } from "./interrupt.js";
|
|
8
8
|
import { MessagesAnnotation } from "@langchain/langgraph";
|
|
@@ -16,7 +16,7 @@ import { InteropZodObject, InteropZodType } from "@langchain/core/utils/types";
|
|
|
16
16
|
* @example
|
|
17
17
|
* ```ts
|
|
18
18
|
* import { ChatOpenAI } from "@langchain/openai";
|
|
19
|
-
* import {
|
|
19
|
+
* import { createAgent, tool } from "langchain";
|
|
20
20
|
* import { z } from "zod";
|
|
21
21
|
*
|
|
22
22
|
* const model = new ChatOpenAI({
|
|
@@ -37,7 +37,7 @@ import { InteropZodObject, InteropZodType } from "@langchain/core/utils/types";
|
|
|
37
37
|
* })
|
|
38
38
|
* })
|
|
39
39
|
*
|
|
40
|
-
* const agent =
|
|
40
|
+
* const agent = createAgent({ llm: model, tools: [getWeather] });
|
|
41
41
|
*
|
|
42
42
|
* const inputs = {
|
|
43
43
|
* messages: [{ role: "user", content: "what is the weather in SF?" }],
|
|
@@ -52,47 +52,47 @@ import { InteropZodObject, InteropZodType } from "@langchain/core/utils/types";
|
|
|
52
52
|
* ```
|
|
53
53
|
*/
|
|
54
54
|
// Overload 1: With responseFormat as single InteropZodType
|
|
55
|
-
declare function
|
|
55
|
+
declare function createAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject = typeof MessagesAnnotation, T extends Record<string, any> = Record<string, any>, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot>(params: CreateAgentParams<StateSchema, T, ContextSchema, InteropZodType<T>> & {
|
|
56
56
|
responseFormat: InteropZodType<T>;
|
|
57
57
|
}): ReactAgent<StateSchema, T, ContextSchema>;
|
|
58
58
|
// Overload 2: With responseFormat as array of InteropZodTypes (infers union type)
|
|
59
|
-
declare function
|
|
59
|
+
declare function createAgent<T extends readonly InteropZodType<any>[], StateSchema extends AnyAnnotationRoot | InteropZodObject = typeof MessagesAnnotation, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot>(params: CreateAgentParams<StateSchema, ExtractZodArrayTypes<T> extends Record<string, any> ? ExtractZodArrayTypes<T> : Record<string, any>, ContextSchema, T> & {
|
|
60
60
|
responseFormat: T;
|
|
61
61
|
}): ReactAgent<StateSchema, ExtractZodArrayTypes<T> extends Record<string, any> ? ExtractZodArrayTypes<T> : Record<string, any>, ContextSchema>;
|
|
62
62
|
// Overload 3: With responseFormat as JsonSchemaFormat (JSON schema object)
|
|
63
|
-
declare function
|
|
63
|
+
declare function createAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject = typeof MessagesAnnotation, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot>(params: CreateAgentParams<StateSchema, Record<string, unknown>, ContextSchema, JsonSchemaFormat> & {
|
|
64
64
|
responseFormat: JsonSchemaFormat;
|
|
65
65
|
}): ReactAgent<StateSchema, Record<string, unknown>, ContextSchema>;
|
|
66
66
|
// Overload 4: With responseFormat as array of JsonSchemaFormat (JSON schema objects)
|
|
67
|
-
declare function
|
|
67
|
+
declare function createAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject = typeof MessagesAnnotation, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot>(params: CreateAgentParams<StateSchema, Record<string, unknown>, ContextSchema, JsonSchemaFormat[]> & {
|
|
68
68
|
responseFormat: JsonSchemaFormat[];
|
|
69
69
|
}): ReactAgent<StateSchema, Record<string, unknown>, ContextSchema>;
|
|
70
70
|
// Overload 4.5: With responseFormat as union of JsonSchemaFormat | JsonSchemaFormat[]
|
|
71
|
-
declare function
|
|
71
|
+
declare function createAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject = typeof MessagesAnnotation, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot>(params: CreateAgentParams<StateSchema, Record<string, unknown>, ContextSchema, JsonSchemaFormat | JsonSchemaFormat[]> & {
|
|
72
72
|
responseFormat: JsonSchemaFormat | JsonSchemaFormat[];
|
|
73
73
|
}): ReactAgent<StateSchema, Record<string, unknown>, ContextSchema>;
|
|
74
74
|
// Overload 5: With responseFormat as TypedToolStrategy (for union types from toolStrategy)
|
|
75
|
-
declare function
|
|
75
|
+
declare function createAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject = typeof MessagesAnnotation, T extends Record<string, any> = Record<string, any>, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot>(params: CreateAgentParams<StateSchema, T, ContextSchema, TypedToolStrategy<T>> & {
|
|
76
76
|
responseFormat: TypedToolStrategy<T>;
|
|
77
77
|
}): ReactAgent<StateSchema, T, ContextSchema>;
|
|
78
78
|
// Overload 6: With responseFormat as single ToolStrategy instance
|
|
79
|
-
declare function
|
|
79
|
+
declare function createAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject = typeof MessagesAnnotation, T extends Record<string, any> = Record<string, any>, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot>(params: CreateAgentParams<StateSchema, T, ContextSchema, ToolStrategy<T>> & {
|
|
80
80
|
responseFormat: ToolStrategy<T>;
|
|
81
81
|
}): ReactAgent<StateSchema, T, ContextSchema>;
|
|
82
82
|
// Overload 7: With responseFormat as ProviderStrategy
|
|
83
|
-
declare function
|
|
83
|
+
declare function createAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject = typeof MessagesAnnotation, T extends Record<string, any> = Record<string, any>, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot>(params: CreateAgentParams<StateSchema, T, ContextSchema, ProviderStrategy<T>> & {
|
|
84
84
|
responseFormat: ProviderStrategy<T>;
|
|
85
85
|
}): ReactAgent<StateSchema, T, ContextSchema>;
|
|
86
86
|
// Overload 8: Without responseFormat property at all
|
|
87
|
-
declare function
|
|
87
|
+
declare function createAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject = typeof MessagesAnnotation, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot>(params: Omit<CreateAgentParams<StateSchema, ResponseFormatUndefined, ContextSchema, never>, "responseFormat">): ReactAgent<StateSchema, ResponseFormatUndefined, ContextSchema>;
|
|
88
88
|
// Overload 9: With responseFormat explicitly undefined
|
|
89
|
-
declare function
|
|
89
|
+
declare function createAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject = typeof MessagesAnnotation, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot>(params: Omit<CreateAgentParams<StateSchema, ResponseFormatUndefined, ContextSchema, never>, "responseFormat"> & {
|
|
90
90
|
responseFormat?: undefined;
|
|
91
91
|
}): ReactAgent<StateSchema, ResponseFormatUndefined, ContextSchema>;
|
|
92
92
|
// Overload 10: For other ResponseFormat values (failsafe)
|
|
93
|
-
declare function
|
|
93
|
+
declare function createAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject = typeof MessagesAnnotation, StructuredResponseFormat extends Record<string, any> = Record<string, any>, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot>(params: CreateAgentParams<StateSchema, StructuredResponseFormat, ContextSchema, ResponseFormat> & {
|
|
94
94
|
responseFormat: ResponseFormat;
|
|
95
95
|
}): ReactAgent<StateSchema, StructuredResponseFormat, ContextSchema>;
|
|
96
96
|
//#endregion
|
|
97
|
-
export {
|
|
97
|
+
export { createAgent };
|
|
98
98
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":["InteropZodObject","InteropZodType","MessagesAnnotation","AnyAnnotationRoot","CreateReactAgentParams","ExtractZodArrayTypes","ToolStrategy","TypedToolStrategy","ProviderStrategy","ResponseFormat","ResponseFormatUndefined","JsonSchemaFormat","ReactAgent","createReactAgent","Record","StateSchema","T","ContextSchema","Omit","StructuredResponseFormat","ToolNode","toolStrategy","providerStrategy"],"sources":["../../src/agents/index.d.ts"],"sourcesContent":["import type { InteropZodObject, InteropZodType } from \"@langchain/core/utils/types\";\nimport { MessagesAnnotation } from \"@langchain/langgraph\";\nimport { type AnyAnnotationRoot } from \"./annotation.js\";\nimport type { CreateReactAgentParams, ExtractZodArrayTypes } from \"./types.js\";\nimport type { ToolStrategy, TypedToolStrategy, ProviderStrategy, ResponseFormat, ResponseFormatUndefined, JsonSchemaFormat } from \"./responses.js\";\nimport { ReactAgent } from \"./ReactAgent.js\";\n/**\n * Creates a StateGraph agent that relies on a chat model utilizing tool calling.\n *\n * @example\n * ```ts\n * import { ChatOpenAI } from \"@langchain/openai\";\n * import { createReactAgent, tool } from \"langchain\";\n * import { z } from \"zod\";\n *\n * const model = new ChatOpenAI({\n * model: \"gpt-4o\",\n * });\n *\n * const getWeather = tool((input) => {\n * if ([\"sf\", \"san francisco\"].includes(input.location.toLowerCase())) {\n * return \"It's 60 degrees and foggy.\";\n * } else {\n * return \"It's 90 degrees and sunny.\";\n * }\n * }, {\n * name: \"get_weather\",\n * description: \"Call to get the current weather.\",\n * schema: z.object({\n * location: z.string().describe(\"Location to get the weather for.\"),\n * })\n * })\n *\n * const agent = createReactAgent({ llm: model, tools: [getWeather] });\n *\n * const inputs = {\n * messages: [{ role: \"user\", content: \"what is the weather in SF?\" }],\n * };\n *\n * const stream = await agent.stream(inputs, { streamMode: \"values\" });\n *\n * for await (const { messages } of stream) {\n * console.log(messages);\n * }\n * // Returns the messages in the state at each step of execution\n * ```\n */\n// Overload 1: With responseFormat as single InteropZodType\nexport declare function createReactAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject = typeof MessagesAnnotation, T extends Record<string, any> = Record<string, any>, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot>(params: CreateReactAgentParams<StateSchema, T, ContextSchema, InteropZodType<T>> & {\n responseFormat: InteropZodType<T>;\n}): ReactAgent<StateSchema, T, ContextSchema>;\n// Overload 2: With responseFormat as array of InteropZodTypes (infers union type)\nexport declare function createReactAgent<T extends readonly InteropZodType<any>[], StateSchema extends AnyAnnotationRoot | InteropZodObject = typeof MessagesAnnotation, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot>(params: CreateReactAgentParams<StateSchema, ExtractZodArrayTypes<T> extends Record<string, any> ? ExtractZodArrayTypes<T> : Record<string, any>, ContextSchema, T> & {\n responseFormat: T;\n}): ReactAgent<StateSchema, ExtractZodArrayTypes<T> extends Record<string, any> ? ExtractZodArrayTypes<T> : Record<string, any>, ContextSchema>;\n// Overload 3: With responseFormat as JsonSchemaFormat (JSON schema object)\nexport declare function createReactAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject = typeof MessagesAnnotation, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot>(params: CreateReactAgentParams<StateSchema, Record<string, unknown>, ContextSchema, JsonSchemaFormat> & {\n responseFormat: JsonSchemaFormat;\n}): ReactAgent<StateSchema, Record<string, unknown>, ContextSchema>;\n// Overload 4: With responseFormat as array of JsonSchemaFormat (JSON schema objects)\nexport declare function createReactAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject = typeof MessagesAnnotation, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot>(params: CreateReactAgentParams<StateSchema, Record<string, unknown>, ContextSchema, JsonSchemaFormat[]> & {\n responseFormat: JsonSchemaFormat[];\n}): ReactAgent<StateSchema, Record<string, unknown>, ContextSchema>;\n// Overload 4.5: With responseFormat as union of JsonSchemaFormat | JsonSchemaFormat[]\nexport declare function createReactAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject = typeof MessagesAnnotation, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot>(params: CreateReactAgentParams<StateSchema, Record<string, unknown>, ContextSchema, JsonSchemaFormat | JsonSchemaFormat[]> & {\n responseFormat: JsonSchemaFormat | JsonSchemaFormat[];\n}): ReactAgent<StateSchema, Record<string, unknown>, ContextSchema>;\n// Overload 5: With responseFormat as TypedToolStrategy (for union types from toolStrategy)\nexport declare function createReactAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject = typeof MessagesAnnotation, T extends Record<string, any> = Record<string, any>, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot>(params: CreateReactAgentParams<StateSchema, T, ContextSchema, TypedToolStrategy<T>> & {\n responseFormat: TypedToolStrategy<T>;\n}): ReactAgent<StateSchema, T, ContextSchema>;\n// Overload 6: With responseFormat as single ToolStrategy instance\nexport declare function createReactAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject = typeof MessagesAnnotation, T extends Record<string, any> = Record<string, any>, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot>(params: CreateReactAgentParams<StateSchema, T, ContextSchema, ToolStrategy<T>> & {\n responseFormat: ToolStrategy<T>;\n}): ReactAgent<StateSchema, T, ContextSchema>;\n// Overload 7: With responseFormat as ProviderStrategy\nexport declare function createReactAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject = typeof MessagesAnnotation, T extends Record<string, any> = Record<string, any>, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot>(params: CreateReactAgentParams<StateSchema, T, ContextSchema, ProviderStrategy<T>> & {\n responseFormat: ProviderStrategy<T>;\n}): ReactAgent<StateSchema, T, ContextSchema>;\n// Overload 8: Without responseFormat property at all\nexport declare function createReactAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject = typeof MessagesAnnotation, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot>(params: Omit<CreateReactAgentParams<StateSchema, ResponseFormatUndefined, ContextSchema, never>, \"responseFormat\">): ReactAgent<StateSchema, ResponseFormatUndefined, ContextSchema>;\n// Overload 9: With responseFormat explicitly undefined\nexport declare function createReactAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject = typeof MessagesAnnotation, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot>(params: Omit<CreateReactAgentParams<StateSchema, ResponseFormatUndefined, ContextSchema, never>, \"responseFormat\"> & {\n responseFormat?: undefined;\n}): ReactAgent<StateSchema, ResponseFormatUndefined, ContextSchema>;\n// Overload 10: For other ResponseFormat values (failsafe)\nexport declare function createReactAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject = typeof MessagesAnnotation, StructuredResponseFormat extends Record<string, any> = Record<string, any>, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot>(params: CreateReactAgentParams<StateSchema, StructuredResponseFormat, ContextSchema, ResponseFormat> & {\n responseFormat: ResponseFormat;\n}): ReactAgent<StateSchema, StructuredResponseFormat, ContextSchema>;\nexport * from \"./types.js\";\nexport * from \"./errors.js\";\nexport * from \"./interrupt.js\";\nexport { ToolNode } from \"./nodes/ToolNode.js\";\nexport { toolStrategy, providerStrategy, ToolStrategy, ProviderStrategy, type ResponseFormat, } from \"./responses.js\";\n"],"mappings":";;;;;;;;;;;;;;;;;AAgDA;;;;;;;;;;;;;;;;;;;;;;AAEc;AAEd;;;;;;;;;;;;;;AAA2VK,iBAJnUQ,gBAImUR,CAAAA,oBAJ9RF,iBAI8RE,GAJ1QL,gBAI0QK,GAAAA,OAJhPH,kBAIgPG,EAAAA,UAJlNS,MAIkNT,CAAAA,MAAAA,EAAAA,GAAAA,CAAAA,GAJ5LS,MAI4LT,CAAAA,MAAAA,EAAAA,GAAAA,CAAAA,EAAAA,sBAJjJF,iBAIiJE,GAJ7HL,gBAI6HK,GAJ1GF,iBAI0GE,CAAAA,CAAAA,MAAAA,EAJ/ED,sBAI+EC,CAJxDU,WAIwDV,EAJ3CW,CAI2CX,EAJxCY,aAIwCZ,EAJzBJ,cAIyBI,CAJVW,CAIUX,CAAAA,CAAAA,GAAAA;EAAoB,cAAMS,EAHjWb,cAGiWa,CAHlVE,CAGkVF,CAAAA;CAAM,CAAA,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wBaO,aAxBb,CAAA;;AAAyCjB,iBA0BzDa,gBA1ByDb,CAAAA,oBA0BpBG,iBA1BoBH,GA0BAA,gBA1BAA,GAAAA,OA0B0BE,kBA1B1BF,EAAAA,iCA0B+Ec,MA1B/Ed,CAAAA,MAAAA,EAAAA,GAAAA,CAAAA,GA0BqGc,MA1BrGd,CAAAA,MAAAA,EAAAA,GAAAA,CAAAA,EAAAA,sBA0BgJG,iBA1BhJH,GA0BoKA,gBA1BpKA,GA0BuLG,iBA1BvLH,CAAAA,CAAAA,MAAAA,EA0BkNI,sBA1BlNJ,CA0ByOe,WA1BzOf,EA0BsPmB,wBA1BtPnB,EA0BgRiB,aA1BhRjB,EA0B+RS,cA1B/RT,CAAAA,GAAAA;EAAgB,cAAUE,EA2BvFO,cA3BuFP;CAAkB,CAAA,EA4BzHU,UA5BiJT,CA4BtIY,WA5BsIZ,EA4BzHgB,wBA5ByHhB,EA4B/Fc,aA5B+Fd,CAAAA"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":["InteropZodObject","InteropZodType","MessagesAnnotation","AnyAnnotationRoot","CreateAgentParams","ExtractZodArrayTypes","ToolStrategy","TypedToolStrategy","ProviderStrategy","ResponseFormat","ResponseFormatUndefined","JsonSchemaFormat","ReactAgent","createAgent","Record","StateSchema","T","ContextSchema","Omit","StructuredResponseFormat","ToolNode","toolStrategy","providerStrategy"],"sources":["../../src/agents/index.d.ts"],"sourcesContent":["import type { InteropZodObject, InteropZodType } from \"@langchain/core/utils/types\";\nimport { MessagesAnnotation } from \"@langchain/langgraph\";\nimport { type AnyAnnotationRoot } from \"./annotation.js\";\nimport type { CreateAgentParams, ExtractZodArrayTypes } from \"./types.js\";\nimport type { ToolStrategy, TypedToolStrategy, ProviderStrategy, ResponseFormat, ResponseFormatUndefined, JsonSchemaFormat } from \"./responses.js\";\nimport { ReactAgent } from \"./ReactAgent.js\";\n/**\n * Creates a StateGraph agent that relies on a chat model utilizing tool calling.\n *\n * @example\n * ```ts\n * import { ChatOpenAI } from \"@langchain/openai\";\n * import { createAgent, tool } from \"langchain\";\n * import { z } from \"zod\";\n *\n * const model = new ChatOpenAI({\n * model: \"gpt-4o\",\n * });\n *\n * const getWeather = tool((input) => {\n * if ([\"sf\", \"san francisco\"].includes(input.location.toLowerCase())) {\n * return \"It's 60 degrees and foggy.\";\n * } else {\n * return \"It's 90 degrees and sunny.\";\n * }\n * }, {\n * name: \"get_weather\",\n * description: \"Call to get the current weather.\",\n * schema: z.object({\n * location: z.string().describe(\"Location to get the weather for.\"),\n * })\n * })\n *\n * const agent = createAgent({ llm: model, tools: [getWeather] });\n *\n * const inputs = {\n * messages: [{ role: \"user\", content: \"what is the weather in SF?\" }],\n * };\n *\n * const stream = await agent.stream(inputs, { streamMode: \"values\" });\n *\n * for await (const { messages } of stream) {\n * console.log(messages);\n * }\n * // Returns the messages in the state at each step of execution\n * ```\n */\n// Overload 1: With responseFormat as single InteropZodType\nexport declare function createAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject = typeof MessagesAnnotation, T extends Record<string, any> = Record<string, any>, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot>(params: CreateAgentParams<StateSchema, T, ContextSchema, InteropZodType<T>> & {\n responseFormat: InteropZodType<T>;\n}): ReactAgent<StateSchema, T, ContextSchema>;\n// Overload 2: With responseFormat as array of InteropZodTypes (infers union type)\nexport declare function createAgent<T extends readonly InteropZodType<any>[], StateSchema extends AnyAnnotationRoot | InteropZodObject = typeof MessagesAnnotation, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot>(params: CreateAgentParams<StateSchema, ExtractZodArrayTypes<T> extends Record<string, any> ? ExtractZodArrayTypes<T> : Record<string, any>, ContextSchema, T> & {\n responseFormat: T;\n}): ReactAgent<StateSchema, ExtractZodArrayTypes<T> extends Record<string, any> ? ExtractZodArrayTypes<T> : Record<string, any>, ContextSchema>;\n// Overload 3: With responseFormat as JsonSchemaFormat (JSON schema object)\nexport declare function createAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject = typeof MessagesAnnotation, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot>(params: CreateAgentParams<StateSchema, Record<string, unknown>, ContextSchema, JsonSchemaFormat> & {\n responseFormat: JsonSchemaFormat;\n}): ReactAgent<StateSchema, Record<string, unknown>, ContextSchema>;\n// Overload 4: With responseFormat as array of JsonSchemaFormat (JSON schema objects)\nexport declare function createAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject = typeof MessagesAnnotation, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot>(params: CreateAgentParams<StateSchema, Record<string, unknown>, ContextSchema, JsonSchemaFormat[]> & {\n responseFormat: JsonSchemaFormat[];\n}): ReactAgent<StateSchema, Record<string, unknown>, ContextSchema>;\n// Overload 4.5: With responseFormat as union of JsonSchemaFormat | JsonSchemaFormat[]\nexport declare function createAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject = typeof MessagesAnnotation, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot>(params: CreateAgentParams<StateSchema, Record<string, unknown>, ContextSchema, JsonSchemaFormat | JsonSchemaFormat[]> & {\n responseFormat: JsonSchemaFormat | JsonSchemaFormat[];\n}): ReactAgent<StateSchema, Record<string, unknown>, ContextSchema>;\n// Overload 5: With responseFormat as TypedToolStrategy (for union types from toolStrategy)\nexport declare function createAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject = typeof MessagesAnnotation, T extends Record<string, any> = Record<string, any>, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot>(params: CreateAgentParams<StateSchema, T, ContextSchema, TypedToolStrategy<T>> & {\n responseFormat: TypedToolStrategy<T>;\n}): ReactAgent<StateSchema, T, ContextSchema>;\n// Overload 6: With responseFormat as single ToolStrategy instance\nexport declare function createAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject = typeof MessagesAnnotation, T extends Record<string, any> = Record<string, any>, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot>(params: CreateAgentParams<StateSchema, T, ContextSchema, ToolStrategy<T>> & {\n responseFormat: ToolStrategy<T>;\n}): ReactAgent<StateSchema, T, ContextSchema>;\n// Overload 7: With responseFormat as ProviderStrategy\nexport declare function createAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject = typeof MessagesAnnotation, T extends Record<string, any> = Record<string, any>, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot>(params: CreateAgentParams<StateSchema, T, ContextSchema, ProviderStrategy<T>> & {\n responseFormat: ProviderStrategy<T>;\n}): ReactAgent<StateSchema, T, ContextSchema>;\n// Overload 8: Without responseFormat property at all\nexport declare function createAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject = typeof MessagesAnnotation, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot>(params: Omit<CreateAgentParams<StateSchema, ResponseFormatUndefined, ContextSchema, never>, \"responseFormat\">): ReactAgent<StateSchema, ResponseFormatUndefined, ContextSchema>;\n// Overload 9: With responseFormat explicitly undefined\nexport declare function createAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject = typeof MessagesAnnotation, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot>(params: Omit<CreateAgentParams<StateSchema, ResponseFormatUndefined, ContextSchema, never>, \"responseFormat\"> & {\n responseFormat?: undefined;\n}): ReactAgent<StateSchema, ResponseFormatUndefined, ContextSchema>;\n// Overload 10: For other ResponseFormat values (failsafe)\nexport declare function createAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject = typeof MessagesAnnotation, StructuredResponseFormat extends Record<string, any> = Record<string, any>, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot>(params: CreateAgentParams<StateSchema, StructuredResponseFormat, ContextSchema, ResponseFormat> & {\n responseFormat: ResponseFormat;\n}): ReactAgent<StateSchema, StructuredResponseFormat, ContextSchema>;\nexport * from \"./types.js\";\nexport * from \"./errors.js\";\nexport * from \"./interrupt.js\";\nexport { ToolNode } from \"./nodes/ToolNode.js\";\nexport { toolStrategy, providerStrategy, ToolStrategy, ProviderStrategy, type ResponseFormat, } from \"./responses.js\";\n"],"mappings":";;;;;;;;;;;;;;;;;AAgDA;;;;;;;;;;;;;;;;;;;;;;AAEc;AAEd;;;;;;;;;;;;;;AAAiVK,iBAJzTQ,WAIyTR,CAAAA,oBAJzRF,iBAIyRE,GAJrQL,gBAIqQK,GAAAA,OAJ3OH,kBAI2OG,EAAAA,UAJ7MS,MAI6MT,CAAAA,MAAAA,EAAAA,GAAAA,CAAAA,GAJvLS,MAIuLT,CAAAA,MAAAA,EAAAA,GAAAA,CAAAA,EAAAA,sBAJ5IF,iBAI4IE,GAJxHL,gBAIwHK,GAJrGF,iBAIqGE,CAAAA,CAAAA,MAAAA,EAJ1ED,iBAI0EC,CAJxDU,WAIwDV,EAJ3CW,CAI2CX,EAJxCY,aAIwCZ,EAJzBJ,cAIyBI,CAJVW,CAIUX,CAAAA,CAAAA,GAAAA;EAAoB,cAAMS,EAHvVb,cAGuVa,CAHxUE,CAGwUF,CAAAA;CAAM,CAAA,EAF7WF,UAE4XK,CAFjXF,WAEiXE,EAFpWD,CAEoWC,EAFjWA,aAEiWA,CAAAA;;AAApIb,iBAApOS,WAAoOT,CAAAA,UAAAA,SAArMH,cAAqMG,CAAAA,GAAAA,CAAAA,EAAAA,EAAAA,oBAA1JD,iBAA0JC,GAAtIJ,gBAAsII,GAAAA,OAA5GF,kBAA4GE,EAAAA,sBAAlED,iBAAkEC,GAA9CJ,gBAA8CI,GAA3BD,iBAA2BC,CAAAA,CAAAA,MAAAA,EAAAA,iBAAAA,CAAkBW,WAAlBX,EAA+BC,oBAA/BD,CAAoDY,CAApDZ,CAAAA,SAA+DU,MAA/DV,CAAAA,MAAAA,EAAAA,GAAAA,CAAAA,GAAqFC,oBAArFD,CAA0GY,CAA1GZ,CAAAA,GAA+GU,MAA/GV,CAAAA,MAAAA,EAAAA,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Z,EA4BpHgB,wBA5BoHhB,EA4B1Fc,aA5B0Fd,CAAAA"}
|
package/dist/agents/index.js
CHANGED
|
@@ -5,10 +5,10 @@ import { ReactAgent } from "./ReactAgent.js";
|
|
|
5
5
|
import "./interrupt.js";
|
|
6
6
|
|
|
7
7
|
//#region src/agents/index.ts
|
|
8
|
-
function
|
|
8
|
+
function createAgent(params) {
|
|
9
9
|
return new ReactAgent(params);
|
|
10
10
|
}
|
|
11
11
|
|
|
12
12
|
//#endregion
|
|
13
|
-
export {
|
|
13
|
+
export { createAgent };
|
|
14
14
|
//# sourceMappingURL=index.js.map
|
package/dist/agents/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["params:
|
|
1
|
+
{"version":3,"file":"index.js","names":["params: CreateAgentParams<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema,\n any\n >"],"sources":["../../src/agents/index.ts"],"sourcesContent":["import type {\n InteropZodObject,\n InteropZodType,\n} from \"@langchain/core/utils/types\";\n\nimport { MessagesAnnotation } from \"@langchain/langgraph\";\n\nimport { type AnyAnnotationRoot } from \"./annotation.js\";\nimport type { CreateAgentParams, ExtractZodArrayTypes } from \"./types.js\";\nimport type {\n ToolStrategy,\n TypedToolStrategy,\n ProviderStrategy,\n ResponseFormat,\n ResponseFormatUndefined,\n JsonSchemaFormat,\n} from \"./responses.js\";\nimport { ReactAgent } from \"./ReactAgent.js\";\n\n/**\n * Creates a StateGraph agent that relies on a chat model utilizing tool calling.\n *\n * @example\n * ```ts\n * import { ChatOpenAI } from \"@langchain/openai\";\n * import { createAgent, tool } from \"langchain\";\n * import { z } from \"zod\";\n *\n * const model = new ChatOpenAI({\n * model: \"gpt-4o\",\n * });\n *\n * const getWeather = tool((input) => {\n * if ([\"sf\", \"san francisco\"].includes(input.location.toLowerCase())) {\n * return \"It's 60 degrees and foggy.\";\n * } else {\n * return \"It's 90 degrees and sunny.\";\n * }\n * }, {\n * name: \"get_weather\",\n * description: \"Call to get the current weather.\",\n * schema: z.object({\n * location: z.string().describe(\"Location to get the weather for.\"),\n * })\n * })\n *\n * const agent = createAgent({ llm: model, tools: [getWeather] });\n *\n * const inputs = {\n * messages: [{ role: \"user\", content: \"what is the weather in SF?\" }],\n * };\n *\n * const stream = await agent.stream(inputs, { streamMode: \"values\" });\n *\n * for await (const { messages } of stream) {\n * console.log(messages);\n * }\n * // Returns the messages in the state at each step of execution\n * ```\n */\n// Overload 1: With responseFormat as single InteropZodType\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = typeof MessagesAnnotation,\n T extends Record<string, any> = Record<string, any>,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n>(\n params: CreateAgentParams<\n StateSchema,\n T,\n ContextSchema,\n InteropZodType<T>\n > & {\n responseFormat: InteropZodType<T>;\n }\n): ReactAgent<StateSchema, T, ContextSchema>;\n\n// Overload 2: With responseFormat as array of InteropZodTypes (infers union type)\nexport function createAgent<\n T extends readonly InteropZodType<any>[],\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = typeof MessagesAnnotation,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n>(\n params: CreateAgentParams<\n StateSchema,\n ExtractZodArrayTypes<T> extends Record<string, any>\n ? ExtractZodArrayTypes<T>\n : Record<string, any>,\n ContextSchema,\n T\n > & {\n responseFormat: T;\n }\n): ReactAgent<\n StateSchema,\n ExtractZodArrayTypes<T> extends Record<string, any>\n ? ExtractZodArrayTypes<T>\n : Record<string, any>,\n ContextSchema\n>;\n\n// Overload 3: With responseFormat as JsonSchemaFormat (JSON schema object)\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = typeof MessagesAnnotation,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n>(\n params: CreateAgentParams<\n StateSchema,\n Record<string, unknown>,\n ContextSchema,\n JsonSchemaFormat\n > & {\n responseFormat: JsonSchemaFormat;\n }\n): ReactAgent<StateSchema, Record<string, unknown>, ContextSchema>;\n\n// Overload 4: With responseFormat as array of JsonSchemaFormat (JSON schema objects)\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = typeof MessagesAnnotation,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n>(\n params: CreateAgentParams<\n StateSchema,\n Record<string, unknown>,\n ContextSchema,\n JsonSchemaFormat[]\n > & {\n responseFormat: JsonSchemaFormat[];\n }\n): ReactAgent<StateSchema, Record<string, unknown>, ContextSchema>;\n\n// Overload 4.5: With responseFormat as union of JsonSchemaFormat | JsonSchemaFormat[]\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = typeof MessagesAnnotation,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n>(\n params: CreateAgentParams<\n StateSchema,\n Record<string, unknown>,\n ContextSchema,\n JsonSchemaFormat | JsonSchemaFormat[]\n > & {\n responseFormat: JsonSchemaFormat | JsonSchemaFormat[];\n }\n): ReactAgent<StateSchema, Record<string, unknown>, ContextSchema>;\n\n// Overload 5: With responseFormat as TypedToolStrategy (for union types from toolStrategy)\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = typeof MessagesAnnotation,\n T extends Record<string, any> = Record<string, any>,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n>(\n params: CreateAgentParams<\n StateSchema,\n T,\n ContextSchema,\n TypedToolStrategy<T>\n > & {\n responseFormat: TypedToolStrategy<T>;\n }\n): ReactAgent<StateSchema, T, ContextSchema>;\n\n// Overload 6: With responseFormat as single ToolStrategy instance\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = typeof MessagesAnnotation,\n T extends Record<string, any> = Record<string, any>,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n>(\n params: CreateAgentParams<StateSchema, T, ContextSchema, ToolStrategy<T>> & {\n responseFormat: ToolStrategy<T>;\n }\n): ReactAgent<StateSchema, T, ContextSchema>;\n\n// Overload 7: With responseFormat as ProviderStrategy\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = typeof MessagesAnnotation,\n T extends Record<string, any> = Record<string, any>,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n>(\n params: CreateAgentParams<\n StateSchema,\n T,\n ContextSchema,\n ProviderStrategy<T>\n > & {\n responseFormat: ProviderStrategy<T>;\n }\n): ReactAgent<StateSchema, T, ContextSchema>;\n\n// Overload 8: Without responseFormat property at all\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = typeof MessagesAnnotation,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n>(\n params: Omit<\n CreateAgentParams<\n StateSchema,\n ResponseFormatUndefined,\n ContextSchema,\n never\n >,\n \"responseFormat\"\n >\n): ReactAgent<StateSchema, ResponseFormatUndefined, ContextSchema>;\n\n// Overload 9: With responseFormat explicitly undefined\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = typeof MessagesAnnotation,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n>(\n params: Omit<\n CreateAgentParams<\n StateSchema,\n ResponseFormatUndefined,\n ContextSchema,\n never\n >,\n \"responseFormat\"\n > & {\n responseFormat?: undefined;\n }\n): ReactAgent<StateSchema, ResponseFormatUndefined, ContextSchema>;\n\n// Overload 10: For other ResponseFormat values (failsafe)\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = typeof MessagesAnnotation,\n StructuredResponseFormat extends Record<string, any> = Record<string, any>,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n>(\n params: CreateAgentParams<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema,\n ResponseFormat\n > & {\n responseFormat: ResponseFormat;\n }\n): ReactAgent<StateSchema, StructuredResponseFormat, ContextSchema>;\n\n// Implementation\nexport function createAgent<\n StateSchema extends AnyAnnotationRoot | InteropZodObject,\n StructuredResponseFormat extends Record<string, any>,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject\n>(\n params: CreateAgentParams<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema,\n any\n >\n): ReactAgent<StateSchema, StructuredResponseFormat, ContextSchema> {\n return new ReactAgent(params);\n}\n\nexport * from \"./types.js\";\nexport * from \"./errors.js\";\nexport * from \"./interrupt.js\";\nexport { ToolNode } from \"./nodes/ToolNode.js\";\nexport {\n toolStrategy,\n providerStrategy,\n ToolStrategy,\n ProviderStrategy,\n type ResponseFormat,\n} from \"./responses.js\";\n"],"mappings":";;;;;;;AAqQA,SAAgB,YAKdA,QAMkE;AAClE,QAAO,IAAI,WAAW;AACvB"}
|
|
@@ -43,7 +43,10 @@ var AgentNode = class extends require_RunnableCallable.RunnableCallable {
|
|
|
43
43
|
/**
|
|
44
44
|
* if we were able to generate a structured response, return it
|
|
45
45
|
*/
|
|
46
|
-
if ("structuredResponse" in response) return
|
|
46
|
+
if ("structuredResponse" in response) return {
|
|
47
|
+
messages: [...state.messages, ...response.messages || []],
|
|
48
|
+
structuredResponse: response.structuredResponse
|
|
49
|
+
};
|
|
47
50
|
/**
|
|
48
51
|
* if we need to direct the agent to the model, return the update
|
|
49
52
|
*/
|
|
@@ -112,7 +115,9 @@ var AgentNode = class extends require_RunnableCallable.RunnableCallable {
|
|
|
112
115
|
* scenario is not defined/supported.
|
|
113
116
|
*/
|
|
114
117
|
if (toolCalls.length > 1) return this.#handleMultipleStructuredOutputs(response, toolCalls);
|
|
115
|
-
|
|
118
|
+
const toolStrategy = this.#structuredToolInfo[toolCalls[0].name];
|
|
119
|
+
const toolMessageContent = toolStrategy?.options?.toolMessageContent;
|
|
120
|
+
return this.#handleSingleStructuredOutput(response, toolCalls[0], toolMessageContent ?? options.lastMessage);
|
|
116
121
|
}
|
|
117
122
|
/**
|
|
118
123
|
* If the model returns multiple structured outputs, we need to handle it.
|
|
@@ -139,7 +144,7 @@ var AgentNode = class extends require_RunnableCallable.RunnableCallable {
|
|
|
139
144
|
const structuredResponse = tool.parse(toolCall.args);
|
|
140
145
|
return {
|
|
141
146
|
structuredResponse,
|
|
142
|
-
|
|
147
|
+
messages: [response, new __langchain_core_messages.AIMessage(lastMessage ?? `Returning structured response: ${JSON.stringify(structuredResponse)}`)]
|
|
143
148
|
};
|
|
144
149
|
} catch (error) {
|
|
145
150
|
return this.#handleToolStrategyError(error, response, toolCall);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AgentNode.cjs","names":["RunnableCallable","options: AgentNodeOptions<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema\n >","#run","#options","#structuredToolInfo","transformResponseFormat","ToolStrategy","state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"]","config: RunnableConfig","ToolMessage","response:\n | AIMessage\n | Command\n | { structuredResponse: StructuredResponseFormat }","#invokeModel","Command","#areMoreStepsNeeded","AIMessage","initChatModel","options: {\n lastMessage?: string;\n }","#deriveModel","validateLLMHasNoBoundTools","#bindTools","#getModelInputState","mergeAbortSignals","ProviderStrategy","#handleMultipleStructuredOutputs","#handleSingleStructuredOutput","response: AIMessage","toolCalls: ToolCall[]","MultipleStructuredOutputsError","#handleToolStrategyError","toolCall: ToolCall","lastMessage?: string","error: ToolStrategyError","response: BaseMessage","hasToolCalls","model: LanguageModelLike","options: Partial<BaseChatModelCallOptions>","hasSupportForJsonSchemaOutput","bindTools","getPromptRunnable","withAgentName"],"sources":["../../../src/agents/nodes/AgentNode.ts"],"sourcesContent":["/* eslint-disable no-instanceof/no-instanceof */\nimport { Runnable, RunnableConfig } from \"@langchain/core/runnables\";\nimport { BaseMessage, AIMessage, ToolMessage } from \"@langchain/core/messages\";\nimport { Command } from \"@langchain/langgraph\";\nimport { type LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { type BaseChatModelCallOptions } from \"@langchain/core/language_models/chat_models\";\nimport {\n InteropZodObject,\n getSchemaDescription,\n} from \"@langchain/core/utils/types\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\n\nimport { initChatModel } from \"../../chat_models/universal.js\";\nimport { MultipleStructuredOutputsError } from \"../errors.js\";\nimport { RunnableCallable } from \"../RunnableCallable.js\";\nimport { PreHookAnnotation, AnyAnnotationRoot } from \"../annotation.js\";\nimport { mergeAbortSignals } from \"./utils.js\";\nimport {\n bindTools,\n getPromptRunnable,\n validateLLMHasNoBoundTools,\n hasToolCalls,\n hasSupportForJsonSchemaOutput,\n} from \"../utils.js\";\nimport {\n InternalAgentState,\n ClientTool,\n ServerTool,\n CreateReactAgentParams,\n} from \"../types.js\";\nimport { withAgentName } from \"../withAgentName.js\";\nimport {\n ToolStrategy,\n ProviderStrategy,\n transformResponseFormat,\n ToolStrategyError,\n} from \"../responses.js\";\n\ntype ResponseHandlerResult<StructuredResponseFormat> =\n | {\n structuredResponse: StructuredResponseFormat;\n message: AIMessage;\n }\n | Promise<Command>;\n\nexport interface AgentNodeOptions<\n StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> extends Pick<\n CreateReactAgentParams<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema\n >,\n \"llm\" | \"model\" | \"prompt\" | \"includeAgentName\" | \"name\" | \"responseFormat\"\n > {\n toolClasses: (ClientTool | ServerTool)[];\n shouldReturnDirect: Set<string>;\n signal?: AbortSignal;\n}\n\nexport class AgentNode<\n StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> extends RunnableCallable<\n InternalAgentState<StructuredResponseFormat> & PreHookAnnotation[\"State\"],\n { messages: BaseMessage[] } | { structuredResponse: StructuredResponseFormat }\n> {\n #options: AgentNodeOptions<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema\n >;\n\n #structuredToolInfo: Record<string, ToolStrategy> = {};\n\n constructor(\n options: AgentNodeOptions<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema\n >\n ) {\n super({\n name: options.name ?? \"model\",\n func: (input, config) =>\n this.#run(input, config as RunnableConfig) as any,\n });\n\n this.#options = options;\n\n /**\n * Populate a list of structured tool info.\n */\n this.#structuredToolInfo = (\n transformResponseFormat(this.#options.responseFormat).filter(\n (format) => format instanceof ToolStrategy\n ) as ToolStrategy[]\n ).reduce((acc, format) => {\n acc[format.name] = format;\n return acc;\n }, {} as Record<string, ToolStrategy>);\n }\n\n async #run(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig\n ) {\n /**\n * Check if we just executed a returnDirect tool\n * If so, we should generate structured response (if needed) and stop\n */\n const lastMessage = state.messages[state.messages.length - 1];\n if (\n lastMessage instanceof ToolMessage &&\n lastMessage.name &&\n this.#options.shouldReturnDirect.has(lastMessage.name)\n ) {\n /**\n * return directly without invoking the model again\n */\n return { messages: [] };\n }\n\n const response:\n | AIMessage\n | Command\n | { structuredResponse: StructuredResponseFormat } =\n await this.#invokeModel(state, config);\n\n /**\n * if we were able to generate a structured response, return it\n */\n if (\"structuredResponse\" in response) {\n return response;\n }\n\n /**\n * if we need to direct the agent to the model, return the update\n */\n if (response instanceof Command) {\n return response;\n }\n\n response.name = this.name;\n response.lc_kwargs.name = this.name;\n\n if (this.#areMoreStepsNeeded(state, response)) {\n return {\n messages: [\n new AIMessage(\"Sorry, need more steps to process this request.\", {\n name: this.name,\n lc_kwargs: { name: this.name },\n id: response.id,\n }),\n ],\n };\n }\n\n return { messages: [response] };\n }\n\n /**\n * Derive the model from the options.\n * @param state - The state of the agent.\n * @param config - The config of the agent.\n * @returns The model.\n */\n #deriveModel(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig\n ) {\n if (this.#options.model) {\n if (typeof this.#options.model === \"string\") {\n return initChatModel(this.#options.model);\n }\n\n throw new Error(\"`model` option must be a string.\");\n }\n\n const model = this.#options.llm;\n\n /**\n * If the model is a function, call it to get the model.\n */\n if (typeof model === \"function\") {\n return model(state, config);\n }\n\n if (model) {\n return model;\n }\n\n throw new Error(\n \"No model option was provided, either via `model` or via `llm` option.\"\n );\n }\n\n async #invokeModel(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig,\n options: {\n lastMessage?: string;\n } = {}\n ): Promise<\n | AIMessage\n | Command\n | { structuredResponse: StructuredResponseFormat; messages?: BaseMessage[] }\n > {\n const model = await this.#deriveModel(state, config);\n\n /**\n * Check if the LLM already has bound tools and throw if it does.\n */\n validateLLMHasNoBoundTools(model);\n\n const modelWithTools = await this.#bindTools(model);\n const modelInput = this.#getModelInputState(state);\n const signal = mergeAbortSignals(this.#options.signal, config.signal);\n const invokeConfig = {\n ...config,\n signal,\n };\n\n const response = (await modelWithTools.invoke(\n modelInput,\n invokeConfig\n )) as AIMessage;\n\n /**\n * if the user requests a native schema output, try to parse the response\n * and return the structured response if it is valid\n */\n if (this.#options.responseFormat instanceof ProviderStrategy) {\n const structuredResponse = this.#options.responseFormat.parse(response);\n if (structuredResponse) {\n return { structuredResponse, messages: [response] };\n }\n }\n\n if (!response.tool_calls) {\n return response;\n }\n\n const toolCalls = response.tool_calls.filter(\n (call) => call.name in this.#structuredToolInfo\n );\n\n /**\n * if there were not structured tool calls, we can return the response\n */\n if (toolCalls.length === 0) {\n return response;\n }\n\n /**\n * if there were multiple structured tool calls, we should throw an error as this\n * scenario is not defined/supported.\n */\n if (toolCalls.length > 1) {\n return this.#handleMultipleStructuredOutputs(response, toolCalls);\n }\n\n return this.#handleSingleStructuredOutput(\n response,\n toolCalls[0],\n options.lastMessage\n );\n }\n\n /**\n * If the model returns multiple structured outputs, we need to handle it.\n * @param response - The response from the model\n * @param toolCalls - The tool calls that were made\n * @returns The response from the model\n */\n #handleMultipleStructuredOutputs(\n response: AIMessage,\n toolCalls: ToolCall[]\n ): Promise<Command> {\n /**\n * the following should never happen, let's throw an error if it does\n */\n if (this.#options.responseFormat instanceof ProviderStrategy) {\n throw new Error(\n \"Multiple structured outputs should not apply to native structured output responses\"\n );\n }\n\n const multipleStructuredOutputsError = new MultipleStructuredOutputsError(\n toolCalls.map((call) => call.name)\n );\n\n return this.#handleToolStrategyError(\n multipleStructuredOutputsError,\n response,\n toolCalls[0]\n );\n }\n\n /**\n * If the model returns a single structured output, we need to handle it.\n * @param toolCall - The tool call that was made\n * @returns The structured response and a message to the LLM if needed\n */\n #handleSingleStructuredOutput(\n response: AIMessage,\n toolCall: ToolCall,\n lastMessage?: string\n ): ResponseHandlerResult<StructuredResponseFormat> {\n const tool = this.#structuredToolInfo[toolCall.name];\n\n try {\n const structuredResponse = tool.parse(\n toolCall.args\n ) as StructuredResponseFormat;\n\n return {\n structuredResponse,\n message: new AIMessage(\n lastMessage ??\n `Returning structured response: ${JSON.stringify(\n structuredResponse\n )}`\n ),\n };\n } catch (error) {\n return this.#handleToolStrategyError(\n error as ToolStrategyError,\n response,\n toolCall\n );\n }\n }\n\n async #handleToolStrategyError(\n error: ToolStrategyError,\n response: AIMessage,\n toolCall: ToolCall\n ): Promise<Command> {\n /**\n * Using the `errorHandler` option of the first `ToolStrategy` entry is sufficient here.\n * There is technically only one `ToolStrategy` entry in `structuredToolInfo` if the user\n * uses `toolStrategy` to define the response format. If the user applies a list of json\n * schema objects, these will be transformed into multiple `ToolStrategy` entries but all\n * with the same `handleError` option.\n */\n const errorHandler = Object.values(this.#structuredToolInfo).at(0)?.options\n ?.handleError;\n\n const toolCallId = toolCall.id;\n if (!toolCallId) {\n throw new Error(\n \"Tool call ID is required to handle tool output errors. Please provide a tool call ID.\"\n );\n }\n\n /**\n * retry if:\n */\n if (\n /**\n * if the user has provided `true` as the `errorHandler` option, return a new AIMessage\n * with the error message and retry the tool call.\n */\n (typeof errorHandler === \"boolean\" && errorHandler) ||\n /**\n * if `errorHandler` is an array and contains MultipleStructuredOutputsError\n */\n (Array.isArray(errorHandler) &&\n errorHandler.some((h) => h instanceof MultipleStructuredOutputsError))\n ) {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: error.message,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * if `errorHandler` is a string, retry the tool call with given string\n */\n if (typeof errorHandler === \"string\") {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: errorHandler,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * if `errorHandler` is a function, retry the tool call with the function\n */\n if (typeof errorHandler === \"function\") {\n const content = await errorHandler(error);\n if (typeof content !== \"string\") {\n throw new Error(\"Error handler must return a string.\");\n }\n\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * throw otherwise, e.g. if `errorHandler` is not defined or set to `false`\n */\n throw error;\n }\n\n #areMoreStepsNeeded(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n response: BaseMessage\n ): boolean {\n const allToolsReturnDirect =\n response instanceof AIMessage &&\n response.tool_calls?.every((call) =>\n this.#options.shouldReturnDirect.has(call.name)\n );\n const remainingSteps =\n \"remainingSteps\" in state ? (state.remainingSteps as number) : undefined;\n return Boolean(\n remainingSteps &&\n ((remainingSteps < 1 && allToolsReturnDirect) ||\n (remainingSteps < 2 && hasToolCalls(state.messages)))\n );\n }\n\n #getModelInputState(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"]\n ): Omit<InternalAgentState<StructuredResponseFormat>, \"llmInputMessages\"> {\n const { messages, llmInputMessages, ...rest } = state;\n if (llmInputMessages && llmInputMessages.length > 0) {\n return { messages: llmInputMessages, ...rest } as Omit<\n InternalAgentState<StructuredResponseFormat>,\n \"llmInputMessages\"\n >;\n }\n return { messages, ...rest } as Omit<\n InternalAgentState<StructuredResponseFormat>,\n \"llmInputMessages\"\n >;\n }\n\n async #bindTools(model: LanguageModelLike): Promise<Runnable> {\n const options: Partial<BaseChatModelCallOptions> = {};\n const structuredTools = Object.values(this.#structuredToolInfo);\n const allTools = this.#options.toolClasses.concat(\n ...structuredTools.map((toolStrategy) => toolStrategy.tool)\n );\n\n /**\n * If there are structured tools, we need to set the tool choice to \"any\"\n * so that the model can choose to use a structured tool or not.\n */\n const toolChoice = structuredTools.length > 0 ? \"any\" : undefined;\n\n /**\n * check if the user requests a native schema output\n */\n if (this.#options.responseFormat instanceof ProviderStrategy) {\n /**\n * if the model does not support JSON schema output, throw an error\n */\n if (!hasSupportForJsonSchemaOutput(model)) {\n throw new Error(\n \"Model does not support native structured output responses. Please use a model that supports native structured output responses or use a tool output.\"\n );\n }\n\n const jsonSchemaParams = {\n name: this.#options.responseFormat.schema?.name ?? \"extract\",\n description: getSchemaDescription(this.#options.responseFormat.schema),\n schema: this.#options.responseFormat.schema,\n strict: true,\n };\n\n Object.assign(options, {\n response_format: {\n type: \"json_schema\",\n json_schema: jsonSchemaParams,\n },\n ls_structured_output_format: {\n kwargs: { method: \"json_schema\" },\n schema: this.#options.responseFormat.schema,\n },\n strict: true,\n });\n }\n\n /**\n * Bind tools to the model if they are not already bound.\n */\n const modelWithTools = await bindTools(model, allTools, {\n ...options,\n tool_choice: toolChoice,\n });\n\n /**\n * Create a model runnable with the prompt and agent name\n */\n const modelRunnable = getPromptRunnable(this.#options.prompt).pipe(\n this.#options.includeAgentName === \"inline\"\n ? withAgentName(modelWithTools, this.#options.includeAgentName)\n : modelWithTools\n );\n\n return modelRunnable;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAiEA,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O;CACR;AACF"}
|
|
1
|
+
{"version":3,"file":"AgentNode.cjs","names":["RunnableCallable","options: AgentNodeOptions<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema\n >","#run","#options","#structuredToolInfo","transformResponseFormat","ToolStrategy","state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"]","config: RunnableConfig","ToolMessage","#invokeModel","Command","#areMoreStepsNeeded","AIMessage","initChatModel","options: {\n lastMessage?: string;\n }","#deriveModel","validateLLMHasNoBoundTools","#bindTools","#getModelInputState","mergeAbortSignals","ProviderStrategy","#handleMultipleStructuredOutputs","#handleSingleStructuredOutput","response: AIMessage","toolCalls: ToolCall[]","MultipleStructuredOutputsError","#handleToolStrategyError","toolCall: ToolCall","lastMessage?: string","error: ToolStrategyError","response: BaseMessage","hasToolCalls","model: LanguageModelLike","options: Partial<BaseChatModelCallOptions>","hasSupportForJsonSchemaOutput","bindTools","getPromptRunnable","withAgentName"],"sources":["../../../src/agents/nodes/AgentNode.ts"],"sourcesContent":["/* eslint-disable no-instanceof/no-instanceof */\nimport { Runnable, RunnableConfig } from \"@langchain/core/runnables\";\nimport { BaseMessage, AIMessage, ToolMessage } from \"@langchain/core/messages\";\nimport { Command } from \"@langchain/langgraph\";\nimport { type LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { type BaseChatModelCallOptions } from \"@langchain/core/language_models/chat_models\";\nimport {\n InteropZodObject,\n getSchemaDescription,\n} from \"@langchain/core/utils/types\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\n\nimport { initChatModel } from \"../../chat_models/universal.js\";\nimport { MultipleStructuredOutputsError } from \"../errors.js\";\nimport { RunnableCallable } from \"../RunnableCallable.js\";\nimport { PreHookAnnotation, AnyAnnotationRoot } from \"../annotation.js\";\nimport { mergeAbortSignals } from \"./utils.js\";\nimport {\n bindTools,\n getPromptRunnable,\n validateLLMHasNoBoundTools,\n hasToolCalls,\n hasSupportForJsonSchemaOutput,\n} from \"../utils.js\";\nimport {\n InternalAgentState,\n ClientTool,\n ServerTool,\n CreateAgentParams,\n} from \"../types.js\";\nimport { withAgentName } from \"../withAgentName.js\";\nimport {\n ToolStrategy,\n ProviderStrategy,\n transformResponseFormat,\n ToolStrategyError,\n} from \"../responses.js\";\n\ntype ResponseHandlerResult<StructuredResponseFormat> =\n | {\n structuredResponse: StructuredResponseFormat;\n messages: BaseMessage[];\n }\n | Promise<Command>;\n\nexport interface AgentNodeOptions<\n StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> extends Pick<\n CreateAgentParams<StateSchema, StructuredResponseFormat, ContextSchema>,\n \"llm\" | \"model\" | \"prompt\" | \"includeAgentName\" | \"name\" | \"responseFormat\"\n > {\n toolClasses: (ClientTool | ServerTool)[];\n shouldReturnDirect: Set<string>;\n signal?: AbortSignal;\n}\n\nexport class AgentNode<\n StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> extends RunnableCallable<\n InternalAgentState<StructuredResponseFormat> & PreHookAnnotation[\"State\"],\n { messages: BaseMessage[] } | { structuredResponse: StructuredResponseFormat }\n> {\n #options: AgentNodeOptions<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema\n >;\n\n #structuredToolInfo: Record<string, ToolStrategy> = {};\n\n constructor(\n options: AgentNodeOptions<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema\n >\n ) {\n super({\n name: options.name ?? \"model\",\n func: (input, config) =>\n this.#run(input, config as RunnableConfig) as any,\n });\n\n this.#options = options;\n\n /**\n * Populate a list of structured tool info.\n */\n this.#structuredToolInfo = (\n transformResponseFormat(this.#options.responseFormat).filter(\n (format) => format instanceof ToolStrategy\n ) as ToolStrategy[]\n ).reduce((acc, format) => {\n acc[format.name] = format;\n return acc;\n }, {} as Record<string, ToolStrategy>);\n }\n\n async #run(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig\n ) {\n /**\n * Check if we just executed a returnDirect tool\n * If so, we should generate structured response (if needed) and stop\n */\n const lastMessage = state.messages[state.messages.length - 1];\n if (\n lastMessage instanceof ToolMessage &&\n lastMessage.name &&\n this.#options.shouldReturnDirect.has(lastMessage.name)\n ) {\n /**\n * return directly without invoking the model again\n */\n return { messages: [] };\n }\n\n const response = await this.#invokeModel(state, config);\n\n /**\n * if we were able to generate a structured response, return it\n */\n if (\"structuredResponse\" in response) {\n return {\n messages: [...state.messages, ...(response.messages || [])],\n structuredResponse: response.structuredResponse,\n };\n }\n\n /**\n * if we need to direct the agent to the model, return the update\n */\n if (response instanceof Command) {\n return response;\n }\n\n response.name = this.name;\n response.lc_kwargs.name = this.name;\n\n if (this.#areMoreStepsNeeded(state, response)) {\n return {\n messages: [\n new AIMessage(\"Sorry, need more steps to process this request.\", {\n name: this.name,\n lc_kwargs: { name: this.name },\n id: response.id,\n }),\n ],\n };\n }\n\n return { messages: [response] };\n }\n\n /**\n * Derive the model from the options.\n * @param state - The state of the agent.\n * @param config - The config of the agent.\n * @returns The model.\n */\n #deriveModel(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig\n ) {\n if (this.#options.model) {\n if (typeof this.#options.model === \"string\") {\n return initChatModel(this.#options.model);\n }\n\n throw new Error(\"`model` option must be a string.\");\n }\n\n const model = this.#options.llm;\n\n /**\n * If the model is a function, call it to get the model.\n */\n if (typeof model === \"function\") {\n return model(state, config);\n }\n\n if (model) {\n return model;\n }\n\n throw new Error(\n \"No model option was provided, either via `model` or via `llm` option.\"\n );\n }\n\n async #invokeModel(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig,\n options: {\n lastMessage?: string;\n } = {}\n ): Promise<AIMessage | ResponseHandlerResult<StructuredResponseFormat>> {\n const model = await this.#deriveModel(state, config);\n\n /**\n * Check if the LLM already has bound tools and throw if it does.\n */\n validateLLMHasNoBoundTools(model);\n\n const modelWithTools = await this.#bindTools(model);\n const modelInput = this.#getModelInputState(state);\n const signal = mergeAbortSignals(this.#options.signal, config.signal);\n const invokeConfig = {\n ...config,\n signal,\n };\n\n const response = (await modelWithTools.invoke(\n modelInput,\n invokeConfig\n )) as AIMessage;\n\n /**\n * if the user requests a native schema output, try to parse the response\n * and return the structured response if it is valid\n */\n if (this.#options.responseFormat instanceof ProviderStrategy) {\n const structuredResponse = this.#options.responseFormat.parse(response);\n if (structuredResponse) {\n return { structuredResponse, messages: [response] };\n }\n }\n\n if (!response.tool_calls) {\n return response;\n }\n\n const toolCalls = response.tool_calls.filter(\n (call) => call.name in this.#structuredToolInfo\n );\n\n /**\n * if there were not structured tool calls, we can return the response\n */\n if (toolCalls.length === 0) {\n return response;\n }\n\n /**\n * if there were multiple structured tool calls, we should throw an error as this\n * scenario is not defined/supported.\n */\n if (toolCalls.length > 1) {\n return this.#handleMultipleStructuredOutputs(response, toolCalls);\n }\n\n const toolStrategy = this.#structuredToolInfo[toolCalls[0].name];\n const toolMessageContent = toolStrategy?.options?.toolMessageContent;\n return this.#handleSingleStructuredOutput(\n response,\n toolCalls[0],\n toolMessageContent ?? options.lastMessage\n );\n }\n\n /**\n * If the model returns multiple structured outputs, we need to handle it.\n * @param response - The response from the model\n * @param toolCalls - The tool calls that were made\n * @returns The response from the model\n */\n #handleMultipleStructuredOutputs(\n response: AIMessage,\n toolCalls: ToolCall[]\n ): Promise<Command> {\n /**\n * the following should never happen, let's throw an error if it does\n */\n if (this.#options.responseFormat instanceof ProviderStrategy) {\n throw new Error(\n \"Multiple structured outputs should not apply to native structured output responses\"\n );\n }\n\n const multipleStructuredOutputsError = new MultipleStructuredOutputsError(\n toolCalls.map((call) => call.name)\n );\n\n return this.#handleToolStrategyError(\n multipleStructuredOutputsError,\n response,\n toolCalls[0]\n );\n }\n\n /**\n * If the model returns a single structured output, we need to handle it.\n * @param toolCall - The tool call that was made\n * @returns The structured response and a message to the LLM if needed\n */\n #handleSingleStructuredOutput(\n response: AIMessage,\n toolCall: ToolCall,\n lastMessage?: string\n ): ResponseHandlerResult<StructuredResponseFormat> {\n const tool = this.#structuredToolInfo[toolCall.name];\n\n try {\n const structuredResponse = tool.parse(\n toolCall.args\n ) as StructuredResponseFormat;\n\n return {\n structuredResponse,\n messages: [\n response,\n new AIMessage(\n lastMessage ??\n `Returning structured response: ${JSON.stringify(\n structuredResponse\n )}`\n ),\n ],\n };\n } catch (error) {\n return this.#handleToolStrategyError(\n error as ToolStrategyError,\n response,\n toolCall\n );\n }\n }\n\n async #handleToolStrategyError(\n error: ToolStrategyError,\n response: AIMessage,\n toolCall: ToolCall\n ): Promise<Command> {\n /**\n * Using the `errorHandler` option of the first `ToolStrategy` entry is sufficient here.\n * There is technically only one `ToolStrategy` entry in `structuredToolInfo` if the user\n * uses `toolStrategy` to define the response format. If the user applies a list of json\n * schema objects, these will be transformed into multiple `ToolStrategy` entries but all\n * with the same `handleError` option.\n */\n const errorHandler = Object.values(this.#structuredToolInfo).at(0)?.options\n ?.handleError;\n\n const toolCallId = toolCall.id;\n if (!toolCallId) {\n throw new Error(\n \"Tool call ID is required to handle tool output errors. Please provide a tool call ID.\"\n );\n }\n\n /**\n * retry if:\n */\n if (\n /**\n * if the user has provided `true` as the `errorHandler` option, return a new AIMessage\n * with the error message and retry the tool call.\n */\n (typeof errorHandler === \"boolean\" && errorHandler) ||\n /**\n * if `errorHandler` is an array and contains MultipleStructuredOutputsError\n */\n (Array.isArray(errorHandler) &&\n errorHandler.some((h) => h instanceof MultipleStructuredOutputsError))\n ) {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: error.message,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * if `errorHandler` is a string, retry the tool call with given string\n */\n if (typeof errorHandler === \"string\") {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: errorHandler,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * if `errorHandler` is a function, retry the tool call with the function\n */\n if (typeof errorHandler === \"function\") {\n const content = await errorHandler(error);\n if (typeof content !== \"string\") {\n throw new Error(\"Error handler must return a string.\");\n }\n\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * throw otherwise, e.g. if `errorHandler` is not defined or set to `false`\n */\n throw error;\n }\n\n #areMoreStepsNeeded(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n response: BaseMessage\n ): boolean {\n const allToolsReturnDirect =\n response instanceof AIMessage &&\n response.tool_calls?.every((call) =>\n this.#options.shouldReturnDirect.has(call.name)\n );\n const remainingSteps =\n \"remainingSteps\" in state ? (state.remainingSteps as number) : undefined;\n return Boolean(\n remainingSteps &&\n ((remainingSteps < 1 && allToolsReturnDirect) ||\n (remainingSteps < 2 && hasToolCalls(state.messages)))\n );\n }\n\n #getModelInputState(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"]\n ): Omit<InternalAgentState<StructuredResponseFormat>, \"llmInputMessages\"> {\n const { messages, llmInputMessages, ...rest } = state;\n if (llmInputMessages && llmInputMessages.length > 0) {\n return { messages: llmInputMessages, ...rest } as Omit<\n InternalAgentState<StructuredResponseFormat>,\n \"llmInputMessages\"\n >;\n }\n return { messages, ...rest } as Omit<\n InternalAgentState<StructuredResponseFormat>,\n \"llmInputMessages\"\n >;\n }\n\n async #bindTools(model: LanguageModelLike): Promise<Runnable> {\n const options: Partial<BaseChatModelCallOptions> = {};\n const structuredTools = Object.values(this.#structuredToolInfo);\n const allTools = this.#options.toolClasses.concat(\n ...structuredTools.map((toolStrategy) => toolStrategy.tool)\n );\n\n /**\n * If there are structured tools, we need to set the tool choice to \"any\"\n * so that the model can choose to use a structured tool or not.\n */\n const toolChoice = structuredTools.length > 0 ? \"any\" : undefined;\n\n /**\n * check if the user requests a native schema output\n */\n if (this.#options.responseFormat instanceof ProviderStrategy) {\n /**\n * if the model does not support JSON schema output, throw an error\n */\n if (!hasSupportForJsonSchemaOutput(model)) {\n throw new Error(\n \"Model does not support native structured output responses. Please use a model that supports native structured output responses or use a tool output.\"\n );\n }\n\n const jsonSchemaParams = {\n name: this.#options.responseFormat.schema?.name ?? \"extract\",\n description: getSchemaDescription(this.#options.responseFormat.schema),\n schema: this.#options.responseFormat.schema,\n strict: true,\n };\n\n Object.assign(options, {\n response_format: {\n type: \"json_schema\",\n json_schema: jsonSchemaParams,\n },\n ls_structured_output_format: {\n kwargs: { method: \"json_schema\" },\n schema: this.#options.responseFormat.schema,\n },\n strict: true,\n });\n }\n\n /**\n * Bind tools to the model if they are not already bound.\n */\n const modelWithTools = await bindTools(model, allTools, {\n ...options,\n tool_choice: toolChoice,\n });\n\n /**\n * Create a model runnable with the prompt and agent name\n */\n const modelRunnable = getPromptRunnable(this.#options.prompt).pipe(\n this.#options.includeAgentName === \"inline\"\n ? withAgentName(modelWithTools, this.#options.includeAgentName)\n : modelWithTools\n );\n\n return modelRunnable;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AA6DA,IAAa,YAAb,cAOUA,0CAGR;CACA;CAMA,sBAAoD,CAAE;CAEtD,YACEC,SAKA;EACA,MAAM;GACJ,MAAM,QAAQ,QAAQ;GACtB,MAAM,CAAC,OAAO,WACZ,KAAKC,KAAK,OAAO,OAAyB;EAC7C,EAAC;EAEF,KAAKC,WAAW;;;;EAKhB,KAAKC,sBACHC,0CAAwB,KAAKF,SAAS,eAAe,CAAC,OACpD,CAAC,WAAW,kBAAkBG,+BAC/B,CACD,OAAO,CAAC,KAAK,WAAW;GACxB,IAAI,OAAO,QAAQ;AACnB,UAAO;EACR,GAAE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,MAAI,oBAAoB,iBAAiB,SAAS,EAChD,QAAO;GAAE,UAAU;GAAkB,GAAG;EAAM;AAKhD,SAAO;GAAE;GAAU,GAAG;EAAM;CAI7B;CAED,MAAMW,WAAWe,OAA6C;EAC5D,MAAMC,UAA6C,CAAE;EACrD,MAAM,kBAAkB,OAAO,OAAO,KAAK9B,oBAAoB;EAC/D,MAAM,WAAW,KAAKD,SAAS,YAAY,OACzC,GAAG,gBAAgB,IAAI,CAAC,iBAAiB,aAAa,KAAK,CAC5D;;;;;EAMD,MAAM,aAAa,gBAAgB,SAAS,IAAI,QAAQ;;;;AAKxD,MAAI,KAAKA,SAAS,0BAA0BkB,oCAAkB;;;;AAI5D,OAAI,CAACc,4CAA8B,MAAM,CACvC,OAAM,IAAI,MACR;GAIJ,MAAM,mBAAmB;IACvB,MAAM,KAAKhC,SAAS,eAAe,QAAQ,QAAQ;IACnD,oEAAkC,KAAKA,SAAS,eAAe,OAAO;IACtE,QAAQ,KAAKA,SAAS,eAAe;IACrC,QAAQ;GACT;GAED,OAAO,OAAO,SAAS;IACrB,iBAAiB;KACf,MAAM;KACN,aAAa;IACd;IACD,6BAA6B;KAC3B,QAAQ,EAAE,QAAQ,cAAe;KACjC,QAAQ,KAAKA,SAAS,eAAe;IACtC;IACD,QAAQ;GACT,EAAC;EACH;;;;EAKD,MAAM,iBAAiB,MAAMiC,wBAAU,OAAO,UAAU;GACtD,GAAG;GACH,aAAa;EACd,EAAC;;;;EAKF,MAAM,gBAAgBC,gCAAkB,KAAKlC,SAAS,OAAO,CAAC,KAC5D,KAAKA,SAAS,qBAAqB,WAC/BmC,oCAAc,gBAAgB,KAAKnC,SAAS,iBAAiB,GAC7D,eACL;AAED,SAAO;CACR;AACF"}
|
|
@@ -42,7 +42,10 @@ var AgentNode = class extends RunnableCallable {
|
|
|
42
42
|
/**
|
|
43
43
|
* if we were able to generate a structured response, return it
|
|
44
44
|
*/
|
|
45
|
-
if ("structuredResponse" in response) return
|
|
45
|
+
if ("structuredResponse" in response) return {
|
|
46
|
+
messages: [...state.messages, ...response.messages || []],
|
|
47
|
+
structuredResponse: response.structuredResponse
|
|
48
|
+
};
|
|
46
49
|
/**
|
|
47
50
|
* if we need to direct the agent to the model, return the update
|
|
48
51
|
*/
|
|
@@ -111,7 +114,9 @@ var AgentNode = class extends RunnableCallable {
|
|
|
111
114
|
* scenario is not defined/supported.
|
|
112
115
|
*/
|
|
113
116
|
if (toolCalls.length > 1) return this.#handleMultipleStructuredOutputs(response, toolCalls);
|
|
114
|
-
|
|
117
|
+
const toolStrategy = this.#structuredToolInfo[toolCalls[0].name];
|
|
118
|
+
const toolMessageContent = toolStrategy?.options?.toolMessageContent;
|
|
119
|
+
return this.#handleSingleStructuredOutput(response, toolCalls[0], toolMessageContent ?? options.lastMessage);
|
|
115
120
|
}
|
|
116
121
|
/**
|
|
117
122
|
* If the model returns multiple structured outputs, we need to handle it.
|
|
@@ -138,7 +143,7 @@ var AgentNode = class extends RunnableCallable {
|
|
|
138
143
|
const structuredResponse = tool.parse(toolCall.args);
|
|
139
144
|
return {
|
|
140
145
|
structuredResponse,
|
|
141
|
-
|
|
146
|
+
messages: [response, new AIMessage(lastMessage ?? `Returning structured response: ${JSON.stringify(structuredResponse)}`)]
|
|
142
147
|
};
|
|
143
148
|
} catch (error) {
|
|
144
149
|
return this.#handleToolStrategyError(error, response, toolCall);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AgentNode.js","names":["options: AgentNodeOptions<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema\n >","#run","#options","#structuredToolInfo","state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"]","config: RunnableConfig","response:\n | AIMessage\n | Command\n | { structuredResponse: StructuredResponseFormat }","#invokeModel","#areMoreStepsNeeded","options: {\n lastMessage?: string;\n }","#deriveModel","#bindTools","#getModelInputState","#handleMultipleStructuredOutputs","#handleSingleStructuredOutput","response: AIMessage","toolCalls: ToolCall[]","#handleToolStrategyError","toolCall: ToolCall","lastMessage?: string","error: ToolStrategyError","response: BaseMessage","model: LanguageModelLike","options: Partial<BaseChatModelCallOptions>"],"sources":["../../../src/agents/nodes/AgentNode.ts"],"sourcesContent":["/* eslint-disable no-instanceof/no-instanceof */\nimport { Runnable, RunnableConfig } from \"@langchain/core/runnables\";\nimport { BaseMessage, AIMessage, ToolMessage } from \"@langchain/core/messages\";\nimport { Command } from \"@langchain/langgraph\";\nimport { type LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { type BaseChatModelCallOptions } from \"@langchain/core/language_models/chat_models\";\nimport {\n InteropZodObject,\n getSchemaDescription,\n} from \"@langchain/core/utils/types\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\n\nimport { initChatModel } from \"../../chat_models/universal.js\";\nimport { MultipleStructuredOutputsError } from \"../errors.js\";\nimport { RunnableCallable } from \"../RunnableCallable.js\";\nimport { PreHookAnnotation, AnyAnnotationRoot } from \"../annotation.js\";\nimport { mergeAbortSignals } from \"./utils.js\";\nimport {\n bindTools,\n getPromptRunnable,\n validateLLMHasNoBoundTools,\n hasToolCalls,\n hasSupportForJsonSchemaOutput,\n} from \"../utils.js\";\nimport {\n InternalAgentState,\n ClientTool,\n ServerTool,\n CreateReactAgentParams,\n} from \"../types.js\";\nimport { withAgentName } from \"../withAgentName.js\";\nimport {\n ToolStrategy,\n ProviderStrategy,\n transformResponseFormat,\n ToolStrategyError,\n} from \"../responses.js\";\n\ntype ResponseHandlerResult<StructuredResponseFormat> =\n | {\n structuredResponse: StructuredResponseFormat;\n message: AIMessage;\n }\n | Promise<Command>;\n\nexport interface AgentNodeOptions<\n StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> extends Pick<\n CreateReactAgentParams<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema\n >,\n \"llm\" | \"model\" | \"prompt\" | \"includeAgentName\" | \"name\" | \"responseFormat\"\n > {\n toolClasses: (ClientTool | ServerTool)[];\n shouldReturnDirect: Set<string>;\n signal?: AbortSignal;\n}\n\nexport class AgentNode<\n StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> extends RunnableCallable<\n InternalAgentState<StructuredResponseFormat> & PreHookAnnotation[\"State\"],\n { messages: BaseMessage[] } | { structuredResponse: StructuredResponseFormat }\n> {\n #options: AgentNodeOptions<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema\n >;\n\n #structuredToolInfo: Record<string, ToolStrategy> = {};\n\n constructor(\n options: AgentNodeOptions<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema\n >\n ) {\n super({\n name: options.name ?? \"model\",\n func: (input, config) =>\n this.#run(input, config as RunnableConfig) as any,\n });\n\n this.#options = options;\n\n /**\n * Populate a list of structured tool info.\n */\n this.#structuredToolInfo = (\n transformResponseFormat(this.#options.responseFormat).filter(\n (format) => format instanceof ToolStrategy\n ) as ToolStrategy[]\n ).reduce((acc, format) => {\n acc[format.name] = format;\n return acc;\n }, {} as Record<string, ToolStrategy>);\n }\n\n async #run(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig\n ) {\n /**\n * Check if we just executed a returnDirect tool\n * If so, we should generate structured response (if needed) and stop\n */\n const lastMessage = state.messages[state.messages.length - 1];\n if (\n lastMessage instanceof ToolMessage &&\n lastMessage.name &&\n this.#options.shouldReturnDirect.has(lastMessage.name)\n ) {\n /**\n * return directly without invoking the model again\n */\n return { messages: [] };\n }\n\n const response:\n | AIMessage\n | Command\n | { structuredResponse: StructuredResponseFormat } =\n await this.#invokeModel(state, config);\n\n /**\n * if we were able to generate a structured response, return it\n */\n if (\"structuredResponse\" in response) {\n return response;\n }\n\n /**\n * if we need to direct the agent to the model, return the update\n */\n if (response instanceof Command) {\n return response;\n }\n\n response.name = this.name;\n response.lc_kwargs.name = this.name;\n\n if (this.#areMoreStepsNeeded(state, response)) {\n return {\n messages: [\n new AIMessage(\"Sorry, need more steps to process this request.\", {\n name: this.name,\n lc_kwargs: { name: this.name },\n id: response.id,\n }),\n ],\n };\n }\n\n return { messages: [response] };\n }\n\n /**\n * Derive the model from the options.\n * @param state - The state of the agent.\n * @param config - The config of the agent.\n * @returns The model.\n */\n #deriveModel(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig\n ) {\n if (this.#options.model) {\n if (typeof this.#options.model === \"string\") {\n return initChatModel(this.#options.model);\n }\n\n throw new Error(\"`model` option must be a string.\");\n }\n\n const model = this.#options.llm;\n\n /**\n * If the model is a function, call it to get the model.\n */\n if (typeof model === \"function\") {\n return model(state, config);\n }\n\n if (model) {\n return model;\n }\n\n throw new Error(\n \"No model option was provided, either via `model` or via `llm` option.\"\n );\n }\n\n async #invokeModel(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig,\n options: {\n lastMessage?: string;\n } = {}\n ): Promise<\n | AIMessage\n | Command\n | { structuredResponse: StructuredResponseFormat; messages?: BaseMessage[] }\n > {\n const model = await this.#deriveModel(state, config);\n\n /**\n * Check if the LLM already has bound tools and throw if it does.\n */\n validateLLMHasNoBoundTools(model);\n\n const modelWithTools = await this.#bindTools(model);\n const modelInput = this.#getModelInputState(state);\n const signal = mergeAbortSignals(this.#options.signal, config.signal);\n const invokeConfig = {\n ...config,\n signal,\n };\n\n const response = (await modelWithTools.invoke(\n modelInput,\n invokeConfig\n )) as AIMessage;\n\n /**\n * if the user requests a native schema output, try to parse the response\n * and return the structured response if it is valid\n */\n if (this.#options.responseFormat instanceof ProviderStrategy) {\n const structuredResponse = this.#options.responseFormat.parse(response);\n if (structuredResponse) {\n return { structuredResponse, messages: [response] };\n }\n }\n\n if (!response.tool_calls) {\n return response;\n }\n\n const toolCalls = response.tool_calls.filter(\n (call) => call.name in this.#structuredToolInfo\n );\n\n /**\n * if there were not structured tool calls, we can return the response\n */\n if (toolCalls.length === 0) {\n return response;\n }\n\n /**\n * if there were multiple structured tool calls, we should throw an error as this\n * scenario is not defined/supported.\n */\n if (toolCalls.length > 1) {\n return this.#handleMultipleStructuredOutputs(response, toolCalls);\n }\n\n return this.#handleSingleStructuredOutput(\n response,\n toolCalls[0],\n options.lastMessage\n );\n }\n\n /**\n * If the model returns multiple structured outputs, we need to handle it.\n * @param response - The response from the model\n * @param toolCalls - The tool calls that were made\n * @returns The response from the model\n */\n #handleMultipleStructuredOutputs(\n response: AIMessage,\n toolCalls: ToolCall[]\n ): Promise<Command> {\n /**\n * the following should never happen, let's throw an error if it does\n */\n if (this.#options.responseFormat instanceof ProviderStrategy) {\n throw new Error(\n \"Multiple structured outputs should not apply to native structured output responses\"\n );\n }\n\n const multipleStructuredOutputsError = new MultipleStructuredOutputsError(\n toolCalls.map((call) => call.name)\n );\n\n return this.#handleToolStrategyError(\n multipleStructuredOutputsError,\n response,\n toolCalls[0]\n );\n }\n\n /**\n * If the model returns a single structured output, we need to handle it.\n * @param toolCall - The tool call that was made\n * @returns The structured response and a message to the LLM if needed\n */\n #handleSingleStructuredOutput(\n response: AIMessage,\n toolCall: ToolCall,\n lastMessage?: string\n ): ResponseHandlerResult<StructuredResponseFormat> {\n const tool = this.#structuredToolInfo[toolCall.name];\n\n try {\n const structuredResponse = tool.parse(\n toolCall.args\n ) as StructuredResponseFormat;\n\n return {\n structuredResponse,\n message: new AIMessage(\n lastMessage ??\n `Returning structured response: ${JSON.stringify(\n structuredResponse\n )}`\n ),\n };\n } catch (error) {\n return this.#handleToolStrategyError(\n error as ToolStrategyError,\n response,\n toolCall\n );\n }\n }\n\n async #handleToolStrategyError(\n error: ToolStrategyError,\n response: AIMessage,\n toolCall: ToolCall\n ): Promise<Command> {\n /**\n * Using the `errorHandler` option of the first `ToolStrategy` entry is sufficient here.\n * There is technically only one `ToolStrategy` entry in `structuredToolInfo` if the user\n * uses `toolStrategy` to define the response format. If the user applies a list of json\n * schema objects, these will be transformed into multiple `ToolStrategy` entries but all\n * with the same `handleError` option.\n */\n const errorHandler = Object.values(this.#structuredToolInfo).at(0)?.options\n ?.handleError;\n\n const toolCallId = toolCall.id;\n if (!toolCallId) {\n throw new Error(\n \"Tool call ID is required to handle tool output errors. Please provide a tool call ID.\"\n );\n }\n\n /**\n * retry if:\n */\n if (\n /**\n * if the user has provided `true` as the `errorHandler` option, return a new AIMessage\n * with the error message and retry the tool call.\n */\n (typeof errorHandler === \"boolean\" && errorHandler) ||\n /**\n * if `errorHandler` is an array and contains MultipleStructuredOutputsError\n */\n (Array.isArray(errorHandler) &&\n errorHandler.some((h) => h instanceof MultipleStructuredOutputsError))\n ) {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: error.message,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * if `errorHandler` is a string, retry the tool call with given string\n */\n if (typeof errorHandler === \"string\") {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: errorHandler,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * if `errorHandler` is a function, retry the tool call with the function\n */\n if (typeof errorHandler === \"function\") {\n const content = await errorHandler(error);\n if (typeof content !== \"string\") {\n throw new Error(\"Error handler must return a string.\");\n }\n\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * throw otherwise, e.g. if `errorHandler` is not defined or set to `false`\n */\n throw error;\n }\n\n #areMoreStepsNeeded(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n response: BaseMessage\n ): boolean {\n const allToolsReturnDirect =\n response instanceof AIMessage &&\n response.tool_calls?.every((call) =>\n this.#options.shouldReturnDirect.has(call.name)\n );\n const remainingSteps =\n \"remainingSteps\" in state ? (state.remainingSteps as number) : undefined;\n return Boolean(\n remainingSteps &&\n ((remainingSteps < 1 && allToolsReturnDirect) ||\n (remainingSteps < 2 && hasToolCalls(state.messages)))\n );\n }\n\n #getModelInputState(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"]\n ): Omit<InternalAgentState<StructuredResponseFormat>, \"llmInputMessages\"> {\n const { messages, llmInputMessages, ...rest } = state;\n if (llmInputMessages && llmInputMessages.length > 0) {\n return { messages: llmInputMessages, ...rest } as Omit<\n InternalAgentState<StructuredResponseFormat>,\n \"llmInputMessages\"\n >;\n }\n return { messages, ...rest } as Omit<\n InternalAgentState<StructuredResponseFormat>,\n \"llmInputMessages\"\n >;\n }\n\n async #bindTools(model: LanguageModelLike): Promise<Runnable> {\n const options: Partial<BaseChatModelCallOptions> = {};\n const structuredTools = Object.values(this.#structuredToolInfo);\n const allTools = this.#options.toolClasses.concat(\n ...structuredTools.map((toolStrategy) => toolStrategy.tool)\n );\n\n /**\n * If there are structured tools, we need to set the tool choice to \"any\"\n * so that the model can choose to use a structured tool or not.\n */\n const toolChoice = structuredTools.length > 0 ? \"any\" : undefined;\n\n /**\n * check if the user requests a native schema output\n */\n if (this.#options.responseFormat instanceof ProviderStrategy) {\n /**\n * if the model does not support JSON schema output, throw an error\n */\n if (!hasSupportForJsonSchemaOutput(model)) {\n throw new Error(\n \"Model does not support native structured output responses. Please use a model that supports native structured output responses or use a tool output.\"\n );\n }\n\n const jsonSchemaParams = {\n name: this.#options.responseFormat.schema?.name ?? \"extract\",\n description: getSchemaDescription(this.#options.responseFormat.schema),\n schema: this.#options.responseFormat.schema,\n strict: true,\n };\n\n Object.assign(options, {\n response_format: {\n type: \"json_schema\",\n json_schema: jsonSchemaParams,\n },\n ls_structured_output_format: {\n kwargs: { method: \"json_schema\" },\n schema: this.#options.responseFormat.schema,\n },\n strict: true,\n });\n }\n\n /**\n * Bind tools to the model if they are not already bound.\n */\n const modelWithTools = await bindTools(model, allTools, {\n ...options,\n tool_choice: toolChoice,\n });\n\n /**\n * Create a model runnable with the prompt and agent name\n */\n const modelRunnable = getPromptRunnable(this.#options.prompt).pipe(\n this.#options.includeAgentName === \"inline\"\n ? withAgentName(modelWithTools, this.#options.includeAgentName)\n : modelWithTools\n );\n\n return modelRunnable;\n }\n}\n"],"mappings":";;;;;;;;;;;;AAiEA,IAAa,YAAb,cAOU,iBAGR;CACA;CAMA,sBAAoD,CAAE;CAEtD,YACEA,SAKA;EACA,MAAM;GACJ,MAAM,QAAQ,QAAQ;GACtB,MAAM,CAAC,OAAO,WACZ,KAAKC,KAAK,OAAO,OAAyB;EAC7C,EAAC;EAEF,KAAKC,WAAW;;;;EAKhB,KAAKC,sBACH,wBAAwB,KAAKD,SAAS,eAAe,CAAC,OACpD,CAAC,WAAW,kBAAkB,aAC/B,CACD,OAAO,CAAC,KAAK,WAAW;GACxB,IAAI,OAAO,QAAQ;AACnB,UAAO;EACR,GAAE,CAAE,EAAiC;CACvC;CAED,MAAMD,KACJG,OAEAC,QACA;;;;;EAKA,MAAM,cAAc,MAAM,SAAS,MAAM,SAAS,SAAS;AAC3D,MACE,uBAAuB,eACvB,YAAY,QACZ,KAAKH,SAAS,mBAAmB,IAAI,YAAY,KAAK;;;;AAKtD,SAAO,EAAE,UAAU,CAAE,EAAE;EAGzB,MAAMI,WAIJ,MAAM,KAAKC,aAAa,OAAO,OAAO;;;;AAKxC,MAAI,wBAAwB,SAC1B,QAAO;;;;AAMT,MAAI,oBAAoB,QACtB,QAAO;EAGT,SAAS,OAAO,KAAK;EACrB,SAAS,UAAU,OAAO,KAAK;AAE/B,MAAI,KAAKC,oBAAoB,OAAO,SAAS,CAC3C,QAAO,EACL,UAAU,CACR,IAAI,UAAU,mDAAmD;GAC/D,MAAM,KAAK;GACX,WAAW,EAAE,MAAM,KAAK,KAAM;GAC9B,IAAI,SAAS;EACd,EACF,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D,MAAM,iBAAiB,MAAM,UAAU,OAAO,UAAU;GACtD,GAAG;GACH,aAAa;EACd,EAAC;;;;EAKF,MAAM,gBAAgB,kBAAkB,KAAKA,SAAS,OAAO,CAAC,KAC5D,KAAKA,SAAS,qBAAqB,WAC/B,cAAc,gBAAgB,KAAKA,SAAS,iBAAiB,GAC7D,eACL;AAED,SAAO;CACR;AACF"}
|
|
1
|
+
{"version":3,"file":"AgentNode.js","names":["options: AgentNodeOptions<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema\n >","#run","#options","#structuredToolInfo","state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"]","config: RunnableConfig","#invokeModel","#areMoreStepsNeeded","options: {\n lastMessage?: string;\n }","#deriveModel","#bindTools","#getModelInputState","#handleMultipleStructuredOutputs","#handleSingleStructuredOutput","response: AIMessage","toolCalls: ToolCall[]","#handleToolStrategyError","toolCall: ToolCall","lastMessage?: string","error: ToolStrategyError","response: BaseMessage","model: LanguageModelLike","options: Partial<BaseChatModelCallOptions>"],"sources":["../../../src/agents/nodes/AgentNode.ts"],"sourcesContent":["/* eslint-disable no-instanceof/no-instanceof */\nimport { Runnable, RunnableConfig } from \"@langchain/core/runnables\";\nimport { BaseMessage, AIMessage, ToolMessage } from \"@langchain/core/messages\";\nimport { Command } from \"@langchain/langgraph\";\nimport { type LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { type BaseChatModelCallOptions } from \"@langchain/core/language_models/chat_models\";\nimport {\n InteropZodObject,\n getSchemaDescription,\n} from \"@langchain/core/utils/types\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\n\nimport { initChatModel } from \"../../chat_models/universal.js\";\nimport { MultipleStructuredOutputsError } from \"../errors.js\";\nimport { RunnableCallable } from \"../RunnableCallable.js\";\nimport { PreHookAnnotation, AnyAnnotationRoot } from \"../annotation.js\";\nimport { mergeAbortSignals } from \"./utils.js\";\nimport {\n bindTools,\n getPromptRunnable,\n validateLLMHasNoBoundTools,\n hasToolCalls,\n hasSupportForJsonSchemaOutput,\n} from \"../utils.js\";\nimport {\n InternalAgentState,\n ClientTool,\n ServerTool,\n CreateAgentParams,\n} from \"../types.js\";\nimport { withAgentName } from \"../withAgentName.js\";\nimport {\n ToolStrategy,\n ProviderStrategy,\n transformResponseFormat,\n ToolStrategyError,\n} from \"../responses.js\";\n\ntype ResponseHandlerResult<StructuredResponseFormat> =\n | {\n structuredResponse: StructuredResponseFormat;\n messages: BaseMessage[];\n }\n | Promise<Command>;\n\nexport interface AgentNodeOptions<\n StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> extends Pick<\n CreateAgentParams<StateSchema, StructuredResponseFormat, ContextSchema>,\n \"llm\" | \"model\" | \"prompt\" | \"includeAgentName\" | \"name\" | \"responseFormat\"\n > {\n toolClasses: (ClientTool | ServerTool)[];\n shouldReturnDirect: Set<string>;\n signal?: AbortSignal;\n}\n\nexport class AgentNode<\n StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> extends RunnableCallable<\n InternalAgentState<StructuredResponseFormat> & PreHookAnnotation[\"State\"],\n { messages: BaseMessage[] } | { structuredResponse: StructuredResponseFormat }\n> {\n #options: AgentNodeOptions<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema\n >;\n\n #structuredToolInfo: Record<string, ToolStrategy> = {};\n\n constructor(\n options: AgentNodeOptions<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema\n >\n ) {\n super({\n name: options.name ?? \"model\",\n func: (input, config) =>\n this.#run(input, config as RunnableConfig) as any,\n });\n\n this.#options = options;\n\n /**\n * Populate a list of structured tool info.\n */\n this.#structuredToolInfo = (\n transformResponseFormat(this.#options.responseFormat).filter(\n (format) => format instanceof ToolStrategy\n ) as ToolStrategy[]\n ).reduce((acc, format) => {\n acc[format.name] = format;\n return acc;\n }, {} as Record<string, ToolStrategy>);\n }\n\n async #run(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig\n ) {\n /**\n * Check if we just executed a returnDirect tool\n * If so, we should generate structured response (if needed) and stop\n */\n const lastMessage = state.messages[state.messages.length - 1];\n if (\n lastMessage instanceof ToolMessage &&\n lastMessage.name &&\n this.#options.shouldReturnDirect.has(lastMessage.name)\n ) {\n /**\n * return directly without invoking the model again\n */\n return { messages: [] };\n }\n\n const response = await this.#invokeModel(state, config);\n\n /**\n * if we were able to generate a structured response, return it\n */\n if (\"structuredResponse\" in response) {\n return {\n messages: [...state.messages, ...(response.messages || [])],\n structuredResponse: response.structuredResponse,\n };\n }\n\n /**\n * if we need to direct the agent to the model, return the update\n */\n if (response instanceof Command) {\n return response;\n }\n\n response.name = this.name;\n response.lc_kwargs.name = this.name;\n\n if (this.#areMoreStepsNeeded(state, response)) {\n return {\n messages: [\n new AIMessage(\"Sorry, need more steps to process this request.\", {\n name: this.name,\n lc_kwargs: { name: this.name },\n id: response.id,\n }),\n ],\n };\n }\n\n return { messages: [response] };\n }\n\n /**\n * Derive the model from the options.\n * @param state - The state of the agent.\n * @param config - The config of the agent.\n * @returns The model.\n */\n #deriveModel(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig\n ) {\n if (this.#options.model) {\n if (typeof this.#options.model === \"string\") {\n return initChatModel(this.#options.model);\n }\n\n throw new Error(\"`model` option must be a string.\");\n }\n\n const model = this.#options.llm;\n\n /**\n * If the model is a function, call it to get the model.\n */\n if (typeof model === \"function\") {\n return model(state, config);\n }\n\n if (model) {\n return model;\n }\n\n throw new Error(\n \"No model option was provided, either via `model` or via `llm` option.\"\n );\n }\n\n async #invokeModel(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig,\n options: {\n lastMessage?: string;\n } = {}\n ): Promise<AIMessage | ResponseHandlerResult<StructuredResponseFormat>> {\n const model = await this.#deriveModel(state, config);\n\n /**\n * Check if the LLM already has bound tools and throw if it does.\n */\n validateLLMHasNoBoundTools(model);\n\n const modelWithTools = await this.#bindTools(model);\n const modelInput = this.#getModelInputState(state);\n const signal = mergeAbortSignals(this.#options.signal, config.signal);\n const invokeConfig = {\n ...config,\n signal,\n };\n\n const response = (await modelWithTools.invoke(\n modelInput,\n invokeConfig\n )) as AIMessage;\n\n /**\n * if the user requests a native schema output, try to parse the response\n * and return the structured response if it is valid\n */\n if (this.#options.responseFormat instanceof ProviderStrategy) {\n const structuredResponse = this.#options.responseFormat.parse(response);\n if (structuredResponse) {\n return { structuredResponse, messages: [response] };\n }\n }\n\n if (!response.tool_calls) {\n return response;\n }\n\n const toolCalls = response.tool_calls.filter(\n (call) => call.name in this.#structuredToolInfo\n );\n\n /**\n * if there were not structured tool calls, we can return the response\n */\n if (toolCalls.length === 0) {\n return response;\n }\n\n /**\n * if there were multiple structured tool calls, we should throw an error as this\n * scenario is not defined/supported.\n */\n if (toolCalls.length > 1) {\n return this.#handleMultipleStructuredOutputs(response, toolCalls);\n }\n\n const toolStrategy = this.#structuredToolInfo[toolCalls[0].name];\n const toolMessageContent = toolStrategy?.options?.toolMessageContent;\n return this.#handleSingleStructuredOutput(\n response,\n toolCalls[0],\n toolMessageContent ?? options.lastMessage\n );\n }\n\n /**\n * If the model returns multiple structured outputs, we need to handle it.\n * @param response - The response from the model\n * @param toolCalls - The tool calls that were made\n * @returns The response from the model\n */\n #handleMultipleStructuredOutputs(\n response: AIMessage,\n toolCalls: ToolCall[]\n ): Promise<Command> {\n /**\n * the following should never happen, let's throw an error if it does\n */\n if (this.#options.responseFormat instanceof ProviderStrategy) {\n throw new Error(\n \"Multiple structured outputs should not apply to native structured output responses\"\n );\n }\n\n const multipleStructuredOutputsError = new MultipleStructuredOutputsError(\n toolCalls.map((call) => call.name)\n );\n\n return this.#handleToolStrategyError(\n multipleStructuredOutputsError,\n response,\n toolCalls[0]\n );\n }\n\n /**\n * If the model returns a single structured output, we need to handle it.\n * @param toolCall - The tool call that was made\n * @returns The structured response and a message to the LLM if needed\n */\n #handleSingleStructuredOutput(\n response: AIMessage,\n toolCall: ToolCall,\n lastMessage?: string\n ): ResponseHandlerResult<StructuredResponseFormat> {\n const tool = this.#structuredToolInfo[toolCall.name];\n\n try {\n const structuredResponse = tool.parse(\n toolCall.args\n ) as StructuredResponseFormat;\n\n return {\n structuredResponse,\n messages: [\n response,\n new AIMessage(\n lastMessage ??\n `Returning structured response: ${JSON.stringify(\n structuredResponse\n )}`\n ),\n ],\n };\n } catch (error) {\n return this.#handleToolStrategyError(\n error as ToolStrategyError,\n response,\n toolCall\n );\n }\n }\n\n async #handleToolStrategyError(\n error: ToolStrategyError,\n response: AIMessage,\n toolCall: ToolCall\n ): Promise<Command> {\n /**\n * Using the `errorHandler` option of the first `ToolStrategy` entry is sufficient here.\n * There is technically only one `ToolStrategy` entry in `structuredToolInfo` if the user\n * uses `toolStrategy` to define the response format. If the user applies a list of json\n * schema objects, these will be transformed into multiple `ToolStrategy` entries but all\n * with the same `handleError` option.\n */\n const errorHandler = Object.values(this.#structuredToolInfo).at(0)?.options\n ?.handleError;\n\n const toolCallId = toolCall.id;\n if (!toolCallId) {\n throw new Error(\n \"Tool call ID is required to handle tool output errors. Please provide a tool call ID.\"\n );\n }\n\n /**\n * retry if:\n */\n if (\n /**\n * if the user has provided `true` as the `errorHandler` option, return a new AIMessage\n * with the error message and retry the tool call.\n */\n (typeof errorHandler === \"boolean\" && errorHandler) ||\n /**\n * if `errorHandler` is an array and contains MultipleStructuredOutputsError\n */\n (Array.isArray(errorHandler) &&\n errorHandler.some((h) => h instanceof MultipleStructuredOutputsError))\n ) {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: error.message,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * if `errorHandler` is a string, retry the tool call with given string\n */\n if (typeof errorHandler === \"string\") {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: errorHandler,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * if `errorHandler` is a function, retry the tool call with the function\n */\n if (typeof errorHandler === \"function\") {\n const content = await errorHandler(error);\n if (typeof content !== \"string\") {\n throw new Error(\"Error handler must return a string.\");\n }\n\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * throw otherwise, e.g. if `errorHandler` is not defined or set to `false`\n */\n throw error;\n }\n\n #areMoreStepsNeeded(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n response: BaseMessage\n ): boolean {\n const allToolsReturnDirect =\n response instanceof AIMessage &&\n response.tool_calls?.every((call) =>\n this.#options.shouldReturnDirect.has(call.name)\n );\n const remainingSteps =\n \"remainingSteps\" in state ? (state.remainingSteps as number) : undefined;\n return Boolean(\n remainingSteps &&\n ((remainingSteps < 1 && allToolsReturnDirect) ||\n (remainingSteps < 2 && hasToolCalls(state.messages)))\n );\n }\n\n #getModelInputState(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"]\n ): Omit<InternalAgentState<StructuredResponseFormat>, \"llmInputMessages\"> {\n const { messages, llmInputMessages, ...rest } = state;\n if (llmInputMessages && llmInputMessages.length > 0) {\n return { messages: llmInputMessages, ...rest } as Omit<\n InternalAgentState<StructuredResponseFormat>,\n \"llmInputMessages\"\n >;\n }\n return { messages, ...rest } as Omit<\n InternalAgentState<StructuredResponseFormat>,\n \"llmInputMessages\"\n >;\n }\n\n async #bindTools(model: LanguageModelLike): Promise<Runnable> {\n const options: Partial<BaseChatModelCallOptions> = {};\n const structuredTools = Object.values(this.#structuredToolInfo);\n const allTools = this.#options.toolClasses.concat(\n ...structuredTools.map((toolStrategy) => toolStrategy.tool)\n );\n\n /**\n * If there are structured tools, we need to set the tool choice to \"any\"\n * so that the model can choose to use a structured tool or not.\n */\n const toolChoice = structuredTools.length > 0 ? \"any\" : undefined;\n\n /**\n * check if the user requests a native schema output\n */\n if (this.#options.responseFormat instanceof ProviderStrategy) {\n /**\n * if the model does not support JSON schema output, throw an error\n */\n if (!hasSupportForJsonSchemaOutput(model)) {\n throw new Error(\n \"Model does not support native structured output responses. Please use a model that supports native structured output responses or use a tool output.\"\n );\n }\n\n const jsonSchemaParams = {\n name: this.#options.responseFormat.schema?.name ?? \"extract\",\n description: getSchemaDescription(this.#options.responseFormat.schema),\n schema: this.#options.responseFormat.schema,\n strict: true,\n };\n\n Object.assign(options, {\n response_format: {\n type: \"json_schema\",\n json_schema: jsonSchemaParams,\n },\n ls_structured_output_format: {\n kwargs: { method: \"json_schema\" },\n schema: this.#options.responseFormat.schema,\n },\n strict: true,\n });\n }\n\n /**\n * Bind tools to the model if they are not already bound.\n */\n const modelWithTools = await bindTools(model, allTools, {\n ...options,\n tool_choice: toolChoice,\n });\n\n /**\n * Create a model runnable with the prompt and agent name\n */\n const modelRunnable = getPromptRunnable(this.#options.prompt).pipe(\n this.#options.includeAgentName === \"inline\"\n ? withAgentName(modelWithTools, this.#options.includeAgentName)\n : modelWithTools\n );\n\n return modelRunnable;\n }\n}\n"],"mappings":";;;;;;;;;;;;AA6DA,IAAa,YAAb,cAOU,iBAGR;CACA;CAMA,sBAAoD,CAAE;CAEtD,YACEA,SAKA;EACA,MAAM;GACJ,MAAM,QAAQ,QAAQ;GACtB,MAAM,CAAC,OAAO,WACZ,KAAKC,KAAK,OAAO,OAAyB;EAC7C,EAAC;EAEF,KAAKC,WAAW;;;;EAKhB,KAAKC,sBACH,wBAAwB,KAAKD,SAAS,eAAe,CAAC,OACpD,CAAC,WAAW,kBAAkB,aAC/B,CACD,OAAO,CAAC,KAAK,WAAW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I,oBAAoB,iBAAiB,SAAS,EAChD,QAAO;GAAE,UAAU;GAAkB,GAAG;EAAM;AAKhD,SAAO;GAAE;GAAU,GAAG;EAAM;CAI7B;CAED,MAAMM,WAAWW,OAA6C;EAC5D,MAAMC,UAA6C,CAAE;EACrD,MAAM,kBAAkB,OAAO,OAAO,KAAKnB,oBAAoB;EAC/D,MAAM,WAAW,KAAKD,SAAS,YAAY,OACzC,GAAG,gBAAgB,IAAI,CAAC,iBAAiB,aAAa,KAAK,CAC5D;;;;;EAMD,MAAM,aAAa,gBAAgB,SAAS,IAAI,QAAQ;;;;AAKxD,MAAI,KAAKA,SAAS,0BAA0B,kBAAkB;;;;AAI5D,OAAI,CAAC,8BAA8B,MAAM,CACvC,OAAM,IAAI,MACR;GAIJ,MAAM,mBAAmB;IACvB,MAAM,KAAKA,SAAS,eAAe,QAAQ,QAAQ;IACnD,aAAa,qBAAqB,KAAKA,SAAS,eAAe,OAAO;IACtE,QAAQ,KAAKA,SAAS,eAAe;IACrC,QAAQ;GACT;GAED,OAAO,OAAO,SAAS;IACrB,iBAAiB;KACf,MAAM;KACN,aAAa;IACd;IACD,6BAA6B;KAC3B,QAAQ,EAAE,QAAQ,cAAe;KACjC,QAAQ,KAAKA,SAAS,eAAe;IACtC;IACD,QAAQ;GACT,EAAC;EACH;;;;EAKD,MAAM,iBAAiB,MAAM,UAAU,OAAO,UAAU;GACtD,GAAG;GACH,aAAa;EACd,EAAC;;;;EAKF,MAAM,gBAAgB,kBAAkB,KAAKA,SAAS,OAAO,CAAC,KAC5D,KAAKA,SAAS,qBAAqB,WAC/B,cAAc,gBAAgB,KAAKA,SAAS,iBAAiB,GAC7D,eACL;AAED,SAAO;CACR;AACF"}
|
|
@@ -12,7 +12,7 @@ const isMessagesState = (input) => typeof input === "object" && input != null &&
|
|
|
12
12
|
const isSendInput = (input) => typeof input === "object" && input != null && "lg_tool_call" in input;
|
|
13
13
|
/**
|
|
14
14
|
* `ToolNode` is a built-in LangGraph component that handles tool calls within an agent's workflow.
|
|
15
|
-
* It works seamlessly with `
|
|
15
|
+
* It works seamlessly with `createAgent`, offering advanced tool execution control, built
|
|
16
16
|
* in parallelism, and error handling.
|
|
17
17
|
*
|
|
18
18
|
* @example
|
|
@@ -117,7 +117,7 @@ var ToolNode = class extends require_RunnableCallable.RunnableCallable {
|
|
|
117
117
|
if (result && (0, __langchain_core_messages.isToolMessage)(result)) return result;
|
|
118
118
|
} else if (this.handleToolErrors) return new __langchain_core_messages.ToolMessage({
|
|
119
119
|
name: call.name,
|
|
120
|
-
content:
|
|
120
|
+
content: `${e}\n Please fix your mistakes.`,
|
|
121
121
|
tool_call_id: call.id
|
|
122
122
|
});
|
|
123
123
|
/**
|