Elffuss BraidHub

kikocis/continue public

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