|
| 1 | +import { ChatCompletionMessageToolCall } from "openai/resources/index.mjs"; |
| 2 | +import { LLM } from "../llm"; |
| 3 | +import { Tool } from "../tool"; |
| 4 | +import { AgentConfig, AgentResponse, LLMResult, Message, Provider, ToolConfig } from "../types"; |
| 5 | + |
| 6 | +export class Agent { |
| 7 | + public name: string; |
| 8 | + public prompt: string; |
| 9 | + public messages: Message[]; |
| 10 | + public maxIterations: number; |
| 11 | + private tools: Tool[]; |
| 12 | + private llm: any; |
| 13 | + private logger: any; |
| 14 | + private provider: Provider; |
| 15 | + private secrets: Record<string, string>; |
| 16 | + |
| 17 | + constructor(name: string, config: AgentConfig) { |
| 18 | + this.name = name; |
| 19 | + this.prompt = this.constructPrompt(config); |
| 20 | + this.provider = config.provider || 'openai'; |
| 21 | + this.tools = this.prepareTools(config.tools || []); |
| 22 | + this.messages = config.messages || []; |
| 23 | + this.maxIterations = config.maxIterations || 10; |
| 24 | + this.secrets = config.secrets; |
| 25 | + this.logger = config.logger || console; |
| 26 | + this.logger.info(this.prompt); |
| 27 | + |
| 28 | + this.llm = new LLM({ provider: this.provider, apiKey: config.secrets.OPENAI_API_KEY, logger: this.logger }); |
| 29 | + } |
| 30 | + |
| 31 | + public async execute(input: string, context?: string): Promise<string> { |
| 32 | + this.setupMessages(input, context); |
| 33 | + let iterationCount = 0; |
| 34 | + let result: LLMResult = {}; |
| 35 | + |
| 36 | + while (true) { |
| 37 | + if (iterationCount > this.maxIterations) break; |
| 38 | + |
| 39 | + if (iterationCount === this.maxIterations) { |
| 40 | + this.pushToMessages({ role: "system", content: "Provide a final answer" }); |
| 41 | + } |
| 42 | + |
| 43 | + result = await this.llm.call(this.messages, this.functions()); |
| 44 | + |
| 45 | + await this.handleLlmResult(result); |
| 46 | + |
| 47 | + if (result.content?.stop) break; |
| 48 | + iterationCount++; |
| 49 | + } |
| 50 | + |
| 51 | + return result.content?.output || ''; |
| 52 | + } |
| 53 | + |
| 54 | + public registerTool(tool: Tool): void { |
| 55 | + this.tools.push(tool); |
| 56 | + } |
| 57 | + |
| 58 | + private setupMessages(input: string, context?: string): void { |
| 59 | + if (!this.messages.length) { |
| 60 | + this.pushToMessages({ role: "system", content: this.prompt }); |
| 61 | + |
| 62 | + if (context) { |
| 63 | + this.pushToMessages({ role: "assistant", content: context }); |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + this.pushToMessages({ role: "user", content: input }); |
| 68 | + } |
| 69 | + |
| 70 | + private async handleLlmResult(result: LLMResult): Promise<void> { |
| 71 | + if (result.toolCalls) { |
| 72 | + const toolResult = await this.executeTool(result.toolCalls); |
| 73 | + this.pushToMessages({ role: "assistant", content: toolResult.output || '' }); |
| 74 | + } else { |
| 75 | + this.pushToMessages({ |
| 76 | + role: "assistant", |
| 77 | + content: result.content?.thoughtProcess || result.content?.output || '' |
| 78 | + }); |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + private constructPrompt(config: AgentConfig): string { |
| 83 | + if (config.prompt) return config.prompt; |
| 84 | + |
| 85 | + return ` |
| 86 | + Persona: ${config.persona} |
| 87 | + Objective: ${config.goal} |
| 88 | + Guidelines: |
| 89 | + - Work diligently until the stated objective is achieved. |
| 90 | + - Utilize only the provided tools for solving the task. Do not make up names of the functions |
| 91 | + - Set 'stop: true' when the objective is complete. |
| 92 | + - If you have enough information to provide the details to the user, prepare a final result collecting all the information you have. |
| 93 | + Output Structure: |
| 94 | + If you find a function, that can be used, directly call the function. |
| 95 | + When providing the final answer: |
| 96 | + { |
| 97 | + 'thoughtProcess': 'Describe the reasoning and steps that will lead to the final result.', |
| 98 | + 'output': 'The complete answer in text form.', |
| 99 | + 'stop': true |
| 100 | + } |
| 101 | + `; |
| 102 | + } |
| 103 | + |
| 104 | + private prepareTools(tools: ToolConfig[]): Tool[] { |
| 105 | + return tools.map( |
| 106 | + (tool) => new Tool(tool.name, tool.description, tool.config, tool.implementation) |
| 107 | + ); |
| 108 | + } |
| 109 | + |
| 110 | + private functions(): Array<{ |
| 111 | + name: string; |
| 112 | + description: string; |
| 113 | + parameters: { |
| 114 | + type: string; |
| 115 | + properties: Record<string, { type: string; description: string }>; |
| 116 | + required: string[]; |
| 117 | + }; |
| 118 | + }> { |
| 119 | + return this.tools.map(tool => { |
| 120 | + const properties: Record<string, { type: string; description: string }> = {}; |
| 121 | + |
| 122 | + Object.entries(tool.config.properties).forEach(([propertyName, propertyDetails]) => { |
| 123 | + properties[propertyName] = { |
| 124 | + type: propertyDetails.type, |
| 125 | + description: propertyDetails.description |
| 126 | + }; |
| 127 | + }); |
| 128 | + |
| 129 | + const required = Object.entries(tool.config.properties) |
| 130 | + .filter(([_, details]) => details.required) |
| 131 | + .map(([name]) => name); |
| 132 | + |
| 133 | + return { |
| 134 | + name: tool.name, |
| 135 | + description: tool.description, |
| 136 | + parameters: { |
| 137 | + type: "object", |
| 138 | + properties, |
| 139 | + required |
| 140 | + } |
| 141 | + }; |
| 142 | + }); |
| 143 | + } |
| 144 | + |
| 145 | + private pushToMessages(message: Message): void { |
| 146 | + this.logger.info(`Message: ${JSON.stringify(message)}`); |
| 147 | + this.messages.push(message); |
| 148 | + } |
| 149 | + |
| 150 | + private async executeTool(toolCalls: ChatCompletionMessageToolCall[]): Promise<AgentResponse> { |
| 151 | + const toolCall = toolCalls[0]; |
| 152 | + |
| 153 | + const tool = this.tools.find(t => t.name === toolCall.function.name); |
| 154 | + |
| 155 | + if (!tool) { |
| 156 | + return { output: "Invalid tool_name, please try again", stop: false }; |
| 157 | + } |
| 158 | + |
| 159 | + this.logger.info( |
| 160 | + `tool_call: ${toolCall.function.name}, ${toolCall.function.arguments}`, |
| 161 | + ); |
| 162 | + |
| 163 | + const functionArgs = JSON.parse(toolCall.function.arguments); |
| 164 | + |
| 165 | + |
| 166 | + const toolResult = await tool.execute( |
| 167 | + Object.fromEntries( |
| 168 | + Object.entries(functionArgs).map(([k, v]) => [k, v]) |
| 169 | + ), |
| 170 | + this.secrets |
| 171 | + ); |
| 172 | + |
| 173 | + return { |
| 174 | + output: toolResult || '', |
| 175 | + stop: false |
| 176 | + }; |
| 177 | + } |
| 178 | +} |
0 commit comments