UNPKG

ai-switcher

Version:

A package which helps you switch between AI APIs using configurations, so that code changes are not required.

63 lines (62 loc) 2.67 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.AnthropicClient = void 0; // src/clients/anthropic.ts const sdk_1 = require("@anthropic-ai/sdk"); const types_1 = require("../types"); const base_1 = require("./base"); class AnthropicClient extends base_1.BaseAIClient { constructor(apiKey) { super(); this.apiKey = apiKey; this.client = new sdk_1.Anthropic({ apiKey }); } async createCompletion(messages, options = {}) { try { // Extract system message if present const systemMessage = messages.find(msg => msg.role === 'system'); const nonSystemMessages = messages.filter(msg => msg.role !== 'system'); const response = await this.client.messages.create({ model: options.model || 'claude-3-haiku-20240307', max_tokens: options.maxTokens || 4096, temperature: options.temperature, top_p: options.topP, stop_sequences: options.stop, system: systemMessage?.content, messages: nonSystemMessages.map(msg => ({ role: msg.role, content: msg.content, })), }); if ('error' in response) { throw new types_1.AIError(`Anthropic error: ${response.error.message}`, 'anthropic'); } // Handle different types of content blocks const block = response.content[0]; if ('text' in block) { return block.text; } throw new types_1.AIError('Unsupported response content type', 'anthropic'); } catch (error) { // Map Anthropic errors to standardized errors if (error?.status === 401) { throw new types_1.AIError('Invalid API key', 'anthropic', 401, error); } if (error?.status === 429) { throw new types_1.AIError('Rate limit exceeded', 'anthropic', 429, error); } if (error?.status === 400) { throw new types_1.AIError(error.message || 'Bad request', 'anthropic', 400, error); } if (error?.status >= 500) { throw new types_1.AIError('Server error', 'anthropic', error.status, error); } throw new types_1.AIError(error.message || 'Unknown error', 'anthropic', undefined, error); } } async createEmbedding(text) { throw new types_1.AIError('Embeddings not supported by Anthropic', 'anthropic'); } } exports.AnthropicClient = AnthropicClient;