From c6cd7188eac21e073a49e856238f271518b2e7b7 Mon Sep 17 00:00:00 2001 From: Luke Lashley Date: Fri, 7 Feb 2025 10:59:37 -0500 Subject: [PATCH 1/5] Fix two bugs introduced by previous updates --- core/llm/llms/Gemini.ts | 78 +++++++++++++++++++------------- core/llm/llms/VertexAI.ts | 93 +++------------------------------------ core/llm/toolSupport.ts | 5 +++ 3 files changed, 59 insertions(+), 117 deletions(-) diff --git a/core/llm/llms/Gemini.ts b/core/llm/llms/Gemini.ts index 4c0fb189b..5c9cf0a4e 100644 --- a/core/llm/llms/Gemini.ts +++ b/core/llm/llms/Gemini.ts @@ -135,21 +135,11 @@ class Gemini extends BaseLLM { }; } - private async *streamChatGemini( + public prepareBody( messages: ChatMessage[], - signal: AbortSignal, options: CompletionOptions, - ): AsyncGenerator { - const apiURL = new URL( - `models/${options.model}:streamGenerateContent?key=${this.apiKey}`, - this.apiBase, - ); - // This feels hacky to repeat code from above function but was the quickest - // way to ensure system message re-formatting isn't done if user has specified v1 - const apiBase = this.apiBase || Gemini.defaultOptions.apiBase!; // Determine if it's a v1 API call based on apiBase - const isV1API = apiBase.includes("/v1/"); - - // Convert chat messages to contents + isV1API: boolean, + ): GeminiChatRequestBody { const body: GeminiChatRequestBody = { contents: messages .filter((msg) => !(msg.role === "system" && isV1API)) @@ -253,7 +243,7 @@ class Gemini extends BaseLLM { } // Helper function to recursively clean JSON Schema objects const cleanJsonSchema = (schema: any): any => { - if (!schema || typeof schema !== 'object') return schema; + if (!schema || typeof schema !== "object") return schema; if (Array.isArray(schema)) { return schema.map(cleanJsonSchema); @@ -273,7 +263,7 @@ class Gemini extends BaseLLM { ...acc, [key]: cleanJsonSchema(value), }), - {} + {}, ); } @@ -304,15 +294,14 @@ class Gemini extends BaseLLM { } } } + return body; + } - const response = await this.fetch(apiURL, { - method: "POST", - body: JSON.stringify(body), - signal, - }); - + public async *processGeminiResponse( + stream: AsyncIterable, + ): AsyncGenerator { let buffer = ""; - for await (const chunk of streamResponse(response)) { + for await (const chunk of stream) { buffer += chunk; if (buffer.startsWith("[")) { buffer = buffer.slice(1); @@ -349,8 +338,8 @@ class Gemini extends BaseLLM { // Process all parts first to maintain order const processedParts: Array<{ - type: 'content' | 'tool' | 'toolCall', - data: any + type: "content" | "tool" | "toolCall"; + data: any; }> = []; for (const part of content.parts) { @@ -366,7 +355,7 @@ class Gemini extends BaseLLM { } else if ("functionCall" in part) { // Queue function call processedParts.push({ - type: 'toolCall', + type: "toolCall", data: { type: "function", id: "", // Not supported by gemini @@ -377,17 +366,17 @@ class Gemini extends BaseLLM { ? part.functionCall.args : JSON.stringify(part.functionCall.args), }, - } + }, }); } else if ("functionResponse" in part) { // Queue function response processedParts.push({ - type: 'tool', + type: "tool", data: { role: "tool", content: part.functionResponse.response.output as string, toolCallId: part.functionResponse.name, - } + }, }); } else { console.warn("Unsupported gemini part type received", part); @@ -404,13 +393,13 @@ class Gemini extends BaseLLM { // Then process tool calls and responses in order for (const part of processedParts) { - if (part.type === 'toolCall') { + if (part.type === "toolCall") { yield { role: "assistant", content: "", toolCalls: [part.data], }; - } else if (part.type === 'tool') { + } else if (part.type === "tool") { yield part.data; } } @@ -426,6 +415,35 @@ class Gemini extends BaseLLM { } } } + + private async *streamChatGemini( + messages: ChatMessage[], + signal: AbortSignal, + options: CompletionOptions, + ): AsyncGenerator { + const apiURL = new URL( + `models/${options.model}:streamGenerateContent?key=${this.apiKey}`, + this.apiBase, + ); + // This feels hacky to repeat code from above function but was the quickest + // way to ensure system message re-formatting isn't done if user has specified v1 + const apiBase = this.apiBase || Gemini.defaultOptions.apiBase!; // Determine if it's a v1 API call based on apiBase + const isV1API = apiBase.includes("/v1/"); + + // Convert chat messages to contents + const body = this.prepareBody(messages, options, isV1API); + + const response = await this.fetch(apiURL, { + method: "POST", + body: JSON.stringify(body), + signal, + }); + for await (const message of this.processGeminiResponse( + streamResponse(response), + )) { + yield message; + } + } private async *streamChatBison( messages: ChatMessage[], signal: AbortSignal, diff --git a/core/llm/llms/VertexAI.ts b/core/llm/llms/VertexAI.ts index 8d20c3212..fc6c53fae 100644 --- a/core/llm/llms/VertexAI.ts +++ b/core/llm/llms/VertexAI.ts @@ -143,97 +143,16 @@ class VertexAI extends BaseLLM { `publishers/google/models/${options.model}:streamGenerateContent`, this.apiBase, ); - // This feels hacky to repeat code from above function but was the quickest - // way to ensure system message re-formatting isn't done if user has specified v1 - const isV1API = this.apiBase.includes("/v1/"); - const contents = messages - .map((msg) => { - if (msg.role === "system" && !isV1API) { - return null; // Don't include system message in contents - } - if (msg.role === "tool") { - return null; - } - - return { - role: msg.role === "assistant" ? "model" : "user", - parts: - typeof msg.content === "string" - ? [{ text: msg.content }] - : msg.content.map(this.geminiInstance.continuePartToGeminiPart), - }; - }) - .filter((c) => c !== null); - - const body = { - ...this.geminiInstance.convertArgs(options), - contents, - // if this.systemMessage is defined, reformat it for Gemini API - ...(this.systemMessage && - !isV1API && { - systemInstruction: { parts: [{ text: this.systemMessage }] }, - }), - }; + const body = this.geminiInstance.prepareBody(messages, options, false); const response = await this.fetch(apiURL, { method: "POST", body: JSON.stringify(body), }); - - let buffer = ""; - for await (const chunk of streamResponse(response)) { - buffer += chunk; - if (buffer.startsWith("[")) { - buffer = buffer.slice(1); - } - if (buffer.endsWith("]")) { - buffer = buffer.slice(0, -1); - } - if (buffer.startsWith(",")) { - buffer = buffer.slice(1); - } - - const parts = buffer.split("\n,"); - - let foundIncomplete = false; - for (let i = 0; i < parts.length; i++) { - const part = parts[i]; - let data; - try { - data = JSON.parse(part); - } catch (e) { - foundIncomplete = true; - continue; // yo! - } - if (data.error) { - throw new Error(data.error.message); - } - // Check for existence of each level before accessing the final 'text' property - if (data?.candidates?.[0]?.content?.parts?.[0]?.text) { - // Incrementally stream the content to make it smoother - const content = data.candidates[0].content.parts[0].text; - const words = content.split(/(\s+)/); - const delaySeconds = Math.min(4.0 / (words.length + 1), 0.1); - while (words.length > 0) { - const wordsToYield = Math.min(3, words.length); - yield { - role: "assistant", - content: words.splice(0, wordsToYield).join(""), - }; - await delay(delaySeconds); - } - } else { - // Handle the case where the expected data structure is not found - if (data?.candidates?.[0]?.finishReason !== "STOP") { - console.warn("Unexpected response format:", data); - } - } - } - if (foundIncomplete) { - buffer = parts[parts.length - 1]; - } else { - buffer = ""; - } + for await (const message of this.geminiInstance.processGeminiResponse( + streamResponse(response), + )) { + yield message; } } @@ -445,7 +364,7 @@ class VertexAI extends BaseLLM { } const resp = await this.fetch( - new URL(this.apiBase + `/publishers/google/models/${this.model}:predict`), + new URL(this.apiBase + `publishers/google/models/${this.model}:predict`), { method: "POST", body: JSON.stringify({ diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index dd8f72fb0..bee55f7e3 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -21,6 +21,11 @@ export const PROVIDER_TOOL_SUPPORT: Record< // All gemini models support function calling return model.toLowerCase().includes("gemini"); }, + vertexai: (model) => { + // All gemini models except flash 2.0 lite support function calling + return model.toLowerCase().includes("gemini") && !model.toLowerCase().includes("lite");; + }, + // https://ollama.com/search?c=tools ollama: (model) => { if ( From f23d825d4d7ec10ad56d27961c55b8c98465db04 Mon Sep 17 00:00:00 2001 From: Luke Lashley Date: Tue, 18 Feb 2025 15:23:47 -0500 Subject: [PATCH 2/5] some extra embedding improvements --- core/llm/llms/VertexAI.ts | 9 ++++++++- extensions/vscode/config_schema.json | 6 +++--- packages/llm-info/src/providers/vertexai.ts | 12 ++++++------ 3 files changed, 17 insertions(+), 10 deletions(-) diff --git a/core/llm/llms/VertexAI.ts b/core/llm/llms/VertexAI.ts index fc6c53fae..9f52d3c6c 100644 --- a/core/llm/llms/VertexAI.ts +++ b/core/llm/llms/VertexAI.ts @@ -16,7 +16,7 @@ class VertexAI extends BaseLLM { declare geminiInstance: Gemini; static defaultOptions: Partial | undefined = { - maxEmbeddingBatchSize: 5, + maxEmbeddingBatchSize: 250, region: "us-central1", }; @@ -35,6 +35,13 @@ class VertexAI extends BaseLLM { } constructor(_options: LLMOptions) { + if (_options.region !== "us-central1") { + // Any region outside of us-central1 has a max batch size of 5. + _options.maxEmbeddingBatchSize = Math.min( + _options.maxEmbeddingBatchSize ?? 5, + 5, + ); + } super(_options); this.apiBase ??= VertexAI.getDefaultApiBaseFrom(_options); this.vertexProvider = diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index d9dab076b..104933472 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -2857,11 +2857,11 @@ "description": "The name of your VertexAI project" }, "region": { - "description": "The region your VertexAI model is hosted in - typically central1", - "default": "central1" + "description": "The region your VertexAI model is hosted in - typically us-central1", + "default": "us-central1" }, "model": { - "default": "text-embedding-004" + "default": "text-embedding-005" } }, "required": ["projectId", "model", "region"] diff --git a/packages/llm-info/src/providers/vertexai.ts b/packages/llm-info/src/providers/vertexai.ts index e9514bc25..6f7d24657 100644 --- a/packages/llm-info/src/providers/vertexai.ts +++ b/packages/llm-info/src/providers/vertexai.ts @@ -21,17 +21,17 @@ export const Gemini: ModelProvider = { }, // embed { - model: "text-embedding-004", + model: "text-embedding-005", displayName: "Vertex Text Embedding", recommendedFor: ["embed"], }, //autocomplete { - model: "code-gecko", - displayName: "VertexAI Code Gecko", - recommendedFor: ["autocomplete"], - maxCompletionTokens: 64, - } + model: "code-gecko", + displayName: "VertexAI Code Gecko", + recommendedFor: ["autocomplete"], + maxCompletionTokens: 64, + }, ], id: "gemini", displayName: "Gemini", From 74991cc333b6c565e5c885ee53b485b9bd51d33c Mon Sep 17 00:00:00 2001 From: Luke Lashley Date: Tue, 18 Feb 2025 15:49:08 -0500 Subject: [PATCH 3/5] fix docs --- docs/docs/customize/model-providers/top-level/vertexai.md | 4 ++-- .../current/customize/model-providers/top-level/vertexai.md | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/docs/customize/model-providers/top-level/vertexai.md b/docs/docs/customize/model-providers/top-level/vertexai.md index 50958cae0..f22fe7a9d 100644 --- a/docs/docs/customize/model-providers/top-level/vertexai.md +++ b/docs/docs/customize/model-providers/top-level/vertexai.md @@ -45,13 +45,13 @@ We recommend configuring **Codestral** or **code-gecko** as your autocomplete mo ## Embeddings model -We recommend configuring **text-embedding-004** as your embeddings model. +We recommend configuring **text-embedding-005** as your embeddings model. ```json title="config.json" { "embeddingsProvider": { "provider": "vertexai", - "model": "text-embedding-004", + "model": "text-embedding-005", "projectId": "[PROJECT_ID]", "region": "us-central1" } diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/vertexai.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/vertexai.md index daf966d9e..974ac69b8 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/vertexai.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/vertexai.md @@ -45,13 +45,13 @@ We recommend configuring **Codestral** or **code-gecko** as your autocomplete mo ## Embeddings model -We recommend configuring **text-embedding-004** as your embeddings model. +We recommend configuring **text-embedding-005** as your embeddings model. ```json title="config.json" { "embeddingsProvider": { "provider": "vertexai", - "model": "text-embedding-004", + "model": "text-embedding-005", "projectId": "[PROJECT_ID]", "region": "us-central1" } From 3e85ea05e9a71341f04fdaaf12bdf5ce580d1c09 Mon Sep 17 00:00:00 2001 From: Luke Date: Thu, 20 Feb 2025 11:28:26 -0500 Subject: [PATCH 4/5] Fix codestral --- core/llm/llms/VertexAI.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/core/llm/llms/VertexAI.ts b/core/llm/llms/VertexAI.ts index 9f52d3c6c..0e0910330 100644 --- a/core/llm/llms/VertexAI.ts +++ b/core/llm/llms/VertexAI.ts @@ -263,7 +263,9 @@ class VertexAI extends BaseLLM { }); for await (const chunk of streamSse(response)) { - yield chunk.choices[0].delta.content; + if (chunk.choices?.[0].delta) { + yield chunk.choices[0].delta.content; + } } } @@ -358,7 +360,7 @@ class VertexAI extends BaseLLM { } supportsFim(): boolean { - return ["code-gecko", "codestral-latest"].includes(this.model); + return this.model.includes("code-gecko") || this.model.includes("codestral"); } protected async _embed(chunks: string[]): Promise { From 4e392852319c888eaa744c35acf4e49c1ca9a818 Mon Sep 17 00:00:00 2001 From: Luke Date: Thu, 20 Feb 2025 11:29:31 -0500 Subject: [PATCH 5/5] format --- core/llm/llms/VertexAI.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/core/llm/llms/VertexAI.ts b/core/llm/llms/VertexAI.ts index 0e0910330..8ef09d107 100644 --- a/core/llm/llms/VertexAI.ts +++ b/core/llm/llms/VertexAI.ts @@ -360,7 +360,9 @@ class VertexAI extends BaseLLM { } supportsFim(): boolean { - return this.model.includes("code-gecko") || this.model.includes("codestral"); + return ( + this.model.includes("code-gecko") || this.model.includes("codestral") + ); } protected async _embed(chunks: string[]): Promise {