UNPKG

ai-switcher

Version:

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

66 lines (59 loc) 2.35 kB
// src/clients/anthropic.ts import { Anthropic } from '@anthropic-ai/sdk'; import { Message, CompletionOptions, AIError } from '../types'; import { BaseAIClient } from './base'; export class AnthropicClient extends BaseAIClient { private client: Anthropic; protected apiKey: string; constructor(apiKey: string) { super(); this.apiKey = apiKey; this.client = new Anthropic({ apiKey }); } async createCompletion(messages: Message[], options: CompletionOptions = {}): Promise<string> { 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 as 'user' | 'assistant', content: msg.content, })), }); if ('error' in response) { throw new AIError(`Anthropic error: ${(response.error as any).message}`, 'anthropic'); } // Handle different types of content blocks const block = response.content[0]; if ('text' in block) { return block.text; } throw new AIError('Unsupported response content type', 'anthropic'); } catch (error: any) { // Map Anthropic errors to standardized errors if (error?.status === 401) { throw new AIError('Invalid API key', 'anthropic', 401, error); } if (error?.status === 429) { throw new AIError('Rate limit exceeded', 'anthropic', 429, error); } if (error?.status === 400) { throw new AIError(error.message || 'Bad request', 'anthropic', 400, error); } if (error?.status >= 500) { throw new AIError('Server error', 'anthropic', error.status, error); } throw new AIError(error.message || 'Unknown error', 'anthropic', undefined, error); } } async createEmbedding(text: string): Promise<number[]> { throw new AIError('Embeddings not supported by Anthropic', 'anthropic'); } }