-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
tools.ts
352 lines (310 loc) Β· 9.54 KB
/
tools.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
import { z } from "zod";
import {
CallbackManager,
CallbackManagerForToolRun,
Callbacks,
parseCallbackConfigArg,
} from "./callbacks/manager.js";
import {
BaseLangChain,
type BaseLangChainParams,
} from "./language_models/base.js";
import { ensureConfig, type RunnableConfig } from "./runnables/config.js";
import type { RunnableInterface } from "./runnables/base.js";
/**
* Parameters for the Tool classes.
*/
export interface ToolParams extends BaseLangChainParams {}
/**
* Custom error class used to handle exceptions related to tool input parsing.
* It extends the built-in `Error` class and adds an optional `output`
* property that can hold the output that caused the exception.
*/
export class ToolInputParsingException extends Error {
output?: string;
constructor(message: string, output?: string) {
super(message);
this.output = output;
}
}
export interface StructuredToolInterface<
// eslint-disable-next-line @typescript-eslint/no-explicit-any
T extends z.ZodObject<any, any, any, any> = z.ZodObject<any, any, any, any>
> extends RunnableInterface<
(z.output<T> extends string ? string : never) | z.input<T>,
string
> {
lc_namespace: string[];
schema: T | z.ZodEffects<T>;
/**
* Calls the tool with the provided argument, configuration, and tags. It
* parses the input according to the schema, handles any errors, and
* manages callbacks.
* @param arg The input argument for the tool.
* @param configArg Optional configuration or callbacks for the tool.
* @param tags Optional tags for the tool.
* @returns A Promise that resolves with a string.
*/
call(
arg: (z.output<T> extends string ? string : never) | z.input<T>,
configArg?: Callbacks | RunnableConfig,
/** @deprecated */
tags?: string[]
): Promise<string>;
name: string;
description: string;
returnDirect: boolean;
}
/**
* Base class for Tools that accept input of any shape defined by a Zod schema.
*/
export abstract class StructuredTool<
// eslint-disable-next-line @typescript-eslint/no-explicit-any
T extends z.ZodObject<any, any, any, any> = z.ZodObject<any, any, any, any>
> extends BaseLangChain<
(z.output<T> extends string ? string : never) | z.input<T>,
string
> {
abstract schema: T | z.ZodEffects<T>;
get lc_namespace() {
return ["langchain", "tools"];
}
constructor(fields?: ToolParams) {
super(fields ?? {});
}
protected abstract _call(
arg: z.output<T>,
runManager?: CallbackManagerForToolRun,
config?: RunnableConfig
): Promise<string>;
/**
* Invokes the tool with the provided input and configuration.
* @param input The input for the tool.
* @param config Optional configuration for the tool.
* @returns A Promise that resolves with a string.
*/
async invoke(
input: (z.output<T> extends string ? string : never) | z.input<T>,
config?: RunnableConfig
): Promise<string> {
return this.call(input, ensureConfig(config));
}
/**
* Calls the tool with the provided argument, configuration, and tags. It
* parses the input according to the schema, handles any errors, and
* manages callbacks.
* @param arg The input argument for the tool.
* @param configArg Optional configuration or callbacks for the tool.
* @param tags Optional tags for the tool.
* @returns A Promise that resolves with a string.
*/
async call(
arg: (z.output<T> extends string ? string : never) | z.input<T>,
configArg?: Callbacks | RunnableConfig,
/** @deprecated */
tags?: string[]
): Promise<string> {
let parsed;
try {
parsed = await this.schema.parseAsync(arg);
} catch (e) {
throw new ToolInputParsingException(
`Received tool input did not match expected schema`,
JSON.stringify(arg)
);
}
const config = parseCallbackConfigArg(configArg);
const callbackManager_ = await CallbackManager.configure(
config.callbacks,
this.callbacks,
config.tags || tags,
this.tags,
config.metadata,
this.metadata,
{ verbose: this.verbose }
);
const runManager = await callbackManager_?.handleToolStart(
this.toJSON(),
typeof parsed === "string" ? parsed : JSON.stringify(parsed),
config.runId,
undefined,
undefined,
undefined,
config.runName
);
delete config.runId;
let result;
try {
result = await this._call(parsed, runManager, config);
} catch (e) {
await runManager?.handleToolError(e);
throw e;
}
await runManager?.handleToolEnd(result);
return result;
}
abstract name: string;
abstract description: string;
returnDirect = false;
}
export interface ToolInterface extends StructuredToolInterface {
/**
* Calls the tool with the provided argument and callbacks. It handles
* string inputs specifically.
* @param arg The input argument for the tool, which can be a string, undefined, or an input of the tool's schema.
* @param callbacks Optional callbacks for the tool.
* @returns A Promise that resolves with a string.
*/
call(
arg: string | undefined | z.input<this["schema"]>,
callbacks?: Callbacks | RunnableConfig
): Promise<string>;
}
/**
* Base class for Tools that accept input as a string.
*/
export abstract class Tool extends StructuredTool {
schema = z
.object({ input: z.string().optional() })
.transform((obj) => obj.input);
constructor(fields?: ToolParams) {
super(fields);
}
/**
* Calls the tool with the provided argument and callbacks. It handles
* string inputs specifically.
* @param arg The input argument for the tool, which can be a string, undefined, or an input of the tool's schema.
* @param callbacks Optional callbacks for the tool.
* @returns A Promise that resolves with a string.
*/
call(
arg: string | undefined | z.input<this["schema"]>,
callbacks?: Callbacks | RunnableConfig
): Promise<string> {
return super.call(
typeof arg === "string" || !arg ? { input: arg } : arg,
callbacks
);
}
}
export interface BaseDynamicToolInput extends ToolParams {
name: string;
description: string;
returnDirect?: boolean;
}
/**
* Interface for the input parameters of the DynamicTool class.
*/
export interface DynamicToolInput extends BaseDynamicToolInput {
func: (
input: string,
runManager?: CallbackManagerForToolRun,
config?: RunnableConfig
) => Promise<string>;
}
/**
* Interface for the input parameters of the DynamicStructuredTool class.
*/
export interface DynamicStructuredToolInput<
// eslint-disable-next-line @typescript-eslint/no-explicit-any
T extends z.ZodObject<any, any, any, any> = z.ZodObject<any, any, any, any>
> extends BaseDynamicToolInput {
func: (
input: z.infer<T>,
runManager?: CallbackManagerForToolRun,
config?: RunnableConfig
) => Promise<string>;
schema: T;
}
/**
* A tool that can be created dynamically from a function, name, and description.
*/
export class DynamicTool extends Tool {
static lc_name() {
return "DynamicTool";
}
name: string;
description: string;
func: DynamicToolInput["func"];
constructor(fields: DynamicToolInput) {
super(fields);
this.name = fields.name;
this.description = fields.description;
this.func = fields.func;
this.returnDirect = fields.returnDirect ?? this.returnDirect;
}
async call(
arg: string | undefined | z.input<this["schema"]>,
configArg?: RunnableConfig | Callbacks
): Promise<string> {
const config = parseCallbackConfigArg(configArg);
if (config.runName === undefined) {
config.runName = this.name;
}
return super.call(arg, config);
}
/** @ignore */
async _call(
input: string,
runManager?: CallbackManagerForToolRun,
config?: RunnableConfig
): Promise<string> {
return this.func(input, runManager, config);
}
}
/**
* A tool that can be created dynamically from a function, name, and
* description, designed to work with structured data. It extends the
* StructuredTool class and overrides the _call method to execute the
* provided function when the tool is called.
*/
export class DynamicStructuredTool<
// eslint-disable-next-line @typescript-eslint/no-explicit-any
T extends z.ZodObject<any, any, any, any> = z.ZodObject<any, any, any, any>
> extends StructuredTool {
static lc_name() {
return "DynamicStructuredTool";
}
name: string;
description: string;
func: DynamicStructuredToolInput["func"];
schema: T;
constructor(fields: DynamicStructuredToolInput<T>) {
super(fields);
this.name = fields.name;
this.description = fields.description;
this.func = fields.func;
this.returnDirect = fields.returnDirect ?? this.returnDirect;
this.schema = fields.schema;
}
async call(
arg: z.output<T>,
configArg?: RunnableConfig | Callbacks,
/** @deprecated */
tags?: string[]
): Promise<string> {
const config = parseCallbackConfigArg(configArg);
if (config.runName === undefined) {
config.runName = this.name;
}
return super.call(arg, config, tags);
}
protected _call(
arg: z.output<T>,
runManager?: CallbackManagerForToolRun,
config?: RunnableConfig
): Promise<string> {
return this.func(arg, runManager, config);
}
}
/**
* Abstract base class for toolkits in LangChain. Toolkits are collections
* of tools that agents can use. Subclasses must implement the `tools`
* property to provide the specific tools for the toolkit.
*/
export abstract class BaseToolkit {
abstract tools: StructuredToolInterface[];
getTools(): StructuredToolInterface[] {
return this.tools;
}
}