forked from i-am-bee/beeai-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbase.ts
451 lines (393 loc) · 12.6 KB
/
base.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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
/**
* Copyright 2024 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { FrameworkError } from "@/errors.js";
import * as R from "remeda";
import { Retryable, RetryableConfig } from "@/internals/helpers/retryable.js";
import { Serializable } from "@/internals/serializable.js";
import { Task } from "promise-based-task";
import { Cache, ObjectHashKeyFn } from "@/cache/decoratorCache.js";
import { BaseCache } from "@/cache/base.js";
import { NullCache } from "@/cache/nullCache.js";
import type { ErrorObject, ValidateFunction } from "ajv";
import {
AnyToolSchemaLike,
createSchemaValidator,
FromSchemaLike,
FromSchemaLikeRaw,
toJsonSchema,
validateSchema,
} from "@/internals/helpers/schema.js";
import { validate } from "@/internals/helpers/general.js";
import { z, ZodSchema } from "zod";
import { Emitter } from "@/emitter/emitter.js";
import { Callback } from "@/emitter/types.js";
import { GetRunContext, RunContext } from "@/context.js";
import { shallowCopy } from "@/serializer/utils.js";
export class ToolError extends FrameworkError {}
export class ToolInputValidationError extends ToolError {
validationErrors: ErrorObject[];
constructor(message: string, validationErrors: ErrorObject[] = []) {
super(message, []);
this.validationErrors = validationErrors;
}
}
export interface RetryOptions {
maxRetries?: number;
factor?: number;
}
export interface BaseToolOptions<TOutput = any> {
retryOptions?: RetryOptions;
fatalErrors?: ErrorConstructor[];
cache?: BaseCache<Task<TOutput>> | false;
}
export interface BaseToolRunOptions {
retryOptions?: RetryOptions;
signal?: AbortSignal;
}
export abstract class ToolOutput extends Serializable {
abstract getTextContent(): string;
abstract isEmpty(): boolean;
toString() {
return this.getTextContent();
}
}
export class StringToolOutput extends ToolOutput {
constructor(
public readonly result = "",
public readonly ctx?: Record<string, any>,
) {
super();
this.result = result ?? "";
}
static {
this.register();
}
isEmpty() {
return !this.result;
}
@Cache()
getTextContent(): string {
return this.result.toString();
}
createSnapshot() {
return {
result: this.result,
ctx: this.ctx,
};
}
loadSnapshot(snapshot: ReturnType<typeof this.createSnapshot>) {
Object.assign(this, snapshot);
}
}
export class JSONToolOutput<T> extends ToolOutput {
constructor(
public readonly result: T,
public readonly ctx?: Record<string, any>,
) {
super();
}
static {
this.register();
}
isEmpty() {
return !this.result || R.isEmpty(this.result);
}
@Cache()
getTextContent(): string {
return JSON.stringify(this.result);
}
createSnapshot() {
return {
result: this.result,
ctx: this.ctx,
};
}
loadSnapshot(snapshot: ReturnType<typeof this.createSnapshot>) {
Object.assign(this, snapshot);
}
}
export interface ToolSnapshot<TOutput extends ToolOutput, TOptions extends BaseToolOptions> {
name: string;
description: string;
options: TOptions;
cache: BaseCache<Task<TOutput>>;
emitter: Emitter<any>;
}
export type ToolInput<T extends AnyTool> = FromSchemaLike<Awaited<ReturnType<T["inputSchema"]>>>;
export type ToolInputRaw<T extends AnyTool> = FromSchemaLikeRaw<
Awaited<ReturnType<T["inputSchema"]>>
>;
type ToolConstructorParameters<TOptions extends BaseToolOptions> =
Partial<TOptions> extends TOptions ? [options?: TOptions] : [options: TOptions];
export interface ToolCallbacks<TInput, TOutput> {
start: Callback<{ input: TInput; options: unknown }>;
success: Callback<{ output: TOutput; input: TInput; options: unknown }>;
error: Callback<{ input: TInput; error: ToolError | ToolInputValidationError; options: unknown }>;
retry: Callback<{ error: ToolError | ToolInputValidationError; input: TInput; options: unknown }>;
finish: Callback<null>;
}
export abstract class Tool<
TOutput extends ToolOutput = ToolOutput,
TOptions extends BaseToolOptions = BaseToolOptions,
TRunOptions extends BaseToolRunOptions = BaseToolRunOptions,
> extends Serializable {
abstract name: string;
abstract description: string;
public readonly cache: BaseCache<Task<TOutput>>;
protected readonly options: TOptions;
public readonly emitter = new Emitter<ToolCallbacks<ToolInput<this>, TOutput>>({
namespace: ["tool"],
creator: this,
});
abstract inputSchema(): Promise<AnyToolSchemaLike> | AnyToolSchemaLike;
constructor(...args: ToolConstructorParameters<TOptions>) {
super();
const [options] = args;
this.options = options ?? ({} as TOptions);
this.cache = options?.cache ? options.cache : new NullCache();
}
protected toError(e: Error, context: any) {
if (e instanceof ToolError) {
Object.assign(e.context, context);
return e;
} else {
return new ToolError(`Tool "${this.name}" has occurred an error!`, [e], {
context,
});
}
}
run(input: ToolInputRaw<this>, options?: TRunOptions): Promise<TOutput> {
return RunContext.enter(
this,
{ signal: options?.signal, params: [input, options] as const },
async (run) => {
const meta = { input, options };
let errorPropagated = false;
try {
await this.assertInput(input);
const output = await new Retryable({
executor: async () => {
errorPropagated = false;
await run.emitter.emit("start", { ...meta });
return this.cache.enabled
? await this._runCached(input, options, run)
: await this._run(input, options, run);
},
onError: async (error) => {
errorPropagated = true;
await run.emitter.emit("error", {
error: this.toError(error, meta),
...meta,
});
if (this.options.fatalErrors?.some((cls) => error instanceof cls)) {
throw error;
}
},
onRetry: async (_, error) => {
await run.emitter.emit("retry", { ...meta, error: this.toError(error, meta) });
},
config: {
...this._createRetryOptions(options?.retryOptions),
signal: options?.signal,
},
}).get();
await run.emitter.emit("success", { output, ...meta });
return output;
} catch (e) {
const error = this.toError(e, meta);
if (!errorPropagated) {
await run.emitter.emit("error", {
error,
options,
input,
});
}
throw error;
} finally {
await this.emitter.emit("finish", null);
}
},
);
}
protected async _runCached(
input: ToolInput<this>,
options: TRunOptions | undefined,
run: GetRunContext<this>,
): Promise<TOutput> {
const key = ObjectHashKeyFn({
input,
options: R.omit(options ?? ({} as TRunOptions), ["signal", "retryOptions"]),
});
const cacheEntry = await this.cache.get(key);
if (cacheEntry !== undefined) {
return cacheEntry!;
}
const task = new Task<TOutput, Error>();
await this.cache.set(key, task);
this._run(input, options, run)
.then((req) => task.resolve(req))
.catch(async (err) => {
void task.reject(err);
await this.cache.delete(key);
});
return task;
}
public async clearCache() {
await this.cache.clear();
}
protected abstract _run(
arg: ToolInput<this>,
options: TRunOptions | undefined,
run: GetRunContext<typeof this>,
): Promise<TOutput>;
async getInputJsonSchema() {
return toJsonSchema(await this.inputSchema());
}
static isTool(value: unknown): value is Tool {
return value instanceof Tool && "name" in value && "description" in value;
}
private _createRetryOptions(...overrides: (RetryOptions | undefined)[]): RetryableConfig {
const defaultOptions: Required<RetryOptions> = {
maxRetries: 0,
factor: 1,
};
return R.pipe(
[defaultOptions, this.options.retryOptions, ...overrides],
R.filter(R.isTruthy),
R.map((input: RetryOptions) => {
const options: RetryableConfig = {
maxRetries: input.maxRetries ?? defaultOptions.maxRetries,
factor: input.factor ?? defaultOptions.maxRetries,
};
return R.pickBy(options, R.isDefined);
}),
R.mergeAll,
) as RetryableConfig;
}
protected async assertInput(input: unknown) {
const schema = await this.inputSchema();
if (schema) {
validateSchema(schema, {
context: {
tool: this.constructor.name,
hint: `To do post-validation override the '${this.validateInput.name}' method.`,
schema,
isFatal: true,
isRetryable: false,
},
});
}
this.validateInput(schema, input);
}
protected validateInput(
schema: AnyToolSchemaLike,
rawInput: unknown,
): asserts rawInput is ToolInput<this> {
const validator = createSchemaValidator(schema) as ValidateFunction<ToolInput<this>>;
const success = validator(rawInput);
if (!success) {
throw new ToolInputValidationError(
[
`The received tool input does not match the expected schema.`,
`Input Schema: "${JSON.stringify(toJsonSchema(schema))}"`,
`Validation Errors: ${JSON.stringify(validator.errors)}`,
].join("\n"),
// ts doesn't infer that when success is false `validator.errors` is defined
validator.errors!,
);
}
}
createSnapshot(): ToolSnapshot<TOutput, TOptions> {
return {
name: this.name,
description: this.description,
cache: this.cache,
options: shallowCopy(this.options),
emitter: this.emitter,
};
}
loadSnapshot(snapshot: ToolSnapshot<TOutput, TOptions>): void {
Object.assign(this, snapshot);
}
}
export type AnyTool = Tool<any, any, any>;
export class DynamicTool<
TOutput extends ToolOutput,
TInputSchema extends AnyToolSchemaLike,
TOptions extends BaseToolOptions = BaseToolOptions,
TRunOptions extends BaseToolRunOptions = BaseToolRunOptions,
TInput = FromSchemaLike<TInputSchema>,
> extends Tool<TOutput, TOptions, TRunOptions> {
static {
this.register();
}
declare name: string;
declare description: string;
private readonly _inputSchema: AnyToolSchemaLike;
private readonly handler;
inputSchema() {
return this._inputSchema;
}
constructor(fields: {
name: string;
description: string;
inputSchema: TInputSchema;
handler: (
input: TInput,
options: TRunOptions | undefined,
run: GetRunContext<DynamicTool<TOutput, TInputSchema, TOptions, TRunOptions, TInput>>,
) => Promise<TOutput>;
options?: TOptions;
}) {
validate(
fields,
z.object({
name: z
.string({ message: "Tool must have a name" })
.refine((val) => /^[a-zA-Z0-9\-_]+$/.test(val), {
message: "Tool name must only have -, _, letters or numbers",
}),
description: z
.string({ message: "Tool must have a description" })
.refine((val) => val && val !== "", { message: "Tool must have a description" }),
inputSchema: z.union([z.instanceof(ZodSchema), z.object({}).passthrough()], {
message: "Tool must have a schema",
}),
handler: z.function(),
options: z.object({}).passthrough().optional(),
}),
);
super(...([fields.options] as ToolConstructorParameters<TOptions>));
this.name = fields.name;
this.description = fields.description;
this._inputSchema = fields.inputSchema;
this.handler = fields.handler;
}
protected _run(
arg: TInput,
options: TRunOptions | undefined,
run: GetRunContext<DynamicTool<TOutput, TInputSchema, TOptions, TRunOptions, TInput>>,
): Promise<TOutput> {
return this.handler(arg, options, run);
}
createSnapshot() {
return { ...super.createSnapshot(), handler: this.handler, _inputSchema: this._inputSchema };
}
loadSnapshot({ handler, ...snapshot }: ReturnType<typeof this.createSnapshot>) {
super.loadSnapshot(snapshot);
Object.assign(this, { handler });
}
}