Elffuss BraidHub

kikocis/continue public

e8ee99375f3e · 11.0 KiBRawPermalink
1import { streamResponse } from "@continuedev/fetch";
2import { OpenAI } from "openai/index";
3import {
4 ChatCompletion,
5 ChatCompletionChunk,
6 ChatCompletionCreateParams,
7 ChatCompletionCreateParamsNonStreaming,
8 ChatCompletionCreateParamsStreaming,
9 Completion,
10 CompletionCreateParamsNonStreaming,
11 CompletionCreateParamsStreaming,
12 CreateEmbeddingResponse,
13 EmbeddingCreateParams,
14 Model,
15} from "openai/resources/index";
16
17import { v4 as uuidv4 } from "uuid";
18import { GeminiConfig } from "../types.js";
19import {
20 chatChunk,
21 chatChunkFromDelta,
22 customFetch,
23 embedding,
24} from "../util.js";
25import {
26 convertOpenAIToolToGeminiFunction,
27 GeminiChatContent,
28 GeminiChatContentPart,
29 GeminiToolFunctionDeclaration,
30} from "../util/gemini-types.js";
31import { safeParseArgs } from "../util/parseArgs.js";
32import {
33 BaseLlmApi,
34 CreateRerankResponse,
35 FimCreateParamsStreaming,
36 RerankCreateParams,
37} from "./base.js";
38
39export class GeminiApi implements BaseLlmApi {
40 apiBase: string = "https://generativelanguage.googleapis.com/v1beta/";
41
42 static maxStopSequences = 5;
43
44 constructor(protected config: GeminiConfig) {
45 this.apiBase = config.apiBase ?? this.apiBase;
46 }
47
48 private _convertMessages(
49 msgs: OpenAI.Chat.Completions.ChatCompletionMessageParam[],
50 ): any[] {
51 return msgs.map((m) => ({
52 role: m.role === "assistant" ? "CHATBOT" : "USER",
53 message: m.content,
54 }));
55 }
56
57 private _oaiPartToGeminiPart(
58 part:
59 | OpenAI.Chat.Completions.ChatCompletionContentPart
60 | OpenAI.Chat.Completions.ChatCompletionContentPartRefusal,
61 ): GeminiChatContentPart {
62 switch (part.type) {
63 case "refusal":
64 return {
65 text: part.refusal,
66 };
67 case "text":
68 return {
69 text: part.text,
70 };
71 case "input_audio":
72 throw new Error("Unsupported part type: input_audio");
73 case "image_url":
74 default:
75 return {
76 inlineData: {
77 mimeType: "image/jpeg",
78 data: part.image_url?.url.split(",")[1],
79 },
80 };
81 }
82 }
83
84 private _convertBody(oaiBody: ChatCompletionCreateParams, url: string) {
85 const generationConfig: any = {};
86
87 if (oaiBody.top_p) {
88 generationConfig.topP = oaiBody.top_p;
89 }
90 if (oaiBody.temperature !== undefined && oaiBody.temperature !== null) {
91 generationConfig.temperature = oaiBody.temperature;
92 }
93 if (oaiBody.max_tokens) {
94 generationConfig.maxOutputTokens = oaiBody.max_tokens;
95 }
96 if (oaiBody.stop) {
97 const stop = Array.isArray(oaiBody.stop) ? oaiBody.stop : [oaiBody.stop];
98 generationConfig.stopSequences = stop.filter((x) => x.trim() !== "");
99 }
100
101 const isV1API = url.includes("/v1/");
102
103 const toolCallIdToNameMap = new Map<string, string>();
104 oaiBody.messages.forEach((msg) => {
105 if (msg.role === "assistant" && msg.tool_calls) {
106 msg.tool_calls.forEach((call) => {
107 toolCallIdToNameMap.set(call.id, call.function.name);
108 });
109 }
110 });
111
112 const contents: (GeminiChatContent | null)[] = oaiBody.messages
113 .map((msg) => {
114 if (msg.role === "system" && !isV1API) {
115 return null; // Don't include system message in contents
116 }
117
118 if (msg.role === "assistant" && msg.tool_calls?.length) {
119 for (const toolCall of msg.tool_calls) {
120 toolCallIdToNameMap.set(toolCall.id, toolCall.function.name);
121 }
122
123 return {
124 role: "model" as const,
125 parts: msg.tool_calls.map((toolCall) => ({
126 functionCall: {
127 id: toolCall.id,
128 name: toolCall.function.name,
129 args: safeParseArgs(
130 toolCall.function.arguments,
131 `Call: ${toolCall.function.name} ${toolCall.id}`,
132 ),
133 },
134 })),
135 };
136 }
137
138 if (msg.role === "tool") {
139 const functionName = toolCallIdToNameMap.get(msg.tool_call_id);
140 return {
141 role: "user" as const,
142 parts: [
143 {
144 functionResponse: {
145 id: msg.tool_call_id,
146 name: functionName ?? "unknown",
147 response: {
148 content:
149 typeof msg.content === "string"
150 ? msg.content
151 : msg.content.map((part) => part.text).join(""),
152 },
153 },
154 },
155 ],
156 };
157 }
158
159 if (!msg.content) {
160 return null;
161 }
162
163 return {
164 role:
165 msg.role === "assistant" ? ("model" as const) : ("user" as const),
166 parts:
167 typeof msg.content === "string"
168 ? [{ text: msg.content }]
169 : msg.content.map(this._oaiPartToGeminiPart),
170 };
171 })
172 .filter((c) => c !== null);
173
174 const sysMsg = oaiBody.messages.find((msg) => msg.role === "system");
175 const finalBody: any = {
176 generationConfig,
177 contents,
178 // if there is a system message, reformat it for Gemini API
179 ...(sysMsg &&
180 !isV1API && {
181 systemInstruction: { parts: [{ text: sysMsg.content }] },
182 }),
183 };
184
185 if (!isV1API) {
186 // Convert and add tools if present
187 if (oaiBody.tools?.length) {
188 // Choosing to map all tools to the functionDeclarations of one tool
189 // Rather than map each tool to its own tool + functionDeclaration
190 // Same difference
191 const functions: GeminiToolFunctionDeclaration[] = [];
192 oaiBody.tools.forEach((tool) => {
193 try {
194 functions.push(convertOpenAIToolToGeminiFunction(tool));
195 } catch (e) {
196 console.warn(
197 `Failed to convert tool to gemini function definition. Skipping: ${JSON.stringify(tool, null, 2)}`,
198 );
199 }
200 });
201
202 if (functions.length) {
203 finalBody.tools = [
204 {
205 functionDeclarations: functions,
206 },
207 ];
208 }
209 }
210 }
211
212 return finalBody;
213 }
214
215 async chatCompletionNonStream(
216 body: ChatCompletionCreateParamsNonStreaming,
217 signal: AbortSignal,
218 ): Promise<ChatCompletion> {
219 let completion = "";
220 for await (const chunk of this.chatCompletionStream(
221 {
222 ...body,
223 stream: true,
224 },
225 signal,
226 )) {
227 completion += chunk.choices[0].delta.content;
228 }
229 return {
230 id: "",
231 object: "chat.completion",
232 model: body.model,
233 created: Date.now(),
234 choices: [
235 {
236 index: 0,
237 logprobs: null,
238 finish_reason: "stop",
239 message: {
240 role: "assistant",
241 content: completion,
242 refusal: null,
243 },
244 },
245 ],
246 usage: undefined,
247 };
248 }
249
250 async *chatCompletionStream(
251 body: ChatCompletionCreateParamsStreaming,
252 signal: AbortSignal,
253 ): AsyncGenerator<ChatCompletionChunk> {
254 const apiURL = new URL(
255 `models/${body.model}:streamGenerateContent?key=${this.config.apiKey}`,
256 this.apiBase,
257 ).toString();
258 const convertedBody = this._convertBody(body, apiURL);
259 const resp = await customFetch(this.config.requestOptions)(apiURL, {
260 method: "POST",
261 body: JSON.stringify(convertedBody),
262 signal,
263 });
264
265 let buffer = "";
266 for await (const chunk of streamResponse(resp as any)) {
267 buffer += chunk;
268 if (buffer.startsWith("[")) {
269 buffer = buffer.slice(1);
270 }
271 if (buffer.endsWith("]")) {
272 buffer = buffer.slice(0, -1);
273 }
274 if (buffer.startsWith(",")) {
275 buffer = buffer.slice(1);
276 }
277
278 const parts = buffer.split("\n,");
279
280 let foundIncomplete = false;
281 for (let i = 0; i < parts.length; i++) {
282 const part = parts[i];
283 let data;
284 try {
285 data = JSON.parse(part);
286 } catch (e) {
287 foundIncomplete = true;
288 continue; // yo!
289 }
290 if (data.error) {
291 throw new Error(data.error.message);
292 }
293
294 // In case of max tokens reached, gemini will sometimes return content with no parts, even though that doesn't match the API spec
295 const contentParts = data?.candidates?.[0]?.content?.parts;
296 if (contentParts) {
297 for (const part of contentParts) {
298 if ("text" in part) {
299 yield chatChunk({
300 content: part.text,
301 model: body.model,
302 });
303 } else if ("functionCall" in part) {
304 yield chatChunkFromDelta({
305 model: body.model,
306 delta: {
307 tool_calls: [
308 {
309 index: 0,
310 id: part.functionCall.id ?? uuidv4(),
311 type: "function",
312 function: {
313 name: part.functionCall.name,
314 arguments: JSON.stringify(part.functionCall.args),
315 },
316 },
317 ],
318 },
319 });
320 }
321 }
322 } else {
323 console.warn("Unexpected response format:", data);
324 }
325 }
326 if (foundIncomplete) {
327 buffer = parts[parts.length - 1];
328 } else {
329 buffer = "";
330 }
331 }
332 }
333 completionNonStream(
334 body: CompletionCreateParamsNonStreaming,
335 ): Promise<Completion> {
336 throw new Error("Method not implemented.");
337 }
338 completionStream(
339 body: CompletionCreateParamsStreaming,
340 ): AsyncGenerator<Completion> {
341 throw new Error("Method not implemented.");
342 }
343 fimStream(
344 body: FimCreateParamsStreaming,
345 ): AsyncGenerator<ChatCompletionChunk> {
346 throw new Error("Method not implemented.");
347 }
348 async rerank(body: RerankCreateParams): Promise<CreateRerankResponse> {
349 throw new Error("Method not implemented.");
350 }
351
352 async embed(body: EmbeddingCreateParams): Promise<CreateEmbeddingResponse> {
353 const inputs = Array.isArray(body.input) ? body.input : [body.input];
354 const response = await customFetch(this.config.requestOptions)(
355 new URL(`${body.model}:batchEmbedContents`, this.apiBase),
356 {
357 method: "POST",
358 body: JSON.stringify({
359 requests: inputs.map((input) => ({
360 model: body.model,
361 content: {
362 role: "user",
363 parts: [{ text: input }],
364 },
365 })),
366 }),
367 headers: {
368 // eslint-disable-next-line @typescript-eslint/naming-convention
369 "x-goog-api-key": this.config.apiKey,
370 // eslint-disable-next-line @typescript-eslint/naming-convention
371 "Content-Type": "application/json",
372 },
373 },
374 );
375
376 const data = (await response.json()) as any;
377 return embedding({
378 model: body.model,
379 usage: {
380 total_tokens: data.total_tokens,
381 prompt_tokens: data.prompt_tokens,
382 },
383 data: data.batchEmbedContents.map((embedding: any) => embedding.values),
384 });
385 }
386
387 list(): Promise<Model[]> {
388 throw new Error("Method not implemented.");
389 }
390}