jorel
Version:
A unified wrapper for working with LLMs from multiple providers, including streams, images, documents & automatic tool use.
77 lines (76 loc) • 2.56 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.LlmTool = void 0;
const zod_1 = require("zod");
const shared_1 = require("../shared");
/**
* A tool that can be used in generations and task executions
*/
class LlmTool {
constructor(config) {
this.requiresConfirmation = config.requiresConfirmation ?? false;
this.name = config.name;
this.description = config.description;
this.executor = config.executor;
this.params = !config.params
? undefined
: config.params instanceof zod_1.ZodObject
? (0, shared_1.zodSchemaToJsonSchema)(config.params)
: this.validateParams(config.params);
}
/**
* Get the type of the tool
*/
get type() {
return this.executor === "transfer" || this.executor === "subTask"
? this.executor
: this.executor
? "function"
: "functionDefinition";
}
/**
* Return the tool as a llm function (e.g., for use inside tool-use messages)
*/
get asLLmFunction() {
return {
type: "function",
function: {
name: this.name,
description: this.description,
parameters: this.params,
},
};
}
/**
* Execute the tool
* @param args Deserialized arguments
* @param env
* @param env.context Contextual data (included in logs)
* @param env.secureContext Secure contextual data (excluded from logs)
*/
async execute(args, env = {}) {
if (!this.executor) {
throw new Error(`Executor not defined for tool: ${this.name}`);
}
if (this.executor === "transfer" || this.executor === "subTask") {
throw new Error(`Cannot execute tool "${this.name}". ${this.executor} tools cannot be executed directly.`);
}
return this.executor(args, env.context || {}, env.secureContext || {});
}
/**
* Internal helper to validate and normalize parameters
* @param params
*/
validateParams(params) {
const { type, properties, items, required, additionalProperties, ...rest } = params ?? {};
return {
type: type ? type : items ? "array" : properties ? "object" : "string",
required: required ?? [],
items,
additionalProperties: additionalProperties ?? false,
properties,
...rest,
};
}
}
exports.LlmTool = LlmTool;