UNPKG

contaigents

Version:

Modular AI Content Ecosystem with Audio Generation

120 lines (119 loc) 4.17 kB
import { BaseLLM } from "./BaseLLM.js"; export class AnthropicProvider extends BaseLLM { constructor() { super(AnthropicProvider.providerConfig); } async executePrompt(prompt, options = {}) { if (!this.isConfigured()) { throw new Error("Anthropic provider is not configured"); } const response = await fetch("https://api.anthropic.com/v1/messages", { method: "POST", headers: { "Content-Type": "application/json", "x-api-key": this.config.apiKey, "anthropic-version": "2023-06-01", }, body: JSON.stringify({ model: this.config.model, messages: [{ role: "user", content: prompt }], max_tokens: options.maxTokens, temperature: options.temperature ?? 0.7, }), }); if (!response.ok) { const error = await response.json(); throw new Error(`Anthropic API error: ${error.error?.message || "Unknown error"}`); } const data = await response.json(); return { content: data.content[0].text, raw: data, }; } async executeConversation(messages, options = {}) { if (!(await this.isConfigured())) { throw new Error("Anthropic provider is not configured"); } // Convert ConversationMessage to Anthropic format const anthropicMessages = messages .filter(msg => msg.role !== 'system') // Anthropic handles system messages differently .map(msg => { // Handle text-only messages if (!msg.images || msg.images.length === 0) { return { role: msg.role === 'assistant' ? 'assistant' : 'user', content: msg.content }; } // Handle messages with images (Claude 3 format) const content = [ { type: "text", text: msg.content } ]; // Add images for (const image of msg.images) { content.push({ type: "image", source: { type: "base64", media_type: image.mimeType, data: image.base64Data } }); } return { role: msg.role === 'assistant' ? 'assistant' : 'user', content }; }); // Extract system message if present const systemMessage = messages.find(msg => msg.role === 'system'); const response = await fetch("https://api.anthropic.com/v1/messages", { method: "POST", headers: { "Content-Type": "application/json", "x-api-key": this.config.apiKey, "anthropic-version": "2023-06-01", }, body: JSON.stringify({ model: this.config.model, messages: anthropicMessages, system: systemMessage?.content, // Anthropic uses separate system field max_tokens: options.maxTokens || 2000, temperature: options.temperature ?? 0.7, }), }); if (!response.ok) { const error = await response.json(); throw new Error(`Anthropic API error: ${error.error?.message || "Unknown error"}`); } const data = await response.json(); return { content: data.content[0].text, raw: data, }; } } AnthropicProvider.providerConfig = { name: "Anthropic", configFields: [ { name: "apiKey", required: true, }, { name: "model", required: true, options: [ "claude-3-opus", "claude-3-sonnet", "claude-3-haiku", "claude-2.1", ], default: "claude-3-opus", }, ], };