UNPKG

agente-toolkit

Version:

A barebones TypeScript library for building AI agents with intelligent tool execution and self-correction capabilities

149 lines (145 loc) 6.27 kB
'use strict'; var OpenAI = require('openai'); var base = require('../base/base.js'); var schemaUtils = require('../utils/schemaUtils.js'); /** * OpenAI adapter with native tool support * Uses OpenAI's built-in function calling when available */ class OpenAIAdapter extends base.BaseAdapter { constructor(apiKey, model = 'gpt-4o') { super(); this.name = 'openai'; this.supportsNativeTools = true; this.client = new OpenAI({ apiKey: apiKey || process.env.OPENAI_API_KEY, }); this.model = model; } /** * Text completion for general prompts. * Supports structured JSON responses via OpenAI's response_format. * * options.json: boolean -> Request a JSON object (model validates JSON) * options.schema: object -> Provide a JSON schema; will request JSON schema mode if supported */ async complete(prompt, options) { var _a, _b, _c; const messages = [ { role: 'user', content: prompt }, ]; const requestParams = { model: this.model, messages, max_tokens: 4096, }; // cast until types updated for experimental schema mode // Structured output handling if (options === null || options === void 0 ? void 0 : options.schema) { // If a schema is provided, prefer json_schema response_format (GPT-4o family supports it) requestParams.response_format = { type: 'json_schema', json_schema: { name: 'structured_response', // Provide the schema as-is; callers must supply a valid JSON schema object schema: options.schema, }, }; } else if (options === null || options === void 0 ? void 0 : options.json) { requestParams.response_format = { type: 'json_object' }; } const completion = (await this.client.chat.completions.create(requestParams)); // ensure non-stream type return ((_c = (_b = (_a = completion.choices) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.message) === null || _c === void 0 ? void 0 : _c.content) || ''; } /** * Execute tools with a prompt - uses native OpenAI function calling */ async executeWithTools(prompt, tools) { var _a, _b; try { // Convert our Tool format to OpenAI's format const openaiTools = tools.map(tool => ({ type: 'function', function: { name: tool.name, description: tool.description, parameters: schemaUtils.SchemaUtils.convertToJsonSchema(tool.paramsSchema), }, })); const toolCalls = []; // Make initial request with tools const messages = [ { role: 'user', content: prompt }, ]; let response = await this.client.chat.completions.create({ model: this.model, messages, tools: openaiTools, tool_choice: 'auto', max_tokens: 4096, }); let finalContent = ''; let currentChoice = response.choices[0]; // Continue conversation while OpenAI wants to make tool calls while (((_a = currentChoice === null || currentChoice === void 0 ? void 0 : currentChoice.message) === null || _a === void 0 ? void 0 : _a.tool_calls) && currentChoice.message.tool_calls.length > 0) { // Add assistant message with tool calls messages.push(currentChoice.message); // Process each tool call for (const toolCall of currentChoice.message.tool_calls) { if (toolCall.type === 'function') { // Find and execute the tool const tool = tools.find(t => t.name === toolCall.function.name); if (!tool) { throw new Error(`Tool ${toolCall.function.name} not found`); } let toolArgs; try { toolArgs = JSON.parse(toolCall.function.arguments); } catch (error) { throw new Error(`Invalid JSON in tool arguments: ${toolCall.function.arguments}`); } const result = await tool.action(toolArgs); toolCalls.push({ name: toolCall.function.name, arguments: toolArgs, result, }); // Add tool result to conversation messages.push({ role: 'tool', content: JSON.stringify(result), tool_call_id: toolCall.id, }); } } // Get follow-up response response = await this.client.chat.completions.create({ model: this.model, messages, tools: openaiTools, tool_choice: 'auto', max_tokens: 4096, }); currentChoice = response.choices[0]; } // Extract final text content (no more tool calls) finalContent = ((_b = currentChoice === null || currentChoice === void 0 ? void 0 : currentChoice.message) === null || _b === void 0 ? void 0 : _b.content) || ''; return { content: finalContent, toolCalls, success: true, }; } catch (error) { return { content: '', toolCalls: [], success: false, errors: [error instanceof Error ? error.message : String(error)], }; } } } exports.OpenAIAdapter = OpenAIAdapter; //# sourceMappingURL=openaiAdapter.js.map