@nomyx/assistant
Version:
A powerful assistant library and cli for your AI projects. works with Vertex AI (Claude and Gemini)
102 lines (101 loc) • 3.55 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadToolsFromFile = loadToolsFromFile;
exports.loadToolFromJson = loadToolFromJson;
const fs_1 = require("fs");
const util_1 = require("util");
const child_process_1 = require("child_process");
const execPromise = (0, util_1.promisify)(child_process_1.exec);
async function loadToolsFromFile(filePath) {
try {
const fileContent = await fs_1.promises.readFile(filePath, 'utf-8');
const toolsData = JSON.parse(fileContent);
return Object.entries(toolsData).map(([name, data]) => loadToolFromJson(name, data));
}
catch (error) {
console.error(`Error loading tools from ${filePath}:`, error);
throw new Error(`Failed to load tools from ${filePath}: ${error instanceof Error ? error.message : String(error)}`);
}
}
function loadToolFromJson(name, toolData) {
if (!isValidToolData(toolData)) {
throw new Error(`Invalid tool data for ${name}`);
}
const tool = {
name,
description: toolData.description,
execute: createExecuteFunction(toolData.code),
getSchema: () => ({
name,
description: toolData.description,
parameters: {
type: 'object',
properties: {
...toolData.input_schema
}
}
}),
validate: createValidateFunction(toolData.input_schema)
};
return tool;
}
function isValidToolData(toolData) {
return (toolData &&
typeof toolData.description === 'string' &&
typeof toolData.code === 'string' &&
isValidSchema(toolData.input_schema) &&
isValidSchema(toolData.output_schema));
}
function isValidSchema(schema) {
return (schema &&
typeof schema === 'object');
}
function createExecuteFunction(code) {
return async (params, context) => {
try {
const func = new Function('params', 'context', 'execPromise', 'require', `
return (async () => {
${code}
})();
`);
return await func(params, context, execPromise, require);
}
catch (error) {
console.error('Error executing tool:', error);
throw new Error(`Tool execution failed: ${error instanceof Error ? error.message : String(error)}`);
}
};
}
function createValidateFunction(inputSchema) {
return (args) => {
for (const [key, value] of Object.entries(args)) {
const paramSchema = inputSchema[key];
if (!paramSchema) {
console.error(`Unknown parameter: ${key}`);
return false;
}
if (!validateType(value, paramSchema)) {
console.error(`Invalid type for parameter ${key}. Expected ${paramSchema}, got ${typeof value}`);
return false;
}
}
return true;
};
}
function validateType(value, expectedType) {
switch (expectedType) {
case 'string':
return typeof value === 'string';
case 'number':
return typeof value === 'number' && !isNaN(value);
case 'boolean':
return typeof value === 'boolean';
case 'array':
return Array.isArray(value);
case 'object':
return typeof value === 'object' && value !== null && !Array.isArray(value);
default:
console.warn(`Unknown type for validation: ${expectedType}`);
return true;
}
}