Elffuss BraidHub

kikocis/continue public

main · 14.3 KiBRawPermalink
1import { streamResponse } from "@continuedev/fetch";
2import { v4 as uuidv4 } from "uuid";
3import {
4 AssistantChatMessage,
5 ChatMessage,
6 CompletionOptions,
7 LLMOptions,
8 MessagePart,
9 TextMessagePart,
10 ToolCallDelta,
11} from "../../index.js";
12import { safeParseToolCallArgs } from "../../tools/parseArgs.js";
13import { renderChatMessage, stripImages } from "../../util/messageContent.js";
14import { BaseLLM } from "../index.js";
15import {
16 GeminiChatContent,
17 GeminiChatContentPart,
18 GeminiChatRequestBody,
19 GeminiChatResponse,
20 GeminiGenerationConfig,
21 GeminiToolFunctionDeclaration,
22 convertContinueToolToGeminiFunction,
23} from "./gemini-types";
24
25class Gemini extends BaseLLM {
26 static providerName = "gemini";
27
28 static defaultOptions: Partial<LLMOptions> = {
29 model: "gemini-pro",
30 apiBase: "https://generativelanguage.googleapis.com/v1beta/",
31 maxStopWords: 5,
32 maxEmbeddingBatchSize: 100,
33 };
34
35 // Function to convert completion options to Gemini format
36 public convertArgs(options: CompletionOptions): GeminiGenerationConfig {
37 // should be public for use within VertexAI
38 const finalOptions: any = {}; // Initialize an empty object
39
40 // Map known options
41 if (options.topK) {
42 finalOptions.topK = options.topK;
43 }
44 if (options.topP) {
45 finalOptions.topP = options.topP;
46 }
47 if (options.temperature !== undefined && options.temperature !== null) {
48 finalOptions.temperature = options.temperature;
49 }
50 if (options.maxTokens) {
51 finalOptions.maxOutputTokens = options.maxTokens;
52 }
53 if (options.stop) {
54 finalOptions.stopSequences = options.stop
55 .filter((x) => x.trim() !== "")
56 .slice(0, this.maxStopWords ?? Gemini.defaultOptions.maxStopWords);
57 }
58
59 return finalOptions;
60 }
61
62 protected async *_streamComplete(
63 prompt: string,
64 signal: AbortSignal,
65 options: CompletionOptions,
66 ): AsyncGenerator<string> {
67 for await (const message of this._streamChat(
68 [{ content: prompt, role: "user" }],
69 signal,
70 options,
71 )) {
72 yield renderChatMessage(message);
73 }
74 }
75
76 /**
77 * Removes the system message and merges it with the next user message if present.
78 * @param messages Array of chat messages
79 * @returns Modified array with system message merged into user message if applicable
80 */
81 public removeSystemMessage(messages: ChatMessage[]): ChatMessage[] {
82 // If no messages or first message isn't system, return copy of original messages
83 if (messages.length === 0 || messages[0]?.role !== "system") {
84 return [...messages];
85 }
86
87 // Extract system message
88 const systemMessage: ChatMessage = messages[0];
89
90 // Extract system content based on its type
91 let systemContent = "";
92
93 if (typeof systemMessage.content === "string") {
94 systemContent = systemMessage.content;
95 } else if (Array.isArray(systemMessage.content)) {
96 const contentArray: Array<MessagePart> =
97 systemMessage.content as Array<MessagePart>;
98
99 const concatenatedText = contentArray
100 .filter((part): part is TextMessagePart => part.type === "text")
101 .map((part) => part.text)
102 .join(" ");
103
104 systemContent = concatenatedText ? concatenatedText : "";
105 } else if (
106 systemMessage.content &&
107 typeof systemMessage.content === "object"
108 ) {
109 const typedContent = systemMessage.content as TextMessagePart;
110 systemContent = typedContent?.text || "";
111 }
112
113 // Create new array without the system message
114 const remainingMessages: ChatMessage[] = messages.slice(1);
115
116 // Check if there's a user message to merge with
117 if (remainingMessages.length > 0 && remainingMessages[0].role === "user") {
118 const userMessage: ChatMessage = remainingMessages[0];
119 const prefix = `System message - follow these instructions in every response: ${systemContent}\n\n---\n\n`;
120
121 // Merge based on user content type
122 if (typeof userMessage.content === "string") {
123 userMessage.content = prefix + userMessage.content;
124 } else if (Array.isArray(userMessage.content)) {
125 const contentArray: Array<MessagePart> =
126 userMessage.content as Array<MessagePart>;
127 const textPart = contentArray.find((part) => part.type === "text") as
128 | TextMessagePart
129 | undefined;
130
131 if (textPart) {
132 textPart.text = prefix + textPart.text;
133 } else {
134 userMessage.content.push({
135 type: "text",
136 text: prefix,
137 } as TextMessagePart);
138 }
139 } else if (
140 userMessage.content &&
141 typeof userMessage.content === "object"
142 ) {
143 const typedContent = userMessage.content as TextMessagePart;
144 userMessage.content = [
145 {
146 type: "text",
147 text: prefix + (typedContent.text || ""),
148 } as TextMessagePart,
149 ];
150 }
151 }
152
153 return remainingMessages;
154 }
155
156 protected async *_streamChat(
157 messages: ChatMessage[],
158 signal: AbortSignal,
159 options: CompletionOptions,
160 ): AsyncGenerator<ChatMessage> {
161 const isV1API = this.apiBase?.includes("/v1/");
162
163 const convertedMsgs = isV1API
164 ? this.removeSystemMessage(messages)
165 : messages;
166
167 if (options.model.includes("bison")) {
168 for await (const message of this.streamChatBison(
169 convertedMsgs,
170 signal,
171 options,
172 )) {
173 yield message;
174 }
175 } else {
176 for await (const message of this.streamChatGemini(
177 convertedMsgs,
178 signal,
179 options,
180 )) {
181 yield message;
182 }
183 }
184 }
185
186 continuePartToGeminiPart(part: MessagePart): GeminiChatContentPart {
187 return part.type === "text"
188 ? {
189 text: part.text,
190 }
191 : {
192 inlineData: {
193 mimeType: "image/jpeg",
194 data: part.imageUrl?.url.split(",")[1],
195 },
196 };
197 }
198
199 public prepareBody(
200 messages: ChatMessage[],
201 options: CompletionOptions,
202 isV1API: boolean,
203 includeToolIds: boolean,
204 ): GeminiChatRequestBody {
205 const toolCallIdToNameMap = new Map<string, string>();
206 messages.forEach((msg) => {
207 if (msg.role === "assistant" && msg.toolCalls) {
208 msg.toolCalls.forEach((call) => {
209 if (call.id && call.function?.name) {
210 toolCallIdToNameMap.set(call.id, call.function.name);
211 }
212 });
213 }
214 });
215 const systemMessage = messages.find(
216 (msg) => msg.role === "system",
217 )?.content;
218
219 const body: GeminiChatRequestBody = {
220 contents: messages
221 .filter((msg) => !(msg.role === "system" && isV1API))
222 .map((msg) => {
223 if (msg.role === "tool") {
224 let functionName = toolCallIdToNameMap.get(msg.toolCallId);
225 if (!functionName) {
226 console.warn(
227 "Sending tool call response for unidentified tool call",
228 );
229 }
230 return {
231 role: "user",
232 parts: [
233 {
234 functionResponse: {
235 id: includeToolIds ? msg.toolCallId : undefined,
236 name: functionName || "unknown",
237 response: {
238 output: msg.content, // "output" key is opinionated - not all functions will output objects
239 },
240 },
241 },
242 ],
243 };
244 }
245 if (msg.role === "assistant") {
246 const assistantMsg: GeminiChatContent = {
247 role: "model",
248 parts:
249 typeof msg.content === "string"
250 ? [{ text: msg.content }]
251 : msg.content.map(this.continuePartToGeminiPart),
252 };
253 if (msg.toolCalls) {
254 msg.toolCalls.forEach((toolCall) => {
255 if (toolCall.function?.name) {
256 assistantMsg.parts.push({
257 functionCall: {
258 name: toolCall.function.name,
259 args: safeParseToolCallArgs(toolCall),
260 },
261 });
262 }
263 });
264 }
265 return assistantMsg;
266 }
267 return {
268 role: "user",
269 parts:
270 typeof msg.content === "string"
271 ? [{ text: msg.content }]
272 : msg.content.map(this.continuePartToGeminiPart),
273 };
274 }),
275 };
276 if (options) {
277 body.generationConfig = this.convertArgs(options);
278 }
279
280 // https://ai.google.dev/gemini-api/docs/api-versions
281 if (!isV1API) {
282 if (systemMessage) {
283 body.systemInstruction = {
284 parts: [{ text: stripImages(systemMessage) }],
285 };
286 }
287 // Convert and add tools if present
288 if (options.tools?.length) {
289 // Choosing to map all tools to the functionDeclarations of one tool
290 // Rather than map each tool to its own tool + functionDeclaration
291 // Same difference
292 const functions: GeminiToolFunctionDeclaration[] = [];
293 options.tools.forEach((tool) => {
294 try {
295 functions.push(convertContinueToolToGeminiFunction(tool));
296 } catch (e) {
297 console.warn(
298 `Failed to convert tool to gemini function definition. Skipping: ${JSON.stringify(tool, null, 2)}`,
299 );
300 }
301 });
302 if (functions.length) {
303 body.tools = [
304 {
305 functionDeclarations: functions,
306 },
307 ];
308 }
309 }
310 }
311 return body;
312 }
313
314 public async *processGeminiResponse(
315 stream: AsyncIterable<string>,
316 ): AsyncGenerator<ChatMessage> {
317 let buffer = "";
318 for await (const chunk of stream) {
319 buffer += chunk;
320 if (buffer.startsWith("[")) {
321 buffer = buffer.slice(1);
322 }
323 if (buffer.endsWith("]")) {
324 buffer = buffer.slice(0, -1);
325 }
326 if (buffer.startsWith(",")) {
327 buffer = buffer.slice(1);
328 }
329
330 const parts = buffer.split("\n,");
331
332 let foundIncomplete = false;
333 for (let i = 0; i < parts.length; i++) {
334 const part = parts[i];
335 let data: GeminiChatResponse;
336 try {
337 data = JSON.parse(part) as GeminiChatResponse;
338 } catch (e) {
339 foundIncomplete = true;
340 continue; // yo!
341 }
342
343 if ("error" in data) {
344 throw new Error(data.error.message);
345 }
346
347 // In case of max tokens reached, gemini will sometimes return content with no parts, even though that doesn't match the API spec
348 const contentParts = data?.candidates?.[0]?.content?.parts;
349 if (contentParts) {
350 const textParts: MessagePart[] = [];
351 const toolCalls: ToolCallDelta[] = [];
352
353 for (const part of contentParts) {
354 if ("text" in part) {
355 textParts.push({ type: "text", text: part.text });
356 } else if ("functionCall" in part) {
357 toolCalls.push({
358 type: "function",
359 id: part.functionCall.id ?? uuidv4(),
360 function: {
361 name: part.functionCall.name,
362 arguments:
363 typeof part.functionCall.args === "string"
364 ? part.functionCall.args
365 : JSON.stringify(part.functionCall.args),
366 },
367 });
368 } else {
369 // Note: function responses shouldn't be streamed, images not supported
370 console.warn("Unsupported gemini part type received", part);
371 }
372 }
373
374 const assistantMessage: AssistantChatMessage = {
375 role: "assistant",
376 content: textParts.length ? textParts : "",
377 };
378 if (toolCalls.length > 0) {
379 assistantMessage.toolCalls = toolCalls;
380 }
381 if (textParts.length || toolCalls.length) {
382 yield assistantMessage;
383 }
384 } else {
385 // Handle the case where the expected data structure is not found
386 console.warn("Unexpected response format:", data);
387 }
388 }
389 if (foundIncomplete) {
390 buffer = parts[parts.length - 1];
391 } else {
392 buffer = "";
393 }
394 }
395 }
396
397 private async *streamChatGemini(
398 messages: ChatMessage[],
399 signal: AbortSignal,
400 options: CompletionOptions,
401 ): AsyncGenerator<ChatMessage> {
402 const apiURL = new URL(
403 `models/${options.model}:streamGenerateContent?key=${this.apiKey}`,
404 this.apiBase,
405 );
406
407 const isV1API = !!this.apiBase?.includes("/v1/");
408
409 // Convert chat messages to contents
410 const body = this.prepareBody(messages, options, isV1API, true);
411
412 const response = await this.fetch(apiURL, {
413 method: "POST",
414 body: JSON.stringify(body),
415 signal,
416 });
417 for await (const message of this.processGeminiResponse(
418 streamResponse(response),
419 )) {
420 yield message;
421 }
422 }
423 private async *streamChatBison(
424 messages: ChatMessage[],
425 signal: AbortSignal,
426 options: CompletionOptions,
427 ): AsyncGenerator<ChatMessage> {
428 const msgList = [];
429 for (const message of messages) {
430 msgList.push({ content: message.content });
431 }
432
433 const apiURL = new URL(
434 `models/${options.model}:generateMessage?key=${this.apiKey}`,
435 this.apiBase,
436 );
437 const body = { prompt: { messages: msgList } };
438 const response = await this.fetch(apiURL, {
439 method: "POST",
440 body: JSON.stringify(body),
441 signal,
442 });
443 if (response.status === 499) {
444 return; // Aborted by user
445 }
446 const data = await response.json();
447 yield { role: "assistant", content: data.candidates[0].content };
448 }
449
450 async _embed(batch: string[]): Promise<number[][]> {
451 // Batch embed endpoint: https://ai.google.dev/api/embeddings?authuser=1#EmbedContentRequest
452 const requests = batch.map((text) => ({
453 model: this.model,
454 content: {
455 role: "user",
456 parts: [{ text }],
457 },
458 }));
459
460 const resp = await this.fetch(
461 new URL(`${this.model}:batchEmbedContents`, this.apiBase),
462 {
463 method: "POST",
464 body: JSON.stringify({
465 requests,
466 }),
467 headers: {
468 "x-goog-api-key": this.apiKey,
469 "Content-Type": "application/json",
470 } as any,
471 },
472 );
473
474 if (!resp.ok) {
475 throw new Error(await resp.text());
476 }
477
478 const data = (await resp.json()) as any;
479
480 return data.embeddings.map((embedding: any) => embedding.values);
481 }
482}
483
484export default Gemini;