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