UNPKG

contextual-agent-sdk

Version:

SDK for building AI agents with seamless voice-text context switching

188 lines 7.38 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.AgentToolManager = void 0; const ToolRegistry_1 = require("../tools/ToolRegistry"); class AgentToolManager { toolRegistry; enabledTools = new Map(); toolCredentials = new Map(); agentId; organizationId; constructor(agentId, organizationId) { this.toolRegistry = new ToolRegistry_1.ToolRegistry(); this.agentId = agentId; this.organizationId = organizationId; } async initializeTools(enabledTools, credentials) { try { for (const tool of enabledTools) { if (tool.enabled) { const toolKey = `${tool.providerId}.${tool.toolId}`; this.enabledTools.set(toolKey, tool); } } for (const cred of credentials) { this.toolCredentials.set(cred.providerId, cred.credentials); } console.log(`[AgentToolManager] Initialized with ${this.enabledTools.size} enabled tools`); const toolList = Array.from(this.enabledTools.keys()); console.log('[AgentToolManager] Available tools:', toolList); } catch (error) { console.error('[AgentToolManager] Failed to initialize tools:', error); throw error; } } isToolEnabled(providerId, toolId) { const toolKey = `${providerId}.${toolId}`; return this.enabledTools.has(toolKey); } getEnabledTools() { return Array.from(this.enabledTools.values()); } async executeTool(request) { const { providerId, toolId, parameters, context } = request; const toolKey = `${providerId}.${toolId}`; try { if (!this.isToolEnabled(providerId, toolId)) { return { success: false, error: `Tool ${toolKey} is not enabled for this agent`, data: null }; } const provider = this.toolRegistry.getProvider(providerId); if (!provider) { return { success: false, error: `Tool provider ${providerId} not found`, data: null }; } const credentials = this.toolCredentials.get(providerId); if (!credentials) { return { success: false, error: `No credentials found for provider ${providerId}`, data: null }; } const executionContext = { agentId: this.agentId, organizationId: this.organizationId, sessionId: context?.sessionId, userId: context?.userId, metadata: { ...context, credentials } }; console.log(`[AgentToolManager] Executing tool ${toolKey} with params:`, parameters); const result = await provider.execute(toolId, parameters, executionContext); console.log(`[AgentToolManager] Tool ${toolKey} execution result:`, { success: result.success, hasData: !!result.data, error: result.error }); return result; } catch (error) { console.error(`[AgentToolManager] Tool execution failed for ${toolKey}:`, error); return { success: false, error: `Tool execution failed: ${error instanceof Error ? error.message : 'Unknown error'}`, data: null }; } } async detectAndExecuteTools(llmResponse, context) { const toolCalls = []; const toolResults = []; let enhancedResponse = llmResponse; try { const toolPattern = /\[TOOL:([^:]+)\.([^:]+):(\{[^}]+\})\]/g; let match; while ((match = toolPattern.exec(llmResponse)) !== null) { const [fullMatch, providerId, toolId, paramsJson] = match; try { const parameters = JSON.parse(paramsJson); const toolCall = { providerId, toolId, parameters }; toolCalls.push(toolCall); const result = await this.executeTool({ providerId, toolId, parameters, context }); toolResults.push(result); if (result.success && result.data) { const resultText = this.formatToolResult(toolCall, result); enhancedResponse = enhancedResponse.replace(fullMatch, resultText); } else { enhancedResponse = enhancedResponse.replace(fullMatch, `[Tool execution failed: ${result.error}]`); } } catch (parseError) { console.error('Failed to parse tool parameters:', parseError); enhancedResponse = enhancedResponse.replace(fullMatch, '[Invalid tool call format]'); } } return { originalResponse: llmResponse, toolCalls, toolResults, enhancedResponse }; } catch (error) { console.error('[AgentToolManager] Tool detection failed:', error); return { originalResponse: llmResponse, toolCalls: [], toolResults: [], enhancedResponse: llmResponse }; } } formatToolResult(toolCall, result) { if (!result.success || !result.data) { return `[${toolCall.providerId}.${toolCall.toolId} failed]`; } if (toolCall.providerId === 'twilio' && toolCall.toolId === 'send_sms') { const smsResult = result.data; return `[SMS sent to ${smsResult.to}: ${smsResult.status}]`; } if (toolCall.providerId === 'twilio' && toolCall.toolId === 'make_call') { const callResult = result.data; return `[Call to ${callResult.to}: ${callResult.status}]`; } return `[${toolCall.providerId}.${toolCall.toolId} executed successfully]`; } getToolCapabilities() { const enabledTools = Array.from(this.enabledTools.keys()); const toolProviders = Array.from(new Set(Array.from(this.enabledTools.values()).map(tool => tool.providerId))); return { enabledTools, toolProviders, totalTools: this.enabledTools.size }; } async cleanup() { try { await this.toolRegistry.cleanup(); this.enabledTools.clear(); this.toolCredentials.clear(); console.log('[AgentToolManager] Cleanup completed'); } catch (error) { console.error('[AgentToolManager] Cleanup failed:', error); } } } exports.AgentToolManager = AgentToolManager; //# sourceMappingURL=AgentToolManager.js.map