|
| 1 | +import { Anthropic } from '@anthropic-ai/sdk'; |
| 2 | +import EventEmitter from 'node:events'; |
| 3 | + |
| 4 | +export default class BaseAgent extends EventEmitter { |
| 5 | + constructor({ name, systemPrompt, metrics, model = 'claude-3-5-sonnet-20241022', maxTokens = 1024 }) { |
| 6 | + super(); |
| 7 | + this.name = name; |
| 8 | + this.systemPrompt = systemPrompt; |
| 9 | + this.metrics = metrics; |
| 10 | + this.model = model; |
| 11 | + this.maxTokens = maxTokens; |
| 12 | + this.apiKey = process.env.ANTHROPIC_API_KEY; |
| 13 | + this.client = this.apiKey ? new Anthropic({ apiKey: this.apiKey }) : null; |
| 14 | + this.online = Boolean(this.client); |
| 15 | + } |
| 16 | + |
| 17 | + async sendMessage({ prompt, context = [] }) { |
| 18 | + this.metrics?.increment(`${this.name}:requests`); |
| 19 | + |
| 20 | + if (!this.online) { |
| 21 | + const simulated = await this.simulateResponse({ prompt, context }); |
| 22 | + this.emit('message', { prompt, response: simulated, offline: true }); |
| 23 | + return { text: simulated, offline: true }; |
| 24 | + } |
| 25 | + |
| 26 | + try { |
| 27 | + const response = await this.client.messages.create({ |
| 28 | + model: this.model, |
| 29 | + max_tokens: this.maxTokens, |
| 30 | + system: this.systemPrompt, |
| 31 | + messages: [ |
| 32 | + ...context, |
| 33 | + { role: 'user', content: prompt }, |
| 34 | + ], |
| 35 | + }); |
| 36 | + |
| 37 | + const text = response.content |
| 38 | + ?.map((fragment) => fragment.text ?? '') |
| 39 | + .join('') |
| 40 | + .trim(); |
| 41 | + |
| 42 | + const payload = { text, raw: response, offline: false }; |
| 43 | + this.emit('message', { prompt, response: payload }); |
| 44 | + return payload; |
| 45 | + } catch (error) { |
| 46 | + this.metrics?.increment(`${this.name}:fallbacks`); |
| 47 | + const simulated = await this.simulateResponse({ prompt, context, error }); |
| 48 | + const payload = { text: simulated, offline: true, error }; |
| 49 | + this.emit('message', { prompt, response: payload, error }); |
| 50 | + return payload; |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + // eslint-disable-next-line class-methods-use-this |
| 55 | + async simulateResponse() { |
| 56 | + return 'Simulation not implemented.'; |
| 57 | + } |
| 58 | +} |
0 commit comments