Elffuss BraidHub

kikocis/continue public

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