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