Elffuss BraidHub

kikocis/continue public

3ecf862e2425 · 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 ): GeminiChatRequestBody {
204 const toolCallIdToNameMap = new Map<string, string>();
205 messages.forEach((msg) => {
206 if (msg.role === "assistant" && msg.toolCalls) {
207 msg.toolCalls.forEach((call) => {
208 if (call.id && call.function?.name) {
209 toolCallIdToNameMap.set(call.id, call.function.name);
210 }
211 });
212 }
213 });
214 const systemMessage = messages.find(
215 (msg) => msg.role === "system",
216 )?.content;
217
218 const body: GeminiChatRequestBody = {
219 contents: messages
220 .filter((msg) => !(msg.role === "system" && isV1API))
221 .map((msg) => {
222 if (msg.role === "tool") {
223 let functionName = toolCallIdToNameMap.get(msg.toolCallId);
224 if (!functionName) {
225 console.warn(
226 "Sending tool call response for unidentified tool call",
227 );
228 }
229 return {
230 role: "user",
231 parts: [
232 {
233 functionResponse: {
234 id: msg.toolCallId,
235 name: functionName || "unknown",
236 response: {
237 output: msg.content, // "output" key is opinionated - not all functions will output objects
238 },
239 },
240 },
241 ],
242 };
243 }
244 if (msg.role === "assistant") {
245 const assistantMsg: GeminiChatContent = {
246 role: "model",
247 parts:
248 typeof msg.content === "string"
249 ? [{ text: msg.content }]
250 : msg.content.map(this.continuePartToGeminiPart),
251 };
252 if (msg.toolCalls) {
253 msg.toolCalls.forEach((toolCall) => {
254 if (toolCall.function?.name) {
255 assistantMsg.parts.push({
256 functionCall: {
257 name: toolCall.function.name,
258 args: safeParseToolCallArgs(toolCall),
259 },
260 });
261 }
262 });
263 }
264 return assistantMsg;
265 }
266 return {
267 role: "user",
268 parts:
269 typeof msg.content === "string"
270 ? [{ text: msg.content }]
271 : msg.content.map(this.continuePartToGeminiPart),
272 };
273 }),
274 };
275 if (options) {
276 body.generationConfig = this.convertArgs(options);
277 }
278
279 // https://ai.google.dev/gemini-api/docs/api-versions
280 if (!isV1API) {
281 if (systemMessage) {
282 body.systemInstruction = {
283 parts: [{ text: stripImages(systemMessage) }],
284 };
285 }
286 // Convert and add tools if present
287 if (options.tools?.length) {
288 // Choosing to map all tools to the functionDeclarations of one tool
289 // Rather than map each tool to its own tool + functionDeclaration
290 // Same difference
291 const functions: GeminiToolFunctionDeclaration[] = [];
292 options.tools.forEach((tool) => {
293 try {
294 functions.push(convertContinueToolToGeminiFunction(tool));
295 } catch (e) {
296 console.warn(
297 `Failed to convert tool to gemini function definition. Skipping: ${JSON.stringify(tool, null, 2)}`,
298 );
299 }
300 });
301 if (functions.length) {
302 body.tools = [
303 {
304 functionDeclarations: functions,
305 },
306 ];
307 }
308 }
309 }
310 return body;
311 }
312
313 public async *processGeminiResponse(
314 stream: AsyncIterable<string>,
315 ): AsyncGenerator<ChatMessage> {
316 let buffer = "";
317 for await (const chunk of stream) {
318 buffer += chunk;
319 if (buffer.startsWith("[")) {
320 buffer = buffer.slice(1);
321 }
322 if (buffer.endsWith("]")) {
323 buffer = buffer.slice(0, -1);
324 }
325 if (buffer.startsWith(",")) {
326 buffer = buffer.slice(1);
327 }
328
329 const parts = buffer.split("\n,");
330
331 let foundIncomplete = false;
332 for (let i = 0; i < parts.length; i++) {
333 const part = parts[i];
334 let data: GeminiChatResponse;
335 try {
336 data = JSON.parse(part) as GeminiChatResponse;
337 } catch (e) {
338 foundIncomplete = true;
339 continue; // yo!
340 }
341
342 if ("error" in data) {
343 throw new Error(data.error.message);
344 }
345
346 // In case of max tokens reached, gemini will sometimes return content with no parts, even though that doesn't match the API spec
347 const contentParts = data?.candidates?.[0]?.content?.parts;
348 if (contentParts) {
349 const textParts: MessagePart[] = [];
350 const toolCalls: ToolCallDelta[] = [];
351
352 for (const part of contentParts) {
353 if ("text" in part) {
354 textParts.push({ type: "text", text: part.text });
355 } else if ("functionCall" in part) {
356 toolCalls.push({
357 type: "function",
358 id: part.functionCall.id ?? uuidv4(),
359 function: {
360 name: part.functionCall.name,
361 arguments:
362 typeof part.functionCall.args === "string"
363 ? part.functionCall.args
364 : JSON.stringify(part.functionCall.args),
365 },
366 });
367 } else {
368 // Note: function responses shouldn't be streamed, images not supported
369 console.warn("Unsupported gemini part type received", part);
370 }
371 }
372
373 const assistantMessage: AssistantChatMessage = {
374 role: "assistant",
375 content: textParts.length ? textParts : "",
376 };
377 if (toolCalls.length > 0) {
378 assistantMessage.toolCalls = toolCalls;
379 }
380 if (textParts.length || toolCalls.length) {
381 yield assistantMessage;
382 }
383 } else {
384 // Handle the case where the expected data structure is not found
385 console.warn("Unexpected response format:", data);
386 }
387 }
388 if (foundIncomplete) {
389 buffer = parts[parts.length - 1];
390 } else {
391 buffer = "";
392 }
393 }
394 }
395
396 private async *streamChatGemini(
397 messages: ChatMessage[],
398 signal: AbortSignal,
399 options: CompletionOptions,
400 ): AsyncGenerator<ChatMessage> {
401 const apiURL = new URL(
402 `models/${options.model}:streamGenerateContent?key=${this.apiKey}`,
403 this.apiBase,
404 );
405
406 const isV1API = !!this.apiBase?.includes("/v1/");
407
408 // Convert chat messages to contents
409 const body = this.prepareBody(messages, options, isV1API);
410
411 const response = await this.fetch(apiURL, {
412 method: "POST",
413 body: JSON.stringify(body),
414 signal,
415 });
416 for await (const message of this.processGeminiResponse(
417 streamResponse(response),
418 )) {
419 yield message;
420 }
421 }
422 private async *streamChatBison(
423 messages: ChatMessage[],
424 signal: AbortSignal,
425 options: CompletionOptions,
426 ): AsyncGenerator<ChatMessage> {
427 const msgList = [];
428 for (const message of messages) {
429 msgList.push({ content: message.content });
430 }
431
432 const apiURL = new URL(
433 `models/${options.model}:generateMessage?key=${this.apiKey}`,
434 this.apiBase,
435 );
436 const body = { prompt: { messages: msgList } };
437 const response = await this.fetch(apiURL, {
438 method: "POST",
439 body: JSON.stringify(body),
440 signal,
441 });
442 if (response.status === 499) {
443 return; // Aborted by user
444 }
445 const data = await response.json();
446 yield { role: "assistant", content: data.candidates[0].content };
447 }
448
449 async _embed(batch: string[]): Promise<number[][]> {
450 // Batch embed endpoint: https://ai.google.dev/api/embeddings?authuser=1#EmbedContentRequest
451 const requests = batch.map((text) => ({
452 model: this.model,
453 content: {
454 role: "user",
455 parts: [{ text }],
456 },
457 }));
458
459 const resp = await this.fetch(
460 new URL(`${this.model}:batchEmbedContents`, this.apiBase),
461 {
462 method: "POST",
463 body: JSON.stringify({
464 requests,
465 }),
466 headers: {
467 "x-goog-api-key": this.apiKey,
468 "Content-Type": "application/json",
469 } as any,
470 },
471 );
472
473 if (!resp.ok) {
474 throw new Error(await resp.text());
475 }
476
477 const data = (await resp.json()) as any;
478
479 return data.embeddings.map((embedding: any) => embedding.values);
480 }
481}
482
483export default Gemini;