@langchain/core 1.1.31 → 1.1.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/dist/language_models/base.cjs +1 -1
- package/dist/language_models/base.js +1 -1
- package/dist/messages/ai.cjs.map +1 -1
- package/dist/messages/ai.js.map +1 -1
- package/dist/messages/base.cjs +4 -3
- package/dist/messages/base.cjs.map +1 -1
- package/dist/messages/base.d.cts.map +1 -1
- package/dist/messages/base.d.ts.map +1 -1
- package/dist/messages/base.js +4 -3
- package/dist/messages/base.js.map +1 -1
- package/dist/messages/block_translators/google.cjs +16 -1
- package/dist/messages/block_translators/google.cjs.map +1 -1
- package/dist/messages/block_translators/google.js +16 -1
- package/dist/messages/block_translators/google.js.map +1 -1
- package/dist/testing/fake_model_builder.cjs +69 -17
- package/dist/testing/fake_model_builder.cjs.map +1 -1
- package/dist/testing/fake_model_builder.d.cts +69 -18
- package/dist/testing/fake_model_builder.d.cts.map +1 -1
- package/dist/testing/fake_model_builder.d.ts +69 -18
- package/dist/testing/fake_model_builder.d.ts.map +1 -1
- package/dist/testing/fake_model_builder.js +69 -18
- package/dist/testing/fake_model_builder.js.map +1 -1
- package/dist/testing/index.cjs +2 -0
- package/dist/testing/index.cjs.map +1 -1
- package/dist/testing/index.d.cts +2 -2
- package/dist/testing/index.d.ts +2 -2
- package/dist/testing/index.js +3 -2
- package/dist/testing/index.js.map +1 -1
- package/dist/tools/index.cjs +4 -0
- package/dist/tools/index.cjs.map +1 -1
- package/dist/tools/index.d.cts +22 -21
- package/dist/tools/index.d.cts.map +1 -1
- package/dist/tools/index.d.ts +22 -21
- package/dist/tools/index.d.ts.map +1 -1
- package/dist/tools/index.js +4 -0
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/types.cjs.map +1 -1
- package/dist/tools/types.d.cts +13 -5
- package/dist/tools/types.d.cts.map +1 -1
- package/dist/tools/types.d.ts +13 -5
- package/dist/tools/types.d.ts.map +1 -1
- package/dist/tools/types.js.map +1 -1
- package/package.json +2 -2
|
@@ -18,22 +18,8 @@ function nextToolCallId() {
|
|
|
18
18
|
*
|
|
19
19
|
* Queue responses with `.respond()` and `.respondWithTools()`, then
|
|
20
20
|
* pass the instance directly wherever a chat model is expected.
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
* `.respond(entry)` — enqueue a `BaseMessage`, `Error`, or factory function.
|
|
25
|
-
*
|
|
26
|
-
* `.respondWithTools(toolCalls[])` — enqueue an `AIMessage` with the given
|
|
27
|
-
* tool calls. Content is derived from the input messages automatically.
|
|
28
|
-
*
|
|
29
|
-
* Both can be mixed freely in one chain. When all queued responses are
|
|
30
|
-
* consumed, further invocations throw.
|
|
31
|
-
*
|
|
32
|
-
* Additional configuration:
|
|
33
|
-
* - `.alwaysThrow(error)` — every call throws (overrides the queue)
|
|
34
|
-
* - `.structuredResponse(value)` — value returned by `withStructuredOutput()`
|
|
35
|
-
*
|
|
36
|
-
* The model records all invocations in `.calls` / `.callCount`.
|
|
21
|
+
* Responses are consumed in first-in-first-out order — one per `invoke()` call.
|
|
22
|
+
* When all queued responses are consumed, further invocations throw.
|
|
37
23
|
*/
|
|
38
24
|
var FakeBuiltModel = class FakeBuiltModel extends BaseChatModel {
|
|
39
25
|
queue = [];
|
|
@@ -42,9 +28,17 @@ var FakeBuiltModel = class FakeBuiltModel extends BaseChatModel {
|
|
|
42
28
|
_tools = [];
|
|
43
29
|
_callIndex = 0;
|
|
44
30
|
_calls = [];
|
|
31
|
+
/**
|
|
32
|
+
* All invocations recorded by this model, in order.
|
|
33
|
+
* Each entry contains the `messages` array and `options` that were
|
|
34
|
+
* passed to `invoke()`.
|
|
35
|
+
*/
|
|
45
36
|
get calls() {
|
|
46
37
|
return this._calls;
|
|
47
38
|
}
|
|
39
|
+
/**
|
|
40
|
+
* The number of times this model has been invoked.
|
|
41
|
+
*/
|
|
48
42
|
get callCount() {
|
|
49
43
|
return this._calls.length;
|
|
50
44
|
}
|
|
@@ -57,6 +51,12 @@ var FakeBuiltModel = class FakeBuiltModel extends BaseChatModel {
|
|
|
57
51
|
_combineLLMOutput() {
|
|
58
52
|
return [];
|
|
59
53
|
}
|
|
54
|
+
/**
|
|
55
|
+
* Enqueue a response that the model will return on its next invocation.
|
|
56
|
+
* @param entry A {@link BaseMessage} to return, an `Error` to throw, or
|
|
57
|
+
* a factory `(messages) => BaseMessage | Error` for dynamic responses.
|
|
58
|
+
* @returns `this`, for chaining.
|
|
59
|
+
*/
|
|
60
60
|
respond(entry) {
|
|
61
61
|
if (typeof entry === "function") this.queue.push({
|
|
62
62
|
kind: "factory",
|
|
@@ -72,6 +72,13 @@ var FakeBuiltModel = class FakeBuiltModel extends BaseChatModel {
|
|
|
72
72
|
});
|
|
73
73
|
return this;
|
|
74
74
|
}
|
|
75
|
+
/**
|
|
76
|
+
* Enqueue an {@link AIMessage} that carries the given tool calls.
|
|
77
|
+
* Content is derived from the input messages at invocation time.
|
|
78
|
+
* @param toolCalls Array of tool calls. Each entry needs `name` and
|
|
79
|
+
* `args`; `id` is optional and auto-generated when omitted.
|
|
80
|
+
* @returns `this`, for chaining.
|
|
81
|
+
*/
|
|
75
82
|
respondWithTools(toolCalls) {
|
|
76
83
|
this.queue.push({
|
|
77
84
|
kind: "toolCalls",
|
|
@@ -84,14 +91,31 @@ var FakeBuiltModel = class FakeBuiltModel extends BaseChatModel {
|
|
|
84
91
|
});
|
|
85
92
|
return this;
|
|
86
93
|
}
|
|
94
|
+
/**
|
|
95
|
+
* Make every invocation throw the given error, regardless of the queue.
|
|
96
|
+
* @param error The error to throw.
|
|
97
|
+
* @returns `this`, for chaining.
|
|
98
|
+
*/
|
|
87
99
|
alwaysThrow(error) {
|
|
88
100
|
this._alwaysThrowError = error;
|
|
89
101
|
return this;
|
|
90
102
|
}
|
|
103
|
+
/**
|
|
104
|
+
* Set the value that {@link withStructuredOutput} will resolve to.
|
|
105
|
+
* @param value The structured object to return.
|
|
106
|
+
* @returns `this`, for chaining.
|
|
107
|
+
*/
|
|
91
108
|
structuredResponse(value) {
|
|
92
109
|
this._structuredResponseValue = value;
|
|
93
110
|
return this;
|
|
94
111
|
}
|
|
112
|
+
/**
|
|
113
|
+
* Bind tools to the model. Returns a new model that shares the same
|
|
114
|
+
* response queue and call history.
|
|
115
|
+
* @param tools The tools to bind, as {@link StructuredTool} instances or
|
|
116
|
+
* plain {@link ToolSpec} objects.
|
|
117
|
+
* @returns A new RunnableBinding with the tools bound.
|
|
118
|
+
*/
|
|
95
119
|
bindTools(tools) {
|
|
96
120
|
const merged = [...this._tools, ...tools];
|
|
97
121
|
const next = new FakeBuiltModel();
|
|
@@ -103,6 +127,13 @@ var FakeBuiltModel = class FakeBuiltModel extends BaseChatModel {
|
|
|
103
127
|
next._callIndex = this._callIndex;
|
|
104
128
|
return next.withConfig({});
|
|
105
129
|
}
|
|
130
|
+
/**
|
|
131
|
+
* Returns a {@link Runnable} that produces the {@link structuredResponse}
|
|
132
|
+
* value. The schema argument is accepted for compatibility but ignored.
|
|
133
|
+
* @param _params Schema or params (ignored).
|
|
134
|
+
* @param _config Options (ignored).
|
|
135
|
+
* @returns A Runnable that resolves to the structured response value.
|
|
136
|
+
*/
|
|
106
137
|
withStructuredOutput(_params, _config) {
|
|
107
138
|
const { _structuredResponseValue } = this;
|
|
108
139
|
return RunnableLambda.from(async () => {
|
|
@@ -150,7 +181,27 @@ var FakeBuiltModel = class FakeBuiltModel extends BaseChatModel {
|
|
|
150
181
|
}
|
|
151
182
|
};
|
|
152
183
|
/**
|
|
153
|
-
* Creates a
|
|
184
|
+
* Creates a new {@link FakeBuiltModel} for testing.
|
|
185
|
+
*
|
|
186
|
+
* Returns a chainable builder — queue responses, then pass the model
|
|
187
|
+
* anywhere a chat model is expected. Responses are consumed in FIFO
|
|
188
|
+
* order, one per `invoke()` call.
|
|
189
|
+
*
|
|
190
|
+
* ## API summary
|
|
191
|
+
*
|
|
192
|
+
* | Method | Description |
|
|
193
|
+
* | --- | --- |
|
|
194
|
+
* | `fakeModel()` | Creates a new fake chat model. Returns a chainable builder. |
|
|
195
|
+
* | `.respond(message)` | Queue an `AIMessage` (or any `BaseMessage`) to return on the next invocation. |
|
|
196
|
+
* | `.respond(error)` | Queue an `Error` to throw on the next invocation. |
|
|
197
|
+
* | `.respond(factory)` | Queue a function `(messages) => BaseMessage \| Error` for dynamic responses. |
|
|
198
|
+
* | `.respondWithTools(toolCalls)` | Shorthand for `.respond()` with tool calls. Each entry needs `name` and `args`; `id` is optional. |
|
|
199
|
+
* | `.alwaysThrow(error)` | Make every invocation throw this error, regardless of the queue. |
|
|
200
|
+
* | `.structuredResponse(value)` | Set the value returned by `.withStructuredOutput()`. |
|
|
201
|
+
* | `.bindTools(tools)` | Bind tools to the model. Returns a `RunnableBinding` that shares the response queue and call recording. |
|
|
202
|
+
* | `.withStructuredOutput(schema)` | Returns a runnable that produces the `.structuredResponse()` value. |
|
|
203
|
+
* | `.calls` | Array of `{ messages, options }` for every invocation (read-only). |
|
|
204
|
+
* | `.callCount` | Number of times the model has been invoked. |
|
|
154
205
|
*
|
|
155
206
|
* @example
|
|
156
207
|
* ```typescript
|
|
@@ -170,5 +221,5 @@ function fakeModel() {
|
|
|
170
221
|
}
|
|
171
222
|
|
|
172
223
|
//#endregion
|
|
173
|
-
export { fakeModel };
|
|
224
|
+
export { FakeBuiltModel, fakeModel };
|
|
174
225
|
//# sourceMappingURL=fake_model_builder.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fake_model_builder.js","names":[],"sources":["../../src/testing/fake_model_builder.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { CallbackManagerForLLMRun } from \"../callbacks/manager.js\";\nimport {\n BaseChatModel,\n BaseChatModelCallOptions,\n} from \"../language_models/chat_models.js\";\nimport {\n BaseLanguageModelInput,\n StructuredOutputMethodOptions,\n StructuredOutputMethodParams,\n} from \"../language_models/base.js\";\nimport { BaseMessage, AIMessage } from \"../messages/index.js\";\nimport type { ToolCall } from \"../messages/tool.js\";\nimport type { ChatResult } from \"../outputs.js\";\nimport { Runnable, RunnableLambda } from \"../runnables/base.js\";\nimport { StructuredTool } from \"../tools/index.js\";\nimport type { InteropZodType } from \"../utils/types/zod.js\";\nimport type { ToolSpec } from \"../utils/testing/chat_models.js\";\n\ntype ResponseFactory = (messages: BaseMessage[]) => BaseMessage | Error;\n\ntype QueueEntry =\n | { kind: \"message\"; message: BaseMessage }\n | { kind: \"toolCalls\"; toolCalls: ToolCall[] }\n | { kind: \"error\"; error: Error }\n | { kind: \"factory\"; factory: ResponseFactory };\n\ninterface FakeModelCall {\n messages: BaseMessage[];\n options: any;\n}\n\nfunction deriveContent(messages: BaseMessage[]): string {\n return messages\n .map((m) => m.text)\n .filter(Boolean)\n .join(\"-\");\n}\n\nlet idCounter = 0;\nfunction nextToolCallId(): string {\n idCounter += 1;\n return `fake_tc_${idCounter}`;\n}\n\n/**\n * A fake chat model for testing, created via {@link fakeModel}.\n *\n * Queue responses with `.respond()` and `.respondWithTools()`, then\n * pass the instance directly wherever a chat model is expected.\n *\n * Each builder method queues a model response consumed in order per `invoke()`:\n *\n * `.respond(entry)` — enqueue a `BaseMessage`, `Error`, or factory function.\n *\n * `.respondWithTools(toolCalls[])` — enqueue an `AIMessage` with the given\n * tool calls. Content is derived from the input messages automatically.\n *\n * Both can be mixed freely in one chain. When all queued responses are\n * consumed, further invocations throw.\n *\n * Additional configuration:\n * - `.alwaysThrow(error)` — every call throws (overrides the queue)\n * - `.structuredResponse(value)` — value returned by `withStructuredOutput()`\n *\n * The model records all invocations in `.calls` / `.callCount`.\n */\nclass FakeBuiltModel extends BaseChatModel {\n private queue: QueueEntry[] = [];\n\n private _alwaysThrowError: Error | undefined;\n\n private _structuredResponseValue: any;\n\n private _tools: (StructuredTool | ToolSpec)[] = [];\n\n private _callIndex = 0;\n\n private _calls: FakeModelCall[] = [];\n\n get calls(): FakeModelCall[] {\n return this._calls;\n }\n\n get callCount(): number {\n return this._calls.length;\n }\n\n constructor() {\n super({});\n }\n\n _llmType(): string {\n return \"fake-model-builder\";\n }\n\n _combineLLMOutput() {\n return [];\n }\n\n respond(entry: BaseMessage | Error | ResponseFactory): this {\n if (typeof entry === \"function\") {\n this.queue.push({ kind: \"factory\", factory: entry });\n } else if (BaseMessage.isInstance(entry)) {\n this.queue.push({ kind: \"message\", message: entry });\n } else {\n this.queue.push({ kind: \"error\", error: entry });\n }\n return this;\n }\n\n respondWithTools(\n toolCalls: Array<{ name: string; args: Record<string, any>; id?: string }>\n ): this {\n this.queue.push({\n kind: \"toolCalls\",\n toolCalls: toolCalls.map((tc) => ({\n name: tc.name,\n args: tc.args,\n id: tc.id ?? nextToolCallId(),\n type: \"tool_call\" as const,\n })),\n });\n return this;\n }\n\n alwaysThrow(error: Error): this {\n this._alwaysThrowError = error;\n return this;\n }\n\n structuredResponse(value: Record<string, any>): this {\n this._structuredResponseValue = value;\n return this;\n }\n\n bindTools(tools: (StructuredTool | ToolSpec)[]) {\n const merged = [...this._tools, ...tools];\n const next = new FakeBuiltModel();\n next.queue = this.queue;\n next._alwaysThrowError = this._alwaysThrowError;\n next._structuredResponseValue = this._structuredResponseValue;\n next._tools = merged;\n next._calls = this._calls;\n next._callIndex = this._callIndex;\n\n return next.withConfig({} as BaseChatModelCallOptions);\n }\n\n withStructuredOutput<\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n _params:\n | StructuredOutputMethodParams<RunOutput, boolean>\n | InteropZodType<RunOutput>\n | Record<string, any>,\n _config?: StructuredOutputMethodOptions<boolean>\n ):\n | Runnable<BaseLanguageModelInput, RunOutput>\n | Runnable<\n BaseLanguageModelInput,\n { raw: BaseMessage; parsed: RunOutput }\n > {\n const { _structuredResponseValue } = this;\n return RunnableLambda.from(async () => {\n return _structuredResponseValue as RunOutput;\n }) as Runnable;\n }\n\n async _generate(\n messages: BaseMessage[],\n options?: this[\"ParsedCallOptions\"],\n _runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n this._calls.push({ messages: [...messages], options });\n\n const currentCallIndex = this._callIndex;\n this._callIndex += 1;\n\n if (this._alwaysThrowError) {\n throw this._alwaysThrowError;\n }\n\n const entry = this.queue[currentCallIndex];\n if (!entry) {\n throw new Error(\n `FakeModel: no response queued for invocation ${currentCallIndex} (${this.queue.length} total queued).`\n );\n }\n\n if (entry.kind === \"error\") {\n throw entry.error;\n }\n\n if (entry.kind === \"factory\") {\n const result = entry.factory(messages);\n if (!BaseMessage.isInstance(result)) {\n throw result;\n }\n return {\n generations: [{ text: \"\", message: result }],\n };\n }\n\n if (entry.kind === \"message\") {\n return {\n generations: [{ text: \"\", message: entry.message }],\n };\n }\n\n const content = deriveContent(messages);\n const message = new AIMessage({\n content,\n id: currentCallIndex.toString(),\n tool_calls:\n entry.toolCalls.length > 0\n ? entry.toolCalls.map((tc) => ({\n ...tc,\n type: \"tool_call\" as const,\n }))\n : undefined,\n });\n\n return {\n generations: [{ text: content, message }],\n llmOutput: {},\n };\n }\n}\n\n/**\n * Creates a fake chat model for testing.\n *\n * @example\n * ```typescript\n * const model = fakeModel()\n * .respondWithTools([{ name: \"search\", args: { query: \"weather\" } }])\n * .respond(new AIMessage(\"Sunny and warm.\"));\n *\n * const r1 = await model.invoke([new HumanMessage(\"What's the weather?\")]);\n * // r1.tool_calls[0].name === \"search\"\n *\n * const r2 = await model.invoke([new HumanMessage(\"Thanks\")]);\n * // r2.content === \"Sunny and warm.\"\n * ```\n */\nexport function fakeModel(): FakeBuiltModel {\n return new FakeBuiltModel();\n}\n"],"mappings":";;;;;;;AAgCA,SAAS,cAAc,UAAiC;AACtD,QAAO,SACJ,KAAK,MAAM,EAAE,KAAK,CAClB,OAAO,QAAQ,CACf,KAAK,IAAI;;AAGd,IAAI,YAAY;AAChB,SAAS,iBAAyB;AAChC,cAAa;AACb,QAAO,WAAW;;;;;;;;;;;;;;;;;;;;;;;;AAyBpB,IAAM,iBAAN,MAAM,uBAAuB,c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C,SAAO,eAAe,KAAK,YAAY;AACrC,UAAO;IACP;;CAGJ,MAAM,UACJ,UACA,SACA,aACqB;AACrB,OAAK,OAAO,KAAK;GAAE,UAAU,CAAC,GAAG,SAAS;GAAE;GAAS,CAAC;EAEtD,MAAM,mBAAmB,KAAK;AAC9B,OAAK,cAAc;AAEnB,MAAI,KAAK,kBACP,OAAM,KAAK;EAGb,MAAM,QAAQ,KAAK,MAAM;AACzB,MAAI,CAAC,MACH,OAAM,IAAI,MACR,gDAAgD,iBAAiB,IAAI,KAAK,MAAM,OAAO,iBACxF;AAGH,MAAI,MAAM,SAAS,QACjB,OAAM,MAAM;AAGd,MAAI,MAAM,SAAS,WAAW;GAC5B,MAAM,SAAS,MAAM,QAAQ,SAAS;AACtC,OAAI,CAAC,YAAY,WAAW,OAAO,CACjC,OAAM;AAER,UAAO,EACL,aAAa,CAAC;IAAE,MAAM;IAAI,SAAS;IAAQ,CAAC,EAC7C;;AAGH,MAAI,MAAM,SAAS,UACjB,QAAO,EACL,aAAa,CAAC;GAAE,MAAM;GAAI,SAAS,MAAM;GAAS,CAAC,EACpD;EAGH,MAAM,UAAU,cAAc,SAAS;AAavC,SAAO;GACL,aAAa,CAAC;IAAE,MAAM;IAAS,SAbjB,IAAI,UAAU;KAC5B;KACA,IAAI,iBAAiB,UAAU;KAC/B,YACE,MAAM,UAAU,SAAS,IACrB,MAAM,UAAU,KAAK,QAAQ;MAC3B,GAAG;MACH,MAAM;MACP,EAAE,GACH;KACP,CAAC;IAGwC,CAAC;GACzC,WAAW,EAAE;GACd;;;;;;;;;;;;;;;;;;;AAoBL,SAAgB,YAA4B;AAC1C,QAAO,IAAI,gBAAgB"}
|
|
1
|
+
{"version":3,"file":"fake_model_builder.js","names":[],"sources":["../../src/testing/fake_model_builder.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { CallbackManagerForLLMRun } from \"../callbacks/manager.js\";\nimport {\n BaseChatModel,\n BaseChatModelCallOptions,\n} from \"../language_models/chat_models.js\";\nimport {\n BaseLanguageModelInput,\n StructuredOutputMethodOptions,\n StructuredOutputMethodParams,\n} from \"../language_models/base.js\";\nimport { BaseMessage, AIMessage } from \"../messages/index.js\";\nimport type { ToolCall } from \"../messages/tool.js\";\nimport type { ChatResult } from \"../outputs.js\";\nimport { Runnable, RunnableLambda } from \"../runnables/base.js\";\nimport { StructuredTool } from \"../tools/index.js\";\nimport type { InteropZodType } from \"../utils/types/zod.js\";\nimport type { ToolSpec } from \"../utils/testing/chat_models.js\";\n\ntype ResponseFactory = (messages: BaseMessage[]) => BaseMessage | Error;\n\ntype QueueEntry =\n | { kind: \"message\"; message: BaseMessage }\n | { kind: \"toolCalls\"; toolCalls: ToolCall[] }\n | { kind: \"error\"; error: Error }\n | { kind: \"factory\"; factory: ResponseFactory };\n\ninterface FakeModelCall {\n messages: BaseMessage[];\n options: any;\n}\n\nfunction deriveContent(messages: BaseMessage[]): string {\n return messages\n .map((m) => m.text)\n .filter(Boolean)\n .join(\"-\");\n}\n\nlet idCounter = 0;\nfunction nextToolCallId(): string {\n idCounter += 1;\n return `fake_tc_${idCounter}`;\n}\n\n/**\n * A fake chat model for testing, created via {@link fakeModel}.\n *\n * Queue responses with `.respond()` and `.respondWithTools()`, then\n * pass the instance directly wherever a chat model is expected.\n * Responses are consumed in first-in-first-out order — one per `invoke()` call.\n * When all queued responses are consumed, further invocations throw.\n */\nexport class FakeBuiltModel extends BaseChatModel {\n private queue: QueueEntry[] = [];\n\n private _alwaysThrowError: Error | undefined;\n\n private _structuredResponseValue: any;\n\n private _tools: (StructuredTool | ToolSpec)[] = [];\n\n private _callIndex = 0;\n\n private _calls: FakeModelCall[] = [];\n\n /**\n * All invocations recorded by this model, in order.\n * Each entry contains the `messages` array and `options` that were\n * passed to `invoke()`.\n */\n get calls(): FakeModelCall[] {\n return this._calls;\n }\n\n /**\n * The number of times this model has been invoked.\n */\n get callCount(): number {\n return this._calls.length;\n }\n\n constructor() {\n super({});\n }\n\n _llmType(): string {\n return \"fake-model-builder\";\n }\n\n _combineLLMOutput() {\n return [];\n }\n\n /**\n * Enqueue a response that the model will return on its next invocation.\n * @param entry A {@link BaseMessage} to return, an `Error` to throw, or\n * a factory `(messages) => BaseMessage | Error` for dynamic responses.\n * @returns `this`, for chaining.\n */\n respond(entry: BaseMessage | Error | ResponseFactory): this {\n if (typeof entry === \"function\") {\n this.queue.push({ kind: \"factory\", factory: entry });\n } else if (BaseMessage.isInstance(entry)) {\n this.queue.push({ kind: \"message\", message: entry });\n } else {\n this.queue.push({ kind: \"error\", error: entry });\n }\n return this;\n }\n\n /**\n * Enqueue an {@link AIMessage} that carries the given tool calls.\n * Content is derived from the input messages at invocation time.\n * @param toolCalls Array of tool calls. Each entry needs `name` and\n * `args`; `id` is optional and auto-generated when omitted.\n * @returns `this`, for chaining.\n */\n respondWithTools(\n toolCalls: Array<{ name: string; args: Record<string, any>; id?: string }>\n ): this {\n this.queue.push({\n kind: \"toolCalls\",\n toolCalls: toolCalls.map((tc) => ({\n name: tc.name,\n args: tc.args,\n id: tc.id ?? nextToolCallId(),\n type: \"tool_call\" as const,\n })),\n });\n return this;\n }\n\n /**\n * Make every invocation throw the given error, regardless of the queue.\n * @param error The error to throw.\n * @returns `this`, for chaining.\n */\n alwaysThrow(error: Error): this {\n this._alwaysThrowError = error;\n return this;\n }\n\n /**\n * Set the value that {@link withStructuredOutput} will resolve to.\n * @param value The structured object to return.\n * @returns `this`, for chaining.\n */\n structuredResponse(value: Record<string, any>): this {\n this._structuredResponseValue = value;\n return this;\n }\n\n /**\n * Bind tools to the model. Returns a new model that shares the same\n * response queue and call history.\n * @param tools The tools to bind, as {@link StructuredTool} instances or\n * plain {@link ToolSpec} objects.\n * @returns A new RunnableBinding with the tools bound.\n */\n bindTools(tools: (StructuredTool | ToolSpec)[]) {\n const merged = [...this._tools, ...tools];\n const next = new FakeBuiltModel();\n next.queue = this.queue;\n next._alwaysThrowError = this._alwaysThrowError;\n next._structuredResponseValue = this._structuredResponseValue;\n next._tools = merged;\n next._calls = this._calls;\n next._callIndex = this._callIndex;\n\n return next.withConfig({} as BaseChatModelCallOptions);\n }\n\n /**\n * Returns a {@link Runnable} that produces the {@link structuredResponse}\n * value. The schema argument is accepted for compatibility but ignored.\n * @param _params Schema or params (ignored).\n * @param _config Options (ignored).\n * @returns A Runnable that resolves to the structured response value.\n */\n withStructuredOutput<\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n _params:\n | StructuredOutputMethodParams<RunOutput, boolean>\n | InteropZodType<RunOutput>\n | Record<string, any>,\n _config?: StructuredOutputMethodOptions<boolean>\n ):\n | Runnable<BaseLanguageModelInput, RunOutput>\n | Runnable<\n BaseLanguageModelInput,\n { raw: BaseMessage; parsed: RunOutput }\n > {\n const { _structuredResponseValue } = this;\n return RunnableLambda.from(async () => {\n return _structuredResponseValue as RunOutput;\n }) as Runnable;\n }\n\n async _generate(\n messages: BaseMessage[],\n options?: this[\"ParsedCallOptions\"],\n _runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n this._calls.push({ messages: [...messages], options });\n\n const currentCallIndex = this._callIndex;\n this._callIndex += 1;\n\n if (this._alwaysThrowError) {\n throw this._alwaysThrowError;\n }\n\n const entry = this.queue[currentCallIndex];\n if (!entry) {\n throw new Error(\n `FakeModel: no response queued for invocation ${currentCallIndex} (${this.queue.length} total queued).`\n );\n }\n\n if (entry.kind === \"error\") {\n throw entry.error;\n }\n\n if (entry.kind === \"factory\") {\n const result = entry.factory(messages);\n if (!BaseMessage.isInstance(result)) {\n throw result;\n }\n return {\n generations: [{ text: \"\", message: result }],\n };\n }\n\n if (entry.kind === \"message\") {\n return {\n generations: [{ text: \"\", message: entry.message }],\n };\n }\n\n const content = deriveContent(messages);\n const message = new AIMessage({\n content,\n id: currentCallIndex.toString(),\n tool_calls:\n entry.toolCalls.length > 0\n ? entry.toolCalls.map((tc) => ({\n ...tc,\n type: \"tool_call\" as const,\n }))\n : undefined,\n });\n\n return {\n generations: [{ text: content, message }],\n llmOutput: {},\n };\n }\n}\n\n/**\n * Creates a new {@link FakeBuiltModel} for testing.\n *\n * Returns a chainable builder — queue responses, then pass the model\n * anywhere a chat model is expected. Responses are consumed in FIFO\n * order, one per `invoke()` call.\n *\n * ## API summary\n *\n * | Method | Description |\n * | --- | --- |\n * | `fakeModel()` | Creates a new fake chat model. Returns a chainable builder. |\n * | `.respond(message)` | Queue an `AIMessage` (or any `BaseMessage`) to return on the next invocation. |\n * | `.respond(error)` | Queue an `Error` to throw on the next invocation. |\n * | `.respond(factory)` | Queue a function `(messages) => BaseMessage \\| Error` for dynamic responses. |\n * | `.respondWithTools(toolCalls)` | Shorthand for `.respond()` with tool calls. Each entry needs `name` and `args`; `id` is optional. |\n * | `.alwaysThrow(error)` | Make every invocation throw this error, regardless of the queue. |\n * | `.structuredResponse(value)` | Set the value returned by `.withStructuredOutput()`. |\n * | `.bindTools(tools)` | Bind tools to the model. Returns a `RunnableBinding` that shares the response queue and call recording. |\n * | `.withStructuredOutput(schema)` | Returns a runnable that produces the `.structuredResponse()` value. |\n * | `.calls` | Array of `{ messages, options }` for every invocation (read-only). |\n * | `.callCount` | Number of times the model has been invoked. |\n *\n * @example\n * ```typescript\n * const model = fakeModel()\n * .respondWithTools([{ name: \"search\", args: { query: \"weather\" } }])\n * .respond(new AIMessage(\"Sunny and warm.\"));\n *\n * const r1 = await model.invoke([new HumanMessage(\"What's the weather?\")]);\n * // r1.tool_calls[0].name === \"search\"\n *\n * const r2 = await model.invoke([new HumanMessage(\"Thanks\")]);\n * // r2.content === \"Sunny and warm.\"\n * ```\n */\nexport function fakeModel(): FakeBuiltModel {\n return new FakeBuiltModel();\n}\n"],"mappings":";;;;;;;AAgCA,SAAS,cAAc,UAAiC;AACtD,QAAO,SACJ,KAAK,MAAM,EAAE,KAAK,CAClB,OAAO,QAAQ,CACf,KAAK,IAAI;;AAGd,IAAI,YAAY;AAChB,SAAS,iBAAyB;AAChC,cAAa;AACb,QAAO,WAAW;;;;;;;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s');
|
|
|
5
5
|
|
|
6
6
|
//#region src/testing/index.ts
|
|
7
7
|
var testing_exports = /* @__PURE__ */ require_runtime.__exportAll({
|
|
8
|
+
FakeBuiltModel: () => require_fake_model_builder.FakeBuiltModel,
|
|
8
9
|
fakeModel: () => require_fake_model_builder.fakeModel,
|
|
9
10
|
langchainMatchers: () => require_matchers.langchainMatchers,
|
|
10
11
|
toBeAIMessage: () => require_matchers.toBeAIMessage,
|
|
@@ -20,6 +21,7 @@ var testing_exports = /* @__PURE__ */ require_runtime.__exportAll({
|
|
|
20
21
|
});
|
|
21
22
|
|
|
22
23
|
//#endregion
|
|
24
|
+
exports.FakeBuiltModel = require_fake_model_builder.FakeBuiltModel;
|
|
23
25
|
exports.fakeModel = require_fake_model_builder.fakeModel;
|
|
24
26
|
exports.langchainMatchers = require_matchers.langchainMatchers;
|
|
25
27
|
Object.defineProperty(exports, 'testing_exports', {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":[],"sources":["../../src/testing/index.ts"],"sourcesContent":["export * from \"./matchers.js\";\nexport { fakeModel } from \"./fake_model_builder.js\";\n"],"mappings":""}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":[],"sources":["../../src/testing/index.ts"],"sourcesContent":["export * from \"./matchers.js\";\nexport { fakeModel, FakeBuiltModel } from \"./fake_model_builder.js\";\n"],"mappings":""}
|
package/dist/testing/index.d.cts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { LangChainMatchers, langchainMatchers, toBeAIMessage, toBeHumanMessage, toBeSystemMessage, toBeToolMessage, toContainToolCall, toHaveBeenInterrupted, toHaveStructuredResponse, toHaveToolCallCount, toHaveToolCalls, toHaveToolMessages } from "./matchers.cjs";
|
|
2
|
-
import { fakeModel } from "./fake_model_builder.cjs";
|
|
3
|
-
export { LangChainMatchers, fakeModel, langchainMatchers, toBeAIMessage, toBeHumanMessage, toBeSystemMessage, toBeToolMessage, toContainToolCall, toHaveBeenInterrupted, toHaveStructuredResponse, toHaveToolCallCount, toHaveToolCalls, toHaveToolMessages };
|
|
2
|
+
import { FakeBuiltModel, fakeModel } from "./fake_model_builder.cjs";
|
|
3
|
+
export { FakeBuiltModel, LangChainMatchers, fakeModel, langchainMatchers, toBeAIMessage, toBeHumanMessage, toBeSystemMessage, toBeToolMessage, toContainToolCall, toHaveBeenInterrupted, toHaveStructuredResponse, toHaveToolCallCount, toHaveToolCalls, toHaveToolMessages };
|
package/dist/testing/index.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { LangChainMatchers, langchainMatchers, toBeAIMessage, toBeHumanMessage, toBeSystemMessage, toBeToolMessage, toContainToolCall, toHaveBeenInterrupted, toHaveStructuredResponse, toHaveToolCallCount, toHaveToolCalls, toHaveToolMessages } from "./matchers.js";
|
|
2
|
-
import { fakeModel } from "./fake_model_builder.js";
|
|
3
|
-
export { LangChainMatchers, fakeModel, langchainMatchers, toBeAIMessage, toBeHumanMessage, toBeSystemMessage, toBeToolMessage, toContainToolCall, toHaveBeenInterrupted, toHaveStructuredResponse, toHaveToolCallCount, toHaveToolCalls, toHaveToolMessages };
|
|
2
|
+
import { FakeBuiltModel, fakeModel } from "./fake_model_builder.js";
|
|
3
|
+
export { FakeBuiltModel, LangChainMatchers, fakeModel, langchainMatchers, toBeAIMessage, toBeHumanMessage, toBeSystemMessage, toBeToolMessage, toContainToolCall, toHaveBeenInterrupted, toHaveStructuredResponse, toHaveToolCallCount, toHaveToolCalls, toHaveToolMessages };
|
package/dist/testing/index.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { __exportAll } from "../_virtual/_rolldown/runtime.js";
|
|
2
2
|
import { langchainMatchers, toBeAIMessage, toBeHumanMessage, toBeSystemMessage, toBeToolMessage, toContainToolCall, toHaveBeenInterrupted, toHaveStructuredResponse, toHaveToolCallCount, toHaveToolCalls, toHaveToolMessages } from "./matchers.js";
|
|
3
|
-
import { fakeModel } from "./fake_model_builder.js";
|
|
3
|
+
import { FakeBuiltModel, fakeModel } from "./fake_model_builder.js";
|
|
4
4
|
|
|
5
5
|
//#region src/testing/index.ts
|
|
6
6
|
var testing_exports = /* @__PURE__ */ __exportAll({
|
|
7
|
+
FakeBuiltModel: () => FakeBuiltModel,
|
|
7
8
|
fakeModel: () => fakeModel,
|
|
8
9
|
langchainMatchers: () => langchainMatchers,
|
|
9
10
|
toBeAIMessage: () => toBeAIMessage,
|
|
@@ -19,5 +20,5 @@ var testing_exports = /* @__PURE__ */ __exportAll({
|
|
|
19
20
|
});
|
|
20
21
|
|
|
21
22
|
//#endregion
|
|
22
|
-
export { fakeModel, langchainMatchers, testing_exports, toBeAIMessage, toBeHumanMessage, toBeSystemMessage, toBeToolMessage, toContainToolCall, toHaveBeenInterrupted, toHaveStructuredResponse, toHaveToolCallCount, toHaveToolCalls, toHaveToolMessages };
|
|
23
|
+
export { FakeBuiltModel, fakeModel, langchainMatchers, testing_exports, toBeAIMessage, toBeHumanMessage, toBeSystemMessage, toBeToolMessage, toContainToolCall, toHaveBeenInterrupted, toHaveStructuredResponse, toHaveToolCallCount, toHaveToolCalls, toHaveToolMessages };
|
|
23
24
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/testing/index.ts"],"sourcesContent":["export * from \"./matchers.js\";\nexport { fakeModel } from \"./fake_model_builder.js\";\n"],"mappings":""}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/testing/index.ts"],"sourcesContent":["export * from \"./matchers.js\";\nexport { fakeModel, FakeBuiltModel } from \"./fake_model_builder.js\";\n"],"mappings":""}
|
package/dist/tools/index.cjs
CHANGED
|
@@ -306,6 +306,10 @@ function tool(func, fields) {
|
|
|
306
306
|
require_index.AsyncLocalStorageProviderSingleton.runWithConfig(require_config.pickRunnableConfigKeys(childConfig), async () => {
|
|
307
307
|
try {
|
|
308
308
|
const result = await func(input, childConfig);
|
|
309
|
+
if (require_iter.isAsyncGenerator(result)) {
|
|
310
|
+
resolve(result);
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
309
313
|
/**
|
|
310
314
|
* If the signal is aborted, we don't want to resolve the promise
|
|
311
315
|
* as the promise is already rejected.
|
package/dist/tools/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["BaseLangChain","ensureConfig","mergeConfigs","_isToolCall","isInteropZodSchema","interopParseAsync","isInteropZodError","z4","ToolInputParsingException","parseCallbackConfigArg","CallbackManager","_configHasToolCallId","isAsyncGenerator","consumeAsyncGenerator","z","isSimpleStringZodSchema","validatesOnlyStrings","patchConfig","AsyncLocalStorageProviderSingleton","pickRunnableConfigKeys","getAbortSignalError","isDirectToolOutput","ToolMessage"],"sources":["../../src/tools/index.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { z as z4, ZodError } from \"zod/v4\";\nimport {\n validate,\n type Schema as ValidationSchema,\n} from \"@cfworker/json-schema\";\nimport {\n CallbackManager,\n CallbackManagerForToolRun,\n parseCallbackConfigArg,\n} from \"../callbacks/manager.js\";\nimport { BaseLangChain } from \"../language_models/base.js\";\nimport {\n mergeConfigs,\n ensureConfig,\n patchConfig,\n pickRunnableConfigKeys,\n type RunnableConfig,\n} from \"../runnables/config.js\";\nimport type { RunnableFunc } from \"../runnables/base.js\";\nimport { isDirectToolOutput, ToolCall, ToolMessage } from \"../messages/tool.js\";\nimport { AsyncLocalStorageProviderSingleton } from \"../singletons/index.js\";\nimport type { RunnableToolLike } from \"../runnables/base.js\";\nimport {\n _configHasToolCallId,\n _isToolCall,\n ToolInputParsingException,\n} from \"./utils.js\";\nimport {\n type InferInteropZodInput,\n type InferInteropZodOutput,\n type InteropZodObject,\n type InteropZodType,\n interopParseAsync,\n isSimpleStringZodSchema,\n isInteropZodError,\n isInteropZodSchema,\n type ZodStringV3,\n type ZodStringV4,\n type ZodObjectV3,\n type ZodObjectV4,\n} from \"../utils/types/zod.js\";\nimport { getAbortSignalError } from \"../utils/signal.js\";\nimport type {\n StructuredToolCallInput,\n ToolInputSchemaBase,\n ToolReturnType,\n ResponseFormat,\n ToolInputSchemaInputType,\n ToolInputSchemaOutputType,\n ToolParams,\n ToolRunnableConfig,\n StructuredToolInterface,\n DynamicToolInput,\n DynamicStructuredToolInput,\n StringInputToolSchema,\n ToolInterface,\n ToolOutputType,\n ToolRuntime,\n} from \"./types.js\";\nimport { type JSONSchema, validatesOnlyStrings } from \"../utils/json_schema.js\";\nimport { consumeAsyncGenerator, isAsyncGenerator } from \"../runnables/iter.js\";\n\nexport type {\n BaseDynamicToolInput,\n ContentAndArtifact,\n DynamicToolInput,\n DynamicStructuredToolInput,\n ResponseFormat,\n StructuredToolCallInput,\n StructuredToolInterface,\n StructuredToolParams,\n ToolInterface,\n ToolParams,\n ToolReturnType,\n ToolRunnableConfig,\n ToolInputSchemaBase as ToolSchemaBase,\n} from \"./types.js\";\n\nexport {\n isLangChainTool,\n isRunnableToolLike,\n isStructuredTool,\n isStructuredToolParams,\n type ToolRuntime,\n} from \"./types.js\";\n\nexport { ToolInputParsingException };\n/**\n * Base class for Tools that accept input of any shape defined by a Zod schema.\n */\nexport abstract class StructuredTool<\n SchemaT = ToolInputSchemaBase,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n>\n extends BaseLangChain<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolOutputT | ToolMessage\n >\n implements StructuredToolInterface<SchemaT, SchemaInputT, ToolOutputT>\n{\n abstract name: string;\n\n abstract description: string;\n\n abstract schema: SchemaT;\n\n /**\n * Optional provider-specific extra fields for the tool.\n *\n * This is used to pass provider-specific configuration that doesn't fit into\n * standard tool fields.\n */\n extras?: Record<string, unknown>;\n\n /**\n * Whether to return the tool's output directly.\n *\n * Setting this to true means that after the tool is called,\n * an agent should stop looping.\n */\n returnDirect = false;\n\n verboseParsingErrors = false;\n\n get lc_namespace() {\n return [\"langchain\", \"tools\"];\n }\n\n /**\n * The tool response format.\n *\n * If \"content\" then the output of the tool is interpreted as the contents of a\n * ToolMessage. If \"content_and_artifact\" then the output is expected to be a\n * two-tuple corresponding to the (content, artifact) of a ToolMessage.\n *\n * @default \"content\"\n */\n responseFormat?: ResponseFormat = \"content\";\n\n /**\n * Default config object for the tool runnable.\n */\n defaultConfig?: ToolRunnableConfig;\n\n constructor(fields?: ToolParams) {\n super(fields ?? {});\n\n this.verboseParsingErrors =\n fields?.verboseParsingErrors ?? this.verboseParsingErrors;\n this.responseFormat = fields?.responseFormat ?? this.responseFormat;\n this.defaultConfig = fields?.defaultConfig ?? this.defaultConfig;\n this.metadata = fields?.metadata ?? this.metadata;\n this.extras = fields?.extras ?? this.extras;\n }\n\n protected abstract _call(\n arg: SchemaOutputT,\n runManager?: CallbackManagerForToolRun,\n parentConfig?: ToolRunnableConfig\n ): Promise<ToolOutputT> | AsyncGenerator<unknown, ToolOutputT>;\n\n /**\n * Invokes the tool with the provided input and configuration.\n * @param input The input for the tool.\n * @param config Optional configuration for the tool.\n * @returns A Promise that resolves with the tool's output.\n */\n async invoke<\n TInput extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n input: TInput,\n config?: TConfig\n ): Promise<ToolReturnType<TInput, TConfig, ToolOutputT>> {\n let toolInput: Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n\n let enrichedConfig: ToolRunnableConfig = ensureConfig(\n mergeConfigs(this.defaultConfig, config)\n );\n if (_isToolCall(input)) {\n toolInput = input.args as Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n enrichedConfig = {\n ...enrichedConfig,\n toolCall: input,\n };\n } else {\n toolInput = input as Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n }\n\n return this.call(toolInput, enrichedConfig) as Promise<\n ToolReturnType<TInput, TConfig, ToolOutputT>\n >;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n *\n * Calls the tool with the provided argument, configuration, and tags. It\n * parses the input according to the schema, handles any errors, and\n * manages callbacks.\n * @param arg The input argument for the tool.\n * @param configArg Optional configuration or callbacks for the tool.\n * @param tags Optional tags for the tool.\n * @returns A Promise that resolves with a string.\n */\n async call<\n TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n arg: TArg,\n configArg?: TConfig,\n /** @deprecated */\n tags?: string[]\n ): Promise<ToolReturnType<TArg, TConfig, ToolOutputT>> {\n // Determine the actual input that needs parsing/validation.\n // If arg is a ToolCall, use its args; otherwise, use arg directly.\n const inputForValidation = _isToolCall(arg) ? arg.args : arg;\n\n let parsed: SchemaOutputT; // This will hold the successfully parsed input of the expected output type.\n if (isInteropZodSchema(this.schema)) {\n try {\n // Validate the inputForValidation - TS needs help here as it can't exclude ToolCall based on the check\n parsed = await interopParseAsync(\n this.schema as InteropZodType,\n inputForValidation as Exclude<TArg, ToolCall>\n );\n } catch (e) {\n let message = `Received tool input did not match expected schema`;\n if (this.verboseParsingErrors) {\n message = `${message}\\nDetails: ${(e as Error).message}`;\n }\n if (isInteropZodError(e)) {\n message = `${message}\\n\\n${z4.prettifyError(e as ZodError)}`;\n }\n // Pass the original raw input arg to the exception\n throw new ToolInputParsingException(message, JSON.stringify(arg));\n }\n } else {\n const result = validate(\n inputForValidation,\n this.schema as ValidationSchema\n );\n if (!result.valid) {\n let message = `Received tool input did not match expected schema`;\n if (this.verboseParsingErrors) {\n message = `${message}\\nDetails: ${result.errors\n .map((e) => `${e.keywordLocation}: ${e.error}`)\n .join(\"\\n\")}`;\n }\n // Pass the original raw input arg to the exception\n throw new ToolInputParsingException(message, JSON.stringify(arg));\n }\n // Assign the validated input to parsed\n // We cast here because validate() doesn't narrow the type sufficiently for TS, but we know it's valid.\n parsed = inputForValidation as SchemaOutputT;\n }\n\n const config = parseCallbackConfigArg(configArg);\n const callbackManager_ = CallbackManager.configure(\n config.callbacks,\n this.callbacks,\n config.tags || tags,\n this.tags,\n config.metadata,\n this.metadata,\n { verbose: this.verbose }\n );\n\n let toolCallId: string | undefined;\n // Extract toolCallId ONLY if the original arg was a ToolCall\n if (_isToolCall(arg)) {\n toolCallId = arg.id;\n }\n // Or if it was provided in the config's toolCall property\n if (!toolCallId && _configHasToolCallId(config)) {\n toolCallId = config.toolCall.id;\n }\n\n const runManager = await callbackManager_?.handleToolStart(\n this.toJSON(),\n // Log the original raw input arg\n typeof arg === \"string\" ? arg : JSON.stringify(arg),\n config.runId,\n undefined,\n undefined,\n undefined,\n config.runName,\n toolCallId\n );\n delete config.runId;\n\n let result;\n try {\n const raw = await this._call(parsed, runManager, config);\n result = isAsyncGenerator(raw)\n ? await consumeAsyncGenerator(raw, async (chunk) => {\n try {\n await runManager?.handleToolEvent(chunk);\n } catch (streamError) {\n await runManager?.handleToolError(streamError);\n }\n })\n : raw;\n } catch (e) {\n await runManager?.handleToolError(e);\n throw e;\n }\n\n let content;\n let artifact;\n if (this.responseFormat === \"content_and_artifact\") {\n if (Array.isArray(result) && result.length === 2) {\n [content, artifact] = result;\n } else {\n throw new Error(\n `Tool response format is \"content_and_artifact\" but the output was not a two-tuple.\\nResult: ${JSON.stringify(\n result\n )}`\n );\n }\n } else {\n content = result;\n }\n\n const formattedOutput = _formatToolOutput<ToolOutputT>({\n content,\n artifact,\n toolCallId,\n name: this.name,\n metadata: this.metadata,\n });\n await runManager?.handleToolEnd(formattedOutput);\n return formattedOutput as ToolReturnType<TArg, TConfig, ToolOutputT>;\n }\n}\n\n/**\n * Base class for Tools that accept input as a string.\n */\nexport abstract class Tool<ToolOutputT = ToolOutputType>\n extends StructuredTool<\n StringInputToolSchema,\n ToolInputSchemaOutputType<StringInputToolSchema>,\n ToolInputSchemaInputType<StringInputToolSchema>,\n ToolOutputT\n >\n implements\n ToolInterface<\n StringInputToolSchema,\n ToolInputSchemaInputType<StringInputToolSchema>,\n ToolOutputT\n >\n{\n schema = z\n .object({ input: z.string().optional() })\n .transform((obj) => obj.input);\n\n constructor(fields?: ToolParams) {\n super(fields);\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n *\n * Calls the tool with the provided argument and callbacks. It handles\n * string inputs specifically.\n * @param arg The input argument for the tool, which can be a string, undefined, or an input of the tool's schema.\n * @param callbacks Optional callbacks for the tool.\n * @returns A Promise that resolves with a string.\n */\n // Match the base class signature including the generics and conditional return type\n call<\n TArg extends string | undefined | z.input<this[\"schema\"]> | ToolCall,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n arg: TArg,\n callbacks?: TConfig\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n // Prepare the input for the base class call method.\n // If arg is string or undefined, wrap it; otherwise, pass ToolCall or { input: ... } directly.\n const structuredArg =\n typeof arg === \"string\" || arg == null ? { input: arg } : arg;\n\n // Ensure TConfig is passed to super.call\n return super.call(structuredArg, callbacks);\n }\n}\n\n/**\n * A tool that can be created dynamically from a function, name, and description.\n */\nexport class DynamicTool<\n ToolOutputT = ToolOutputType,\n> extends Tool<ToolOutputT> {\n static lc_name() {\n return \"DynamicTool\";\n }\n\n name: string;\n\n description: string;\n\n func: DynamicToolInput<ToolOutputT>[\"func\"];\n\n constructor(fields: DynamicToolInput<ToolOutputT>) {\n super(fields);\n this.name = fields.name;\n this.description = fields.description;\n this.func = fields.func;\n this.returnDirect = fields.returnDirect ?? this.returnDirect;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n */\n async call<\n TArg extends string | undefined | z.input<this[\"schema\"]> | ToolCall,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n arg: TArg,\n configArg?: TConfig\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n const config = parseCallbackConfigArg(configArg);\n if (config.runName === undefined) {\n config.runName = this.name;\n }\n // Call the Tool class's call method, passing generics through\n // Cast config to TConfig to satisfy the super.call signature\n return super.call<TArg, TConfig>(arg, config as TConfig);\n }\n\n /** @ignore */\n _call(\n input: string, // DynamicTool's _call specifically expects a string after schema transformation\n runManager?: CallbackManagerForToolRun,\n parentConfig?: ToolRunnableConfig\n ): Promise<ToolOutputT> | AsyncGenerator<unknown, ToolOutputT> {\n return this.func(input, runManager, parentConfig);\n }\n}\n\n/**\n * A tool that can be created dynamically from a function, name, and\n * description, designed to work with structured data. It extends the\n * StructuredTool class and overrides the _call method to execute the\n * provided function when the tool is called.\n *\n * Schema can be passed as Zod or JSON schema. The tool will not validate\n * input if JSON schema is passed.\n *\n * @template SchemaT The input schema type for the tool (Zod schema or JSON schema). Defaults to `ToolInputSchemaBase`.\n * @template SchemaOutputT The output type derived from the schema after parsing/validation. Defaults to `ToolInputSchemaOutputType<SchemaT>`.\n * @template SchemaInputT The input type derived from the schema before parsing. Defaults to `ToolInputSchemaInputType<SchemaT>`.\n * @template ToolOutputT The return type of the tool's function. Defaults to `ToolOutputType`.\n * @template NameT The literal type of the tool name (for discriminated union support). Defaults to `string`.\n */\nexport class DynamicStructuredTool<\n SchemaT = ToolInputSchemaBase,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n NameT extends string = string,\n> extends StructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT> {\n static lc_name() {\n return \"DynamicStructuredTool\";\n }\n\n declare name: NameT;\n\n description: string;\n\n func: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT>[\"func\"];\n\n schema: SchemaT;\n\n constructor(\n fields: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT> & {\n name: NameT;\n }\n ) {\n super(fields);\n this.name = fields.name;\n this.description = fields.description;\n this.func = fields.func;\n this.returnDirect = fields.returnDirect ?? this.returnDirect;\n this.schema = fields.schema;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n */\n // Match the base class signature\n async call<\n TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n arg: TArg,\n configArg?: TConfig,\n /** @deprecated */\n tags?: string[]\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n const config = parseCallbackConfigArg(configArg);\n if (config.runName === undefined) {\n config.runName = this.name;\n }\n\n // Call the base class method, passing generics through\n // Cast config to TConfig to satisfy the super.call signature\n return super.call<TArg, TConfig>(arg, config as TConfig, tags);\n }\n\n protected _call(\n arg: Parameters<\n DynamicStructuredToolInput<SchemaT, SchemaOutputT>[\"func\"]\n >[0],\n runManager?: CallbackManagerForToolRun,\n parentConfig?: RunnableConfig\n ): Promise<ToolOutputT> | AsyncGenerator<unknown, ToolOutputT> {\n return this.func(arg, runManager, parentConfig);\n }\n}\n\n/**\n * Abstract base class for toolkits in LangChain. Toolkits are collections\n * of tools that agents can use. Subclasses must implement the `tools`\n * property to provide the specific tools for the toolkit.\n */\nexport abstract class BaseToolkit {\n abstract tools: StructuredToolInterface[];\n\n getTools(): StructuredToolInterface[] {\n return this.tools;\n }\n}\n\n/**\n * Parameters for the tool function.\n * Schema can be provided as Zod or JSON schema.\n * Both schema types will be validated.\n * @template {ToolInputSchemaBase} RunInput The input schema for the tool.\n * @template {string} NameT The literal name type for discriminated union support.\n */\ninterface ToolWrapperParams<\n RunInput = ToolInputSchemaBase | undefined,\n NameT extends string = string,\n> extends ToolParams {\n /**\n * The name of the tool. If using with an LLM, this\n * will be passed as the tool name.\n */\n name: NameT;\n /**\n * The description of the tool.\n * @default `${fields.name} tool`\n */\n description?: string;\n /**\n * The input schema for the tool. If using an LLM, this\n * will be passed as the tool schema to generate arguments\n * for.\n */\n schema?: RunInput;\n /**\n * The tool response format.\n *\n * If \"content\" then the output of the tool is interpreted as the contents of a\n * ToolMessage. If \"content_and_artifact\" then the output is expected to be a\n * two-tuple corresponding to the (content, artifact) of a ToolMessage.\n *\n * @default \"content\"\n */\n responseFormat?: ResponseFormat;\n /**\n * Whether to return the tool's output directly.\n *\n * Setting this to true means that after the tool is called,\n * an agent should stop looping.\n */\n returnDirect?: boolean;\n}\n\n/**\n * Creates a new StructuredTool instance with the provided function, name, description, and schema.\n *\n * Schema can be provided as Zod or JSON schema, and both will be validated.\n *\n * @function\n * @template {ToolInputSchemaBase} SchemaT The input schema for the tool.\n * @template {ToolReturnType} ToolOutputT The output type of the tool.\n *\n * @param {RunnableFunc<z.output<SchemaT>, ToolOutputT>} func - The function to invoke when the tool is called.\n * @param {ToolWrapperParams<SchemaT>} fields - An object containing the following properties:\n * @param {string} fields.name The name of the tool.\n * @param {string | undefined} fields.description The description of the tool. Defaults to either the description on the Zod schema, or `${fields.name} tool`.\n * @param {z.AnyZodObject | z.ZodString | undefined} fields.schema The Zod schema defining the input for the tool. If undefined, it will default to a Zod string schema.\n *\n * @returns {DynamicStructuredTool<SchemaT>} A new StructuredTool instance.\n */\nexport function tool<SchemaT extends ZodStringV3, ToolOutputT = ToolOutputType>(\n func: RunnableFunc<\n InferInteropZodOutput<SchemaT>,\n ToolOutputT,\n ToolRunnableConfig\n >,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<SchemaT extends ZodStringV4, ToolOutputT = ToolOutputType>(\n func: RunnableFunc<\n InferInteropZodOutput<SchemaT>,\n ToolOutputT,\n ToolRunnableConfig\n >,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodObjectV3,\n NameT extends string,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n>(\n func: RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n>;\n\nexport function tool<\n SchemaT extends ZodObjectV4,\n NameT extends string,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n>(\n func: RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n>;\n\nexport function tool<\n SchemaT extends JSONSchema,\n NameT extends string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n>(\n func: RunnableFunc<\n Parameters<DynamicStructuredToolInput<SchemaT>[\"func\"]>[0],\n ToolOutputT,\n ToolRunnableConfig\n >,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n>;\n\nexport function tool<\n SchemaT extends InteropZodObject | InteropZodType<string> | JSONSchema =\n InteropZodObject,\n NameT extends string = string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n>(\n func: RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n fields: ToolWrapperParams<SchemaT, NameT>\n):\n | DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n >\n | DynamicTool<ToolOutputT>;\n\n// Overloads with ToolRuntime as CallOptions\nexport function tool<\n SchemaT extends ZodStringV3,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: InferInteropZodOutput<SchemaT>,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodStringV4,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: InferInteropZodOutput<SchemaT>,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodObjectV3,\n NameT extends string,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n>;\n\nexport function tool<\n SchemaT extends ZodObjectV4,\n NameT extends string,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n>;\n\nexport function tool<\n SchemaT extends JSONSchema,\n NameT extends string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: Parameters<DynamicStructuredToolInput<SchemaT>[\"func\"]>[0],\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n>;\n\nexport function tool<\n SchemaT extends InteropZodObject | InteropZodType<string> | JSONSchema =\n InteropZodObject,\n NameT extends string = string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n):\n | DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n >\n | DynamicTool<ToolOutputT> {\n const isSimpleStringSchema = isSimpleStringZodSchema(fields.schema);\n const isStringJSONSchema = validatesOnlyStrings(fields.schema);\n\n // If the schema is not provided, or it's a simple string schema, create a DynamicTool\n if (!fields.schema || isSimpleStringSchema || isStringJSONSchema) {\n return new DynamicTool<ToolOutputT>({\n ...fields,\n description:\n fields.description ??\n (fields.schema as { description?: string } | undefined)?.description ??\n `${fields.name} tool`,\n func: async (input, runManager, config) => {\n return new Promise<ToolOutputT>((resolve, reject) => {\n const childConfig = patchConfig(config, {\n callbacks: runManager?.getChild(),\n });\n // eslint-disable-next-line no-void\n void AsyncLocalStorageProviderSingleton.runWithConfig(\n pickRunnableConfigKeys(childConfig),\n async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n resolve(func(input as any, childConfig as any));\n } catch (e) {\n reject(e);\n }\n }\n );\n });\n },\n });\n }\n\n const schema = fields.schema as InteropZodObject | JSONSchema;\n\n const description =\n fields.description ??\n (fields.schema as { description?: string }).description ??\n `${fields.name} tool`;\n\n return new DynamicStructuredTool<\n typeof schema,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n >({\n ...fields,\n description,\n schema,\n func: async (input, runManager, config) => {\n return new Promise<ToolOutputT>((resolve, reject) => {\n let listener: (() => void) | undefined;\n const cleanup = () => {\n if (config?.signal && listener) {\n config.signal.removeEventListener(\"abort\", listener);\n }\n };\n\n if (config?.signal) {\n listener = () => {\n cleanup();\n reject(getAbortSignalError(config.signal));\n };\n config.signal.addEventListener(\"abort\", listener, { once: true });\n }\n\n const childConfig = patchConfig(config, {\n callbacks: runManager?.getChild(),\n });\n // eslint-disable-next-line no-void\n void AsyncLocalStorageProviderSingleton.runWithConfig(\n pickRunnableConfigKeys(childConfig),\n async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result = await func(input as any, childConfig as any);\n\n /**\n * If the signal is aborted, we don't want to resolve the promise\n * as the promise is already rejected.\n */\n if (config?.signal?.aborted) {\n cleanup();\n return;\n }\n\n cleanup();\n resolve(result);\n } catch (e) {\n cleanup();\n reject(e);\n }\n }\n );\n });\n },\n }) as DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n >;\n}\n\nfunction _formatToolOutput<TOutput extends ToolOutputType>(params: {\n content: TOutput;\n name: string;\n artifact?: unknown;\n toolCallId?: string;\n metadata?: Record<string, unknown>;\n}): ToolMessage | TOutput {\n const { content, artifact, toolCallId, metadata } = params;\n if (toolCallId && !isDirectToolOutput(content)) {\n if (\n typeof content === \"string\" ||\n (Array.isArray(content) &&\n content.every((item) => typeof item === \"object\"))\n ) {\n return new ToolMessage({\n status: \"success\",\n content,\n artifact,\n tool_call_id: toolCallId,\n name: params.name,\n metadata,\n });\n } else {\n return new ToolMessage({\n status: \"success\",\n content: _stringify(content),\n artifact,\n tool_call_id: toolCallId,\n name: params.name,\n metadata,\n });\n }\n } else {\n return content;\n }\n}\n\nfunction _stringify(content: unknown): string {\n try {\n return JSON.stringify(content) ?? \"\";\n } catch (_noOp) {\n return `${content}`;\n }\n}\n\nexport type ServerTool = Record<string, unknown>;\nexport type ClientTool =\n | StructuredToolInter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YAAO,OAAO,iBAAiB,SAAS,UAAU,EAAE,MAAM,MAAM,CAAC;;IAGnE,MAAM,cAAcH,2BAAY,QAAQ,EACtC,WAAW,YAAY,UAAU,EAClC,CAAC;AAEF,IAAKC,iDAAmC,cACtCC,sCAAuB,YAAY,EACnC,YAAY;AACV,SAAI;MAEF,MAAM,SAAS,MAAM,KAAK,OAAc,YAAmB;;;;;AAM3D,UAAI,QAAQ,QAAQ,SAAS;AAC3B,gBAAS;AACT;;AAGF,eAAS;AACT,cAAQ,OAAO;cACR,GAAG;AACV,eAAS;AACT,aAAO,EAAE;;MAGd;KACD;;EAEL,CAAC;;AASJ,SAAS,kBAAkD,QAMjC;CACxB,MAAM,EAAE,SAAS,UAAU,YAAY,aAAa;AACpD,KAAI,cAAc,CAACE,yCAAmB,QAAQ,CAC5C,KACE,OAAO,YAAY,YAClB,MAAM,QAAQ,QAAQ,IACrB,QAAQ,OAAO,SAAS,OAAO,SAAS,SAAS,CAEnD,QAAO,IAAIC,kCAAY;EACrB,QAAQ;EACR;EACA;EACA,cAAc;EACd,MAAM,OAAO;EACb;EACD,CAAC;KAEF,QAAO,IAAIA,kCAAY;EACrB,QAAQ;EACR,SAAS,WAAW,QAAQ;EAC5B;EACA,cAAc;EACd,MAAM,OAAO;EACb;EACD,CAAC;KAGJ,QAAO;;AAIX,SAAS,WAAW,SAA0B;AAC5C,KAAI;AACF,SAAO,KAAK,UAAU,QAAQ,IAAI;UAC3B,OAAO;AACd,SAAO,GAAG"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["BaseLangChain","ensureConfig","mergeConfigs","_isToolCall","isInteropZodSchema","interopParseAsync","isInteropZodError","z4","ToolInputParsingException","parseCallbackConfigArg","CallbackManager","_configHasToolCallId","isAsyncGenerator","consumeAsyncGenerator","z","isSimpleStringZodSchema","validatesOnlyStrings","patchConfig","AsyncLocalStorageProviderSingleton","pickRunnableConfigKeys","getAbortSignalError","isDirectToolOutput","ToolMessage"],"sources":["../../src/tools/index.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { z as z4, ZodError } from \"zod/v4\";\nimport {\n validate,\n type Schema as ValidationSchema,\n} from \"@cfworker/json-schema\";\nimport {\n CallbackManager,\n CallbackManagerForToolRun,\n parseCallbackConfigArg,\n} from \"../callbacks/manager.js\";\nimport { BaseLangChain } from \"../language_models/base.js\";\nimport {\n mergeConfigs,\n ensureConfig,\n patchConfig,\n pickRunnableConfigKeys,\n type RunnableConfig,\n} from \"../runnables/config.js\";\nimport type { RunnableFunc } from \"../runnables/base.js\";\nimport { isDirectToolOutput, ToolCall, ToolMessage } from \"../messages/tool.js\";\nimport { AsyncLocalStorageProviderSingleton } from \"../singletons/index.js\";\nimport type { RunnableToolLike } from \"../runnables/base.js\";\nimport {\n _configHasToolCallId,\n _isToolCall,\n ToolInputParsingException,\n} from \"./utils.js\";\nimport {\n type InferInteropZodInput,\n type InferInteropZodOutput,\n type InteropZodObject,\n type InteropZodType,\n interopParseAsync,\n isSimpleStringZodSchema,\n isInteropZodError,\n isInteropZodSchema,\n type ZodStringV3,\n type ZodStringV4,\n type ZodObjectV3,\n type ZodObjectV4,\n} from \"../utils/types/zod.js\";\nimport { getAbortSignalError } from \"../utils/signal.js\";\nimport type {\n StructuredToolCallInput,\n ToolInputSchemaBase,\n ToolReturnType,\n ResponseFormat,\n ToolInputSchemaInputType,\n ToolInputSchemaOutputType,\n ToolParams,\n ToolRunnableConfig,\n StructuredToolInterface,\n DynamicToolInput,\n DynamicStructuredToolInput,\n StringInputToolSchema,\n ToolInterface,\n ToolOutputType,\n ToolRuntime,\n ToolEventType,\n InferToolEventFromFunc,\n InferToolOutputFromFunc,\n} from \"./types.js\";\nimport { type JSONSchema, validatesOnlyStrings } from \"../utils/json_schema.js\";\nimport { consumeAsyncGenerator, isAsyncGenerator } from \"../runnables/iter.js\";\n\nexport type {\n BaseDynamicToolInput,\n ContentAndArtifact,\n DynamicToolInput,\n DynamicStructuredToolInput,\n ResponseFormat,\n StructuredToolCallInput,\n StructuredToolInterface,\n StructuredToolParams,\n ToolInterface,\n ToolParams,\n ToolReturnType,\n ToolRunnableConfig,\n ToolInputSchemaBase as ToolSchemaBase,\n} from \"./types.js\";\n\nexport {\n isLangChainTool,\n isRunnableToolLike,\n isStructuredTool,\n isStructuredToolParams,\n type ToolRuntime,\n} from \"./types.js\";\n\nexport { ToolInputParsingException };\n/**\n * Base class for Tools that accept input of any shape defined by a Zod schema.\n */\nexport abstract class StructuredTool<\n SchemaT = ToolInputSchemaBase,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n ToolEventT = ToolEventType,\n>\n extends BaseLangChain<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolOutputT | ToolMessage\n >\n implements StructuredToolInterface<SchemaT, SchemaInputT, ToolOutputT>\n{\n abstract name: string;\n\n abstract description: string;\n\n abstract schema: SchemaT;\n\n /**\n * Optional provider-specific extra fields for the tool.\n *\n * This is used to pass provider-specific configuration that doesn't fit into\n * standard tool fields.\n */\n extras?: Record<string, unknown>;\n\n /**\n * Whether to return the tool's output directly.\n *\n * Setting this to true means that after the tool is called,\n * an agent should stop looping.\n */\n returnDirect = false;\n\n verboseParsingErrors = false;\n\n get lc_namespace() {\n return [\"langchain\", \"tools\"];\n }\n\n /**\n * The tool response format.\n *\n * If \"content\" then the output of the tool is interpreted as the contents of a\n * ToolMessage. If \"content_and_artifact\" then the output is expected to be a\n * two-tuple corresponding to the (content, artifact) of a ToolMessage.\n *\n * @default \"content\"\n */\n responseFormat?: ResponseFormat = \"content\";\n\n /**\n * Default config object for the tool runnable.\n */\n defaultConfig?: ToolRunnableConfig;\n\n constructor(fields?: ToolParams) {\n super(fields ?? {});\n\n this.verboseParsingErrors =\n fields?.verboseParsingErrors ?? this.verboseParsingErrors;\n this.responseFormat = fields?.responseFormat ?? this.responseFormat;\n this.defaultConfig = fields?.defaultConfig ?? this.defaultConfig;\n this.metadata = fields?.metadata ?? this.metadata;\n this.extras = fields?.extras ?? this.extras;\n }\n\n protected abstract _call(\n arg: SchemaOutputT,\n runManager?: CallbackManagerForToolRun,\n parentConfig?: ToolRunnableConfig\n ): Promise<ToolOutputT> | AsyncGenerator<ToolEventT, ToolOutputT>;\n\n /**\n * Invokes the tool with the provided input and configuration.\n * @param input The input for the tool.\n * @param config Optional configuration for the tool.\n * @returns A Promise that resolves with the tool's output.\n */\n async invoke<\n TInput extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n input: TInput,\n config?: TConfig\n ): Promise<ToolReturnType<TInput, TConfig, ToolOutputT>> {\n let toolInput: Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n\n let enrichedConfig: ToolRunnableConfig = ensureConfig(\n mergeConfigs(this.defaultConfig, config)\n );\n if (_isToolCall(input)) {\n toolInput = input.args as Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n enrichedConfig = {\n ...enrichedConfig,\n toolCall: input,\n };\n } else {\n toolInput = input as Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n }\n\n return this.call(toolInput, enrichedConfig) as Promise<\n ToolReturnType<TInput, TConfig, ToolOutputT>\n >;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n *\n * Calls the tool with the provided argument, configuration, and tags. It\n * parses the input according to the schema, handles any errors, and\n * manages callbacks.\n * @param arg The input argument for the tool.\n * @param configArg Optional configuration or callbacks for the tool.\n * @param tags Optional tags for the tool.\n * @returns A Promise that resolves with a string.\n */\n async call<\n TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n arg: TArg,\n configArg?: TConfig,\n /** @deprecated */\n tags?: string[]\n ): Promise<ToolReturnType<TArg, TConfig, ToolOutputT>> {\n // Determine the actual input that needs parsing/validation.\n // If arg is a ToolCall, use its args; otherwise, use arg directly.\n const inputForValidation = _isToolCall(arg) ? arg.args : arg;\n\n let parsed: SchemaOutputT; // This will hold the successfully parsed input of the expected output type.\n if (isInteropZodSchema(this.schema)) {\n try {\n // Validate the inputForValidation - TS needs help here as it can't exclude ToolCall based on the check\n parsed = await interopParseAsync(\n this.schema as InteropZodType,\n inputForValidation as Exclude<TArg, ToolCall>\n );\n } catch (e) {\n let message = `Received tool input did not match expected schema`;\n if (this.verboseParsingErrors) {\n message = `${message}\\nDetails: ${(e as Error).message}`;\n }\n if (isInteropZodError(e)) {\n message = `${message}\\n\\n${z4.prettifyError(e as ZodError)}`;\n }\n // Pass the original raw input arg to the exception\n throw new ToolInputParsingException(message, JSON.stringify(arg));\n }\n } else {\n const result = validate(\n inputForValidation,\n this.schema as ValidationSchema\n );\n if (!result.valid) {\n let message = `Received tool input did not match expected schema`;\n if (this.verboseParsingErrors) {\n message = `${message}\\nDetails: ${result.errors\n .map((e) => `${e.keywordLocation}: ${e.error}`)\n .join(\"\\n\")}`;\n }\n // Pass the original raw input arg to the exception\n throw new ToolInputParsingException(message, JSON.stringify(arg));\n }\n // Assign the validated input to parsed\n // We cast here because validate() doesn't narrow the type sufficiently for TS, but we know it's valid.\n parsed = inputForValidation as SchemaOutputT;\n }\n\n const config = parseCallbackConfigArg(configArg);\n const callbackManager_ = CallbackManager.configure(\n config.callbacks,\n this.callbacks,\n config.tags || tags,\n this.tags,\n config.metadata,\n this.metadata,\n { verbose: this.verbose }\n );\n\n let toolCallId: string | undefined;\n // Extract toolCallId ONLY if the original arg was a ToolCall\n if (_isToolCall(arg)) {\n toolCallId = arg.id;\n }\n // Or if it was provided in the config's toolCall property\n if (!toolCallId && _configHasToolCallId(config)) {\n toolCallId = config.toolCall.id;\n }\n\n const runManager = await callbackManager_?.handleToolStart(\n this.toJSON(),\n // Log the original raw input arg\n typeof arg === \"string\" ? arg : JSON.stringify(arg),\n config.runId,\n undefined,\n undefined,\n undefined,\n config.runName,\n toolCallId\n );\n delete config.runId;\n\n let result;\n try {\n const raw = await this._call(parsed, runManager, config);\n result = isAsyncGenerator(raw)\n ? await consumeAsyncGenerator(raw, async (chunk) => {\n try {\n await runManager?.handleToolEvent(chunk);\n } catch (streamError) {\n await runManager?.handleToolError(streamError);\n }\n })\n : raw;\n } catch (e) {\n await runManager?.handleToolError(e);\n throw e;\n }\n\n let content;\n let artifact;\n if (this.responseFormat === \"content_and_artifact\") {\n if (Array.isArray(result) && result.length === 2) {\n [content, artifact] = result;\n } else {\n throw new Error(\n `Tool response format is \"content_and_artifact\" but the output was not a two-tuple.\\nResult: ${JSON.stringify(\n result\n )}`\n );\n }\n } else {\n content = result;\n }\n\n const formattedOutput = _formatToolOutput<ToolOutputT>({\n content,\n artifact,\n toolCallId,\n name: this.name,\n metadata: this.metadata,\n });\n await runManager?.handleToolEnd(formattedOutput);\n return formattedOutput as ToolReturnType<TArg, TConfig, ToolOutputT>;\n }\n}\n\n/**\n * Base class for Tools that accept input as a string.\n */\nexport abstract class Tool<\n ToolOutputT = ToolOutputType,\n ToolEventT = ToolEventType,\n>\n extends StructuredTool<\n StringInputToolSchema,\n ToolInputSchemaOutputType<StringInputToolSchema>,\n ToolInputSchemaInputType<StringInputToolSchema>,\n ToolOutputT,\n ToolEventT\n >\n implements\n ToolInterface<\n StringInputToolSchema,\n ToolInputSchemaInputType<StringInputToolSchema>,\n ToolOutputT\n >\n{\n schema = z\n .object({ input: z.string().optional() })\n .transform((obj) => obj.input);\n\n constructor(fields?: ToolParams) {\n super(fields);\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n *\n * Calls the tool with the provided argument and callbacks. It handles\n * string inputs specifically.\n * @param arg The input argument for the tool, which can be a string, undefined, or an input of the tool's schema.\n * @param callbacks Optional callbacks for the tool.\n * @returns A Promise that resolves with a string.\n */\n // Match the base class signature including the generics and conditional return type\n call<\n TArg extends string | undefined | z.input<this[\"schema\"]> | ToolCall,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n arg: TArg,\n callbacks?: TConfig\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n // Prepare the input for the base class call method.\n // If arg is string or undefined, wrap it; otherwise, pass ToolCall or { input: ... } directly.\n const structuredArg =\n typeof arg === \"string\" || arg == null ? { input: arg } : arg;\n\n // Ensure TConfig is passed to super.call\n return super.call(structuredArg, callbacks);\n }\n}\n\n/**\n * A tool that can be created dynamically from a function, name, and description.\n */\nexport class DynamicTool<\n ToolOutputT = ToolOutputType,\n ToolEventT = ToolEventType,\n> extends Tool<ToolOutputT, ToolEventT> {\n static lc_name() {\n return \"DynamicTool\";\n }\n\n name: string;\n\n description: string;\n\n func: DynamicToolInput<ToolOutputT, ToolEventT>[\"func\"];\n\n constructor(fields: DynamicToolInput<ToolOutputT, ToolEventT>) {\n super(fields);\n this.name = fields.name;\n this.description = fields.description;\n this.func = fields.func;\n this.returnDirect = fields.returnDirect ?? this.returnDirect;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n */\n async call<\n TArg extends string | undefined | z.input<this[\"schema\"]> | ToolCall,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n arg: TArg,\n configArg?: TConfig\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n const config = parseCallbackConfigArg(configArg);\n if (config.runName === undefined) {\n config.runName = this.name;\n }\n // Call the Tool class's call method, passing generics through\n // Cast config to TConfig to satisfy the super.call signature\n return super.call<TArg, TConfig>(arg, config as TConfig);\n }\n\n /** @ignore */\n _call(\n input: string, // DynamicTool's _call specifically expects a string after schema transformation\n runManager?: CallbackManagerForToolRun,\n parentConfig?: ToolRunnableConfig\n ): Promise<ToolOutputT> | AsyncGenerator<ToolEventT, ToolOutputT> {\n return this.func(input, runManager, parentConfig);\n }\n}\n\n/**\n * A tool that can be created dynamically from a function, name, and\n * description, designed to work with structured data. It extends the\n * StructuredTool class and overrides the _call method to execute the\n * provided function when the tool is called.\n *\n * Schema can be passed as Zod or JSON schema. The tool will not validate\n * input if JSON schema is passed.\n *\n * @template SchemaT The input schema type for the tool (Zod schema or JSON schema). Defaults to `ToolInputSchemaBase`.\n * @template SchemaOutputT The output type derived from the schema after parsing/validation. Defaults to `ToolInputSchemaOutputType<SchemaT>`.\n * @template SchemaInputT The input type derived from the schema before parsing. Defaults to `ToolInputSchemaInputType<SchemaT>`.\n * @template ToolOutputT The return type of the tool's function. Defaults to `ToolOutputType`.\n * @template NameT The literal type of the tool name (for discriminated union support). Defaults to `string`.\n */\nexport class DynamicStructuredTool<\n SchemaT = ToolInputSchemaBase,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n ToolEventT = ToolEventType,\n NameT extends string = string,\n> extends StructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n ToolEventT\n> {\n static lc_name() {\n return \"DynamicStructuredTool\";\n }\n\n declare name: NameT;\n\n description: string;\n\n func: DynamicStructuredToolInput<\n SchemaT,\n SchemaOutputT,\n ToolOutputT,\n ToolEventT\n >[\"func\"];\n\n schema: SchemaT;\n\n constructor(\n fields: DynamicStructuredToolInput<\n SchemaT,\n SchemaOutputT,\n ToolOutputT,\n ToolEventT\n > & {\n name: NameT;\n }\n ) {\n super(fields);\n this.name = fields.name;\n this.description = fields.description;\n this.func = fields.func;\n this.returnDirect = fields.returnDirect ?? this.returnDirect;\n this.schema = fields.schema;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n */\n // Match the base class signature\n async call<\n TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n arg: TArg,\n configArg?: TConfig,\n /** @deprecated */\n tags?: string[]\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n const config = parseCallbackConfigArg(configArg);\n if (config.runName === undefined) {\n config.runName = this.name;\n }\n\n // Call the base class method, passing generics through\n // Cast config to TConfig to satisfy the super.call signature\n return super.call<TArg, TConfig>(arg, config as TConfig, tags);\n }\n\n protected _call(\n arg: Parameters<\n DynamicStructuredToolInput<\n SchemaT,\n SchemaOutputT,\n ToolOutputT,\n ToolEventT\n >[\"func\"]\n >[0],\n runManager?: CallbackManagerForToolRun,\n parentConfig?: RunnableConfig\n ): Promise<ToolOutputT> | AsyncGenerator<ToolEventT, ToolOutputT> {\n return this.func(arg, runManager, parentConfig);\n }\n}\n\n/**\n * Abstract base class for toolkits in LangChain. Toolkits are collections\n * of tools that agents can use. Subclasses must implement the `tools`\n * property to provide the specific tools for the toolkit.\n */\nexport abstract class BaseToolkit {\n abstract tools: StructuredToolInterface[];\n\n getTools(): StructuredToolInterface[] {\n return this.tools;\n }\n}\n\n/**\n * Parameters for the tool function.\n * Schema can be provided as Zod or JSON schema.\n * Both schema types will be validated.\n * @template {ToolInputSchemaBase} RunInput The input schema for the tool.\n * @template {string} NameT The literal name type for discriminated union support.\n */\ninterface ToolWrapperParams<\n RunInput = ToolInputSchemaBase | undefined,\n NameT extends string = string,\n> extends ToolParams {\n /**\n * The name of the tool. If using with an LLM, this\n * will be passed as the tool name.\n */\n name: NameT;\n /**\n * The description of the tool.\n * @default `${fields.name} tool`\n */\n description?: string;\n /**\n * The input schema for the tool. If using an LLM, this\n * will be passed as the tool schema to generate arguments\n * for.\n */\n schema?: RunInput;\n /**\n * The tool response format.\n *\n * If \"content\" then the output of the tool is interpreted as the contents of a\n * ToolMessage. If \"content_and_artifact\" then the output is expected to be a\n * two-tuple corresponding to the (content, artifact) of a ToolMessage.\n *\n * @default \"content\"\n */\n responseFormat?: ResponseFormat;\n /**\n * Whether to return the tool's output directly.\n *\n * Setting this to true means that after the tool is called,\n * an agent should stop looping.\n */\n returnDirect?: boolean;\n}\n\n/**\n * Creates a new StructuredTool instance with the provided function, name, description, and schema.\n *\n * Schema can be provided as Zod or JSON schema, and both will be validated.\n *\n * @function\n * @template {ToolInputSchemaBase} SchemaT The input schema for the tool.\n * @template {ToolReturnType} ToolOutputT The output type of the tool.\n *\n * @param {RunnableFunc<z.output<SchemaT>, ToolOutputT>} func - The function to invoke when the tool is called.\n * @param {ToolWrapperParams<SchemaT>} fields - An object containing the following properties:\n * @param {string} fields.name The name of the tool.\n * @param {string | undefined} fields.description The description of the tool. Defaults to either the description on the Zod schema, or `${fields.name} tool`.\n * @param {z.AnyZodObject | z.ZodString | undefined} fields.schema The Zod schema defining the input for the tool. If undefined, it will default to a Zod string schema.\n *\n * @returns {DynamicStructuredTool<SchemaT>} A new StructuredTool instance.\n */\nexport function tool<\n SchemaT extends ZodStringV3,\n ToolOutputT = ToolOutputType,\n FuncT extends RunnableFunc<\n InferInteropZodOutput<SchemaT>,\n ToolOutputT,\n ToolRunnableConfig\n > = RunnableFunc<\n InferInteropZodOutput<SchemaT>,\n ToolOutputT,\n ToolRunnableConfig\n >,\n>(\n func: FuncT,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<InferToolOutputFromFunc<FuncT>, InferToolEventFromFunc<FuncT>>;\n\nexport function tool<\n SchemaT extends ZodStringV4,\n ToolOutputT = ToolOutputType,\n FuncT extends RunnableFunc<\n InferInteropZodOutput<SchemaT>,\n ToolOutputT,\n ToolRunnableConfig\n > = RunnableFunc<\n InferInteropZodOutput<SchemaT>,\n ToolOutputT,\n ToolRunnableConfig\n >,\n>(\n func: FuncT,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<InferToolOutputFromFunc<FuncT>, InferToolEventFromFunc<FuncT>>;\n\nexport function tool<\n SchemaT extends ZodObjectV3,\n NameT extends string,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n FuncT extends RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig> =\n RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n>(\n func: FuncT,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n InferToolOutputFromFunc<FuncT>,\n InferToolEventFromFunc<FuncT>,\n NameT\n>;\n\nexport function tool<\n SchemaT extends ZodObjectV4,\n NameT extends string,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n FuncT extends RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig> =\n RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n>(\n func: FuncT,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n InferToolOutputFromFunc<FuncT>,\n InferToolEventFromFunc<FuncT>,\n NameT\n>;\n\nexport function tool<\n SchemaT extends JSONSchema,\n NameT extends string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n FuncT extends RunnableFunc<\n Parameters<DynamicStructuredToolInput<SchemaT>[\"func\"]>[0],\n ToolOutputT,\n ToolRunnableConfig\n > = RunnableFunc<\n Parameters<DynamicStructuredToolInput<SchemaT>[\"func\"]>[0],\n ToolOutputT,\n ToolRunnableConfig\n >,\n>(\n func: FuncT,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n InferToolOutputFromFunc<FuncT>,\n InferToolEventFromFunc<FuncT>,\n NameT\n>;\n\nexport function tool<\n SchemaT extends InteropZodObject | InteropZodType<string> | JSONSchema =\n InteropZodObject,\n NameT extends string = string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n FuncT extends RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig> =\n RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n>(\n func: FuncT,\n fields: ToolWrapperParams<SchemaT, NameT>\n):\n | DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n InferToolOutputFromFunc<FuncT>,\n InferToolEventFromFunc<FuncT>,\n NameT\n >\n | DynamicTool<InferToolOutputFromFunc<FuncT>, InferToolEventFromFunc<FuncT>>;\n\n// Overloads with ToolRuntime as CallOptions\nexport function tool<\n SchemaT extends ZodStringV3,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: InferInteropZodOutput<SchemaT>,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodStringV4,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: InferInteropZodOutput<SchemaT>,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodObjectV3,\n NameT extends string,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n ToolEventType,\n NameT\n>;\n\nexport function tool<\n SchemaT extends ZodObjectV4,\n NameT extends string,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n ToolEventType,\n NameT\n>;\n\nexport function tool<\n SchemaT extends JSONSchema,\n NameT extends string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: Parameters<DynamicStructuredToolInput<SchemaT>[\"func\"]>[0],\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n ToolEventType,\n NameT\n>;\n\nexport function tool<\n SchemaT extends InteropZodObject | InteropZodType<string> | JSONSchema =\n InteropZodObject,\n NameT extends string = string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n):\n | DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n ToolEventType,\n NameT\n >\n | DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends InteropZodObject | InteropZodType<string> | JSONSchema =\n InteropZodObject,\n NameT extends string = string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n ToolEventT = ToolEventType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n):\n | DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n ToolEventT,\n NameT\n >\n | DynamicTool<ToolOutputT, ToolEventT> {\n const isSimpleStringSchema = isSimpleStringZodSchema(fields.schema);\n const isStringJSONSchema = validatesOnlyStrings(fields.schema);\n\n // If the schema is not provided, or it's a simple string schema, create a DynamicTool\n if (!fields.schema || isSimpleStringSchema || isStringJSONSchema) {\n return new DynamicTool<ToolOutputT, ToolEventT>({\n ...fields,\n description:\n fields.description ??\n (fields.schema as { description?: string } | undefined)?.description ??\n `${fields.name} tool`,\n func: async (input, runManager, config) => {\n return new Promise<ToolOutputT>((resolve, reject) => {\n const childConfig = patchConfig(config, {\n callbacks: runManager?.getChild(),\n });\n // eslint-disable-next-line no-void\n void AsyncLocalStorageProviderSingleton.runWithConfig(\n pickRunnableConfigKeys(childConfig),\n async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n resolve(func(input as any, childConfig as any));\n } catch (e) {\n reject(e);\n }\n }\n );\n });\n },\n });\n }\n\n const schema = fields.schema as InteropZodObject | JSONSchema;\n\n const description =\n fields.description ??\n (fields.schema as { description?: string }).description ??\n `${fields.name} tool`;\n\n return new DynamicStructuredTool<\n typeof schema,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n ToolEventT,\n NameT\n >({\n ...fields,\n description,\n schema,\n func: async (input, runManager, config) => {\n return new Promise<ToolOutputT>((resolve, reject) => {\n let listener: (() => void) | undefined;\n const cleanup = () => {\n if (config?.signal && listener) {\n config.signal.removeEventListener(\"abort\", listener);\n }\n };\n\n if (config?.signal) {\n listener = () => {\n cleanup();\n reject(getAbortSignalError(config.signal));\n };\n config.signal.addEventListener(\"abort\", listener, { once: true });\n }\n\n const childConfig = patchConfig(config, {\n callbacks: runManager?.getChild(),\n });\n // eslint-disable-next-line no-void\n void AsyncLocalStorageProviderSingleton.runWithConfig(\n pickRunnableConfigKeys(childConfig),\n async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result = await func(input as any, childConfig as any);\n if (isAsyncGenerator(result)) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n resolve(result as any);\n return;\n }\n\n /**\n * If the signal is aborted, we don't want to resolve the promise\n * as the promise is already rejected.\n */\n if (config?.signal?.aborted) {\n cleanup();\n return;\n }\n\n cleanup();\n resolve(result);\n } catch (e) {\n cleanup();\n reject(e);\n }\n }\n );\n });\n },\n }) as DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n ToolEventT,\n NameT\n >;\n}\n\nfunction _formatToolOutput<TOutput extends ToolOutputType>(params: {\n content: TOutput;\n name: string;\n artifact?: unknown;\n toolCallId?: string;\n metadata?: Record<string, unknown>;\n}): ToolMessage | TOutput {\n const { content, artifact, toolCallId, metadata } = params;\n if (toolCallId && !isDirectToolOutput(content)) {\n if (\n typeof content === \"string\" ||\n (Array.isArray(content) &&\n content.every((item) => typeof item === \"object\"))\n ) {\n return new ToolMessage({\n status: \"success\",\n content,\n artifact,\n tool_call_id: toolCallId,\n name: params.name,\n metadata,\n });\n } else {\n return new ToolMessage({\n status: \"success\",\n content: _stringify(content),\n artifact,\n tool_call_id: toolCallId,\n name: params.name,\n metadata,\n });\n }\n } else {\n return content;\n }\n}\n\nfunction _stringify(content: unknown): string {\n try {\n return JSON.stringify(content) ?? \"\";\n } catch (_noOp) {\n return `${content}`;\n }\n}\n\nexport type ServerTool = Record<string, unknown>;\nexport type ClientTool =\n | StructuredToolInterface\n | DynamicTool\n | RunnableToolLike;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8FA,IAAsB,iBAAtB,cAOUA,2CAKV;;;;;;;CAaE;;;;;;;CAQA,eAAe;CAEf,uBA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AAY,EACnC,YAAY;AACV,SAAI;MAEF,MAAM,SAAS,MAAM,KAAK,OAAc,YAAmB;AAC3D,UAAIP,8BAAiB,OAAO,EAAE;AAE5B,eAAQ,OAAc;AACtB;;;;;;AAOF,UAAI,QAAQ,QAAQ,SAAS;AAC3B,gBAAS;AACT;;AAGF,eAAS;AACT,cAAQ,OAAO;cACR,GAAG;AACV,eAAS;AACT,aAAO,EAAE;;MAGd;KACD;;EAEL,CAAC;;AAUJ,SAAS,kBAAkD,QAMjC;CACxB,MAAM,EAAE,SAAS,UAAU,YAAY,aAAa;AACpD,KAAI,cAAc,CAACS,yCAAmB,QAAQ,CAC5C,KACE,OAAO,YAAY,YAClB,MAAM,QAAQ,QAAQ,IACrB,QAAQ,OAAO,SAAS,OAAO,SAAS,SAAS,CAEnD,QAAO,IAAIC,kCAAY;EACrB,QAAQ;EACR;EACA;EACA,cAAc;EACd,MAAM,OAAO;EACb;EACD,CAAC;KAEF,QAAO,IAAIA,kCAAY;EACrB,QAAQ;EACR,SAAS,WAAW,QAAQ;EAC5B;EACA,cAAc;EACd,MAAM,OAAO;EACb;EACD,CAAC;KAGJ,QAAO;;AAIX,SAAS,WAAW,SAA0B;AAC5C,KAAI;AACF,SAAO,KAAK,UAAU,QAAQ,IAAI;UAC3B,OAAO;AACd,SAAO,GAAG"}
|
package/dist/tools/index.d.cts
CHANGED
|
@@ -6,14 +6,14 @@ import { RunnableFunc, RunnableToolLike } from "../runnables/base.cjs";
|
|
|
6
6
|
import { JsonSchema7Type } from "../utils/zod-to-json-schema/parseTypes.cjs";
|
|
7
7
|
import { BaseLangChain } from "../language_models/base.cjs";
|
|
8
8
|
import { ToolInputParsingException } from "./utils.cjs";
|
|
9
|
-
import { BaseDynamicToolInput, ContentAndArtifact, DynamicStructuredToolInput, DynamicToolInput, ResponseFormat, StringInputToolSchema, StructuredToolCallInput, StructuredToolInterface, StructuredToolParams, ToolInputSchemaBase, ToolInputSchemaInputType, ToolInputSchemaOutputType, ToolInterface, ToolOutputType, ToolParams, ToolReturnType, ToolRunnableConfig, ToolRuntime, isLangChainTool, isRunnableToolLike, isStructuredTool, isStructuredToolParams } from "./types.cjs";
|
|
9
|
+
import { BaseDynamicToolInput, ContentAndArtifact, DynamicStructuredToolInput, DynamicToolInput, InferToolEventFromFunc, InferToolOutputFromFunc, ResponseFormat, StringInputToolSchema, StructuredToolCallInput, StructuredToolInterface, StructuredToolParams, ToolEventType, ToolInputSchemaBase, ToolInputSchemaInputType, ToolInputSchemaOutputType, ToolInterface, ToolOutputType, ToolParams, ToolReturnType, ToolRunnableConfig, ToolRuntime, isLangChainTool, isRunnableToolLike, isStructuredTool, isStructuredToolParams } from "./types.cjs";
|
|
10
10
|
import { z } from "zod/v3";
|
|
11
11
|
|
|
12
12
|
//#region src/tools/index.d.ts
|
|
13
13
|
/**
|
|
14
14
|
* Base class for Tools that accept input of any shape defined by a Zod schema.
|
|
15
15
|
*/
|
|
16
|
-
declare abstract class StructuredTool<SchemaT = ToolInputSchemaBase, SchemaOutputT = ToolInputSchemaOutputType<SchemaT>, SchemaInputT = ToolInputSchemaInputType<SchemaT>, ToolOutputT = ToolOutputType> extends BaseLangChain<StructuredToolCallInput<SchemaT, SchemaInputT>, ToolOutputT | ToolMessage> implements StructuredToolInterface<SchemaT, SchemaInputT, ToolOutputT> {
|
|
16
|
+
declare abstract class StructuredTool<SchemaT = ToolInputSchemaBase, SchemaOutputT = ToolInputSchemaOutputType<SchemaT>, SchemaInputT = ToolInputSchemaInputType<SchemaT>, ToolOutputT = ToolOutputType, ToolEventT = ToolEventType> extends BaseLangChain<StructuredToolCallInput<SchemaT, SchemaInputT>, ToolOutputT | ToolMessage> implements StructuredToolInterface<SchemaT, SchemaInputT, ToolOutputT> {
|
|
17
17
|
abstract name: string;
|
|
18
18
|
abstract description: string;
|
|
19
19
|
abstract schema: SchemaT;
|
|
@@ -48,7 +48,7 @@ declare abstract class StructuredTool<SchemaT = ToolInputSchemaBase, SchemaOutpu
|
|
|
48
48
|
*/
|
|
49
49
|
defaultConfig?: ToolRunnableConfig;
|
|
50
50
|
constructor(fields?: ToolParams);
|
|
51
|
-
protected abstract _call(arg: SchemaOutputT, runManager?: CallbackManagerForToolRun, parentConfig?: ToolRunnableConfig): Promise<ToolOutputT> | AsyncGenerator<
|
|
51
|
+
protected abstract _call(arg: SchemaOutputT, runManager?: CallbackManagerForToolRun, parentConfig?: ToolRunnableConfig): Promise<ToolOutputT> | AsyncGenerator<ToolEventT, ToolOutputT>;
|
|
52
52
|
/**
|
|
53
53
|
* Invokes the tool with the provided input and configuration.
|
|
54
54
|
* @param input The input for the tool.
|
|
@@ -74,7 +74,7 @@ declare abstract class StructuredTool<SchemaT = ToolInputSchemaBase, SchemaOutpu
|
|
|
74
74
|
/**
|
|
75
75
|
* Base class for Tools that accept input as a string.
|
|
76
76
|
*/
|
|
77
|
-
declare abstract class Tool<ToolOutputT = ToolOutputType> extends StructuredTool<StringInputToolSchema, ToolInputSchemaOutputType<StringInputToolSchema>, ToolInputSchemaInputType<StringInputToolSchema>, ToolOutputT> implements ToolInterface<StringInputToolSchema, ToolInputSchemaInputType<StringInputToolSchema>, ToolOutputT> {
|
|
77
|
+
declare abstract class Tool<ToolOutputT = ToolOutputType, ToolEventT = ToolEventType> extends StructuredTool<StringInputToolSchema, ToolInputSchemaOutputType<StringInputToolSchema>, ToolInputSchemaInputType<StringInputToolSchema>, ToolOutputT, ToolEventT> implements ToolInterface<StringInputToolSchema, ToolInputSchemaInputType<StringInputToolSchema>, ToolOutputT> {
|
|
78
78
|
schema: z.ZodEffects<z.ZodObject<{
|
|
79
79
|
input: z.ZodOptional<z.ZodString>;
|
|
80
80
|
}, "strip", z.ZodTypeAny, {
|
|
@@ -99,18 +99,18 @@ declare abstract class Tool<ToolOutputT = ToolOutputType> extends StructuredTool
|
|
|
99
99
|
/**
|
|
100
100
|
* A tool that can be created dynamically from a function, name, and description.
|
|
101
101
|
*/
|
|
102
|
-
declare class DynamicTool<ToolOutputT = ToolOutputType> extends Tool<ToolOutputT> {
|
|
102
|
+
declare class DynamicTool<ToolOutputT = ToolOutputType, ToolEventT = ToolEventType> extends Tool<ToolOutputT, ToolEventT> {
|
|
103
103
|
static lc_name(): string;
|
|
104
104
|
name: string;
|
|
105
105
|
description: string;
|
|
106
|
-
func: DynamicToolInput<ToolOutputT>["func"];
|
|
107
|
-
constructor(fields: DynamicToolInput<ToolOutputT>);
|
|
106
|
+
func: DynamicToolInput<ToolOutputT, ToolEventT>["func"];
|
|
107
|
+
constructor(fields: DynamicToolInput<ToolOutputT, ToolEventT>);
|
|
108
108
|
/**
|
|
109
109
|
* @deprecated Use .invoke() instead. Will be removed in 0.3.0.
|
|
110
110
|
*/
|
|
111
111
|
call<TArg extends string | undefined | z.input<this["schema"]> | ToolCall, TConfig extends ToolRunnableConfig | undefined>(arg: TArg, configArg?: TConfig): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>>;
|
|
112
112
|
/** @ignore */
|
|
113
|
-
_call(input: string, runManager?: CallbackManagerForToolRun, parentConfig?: ToolRunnableConfig): Promise<ToolOutputT> | AsyncGenerator<
|
|
113
|
+
_call(input: string, runManager?: CallbackManagerForToolRun, parentConfig?: ToolRunnableConfig): Promise<ToolOutputT> | AsyncGenerator<ToolEventT, ToolOutputT>;
|
|
114
114
|
}
|
|
115
115
|
/**
|
|
116
116
|
* A tool that can be created dynamically from a function, name, and
|
|
@@ -127,13 +127,13 @@ declare class DynamicTool<ToolOutputT = ToolOutputType> extends Tool<ToolOutputT
|
|
|
127
127
|
* @template ToolOutputT The return type of the tool's function. Defaults to `ToolOutputType`.
|
|
128
128
|
* @template NameT The literal type of the tool name (for discriminated union support). Defaults to `string`.
|
|
129
129
|
*/
|
|
130
|
-
declare class DynamicStructuredTool<SchemaT = ToolInputSchemaBase, SchemaOutputT = ToolInputSchemaOutputType<SchemaT>, SchemaInputT = ToolInputSchemaInputType<SchemaT>, ToolOutputT = ToolOutputType, NameT extends string = string> extends StructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT> {
|
|
130
|
+
declare class DynamicStructuredTool<SchemaT = ToolInputSchemaBase, SchemaOutputT = ToolInputSchemaOutputType<SchemaT>, SchemaInputT = ToolInputSchemaInputType<SchemaT>, ToolOutputT = ToolOutputType, ToolEventT = ToolEventType, NameT extends string = string> extends StructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT, ToolEventT> {
|
|
131
131
|
static lc_name(): string;
|
|
132
132
|
name: NameT;
|
|
133
133
|
description: string;
|
|
134
|
-
func: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT>["func"];
|
|
134
|
+
func: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT, ToolEventT>["func"];
|
|
135
135
|
schema: SchemaT;
|
|
136
|
-
constructor(fields: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT> & {
|
|
136
|
+
constructor(fields: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT, ToolEventT> & {
|
|
137
137
|
name: NameT;
|
|
138
138
|
});
|
|
139
139
|
/**
|
|
@@ -142,7 +142,7 @@ declare class DynamicStructuredTool<SchemaT = ToolInputSchemaBase, SchemaOutputT
|
|
|
142
142
|
call<TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>, TConfig extends ToolRunnableConfig | undefined>(arg: TArg, configArg?: TConfig, /** @deprecated */
|
|
143
143
|
|
|
144
144
|
tags?: string[]): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>>;
|
|
145
|
-
protected _call(arg: Parameters<DynamicStructuredToolInput<SchemaT, SchemaOutputT>["func"]>[0], runManager?: CallbackManagerForToolRun, parentConfig?: RunnableConfig): Promise<ToolOutputT> | AsyncGenerator<
|
|
145
|
+
protected _call(arg: Parameters<DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT, ToolEventT>["func"]>[0], runManager?: CallbackManagerForToolRun, parentConfig?: RunnableConfig): Promise<ToolOutputT> | AsyncGenerator<ToolEventT, ToolOutputT>;
|
|
146
146
|
}
|
|
147
147
|
/**
|
|
148
148
|
* Abstract base class for toolkits in LangChain. Toolkits are collections
|
|
@@ -212,17 +212,18 @@ interface ToolWrapperParams<RunInput = ToolInputSchemaBase | undefined, NameT ex
|
|
|
212
212
|
*
|
|
213
213
|
* @returns {DynamicStructuredTool<SchemaT>} A new StructuredTool instance.
|
|
214
214
|
*/
|
|
215
|
-
declare function tool<SchemaT extends ZodStringV3, ToolOutputT = ToolOutputType
|
|
216
|
-
declare function tool<SchemaT extends ZodStringV4, ToolOutputT = ToolOutputType
|
|
217
|
-
declare function tool<SchemaT extends ZodObjectV3, NameT extends string, SchemaOutputT = InferInteropZodOutput<SchemaT>, SchemaInputT = InferInteropZodInput<SchemaT>, ToolOutputT = ToolOutputType>
|
|
218
|
-
declare function tool<SchemaT extends ZodObjectV4, NameT extends string, SchemaOutputT = InferInteropZodOutput<SchemaT>, SchemaInputT = InferInteropZodInput<SchemaT>, ToolOutputT = ToolOutputType>
|
|
219
|
-
declare function tool<SchemaT extends JsonSchema7Type, NameT extends string, SchemaOutputT = ToolInputSchemaOutputType<SchemaT>, SchemaInputT = ToolInputSchemaInputType<SchemaT>, ToolOutputT = ToolOutputType>
|
|
220
|
-
declare function tool<SchemaT extends InteropZodObject | InteropZodType<string> | JsonSchema7Type = InteropZodObject, NameT extends string = string, SchemaOutputT = ToolInputSchemaOutputType<SchemaT>, SchemaInputT = ToolInputSchemaInputType<SchemaT>, ToolOutputT = ToolOutputType>
|
|
215
|
+
declare function tool<SchemaT extends ZodStringV3, ToolOutputT = ToolOutputType, FuncT extends RunnableFunc<InferInteropZodOutput<SchemaT>, ToolOutputT, ToolRunnableConfig> = RunnableFunc<InferInteropZodOutput<SchemaT>, ToolOutputT, ToolRunnableConfig>>(func: FuncT, fields: ToolWrapperParams<SchemaT>): DynamicTool<InferToolOutputFromFunc<FuncT>, InferToolEventFromFunc<FuncT>>;
|
|
216
|
+
declare function tool<SchemaT extends ZodStringV4, ToolOutputT = ToolOutputType, FuncT extends RunnableFunc<InferInteropZodOutput<SchemaT>, ToolOutputT, ToolRunnableConfig> = RunnableFunc<InferInteropZodOutput<SchemaT>, ToolOutputT, ToolRunnableConfig>>(func: FuncT, fields: ToolWrapperParams<SchemaT>): DynamicTool<InferToolOutputFromFunc<FuncT>, InferToolEventFromFunc<FuncT>>;
|
|
217
|
+
declare function tool<SchemaT extends ZodObjectV3, NameT extends string, SchemaOutputT = InferInteropZodOutput<SchemaT>, SchemaInputT = InferInteropZodInput<SchemaT>, ToolOutputT = ToolOutputType, FuncT extends RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig> = RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>>(func: FuncT, fields: ToolWrapperParams<SchemaT, NameT>): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, InferToolOutputFromFunc<FuncT>, InferToolEventFromFunc<FuncT>, NameT>;
|
|
218
|
+
declare function tool<SchemaT extends ZodObjectV4, NameT extends string, SchemaOutputT = InferInteropZodOutput<SchemaT>, SchemaInputT = InferInteropZodInput<SchemaT>, ToolOutputT = ToolOutputType, FuncT extends RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig> = RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>>(func: FuncT, fields: ToolWrapperParams<SchemaT, NameT>): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, InferToolOutputFromFunc<FuncT>, InferToolEventFromFunc<FuncT>, NameT>;
|
|
219
|
+
declare function tool<SchemaT extends JsonSchema7Type, NameT extends string, SchemaOutputT = ToolInputSchemaOutputType<SchemaT>, SchemaInputT = ToolInputSchemaInputType<SchemaT>, ToolOutputT = ToolOutputType, FuncT extends RunnableFunc<Parameters<DynamicStructuredToolInput<SchemaT>["func"]>[0], ToolOutputT, ToolRunnableConfig> = RunnableFunc<Parameters<DynamicStructuredToolInput<SchemaT>["func"]>[0], ToolOutputT, ToolRunnableConfig>>(func: FuncT, fields: ToolWrapperParams<SchemaT, NameT>): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, InferToolOutputFromFunc<FuncT>, InferToolEventFromFunc<FuncT>, NameT>;
|
|
220
|
+
declare function tool<SchemaT extends InteropZodObject | InteropZodType<string> | JsonSchema7Type = InteropZodObject, NameT extends string = string, SchemaOutputT = ToolInputSchemaOutputType<SchemaT>, SchemaInputT = ToolInputSchemaInputType<SchemaT>, ToolOutputT = ToolOutputType, FuncT extends RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig> = RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>>(func: FuncT, fields: ToolWrapperParams<SchemaT, NameT>): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, InferToolOutputFromFunc<FuncT>, InferToolEventFromFunc<FuncT>, NameT> | DynamicTool<InferToolOutputFromFunc<FuncT>, InferToolEventFromFunc<FuncT>>;
|
|
221
221
|
declare function tool<SchemaT extends ZodStringV3, ToolOutputT = ToolOutputType, TState = unknown, TContext = unknown>(func: (input: InferInteropZodOutput<SchemaT>, runtime: ToolRuntime<TState, TContext>) => ToolOutputT | Promise<ToolOutputT>, fields: ToolWrapperParams<SchemaT>): DynamicTool<ToolOutputT>;
|
|
222
222
|
declare function tool<SchemaT extends ZodStringV4, ToolOutputT = ToolOutputType, TState = unknown, TContext = unknown>(func: (input: InferInteropZodOutput<SchemaT>, runtime: ToolRuntime<TState, TContext>) => ToolOutputT | Promise<ToolOutputT>, fields: ToolWrapperParams<SchemaT>): DynamicTool<ToolOutputT>;
|
|
223
|
-
declare function tool<SchemaT extends ZodObjectV3, NameT extends string, SchemaOutputT = InferInteropZodOutput<SchemaT>, SchemaInputT = InferInteropZodInput<SchemaT>, ToolOutputT = ToolOutputType, TState = unknown, TContext = unknown>(func: (input: SchemaOutputT, runtime: ToolRuntime<TState, TContext>) => ToolOutputT | Promise<ToolOutputT>, fields: ToolWrapperParams<SchemaT, NameT>): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT, NameT>;
|
|
224
|
-
declare function tool<SchemaT extends ZodObjectV4, NameT extends string, SchemaOutputT = InferInteropZodOutput<SchemaT>, SchemaInputT = InferInteropZodInput<SchemaT>, ToolOutputT = ToolOutputType, TState = unknown, TContext = unknown>(func: (input: SchemaOutputT, runtime: ToolRuntime<TState, TContext>) => ToolOutputT | Promise<ToolOutputT>, fields: ToolWrapperParams<SchemaT, NameT>): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT, NameT>;
|
|
225
|
-
declare function tool<SchemaT extends JsonSchema7Type, NameT extends string, SchemaOutputT = ToolInputSchemaOutputType<SchemaT>, SchemaInputT = ToolInputSchemaInputType<SchemaT>, ToolOutputT = ToolOutputType, TState = unknown, TContext = unknown>(func: (input: Parameters<DynamicStructuredToolInput<SchemaT>["func"]>[0], runtime: ToolRuntime<TState, TContext>) => ToolOutputT | Promise<ToolOutputT>, fields: ToolWrapperParams<SchemaT, NameT>): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT, NameT>;
|
|
223
|
+
declare function tool<SchemaT extends ZodObjectV3, NameT extends string, SchemaOutputT = InferInteropZodOutput<SchemaT>, SchemaInputT = InferInteropZodInput<SchemaT>, ToolOutputT = ToolOutputType, TState = unknown, TContext = unknown>(func: (input: SchemaOutputT, runtime: ToolRuntime<TState, TContext>) => ToolOutputT | Promise<ToolOutputT>, fields: ToolWrapperParams<SchemaT, NameT>): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT, ToolEventType, NameT>;
|
|
224
|
+
declare function tool<SchemaT extends ZodObjectV4, NameT extends string, SchemaOutputT = InferInteropZodOutput<SchemaT>, SchemaInputT = InferInteropZodInput<SchemaT>, ToolOutputT = ToolOutputType, TState = unknown, TContext = unknown>(func: (input: SchemaOutputT, runtime: ToolRuntime<TState, TContext>) => ToolOutputT | Promise<ToolOutputT>, fields: ToolWrapperParams<SchemaT, NameT>): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT, ToolEventType, NameT>;
|
|
225
|
+
declare function tool<SchemaT extends JsonSchema7Type, NameT extends string, SchemaOutputT = ToolInputSchemaOutputType<SchemaT>, SchemaInputT = ToolInputSchemaInputType<SchemaT>, ToolOutputT = ToolOutputType, TState = unknown, TContext = unknown>(func: (input: Parameters<DynamicStructuredToolInput<SchemaT>["func"]>[0], runtime: ToolRuntime<TState, TContext>) => ToolOutputT | Promise<ToolOutputT>, fields: ToolWrapperParams<SchemaT, NameT>): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT, ToolEventType, NameT>;
|
|
226
|
+
declare function tool<SchemaT extends InteropZodObject | InteropZodType<string> | JsonSchema7Type = InteropZodObject, NameT extends string = string, SchemaOutputT = ToolInputSchemaOutputType<SchemaT>, SchemaInputT = ToolInputSchemaInputType<SchemaT>, ToolOutputT = ToolOutputType, TState = unknown, TContext = unknown>(func: (input: SchemaOutputT, runtime: ToolRuntime<TState, TContext>) => ToolOutputT | Promise<ToolOutputT>, fields: ToolWrapperParams<SchemaT, NameT>): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT, ToolEventType, NameT> | DynamicTool<ToolOutputT>;
|
|
226
227
|
type ServerTool = Record<string, unknown>;
|
|
227
228
|
type ClientTool = StructuredToolInterface | DynamicTool | RunnableToolLike;
|
|
228
229
|
//#endregion
|