Elffuss BraidHub

kikocis/continue public

87f75892af56 · 11.5 KiBRawPermalink
1import { streamSse } from "@continuedev/fetch";
2import { OpenAI } from "openai/index";
3import {
4 ChatCompletion,
5 ChatCompletionChunk,
6 ChatCompletionCreateParamsNonStreaming,
7 ChatCompletionCreateParamsStreaming,
8 Completion,
9 CompletionCreateParamsNonStreaming,
10 CompletionCreateParamsStreaming,
11 CompletionUsage,
12} from "openai/resources/index";
13import { ChatCompletionCreateParams } from "openai/resources/index.js";
14import { AnthropicConfig } from "../types.js";
15import {
16 chatChunk,
17 chatChunkFromDelta,
18 customFetch,
19 usageChatChunk,
20} from "../util.js";
21import { EMPTY_CHAT_COMPLETION } from "../util/emptyChatCompletion.js";
22import { safeParseArgs } from "../util/parseArgs.js";
23import {
24 CACHING_STRATEGIES,
25 CachingStrategyName,
26} from "./AnthropicCachingStrategies.js";
27import {
28 BaseLlmApi,
29 CreateRerankResponse,
30 FimCreateParamsStreaming,
31 RerankCreateParams,
32} from "./base.js";
33
34export 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 // Type guard for function tools
98 if (tool.type === "function" && "function" in tool) {
99 return {
100 name: tool.function.name,
101 description: tool.function.description,
102 input_schema: tool.function.parameters,
103 };
104 } else {
105 throw new Error(`Unsupported tool type in Anthropic: ${tool.type}`);
106 }
107 }),
108 tool_choice: oaiBody.tool_choice
109 ? {
110 type: "tool",
111 name:
112 typeof oaiBody.tool_choice === "string"
113 ? oaiBody.tool_choice
114 : oaiBody.tool_choice && "function" in oaiBody.tool_choice
115 ? oaiBody.tool_choice.function.name
116 : undefined,
117 }
118 : undefined,
119 };
120
121 return anthropicBody;
122 }
123
124 private _convertMessages(
125 msgs: OpenAI.Chat.Completions.ChatCompletionMessageParam[],
126 ): any[] {
127 const messages = msgs.map((message) => {
128 if (message.role === "tool") {
129 return {
130 role: "user",
131 content: [
132 {
133 type: "tool_result",
134 tool_use_id: message.tool_call_id,
135 content:
136 typeof message.content === "string"
137 ? message.content
138 : message.content.map((part) => part.text).join(""),
139 },
140 ],
141 };
142 } else if (message.role === "assistant" && message.tool_calls) {
143 return {
144 role: "assistant",
145 content: message.tool_calls.map((toolCall) => {
146 // Type guard for function tool calls
147 if (toolCall.type === "function" && "function" in toolCall) {
148 return {
149 type: "tool_use",
150 id: toolCall.id,
151 name: toolCall.function?.name,
152 input: safeParseArgs(
153 toolCall.function?.arguments,
154 `${toolCall.function?.name} ${toolCall.id}`,
155 ),
156 };
157 } else {
158 throw new Error(`Unsupported tool call type: ${toolCall.type}`);
159 }
160 }),
161 };
162 }
163
164 if (!Array.isArray(message.content)) {
165 return message;
166 }
167 return {
168 ...message,
169 content: message.content
170 .map((part) => {
171 if (part.type === "text") {
172 if ((part.text?.trim() ?? "") === "") {
173 return null;
174 }
175 return part;
176 }
177 const dataUrl =
178 (part as OpenAI.Chat.Completions.ChatCompletionContentPartImage)
179 ?.image_url?.url || "";
180 // Extract media type from data URL (ex. "data:image/png;base64,..." -> "image/png")
181 const mediaTypeMatch = dataUrl.match(/^data:([^;]+);base64,/);
182 const mediaType = mediaTypeMatch ? mediaTypeMatch[1] : "image/jpeg";
183
184 return {
185 type: "image",
186 source: {
187 type: "base64",
188 media_type: mediaType,
189 data: dataUrl.split(",")[1],
190 },
191 };
192 })
193 .filter((x) => x !== null),
194 };
195 });
196 return messages;
197 }
198
199 async chatCompletionNonStream(
200 body: ChatCompletionCreateParamsNonStreaming,
201 signal: AbortSignal,
202 ): Promise<ChatCompletion> {
203 const response = await customFetch(this.config.requestOptions)(
204 new URL("messages", this.apiBase),
205 {
206 method: "POST",
207 headers: {
208 "Content-Type": "application/json",
209 Accept: "application/json",
210 "anthropic-version": "2023-06-01",
211 "anthropic-beta": "prompt-caching-2024-07-31",
212 "x-api-key": this.config.apiKey,
213 },
214 body: JSON.stringify(this._convertBody(body)),
215 signal,
216 },
217 );
218
219 if (response.status === 499) {
220 return EMPTY_CHAT_COMPLETION;
221 }
222
223 const completion = (await response.json()) as any;
224
225 const usage: Record<string, number> | undefined = completion.usage;
226 return {
227 id: completion.id,
228 object: "chat.completion",
229 model: body.model,
230 created: Date.now(),
231 usage: {
232 total_tokens: (usage?.input_tokens ?? 0) + (usage?.output_tokens ?? 0),
233 completion_tokens: usage?.output_tokens ?? 0,
234 prompt_tokens: usage?.input_tokens ?? 0,
235 prompt_tokens_details: {
236 cached_tokens: usage?.cache_read_input_tokens ?? 0,
237 },
238 },
239 choices: [
240 {
241 logprobs: null,
242 finish_reason: "stop",
243 message: {
244 role: "assistant",
245 content: completion.content[0].text,
246 refusal: null,
247 },
248 index: 0,
249 },
250 ],
251 };
252 }
253
254 // This is split off so e.g. VertexAI can use it
255 async *handleStreamResponse(response: any, model: string) {
256 let lastToolUseId: string | undefined;
257 let lastToolUseName: string | undefined;
258
259 const usage: CompletionUsage = {
260 completion_tokens: 0,
261 prompt_tokens: 0,
262 total_tokens: 0,
263 };
264 for await (const value of streamSse(response as any)) {
265 // https://docs.anthropic.com/en/api/messages-streaming#event-types
266 switch (value.type) {
267 case "content_block_start":
268 if (value.content_block.type === "tool_use") {
269 lastToolUseId = value.content_block.id;
270 lastToolUseName = value.content_block.name;
271 }
272 break;
273 case "message_start":
274 usage.prompt_tokens = value.message.usage?.input_tokens ?? 0;
275 usage.prompt_tokens_details = {
276 cached_tokens: value.message.usage?.cache_read_input_tokens ?? 0,
277 };
278 break;
279 case "message_delta":
280 usage.completion_tokens = value.usage?.output_tokens ?? 0;
281 break;
282 case "content_block_delta":
283 // https://docs.anthropic.com/en/api/messages-streaming#delta-types
284 switch (value.delta.type) {
285 case "text_delta":
286 yield chatChunk({
287 content: value.delta.text,
288 model,
289 });
290 break;
291 case "input_json_delta":
292 if (!lastToolUseId || !lastToolUseName) {
293 throw new Error("No tool use found");
294 }
295 yield chatChunkFromDelta({
296 model,
297 delta: {
298 tool_calls: [
299 {
300 id: lastToolUseId,
301 type: "function",
302 index: 0,
303 function: {
304 name: lastToolUseName,
305 arguments: value.delta.partial_json,
306 },
307 },
308 ],
309 },
310 });
311 break;
312 }
313 break;
314 case "content_block_stop":
315 lastToolUseId = undefined;
316 lastToolUseName = undefined;
317 break;
318 default:
319 break;
320 }
321 }
322
323 yield usageChatChunk({
324 model,
325 usage: {
326 ...usage,
327 total_tokens: usage.completion_tokens + usage.prompt_tokens,
328 },
329 });
330 }
331
332 async *chatCompletionStream(
333 body: ChatCompletionCreateParamsStreaming,
334 signal: AbortSignal,
335 ): AsyncGenerator<ChatCompletionChunk, any, unknown> {
336 body.messages;
337 const response = await customFetch(this.config.requestOptions)(
338 new URL("messages", this.apiBase),
339 {
340 method: "POST",
341 headers: {
342 "Content-Type": "application/json",
343 Accept: "application/json",
344 "anthropic-version": "2023-06-01",
345 "anthropic-beta": "prompt-caching-2024-07-31",
346 "x-api-key": this.config.apiKey,
347 },
348 body: JSON.stringify(this._convertBody(body)),
349 signal,
350 },
351 );
352 yield* this.handleStreamResponse(response, body.model);
353 }
354 async completionNonStream(
355 body: CompletionCreateParamsNonStreaming,
356 signal: AbortSignal,
357 ): Promise<Completion> {
358 throw new Error("Method not implemented.");
359 }
360 async *completionStream(
361 body: CompletionCreateParamsStreaming,
362 signal: AbortSignal,
363 ): AsyncGenerator<Completion, any, unknown> {
364 throw new Error("Method not implemented.");
365 }
366 async *fimStream(
367 body: FimCreateParamsStreaming,
368 signal: AbortSignal,
369 ): AsyncGenerator<ChatCompletionChunk, any, unknown> {
370 throw new Error("Method not implemented.");
371 }
372
373 async embed(
374 body: OpenAI.Embeddings.EmbeddingCreateParams,
375 ): Promise<OpenAI.Embeddings.CreateEmbeddingResponse> {
376 throw new Error("Method not implemented.");
377 }
378
379 async rerank(body: RerankCreateParams): Promise<CreateRerankResponse> {
380 throw new Error("Method not implemented.");
381 }
382
383 list(): Promise<OpenAI.Models.Model[]> {
384 throw new Error("Method not implemented.");
385 }
386}