|
| 1 | +import { AnthropicStream, StreamingTextResponse, anthropic } from 'ai'; |
| 2 | +import { ContentBlockParam } from '@anthropic-ai/sdk/resources/messages/messages.js'; |
| 3 | + |
| 4 | +import { getAnthropicApiKeyError } from '../../utils/errors.js'; |
| 5 | +import { Message, Tool, ToolContext, ToolUseContent } from '../types.js'; |
| 6 | +import { TokenUsage } from '../tokens.js'; |
| 7 | + |
| 8 | +import { LLMProvider, LLMProviderResponse } from './types.js'; |
| 9 | + |
| 10 | +function processResponse(content: any[]): { |
| 11 | + content: any[]; |
| 12 | + toolCalls: ToolUseContent[]; |
| 13 | +} { |
| 14 | + const processedContent: any[] = []; |
| 15 | + const toolCalls: ToolUseContent[] = []; |
| 16 | + |
| 17 | + for (const message of content) { |
| 18 | + if (message.type === 'text') { |
| 19 | + processedContent.push({ type: 'text', text: message.text }); |
| 20 | + } else if (message.type === 'tool_use') { |
| 21 | + const toolUse: ToolUseContent = { |
| 22 | + type: 'tool_use', |
| 23 | + name: message.name, |
| 24 | + id: message.id, |
| 25 | + input: message.input, |
| 26 | + }; |
| 27 | + processedContent.push(toolUse); |
| 28 | + toolCalls.push(toolUse); |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + return { content: processedContent, toolCalls }; |
| 33 | +} |
| 34 | + |
| 35 | +// Helper function to add cache control to content blocks |
| 36 | +function addCacheControlToContentBlocks( |
| 37 | + content: ContentBlockParam[], |
| 38 | +): ContentBlockParam[] { |
| 39 | + return content.map((c, i) => { |
| 40 | + if (i === content.length - 1) { |
| 41 | + if ( |
| 42 | + c.type === 'text' || |
| 43 | + c.type === 'document' || |
| 44 | + c.type === 'image' || |
| 45 | + c.type === 'tool_use' || |
| 46 | + c.type === 'tool_result' || |
| 47 | + c.type === 'thinking' || |
| 48 | + c.type === 'redacted_thinking' |
| 49 | + ) { |
| 50 | + return { ...c, cache_control: { type: 'ephemeral' } }; |
| 51 | + } |
| 52 | + } |
| 53 | + return c; |
| 54 | + }); |
| 55 | +} |
| 56 | + |
| 57 | +// Helper function to add cache control to messages |
| 58 | +function addCacheControlToMessages(messages: any[]): any[] { |
| 59 | + return messages.map((m, i) => { |
| 60 | + if (typeof m.content === 'string') { |
| 61 | + return { |
| 62 | + ...m, |
| 63 | + content: [ |
| 64 | + { |
| 65 | + type: 'text', |
| 66 | + text: m.content, |
| 67 | + cache_control: { type: 'ephemeral' }, |
| 68 | + }, |
| 69 | + ] as ContentBlockParam[], |
| 70 | + }; |
| 71 | + } |
| 72 | + return { |
| 73 | + ...m, |
| 74 | + content: |
| 75 | + i >= messages.length - 2 |
| 76 | + ? addCacheControlToContentBlocks(m.content) |
| 77 | + : m.content, |
| 78 | + }; |
| 79 | + }); |
| 80 | +} |
| 81 | + |
| 82 | +// Helper function to add cache control to tools |
| 83 | +function addCacheControlToTools<T>(tools: T[]): T[] { |
| 84 | + return tools.map((t, i) => ({ |
| 85 | + ...t, |
| 86 | + ...(i === tools.length - 1 ? { cache_control: { type: 'ephemeral' } } : {}), |
| 87 | + })); |
| 88 | +} |
| 89 | + |
| 90 | +export class AnthropicProvider implements LLMProvider { |
| 91 | + private model: string; |
| 92 | + private maxTokens: number; |
| 93 | + private temperature: number; |
| 94 | + |
| 95 | + constructor({ |
| 96 | + model = 'claude-3-7-sonnet-latest', |
| 97 | + maxTokens = 4096, |
| 98 | + temperature = 0.7, |
| 99 | + } = {}) { |
| 100 | + this.model = model; |
| 101 | + this.maxTokens = maxTokens; |
| 102 | + this.temperature = temperature; |
| 103 | + } |
| 104 | + |
| 105 | + async sendRequest({ |
| 106 | + systemPrompt, |
| 107 | + messages, |
| 108 | + tools, |
| 109 | + context, |
| 110 | + }: { |
| 111 | + systemPrompt: string; |
| 112 | + messages: Message[]; |
| 113 | + tools: Tool[]; |
| 114 | + context: ToolContext; |
| 115 | + }): Promise<LLMProviderResponse> { |
| 116 | + const { logger, tokenTracker } = context; |
| 117 | + |
| 118 | + const apiKey = process.env.ANTHROPIC_API_KEY; |
| 119 | + if (!apiKey) throw new Error(getAnthropicApiKeyError()); |
| 120 | + |
| 121 | + // Using Vercel AI SDK to create Anthropic client |
| 122 | + const client = anthropic({ |
| 123 | + apiKey, |
| 124 | + }); |
| 125 | + |
| 126 | + logger.verbose( |
| 127 | + `Requesting completion with ${messages.length} messages with ${JSON.stringify(messages).length} bytes`, |
| 128 | + ); |
| 129 | + |
| 130 | + // Create request parameters |
| 131 | + const response = await client.messages.create({ |
| 132 | + model: this.model, |
| 133 | + max_tokens: this.maxTokens, |
| 134 | + temperature: this.temperature, |
| 135 | + messages: addCacheControlToMessages(messages), |
| 136 | + system: [ |
| 137 | + { |
| 138 | + type: 'text', |
| 139 | + text: systemPrompt, |
| 140 | + cache_control: { type: 'ephemeral' }, |
| 141 | + }, |
| 142 | + ], |
| 143 | + tools: addCacheControlToTools( |
| 144 | + tools.map((t) => ({ |
| 145 | + name: t.name, |
| 146 | + description: t.description, |
| 147 | + input_schema: t.parameters, |
| 148 | + })), |
| 149 | + ), |
| 150 | + tool_choice: { type: 'auto' }, |
| 151 | + }); |
| 152 | + |
| 153 | + if (!response.content.length) { |
| 154 | + return { content: [], toolCalls: [] }; |
| 155 | + } |
| 156 | + |
| 157 | + // Track token usage |
| 158 | + const tokenUsagePerMessage = TokenUsage.fromMessage(response); |
| 159 | + tokenTracker.tokenUsage.add(tokenUsagePerMessage); |
| 160 | + |
| 161 | + return processResponse(response.content); |
| 162 | + } |
| 163 | +} |
0 commit comments