@llamaindex/core
Version:
LlamaIndex Core Module
79 lines (76 loc) • 2.92 kB
JavaScript
import { z } from 'zod';
import { zodToJsonSchema } from '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 z.ZodSchema) {
const jsonSchema = zodToJsonSchema(parameters);
return new FunctionTool(execute, {
...restConfig,
parameters: jsonSchema
}, parameters);
}
return new FunctionTool(execute, fnOrConfig);
}
// Handle the original cases
if (schema && schema.parameters instanceof z.ZodSchema) {
const jsonSchema = 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;
export { FunctionTool, tool };