|
| 1 | +import { LLMMessage, LLMModel, callLLMChatCompletion } from "~/utils/llmUtils"; |
| 2 | +import { Config } from "~/utils/config"; |
| 3 | + |
| 4 | +export interface Agent { |
| 5 | + name: string; |
| 6 | + task: string; |
| 7 | + messages: LLMMessage[]; |
| 8 | + model: LLMModel; |
| 9 | +} |
| 10 | + |
| 11 | +let nextkey = 0; |
| 12 | +const agents: {[key: string]: Agent} = {}; |
| 13 | + |
| 14 | +export async function startAgent( |
| 15 | + name: string, |
| 16 | + task: string, |
| 17 | + prompt: string, |
| 18 | + model: LLMModel = Config.fast_llm_model |
| 19 | +) { |
| 20 | + const firstMessage = `You are ${name}. Respond with: "Acknowledged".`; |
| 21 | + const { key, agentReply } = await createAgent(name, task, firstMessage, model); |
| 22 | + |
| 23 | + const agentResponse = await messageAgent(key, prompt); |
| 24 | + |
| 25 | + return `Agent ${name} created with key ${key}. First response: ${agentResponse}`; |
| 26 | +} |
| 27 | + |
| 28 | +export async function createAgent( |
| 29 | + name: string, |
| 30 | + task: string, |
| 31 | + prompt: string, |
| 32 | + model: LLMModel |
| 33 | +): Promise<{ key: string; agentReply: string }> { |
| 34 | + const messages: LLMMessage[] = [{ role: "user", content: prompt }]; |
| 35 | + |
| 36 | + const agentReply = await callLLMChatCompletion(messages, model); |
| 37 | + |
| 38 | + messages.push({ role: "assistant", content: agentReply }); |
| 39 | + |
| 40 | + const agent: Agent = { |
| 41 | + name, |
| 42 | + task, |
| 43 | + messages, |
| 44 | + model, |
| 45 | + }; |
| 46 | + const key = `${nextkey}`; |
| 47 | + nextkey = nextkey + 1; |
| 48 | + |
| 49 | + agents[key] = agent; |
| 50 | + |
| 51 | + return { key, agentReply }; |
| 52 | +} |
| 53 | + |
| 54 | +export async function messageAgent( |
| 55 | + key: string, |
| 56 | + message: string |
| 57 | +): Promise<string> { |
| 58 | + if (!agents[key]) { |
| 59 | + return "Invalid key, agent doesn't exist"; |
| 60 | + } |
| 61 | + const { messages, model } = agents[key]; |
| 62 | + messages.push({ role: "user", content: message }); |
| 63 | + |
| 64 | + const agentReply = await callLLMChatCompletion(messages, model); |
| 65 | + |
| 66 | + messages.push({ role: "assistant", content: agentReply }); |
| 67 | + return agentReply; |
| 68 | +} |
| 69 | + |
| 70 | +export function listAgents(): [string, string][] { |
| 71 | + return Object.keys(agents).map((key: string) => [key, agents[key].task]); |
| 72 | +} |
| 73 | + |
| 74 | +export function deleteAgent(key: string): boolean { |
| 75 | + if (agents[key]) { |
| 76 | + delete agents[key]; |
| 77 | + return true; |
| 78 | + } |
| 79 | + |
| 80 | + return false; |
| 81 | +} |
0 commit comments