|
| 1 | +import { generateText, type CoreMessage } from "ai"; |
| 2 | +import type { ToolDefinition } from "../tools/types.js"; |
| 3 | +import type { Dispatch, SetStateAction } from "react"; |
| 4 | + |
| 5 | +import { providerEnvVar } from "./constants.js"; |
| 6 | +import type { Message, Provider } from "./types.js"; |
| 7 | +import { ProviderFactory } from "./providers.js"; |
| 8 | + |
| 9 | +// Enum-like MODEL_TYPES for factory selection |
| 10 | +export const MODEL_TYPES = { |
| 11 | + OPENAI: "openai", |
| 12 | + GOOGLE: "google", |
| 13 | + ANTHROPIC: "anthropic", |
| 14 | + GROQ: "groq", |
| 15 | +} as const; |
| 16 | + |
| 17 | +export class AIAgent { |
| 18 | + private provider: Provider; |
| 19 | + private model: string; |
| 20 | + private conversation: CoreMessage[] = []; |
| 21 | + private apiKey: string | undefined; |
| 22 | + |
| 23 | + constructor( |
| 24 | + provider: Provider, |
| 25 | + model: string, |
| 26 | + private tools: ToolDefinition[], |
| 27 | + private setIsProcessing: Dispatch<SetStateAction<boolean>>, |
| 28 | + private setMessages: Dispatch<SetStateAction<Message[]>>, |
| 29 | + ) { |
| 30 | + this.provider = provider; |
| 31 | + this.model = model; |
| 32 | + |
| 33 | + const envVarName = providerEnvVar[this.provider as string]; |
| 34 | + this.apiKey = envVarName ? process.env[envVarName] : undefined; |
| 35 | + } |
| 36 | + |
| 37 | + async processMessage(userInput: string): Promise<void> { |
| 38 | + this.setIsProcessing(true); |
| 39 | + |
| 40 | + // Track conversation for context |
| 41 | + this.conversation.push({ role: "user", content: userInput }); |
| 42 | + |
| 43 | + try { |
| 44 | + const model = this.createModel(); |
| 45 | + if (!model) { |
| 46 | + throw new Error( |
| 47 | + `Missing API key for provider: ${this.provider}. Set ${providerEnvVar[this.provider]}`, |
| 48 | + ); |
| 49 | + } |
| 50 | + |
| 51 | + const { text } = await generateText({ |
| 52 | + model, |
| 53 | + messages: this.conversation, |
| 54 | + }); |
| 55 | + |
| 56 | + // Append assistant message to conversation and UI |
| 57 | + this.conversation.push({ role: "assistant", content: text }); |
| 58 | + this.setMessages((prev) => [ |
| 59 | + ...prev, |
| 60 | + { role: "assistant", content: text, timestamp: new Date() }, |
| 61 | + ]); |
| 62 | + } catch (error) { |
| 63 | + const msg = error instanceof Error ? error.message : String(error); |
| 64 | + this.setMessages((prev) => [ |
| 65 | + ...prev, |
| 66 | + { role: "system", content: `❌ Error: ${msg}`, timestamp: new Date() }, |
| 67 | + ]); |
| 68 | + } finally { |
| 69 | + this.setIsProcessing(false); |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + private createModel() { |
| 74 | + return ProviderFactory.create(this.provider, this.model, this.apiKey); |
| 75 | + } |
| 76 | +} |
0 commit comments