| 1 | import { |
| 2 | ContentBlockParam, |
| 3 | MessageCreateParams, |
| 4 | MessageParam, |
| 5 | RawContentBlockDeltaEvent, |
| 6 | RawContentBlockStartEvent, |
| 7 | RawMessageDeltaEvent, |
| 8 | RawMessageStartEvent, |
| 9 | RawMessageStreamEvent, |
| 10 | Tool, |
| 11 | ToolUseBlock, |
| 12 | } from "@anthropic-ai/sdk/resources"; |
| 13 | import { streamSse } from "@continuedev/fetch"; |
| 14 | import { OpenAI } from "openai/index"; |
| 15 | import { |
| 16 | ChatCompletion, |
| 17 | ChatCompletionChunk, |
| 18 | ChatCompletionContentPartRefusal, |
| 19 | ChatCompletionContentPartText, |
| 20 | ChatCompletionCreateParamsNonStreaming, |
| 21 | ChatCompletionCreateParamsStreaming, |
| 22 | Completion, |
| 23 | CompletionCreateParamsNonStreaming, |
| 24 | CompletionCreateParamsStreaming, |
| 25 | CompletionUsage, |
| 26 | } from "openai/resources/index"; |
| 27 | import { ChatCompletionCreateParams } from "openai/resources/index.js"; |
| 28 | import { AnthropicConfig } from "../types.js"; |
| 29 | import { |
| 30 | chatChunk, |
| 31 | chatChunkFromDelta, |
| 32 | customFetch, |
| 33 | usageChatChunk, |
| 34 | } from "../util.js"; |
| 35 | import { EMPTY_CHAT_COMPLETION } from "../util/emptyChatCompletion.js"; |
| 36 | import { safeParseArgs } from "../util/parseArgs.js"; |
| 37 | import { |
| 38 | CACHING_STRATEGIES, |
| 39 | CachingStrategyName, |
| 40 | } from "./AnthropicCachingStrategies.js"; |
| 41 | import { |
| 42 | getAnthropicHeaders, |
| 43 | getAnthropicMediaTypeFromDataUrl, |
| 44 | openAiToolChoiceToAnthropicToolChoice, |
| 45 | openaiToolToAnthropicTool, |
| 46 | } from "./AnthropicUtils.js"; |
| 47 | import { |
| 48 | BaseLlmApi, |
| 49 | CreateRerankResponse, |
| 50 | FimCreateParamsStreaming, |
| 51 | RerankCreateParams, |
| 52 | } from "./base.js"; |
| 53 | |
| 54 | export class AnthropicApi implements BaseLlmApi { |
| 55 | apiBase: string = "https://api.anthropic.com/v1/"; |
| 56 | |
| 57 | constructor( |
| 58 | protected config: AnthropicConfig & { |
| 59 | cachingStrategy?: CachingStrategyName; |
| 60 | }, |
| 61 | ) { |
| 62 | this.apiBase = config.apiBase ?? this.apiBase; |
| 63 | if (!this.apiBase.endsWith("/")) { |
| 64 | this.apiBase += "/"; |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | private _convertBody(oaiBody: ChatCompletionCreateParams) { |
| 69 | // Step 1: Convert to clean Anthropic body (no caching) |
| 70 | const cleanBody = this._convertToCleanAnthropicBody(oaiBody); |
| 71 | |
| 72 | // Step 2: Apply caching strategy |
| 73 | const cachingStrategy = |
| 74 | CACHING_STRATEGIES[this.config.cachingStrategy ?? "systemAndTools"]; |
| 75 | return cachingStrategy(cleanBody); |
| 76 | } |
| 77 | |
| 78 | private maxTokensForModel(model: string): number { |
| 79 | if (model.includes("haiku")) { |
| 80 | return 8192; |
| 81 | } |
| 82 | return 32_000; |
| 83 | } |
| 84 | |
| 85 | public _convertToCleanAnthropicBody( |
| 86 | oaiBody: ChatCompletionCreateParams, |
| 87 | ): MessageCreateParams { |
| 88 | let stop = undefined; |
| 89 | if (oaiBody.stop && Array.isArray(oaiBody.stop)) { |
| 90 | stop = oaiBody.stop.filter((x) => x.trim() !== ""); |
| 91 | } else if (typeof oaiBody.stop === "string" && oaiBody.stop.trim() !== "") { |
| 92 | stop = [oaiBody.stop]; |
| 93 | } |
| 94 | |
| 95 | const systemMessage = oaiBody.messages.find( |
| 96 | (msg) => msg.role === "system", |
| 97 | )?.content; |
| 98 | |
| 99 | // TODO support custom tools |
| 100 | const functionTools = oaiBody.tools?.filter((t) => t.type === "function"); |
| 101 | let tools: Tool[] | undefined = undefined; |
| 102 | |
| 103 | if ( |
| 104 | oaiBody.tool_choice !== "none" && |
| 105 | functionTools && |
| 106 | functionTools.length > 0 |
| 107 | ) { |
| 108 | if ( |
| 109 | typeof oaiBody.tool_choice !== "string" && |
| 110 | oaiBody.tool_choice?.type === "allowed_tools" |
| 111 | ) { |
| 112 | const allowedToolNames = new Set( |
| 113 | oaiBody.tool_choice?.allowed_tools.tools.map( |
| 114 | (tool) => tool["name"], |
| 115 | ) ?? [], |
| 116 | ); |
| 117 | const allowedTools = functionTools.filter((t) => |
| 118 | allowedToolNames.has(t.function.name), |
| 119 | ); |
| 120 | tools = allowedTools.map(openaiToolToAnthropicTool); |
| 121 | } else { |
| 122 | tools = functionTools.map(openaiToolToAnthropicTool); |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | const anthropicBody: MessageCreateParams = { |
| 127 | messages: this._convertMessages( |
| 128 | oaiBody.messages.filter((msg) => msg.role !== "system"), |
| 129 | ), |
| 130 | system: |
| 131 | typeof systemMessage === "string" |
| 132 | ? [ |
| 133 | { |
| 134 | type: "text", |
| 135 | text: systemMessage, |
| 136 | }, |
| 137 | ] |
| 138 | : systemMessage, |
| 139 | top_p: oaiBody.top_p ?? undefined, |
| 140 | temperature: oaiBody.temperature ?? undefined, |
| 141 | max_tokens: oaiBody.max_tokens ?? this.maxTokensForModel(oaiBody.model), // max_tokens is required |
| 142 | model: oaiBody.model, |
| 143 | stop_sequences: stop, |
| 144 | stream: oaiBody.stream ?? undefined, |
| 145 | tools, |
| 146 | tool_choice: openAiToolChoiceToAnthropicToolChoice(oaiBody.tool_choice), |
| 147 | }; |
| 148 | |
| 149 | return anthropicBody; |
| 150 | } |
| 151 | |
| 152 | private convertToolCallsToBlocks( |
| 153 | toolCall: OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall, |
| 154 | ): ToolUseBlock | undefined { |
| 155 | const toolCallId = toolCall.id; |
| 156 | const toolName = toolCall.function?.name; |
| 157 | if (toolCallId && toolName) { |
| 158 | return { |
| 159 | type: "tool_use", |
| 160 | id: toolCallId, |
| 161 | name: toolName, |
| 162 | input: safeParseArgs( |
| 163 | toolCall.function.arguments, |
| 164 | `${toolName} ${toolCallId}`, |
| 165 | ), |
| 166 | }; |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | // 1. ignores empty content |
| 171 | // 2. converts string content to text parts |
| 172 | // 3. converts text and refusal parts to text blocks |
| 173 | // 4. converts image parts to image blocks |
| 174 | private convertMessageContentToBlocks( |
| 175 | content: |
| 176 | | string |
| 177 | | OpenAI.Chat.Completions.ChatCompletionContentPart[] |
| 178 | | (ChatCompletionContentPartText | ChatCompletionContentPartRefusal)[], |
| 179 | ): ContentBlockParam[] { |
| 180 | const blocks: ContentBlockParam[] = []; |
| 181 | if (typeof content === "string") { |
| 182 | if (content) { |
| 183 | blocks.push({ |
| 184 | type: "text", |
| 185 | text: content, |
| 186 | }); |
| 187 | } |
| 188 | } else { |
| 189 | const supportedParts = content.filter( |
| 190 | (p) => |
| 191 | p.type === "text" || p.type === "image_url" || p.type === "refusal", |
| 192 | ); |
| 193 | for (const part of supportedParts) { |
| 194 | if (part.type === "image_url") { |
| 195 | const dataUrl = part.image_url.url; |
| 196 | if (dataUrl?.startsWith("data:")) { |
| 197 | blocks.push({ |
| 198 | type: "image", |
| 199 | source: { |
| 200 | type: "base64", |
| 201 | media_type: getAnthropicMediaTypeFromDataUrl(dataUrl), |
| 202 | data: dataUrl.split(",")[1], |
| 203 | }, |
| 204 | }); |
| 205 | } |
| 206 | } else { |
| 207 | const text = part.type === "text" ? part.text : part.refusal; |
| 208 | if (text) { |
| 209 | blocks.push({ |
| 210 | type: "text", |
| 211 | text, |
| 212 | }); |
| 213 | } |
| 214 | } |
| 215 | } |
| 216 | } |
| 217 | return blocks; |
| 218 | } |
| 219 | |
| 220 | private getContentBlocksFromChatMessage( |
| 221 | message: OpenAI.Chat.Completions.ChatCompletionMessageParam, |
| 222 | ): ContentBlockParam[] { |
| 223 | switch (message.role) { |
| 224 | // One tool message = one tool_result block |
| 225 | case "tool": |
| 226 | return [ |
| 227 | { |
| 228 | type: "tool_result", |
| 229 | tool_use_id: message.tool_call_id, |
| 230 | content: message.content, |
| 231 | }, |
| 232 | ]; |
| 233 | case "user": |
| 234 | return this.convertMessageContentToBlocks(message.content); |
| 235 | case "assistant": |
| 236 | const blocks: ContentBlockParam[] = message.content |
| 237 | ? this.convertMessageContentToBlocks(message.content) |
| 238 | : []; |
| 239 | // If any tool calls are present, always put them last |
| 240 | // Loses order vs what was originally sent, but they typically come last |
| 241 | for (const toolCall of message.tool_calls ?? []) { |
| 242 | if (toolCall.type !== "function") { |
| 243 | // TODO support custom tool calls |
| 244 | continue; |
| 245 | } |
| 246 | const block = this.convertToolCallsToBlocks(toolCall); |
| 247 | if (block) { |
| 248 | blocks.push(block); |
| 249 | } |
| 250 | } |
| 251 | return blocks; |
| 252 | // system, etc. |
| 253 | default: |
| 254 | return []; |
| 255 | } |
| 256 | } |
| 257 | |
| 258 | private _convertMessages( |
| 259 | msgs: OpenAI.Chat.Completions.ChatCompletionMessageParam[], |
| 260 | ): MessageParam[] { |
| 261 | const nonSystemMessages = msgs.filter((m) => m.role !== "system"); |
| 262 | |
| 263 | const convertedMessages: MessageParam[] = []; |
| 264 | let currentRole: "user" | "assistant" | undefined = undefined; |
| 265 | let currentParts: ContentBlockParam[] = []; |
| 266 | |
| 267 | const flushCurrentMessage = () => { |
| 268 | if (currentRole && currentParts.length > 0) { |
| 269 | convertedMessages.push({ |
| 270 | role: currentRole, |
| 271 | content: currentParts, |
| 272 | }); |
| 273 | currentParts = []; |
| 274 | } |
| 275 | }; |
| 276 | |
| 277 | for (const message of nonSystemMessages) { |
| 278 | const newRole = |
| 279 | message.role === "user" || message.role === "tool" |
| 280 | ? "user" |
| 281 | : "assistant"; |
| 282 | if (currentRole !== newRole) { |
| 283 | flushCurrentMessage(); |
| 284 | currentRole = newRole; |
| 285 | } |
| 286 | currentParts.push(...this.getContentBlocksFromChatMessage(message)); |
| 287 | } |
| 288 | flushCurrentMessage(); |
| 289 | |
| 290 | return convertedMessages; |
| 291 | } |
| 292 | |
| 293 | async chatCompletionNonStream( |
| 294 | body: ChatCompletionCreateParamsNonStreaming, |
| 295 | signal: AbortSignal, |
| 296 | ): Promise<ChatCompletion> { |
| 297 | const response = await customFetch(this.config.requestOptions)( |
| 298 | new URL("messages", this.apiBase), |
| 299 | { |
| 300 | method: "POST", |
| 301 | headers: this.getHeaders(), |
| 302 | body: JSON.stringify(this._convertBody(body)), |
| 303 | signal, |
| 304 | }, |
| 305 | ); |
| 306 | |
| 307 | if (response.status === 499) { |
| 308 | return EMPTY_CHAT_COMPLETION; |
| 309 | } |
| 310 | |
| 311 | const completion = await response.json(); |
| 312 | |
| 313 | const usage: Record<string, number> | undefined = completion.usage; |
| 314 | return { |
| 315 | id: completion.id, |
| 316 | object: "chat.completion", |
| 317 | model: body.model, |
| 318 | created: Date.now(), |
| 319 | usage: { |
| 320 | total_tokens: (usage?.input_tokens ?? 0) + (usage?.output_tokens ?? 0), |
| 321 | completion_tokens: usage?.output_tokens ?? 0, |
| 322 | prompt_tokens: usage?.input_tokens ?? 0, |
| 323 | prompt_tokens_details: { |
| 324 | cached_tokens: usage?.cache_read_input_tokens ?? 0, |
| 325 | }, |
| 326 | }, |
| 327 | choices: [ |
| 328 | { |
| 329 | logprobs: null, |
| 330 | finish_reason: "stop", |
| 331 | message: { |
| 332 | role: "assistant", |
| 333 | content: completion.content[0].text, |
| 334 | refusal: null, |
| 335 | }, |
| 336 | index: 0, |
| 337 | }, |
| 338 | ], |
| 339 | }; |
| 340 | } |
| 341 | |
| 342 | // This is split off so e.g. VertexAI can use it |
| 343 | async *handleStreamResponse(response: any, model: string) { |
| 344 | let lastToolUseId: string | undefined; |
| 345 | let lastToolUseName: string | undefined; |
| 346 | |
| 347 | const usage: CompletionUsage = { |
| 348 | completion_tokens: 0, |
| 349 | prompt_tokens: 0, |
| 350 | total_tokens: 0, |
| 351 | }; |
| 352 | for await (const event of streamSse(response)) { |
| 353 | // https://docs.anthropic.com/en/api/messages-streaming#event-types |
| 354 | const rawEvent = event as RawMessageStreamEvent; |
| 355 | switch (rawEvent.type) { |
| 356 | case "content_block_start": |
| 357 | const blockStartEvent = rawEvent as RawContentBlockStartEvent; |
| 358 | if (blockStartEvent.content_block.type === "tool_use") { |
| 359 | lastToolUseId = blockStartEvent.content_block.id; |
| 360 | lastToolUseName = blockStartEvent.content_block.name; |
| 361 | } |
| 362 | break; |
| 363 | case "message_start": |
| 364 | const startEvent = rawEvent as RawMessageStartEvent; |
| 365 | usage.prompt_tokens = startEvent.message.usage?.input_tokens ?? 0; |
| 366 | usage.prompt_tokens_details = { |
| 367 | cached_tokens: |
| 368 | startEvent.message.usage?.cache_read_input_tokens ?? 0, |
| 369 | }; |
| 370 | break; |
| 371 | case "message_delta": |
| 372 | const deltaEvent = rawEvent as RawMessageDeltaEvent; |
| 373 | usage.completion_tokens = deltaEvent.usage?.output_tokens ?? 0; |
| 374 | break; |
| 375 | case "content_block_delta": |
| 376 | // https://docs.anthropic.com/en/api/messages-streaming#delta-types |
| 377 | const blockDeltaEvent = rawEvent as RawContentBlockDeltaEvent; |
| 378 | switch (blockDeltaEvent.delta.type) { |
| 379 | case "text_delta": |
| 380 | yield chatChunk({ |
| 381 | content: blockDeltaEvent.delta.text, |
| 382 | model, |
| 383 | }); |
| 384 | break; |
| 385 | case "input_json_delta": |
| 386 | if (!lastToolUseId || !lastToolUseName) { |
| 387 | throw new Error("No tool use found"); |
| 388 | } |
| 389 | yield chatChunkFromDelta({ |
| 390 | model, |
| 391 | delta: { |
| 392 | tool_calls: [ |
| 393 | { |
| 394 | id: lastToolUseId, |
| 395 | type: "function", |
| 396 | index: 0, |
| 397 | function: { |
| 398 | name: lastToolUseName, |
| 399 | arguments: blockDeltaEvent.delta.partial_json, |
| 400 | }, |
| 401 | }, |
| 402 | ], |
| 403 | }, |
| 404 | }); |
| 405 | break; |
| 406 | } |
| 407 | break; |
| 408 | case "content_block_stop": |
| 409 | lastToolUseId = undefined; |
| 410 | lastToolUseName = undefined; |
| 411 | break; |
| 412 | default: |
| 413 | break; |
| 414 | } |
| 415 | } |
| 416 | |
| 417 | yield usageChatChunk({ |
| 418 | model, |
| 419 | usage: { |
| 420 | ...usage, |
| 421 | total_tokens: usage.completion_tokens + usage.prompt_tokens, |
| 422 | }, |
| 423 | }); |
| 424 | } |
| 425 | |
| 426 | async *chatCompletionStream( |
| 427 | body: ChatCompletionCreateParamsStreaming, |
| 428 | signal: AbortSignal, |
| 429 | ): AsyncGenerator<ChatCompletionChunk> { |
| 430 | const response = await customFetch(this.config.requestOptions)( |
| 431 | new URL("messages", this.apiBase), |
| 432 | { |
| 433 | method: "POST", |
| 434 | headers: this.getHeaders(), |
| 435 | body: JSON.stringify(this._convertBody(body)), |
| 436 | signal, |
| 437 | }, |
| 438 | ); |
| 439 | yield* this.handleStreamResponse(response, body.model); |
| 440 | } |
| 441 | |
| 442 | private getHeaders(): Record<string, string> { |
| 443 | const enableCaching = this.config?.cachingStrategy !== "none"; |
| 444 | return getAnthropicHeaders(this.config.apiKey, enableCaching); |
| 445 | } |
| 446 | |
| 447 | async completionNonStream( |
| 448 | body: CompletionCreateParamsNonStreaming, |
| 449 | signal: AbortSignal, |
| 450 | ): Promise<Completion> { |
| 451 | throw new Error("Method not implemented."); |
| 452 | } |
| 453 | async *completionStream( |
| 454 | body: CompletionCreateParamsStreaming, |
| 455 | signal: AbortSignal, |
| 456 | ): AsyncGenerator<Completion> { |
| 457 | throw new Error("Method not implemented."); |
| 458 | } |
| 459 | async *fimStream( |
| 460 | body: FimCreateParamsStreaming, |
| 461 | signal: AbortSignal, |
| 462 | ): AsyncGenerator<ChatCompletionChunk> { |
| 463 | throw new Error("Method not implemented."); |
| 464 | } |
| 465 | |
| 466 | async embed( |
| 467 | body: OpenAI.Embeddings.EmbeddingCreateParams, |
| 468 | ): Promise<OpenAI.Embeddings.CreateEmbeddingResponse> { |
| 469 | throw new Error("Method not implemented."); |
| 470 | } |
| 471 | |
| 472 | async rerank(body: RerankCreateParams): Promise<CreateRerankResponse> { |
| 473 | throw new Error("Method not implemented."); |
| 474 | } |
| 475 | |
| 476 | list(): Promise<OpenAI.Models.Model[]> { |
| 477 | throw new Error("Method not implemented."); |
| 478 | } |
| 479 | } |