| 1 | import { streamSse } from "@continuedev/fetch"; |
| 2 | import { OpenAI } from "openai/index"; |
| 3 | import { |
| 4 | ChatCompletion, |
| 5 | ChatCompletionChunk, |
| 6 | ChatCompletionCreateParamsNonStreaming, |
| 7 | ChatCompletionCreateParamsStreaming, |
| 8 | Completion, |
| 9 | CompletionCreateParamsNonStreaming, |
| 10 | CompletionCreateParamsStreaming, |
| 11 | CompletionUsage, |
| 12 | } from "openai/resources/index"; |
| 13 | import { ChatCompletionCreateParams } from "openai/src/resources/index.js"; |
| 14 | import { AnthropicConfig } from "../types.js"; |
| 15 | import { |
| 16 | chatChunk, |
| 17 | chatChunkFromDelta, |
| 18 | customFetch, |
| 19 | usageChatChunk, |
| 20 | } from "../util.js"; |
| 21 | import { EMPTY_CHAT_COMPLETION } from "../util/emptyChatCompletion.js"; |
| 22 | import { safeParseArgs } from "../util/parseArgs.js"; |
| 23 | import { |
| 24 | CACHING_STRATEGIES, |
| 25 | CachingStrategyName, |
| 26 | } from "./AnthropicCachingStrategies.js"; |
| 27 | import { |
| 28 | BaseLlmApi, |
| 29 | CreateRerankResponse, |
| 30 | FimCreateParamsStreaming, |
| 31 | RerankCreateParams, |
| 32 | } from "./base.js"; |
| 33 | |
| 34 | export class AnthropicApi implements BaseLlmApi { |
| 35 | apiBase: string = "https://api.anthropic.com/v1/"; |
| 36 | |
| 37 | constructor( |
| 38 | protected config: AnthropicConfig & { |
| 39 | cachingStrategy?: CachingStrategyName; |
| 40 | }, |
| 41 | ) { |
| 42 | this.apiBase = config.apiBase ?? this.apiBase; |
| 43 | if (!this.apiBase.endsWith("/")) { |
| 44 | this.apiBase += "/"; |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | private _convertBody(oaiBody: ChatCompletionCreateParams) { |
| 49 | // Step 1: Convert to clean Anthropic body (no caching) |
| 50 | const cleanBody = this._convertToCleanAnthropicBody(oaiBody); |
| 51 | |
| 52 | // Step 2: Apply caching strategy |
| 53 | const cachingStrategy = |
| 54 | CACHING_STRATEGIES[this.config.cachingStrategy ?? "systemAndTools"]; |
| 55 | return cachingStrategy(cleanBody); |
| 56 | } |
| 57 | |
| 58 | private maxTokensForModel(model: string): number { |
| 59 | if (model.includes("haiku")) { |
| 60 | return 8192; |
| 61 | } |
| 62 | |
| 63 | return 32_000; |
| 64 | } |
| 65 | |
| 66 | public _convertToCleanAnthropicBody(oaiBody: ChatCompletionCreateParams) { |
| 67 | let stop = undefined; |
| 68 | if (oaiBody.stop && Array.isArray(oaiBody.stop)) { |
| 69 | stop = oaiBody.stop.filter((x) => x.trim() !== ""); |
| 70 | } else if (typeof oaiBody.stop === "string" && oaiBody.stop.trim() !== "") { |
| 71 | stop = [oaiBody.stop]; |
| 72 | } |
| 73 | |
| 74 | const systemMessage = oaiBody.messages.find( |
| 75 | (msg) => msg.role === "system", |
| 76 | )?.content; |
| 77 | |
| 78 | const anthropicBody = { |
| 79 | messages: this._convertMessages( |
| 80 | oaiBody.messages.filter((msg) => msg.role !== "system"), |
| 81 | ), |
| 82 | system: systemMessage |
| 83 | ? [ |
| 84 | { |
| 85 | type: "text", |
| 86 | text: systemMessage, |
| 87 | }, |
| 88 | ] |
| 89 | : systemMessage, |
| 90 | top_p: oaiBody.top_p, |
| 91 | temperature: oaiBody.temperature, |
| 92 | max_tokens: oaiBody.max_tokens ?? this.maxTokensForModel(oaiBody.model), // max_tokens is required |
| 93 | model: oaiBody.model, |
| 94 | stop_sequences: stop, |
| 95 | stream: oaiBody.stream, |
| 96 | tools: oaiBody.tools?.map((tool) => ({ |
| 97 | name: tool.function.name, |
| 98 | description: tool.function.description, |
| 99 | input_schema: tool.function.parameters, |
| 100 | })), |
| 101 | tool_choice: oaiBody.tool_choice |
| 102 | ? { |
| 103 | type: "tool", |
| 104 | name: |
| 105 | typeof oaiBody.tool_choice === "string" |
| 106 | ? oaiBody.tool_choice |
| 107 | : oaiBody.tool_choice?.function.name, |
| 108 | } |
| 109 | : undefined, |
| 110 | }; |
| 111 | |
| 112 | return anthropicBody; |
| 113 | } |
| 114 | |
| 115 | private _convertMessages( |
| 116 | msgs: OpenAI.Chat.Completions.ChatCompletionMessageParam[], |
| 117 | ): any[] { |
| 118 | const messages = msgs.map((message) => { |
| 119 | if (message.role === "tool") { |
| 120 | return { |
| 121 | role: "user", |
| 122 | content: [ |
| 123 | { |
| 124 | type: "tool_result", |
| 125 | tool_use_id: message.tool_call_id, |
| 126 | content: |
| 127 | typeof message.content === "string" |
| 128 | ? message.content |
| 129 | : message.content.map((part) => part.text).join(""), |
| 130 | }, |
| 131 | ], |
| 132 | }; |
| 133 | } else if (message.role === "assistant" && message.tool_calls) { |
| 134 | return { |
| 135 | role: "assistant", |
| 136 | content: message.tool_calls.map((toolCall) => ({ |
| 137 | type: "tool_use", |
| 138 | id: toolCall.id, |
| 139 | name: toolCall.function?.name, |
| 140 | input: safeParseArgs( |
| 141 | toolCall.function?.arguments, |
| 142 | `${toolCall.function?.name} ${toolCall.id}`, |
| 143 | ), |
| 144 | })), |
| 145 | }; |
| 146 | } |
| 147 | |
| 148 | if (!Array.isArray(message.content)) { |
| 149 | return message; |
| 150 | } |
| 151 | return { |
| 152 | ...message, |
| 153 | content: message.content |
| 154 | .map((part) => { |
| 155 | if (part.type === "text") { |
| 156 | if ((part.text?.trim() ?? "") === "") { |
| 157 | return null; |
| 158 | } |
| 159 | return part; |
| 160 | } |
| 161 | return { |
| 162 | type: "image", |
| 163 | source: { |
| 164 | type: "base64", |
| 165 | media_type: "image/jpeg", |
| 166 | // @ts-ignore |
| 167 | data: part.image_url.url.split(",")[1], |
| 168 | }, |
| 169 | }; |
| 170 | }) |
| 171 | .filter((x) => x !== null), |
| 172 | }; |
| 173 | }); |
| 174 | return messages; |
| 175 | } |
| 176 | |
| 177 | async chatCompletionNonStream( |
| 178 | body: ChatCompletionCreateParamsNonStreaming, |
| 179 | signal: AbortSignal, |
| 180 | ): Promise<ChatCompletion> { |
| 181 | const response = await customFetch(this.config.requestOptions)( |
| 182 | new URL("messages", this.apiBase), |
| 183 | { |
| 184 | method: "POST", |
| 185 | headers: { |
| 186 | "Content-Type": "application/json", |
| 187 | Accept: "application/json", |
| 188 | "anthropic-version": "2023-06-01", |
| 189 | "anthropic-beta": "prompt-caching-2024-07-31", |
| 190 | "x-api-key": this.config.apiKey, |
| 191 | }, |
| 192 | body: JSON.stringify(this._convertBody(body)), |
| 193 | signal, |
| 194 | }, |
| 195 | ); |
| 196 | |
| 197 | if (response.status === 499) { |
| 198 | return EMPTY_CHAT_COMPLETION; |
| 199 | } |
| 200 | |
| 201 | const completion = (await response.json()) as any; |
| 202 | |
| 203 | const usage: Record<string, number> | undefined = completion.usage; |
| 204 | return { |
| 205 | id: completion.id, |
| 206 | object: "chat.completion", |
| 207 | model: body.model, |
| 208 | created: Date.now(), |
| 209 | usage: { |
| 210 | total_tokens: (usage?.input_tokens ?? 0) + (usage?.output_tokens ?? 0), |
| 211 | completion_tokens: usage?.output_tokens ?? 0, |
| 212 | prompt_tokens: usage?.input_tokens ?? 0, |
| 213 | prompt_tokens_details: { |
| 214 | cached_tokens: usage?.cache_read_input_tokens ?? 0, |
| 215 | }, |
| 216 | }, |
| 217 | choices: [ |
| 218 | { |
| 219 | logprobs: null, |
| 220 | finish_reason: "stop", |
| 221 | message: { |
| 222 | role: "assistant", |
| 223 | content: completion.content[0].text, |
| 224 | refusal: null, |
| 225 | }, |
| 226 | index: 0, |
| 227 | }, |
| 228 | ], |
| 229 | }; |
| 230 | } |
| 231 | |
| 232 | // This is split off so e.g. VertexAI can use it |
| 233 | async *handleStreamResponse(response: any, model: string) { |
| 234 | let lastToolUseId: string | undefined; |
| 235 | let lastToolUseName: string | undefined; |
| 236 | |
| 237 | const usage: CompletionUsage = { |
| 238 | completion_tokens: 0, |
| 239 | prompt_tokens: 0, |
| 240 | total_tokens: 0, |
| 241 | }; |
| 242 | for await (const value of streamSse(response as any)) { |
| 243 | // https://docs.anthropic.com/en/api/messages-streaming#event-types |
| 244 | switch (value.type) { |
| 245 | case "content_block_start": |
| 246 | if (value.content_block.type === "tool_use") { |
| 247 | lastToolUseId = value.content_block.id; |
| 248 | lastToolUseName = value.content_block.name; |
| 249 | } |
| 250 | break; |
| 251 | case "message_start": |
| 252 | usage.prompt_tokens = value.message.usage?.input_tokens ?? 0; |
| 253 | usage.prompt_tokens_details = { |
| 254 | cached_tokens: value.message.usage?.cache_read_input_tokens ?? 0, |
| 255 | }; |
| 256 | break; |
| 257 | case "message_delta": |
| 258 | usage.completion_tokens = value.usage?.output_tokens ?? 0; |
| 259 | break; |
| 260 | case "content_block_delta": |
| 261 | // https://docs.anthropic.com/en/api/messages-streaming#delta-types |
| 262 | switch (value.delta.type) { |
| 263 | case "text_delta": |
| 264 | yield chatChunk({ |
| 265 | content: value.delta.text, |
| 266 | model, |
| 267 | }); |
| 268 | break; |
| 269 | case "input_json_delta": |
| 270 | if (!lastToolUseId || !lastToolUseName) { |
| 271 | throw new Error("No tool use found"); |
| 272 | } |
| 273 | yield chatChunkFromDelta({ |
| 274 | model, |
| 275 | delta: { |
| 276 | tool_calls: [ |
| 277 | { |
| 278 | id: lastToolUseId, |
| 279 | type: "function", |
| 280 | index: 0, |
| 281 | function: { |
| 282 | name: lastToolUseName, |
| 283 | arguments: value.delta.partial_json, |
| 284 | }, |
| 285 | }, |
| 286 | ], |
| 287 | }, |
| 288 | }); |
| 289 | break; |
| 290 | } |
| 291 | break; |
| 292 | case "content_block_stop": |
| 293 | lastToolUseId = undefined; |
| 294 | lastToolUseName = undefined; |
| 295 | break; |
| 296 | default: |
| 297 | break; |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | yield usageChatChunk({ |
| 302 | model, |
| 303 | usage: { |
| 304 | ...usage, |
| 305 | total_tokens: usage.completion_tokens + usage.prompt_tokens, |
| 306 | }, |
| 307 | }); |
| 308 | } |
| 309 | |
| 310 | async *chatCompletionStream( |
| 311 | body: ChatCompletionCreateParamsStreaming, |
| 312 | signal: AbortSignal, |
| 313 | ): AsyncGenerator<ChatCompletionChunk, any, unknown> { |
| 314 | body.messages; |
| 315 | const response = await customFetch(this.config.requestOptions)( |
| 316 | new URL("messages", this.apiBase), |
| 317 | { |
| 318 | method: "POST", |
| 319 | headers: { |
| 320 | "Content-Type": "application/json", |
| 321 | Accept: "application/json", |
| 322 | "anthropic-version": "2023-06-01", |
| 323 | "anthropic-beta": "prompt-caching-2024-07-31", |
| 324 | "x-api-key": this.config.apiKey, |
| 325 | }, |
| 326 | body: JSON.stringify(this._convertBody(body)), |
| 327 | signal, |
| 328 | }, |
| 329 | ); |
| 330 | yield* this.handleStreamResponse(response, body.model); |
| 331 | } |
| 332 | async completionNonStream( |
| 333 | body: CompletionCreateParamsNonStreaming, |
| 334 | signal: AbortSignal, |
| 335 | ): Promise<Completion> { |
| 336 | throw new Error("Method not implemented."); |
| 337 | } |
| 338 | async *completionStream( |
| 339 | body: CompletionCreateParamsStreaming, |
| 340 | signal: AbortSignal, |
| 341 | ): AsyncGenerator<Completion, any, unknown> { |
| 342 | throw new Error("Method not implemented."); |
| 343 | } |
| 344 | async *fimStream( |
| 345 | body: FimCreateParamsStreaming, |
| 346 | signal: AbortSignal, |
| 347 | ): AsyncGenerator<ChatCompletionChunk, any, unknown> { |
| 348 | throw new Error("Method not implemented."); |
| 349 | } |
| 350 | |
| 351 | async embed( |
| 352 | body: OpenAI.Embeddings.EmbeddingCreateParams, |
| 353 | ): Promise<OpenAI.Embeddings.CreateEmbeddingResponse> { |
| 354 | throw new Error("Method not implemented."); |
| 355 | } |
| 356 | |
| 357 | async rerank(body: RerankCreateParams): Promise<CreateRerankResponse> { |
| 358 | throw new Error("Method not implemented."); |
| 359 | } |
| 360 | |
| 361 | list(): Promise<OpenAI.Models.Model[]> { |
| 362 | throw new Error("Method not implemented."); |
| 363 | } |
| 364 | } |