UNPKG

@llamaindex/core

Version:
82 lines (78 loc) 3.05 kB
Object.defineProperty(exports, '__esModule', { value: true }); var zod = require('zod'); var zodToJsonSchema = require('zod-to-json-schema'); class FunctionTool { #fn; #additionalArg; #metadata; #zodType; constructor(fn, metadata, zodType, additionalArg){ this.#zodType = null; this.bind = (additionalArg)=>{ return new FunctionTool(this.#fn, this.#metadata, this.#zodType ?? undefined, additionalArg); }; this.call = (input)=>{ if (this.#metadata.requireContext) { const inputWithContext = input; if (!inputWithContext.context) { throw new Error("Tool call requires context, but context parameter is missing"); } } if (this.#zodType) { const result = this.#zodType.safeParse(input); if (result.success) { if (this.#metadata.requireContext) { const { context } = input; return this.#fn.call(null, { context, ...result.data }, this.#additionalArg); } else { return this.#fn.call(null, result.data, this.#additionalArg); } } else { console.warn(result.error.errors); } } return this.#fn.call(null, input, this.#additionalArg); }; this.#fn = fn; this.#metadata = metadata; if (zodType) { this.#zodType = zodType; } this.#additionalArg = additionalArg; } // eslint-disable-next-line @typescript-eslint/no-explicit-any static from(fnOrConfig, schema) { // Handle the case where an object with execute function is passed if (typeof schema === "undefined" && typeof fnOrConfig === "object" && fnOrConfig.execute) { const { execute, parameters, ...restConfig } = fnOrConfig; if (parameters instanceof zod.z.ZodSchema) { const jsonSchema = zodToJsonSchema.zodToJsonSchema(parameters); return new FunctionTool(execute, { ...restConfig, parameters: jsonSchema }, parameters); } return new FunctionTool(execute, fnOrConfig); } // Handle the original cases if (schema && schema.parameters instanceof zod.z.ZodSchema) { const jsonSchema = zodToJsonSchema.zodToJsonSchema(schema.parameters); return new FunctionTool(fnOrConfig, { ...schema, parameters: jsonSchema }, schema.parameters); } return new FunctionTool(fnOrConfig, schema); } get metadata() { return this.#metadata; } } /** * A simpler alias for creating a FunctionTool. */ const tool = FunctionTool.from; exports.FunctionTool = FunctionTool; exports.tool = tool;