| 1 | import { streamSse } from "@continuedev/fetch"; |
| 2 | import { |
| 3 | ChatMessage, |
| 4 | CompletionOptions, |
| 5 | LLMOptions, |
| 6 | Usage, |
| 7 | } from "../../index.js"; |
| 8 | import { safeParseToolCallArgs } from "../../tools/parseArgs.js"; |
| 9 | import { renderChatMessage, stripImages } from "../../util/messageContent.js"; |
| 10 | import { BaseLLM } from "../index.js"; |
| 11 | |
| 12 | const errorMessages = { |
| 13 | invalid_request_error: |
| 14 | "There was an issue with the format or content of your request.", |
| 15 | authentication_error: "There's an issue with your API key.", |
| 16 | permission_error: |
| 17 | "Your API key does not have permission to use the specified resource.", |
| 18 | not_found_error: "The requested resource was not found.", |
| 19 | request_too_large: |
| 20 | "Request exceeds the maximum allowed number of bytes (32 MB limit).", |
| 21 | rate_limit_error: "Your account has hit a rate limit.", |
| 22 | api_error: |
| 23 | "An unexpected error has occurred internal to Anthropic's systems.", |
| 24 | overloaded_error: |
| 25 | "Anthropic's API is temporarily overloaded. Please check their status page: https://status.anthropic.com/#past-incidents", |
| 26 | }; |
| 27 | |
| 28 | class Anthropic extends BaseLLM { |
| 29 | static providerName = "anthropic"; |
| 30 | static defaultOptions: Partial<LLMOptions> = { |
| 31 | model: "claude-3-5-sonnet-latest", |
| 32 | completionOptions: { |
| 33 | model: "claude-3-5-sonnet-latest", |
| 34 | maxTokens: 8192, |
| 35 | }, |
| 36 | apiBase: "https://api.anthropic.com/v1/", |
| 37 | }; |
| 38 | |
| 39 | public convertArgs(options: CompletionOptions) { |
| 40 | // should be public for use within VertexAI |
| 41 | const finalOptions = { |
| 42 | top_k: options.topK, |
| 43 | top_p: options.topP, |
| 44 | temperature: options.temperature, |
| 45 | max_tokens: options.maxTokens ?? 2048, |
| 46 | model: options.model === "claude-2" ? "claude-2.1" : options.model, |
| 47 | stop_sequences: options.stop?.filter((x) => x.trim() !== ""), |
| 48 | stream: options.stream ?? true, |
| 49 | tools: options.tools?.map((tool) => ({ |
| 50 | name: tool.function.name, |
| 51 | description: tool.function.description, |
| 52 | input_schema: tool.function.parameters, |
| 53 | })), |
| 54 | thinking: options.reasoning |
| 55 | ? { |
| 56 | type: "enabled", |
| 57 | budget_tokens: options.reasoningBudgetTokens, |
| 58 | } |
| 59 | : undefined, |
| 60 | tool_choice: options.toolChoice |
| 61 | ? { |
| 62 | type: "tool", |
| 63 | name: options.toolChoice.function.name, |
| 64 | } |
| 65 | : undefined, |
| 66 | }; |
| 67 | |
| 68 | return finalOptions; |
| 69 | } |
| 70 | |
| 71 | private convertMessage(message: ChatMessage, addCaching: boolean): any { |
| 72 | if (message.role === "tool") { |
| 73 | return { |
| 74 | role: "user", |
| 75 | content: [ |
| 76 | { |
| 77 | type: "tool_result", |
| 78 | tool_use_id: message.toolCallId, |
| 79 | content: renderChatMessage(message) || undefined, |
| 80 | }, |
| 81 | ], |
| 82 | }; |
| 83 | } else if (message.role === "assistant" && message.toolCalls) { |
| 84 | return { |
| 85 | role: "assistant", |
| 86 | content: message.toolCalls.map((toolCall) => ({ |
| 87 | type: "tool_use", |
| 88 | id: toolCall.id, |
| 89 | name: toolCall.function?.name, |
| 90 | input: safeParseToolCallArgs(toolCall), |
| 91 | })), |
| 92 | }; |
| 93 | } else if (message.role === "thinking" && !message.redactedThinking) { |
| 94 | return { |
| 95 | role: "assistant", |
| 96 | content: [ |
| 97 | { |
| 98 | type: "thinking", |
| 99 | thinking: message.content, |
| 100 | signature: message.signature, |
| 101 | }, |
| 102 | ], |
| 103 | }; |
| 104 | } else if (message.role === "thinking" && message.redactedThinking) { |
| 105 | return { |
| 106 | role: "assistant", |
| 107 | content: [ |
| 108 | { |
| 109 | type: "redacted_thinking", |
| 110 | data: message.redactedThinking, |
| 111 | }, |
| 112 | ], |
| 113 | }; |
| 114 | } |
| 115 | |
| 116 | if (typeof message.content === "string") { |
| 117 | var chatMessage = { |
| 118 | role: message.role, |
| 119 | content: [ |
| 120 | { |
| 121 | type: "text", |
| 122 | text: message.content, |
| 123 | ...(addCaching ? { cache_control: { type: "ephemeral" } } : {}), |
| 124 | }, |
| 125 | ], |
| 126 | }; |
| 127 | return chatMessage; |
| 128 | } |
| 129 | |
| 130 | return { |
| 131 | role: message.role, |
| 132 | content: message.content.map((part, contentIdx) => { |
| 133 | if (part.type === "text") { |
| 134 | const newpart = { |
| 135 | ...part, |
| 136 | // If multiple text parts, only add cache_control to the last one |
| 137 | ...(addCaching && contentIdx === message.content.length - 1 |
| 138 | ? { cache_control: { type: "ephemeral" } } |
| 139 | : {}), |
| 140 | }; |
| 141 | return newpart; |
| 142 | } |
| 143 | return { |
| 144 | type: "image", |
| 145 | source: { |
| 146 | type: "base64", |
| 147 | media_type: "image/jpeg", |
| 148 | data: part.imageUrl?.url.split(",")[1], |
| 149 | }, |
| 150 | }; |
| 151 | }), |
| 152 | }; |
| 153 | } |
| 154 | |
| 155 | public convertMessages(msgs: ChatMessage[]): any[] { |
| 156 | // should be public for use within VertexAI |
| 157 | const filteredmessages = msgs.filter( |
| 158 | (m) => m.role !== "system" && !!m.content, |
| 159 | ); |
| 160 | const lastTwoUserMsgIndices = filteredmessages |
| 161 | .map((msg, index) => (msg.role === "user" ? index : -1)) |
| 162 | .filter((index) => index !== -1) |
| 163 | .slice(-2); |
| 164 | |
| 165 | const messages = filteredmessages.map((message, filteredMsgIdx) => { |
| 166 | // Add cache_control parameter to the last two user messages |
| 167 | // The second-to-last because it retrieves potentially already cached contents, |
| 168 | // The last one because we want it cached for later retrieval. |
| 169 | // See: https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching |
| 170 | const addCaching = |
| 171 | this.cacheBehavior?.cacheConversation && |
| 172 | lastTwoUserMsgIndices.includes(filteredMsgIdx); |
| 173 | |
| 174 | const chatMessage = this.convertMessage(message, !!addCaching); |
| 175 | return chatMessage; |
| 176 | }); |
| 177 | return messages; |
| 178 | } |
| 179 | |
| 180 | protected async *_streamComplete( |
| 181 | prompt: string, |
| 182 | signal: AbortSignal, |
| 183 | options: CompletionOptions, |
| 184 | ): AsyncGenerator<string> { |
| 185 | const messages = [{ role: "user" as const, content: prompt }]; |
| 186 | for await (const update of this._streamChat(messages, signal, options)) { |
| 187 | yield renderChatMessage(update); |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | async *handleResponse( |
| 192 | response: any, |
| 193 | stream: boolean | undefined, |
| 194 | ): AsyncGenerator<ChatMessage> { |
| 195 | if (response.status === 499) { |
| 196 | return; // Aborted by user |
| 197 | } |
| 198 | |
| 199 | if (!response.ok) { |
| 200 | const json = await response.json(); |
| 201 | if (json.type === "error") { |
| 202 | if (json.error?.type in errorMessages) { |
| 203 | throw new Error( |
| 204 | errorMessages[json.error.type as keyof typeof errorMessages], |
| 205 | ); |
| 206 | } |
| 207 | throw new Error(json.message); |
| 208 | } |
| 209 | throw new Error( |
| 210 | `Anthropic API sent back ${response.status}: ${JSON.stringify(json)}`, |
| 211 | ); |
| 212 | } |
| 213 | |
| 214 | if (stream === false) { |
| 215 | const data = await response.json(); |
| 216 | const cost = data.usage |
| 217 | ? { |
| 218 | inputTokens: data.usage.input_tokens, |
| 219 | outputTokens: data.usage.output_tokens, |
| 220 | totalTokens: data.usage.input_tokens + data.usage.output_tokens, |
| 221 | } |
| 222 | : {}; |
| 223 | yield { |
| 224 | role: "assistant", |
| 225 | content: data.content[0].text, |
| 226 | ...(Object.keys(cost).length > 0 ? { cost } : {}), |
| 227 | }; |
| 228 | return; |
| 229 | } |
| 230 | |
| 231 | let lastToolUseId: string | undefined; |
| 232 | let lastToolUseName: string | undefined; |
| 233 | let usage: Usage = { |
| 234 | promptTokens: 0, |
| 235 | completionTokens: 0, |
| 236 | promptTokensDetails: { |
| 237 | cachedTokens: 0, |
| 238 | cacheWriteTokens: 0, |
| 239 | }, |
| 240 | }; |
| 241 | |
| 242 | for await (const value of streamSse(response)) { |
| 243 | // https://docs.anthropic.com/en/api/messages-streaming#event-types |
| 244 | switch (value.type) { |
| 245 | case "message_start": |
| 246 | // Capture initial usage information |
| 247 | usage.promptTokens = value.message.usage.input_tokens; |
| 248 | usage.promptTokensDetails!.cachedTokens = |
| 249 | value.message.usage.cache_read_input_tokens; |
| 250 | usage.promptTokensDetails!.cacheWriteTokens = |
| 251 | value.message.usage.cache_creation_input_tokens; |
| 252 | break; |
| 253 | case "message_delta": |
| 254 | // Update usage information during streaming |
| 255 | if (value.usage) { |
| 256 | usage.completionTokens = value.usage.output_tokens; |
| 257 | } |
| 258 | break; |
| 259 | case "content_block_start": |
| 260 | if (value.content_block.type === "tool_use") { |
| 261 | lastToolUseId = value.content_block.id; |
| 262 | lastToolUseName = value.content_block.name; |
| 263 | } |
| 264 | // handle redacted thinking |
| 265 | if (value.content_block.type === "redacted_thinking") { |
| 266 | yield { |
| 267 | role: "thinking", |
| 268 | content: "", |
| 269 | redactedThinking: value.content_block.data, |
| 270 | }; |
| 271 | } |
| 272 | break; |
| 273 | case "content_block_delta": |
| 274 | // https://docs.anthropic.com/en/api/messages-streaming#delta-types |
| 275 | switch (value.delta.type) { |
| 276 | case "text_delta": |
| 277 | yield { role: "assistant", content: value.delta.text }; |
| 278 | break; |
| 279 | case "thinking_delta": |
| 280 | yield { role: "thinking", content: value.delta.thinking }; |
| 281 | break; |
| 282 | case "signature_delta": |
| 283 | yield { |
| 284 | role: "thinking", |
| 285 | content: "", |
| 286 | signature: value.delta.signature, |
| 287 | }; |
| 288 | break; |
| 289 | case "input_json_delta": |
| 290 | if (!lastToolUseId || !lastToolUseName) { |
| 291 | throw new Error("No tool use found"); |
| 292 | } |
| 293 | yield { |
| 294 | role: "assistant", |
| 295 | content: "", |
| 296 | toolCalls: [ |
| 297 | { |
| 298 | id: lastToolUseId, |
| 299 | type: "function", |
| 300 | function: { |
| 301 | name: lastToolUseName, |
| 302 | arguments: value.delta.partial_json, |
| 303 | }, |
| 304 | }, |
| 305 | ], |
| 306 | }; |
| 307 | break; |
| 308 | } |
| 309 | break; |
| 310 | case "content_block_stop": |
| 311 | lastToolUseId = undefined; |
| 312 | lastToolUseName = undefined; |
| 313 | break; |
| 314 | default: |
| 315 | break; |
| 316 | } |
| 317 | } |
| 318 | |
| 319 | yield { |
| 320 | role: "assistant", |
| 321 | content: "", |
| 322 | usage, |
| 323 | }; |
| 324 | } |
| 325 | |
| 326 | protected async *_streamChat( |
| 327 | messages: ChatMessage[], |
| 328 | signal: AbortSignal, |
| 329 | options: CompletionOptions, |
| 330 | ): AsyncGenerator<ChatMessage> { |
| 331 | if (!this.apiKey || this.apiKey === "") { |
| 332 | throw new Error( |
| 333 | "Request not sent. You have an Anthropic model configured in your config.json, but the API key is not set.", |
| 334 | ); |
| 335 | } |
| 336 | |
| 337 | const systemMessage = stripImages( |
| 338 | messages.filter((m) => m.role === "system")[0]?.content ?? "", |
| 339 | ); |
| 340 | const shouldCacheSystemMessage = !!( |
| 341 | this.cacheBehavior?.cacheSystemMessage && systemMessage |
| 342 | ); |
| 343 | |
| 344 | const msgs = this.convertMessages(messages); |
| 345 | const response = await this.fetch(new URL("messages", this.apiBase), { |
| 346 | method: "POST", |
| 347 | headers: { |
| 348 | "Content-Type": "application/json", |
| 349 | Accept: "application/json", |
| 350 | "anthropic-version": "2023-06-01", |
| 351 | "x-api-key": this.apiKey as string, |
| 352 | ...(shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation |
| 353 | ? { "anthropic-beta": "prompt-caching-2024-07-31" } |
| 354 | : {}), |
| 355 | }, |
| 356 | body: JSON.stringify({ |
| 357 | ...this.convertArgs(options), |
| 358 | messages: msgs, |
| 359 | system: shouldCacheSystemMessage |
| 360 | ? [ |
| 361 | { |
| 362 | type: "text", |
| 363 | text: systemMessage, |
| 364 | cache_control: { type: "ephemeral" }, |
| 365 | }, |
| 366 | ] |
| 367 | : systemMessage, |
| 368 | }), |
| 369 | signal, |
| 370 | }); |
| 371 | |
| 372 | yield* this.handleResponse(response, options.stream); |
| 373 | } |
| 374 | } |
| 375 | |
| 376 | export default Anthropic; |