From 853a62f28f54ddfd3f1633c611d043faa63fb3d2 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 21 Oct 2024 23:40:48 -0700 Subject: [PATCH 01/34] testing for autocomplete filtering --- core/autocomplete/test/filter.test.ts | 66 +++++++++++++++++++++++++ core/autocomplete/test/util.ts | 71 +++++++++++++++++++++++++++ core/llm/llms/Mock.ts | 14 +++--- core/util/filesystem.ts | 2 +- 4 files changed, 146 insertions(+), 7 deletions(-) create mode 100644 core/autocomplete/test/filter.test.ts create mode 100644 core/autocomplete/test/util.ts diff --git a/core/autocomplete/test/filter.test.ts b/core/autocomplete/test/filter.test.ts new file mode 100644 index 000000000..a146c870d --- /dev/null +++ b/core/autocomplete/test/filter.test.ts @@ -0,0 +1,66 @@ +import { dedent } from "../../util"; +import { testAutocompleteFiltering } from "./util"; + +describe("llms/Mock", () => { + it("should pass unless maybe I messed up the whitespace at the start or something idk", async () => { + const input = dedent` + class Calculator { + constructor() { + this.result = 0; + } + + add(number) { + this.result += number; + return this; + } + + subtract(number) { + this.result -= number; + return this; + } + + multiply(number) { + this.result *= number; + return this; + } + + divide(number) { + <|fim|> + + getResult() { + return this.result; + } + + reset() { + this.result = 0; + return this; + } + } + + `; + const completion = dedent` + if (number === 0) { + throw new Error("Cannot divide by zero"); + } + this.result /= number; + return this; + }`; + await testAutocompleteFiltering({ + input, + completion, + expectToDisplay: completion, + description: "divide", + filename: "test.js", + }); + }); + + it("should pass", async () => { + await testAutocompleteFiltering({ + input: "console.log('Hello <|fim|>!');", + completion: "World", + expectToDisplay: "World", + description: "Hello World", + filename: "test.js", + }); + }); +}); diff --git a/core/autocomplete/test/util.ts b/core/autocomplete/test/util.ts new file mode 100644 index 000000000..1b2e21ca9 --- /dev/null +++ b/core/autocomplete/test/util.ts @@ -0,0 +1,71 @@ +import fs from "node:fs"; +import path from "node:path"; +import Mock from "../../llm/llms/Mock"; +import { testConfigHandler, testIde } from "../../test/util/fixtures"; +import { AutocompleteInput, CompletionProvider } from "../completionProvider"; + +const FIM_DELIMITER = "<|fim|>"; + +function parseFimExample(text: string): { prefix: string; suffix: string } { + const [prefix, suffix] = text.split(FIM_DELIMITER); + return { prefix, suffix }; +} + +interface AutocompleteFileringTestInput { + description: string; + filename: string; + input: string; + completion: string; + expectToDisplay: string | null; +} + +export async function testAutocompleteFiltering( + test: AutocompleteFileringTestInput, +) { + const { prefix, suffix } = parseFimExample(test.input); + + // Setup necessary objects + const llm = new Mock({ + model: "mock", + }); + llm.completion = test.completion; + const ide = testIde; + const configHandler = testConfigHandler; + + // Create a real file + const [workspaceDir] = await ide.getWorkspaceDirs(); + const filepath = path.join(workspaceDir, test.filename); + fs.writeFileSync(filepath, test.input.replace(FIM_DELIMITER, "")); + + // Prepare completion input and provider + const completionProvider = new CompletionProvider( + configHandler, + ide, + async () => llm, + () => {}, + async () => [], + ); + + const line = prefix.split("\n").length - 1; + const character = prefix.split("\n")[line].length; + const autocompleteInput: AutocompleteInput = { + clipboardText: "", + completionId: "test-completion-id", + filepath, + pos: { + line, + character, + }, + recentlyEditedFiles: [], + recentlyEditedRanges: [], + }; + + // Generate a completion + const result = await completionProvider.provideInlineCompletionItems( + autocompleteInput, + undefined, + ); + + // Ensure that we return the text that is wanted to be displayed + expect(result?.completion).toEqual(test.expectToDisplay); +} diff --git a/core/llm/llms/Mock.ts b/core/llm/llms/Mock.ts index d5e2ef59c..e6097a60d 100644 --- a/core/llm/llms/Mock.ts +++ b/core/llm/llms/Mock.ts @@ -2,24 +2,26 @@ import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js"; import { BaseLLM } from "../index.js"; class Mock extends BaseLLM { - static Completion = "Test Completion"; + public completion: string = "Test Completion"; static providerName: ModelProvider = "mock"; protected async *_streamComplete( prompt: string, options: CompletionOptions, ): AsyncGenerator { - yield Mock.Completion; + yield this.completion; } protected async *_streamChat( messages: ChatMessage[], options: CompletionOptions, ): AsyncGenerator { - yield { - role: "assistant", - content: Mock.Completion, - }; + for (const char of this.completion) { + yield { + role: "assistant", + content: char, + }; + } } } diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index 6e8bd6c0d..0f64d912c 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -38,7 +38,7 @@ class FileSystemIde implements IDE { throw new Error("Method not implemented."); } onDidChangeActiveTextEditor(callback: (filepath: string) => void): void { - throw new Error("Method not implemented."); + return; } async getIdeSettings(): Promise { From 6e543f4d08b08abbe0bc3c5652f237308048ceb6 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 22 Oct 2024 14:43:17 +0700 Subject: [PATCH 02/34] refactor: clean up code --- core/autocomplete/completionProvider.ts | 16 +++--- core/autocomplete/test/filter.test.ts | 64 ++---------------------- core/autocomplete/test/testCases.ts | 65 +++++++++++++++++++++++++ core/autocomplete/test/util.ts | 2 +- 4 files changed, 79 insertions(+), 68 deletions(-) create mode 100644 core/autocomplete/test/testCases.ts diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index bc826f934..6c1fed1cf 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -111,6 +111,14 @@ const ERRORS_TO_IGNORE = [ "unexpected server status", ]; +const LOCAL_PROVIDERS: ModelProvider[] = [ + "ollama", + "lmstudio", + "llama.cpp", + "llamafile", + "text-gen-webui", +]; + function formatExternalSnippet( filepath: string, snippet: string, @@ -335,13 +343,7 @@ export class CompletionProvider { } // Set model-specific options - const LOCAL_PROVIDERS: ModelProvider[] = [ - "ollama", - "lmstudio", - "llama.cpp", - "llamafile", - "text-gen-webui", - ]; + if ( !config.tabAutocompleteOptions?.maxPromptTokens && LOCAL_PROVIDERS.includes(llm.providerName) diff --git a/core/autocomplete/test/filter.test.ts b/core/autocomplete/test/filter.test.ts index a146c870d..98cef6be6 100644 --- a/core/autocomplete/test/filter.test.ts +++ b/core/autocomplete/test/filter.test.ts @@ -1,66 +1,10 @@ -import { dedent } from "../../util"; import { testAutocompleteFiltering } from "./util"; +import { testCases } from "./testCases"; describe("llms/Mock", () => { - it("should pass unless maybe I messed up the whitespace at the start or something idk", async () => { - const input = dedent` - class Calculator { - constructor() { - this.result = 0; - } - - add(number) { - this.result += number; - return this; - } - - subtract(number) { - this.result -= number; - return this; - } - - multiply(number) { - this.result *= number; - return this; - } - - divide(number) { - <|fim|> - - getResult() { - return this.result; - } - - reset() { - this.result = 0; - return this; - } - } - - `; - const completion = dedent` - if (number === 0) { - throw new Error("Cannot divide by zero"); - } - this.result /= number; - return this; - }`; - await testAutocompleteFiltering({ - input, - completion, - expectToDisplay: completion, - description: "divide", - filename: "test.js", - }); - }); - - it("should pass", async () => { - await testAutocompleteFiltering({ - input: "console.log('Hello <|fim|>!');", - completion: "World", - expectToDisplay: "World", - description: "Hello World", - filename: "test.js", + describe("Autocomplete Filtering Tests", () => { + it.each(testCases)("$description", async (testCase) => { + await testAutocompleteFiltering(testCase); }); }); }); diff --git a/core/autocomplete/test/testCases.ts b/core/autocomplete/test/testCases.ts new file mode 100644 index 000000000..4b9e3c05e --- /dev/null +++ b/core/autocomplete/test/testCases.ts @@ -0,0 +1,65 @@ +import { dedent } from "../../util"; +import { AutocompleteFileringTestInput } from "./util"; + +export const testCases: AutocompleteFileringTestInput[] = [ + { + description: + "should pass unless maybe I messed up the whitespace at the start or something idk", + filename: "test.js", + input: dedent` + class Calculator { + constructor() { + this.result = 0; + } + + add(number) { + this.result += number; + return this; + } + + subtract(number) { + this.result -= number; + return this; + } + + multiply(number) { + this.result *= number; + return this; + } + + divide(number) { + <|fim|> + + getResult() { + return this.result; + } + + reset() { + this.result = 0; + return this; + } + } + `, + completion: dedent` + if (number === 0) { + throw new Error("Cannot divide by zero"); + } + this.result /= number; + return this; + }`, + expectToDisplay: dedent` + if (number === 0) { + throw new Error("Cannot divide by zero"); + } + this.result /= number; + return this; + }`, + }, + { + description: "should pass", + filename: "test.js", + input: "console.log('Hello <|fim|>!');", + completion: "World", + expectToDisplay: "World", + }, +]; diff --git a/core/autocomplete/test/util.ts b/core/autocomplete/test/util.ts index 1b2e21ca9..0841a0dc2 100644 --- a/core/autocomplete/test/util.ts +++ b/core/autocomplete/test/util.ts @@ -11,7 +11,7 @@ function parseFimExample(text: string): { prefix: string; suffix: string } { return { prefix, suffix }; } -interface AutocompleteFileringTestInput { +export interface AutocompleteFileringTestInput { description: string; filename: string; input: string; From 38a43052a010a101f0d204f4ed296c0f2803d95b Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 22 Oct 2024 15:51:01 +0700 Subject: [PATCH 03/34] test: fix failing bracket tests --- core/autocomplete/completionProvider.ts | 7 -- .../services/BracketMatchingService.ts | 92 ------------------- core/autocomplete/test/testCases.ts | 8 +- 3 files changed, 3 insertions(+), 104 deletions(-) diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index 6c1fed1cf..e3d5a0a20 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -702,13 +702,6 @@ export class CompletionProvider { fullStop, ); charGenerator = stopAtStopTokens(charGenerator, stop); - charGenerator = this.bracketMatchingService.stopOnUnmatchedClosingBracket( - charGenerator, - prefix, - suffix, - filepath, - multiline, - ); let lineGenerator = streamLines(charGenerator); lineGenerator = stopAtLines(lineGenerator, fullStop); diff --git a/core/autocomplete/services/BracketMatchingService.ts b/core/autocomplete/services/BracketMatchingService.ts index 3734df2be..4d9dcd16b 100644 --- a/core/autocomplete/services/BracketMatchingService.ts +++ b/core/autocomplete/services/BracketMatchingService.ts @@ -39,96 +39,4 @@ export class BracketMatchingService { this.openingBracketsFromLastCompletion = stack; this.lastCompletionFile = filepath; } - - async *stopOnUnmatchedClosingBracket( - stream: AsyncGenerator, - prefix: string, - suffix: string, - filepath: string, - multiline: boolean, // Whether this is a multiline completion or not - ): AsyncGenerator { - let stack: string[] = []; - if (multiline) { - // Add opening brackets from the previous response - if (this.lastCompletionFile === filepath) { - stack = [...this.openingBracketsFromLastCompletion]; - } else { - this.lastCompletionFile = undefined; - } - } else { - // If single line completion, then allow completing bracket pairs that are - // started on the current line but not finished on the current line - if (!multiline) { - const currentLine = - (prefix.split("\n").pop() ?? "") + (suffix.split("\n")[0] ?? ""); - for (let i = 0; i < currentLine.length; i++) { - const char = currentLine[i]; - if (Object.keys(BracketMatchingService.BRACKETS).includes(char)) { - // It's an opening bracket - stack.push(char); - } else if ( - Object.values(BracketMatchingService.BRACKETS).includes(char) - ) { - // It's a closing bracket - if ( - stack.length === 0 || - BracketMatchingService.BRACKETS[stack.pop()!] !== char - ) { - break; - } - } - } - } - } - - // Add corresponding open brackets from suffix to stack - // because we overwrite them and the diff is displayed, and this allows something to be edited after that - for (let i = 0; i < suffix.length; i++) { - if (suffix[i] === " ") {continue;} - const openBracket = BracketMatchingService.BRACKETS_REVERSE[suffix[i]]; - if (!openBracket) {break;} - stack.unshift(openBracket); - } - - let all = ""; - let seenNonWhitespaceOrClosingBracket = false; - for await (let chunk of stream) { - // Allow closing brackets before any non-whitespace characters - if (!seenNonWhitespaceOrClosingBracket) { - const firstNonWhitespaceOrClosingBracketIndex = - chunk.search(/[^\s\)\}\]]/); - if (firstNonWhitespaceOrClosingBracketIndex !== -1) { - yield chunk.slice(0, firstNonWhitespaceOrClosingBracketIndex); - chunk = chunk.slice(firstNonWhitespaceOrClosingBracketIndex); - seenNonWhitespaceOrClosingBracket = true; - } else { - yield chunk; - continue; - } - } - - all += chunk; - const allLines = all.split("\n"); - for (let i = 0; i < chunk.length; i++) { - const char = chunk[i]; - if (Object.values(BracketMatchingService.BRACKETS).includes(char)) { - // It's a closing bracket - if ( - stack.length === 0 || - BracketMatchingService.BRACKETS[stack.pop()!] !== char - ) { - // If the stack is empty or the top of the stack doesn't match the current closing bracket - yield chunk.slice(0, i); - return; // Stop the generator if the closing bracket doesn't have a matching opening bracket in the stream - } - } else if ( - Object.keys(BracketMatchingService.BRACKETS).includes(char) - ) { - // It's an opening bracket - stack.push(char); - } - } - yield chunk; - } - } } diff --git a/core/autocomplete/test/testCases.ts b/core/autocomplete/test/testCases.ts index 4b9e3c05e..34484a7db 100644 --- a/core/autocomplete/test/testCases.ts +++ b/core/autocomplete/test/testCases.ts @@ -4,7 +4,7 @@ import { AutocompleteFileringTestInput } from "./util"; export const testCases: AutocompleteFileringTestInput[] = [ { description: - "should pass unless maybe I messed up the whitespace at the start or something idk", + "Should preserve closing brackets when the opening bracket is not a part of the completion.", filename: "test.js", input: dedent` class Calculator { @@ -40,15 +40,13 @@ export const testCases: AutocompleteFileringTestInput[] = [ } } `, - completion: dedent` - if (number === 0) { + completion: dedent`if (number === 0) { throw new Error("Cannot divide by zero"); } this.result /= number; return this; }`, - expectToDisplay: dedent` - if (number === 0) { + expectToDisplay: dedent`if (number === 0) { throw new Error("Cannot divide by zero"); } this.result /= number; From d09711ab5895aca1c91552e7d9140b3aa0535d77 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 22 Oct 2024 16:17:57 +0700 Subject: [PATCH 04/34] fix: broken build --- extensions/vscode/tsconfig.json | 1 + 1 file changed, 1 insertion(+) diff --git a/extensions/vscode/tsconfig.json b/extensions/vscode/tsconfig.json index 157952843..b35899669 100644 --- a/extensions/vscode/tsconfig.json +++ b/extensions/vscode/tsconfig.json @@ -16,6 +16,7 @@ "exclude": [ "../../core/dist/**/*", "../../core/**/*.test.ts", + "../../core/**/test/**/*", "../../core/**/*.skip.ts" ] } From 180f7e547a8721982501cd416770f5017494e499 Mon Sep 17 00:00:00 2001 From: Luke Lashley Date: Tue, 22 Oct 2024 22:35:52 -0400 Subject: [PATCH 05/34] Add code-gecko --- core/llm/llms/VertexAI.ts | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/core/llm/llms/VertexAI.ts b/core/llm/llms/VertexAI.ts index 772b30ea7..468bbbe1f 100644 --- a/core/llm/llms/VertexAI.ts +++ b/core/llm/llms/VertexAI.ts @@ -1,6 +1,7 @@ import { GoogleAuth } from "google-auth-library"; import { LLMOptions } from "../../index.js"; import { BaseLLM } from "../index.js"; +import { CompletionOptions } from "@continuedev/config-types"; abstract class VertexAI extends BaseLLM { declare apiBase: string; @@ -41,6 +42,42 @@ abstract class VertexAI extends BaseLLM { }, }); } + + supportsFim(): boolean { + return true; + } + + protected async *_streamFim( + prefix: string, + suffix: string, + options: CompletionOptions, + ): AsyncGenerator { + const endpoint = new URL("publishers/google/models/code-gecko:predict", this.apiBase); + const resp = await this.fetch(endpoint, { + method: "POST", + body: JSON.stringify({ + instances: [ + {prefix: prefix, + suffix: suffix + } + ], + parameters: { + temperature: options.temperature, + maxOutputTokens: Math.min(options.maxTokens ?? 64,64), + stopSequences: options.stop?.splice(0,5), + frequencyPenalty: options.frequencyPenalty, + presencePenalty: options.frequencyPenalty, + } + + }), + }); + // Streaming is not supported by code-gecko + // TODO: convert to non-streaming fim method when one exist in continue. + yield (await resp.json()).predictions[0].content; + } } + + + export default VertexAI; From d5a55b433489725da90f1c20f795651e9b10b6f5 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 22 Oct 2024 16:18:11 +0700 Subject: [PATCH 06/34] improv: multiline autocomplete for CSS blocks --- core/autocomplete/completionProvider.ts | 45 +++++++++++---- core/autocomplete/shouldCompleteMultiline.ts | 44 +------------- core/autocomplete/test/testCases.ts | 61 +++++++++++++++++--- core/autocomplete/test/util.ts | 8 +-- 4 files changed, 93 insertions(+), 65 deletions(-) diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index e3d5a0a20..17f820efc 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -432,6 +432,33 @@ export class CompletionProvider { }; } + private isMultiline({ + language, + prefix, + suffix, + selectedCompletionInfo, + multilineCompletions, + completeMultiline, + }: { + language: AutocompleteLanguageInfo; + prefix: string; + suffix: string; + selectedCompletionInfo: AutocompleteInput["selectedCompletionInfo"]; + multilineCompletions: TabAutocompleteOptions["multilineCompletions"]; + completeMultiline: boolean; + }) { + let langMultilineDecision = language.useMultiline?.({ prefix, suffix }); + if (langMultilineDecision) { + return langMultilineDecision; + } else { + return ( + !selectedCompletionInfo && // Only ever single-line if using intellisense selected value + multilineCompletions !== "never" && + (multilineCompletions === "always" || completeMultiline) + ); + } + } + async getTabCompletion( token: AbortSignal, options: TabAutocompleteOptions, @@ -651,16 +678,14 @@ export class CompletionProvider { ...lang.topLevelKeywords.map((word) => `\n${word}`), ]; - let langMultilineDecision = lang.useMultiline?.({ prefix, suffix }); - let multiline: boolean = false; - if (langMultilineDecision) { - multiline = langMultilineDecision; - } else { - multiline = - !input.selectedCompletionInfo && // Only ever single-line if using intellisense selected value - options.multilineCompletions !== "never" && - (options.multilineCompletions === "always" || completeMultiline); - } + const multiline = this.isMultiline({ + multilineCompletions: options.multilineCompletions, + language: lang, + selectedCompletionInfo: input.selectedCompletionInfo, + prefix, + suffix, + completeMultiline, + }); // Try to reuse pending requests if what the user typed matches start of completion const generator = this.generatorReuseManager.getGenerator( diff --git a/core/autocomplete/shouldCompleteMultiline.ts b/core/autocomplete/shouldCompleteMultiline.ts index ae114151d..af244992e 100644 --- a/core/autocomplete/shouldCompleteMultiline.ts +++ b/core/autocomplete/shouldCompleteMultiline.ts @@ -3,33 +3,6 @@ import { AutocompleteLanguageInfo } from "./languages"; const BLOCK_TYPES = ["body", "statement_block"]; -function shouldCompleteMultilineAst( - treePath: AstPath, - cursorLine: number, -): boolean { - // If at the base of the file, do multiline - if (treePath.length === 1) { - return true; - } - - // If at the first line of an otherwise empty funtion body, do multiline - for (let i = treePath.length - 1; i >= 0; i--) { - const node = treePath[i]; - if ( - BLOCK_TYPES.includes(node.type) && - Math.abs(node.startPosition.row - cursorLine) <= 1 - ) { - let text = node.text; - text = text.slice(text.indexOf("{") + 1); - text = text.slice(0, text.lastIndexOf("}")); - text = text.trim(); - return text.split("\n").length === 1; - } - } - - return false; -} - function isMidlineCompletion(prefix: string, suffix: string): boolean { return !suffix.startsWith("\n"); } @@ -56,20 +29,5 @@ export async function shouldCompleteMultiline( return false; } - // First, if the line before ends with an opening bracket, then assume multi-line - if ( - ["{", "(", "["].includes( - fullPrefix.split("\n").slice(-2)[0]?.trim().slice(-1)[0], - ) - ) { - return true; - } - - // Use AST to determine whether to complete multiline - let completeMultiline = false; - if (treePath) { - const cursorLine = fullPrefix.split("\n").length - 1; - completeMultiline = shouldCompleteMultilineAst(treePath, cursorLine); - } - return completeMultiline; + return true; } diff --git a/core/autocomplete/test/testCases.ts b/core/autocomplete/test/testCases.ts index 34484a7db..64c9e8e37 100644 --- a/core/autocomplete/test/testCases.ts +++ b/core/autocomplete/test/testCases.ts @@ -2,6 +2,13 @@ import { dedent } from "../../util"; import { AutocompleteFileringTestInput } from "./util"; export const testCases: AutocompleteFileringTestInput[] = [ + { + description: "should pass", + filename: "test.js", + input: "console.log('Hello <|fim|>!');", + llmOutput: "World", + expectedCompletion: "World", + }, { description: "Should preserve closing brackets when the opening bracket is not a part of the completion.", @@ -29,7 +36,7 @@ export const testCases: AutocompleteFileringTestInput[] = [ divide(number) { <|fim|> - + getResult() { return this.result; } @@ -40,13 +47,13 @@ export const testCases: AutocompleteFileringTestInput[] = [ } } `, - completion: dedent`if (number === 0) { + llmOutput: dedent`if (number === 0) { throw new Error("Cannot divide by zero"); } this.result /= number; return this; }`, - expectToDisplay: dedent`if (number === 0) { + expectedCompletion: dedent`if (number === 0) { throw new Error("Cannot divide by zero"); } this.result /= number; @@ -54,10 +61,48 @@ export const testCases: AutocompleteFileringTestInput[] = [ }`, }, { - description: "should pass", - filename: "test.js", - input: "console.log('Hello <|fim|>!');", - completion: "World", - expectToDisplay: "World", + description: "Should multiline-autocomplete CSS blocks", + input: `body { + font-family: Arial, sans-serif; + font-size: 16px; + color: #333333; +} + +h1 { + font-size: 24px; + font-weight: bold; + color: #000000; +} + +h4<|fim|> + +a { + text-decoration: none; + color: #007bff; +} + +.container { + width: 100%; + max-width: 1200px; + margin: 0 auto; + padding: 20px; +} + +.button { + display: inline-block; + padding: 10px 20px; + background-color: #007bff; + color: #ffffff;`, + llmOutput: ` { + font-size: 18px; + font-weight: bold; + color: #000000; +}`, + expectedCompletion: ` { + font-size: 18px; + font-weight: bold; + color: #000000; +}`, + filename: "test.css", }, ]; diff --git a/core/autocomplete/test/util.ts b/core/autocomplete/test/util.ts index 0841a0dc2..8a65031a1 100644 --- a/core/autocomplete/test/util.ts +++ b/core/autocomplete/test/util.ts @@ -15,8 +15,8 @@ export interface AutocompleteFileringTestInput { description: string; filename: string; input: string; - completion: string; - expectToDisplay: string | null; + llmOutput: string; + expectedCompletion: string | null; } export async function testAutocompleteFiltering( @@ -28,7 +28,7 @@ export async function testAutocompleteFiltering( const llm = new Mock({ model: "mock", }); - llm.completion = test.completion; + llm.completion = test.llmOutput; const ide = testIde; const configHandler = testConfigHandler; @@ -67,5 +67,5 @@ export async function testAutocompleteFiltering( ); // Ensure that we return the text that is wanted to be displayed - expect(result?.completion).toEqual(test.expectToDisplay); + expect(result?.completion).toEqual(test.expectedCompletion); } From 7cc7b8b31a57aa28f8a86e6ce543d56cd779c0d9 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Wed, 23 Oct 2024 12:22:39 +0700 Subject: [PATCH 07/34] improve: remove redundant comment --- core/autocomplete/completionProvider.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index 17f820efc..893f9bc36 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -342,8 +342,6 @@ export class CompletionProvider { llm.completionOptions.temperature = 0.01; } - // Set model-specific options - if ( !config.tabAutocompleteOptions?.maxPromptTokens && LOCAL_PROVIDERS.includes(llm.providerName) From 9be15f7e8af24842bed8ec5de2539341fce0b7e3 Mon Sep 17 00:00:00 2001 From: Luke Lashley Date: Wed, 23 Oct 2024 17:50:25 -0400 Subject: [PATCH 08/34] Refactor VertexAI --- core/index.d.ts | 8 +- .../embeddings/VertexEmbeddingsProvider.ts | 2 +- core/indexing/embeddings/index.ts | 2 +- core/llm/autodetect.ts | 10 +- core/llm/llms/AnthropicVertexAI.ts | 142 ------ core/llm/llms/GeminiVertexAI.ts | 232 --------- core/llm/llms/MistralVertexAI.ts | 106 ---- core/llm/llms/VertexAI.ts | 472 +++++++++++++++++- core/llm/llms/index.ts | 8 +- .../more/anthropic-vertexai.md | 79 --- .../model-providers/more/gemini-vertexai.md | 56 --- .../vertexai.md} | 57 ++- .../customize/model-types/autocomplete.md | 2 +- docs/docs/customize/model-types/embeddings.md | 2 +- docs/static/schemas/config.json | 98 +--- .../src/main/resources/config_schema.json | 98 +--- extensions/vscode/config_schema.json | 98 +--- extensions/vscode/continue_rc_schema.json | 113 +---- gui/public/logos/vertexai.png | Bin 0 -> 10024 bytes gui/src/pages/AddNewModel/configs/models.ts | 27 + .../pages/AddNewModel/configs/providers.ts | 32 ++ packages/llm-info/src/providers/vertexai.ts | 38 ++ 22 files changed, 639 insertions(+), 1043 deletions(-) delete mode 100644 core/llm/llms/AnthropicVertexAI.ts delete mode 100644 core/llm/llms/GeminiVertexAI.ts delete mode 100644 core/llm/llms/MistralVertexAI.ts delete mode 100644 docs/docs/customize/model-providers/more/anthropic-vertexai.md delete mode 100644 docs/docs/customize/model-providers/more/gemini-vertexai.md rename docs/docs/customize/model-providers/{more/mistral-vertexai.md => top-level/vertexai.md} (50%) create mode 100644 gui/public/logos/vertexai.png create mode 100644 packages/llm-info/src/providers/vertexai.ts diff --git a/core/index.d.ts b/core/index.d.ts index 183d5e427..45090c1c4 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -612,7 +612,6 @@ type ModelProvider = | "openai" | "free-trial" | "anthropic" - | "anthropic-vertexai" | "cohere" | "together" | "ollama" @@ -625,9 +624,7 @@ type ModelProvider = | "lmstudio" | "llamafile" | "gemini" - | "gemini-vertexai" | "mistral" - | "mistral-vertexai" | "bedrock" | "bedrockimport" | "sagemaker" @@ -648,7 +645,8 @@ type ModelProvider = | "nvidia" | "vllm" | "mock" - | "cerebras"; + | "cerebras" + | "vertexai"; export type ModelName = @@ -823,7 +821,7 @@ export type EmbeddingsProviderName = | "nvidia" | "voyage" | "mistral" - | "vertex"; + | "vertexai"; export interface EmbedOptions { apiBase?: string; diff --git a/core/indexing/embeddings/VertexEmbeddingsProvider.ts b/core/indexing/embeddings/VertexEmbeddingsProvider.ts index 06a8929cc..7188254a1 100644 --- a/core/indexing/embeddings/VertexEmbeddingsProvider.ts +++ b/core/indexing/embeddings/VertexEmbeddingsProvider.ts @@ -8,7 +8,7 @@ import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js"; * [View the Vertex Text Embedding docs.](https://cloud.google.com/vertex-ai/generative-ai/docs/embeddings/get-text-embeddings) */ class VertexEmbeddingsProvider extends BaseEmbeddingsProvider { - static providerName: EmbeddingsProviderName = "vertex"; + static providerName: EmbeddingsProviderName = "vertexai"; declare apiBase: string; diff --git a/core/indexing/embeddings/index.ts b/core/indexing/embeddings/index.ts index fe9309f73..d9ca8b732 100644 --- a/core/indexing/embeddings/index.ts +++ b/core/indexing/embeddings/index.ts @@ -38,5 +38,5 @@ export const allEmbeddingsProviders: Record< nvidia: NvidiaEmbeddingsProvider, voyage: VoyageEmbeddingsProvider, mistral: MistralEmbeddingsProvider, - vertex: VertexEmbeddingsProvider + vertexai: VertexEmbeddingsProvider }; diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index 369421406..a03500907 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -41,28 +41,26 @@ const PROVIDER_HANDLES_TEMPLATING: ModelProvider[] = [ "together", "msty", "anthropic", - "anthropic-vertexai", "bedrock", "sagemaker", "continue-proxy", "mistral", - "mistral-vertexai", "sambanova", + "vertexai" ]; const PROVIDER_SUPPORTS_IMAGES: ModelProvider[] = [ "openai", "ollama", "gemini", - "gemini-vertexai", "free-trial", "msty", "anthropic", - "anthropic-vertexai", "bedrock", "sagemaker", "continue-proxy", "openrouter", + "vertexai" ]; const MODEL_SUPPORTS_IMAGES: string[] = [ @@ -107,20 +105,18 @@ function modelSupportsImages( } const PARALLEL_PROVIDERS: ModelProvider[] = [ "anthropic", - "anthropic-vertexai", "bedrock", "sagemaker", "deepinfra", "gemini", - "gemini-vertexai", "huggingface-inference-api", "huggingface-tgi", "mistral", - "mistral-vertexai", "free-trial", "replicate", "together", "sambanova", + "vertexai" ]; function llmCanGenerateInParallel( diff --git a/core/llm/llms/AnthropicVertexAI.ts b/core/llm/llms/AnthropicVertexAI.ts deleted file mode 100644 index c910e8b85..000000000 --- a/core/llm/llms/AnthropicVertexAI.ts +++ /dev/null @@ -1,142 +0,0 @@ -import { - ChatMessage, - CompletionOptions, - LLMOptions, - ModelProvider, -} from "../../index.js"; -import { stripImages } from "../images.js"; -import { streamSse } from "../stream.js"; -import VertexAI from "./VertexAI.js"; - -class AnthropicVertexAI extends VertexAI { - static providerName: ModelProvider = "anthropic-vertexai"; - static defaultOptions: Partial = { - region: "us-east5", - model: "claude-3-5-sonnet", - }; - - private _convertArgs(options: CompletionOptions) { - const finalOptions = { - anthropic_version: "vertex-2023-10-16", - top_k: options.topK, - top_p: options.topP, - temperature: options.temperature, - max_tokens: options.maxTokens ?? 2048, - stop_sequences: options.stop?.filter((x) => x.trim() !== ""), - stream: options.stream ?? true, - }; - - return finalOptions; - } - - private _convertMessages(msgs: ChatMessage[]): any[] { - const filteredmessages = msgs.filter((m) => m.role !== "system") - const lastTwoUserMsgIndices = filteredmessages - .map((msg, index) => (msg.role === "user" ? index : -1)) - .filter((index) => index !== -1).slice(-2); - - const messages = filteredmessages.map((message, filteredMsgIdx) => { - // Add cache_control parameter to the last two user messages - // The second-to-last because it retrieves potentially already cached contents, - // The last one because we want it cached for later retrieval. - // See: https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching - const addCaching = this.cacheBehavior?.cacheConversation && lastTwoUserMsgIndices.includes(filteredMsgIdx); - - if (typeof message.content === "string") { - var chatMessage = { - ...message, - content: [{ - type: "text", - text: message.content, - ...(addCaching? { cache_control: { type: "ephemeral" } } : {}) - }] - }; - return chatMessage; - } - - return { - ...message, - content: message.content.map((part, contentIdx) => { - if (part.type === "text") { - const newpart = { - ...part, - // If multiple text parts, only add cache_control to the last one - ...((addCaching && contentIdx == message.content.length - 1) ? { cache_control: { type: "ephemeral" } } : {}) - }; - return newpart; - } - return { - type: "image", - source: { - type: "base64", - media_type: "image/jpeg", - data: part.imageUrl?.url.split(",")[1], - }, - }; - }), - }; - }); - return messages; - } - - protected async *_streamComplete( - prompt: string, - options: CompletionOptions, - ): AsyncGenerator { - const messages = [{ role: "user" as const, content: prompt }]; - for await (const update of this._streamChat(messages, options)) { - yield stripImages(update.content); - } - } - - protected async *_streamChat( - messages: ChatMessage[], - options: CompletionOptions, - ): AsyncGenerator { - const shouldCacheSystemMessage = !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage; - const systemMessage: string = stripImages( - messages.filter((m) => m.role === "system")[0]?.content, - ); - const apiURL = new URL( - `publishers/anthropic/models/${options.model}:streamRawPredict`, - this.apiBase - ); - - const response = await this.fetch(apiURL, { - method: "POST", - headers: { - ...(shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation - ? { "anthropic-beta": "prompt-caching-2024-07-31" } - : {}), - }, - body: JSON.stringify({ - ...this._convertArgs(options), - messages: this._convertMessages(messages), - system: shouldCacheSystemMessage - ? [ - { - type: "text", - text: this.systemMessage, - cache_control: { type: "ephemeral" }, - }, - ] - : systemMessage, - }), - }); - - if (options.stream === false) { - const data = await response.json(); - yield { role: "assistant", content: data.content[0].text }; - return; - } - - for await (const value of streamSse(response)) { - if (value.type == "message_start") console.log(value); - if (value.delta?.text) { - yield { role: "assistant", content: value.delta.text }; - } - } - } -} - -export default AnthropicVertexAI; diff --git a/core/llm/llms/GeminiVertexAI.ts b/core/llm/llms/GeminiVertexAI.ts deleted file mode 100644 index 2dc5e8cc1..000000000 --- a/core/llm/llms/GeminiVertexAI.ts +++ /dev/null @@ -1,232 +0,0 @@ -import { - ChatMessage, - CompletionOptions, - LLMOptions, - MessagePart, - ModelProvider, -} from "../../index.js"; -import { stripImages } from "../images.js"; -import { streamResponse } from "../stream.js"; -import VertexAI from "./VertexAI.js"; - -class GeminiVertexAI extends VertexAI { - static providerName: ModelProvider = "gemini-vertexai"; - - static defaultOptions: Partial = { - model: "gemini-pro", - region: "us-central1", - }; - - // Function to convert completion options to Gemini format - private _convertArgs(options: CompletionOptions) { - const finalOptions: any = {}; // Initialize an empty object - - // Map known options - if (options.topK) { - finalOptions.topK = options.topK; - } - if (options.topP) { - finalOptions.topP = options.topP; - } - if (options.temperature !== undefined && options.temperature !== null) { - finalOptions.temperature = options.temperature; - } - if (options.maxTokens) { - finalOptions.maxOutputTokens = options.maxTokens; - } - if (options.stop) { - finalOptions.stopSequences = options.stop.filter((x) => x.trim() !== ""); - } - - return { generationConfig: finalOptions }; // Wrap options under 'generationConfig' - } - - protected async *_streamComplete( - prompt: string, - options: CompletionOptions, - ): AsyncGenerator { - for await (const message of this._streamChat( - [{ content: prompt, role: "user" }], - options, - )) { - yield stripImages(message.content); - } - } - - private removeSystemMessage(messages: ChatMessage[]) { - const msgs = [...messages]; - - if (msgs[0]?.role === "system") { - const sysMsg = msgs.shift()?.content; - // @ts-ignore - if (msgs[0]?.role === "user") { - msgs[0].content = `System message - follow these instructions in every response: ${sysMsg}\n\n---\n\n${msgs[0].content}`; - } - } - - return msgs; - } - - protected async *_streamChat( - messages: ChatMessage[], - options: CompletionOptions, - ): AsyncGenerator { - const isV1API = this.apiBase.includes("/v1/"); - - // Conditionally apply removeSystemMessage - const convertedMsgs = isV1API - ? this.removeSystemMessage(messages) - : messages; - - if (options.model.includes("gemini")) { - yield* this.streamChatGemini(convertedMsgs, options); - } else { - yield* this.streamChatBison(convertedMsgs, options); - } - } - - private _continuePartToGeminiPart(part: MessagePart) { - return part.type === "text" - ? { - text: part.text, - } - : { - inlineData: { - mimeType: "image/jpeg", - data: part.imageUrl?.url.split(",")[1], - }, - }; - } - - private async *streamChatGemini( - messages: ChatMessage[], - options: CompletionOptions, - ): AsyncGenerator { - const apiURL = new URL( - `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 - } - return { - role: msg.role === "assistant" ? "model" : "user", - parts: - typeof msg.content === "string" - ? [{ text: msg.content }] - : msg.content.map(this._continuePartToGeminiPart), - }; - }) - .filter((c) => c !== null); - - const body = { - ...this._convertArgs(options), - contents, - // if this.systemMessage is defined, reformat it for Gemini API - ...(this.systemMessage && - !isV1API && { - systemInstruction: { parts: [{ text: this.systemMessage }] }, - }), - }; - 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 - console.warn("Unexpected response format:", data); - } - } - if (foundIncomplete) { - buffer = parts[parts.length - 1]; - } else { - buffer = ""; - } - } - } - - private async *streamChatBison( - messages: ChatMessage[], - options: CompletionOptions, - ): AsyncGenerator { - const instances = messages.map((message) => ({ prompt: message.content })); - - const apiURL = new URL( - `publishers/google/models/${options.model}:predict`, - this.apiBase, - ); - const body = { - instances, - parameters: { - temperature: options.temperature, - maxOutputTokens: options.maxTokens, - topP: options.topP, - topK: options.topK, - stopSequences: options.stop, - presencePenalty: options.presencePenalty, - frequencyPenalty: options.frequencyPenalty, - }, - }; - const response = await this.fetch(apiURL, { - method: "POST", - body: JSON.stringify(body), - }); - const data = await response.json(); - yield { role: "assistant", content: data.predictions[0].content }; - } -} - -async function delay(seconds: number) { - return new Promise((resolve) => setTimeout(resolve, seconds * 1000)); -} - -export default GeminiVertexAI; diff --git a/core/llm/llms/MistralVertexAI.ts b/core/llm/llms/MistralVertexAI.ts deleted file mode 100644 index af0fc6272..000000000 --- a/core/llm/llms/MistralVertexAI.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { - ChatMessage, - CompletionOptions, - LLMOptions, - ModelProvider -} from "../../index.js"; -import { stripImages } from "../images.js"; -import { streamSse } from "../stream.js"; -import { gptEditPrompt } from "../templates/edit.js"; -import VertexAI from "./VertexAI.js"; - -class MistralVertexAI extends VertexAI { - static providerName: ModelProvider = "mistral-vertexai"; - static defaultOptions: Partial = { - region: "us-central1", - model: "codestral-latest", - promptTemplates: { - edit: gptEditPrompt, - }, - }; - - protected async *_streamComplete( - prompt: string, - options: CompletionOptions, - ): AsyncGenerator { - for await (const chunk of this._streamChat( - [{ role: "user", content: prompt }], - options, - )) { - yield stripImages(chunk.content); - } - } - - protected async *_streamChat( - messages: ChatMessage[], - options: CompletionOptions, - ): AsyncGenerator { - const apiBase = this.apiBase!; - const apiURL = new URL( - `publishers/mistralai/models/${options.model}:streamRawPredict`, - apiBase, - ); - - const lastMessage = messages[messages.length - 1]; - if (lastMessage?.role === "assistant") { - (lastMessage as any).prefix = true; - } - - const body = { - model: options.model, - temperature: options.temperature, - top_p: options.topP, - max_tokens: options.maxTokens, - stream: options.stream ?? true, - stop: options.stop, - messages, - }; - - const response = await this.fetch(apiURL, { - method: "POST", - body: JSON.stringify(body), - }); - - for await (const chunk of streamSse(response)) { - yield chunk.choices[0].delta; - } - } - - protected async *_streamFim( - prefix: string, - suffix: string, - options: CompletionOptions, - ): AsyncGenerator { - const apiBase = this.apiBase!; - const apiURL = new URL( - `publishers/mistralai/models/${options.model}:streamRawPredict`, - apiBase, - ); - - const body = { - model: options.model, - max_tokens: options.maxTokens, - temperature: options.temperature, - top_p: options.topP, - stream: options.stream ?? true, - stop: options.stop, - prompt: prefix, - suffix, - }; - - const response = await this.fetch(apiURL, { - method: "POST", - body: JSON.stringify(body), - }); - - for await (const chunk of streamSse(response)) { - yield chunk.choices[0].delta.content; - } - } - - supportsFim(): boolean { - return true; - } -} - -export default MistralVertexAI; diff --git a/core/llm/llms/VertexAI.ts b/core/llm/llms/VertexAI.ts index 468bbbe1f..6c94a9a77 100644 --- a/core/llm/llms/VertexAI.ts +++ b/core/llm/llms/VertexAI.ts @@ -1,10 +1,20 @@ import { GoogleAuth } from "google-auth-library"; -import { LLMOptions } from "../../index.js"; import { BaseLLM } from "../index.js"; -import { CompletionOptions } from "@continuedev/config-types"; +import { stripImages } from "../images.js"; +import { streamSse } from "../stream.js"; +import { + ChatMessage, + CompletionOptions, + LLMOptions, + MessagePart, + ModelProvider, +} from "../../index.js"; +import { streamResponse } from "../stream.js"; -abstract class VertexAI extends BaseLLM { +class VertexAI extends BaseLLM { + static providerName: ModelProvider = "vertexai"; declare apiBase: string; + declare vertexProvider: string; private clientPromise = new GoogleAuth({ scopes: "https://www.googleapis.com/auth/cloud-platform", @@ -23,6 +33,14 @@ abstract class VertexAI extends BaseLLM { constructor(_options: LLMOptions) { super(_options); this.apiBase ??= VertexAI.getDefaultApiBaseFrom(_options); + this.vertexProvider = + _options.model.includes("mistral") || _options.model.includes("codestral") || _options.model.includes("mixtral") + ? "Mistral" + : _options.model.includes("claude") + ? "anthropic" + : _options.model.includes("gemini") + ? "gemini" : + "unknown"; } async fetch(url: RequestInfo | URL, init?: RequestInit) { @@ -42,12 +60,378 @@ abstract class VertexAI extends BaseLLM { }, }); } - - supportsFim(): boolean { - return true; + + // Anthropic functions + private _anthropicConvertArgs(options: CompletionOptions) { + const finalOptions = { + anthropic_version: "vertex-2023-10-16", + top_k: options.topK, + top_p: options.topP, + temperature: options.temperature, + max_tokens: options.maxTokens ?? 2048, + stop_sequences: options.stop?.filter((x) => x.trim() !== ""), + stream: options.stream ?? true, + }; + + return finalOptions; } - protected async *_streamFim( + private _anthropicConvertMessages(msgs: ChatMessage[]): any[] { + const filteredmessages = msgs.filter((m) => m.role !== "system") + const lastTwoUserMsgIndices = filteredmessages + .map((msg, index) => (msg.role === "user" ? index : -1)) + .filter((index) => index !== -1).slice(-2); + + const messages = filteredmessages.map((message, filteredMsgIdx) => { + // Add cache_control parameter to the last two user messages + // The second-to-last because it retrieves potentially already cached contents, + // The last one because we want it cached for later retrieval. + // See: https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching + const addCaching = this.cacheBehavior?.cacheConversation && lastTwoUserMsgIndices.includes(filteredMsgIdx); + + if (typeof message.content === "string") { + var chatMessage = { + ...message, + content: [{ + type: "text", + text: message.content, + ...(addCaching ? { cache_control: { type: "ephemeral" } } : {}) + }] + }; + return chatMessage; + } + + return { + ...message, + content: message.content.map((part, contentIdx) => { + if (part.type === "text") { + const newpart = { + ...part, + // If multiple text parts, only add cache_control to the last one + ...((addCaching && contentIdx == message.content.length - 1) ? { cache_control: { type: "ephemeral" } } : {}) + }; + return newpart; + } + return { + type: "image", + source: { + type: "base64", + media_type: "image/jpeg", + data: part.imageUrl?.url.split(",")[1], + }, + }; + }), + }; + }); + return messages; + } + + protected async *StreamChatAnthropic( + messages: ChatMessage[], + options: CompletionOptions, + ): AsyncGenerator { + const shouldCacheSystemMessage = !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage; + const systemMessage: string = stripImages( + messages.filter((m) => m.role === "system")[0]?.content, + ); + const apiURL = new URL( + `publishers/anthropic/models/${options.model}:streamRawPredict`, + this.apiBase + ); + + const response = await this.fetch(apiURL, { + method: "POST", + headers: { + ...(shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation + ? { "anthropic-beta": "prompt-caching-2024-07-31" } + : {}), + }, + body: JSON.stringify({ + ...this._anthropicConvertArgs(options), + messages: this._anthropicConvertMessages(messages), + system: shouldCacheSystemMessage + ? [ + { + type: "text", + text: this.systemMessage, + cache_control: { type: "ephemeral" }, + }, + ] + : systemMessage, + }), + }); + + if (options.stream === false) { + const data = await response.json(); + yield { role: "assistant", content: data.content[0].text }; + return; + } + + for await (const value of streamSse(response)) { + if (value.type == "message_start") console.log(value); + if (value.delta?.text) { + yield { role: "assistant", content: value.delta.text }; + } + } + } + + + //Gemini + // Function to convert completion options to Gemini format + private _geminiConvertArgs(options: CompletionOptions) { + const finalOptions: any = {}; // Initialize an empty object + + // Map known options + if (options.topK) { + finalOptions.topK = options.topK; + } + if (options.topP) { + finalOptions.topP = options.topP; + } + if (options.temperature !== undefined && options.temperature !== null) { + finalOptions.temperature = options.temperature; + } + if (options.maxTokens) { + finalOptions.maxOutputTokens = options.maxTokens; + } + if (options.stop) { + finalOptions.stopSequences = options.stop.filter((x) => x.trim() !== ""); + } + + return { generationConfig: finalOptions }; // Wrap options under 'generationConfig' + } + + + private removeSystemMessage(messages: ChatMessage[]) { + const msgs = [...messages]; + + if (msgs[0]?.role === "system") { + const sysMsg = msgs.shift()?.content; + // @ts-ignore + if (msgs[0]?.role === "user") { + msgs[0].content = `System message - follow these instructions in every response: ${sysMsg}\n\n---\n\n${msgs[0].content}`; + } + } + + return msgs; + } + + + private _continuePartToGeminiPart(part: MessagePart) { + return part.type === "text" + ? { + text: part.text, + } + : { + inlineData: { + mimeType: "image/jpeg", + data: part.imageUrl?.url.split(",")[1], + }, + }; + } + + private async *streamChatGemini( + messages: ChatMessage[], + options: CompletionOptions, + ): AsyncGenerator { + const apiURL = new URL( + `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 + } + return { + role: msg.role === "assistant" ? "model" : "user", + parts: + typeof msg.content === "string" + ? [{ text: msg.content }] + : msg.content.map(this._continuePartToGeminiPart), + }; + }) + .filter((c) => c !== null); + + const body = { + ...this._geminiConvertArgs(options), + contents, + // if this.systemMessage is defined, reformat it for Gemini API + ...(this.systemMessage && + !isV1API && { + systemInstruction: { parts: [{ text: this.systemMessage }] }, + }), + }; + 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 = ""; + } + } + } + + private async *streamChatBison( + messages: ChatMessage[], + options: CompletionOptions, + ): AsyncGenerator { + const instances = messages.map((message) => ({ prompt: message.content })); + + const apiURL = new URL( + `publishers/google/models/${options.model}:predict`, + this.apiBase, + ); + const body = { + instances, + parameters: { + temperature: options.temperature, + maxOutputTokens: options.maxTokens, + topP: options.topP, + topK: options.topK, + stopSequences: options.stop, + presencePenalty: options.presencePenalty, + frequencyPenalty: options.frequencyPenalty, + }, + }; + const response = await this.fetch(apiURL, { + method: "POST", + body: JSON.stringify(body), + }); + const data = await response.json(); + yield { role: "assistant", content: data.predictions[0].content }; + } + + //Mistral + + + protected async *StreamChatMistral( + messages: ChatMessage[], + options: CompletionOptions, + ): AsyncGenerator { + const apiBase = this.apiBase!; + const apiURL = new URL( + `publishers/mistralai/models/${options.model}:streamRawPredict`, + apiBase, + ); + + const lastMessage = messages[messages.length - 1]; + if (lastMessage?.role === "assistant") { + (lastMessage as any).prefix = true; + } + + const body = { + model: options.model, + temperature: options.temperature, + top_p: options.topP, + max_tokens: options.maxTokens, + stream: options.stream ?? true, + stop: options.stop, + messages, + }; + + const response = await this.fetch(apiURL, { + method: "POST", + body: JSON.stringify(body), + }); + + for await (const chunk of streamSse(response)) { + yield chunk.choices[0].delta; + } + } + + protected async *StreamFimMistral( + prefix: string, + suffix: string, + options: CompletionOptions, + ): AsyncGenerator { + const apiBase = this.apiBase!; + const apiURL = new URL( + `publishers/mistralai/models/${options.model}:streamRawPredict`, + apiBase, + ); + + const body = { + model: options.model, + max_tokens: options.maxTokens, + temperature: options.temperature, + top_p: options.topP, + stream: options.stream ?? true, + stop: options.stop, + prompt: prefix, + suffix, + }; + + const response = await this.fetch(apiURL, { + method: "POST", + body: JSON.stringify(body), + }); + + for await (const chunk of streamSse(response)) { + yield chunk.choices[0].delta.content; + } + } + + + + //gecko + protected async *streamFimGecko( prefix: string, suffix: string, options: CompletionOptions, @@ -57,14 +441,15 @@ abstract class VertexAI extends BaseLLM { method: "POST", body: JSON.stringify({ instances: [ - {prefix: prefix, + { + prefix: prefix, suffix: suffix } ], parameters: { temperature: options.temperature, - maxOutputTokens: Math.min(options.maxTokens ?? 64,64), - stopSequences: options.stop?.splice(0,5), + maxOutputTokens: Math.min(options.maxTokens ?? 64, 64), + stopSequences: options.stop?.splice(0, 5), frequencyPenalty: options.frequencyPenalty, presencePenalty: options.frequencyPenalty, } @@ -75,9 +460,74 @@ abstract class VertexAI extends BaseLLM { // TODO: convert to non-streaming fim method when one exist in continue. yield (await resp.json()).predictions[0].content; } + + //Manager functions + + protected async *_streamChat( + messages: ChatMessage[], + options: CompletionOptions, + ): AsyncGenerator { + const isV1API = this.apiBase.includes("/v1/"); + + // Conditionally apply removeSystemMessage + const convertedMsgs = isV1API + ? this.removeSystemMessage(messages) + : messages; + if (this.vertexProvider == "gemini") { + yield* this.streamChatGemini(convertedMsgs, options); + } else if (this.vertexProvider == "mistral") { + yield* this.StreamChatMistral(messages, options); + } else if (this.vertexProvider == "anthropic") { + yield* this.StreamChatAnthropic(messages, options) + } else { + if (options.model.includes("bison")) { + yield* this.streamChatBison(convertedMsgs, options); + } + } + } + + protected async *_streamComplete( + prompt: string, + options: CompletionOptions, + ): AsyncGenerator { + for await (const message of this._streamChat( + [{ content: prompt, role: "user" }], + options, + )) { + yield stripImages(message.content); + } + } + + protected async *_streamFim( + prefix: string, + suffix: string, + options: CompletionOptions, + ): AsyncGenerator { + + + + if (this.model === "code-gecko") { + yield* this.streamFimGecko(prefix, suffix, options); + } else if (this.model.includes("codestral")) { + yield* this.StreamFimMistral(prefix, suffix, options); + } else { + throw new Error(`Unsupported model: ${this.model}`); + } + + + } + + supportsFim(): boolean { + return ["code-gecko", "codestral-latest"].includes(this.model); + } + + +} + +async function delay(seconds: number) { + return new Promise((resolve) => setTimeout(resolve, seconds * 1000)); } - export default VertexAI; diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index b504aa900..444d83457 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -8,7 +8,6 @@ import { import { renderTemplatedString } from "../../promptFiles/renderTemplatedString"; import { BaseLLM } from "../index"; import Anthropic from "./Anthropic"; -import AnthropicVertexAI from "./AnthropicVertexAI"; import Azure from "./Azure"; import Bedrock from "./Bedrock"; import BedrockImport from "./BedrockImport"; @@ -21,7 +20,6 @@ import Fireworks from "./Fireworks"; import Flowise from "./Flowise"; import FreeTrial from "./FreeTrial"; import Gemini from "./Gemini"; -import GeminiVertexAI from "./GeminiVertexAI"; import Groq from "./Groq"; import HuggingFaceInferenceAPI from "./HuggingFaceInferenceAPI"; import HuggingFaceTGI from "./HuggingFaceTGI"; @@ -30,7 +28,6 @@ import LMStudio from "./LMStudio"; import LlamaCpp from "./LlamaCpp"; import Llamafile from "./Llamafile"; import Mistral from "./Mistral"; -import MistralVertexAI from "./MistralVertexAI"; import Mock from "./Mock"; import Msty from "./Msty"; import Nvidia from "./Nvidia"; @@ -45,14 +42,13 @@ import Together from "./Together"; import Vllm from "./Vllm"; import WatsonX from "./WatsonX"; import ContinueProxy from "./stubs/ContinueProxy"; +import VertexAI from "./VertexAI"; const LLMs = [ Anthropic, - AnthropicVertexAI, Cohere, FreeTrial, Gemini, - GeminiVertexAI, Llamafile, Ollama, Replicate, @@ -65,7 +61,6 @@ const LLMs = [ OpenAI, LMStudio, Mistral, - MistralVertexAI, Bedrock, BedrockImport, SageMaker, @@ -85,6 +80,7 @@ const LLMs = [ SambaNova, Mock, Cerebras, + VertexAI ]; export async function llmFromDescription( diff --git a/docs/docs/customize/model-providers/more/anthropic-vertexai.md b/docs/docs/customize/model-providers/more/anthropic-vertexai.md deleted file mode 100644 index 3f5280598..000000000 --- a/docs/docs/customize/model-providers/more/anthropic-vertexai.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -title: Anthropic Vertex AI -slug: ../anthropic-vertexai ---- - -:::info - -You need to enable the [Vertex AI API](https://console.cloud.google.com/marketplace/product/google/aiplatform.googleapis.com) and set up the [Google Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc). - -::: - -## Chat model - -We recommend configuring **Claude 3.5 Sonnet** as your chat model. - -```json title="config.json" -{ - "models": [ - { - "title": "Claude 3.5 Sonnet", - "provider": "anthropic-vertexai", - "model": "claude-3-5-sonnet-20240620", - "projectId": "[PROJECT_ID]", - "region": "us-east5" - } - ] -} -``` - -## Autocomplete model - -Anthropic Vertex AI currently does not offer any autocomplete models. - -[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers. - -## Embeddings model - -We recommend configuring **text-embedding-004** as your embeddings model. - -```json title="config.json" -{ - "embeddingsProvider": { - "provider": "vertex", - "model": "text-embedding-004", - "projectId": "[PROJECT_ID]", - "region": "us-central1" - } -} -``` - -## Reranking model - -Anthropic Vertex AI currently does not offer any reranking models. - -[Click here](../../model-types/reranking.md) to see a list of reranking model providers. - -## Prompt caching - -Anthropic Vertex AI supports [prompt caching with Claude](https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching). - -To enable caching of the system message and the turn-by-turn conversation, update your your model configuration as following: - -```jsonc -{ - "models": [ - { - // Enable prompt caching - "cacheBehavior": { - "cacheSystemMessage": true, - "cacheConversation": true - }, - "title": "Anthropic", - "provider": "anthropic", - "model": "claude-3-5-sonnet-20240620", - "apiKey": "[API_KEY]" - } - ] -} -``` diff --git a/docs/docs/customize/model-providers/more/gemini-vertexai.md b/docs/docs/customize/model-providers/more/gemini-vertexai.md deleted file mode 100644 index 074278c1f..000000000 --- a/docs/docs/customize/model-providers/more/gemini-vertexai.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -title: Gemini Vertex AI -slug: ../gemini-vertexai ---- - -:::info - -You need to enable the [Vertex AI API](https://console.cloud.google.com/marketplace/product/google/aiplatform.googleapis.com) and set up the [Google Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc). - -::: - -## Chat model - -We recommend configuring **Gemini 1.5 Pro** as your chat model. - -```json title="config.json" -{ - "models": [ - { - "title": "Gemini 1.5 Pro (Vertex AI)", - "provider": "gemini-vertexai", - "model": "gemini-1.5-pro", - "projectId": "[PROJECT_ID]", - "region": "us-central1" - } - ] -} -``` - -## Autocomplete model - -Gemini Vertex AI currently does not offer any autocomplete models. - -[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers. - -## Embeddings model - -We recommend configuring **text-embedding-004** as your embeddings model. - -```json title="config.json" -{ - "embeddingsProvider": { - "provider": "vertex", - "model": "text-embedding-004", - "projectId": "[PROJECT_ID]", - "region": "us-central1" - } -} -``` - - -## Reranking model - -Gemini Vertex AI currently does not offer any reranking models. - -[Click here](../../model-types/reranking.md) to see a list of reranking model providers. diff --git a/docs/docs/customize/model-providers/more/mistral-vertexai.md b/docs/docs/customize/model-providers/top-level/vertexai.md similarity index 50% rename from docs/docs/customize/model-providers/more/mistral-vertexai.md rename to docs/docs/customize/model-providers/top-level/vertexai.md index 8d64c7ffe..5e3dbbbbe 100644 --- a/docs/docs/customize/model-providers/more/mistral-vertexai.md +++ b/docs/docs/customize/model-providers/top-level/vertexai.md @@ -1,6 +1,6 @@ --- -title: Mistral Vertex AI -slug: ../mistral-vertexai +title: Vertex AI +slug: ../vertexai --- :::info @@ -11,14 +11,14 @@ You need to enable the [Vertex AI API](https://console.cloud.google.com/marketpl ## Chat model -We recommend configuring **Mistral Large** as your chat model. +We recommend configuring **Mistral Large**, **Gemini 1.5 Pro**, or **Claude 3.5 Sonnet** as your chat model. ```json title="config.json" { "models": [ { "title": "Mistral Large (Vertex AI)", - "provider": "mistral-vertexai", + "provider": "vertexai", "model": "mistral-large", "projectId": "[PROJECT_ID]", "region": "us-central1" @@ -27,15 +27,56 @@ We recommend configuring **Mistral Large** as your chat model. } ``` +```json title="config.json" +{ + "models": [ + { + "title": "Gemini 1.5 Pro (Vertex AI)", + "provider": "vertexai", + "model": "gemini-1.5-pro", + "projectId": "[PROJECT_ID]", + "region": "us-central1" + } + ] +} +``` + +```json title="config.json" +{ + "models": [ + { + "title": "Claude 3.5 Sonnet", + "provider": "vertexai", + "model": "claude-3-5-sonnet-20240620", + "projectId": "[PROJECT_ID]", + "region": "us-east5" + } + ] +} +``` + + ## Autocomplete model -We recommend configuring **Codestral** as your autocomplete model. +We recommend configuring **Codestral** or **code-gecko** as your autocomplete model. ```json title="config.json" { "tabAutocompleteModel": { "title": "Codestral (Vertex AI)", - "provider": "mistral-vertexai", + "provider": "vertexai", + "model": "codestral", + "projectId": "[PROJECT_ID]", + "region": "us-central1" + } +} +``` + +```json title="config.json" +{ + "tabAutocompleteModel": { + "title": "Code Gecko (Vertex AI)", + "provider": "vertexai", "model": "codestral", "projectId": "[PROJECT_ID]", "region": "us-central1" @@ -50,7 +91,7 @@ We recommend configuring **text-embedding-004** as your embeddings model. ```json title="config.json" { "embeddingsProvider": { - "provider": "vertex", + "provider": "vertexai", "model": "text-embedding-004", "projectId": "[PROJECT_ID]", "region": "us-central1" @@ -60,6 +101,6 @@ We recommend configuring **text-embedding-004** as your embeddings model. ## Reranking model -Mistral Vertex AI currently does not offer any reranking models. +Vertex AI currently does not offer any reranking models. [Click here](../../model-types/reranking.md) to see a list of reranking model providers. diff --git a/docs/docs/customize/model-types/autocomplete.md b/docs/docs/customize/model-types/autocomplete.md index a7eaa5e63..64d39c893 100644 --- a/docs/docs/customize/model-types/autocomplete.md +++ b/docs/docs/customize/model-types/autocomplete.md @@ -11,6 +11,6 @@ In Continue, these models are used to display inline [Autocomplete](../../autoco ## Recommended Autocomplete models -If you have the ability to use any model, we recommend `Codestral` with [Mistral](../model-providers/top-level/mistral.md#autocomplete-model) or [Mistral Vertex AI](../model-providers/more/mistral-vertexai.md#autocomplete-model). +If you have the ability to use any model, we recommend `Codestral` with [Mistral](../model-providers/top-level/mistral.md#autocomplete-model) or [Vertex AI](../model-providers/top-level/vertexai.md#autocomplete-model). If you want to run a model locally, we recommend `Starcoder2-3B` with [Ollama](../model-providers/top-level/ollama.md#autocomplete-model). diff --git a/docs/docs/customize/model-types/embeddings.md b/docs/docs/customize/model-types/embeddings.md index a84346fa0..a6b565cb6 100644 --- a/docs/docs/customize/model-types/embeddings.md +++ b/docs/docs/customize/model-types/embeddings.md @@ -72,4 +72,4 @@ See [here](../model-providers/top-level/gemini.md#embeddings-model) for instruct ### Vertex -See [here](../model-providers/more/vertex.md#embeddings-model) for instructions on how to use Vertex for embeddings. \ No newline at end of file +See [here](../model-providers/top-level/vertexai.md#embeddings-model) for instructions on how to use Vertex for embeddings. \ No newline at end of file diff --git a/docs/static/schemas/config.json b/docs/static/schemas/config.json index 6da984ead..6dee86b56 100644 --- a/docs/static/schemas/config.json +++ b/docs/static/schemas/config.json @@ -169,7 +169,6 @@ "openai", "free-trial", "anthropic", - "anthropic-vertexai", "cohere", "bedrock", "bedrockimport", @@ -181,11 +180,9 @@ "llama.cpp", "replicate", "gemini", - "gemini-vertexai", "lmstudio", "llamafile", "mistral", - "mistral-vertexai", "deepinfra", "groq", "fireworks", @@ -198,7 +195,8 @@ "sambanova", "nvidia", "vllm", - "cerebras" + "cerebras", + "vertexai" ], "markdownEnumDescriptions": [ "### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/openai)", @@ -787,49 +785,6 @@ } } }, - { - "if": { - "properties": { - "provider": { - "enum": ["anthropic-vertexai"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "cacheBehavior": { - "title": "Caching Behavior", - "description": "Options for the prompt caching", - "properties": { - "cacheSystemMessage": { - "type": "boolean" - }, - "cacheConversation": { - "type": "boolean" - } - } - }, - "model": { - "anyOf": [ - { - "enum": [ - "claude-3-5-opus", - "claude-3-5-sonnet", - "claude-3-5-haiku", - "claude-3-opus", - "claude-3-sonnet", - "claude-3-haiku" - ] - }, - { - "type": "string" - } - ] - } - } - } - }, { "if": { "properties": { @@ -925,35 +880,6 @@ } } }, - { - "if": { - "properties": { - "provider": { - "enum": ["gemini-vertexai"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "gemini-pro", - "gemini-1.5-pro-latest", - "gemini-1.5-pro", - "gemini-1.5-flash-latest", - "gemini-1.5-flash" - ] - }, - { "type": "string" } - ] - } - }, - "required": ["projectId", "region"] - } - }, { "if": { "properties": { @@ -1152,26 +1078,12 @@ "if": { "properties": { "provider": { - "enum": ["mistral-vertexai"] + "enum": ["vertexai"] } }, "required": ["provider"] }, "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "codestral", - "mistral-nemo", - "mistral-large" - ] - }, - { "type": "string" } - ] - } - }, "required": ["projectId", "region"] } }, @@ -2428,7 +2340,7 @@ "nvidia", "bedrock", "sagemaker", - "vertex" + "vertexai" ] }, "model": { @@ -2507,7 +2419,7 @@ "if": { "properties": { "provider": { - "enum": ["vertex"] + "enum": ["vertexai"] } }, "required": ["provider"] diff --git a/extensions/intellij/src/main/resources/config_schema.json b/extensions/intellij/src/main/resources/config_schema.json index 6da984ead..6dee86b56 100644 --- a/extensions/intellij/src/main/resources/config_schema.json +++ b/extensions/intellij/src/main/resources/config_schema.json @@ -169,7 +169,6 @@ "openai", "free-trial", "anthropic", - "anthropic-vertexai", "cohere", "bedrock", "bedrockimport", @@ -181,11 +180,9 @@ "llama.cpp", "replicate", "gemini", - "gemini-vertexai", "lmstudio", "llamafile", "mistral", - "mistral-vertexai", "deepinfra", "groq", "fireworks", @@ -198,7 +195,8 @@ "sambanova", "nvidia", "vllm", - "cerebras" + "cerebras", + "vertexai" ], "markdownEnumDescriptions": [ "### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/openai)", @@ -787,49 +785,6 @@ } } }, - { - "if": { - "properties": { - "provider": { - "enum": ["anthropic-vertexai"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "cacheBehavior": { - "title": "Caching Behavior", - "description": "Options for the prompt caching", - "properties": { - "cacheSystemMessage": { - "type": "boolean" - }, - "cacheConversation": { - "type": "boolean" - } - } - }, - "model": { - "anyOf": [ - { - "enum": [ - "claude-3-5-opus", - "claude-3-5-sonnet", - "claude-3-5-haiku", - "claude-3-opus", - "claude-3-sonnet", - "claude-3-haiku" - ] - }, - { - "type": "string" - } - ] - } - } - } - }, { "if": { "properties": { @@ -925,35 +880,6 @@ } } }, - { - "if": { - "properties": { - "provider": { - "enum": ["gemini-vertexai"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "gemini-pro", - "gemini-1.5-pro-latest", - "gemini-1.5-pro", - "gemini-1.5-flash-latest", - "gemini-1.5-flash" - ] - }, - { "type": "string" } - ] - } - }, - "required": ["projectId", "region"] - } - }, { "if": { "properties": { @@ -1152,26 +1078,12 @@ "if": { "properties": { "provider": { - "enum": ["mistral-vertexai"] + "enum": ["vertexai"] } }, "required": ["provider"] }, "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "codestral", - "mistral-nemo", - "mistral-large" - ] - }, - { "type": "string" } - ] - } - }, "required": ["projectId", "region"] } }, @@ -2428,7 +2340,7 @@ "nvidia", "bedrock", "sagemaker", - "vertex" + "vertexai" ] }, "model": { @@ -2507,7 +2419,7 @@ "if": { "properties": { "provider": { - "enum": ["vertex"] + "enum": ["vertexai"] } }, "required": ["provider"] diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 6da984ead..6dee86b56 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -169,7 +169,6 @@ "openai", "free-trial", "anthropic", - "anthropic-vertexai", "cohere", "bedrock", "bedrockimport", @@ -181,11 +180,9 @@ "llama.cpp", "replicate", "gemini", - "gemini-vertexai", "lmstudio", "llamafile", "mistral", - "mistral-vertexai", "deepinfra", "groq", "fireworks", @@ -198,7 +195,8 @@ "sambanova", "nvidia", "vllm", - "cerebras" + "cerebras", + "vertexai" ], "markdownEnumDescriptions": [ "### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/openai)", @@ -787,49 +785,6 @@ } } }, - { - "if": { - "properties": { - "provider": { - "enum": ["anthropic-vertexai"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "cacheBehavior": { - "title": "Caching Behavior", - "description": "Options for the prompt caching", - "properties": { - "cacheSystemMessage": { - "type": "boolean" - }, - "cacheConversation": { - "type": "boolean" - } - } - }, - "model": { - "anyOf": [ - { - "enum": [ - "claude-3-5-opus", - "claude-3-5-sonnet", - "claude-3-5-haiku", - "claude-3-opus", - "claude-3-sonnet", - "claude-3-haiku" - ] - }, - { - "type": "string" - } - ] - } - } - } - }, { "if": { "properties": { @@ -925,35 +880,6 @@ } } }, - { - "if": { - "properties": { - "provider": { - "enum": ["gemini-vertexai"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "gemini-pro", - "gemini-1.5-pro-latest", - "gemini-1.5-pro", - "gemini-1.5-flash-latest", - "gemini-1.5-flash" - ] - }, - { "type": "string" } - ] - } - }, - "required": ["projectId", "region"] - } - }, { "if": { "properties": { @@ -1152,26 +1078,12 @@ "if": { "properties": { "provider": { - "enum": ["mistral-vertexai"] + "enum": ["vertexai"] } }, "required": ["provider"] }, "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "codestral", - "mistral-nemo", - "mistral-large" - ] - }, - { "type": "string" } - ] - } - }, "required": ["projectId", "region"] } }, @@ -2428,7 +2340,7 @@ "nvidia", "bedrock", "sagemaker", - "vertex" + "vertexai" ] }, "model": { @@ -2507,7 +2419,7 @@ "if": { "properties": { "provider": { - "enum": ["vertex"] + "enum": ["vertexai"] } }, "required": ["provider"] diff --git a/extensions/vscode/continue_rc_schema.json b/extensions/vscode/continue_rc_schema.json index 86304fa6e..baef5f84e 100644 --- a/extensions/vscode/continue_rc_schema.json +++ b/extensions/vscode/continue_rc_schema.json @@ -172,7 +172,6 @@ "openai", "free-trial", "anthropic", - "anthropic-vertexai", "cohere", "bedrock", "bedrockimport", @@ -184,11 +183,9 @@ "llama.cpp", "replicate", "gemini", - "gemini-vertexai", "lmstudio", "llamafile", "mistral", - "mistral-vertexai", "deepinfra", "groq", "fireworks", @@ -201,7 +198,8 @@ "sambanova", "nvidia", "vllm", - "cerebras" + "cerebras", + "vertexai" ], "markdownEnumDescriptions": [ "### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/openai)", @@ -844,53 +842,6 @@ } } }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "anthropic-vertexai" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "cacheBehavior": { - "title": "Caching Behavior", - "description": "Options for the prompt caching", - "properties": { - "cacheSystemMessage": { - "type": "boolean" - }, - "cacheConversation": { - "type": "boolean" - } - } - }, - "model": { - "anyOf": [ - { - "enum": [ - "claude-3-5-opus", - "claude-3-5-sonnet", - "claude-3-5-haiku", - "claude-3-opus", - "claude-3-sonnet", - "claude-3-haiku" - ] - }, - { - "type": "string" - } - ] - } - } - } - }, { "if": { "properties": { @@ -1005,44 +956,6 @@ } } }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "gemini-vertexai" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "gemini-pro", - "gemini-1.5-pro-latest", - "gemini-1.5-pro", - "gemini-1.5-flash-latest", - "gemini-1.5-flash" - ] - }, - { - "type": "string" - } - ] - } - }, - "required": [ - "projectId", - "region" - ] - } - }, { "if": { "properties": { @@ -1260,7 +1173,7 @@ "properties": { "provider": { "enum": [ - "mistral-vertexai" + "vertexai" ] } }, @@ -1269,22 +1182,6 @@ ] }, "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "codestral", - "mistral-nemo", - "mistral-large" - ] - }, - { - "type": "string" - } - ] - } - }, "required": [ "projectId", "region" @@ -2725,7 +2622,7 @@ "nvidia", "bedrock", "sagemaker", - "vertex" + "vertexai" ] }, "model": { @@ -2822,7 +2719,7 @@ "properties": { "provider": { "enum": [ - "vertex" + "vertexai" ] } }, diff --git a/gui/public/logos/vertexai.png b/gui/public/logos/vertexai.png new file mode 100644 index 0000000000000000000000000000000000000000..1744c1f07a37579c2fc0729b51400ebd52ff1535 GIT binary patch literal 10024 zcmch7XH-*Lv@S$?34(}JMY>W#FF{axM+KyakU&I0N+P|6CUTJ8L7H@xE=Y$^6qQ~S zkQ%9>_nzS09M3uT{6uAEM3kB$NF@%frPl%g?0+-TxKu%M= zdz>mr7aL9~5ouwBn4~zTjGTy=w5Xi8q!6dLsF(~yR0bj@AuK8e6_tic$Z`JlZ~@U= z9zTH^sH*=J3*Z#E?A+W?Pzc1+(^JG#LImkz3lWo(lY@wgL&U{}0fextx3im-m$0)d z_un2=ZCnv9_9!=dq%-HaM=NWjyPEIdoKXL`b$0!$O+dpSUREfGn26|kNq+)6%E8)XAAuyIAYyC7@;IQMxd6ja5<#>x%pVuVCG{@ulU zc1Sm*s~r->siJb;HCavp6MN^!NKe-rf74CMT9|I1{_^tgd1PlS<_xl_CTLP@VVZROkF#&@9FW(>9nzkNYyDwP(2?`iieBi=r zC|P?CY*^hm%%a~7NM_tZac_HZ9uiwChJf5WL)Nc{Yu)u^QP;uNR91d^P*Gl77$FRIb*}MLCSOE&&%uo z(Q=1B>SatMo^L>l;I6p(VWr19Vg0{ARc z>W61$GT-5Y4NBj?6(mWo3Dyt$Tx)A)o_AMEM%ZPDd<6hkMzMrhwxrR1B+0! zU31CEN-$eVs_niLn~@VsSwy9jlq1ZOzgg{biD3y-MyR0!|F4fwb$);EM)r0Beuv~i|rGq zzxX5!Jr6JOXbw@cCNqq%-_hLktJ54pl@+VaKGDlvPO=i$L?YvEv2=Esy~t5fKh8h& zf8n4Y%rJPje5vUHY}_%NQMx5Tt>#tQ(%rQv0Q%wQq`|8km)?Xr<=e3@-9)Gm*&!FpNdj*;SDEVy_C_u4`d7UDts!!ZHO3Lb=jeMYDqKs!`>gRTSJU zTr>bvQSkQYr6{!j57AjR`SxfJl&rpmT&9{SVtXngTw-W#<_-M^fBQ)zYm9F6L6?on z!9*hijMl#WpzM*{P%qco;%IG|V<=_!;$f`0)h1i%E4jL#aB?e?em+cLyQxA|H`HgP zH!o_s>icdSO-WvTX-kNShU93>qH)Hg><)B%RB*6qsE12Ku|6kF&D5FJL#=?K>U2#L z#c0)@3_E0Ev`U0AT1jT#e?I6ZeTmQ8e-zy)f5}5Mg7!%lG9{v7c<_-qdP#Z6$rWr<=d@uN&N5u%xlQ$^ajtJcirT};i5P?(ORq*oGu5Yhp+4d4%;xuze9nhIc7BMn zPT9KU$sO&~)4xc?Q!=qnQ~1B>AT3yvJ7xD_S$C{nreD+|nL2~|*>Fd$L!{f;A6cEI zcdC!6%IXxD+`i1$&LU3Gv*%v(?<@6R*m5;sj~Z!F7L4FL{@yawrF{BQgx6G1@RG!e~9NV)AzUIkf$64_MR_OP6Cp zEMzKl_B3I~Hw*co3-WANuq|$H!2}KQnny~jel5pjb74}pOiboefFk%!Wx4E{7Is$e z72x9^qIt)N!CXtDLE!UTQo6GreE1J=1Ro#8%F$Y)h}<&%B>V}2mTBO#RLRPF+)P~xEYV#m z5f)*`f#Wus@;0m94Pjbniic&|X~=?Y1`_9L0!E(wpmFIhpJR_ktzouCWMJY*ypyea zk~^AXsUmRNVWBjF@T>KcU#t^aIQQ_EkIh8c(qQr*u4^kaluo4ehh^UH914Sh+ta!Dreru!hE{V!~(YbZR>o2q4r<)4-l7Ek&`uE zS1@|fm+dB|V9d53N(uMEF2=MBlmHzYqMnd}_$9x0tcOMm6Vyl6WedTi*oiataW z?kn_gV-#a;NHUDJ39o5P%;rZ$P03d~eR|(?_rt%9Q^tranOxH$7tHyvs}c2whw)Hm zU%6s3cqD4poa`93EV_?hL3}`F`S=x^WrW=a5A|)j9EW`T&~&V=(4tndbl*s8$+Ld% z8JMHQZO*rmLgNcyO>Z!?O+dVp)Rn=gYprV^F6h%*&n|~!3^Ey3?)P`A&eOqZ@p+jX&hK}0~5eX7vELR;AdX2lisQ? z>xkxf(^Q)8ES5j!*YbFHSVsV}At})MwGUk`)SlqBQ%oY*8a^pM{;6JGyK?uOGjl61 zTeBhUKlhz&f8woBk514=C&5W&ix+l}!>-)MXjg!4u`eC%b#_Ps_Dhz5#pta5au{zM zjQ6OJLGHO!{~_fWe>ff*?Jg0zj`YgTkAw5)RtdK@Kbxl89&QBe*}YCC`Uzs_!+Vr{ z!#qKF{gbS@X2>Oqt^TaJGJ_)q<2kV`@7O!R{u~Y_dU(9P!l&E*^tW3T@73p_@%ZE{ zYvo=$UN4!SznE2!i`UVy*sWf>fI_QU5IZ48Y+g}O+c{$%!n>ZI2&44K5--aEu1rB% ztKLV`DcG{(uiTRl*9;S*VZ3SZr5m-<@iRQ6w~g)Nt4k4AXT475Gm3U5o&>9m!o%bm zWL122<`v9Gy&Ks@DXlfGU0I83X*ByfWfVKpd@R_xlkO30 zL9M7yz51hjc-5oM$qVgrvXh2)PJ%m?RGXU$k4_EyCr)+y9}sF`gx*V&JX=#dP9?pC z>zAiTG0henlQM^xv#_F6yWnfSUgS@$6nuAAj#uo^jI$2@IZ*|n?oJB|)?T4r)O6LA z)fHv3soNXt?<87|M@_PD1ufq?huRy)Dt!nmpWY!9Pxl@COCvTEzIAFFct==lPCU@? z-;MaR_c`}!#7JkuH1^3dfnZ@fe5%+nb2inXz>kwX%Hj9S-0mGZ^}E~}GxM&4k|sfM zf4)rYuKj|eaHh532|3*cYqLe8F@G_GGiMVQ=zuZLW&+ zdq1|-r}8vG*_n#4P#bynx;Ps~zk>C!RtT&#_;f!z>o8M3CMwwQ{ldi~`}x^ZC6=>K z&PRRyial|$rDr@_o0!u0XSYv(ZZ&IcgYW?dea;$j+?07D=uncUrguW&57wxB*oZgb z52hj)w!NIn4+t=u#?M)q8);eg@4wufjkvWG-L34+7)KwMc8keRjjYtf16?f8D{Tti zNb%2K)^YpJqmmYzi zHSutnRCcIj$U!M`mWu9cPNwa^Cc2n`(;~EXejrN%_v_4vSNR>)>VEu}97x}50)M|i zNs4NM3M^Hrr~uhOh5VZH-P`Hq+|vA>Ki8+i_(u$SU;=M|ug(0iN)peFgV68sc8fWf z`C>WT%%$&#b8f~y7m}^DBzFgpj|Vo-40(IGKB)Y9swHVl1>4yXi9WdJ1;lDV?JW_rQCADom@=86P@0Sk^rW%bIWz^@P5bQ;WMea9+s~-91r6#Fg zG;XjAQy*I5WB8fESu(1f8@CsJjS`bW@{_S^P@8*DGX9K*?K=Mg?yi8sX;j=M&<5{`p@AapT$)x+rG9g<03CQzDrBoYr}RBalf_E3d6onL5ZFG z5$$eDAFL;)FXeBE<+86vQ;2kH#oJ3ROW0Q@T+DdPs<)peIj%>cU(T9&-~Y+`q5Bm2 zrL4VMWGWne$|wUB4%Zrtm~=auPJpuIm{3PQJ*)tdZokHo@-n}YzOOI!N<`df)Yd}- zERRS;;VGLt_u6-?yk1DrhK`xs#7rHVRZ&4nSz+tKkoS#)L)UxU8=YOH}h7BrmLPo0xq={dAM3ULor_hB-r> zrQ23M{D3}T@M~ga7LDZ`glGEV#tpW~)mccs)0Rben>2QZmZnUp_9OgKPh3P!2~snSk! zSz5(|BXYXrWkAI=4`$0*ZqYp0AW%HgZc10ZkQx-7y2n9TB08XSVT?hZyf^YiNzJtGL#s$BeYaq}ZTK-}kwmn>4%*gGU`I8On9GKp zPHFYf8Dy-8WP1NmXAl7cO(=|_Ixkb1(Tck9ReV=wA{C-Ci*&&;y?^3meP!KgYbdjg zjM|KpRH!>tXxVA2Sw6`3pr(znVvN-A(~!b+fGPvN;HA49f=`x{KA^eRnq`vAm4q@N z{bOEhVNDyGP}>YynwR8J7Faa@XL*r>yO2kSt56%PYv3m{%ga6wyI@RWj?LY}VWsw& z7t1G%W1VVMk@sdHHg;2%3>-Xo8`cI9GLiZ@n(Jpn8bf-yEN$(u6U_!KNlHmTz@VS2 z^?JLO7V1pe;>4f_io!?+yC>MG%Who>3jK3WQLk`j=%pY(-21sQvQN z?7;N1kOcMya_agQ3<31AL+k7g4_mQ6U|}-d(zPK(aS=p zwQ}E}i5C7>R7`;A8`QXQ*Oc3_4ff;)VrV5j-&>QZIh7Y@LmxNwW7w8j;@8g^{W z{`yY{XjnTp^f`uN&5P%i@1IC>EfP3h4L)TLe)4C&DxwnXM-z&xJS5I@9+@D-)*)H` zbyPhc(HsOMaZih=6Gn2t98B4I6w%snJ(VaDLm|ZeKd|0CGy(Lco?NdGnt)aNr9pO; zb{Gj0xa~YLmdOtH6ztp%NSs6UxdX1tSOICSzJPB81EHM5`KFFlfI%Ji##2>sd{Jf4dgUa9+mEvIbg__<}(l&Op3 z8C3CkyRj|V-I5;IqyL%q>{ZTfzp;}MFKxPIagRK2^fD&4Uqc=*#TX~=sRPxbOsTlK zARJu0y*o%0uwHR+^Vv50YYB50@(_-PNk`{k(k1o_8o7x$OyTQp9RRn zq*HpV0x`*B5#&Fa=Mt&gk(!@2BQYdaI&+DnKV?J_ELe!rm_E2PLkaTIyd>2x2vZ2v z9?o~Q`$==+m3KKIYHO5n;<+m>a_?BW)D_Pg6)o0%UH(&LH?rP(hZtyqpzq|baWn9D zIh>lu#N`Cxtx+SXhwj{d3%9DDlKJ}*m#y&sMEV)^%RD;#PTpnmf#oNppu{};#-t9%HRqS*_KQmCqlrK7 z&22EL?O!B4n-)2~Ig9(udMk=mOG7FkhRLLdB0%r@C|y}VTjRJEPaen-2=Y|IY}lx# zl{$}lvAy07??nBf9@oGh|FNdEv1cXt#(68x#G~{oMwq-}CoIGy@KS2EDIfVv9jI^B zHd*T*>D*{oKi3}F`F_gSPBC!nPRCv#E%_s~gyYQM%Tv!wO$OscS4OVrMq>(11)V}Z ze^7kZK_<&5h__*zT#>Dg#n^^ku4;oB3N-&1xVPG&3(CA9l!|l<**;X?3ysG?ZG%Jm zK-VOVdng0+Di8hnyi`F`$_!B$ozArsN=0!gb~V%C_Dtfk*U#Y&300Iuy=F zsy|;4O+NY)BycDaF%UW%oc0rPy>44vQUR_R8r~sZtxoULIUBOd0u@rx(N*3w^}To@ zJRDbHZx_zB7hXUv=Cx(=BH1hPI$~Lg=7b6qrqKU-KrJ_wI_@5hCv-};evVH_lRR{y zGFb_xN=Yq%SU!lOA`XfXlK&&L-B4>aaPvNnYXRWYM$N9->yy#W57gjD{Q6$fuztyL zXKT}VI&g>MVJ*EQhV~Y`S4nqmW?S(Y?^YTwxmdj??^d9kohJ3^?m%;3c}_S<`1JwJ z9Uf70xTf>m-6jW}Cx|kvca!mu{#NBu*2ueaDY#%!Z1(Lmkt_aEe z(aRY0){6Ln&;?M;oAce_(V2S1v6i;J_#L;NY}?c$`cy7S)uM=2#+)E=NsxplW$o)F zb@*ynoYyxR*47hl+mve>?=CW5G(D8OV8NpqD+b~gC+nKRIR=Ipcf27IH9N*!`=HXjUm(IkpySL(VC^(t z8Dw%mx_Ik?>SH7fTL}r$5Q6^kITI2@cR+fz0>^n(;S{uaLGkk$4|#2)%0m{nFYKS` z%+$cNj|U2IVScfJtru1XV(*bzkogbf=7MRz4$yCTvhJyYqTo;DIGGMXpu52>ny+Jw z9*_#sSywP^$zat>`1PqkyQ&PTRwbNUvbY4s6V2-2>tG$ypfIIuBLNCs7HWeVR!Ixc zwLBh@MHlTqT8)&ktuYTZnR_bHb+2-sV}@JHp*j@0{FG%+xUO&cV@v7isKCumfDxntzevM;+47;haPc`pUPTG18}6iau&HQpGxL zrSz(il$V541Xc|Livm=n-`yu7T+4_dWV8g5Z~J2 zbL}mU=mebNr{&j~_lp|N`7}@1XhdXM_d8|hrQ05fQ(vh{*{L02{(OmCIEdUW-}h9ch7`*Tl@*RLn1jO|b9Kms}#6yZ4n6uEP@@ z^TPcuS|ie{bJxpiVDQ6VzY3E+Og$Z+x=GWKA<@4}$La68nc+(wCK&JyPS>VBc&mfc z6eE}gf^eu)k2SXCuX=tr#1@nV4Q-YVE5>G+G`#7aH>x)jF{_zPb?75lh@S*hY6yc>UC3>7xBx zwrcocuJ`z+=o3t%19~GQmDsl`h~Gn9>@<^Z1dl~B-S=*c4bbxlIcOZB>ry

Da1n z=4aT~F>ZcXg^4iVsvM;@Q#?DEJCL_H9lrL7)@#sz4hCtSsw0#&hk%>IYNGgX>%}V` z138BShkXRNTVqjw#{fZJ@Q5m!snX)%bG`EM#*pZiFiVm4tmhLad-62X$jkCLoG-4x za1JL8&L$t+EqzSR5kS|xH?G*=B;wI=X#N%4K;e7sWH~%O!mL!Bv@t@agEWffK04c%$o5jF`OE(6{wd0Z^t?=ls~ARHRrY@D6#{6~K27cDW({4) zz93wq^%?9bkdD*qIpci&RJwHE(lvSC$nektfX=u`nwu6m3$iq*{K=q+ogUl%>mqj5G0<80<7|@~`zoxGq zRb5RLP?PNE3tRew0vdq6fAj|H;vEc#Z~nqohuKi&dG6%c2K03u4CsJ}{ZJCHJ>PrJ zorXUfyjKJmVTO=TG3j^*!IR4uZvZne|cHm5jjVG1PyAgQVGZyFu8~jsq9I)Gp zIr(7N>dwi=pv#_&r7+?m7C0%ccIAFGfF`miR{;vSruULF8km(}4o;`pqVr~uYd)h( z0FFF3wF3^byo-Sd`iRswGq&e`mX%fxA5 zs+>ec;-SFTvb)M?PZ&))AHLr0&3w(ZB@-x6(5TGpRSEze9Wx8g+Xu>-Tf!60L?eN7 ztrCbZ_8JCe@RH)0$IE0d$u7W60`od!>GldRMj1K*<#q|9Kp7JzK^z`H2Wn+zq4I!X zLdMw!qmvsygjk+HyLQmrO0u>mP!f79hHa^ zH#X6a@mC2EYdk_js!!dM-FYR6(=ACo5cEtap@OHv?VuX`!{_uB3!_{@@GN=18a%58 z_1Ko&&$O)%vm}#_!Ci>%>QV8`B{>N6(w~YB^_qR;`nK@eR5!JCQ>7e zfeAJCBZ-VQpVV=0axtj7(F~Ma{+u+@Pl1}+v_;djH7e^?x90`tOls;nG8J+Sw#M;i zrJBTz?w5~)7c#w*17!|zt9`qR8beoKkT&IL%uvU)cnpESPgneBSUra%x+?;UANlF{ zE;ZN=C0h}j`>EWfo$;f86F3^M^Wn(3chj?G2xMuycI&`|sYY?orGf{0nJ&sPlWj+~ z#EQ7sqyuCOF`v-!y~?yzRcMUZmv%37pYtat{`D)Js^IN|s{Ul>a^a7lv*RK8tyl2a z(4#7TYvSAfE18z2K59bnZ3D!|n&Fz>S=uw*Ta7*ttg%QF!DTj0CN!qDs{b0vWUl*R zi-knU9_yiiCvT0XM*y^`2X`YAG MQqxy0Q-%ls2hrHpq5uE@ literal 0 HcmV?d00001 diff --git a/gui/src/pages/AddNewModel/configs/models.ts b/gui/src/pages/AddNewModel/configs/models.ts index f3e0b9cfe..ca6844667 100644 --- a/gui/src/pages/AddNewModel/configs/models.ts +++ b/gui/src/pages/AddNewModel/configs/models.ts @@ -791,6 +791,33 @@ export const models: { [key: string]: ModelPackage } = { providerOptions: ["watsonx"], isOpenSource: false, }, + VertexGemini15Pro: { + title: "Gemini 1.5 Pro", + description: "A newer Gemini model with 1M token context length", + params: { + title: "Gemini 1.5 Pro", + model: "gemini-1.5-pro-002", + contextLength: 2_097_152, + }, + icon: "gemini.png", + providerOptions: ["vertexai"], + isOpenSource: false, + }, + VertexGemini15Flash: { + title: "Gemini 1.5 Flash", + description: + "Fast and versatile multimodal model for scaling across diverse tasks", + params: { + title: "Gemini 1.5 Flash", + model: "gemini-1.5-flash-002", + contextLength: 1_048_576, + }, + icon: "gemini.png", + providerOptions: ["vertexai"], + isOpenSource: false, + }, + + AUTODETECT: { title: "Autodetect", description: diff --git a/gui/src/pages/AddNewModel/configs/providers.ts b/gui/src/pages/AddNewModel/configs/providers.ts index 1bca2efff..dfaac3ffd 100644 --- a/gui/src/pages/AddNewModel/configs/providers.ts +++ b/gui/src/pages/AddNewModel/configs/providers.ts @@ -626,4 +626,36 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo ], apiKeyUrl: "https://cloud.cerebras.ai/", }, + vertexai: { + title: "VertexAI", + provider: "vertexai", + description: "Use supported vertex AI models", + longDescription: + "Use the supported vertex AI models - see [here](https://cloud.google.com/docs/authentication/provide-credentials-adc) to authenticate", + icon: "vertexai.png", + packages: [ + models.VertexGemini15Pro, + models.VertexGemini15Flash, + + ], + collectInputFor: [ + { + inputType: "project", + key: "projectId", + label: "Project Id", + placeholder: "Enter your Vertex AI project id", + required: true, + }, + { + inputType: "region", + key: "region", + label: "Region", + placeholder: "Enter your Vertex AI region", + required: true, + }, + + ...completionParamsInputsConfigs, + ], + }, + }; diff --git a/packages/llm-info/src/providers/vertexai.ts b/packages/llm-info/src/providers/vertexai.ts new file mode 100644 index 000000000..e9514bc25 --- /dev/null +++ b/packages/llm-info/src/providers/vertexai.ts @@ -0,0 +1,38 @@ +import { AllMediaTypes, ModelProvider } from "../types.js"; + +export const Gemini: ModelProvider = { + models: [ + { + model: "gemini-1.5-flash", + displayName: "Gemini 1.5 Flash", + contextLength: 1048576, + maxCompletionTokens: 8192, + mediaTypes: AllMediaTypes, + regex: /gemini-1\.5-flash/i, + recommendedFor: ["chat"], + }, + { + model: "gemini-1.5-pro", + displayName: "Gemini 1.5 Pro", + contextLength: 2097152, + maxCompletionTokens: 8192, + regex: /gemini-1\.5-pro/i, + recommendedFor: ["chat"], + }, + // embed + { + model: "text-embedding-004", + displayName: "Vertex Text Embedding", + recommendedFor: ["embed"], + }, + //autocomplete + { + model: "code-gecko", + displayName: "VertexAI Code Gecko", + recommendedFor: ["autocomplete"], + maxCompletionTokens: 64, + } + ], + id: "gemini", + displayName: "Gemini", +}; From cb45761e426adc14cc3d90db45a0b4d7442daeab Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 24 Oct 2024 14:31:22 +0700 Subject: [PATCH 09/34] test: add more languages --- core/autocomplete/test/testCases.ts | 1906 +++++++++++++++++++++++++++ core/util/parameters.ts | 2 +- manual-testing-sandbox/Dockerfile | 18 + manual-testing-sandbox/config.yaml | 14 + manual-testing-sandbox/data.json | 8 + manual-testing-sandbox/program.cs | 34 + manual-testing-sandbox/query.sql | 9 + manual-testing-sandbox/readme.md | 4 +- manual-testing-sandbox/test.css | 2 +- manual-testing-sandbox/test.html | 25 + manual-testing-sandbox/test.java | 28 + manual-testing-sandbox/test.php | 44 + manual-testing-sandbox/test.py | 18 + manual-testing-sandbox/test.rb | 30 + manual-testing-sandbox/test.sh | 21 + 15 files changed, 2159 insertions(+), 4 deletions(-) create mode 100644 manual-testing-sandbox/Dockerfile create mode 100644 manual-testing-sandbox/config.yaml create mode 100644 manual-testing-sandbox/data.json create mode 100644 manual-testing-sandbox/program.cs create mode 100644 manual-testing-sandbox/query.sql create mode 100644 manual-testing-sandbox/test.html create mode 100644 manual-testing-sandbox/test.java create mode 100644 manual-testing-sandbox/test.php create mode 100644 manual-testing-sandbox/test.py create mode 100644 manual-testing-sandbox/test.rb create mode 100644 manual-testing-sandbox/test.sh diff --git a/core/autocomplete/test/testCases.ts b/core/autocomplete/test/testCases.ts index 64c9e8e37..d171c9f5d 100644 --- a/core/autocomplete/test/testCases.ts +++ b/core/autocomplete/test/testCases.ts @@ -105,4 +105,1910 @@ a { }`, filename: "test.css", }, + { + description: "Should complete CSS rules inside a nested selector", + filename: "styles.css", + input: ` +.container { + display: flex; + justify-content: center; + align-items: center; + width: 100%; + height: 100vh; + + .inner { + <|fim|> + } +} +`, + llmOutput: `width: 50%; + height: 50%; + background-color: #f0f0f0;`, + expectedCompletion: `width: 50%; + height: 50%; + background-color: #f0f0f0;`, + }, + + { + description: + "Should complete a CSS rule when the property is partially typed", + filename: "styles.css", + input: ` +button { + border: 2px solid #000; + border-radius<|fim|> +}`, + llmOutput: `: 5px;`, + expectedCompletion: `: 5px;`, + }, + + { + description: "Should handle CSS autocomplete with a single bracket present", + filename: "styles.css", + input: ` +.card { + box-shadow: 0 4px 8px rgba(0,0,0,0.2); + transition: 0.3s; + padding: 16px; + border-bottom-left-radius: <|fim|>px; + border-bottom-right-radius: 8px; +} +`, + llmOutput: `8`, + expectedCompletion: `8`, + }, + + { + description: "Should autocomplete CSS pseudoclass", + filename: "pseudoClass.css", + input: ` +input:focus { + outline: none; + border: 2px solid <|fim|>; +} +`, + llmOutput: `#4CAF50;`, + expectedCompletion: `#4CAF50;`, + }, + + { + description: "Should handle CSS variable syntax", + filename: "variables.css", + input: ` +:root { + --primary-color: #3498db; + --padding: 10px; +} + +.section { + background-color: var(<|fim|>); + padding: var(--padding); +} +`, + llmOutput: `--primary-color`, + expectedCompletion: `--primary-color`, + }, + + { + description: "Should complete CSS grid template columns", + filename: "grid.css", + input: ` +.grid-container { + display: grid; + grid-template-columns: repeat(<|fim|>); + grid-gap: 10px; +} +`, + llmOutput: `3, 1fr);`, + expectedCompletion: `3, 1fr);`, + }, + + { + description: "Should complete PHP function inside a class with comments", + input: `name = $name; + $this->email = $email; + } + + public function <|fim|> + + public function setEmail($email) { + $this->email = $email; + } +}`, + llmOutput: `getDetails() { + return "Name: " . $this->name . ", Email: " . $this->email; + }`, + expectedCompletion: `getDetails() { + return "Name: " . $this->name . ", Email: " . $this->email; + }`, + filename: "User.php", + }, + + { + description: "Should autocomplete PHP function with inline logic", + input: ` +} + +echo calculateArea(5, 3);`, + llmOutput: `return $length * $width;`, + expectedCompletion: `return $length * $width;`, + filename: "areaCalculator.php", + }, + + { + description: "Should handle PHP completion in the middle of an array", + input: `); + +echo "First color is: " . $colors[0];`, + llmOutput: `"Blue"`, + expectedCompletion: `"Blue"`, + filename: "colors.php", + }, + { + description: "Should autocomplete React return statements (jsx)", + input: `import React from "react"; + +export const Button = ({ + onClick, + children, +}: { + children: React.ReactNode; + onClick: () => void; +}) => { + return ( +<|fim|> + ); +};`, + llmOutput: ``, + expectedCompletion: ``, + filename: "Button.tsx", + }, + { + description: "Should autocomplete React state initialization", + input: `import React, { useState } from "react"; + +export const Counter = () => { + const [count, setCount] = useState(<|fim|>); + + return ( +

+

You clicked {count} times

+ +
+ ); +};`, + llmOutput: `0`, + expectedCompletion: `0`, + filename: "Counter.tsx", + }, + + { + description: "Should autocomplete React effect hook", + input: `import React, { useState, useEffect } from "react"; + +export const Timer = () => { + const [seconds, setSeconds] = useState(0); + + useEffect(() => { + const interval = setInterval(() => { + setSeconds(seconds + 1); + }, 1000); + + <|fim|>; + + return () => clearInterval(interval); + }, [seconds]); + + return ( +
+

{seconds} seconds have passed.

+
+ ); +};`, + llmOutput: `return () => clearInterval(interval);`, + expectedCompletion: `return () => clearInterval(interval);`, + filename: "Timer.tsx", + }, + + { + description: "Should autocomplete React component methods", + input: `import React from "react"; + +class Form extends React.Component { + constructor(props) { + super(props); + this.state = { name: '' }; + } + + handleChange = (event) => { + <|fim|> + } + + handleSubmit = (event) => { + event.preventDefault(); + alert('A name was submitted: ' + this.state.name); + } + + render() { + return ( +
+ + +
+ ); + } +}`, + llmOutput: `this.setState({ name: event.target.value });`, + expectedCompletion: `this.setState({ name: event.target.value });`, + filename: "Form.tsx", + }, + { + description: "Should autocomplete Python function definition", + filename: "test.py", + input: `def calculate_area(length, width): + area = length * width + return area + +def calculate_perimeter(length, width): + <|fim|> +`, + llmOutput: `perimeter = 2 * (length + width) + return perimeter`, + expectedCompletion: `perimeter = 2 * (length + width) + return perimeter`, + }, + { + description: "Should complete Python class method with self", + filename: "test.py", + input: `class BankAccount: + def __init__(self, owner, balance=0): + self.owner = owner + self.balance = balance + + def deposit(self, amount): + self.balance += amount + return self.balance + + def withdraw(self, amount): + <|fim|> +`, + llmOutput: `if amount > self.balance: + return "Insufficient funds" + self.balance -= amount + return self.balance`, + expectedCompletion: `if amount > self.balance: + return "Insufficient funds" + self.balance -= amount + return self.balance`, + }, + { + description: "Should autocomplete Python list comprehension", + filename: "test.py", + input: `squares = [x**2 for x in range(10)] +even_squares = [x for x in squares if x % 2 == 0] +print(even_squares) + +odd_squares = [<|fim|> +print(odd_squares) +`, + llmOutput: `x for x in squares if x % 2 != 0`, + expectedCompletion: `x for x in squares if x % 2 != 0`, + }, + { + description: "Should handle python multi-line string", + filename: "test.py", + input: `def create_greeting(name): + greeting = """Hello, """ + name + """! +Welcome to our community. We hope you have a great time here. +If you have any questions, feel free to reach out.""" + return greeting + +message = create_greeting("Alice") +print(message) + +multi_line_message = """<|fim|> +print(multi_line_message) +`, + llmOutput: `This is a multi-line message. +It continues across multiple lines, +which allows for easy reading and formatting. +""" +`, + expectedCompletion: `This is a multi-line message. +It continues across multiple lines, +which allows for easy reading and formatting. +""" +`, + }, + { + description: "Should autocomplete a simple Go function declaration", + filename: "simpleFunction.go", + input: `package main + +import ( + "fmt" +) + +func main() { + fmt.Println("Hello, World!") +} + +func calculateArea<|fim|>`, + llmOutput: `(length float64, width float64) float64 { + return length * width +}`, + expectedCompletion: `(length float64, width float64) float64 { + return length * width +}`, + }, + + { + description: + "Should handle autocomplete in the middle of a Go struct definition", + filename: "structDefinition.go", + input: `package main + +type Person struct { + FirstName string + LastName string + Age int + Address Address +} + +type Address struct { + Street string + City <|fim|> +} + +func main() {}`, + llmOutput: `string + State string + ZipCode string +}`, + expectedCompletion: `string + State string + ZipCode string +}`, + }, + + { + description: "Should autocomplete a missing Go function body bracket", + filename: "missingBracket.go", + input: `package main + +func add(a int, b int) int { + return a + b<|fim|> + +func multiply(a int, b int) int { + return a * b +} + +func main() { + result1 := add(2, 3) + result2 := multiply(4, 5) + println(result1, result2) +}`, + llmOutput: ` +}`, + expectedCompletion: ` +}`, + }, + { + description: + "Should autocomplete SQL query with subquery and alias in SELECT clause", + filename: "complex_query.sql", + input: `SELECT u.id, + u.name, + (SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) AS order_count + FROM users u + WHERE u.active = 1 + <|fim|>`, + llmOutput: ` AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)`, + expectedCompletion: ` AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)`, + }, + { + description: + "Should autocomplete SQL query with nested functions and missing bracket", + filename: "_nested_function.sql", + input: `SELECT name, ROUND(AVG(rating), 2) as avg_rating + FROM movies + WHERE release_year > 2000 AND director = 'Christopher Nolan' + GROUP BY name + HAVING avg_rating > <|fim|>`, + llmOutput: `8.5)`, + expectedCompletion: `8.5)`, + }, + { + description: + "Should autocomplete multi-line SQL query with CASE statements", + filename: "case_statement.sql", + input: `SELECT order_id, + order_date, + CASE + WHEN status = 'shipped' THEN 'Completed' + WHEN status = 'pending' THEN 'Pending Approval' + <|fim|> + ELSE 'Unknown' + END as order_status + FROM orders`, + llmOutput: `WHEN status = 'cancelled' THEN 'Cancelled'`, + expectedCompletion: `WHEN status = 'cancelled' THEN 'Cancelled'`, + }, + { + description: "Should autocomplete HTML paragraph content", + input: ` + + Document + + +

<|fim|>

+ +`, + llmOutput: `This is a paragraph with some sample text.`, + expectedCompletion: `This is a paragraph with some sample text.`, + filename: "test.html", + }, + { + description: "Should autocomplete HTML attributes within a tag", + input: `
+ > +
+

Title

+

Description text.

+
+
`, + llmOutput: `alt="Description of image"`, + expectedCompletion: `alt="Description of image"`, + filename: "test.html", + }, + { + description: "Should autocomplete HTML nested tags", + input: `
    +
  • Item 1
  • +
  • Item 2
  • +
  • Item 3
  • +
`, + llmOutput: `>Item 4`, + expectedCompletion: `>Item 4`, + filename: "test.html", + }, + + { + description: "Should complete a class method in Ruby", + input: ` +class Greeter + def initialize(name) + @name = name + end + + def greet + puts "Hello, <|fim|> + end +end + +g = Greeter.new("World") +g.greet +`, + llmOutput: "#{@name}!", + expectedCompletion: "#{@name}!", + filename: "greeter.rb", + }, + { + description: "Should complete Ruby if-else block", + input: ` +number = 10 + +if number > 5 + puts "Number is greater than 5" +<|fim|> +end +`, + llmOutput: `else + puts "Number is 5 or less"`, + expectedCompletion: `else + puts "Number is 5 or less"`, + filename: "conditional.rb", + }, + { + description: "Should complete Ruby array method", + input: ` +numbers = [1, 2, 3, 4, 5] +squared_numbers = numbers.<|fim|> +`, + llmOutput: `map { |n| n ** 2 }`, + expectedCompletion: `map { |n| n ** 2 }`, + filename: "array_methods.rb", + }, + { + description: "Should autocomplete a Java method within a class", + filename: "Calculator.java", + input: ` +public class Calculator { + private double result; + + public Calculator() { + this.result = 0.0; + } + + public void add(double number) { + result += number; +<|fim|>`, + llmOutput: ` + } + + public void subtract(double number) { + result -= number; + } +`, + expectedCompletion: ` + } + + public void subtract(double number) { + result -= number; + } +`, + }, + { + description: "Should autocomplete Java when inside a block", + filename: "Main.java", + input: ` +public class Main { + public static void main(String[] args) { + for (int i = 0; i < 10; i++) { + if (i % 2 == 0) { + System.out.println("Even: " + i); + } else { +<|fim|> + } + } + } +}`, + llmOutput: ` + System.out.println("Odd: " + i); +`, + expectedCompletion: ` + System.out.println("Odd: " + i); +`, + }, + { + description: "Should autocomplete Java within a string", + filename: "App.java", + input: ` +public class App { + public static void main(String[] args) { + String message = "Hello, <|fim|>"; + System.out.println(message); + } +}`, + llmOutput: `World`, + expectedCompletion: `World`, + }, + { + description: + "Should autocomplete a C++ class definition with a constructor", + filename: "test.cpp", + input: "class Vehicle { public: Vehicle(<|fim|>); };", + llmOutput: "int wheels, double weight", + expectedCompletion: "int wheels, double weight", + }, + { + description: "Should complete a C++ method declaration inside a class", + filename: "test.cpp", + input: + "class Calculator { public: int add(int a, int b); int subtract(int a, int b);<|fim|> };", + llmOutput: " int multiply(int a, int b);", + expectedCompletion: " int multiply(int a, int b);", + }, + + { + description: "Should autocomplete C++ for loop syntax", + filename: "test.cpp", + input: ` + int sum = 0; + for (int i = 0; i < 10; <|fim|>) { + sum += i; + } + `, + llmOutput: "i++", + expectedCompletion: "i++", + }, + { + description: "Should autocomplete a Markdown list with nested items", + filename: "test.md", + input: ` +- Item 1 +- Item 2 + - Subitem 1 + <|fim|> +- Item 3 +`, + llmOutput: ` - Subitem 2 + - Subitem 3 +`, + expectedCompletion: ` - Subitem 2 + - Subitem 3 +`, + }, + { + description: + "Should autocomplete a Markdown heading and preserve formatting", + filename: "test.md", + input: `# My Document + +## Introduction +This is a sample document for testing. + +## <|fim|> +### Conclusion +Thank you for reading. +`, + llmOutput: `Features +Here is a list of features: +- Feature 1 +- Feature 2 +`, + expectedCompletion: `Features +Here is a list of features: +- Feature 1 +- Feature 2 +`, + }, + { + description: "Should complete a Markdown code block", + filename: "test.md", + input: ` +Here is a sample JavaScript function: + +\`\`\`javascript +function sayHello() { + console.log("Hello, <|fim|> +} +\`\`\` +`, + llmOutput: `world!"); +`, + expectedCompletion: `world!"); +`, + }, + { + description: "Should autocomplete JSON object inside an array", + filename: "data.json", + input: `{ + "users": [ + { "id": 1, "name": "Alice" }, + { "id": 2, "name": "Bob" } + <|fim|> + ] +}`, + llmOutput: `, { "id": 3, "name": "Charlie" }`, + expectedCompletion: `, { "id": 3, "name": "Charlie" }`, + }, + { + description: "Should autocomplete nested JSON objects", + filename: "config.json", + input: `{ + "server": { + "host": "localhost", + "port": 8080, + "features": { + "enableLogging": true, + "maxConnections": 100 + <|fim|> + } +}`, + llmOutput: `, + "timeout": 5000 + }`, + expectedCompletion: `, + "timeout": 5000 + }`, + }, + { + description: "Should autocomplete JSON object with missing bracket", + filename: "settings.json", + input: `{ + "theme": "dark", + "language": "en"<|fim|> + `, + llmOutput: `, + "notifications": true + }`, + expectedCompletion: `, + "notifications": true + }`, + }, + { + description: "Should autocomplete within a CSV record", + filename: "test.csv", + input: `Name, Age, City +John Doe, 30, New York +Jane Smith<|fim|>`, + llmOutput: `, 25, Los Angeles`, + expectedCompletion: `, 25, Los Angeles`, + }, + { + description: + "Should complete CSV record when starting in the middle of a word", + filename: "test.csv", + input: `Product, Price, Quantity +Laptop, 1200, 5 +Smart<|fim|>`, + llmOutput: `phone, 800, 10`, + expectedCompletion: `phone, 800, 10`, + }, + { + description: "Should complete CSV structure adding closing brackets", + filename: "test.csv", + input: `ID, Name, JoiningDate +1, Alice, 2023-01-10 +2, B<|fim|>`, + llmOutput: `ob, 2023-02-10`, + expectedCompletion: `ob, 2023-02-10`, + }, + { + description: "Should complete YAML list item and preserve structure", + filename: "test.yaml", + input: ` + services: + - name: web + image: nginx + - name: app<|fim|> + volumes: + - volume1 + - volume2 + `, + llmOutput: ` + image: node + `, + expectedCompletion: ` + image: node + `, + }, + { + description: + "Should complete YAML key-value pair inside a nested structure", + filename: "test.yaml", + input: ` + version: '3' + services: + db: + image: postgres + environment: + POSTGRES_USER: user + POSTGRES_PASSWORD: pass + POSTGRES_DB: mydb<|fim|> + `, + llmOutput: ` + PGDATA: /var/lib/postgresql/data/pgdata + `, + expectedCompletion: ` + PGDATA: /var/lib/postgresql/data/pgdata + `, + }, + { + description: "Should complete YAML block within an existing block", + filename: "test.yaml", + input: ` + pipelines: + branches: + master: + - step: + name: Build and Test + script: + - npm install + - npm run test + - step: + name: Deploy<|fim|> + `, + llmOutput: ` + script: + - npm run deploy + `, + expectedCompletion: ` + script: + - npm run deploy + `, + }, + { + description: + "Should autocomplete a Rust function implementation inside a struct", + filename: "main.rs", + input: ` +struct Calculator { + result: f64, +} + +impl Calculator { + fn new() -> Self { + Calculator { result: 0.0 } + } + + fn add(&mut self, number: f64) { + self.result += number; + } + + fn subtract(&mut self, number: f64) { + self.result -= number; + } + + fn multiply(&mut self, number: f64) { + self.result *= number; + } + + fn divide(&mut self, number: f64) { + if number != 0.0 { + self.result /= number; + } else { + println!("Cannot divide by zero."); + } + } + + fn reset(&mut self) { + self.result = 0.0; + } + + fn get_result(&self) -> f64 { + self.result + } + + fn<|fim|> +} +`, + llmOutput: ` divide(&mut self, number: f64) { + if number != 0.0 { + self.result /= number; + } else { + println!("Cannot divide by zero."); + } +}`, + expectedCompletion: ` divide(&mut self, number: f64) { + if number != 0.0 { + self.result /= number; + } else { + println!("Cannot divide by zero."); + } +}`, + }, + { + description: "Should autocomplete Rust match arms", + filename: "main.rs", + input: ` +fn get_status_code_description(code: u16) -> &'static str { + match code { + 200 => "OK", + 404 => "Not Found", + 500 => "Internal Server Error", + <|fim|> + } +} +`, + llmOutput: `403 => "Forbidden", + 401 => "Unauthorized", + _ => "Unknown Status", +`, + expectedCompletion: `403 => "Forbidden", + 401 => "Unauthorized", + _ => "Unknown Status",`, + }, + { + description: "Should autocomplete Rust struct definition", + filename: "main.rs", + input: ` +struct User { + id: u32, + username: String, + email: String, + is_active: bool, + <|fim|> +} + +impl User { + fn new(id: u32, username: String, email: String) -> Self { + User { + id, + username, + email, + is_active: true, + } + } +} +`, + llmOutput: `created_at: String, + updated_at: String,`, + expectedCompletion: `created_at: String, + updated_at: String,`, + }, + { + description: "Haskell: Nested pattern matching with let bindings", + filename: "NestedPattern.hs", + input: `module NestedPattern where + +data Tree a = Leaf a | Node (Tree a) (Tree a) + +sumTree :: Num a => Tree a -> a +sumTree (Leaf x) = x +sumTree (Node left right) = + let leftSum = <|fim|> + rightSum = sumTree right + in leftSum + rightSum`, + llmOutput: `sumTree left`, + expectedCompletion: `sumTree left`, + }, + { + description: "Haskell: Complex function with where clause and guards", + filename: "QuadraticSolver.hs", + input: `module QuadraticSolver where + +solveQuadratic :: (Ord a, Floating a) => a -> a -> a -> Maybe (a, a) +solveQuadratic a b c + | discriminant < 0 = Nothing + | otherwise = Just (x1, x2) + where + discriminant = b^2 - 4*a*c + sqrtD = sqrt discriminant + x1 = (-b + sqrtD) / (2*a) + <|fim|> = (-b - sqrtD) / (2*a)`, + llmOutput: `x2`, + expectedCompletion: `x2`, + }, + { + description: "Haskell: List comprehension with complex filter", + filename: "PrimeNumbers.hs", + input: `module PrimeNumbers where + +primesUpTo :: Int -> [Int] +primesUpTo n = [x | x <- [2..n], isPrime x] + where isPrime num = <|fim|> && all (\d -> num \`mod\` d /= 0) [2..(floor . sqrt $ fromIntegral num)]`, + llmOutput: `num > 1`, + expectedCompletion: `num > 1`, + }, + { + description: "Should autocomplete Dart class methods", + filename: "calculator.dart", + input: ` +class Calculator { + double result = 0.0; + + void add(double number) { + result += number; + } + + void multiply(double number) { + result *= number; + } + + <|fim|> + + double getResult() { + return result; + } +}`, + llmOutput: `void subtract(double number) { + result -= number; + }`, + expectedCompletion: `void subtract(double number) { + result -= number; + }`, + }, + { + description: "Should handle string interpolation in Dart", + filename: "greetings.dart", + input: ` +void main() { + var name = "World"; + print('Hello, <|fim|>!'); +}`, + llmOutput: `\${name}`, + expectedCompletion: `\${name}`, + }, + { + description: "Should autocomplete within a Dart function body", + filename: "counter.dart", + input: ` +class Counter { + int count = 0; + + void increment() { + count++; + } + + void decrement() { + <|fim|> + + void reset() { + count = 0; + } +}`, + llmOutput: `count--;`, + expectedCompletion: `count--;`, + }, + { + description: + "Should autocomplete Clojure function definition with missing closing parenthesis", + input: `(defn calculate-sum [a b] + (let [sum (+ a b)] + (println "The sum is" sum) + sum<|fim|>`, + llmOutput: `))`, + expectedCompletion: `))`, + filename: "test.clj", + }, + { + description: + "Should autocomplete missing part of a Clojure map within a function", + input: `(defn get-user [] + {:username "johndoe" + :email "johndoe@example.com" + :age 30 + <|fim|> + (println "User information loaded"))`, + llmOutput: `:location "Unknown"}`, + expectedCompletion: `:location "Unknown"}`, + filename: "test.clj", + }, + { + description: + "Should autocomplete inside a Clojure vector within a looping construct", + input: `(defn odd-numbers [] + (loop [nums [1 3 5<|fim|> 9 11]] + (when (seq nums) + (println (first nums)) + (recur (rest nums)))))`, + llmOutput: ` 7,`, + expectedCompletion: ` 7,`, + filename: "test.clj", + }, + { + description: "Should autocomplete R function definition", + filename: "calculate.R", + input: ` +calculate_mean <- function(numbers) { + total <- sum(numbers) + <|fim|> +}`, + llmOutput: `mean_value <- total / length(numbers) + return(mean_value)`, + expectedCompletion: `mean_value <- total / length(numbers) + return(mean_value)`, + }, + { + description: "Should complete R loop and print statement", + filename: "loopPrint.R", + input: ` +numbers <- c(1, 2, 3, 4, 5) +for (number in numbers) { + print(<|fim|>) +}`, + llmOutput: `number)`, + expectedCompletion: `number)`, + }, + { + description: "Should autocomplete R data frame creation", + filename: "dataFrame.R", + input: ` +data <- data.frame( + Name = c("Alice", "Bob", "Charlie"), + Age = c(25, 30, 35), + <|fim|> +)`, + llmOutput: `Height = c(165, 180, 175)`, + expectedCompletion: `Height = c(165, 180, 175)`, + }, + { + description: "Should autocomplete R if-else statement", + filename: "condition.R", + input: ` +grade <- 85 +if (grade >= 90) { + print("A") +} else if (grade >= 80) { + <|fim|> +} else { + print("C") +}`, + llmOutput: `print("B")`, + expectedCompletion: `print("B")`, + }, + { + description: "Should autocomplete R ggplot2 plot structure", + filename: "plot.R", + input: ` +library(ggplot2) + +ggplot(data=mtcars, aes(x=wt, y=mpg)) + + geom_point() + + <|fim|>`, + llmOutput: `geom_smooth(method='lm', se=FALSE)`, + expectedCompletion: `geom_smooth(method='lm', se=FALSE)`, + }, + { + description: "Should autocomplete Scala class with a method", + filename: "Person.scala", + input: `class Person(val name: String, val age: Int) { + def greet(): String = { + <|fim|> + } + }`, + llmOutput: `s"Hello, my name is $name and I am $age years old."`, + expectedCompletion: `s"Hello, my name is $name and I am $age years old."`, + }, + + { + description: "Should handle Scala case class with a missing field", + filename: "Person.scala", + input: `case class Address(city: String, postalCode: String) + case class Person(name: String, age: Int, address: Address) + + val alice = Person("Alice", 30, Address("Wonderland", <|fim|>))`, + llmOutput: `"12345")`, + expectedCompletion: `"12345")`, + }, + + { + description: "Should autocomplete Scala function with missing body bracket", + filename: "Math.scala", + input: `object MathUtils { + def add(a: Int, b: Int): Int = { + a + b<|fim|> + + def multiply(a: Int, b: Int): Int = { + a * b + } + } + + object Main extends App { + println(MathUtils.add(3, 5)) + println(MathUtils.multiply(4, 6)) + }`, + llmOutput: ` + }`, + expectedCompletion: ` + }`, + }, + { + description: "Should autocomplete C function definition", + filename: "math_utils.c", + input: `#include + +int add(int a, int b) { + return a + b; +} + +int multiply(int a, int b) { + return a * b; +} + +int subtract(int a, int b) { + <|fim|> +} + +int main() { + printf("Result: %d", add(2, 3)); + return 0; +}`, + llmOutput: `return a - b;`, + expectedCompletion: `return a - b;`, + }, + + { + description: "Should handle C struct with missing field initialization", + filename: "person.c", + input: `#include + +typedef struct { + char name[50]; + int age; + float height; +} Person; + +int main() { + Person alice = {"Alice", 30, <|fim|>}; + printf("Name: %s, Age: %d, Height: %.2f", alice.name, alice.age, alice.height); + return 0; +}`, + llmOutput: `5.5`, + expectedCompletion: `5.5`, + }, + + { + description: "Should autocomplete C function with missing body bracket", + filename: "area.c", + input: `#include + +double calculateCircleArea(double radius) { + const double pi = 3.14159; + return pi * radius * radius;<|fim|> + +double calculateRectangleArea(double length, double width) { + return length * width; +} + +int main() { + printf("Circle Area: %.2f", calculateCircleArea(5.0)); + printf("Rectangle Area: %.2f", calculateRectangleArea(4.0, 6.0)); + return 0; +}`, + llmOutput: ` +}`, + expectedCompletion: ` +}`, + }, + { + description: "Should autocomplete a simple Kotlin function declaration", + filename: "simpleFunction.kt", + input: ` +fun main() { + println("Hello, World!") +} + +fun calculateArea(length: Double, width: Double): Double <|fim|>`, + llmOutput: `{ + return length * width +}`, + expectedCompletion: `{ + return length * width +}`, + }, + { + description: "Should handle autocomplete inside a Kotlin data class", + filename: "dataClass.kt", + input: ` +data class User( + val id: Int, + val name: String, + val email: String, + <|fim|> +)`, + llmOutput: `val age: Int`, + expectedCompletion: `val age: Int`, + }, + { + description: + "Should complete Kotlin if-else structure with missing brackets", + filename: "controlStructure.kt", + input: ` +fun getMax(a: Int, b: Int): Int { + if (a > b<|fim|> + } else { + return b + } +}`, + llmOutput: `) { + return a`, + expectedCompletion: `) { + return a`, + }, + { + description: "Should autocomplete Solidity function definition", + filename: "SimpleStorage.sol", + input: ` +pragma solidity ^0.8.0; + +contract SimpleStorage { + uint private data; + + function set(uint x) public { + data = x; + } + + function get() public view returns (uint) { + <|fim|> + } +} + `, + llmOutput: `return data;`, + expectedCompletion: `return data;`, + }, + + { + description: "Should autocomplete Solidity event with parameters", + filename: "EventExample.sol", + input: ` +pragma solidity ^0.8.0; + +contract EventExample { + event DataStored(uint indexed id, string content); + + function storeData(uint id, string memory content) public { + emit DataStored(<|fim|>); + } +} + `, + llmOutput: `id, content`, + expectedCompletion: `id, content`, + }, + + { + description: "Should handle Solidity struct definition completion", + filename: "StructDefinition.sol", + input: ` +pragma solidity ^0.8.0; + +contract StructExample { + struct Person { + string name; + uint age; + address wallet; + } + + Person[] private people; + + function addPerson(string memory name, uint age, address wallet) public { + people.push(Person(name, age, wallet)); + } + + function getFirstPerson<|fim|> +} + `, + llmOutput: `() public view returns (string memory, uint, address) { + if (people.length > 0) { + Person storage person = people[0]; + return (person.name, person.age, person.wallet); + } + return ("", 0, address(0)); + }`, + expectedCompletion: `() public view returns (string memory, uint, address) { + if (people.length > 0) { + Person storage person = people[0]; + return (person.name, person.age, person.wallet); + } + return ("", 0, address(0)); + }`, + }, + { + description: "Should autocomplete TypeScript interface properties", + filename: "User.ts", + input: ` +interface User { + id: number; + name: string; + e<|fim|> +} +`, + llmOutput: `mail: string; + age: number; +}`, + expectedCompletion: `mail: string; + age: number; +}`, + }, + + { + description: + "Should autocomplete a TypeScript arrow function inside a variable assignment", + filename: "mathOperations.ts", + input: ` +const addNumbers = (a: number, b: number): number => { + return a + b; +}; + +const multiplyNumbers = (a: number, b: number): number => { + re<|fim|> +} + +console.log(multiplyNumbers(2, 3)); +`, + llmOutput: `turn a * b;`, + expectedCompletion: `turn a * b;`, + }, + + { + description: + "Should handle autocomplete inside a nested TypeScript class method", + filename: "Account.ts", + input: ` +class Account { + private balance: number = 0; + + deposit(amount: number) { + this.balance += amount; + return this.balance; + } + + withdraw(amount: number) { + if (amount > this.balance) { + throw new Error("Insufficient funds"); + } + this.balance -= amount; + return thi<|fim|> + } +} +`, + llmOutput: `s.balance;`, + expectedCompletion: `s.balance;`, + }, + + { + description: "Should autocomplete a TypeScript generic function", + filename: "GenericFunction.ts", + input: ` +function identity(arg: T): T { + return ar<|fim|> +} + +console.log(identity(5)); +`, + llmOutput: `g;`, + expectedCompletion: `g;`, + }, + + { + description: + "Should autocomplete a TypeScript promise within an asynchronous function", + filename: "asyncFunction.ts", + input: ` +async function fetchData(url: string): Promise { + const response = await fetch(url); + <|fim|> + return data; +} + +fetchData('https://api.example.com/data'); +`, + llmOutput: `const data = await response.json();`, + expectedCompletion: `const data = await response.json();`, + }, + + { + description: + "Should autocomplete a C# class with a constructor and property", + filename: "Person.cs", + input: `using System; + +public class Person +{ + public string Name { get; set; } + public int Age { get; set; } + + public Person(string name, int <|fim|> +}`, + llmOutput: `age) + { + Name = name; + Age = age; + }`, + expectedCompletion: `age) + { + Name = name; + Age = age; + }`, + }, + { + description: "Should autocomplete a C# interface method", + filename: "IGreetable.cs", + input: `public interface IGreetable +{ + void <|fim|> +}`, + llmOutput: `Greet();`, + expectedCompletion: `Greet();`, + }, + { + description: "Should autocomplete inside C# method with if condition", + filename: "Calculator.cs", + input: `using System; + +public class Calculator +{ + public int Add(int a, int b) + { + if(<|fim|>) + { + return a + b; + } + return 0; + } +}`, + llmOutput: `a > 0 && b > 0`, + expectedCompletion: `a > 0 && b > 0`, + }, + { + description: "Should complete a simple Julia function", + filename: "simpleFunction.jl", + input: `function calculate_area(length, width) + <|fim|> +end +`, + llmOutput: `return length * width`, + expectedCompletion: `return length * width`, + }, + { + description: "Should autocomplete Julia for loop", + filename: "loop.jl", + input: `numbers = [1, 2, 3, 4, 5] +squared_numbers = [] + +for num in numbers + <|fim|> +end + +println(squared_numbers) +`, + llmOutput: `push!(squared_numbers, num^2)`, + expectedCompletion: `push!(squared_numbers, num^2)`, + }, + { + description: "Should complete a Julia struct definition", + filename: "structDefinition.jl", + input: `struct Person + first_name::String + last_name::String + age::Int + address::Address +end + +struct Address + street::String + city::String + <|fim|> +end +`, + llmOutput: `state::String + zip_code::String`, + expectedCompletion: `state::String + zip_code::String`, + }, + { + description: "Should complete a Julia dictionary access", + filename: "dictionary.jl", + input: `grades = Dict("Alice" => 90, "Bob" => 85, "Eve" => 88) + +function get_grade(student_name) + return grades[<|fim|>] +end + +println(get_grade("Alice")) # Should print 90 +`, + llmOutput: `student_name`, + expectedCompletion: `student_name`, + }, + { + description: "Should complete a Julia module declaration", + filename: "moduleDeclaration.jl", + input: `module MathOperations + +export add, subtract + +function add(a, b) + return a + b +end + +function subtract(a, b) + return a - b +end + +<|fim|> +`, + llmOutput: `end`, + expectedCompletion: `end`, + }, + { + description: "Should complete F# let-binding with function definition", + filename: "mathModule.fs", + input: `module MathModule + +let calculateArea length width = + <|fim|>`, + llmOutput: `length * width`, + expectedCompletion: `length * width`, + }, + + { + description: "Should complete incomplete F# type definition", + filename: "personType.fs", + input: `type Person = { + FirstName: string + LastName: string + Age: int<|fim|> +} + +let john = { FirstName = "John"; LastName = "Doe"; Age = 30 }`, + llmOutput: ` + Address: string +}`, + expectedCompletion: ` + Address: string +}`, + }, + + { + description: "Should complete F# pattern matching expression", + filename: "patternMatching.fs", + input: `let describeNumber number = + match number with + | 0 -> "Zero" + | 1 -> "One" + | <|fim|>`, + llmOutput: `2 -> "Two" + | _ -> "Other"`, + expectedCompletion: `2 -> "Two" + | _ -> "Other"`, + }, + + { + description: "Should complete F# list comprehension expression", + filename: "listComprehension.fs", + input: `let squares = [ for x in 1..10 -> x * x ] +let evenSquares = [ for x in squares do if x % 2 = 0 then yield x ] +let oddSquares = [<|fim|>]`, + llmOutput: ` for x in squares do if x % 2 <> 0 then yield x ]`, + expectedCompletion: ` for x in squares do if x % 2 <> 0 then yield x ]`, + }, + + { + description: "Should complete an F# recursive function", + filename: "recursiveFunctions.fs", + input: `let rec factorial n = + if n <= 1 then 1 + else n <|fim|> factorial (n - 1)`, + llmOutput: ` * `, + expectedCompletion: ` * `, + }, + + { + description: "Should complete F# member method inside a class type", + filename: "bankAccount.fs", + input: `type BankAccount(owner: string, initialBalance: float) = + let mutable balance = initialBalance + + member this.Deposit amount = + balance <- balance + amount + this + <|fim|>`, + llmOutput: ` + member this.Withdraw amount = + if amount > balance then + failwith "Insufficient funds" + balance <- balance - amount + this`, + expectedCompletion: ` + member this.Withdraw amount = + if amount > balance then + failwith "Insufficient funds" + balance <- balance - amount + this`, + }, + + { + description: "Should complete F# async workflow function", + filename: "asyncWorkflow.fs", + input: `let fetchDataAsync url = + async { + use client = new System.Net.Http.HttpClient() + <|fim|> + }`, + llmOutput: `let! response = client.GetStringAsync(url) + return response`, + expectedCompletion: `let! response = client.GetStringAsync(url) + return response`, + }, + { + description: "Should autocomplete SCSS nested class starting inside a rule", + filename: "styles.scss", + input: `nav { + display: flex; + justify-content: space-between; + .logo { + font-size: 1.5rem; + color: #333; + + .brand<|fim|> + } + + ul { + list-style: none; + display: flex; + gap: 1rem; + } +}`, + llmOutput: `-name { + font-weight: bold; + text-transform: uppercase; +}`, + expectedCompletion: `-name { + font-weight: bold; + text-transform: uppercase; +}`, + }, + + { + description: "Should handle SCSS mixin within a class", + filename: "styles.scss", + input: `.card { + border: 1px solid #ccc; + padding: 10px; + + @include<|fim|> + + &:hover { + box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); + } +}`, + llmOutput: ` transition(all 0.3s ease);`, + expectedCompletion: ` transition(all 0.3s ease);`, + }, + + { + description: + "Should autocomplete SCSS variable in the middle of a statement", + filename: "styles.scss", + input: `$primary-color: #007bff; +$secondary-color: #6c757d; + +.button { + background-color: <|fim|> color; + padding: 10px 15px; + border: none; + color: #fff; + border-radius: 4px; +}`, + llmOutput: `$primary-`, + expectedCompletion: `$primary-`, + }, + { + description: "Should autocomplete Vue component method", + filename: "MyComponent.vue", + input: ` + + +`, + llmOutput: `() { + this.count = 0; + }`, + expectedCompletion: `() { + this.count = 0; + }`, + }, + { + description: "Should autocomplete Vue computed property", + filename: "UserComponent.vue", + input: ` + + +`, + llmOutput: `() { + return this.firstName + ' ' + this.lastName; + }`, + expectedCompletion: `() { + return this.firstName + ' ' + this.lastName; + }`, + }, + { + description: "Should autocomplete Vue method using props", + filename: "TodoItem.vue", + input: ` + + +`, + llmOutput: `this.completed`, + expectedCompletion: `this.completed`, + }, + { + description: "Should autocomplete Svelte reactive statement", + filename: "Counter.svelte", + input: ` + + + +`, + llmOutput: `doubledCount = count * 2`, + expectedCompletion: `doubledCount = count * 2`, +}, + +{ + description: "Should autocomplete Svelte component inside HTML", + filename: "NestedComponent.svelte", + input: ` + + +
+

Hello Svelte

+ /> +
+`, + llmOutput: `name="World"`, + expectedCompletion: `name="World"`, +}, + +{ + description: "Should handle autocomplete in Svelte each block", + filename: "List.svelte", + input: ` + + +
    + {#each items as item} +
  • {item}
  • + {/each<|fim|> +
+`, + llmOutput: `}`, + expectedCompletion: `}`, +}, + ]; diff --git a/core/util/parameters.ts b/core/util/parameters.ts index 88c7d38a6..c12244452 100644 --- a/core/util/parameters.ts +++ b/core/util/parameters.ts @@ -13,7 +13,7 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { slidingWindowSize: 500, maxSnippetPercentage: 0.6, recentlyEditedSimilarityThreshold: 0.3, - useCache: true, + useCache: false, onlyMyCode: true, useOtherFiles: true, useRecentlyEdited: true, diff --git a/manual-testing-sandbox/Dockerfile b/manual-testing-sandbox/Dockerfile new file mode 100644 index 000000000..0a3883323 --- /dev/null +++ b/manual-testing-sandbox/Dockerfile @@ -0,0 +1,18 @@ +# Use a base image +FROM python:3.9-slim + +# Set working directory +WORKDIR /app + +# Copy requirements file and install dependencies +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +# Copy the rest of the application code +COPY . . + +# Set environment variables +ENV PORT=8080 + +# Start the application +CMD ["python", "app.py"] diff --git a/manual-testing-sandbox/config.yaml b/manual-testing-sandbox/config.yaml new file mode 100644 index 000000000..83bb21c52 --- /dev/null +++ b/manual-testing-sandbox/config.yaml @@ -0,0 +1,14 @@ +AWSTemplateFormatVersion: "2010-09-09" +Description: Sample CloudFormation template + +Resources: + S3Bucket: + Type: "AWS::S3::Bucket" + Properties: + BucketName: my-sample-bucket + + EC2Instance: + Type: "AWS::EC2::Instance" + Properties: + InstanceType: "t2.micro" + ImageId: "ami-0abcdef12345abcdef" diff --git a/manual-testing-sandbox/data.json b/manual-testing-sandbox/data.json new file mode 100644 index 000000000..7a187514a --- /dev/null +++ b/manual-testing-sandbox/data.json @@ -0,0 +1,8 @@ +{ + "employees": [ + { "name": "John Doe", "age": 30, "position": "Developer" }, + { "name": "Jane Smith", "age": 25, "position": "Designer" }, + { "name": "Emily Johnson", "age": 35, "position": "Manager" } + ], + "active": true +} diff --git a/manual-testing-sandbox/program.cs b/manual-testing-sandbox/program.cs new file mode 100644 index 000000000..4def78911 --- /dev/null +++ b/manual-testing-sandbox/program.cs @@ -0,0 +1,34 @@ +using System; + +public class Program +{ + public static void Main(string[] args) + { + Console.WriteLine("Hello World!"); + Calculator calc = new Calculator(); + calc.Add(5).Subtract(3); + Console.WriteLine("Result: " + calc.GetResult()); + } + + public class Calculator + { + private double result; + + public Calculator Add(double number) + { + result += number; + return this; + } + + public Calculator Subtract(double number) + { + result -= number; + return this; + } + + public double GetResult() + { + return result; + } + } +} \ No newline at end of file diff --git a/manual-testing-sandbox/query.sql b/manual-testing-sandbox/query.sql new file mode 100644 index 000000000..6fcd66e3c --- /dev/null +++ b/manual-testing-sandbox/query.sql @@ -0,0 +1,9 @@ +CREATE TABLE employees ( + id INT AUTO_INCREMENT PRIMARY KEY, + name VARCHAR(100) NOT NULL, + age INT NOT NULL, + position VARCHAR(100) +); + +INSERT INTO employees (name, age, position) VALUES ('John Doe', 30, 'Developer'); +SELECT * FROM employees WHERE age > 25; diff --git a/manual-testing-sandbox/readme.md b/manual-testing-sandbox/readme.md index 5b25d31ee..461ce38b7 100644 --- a/manual-testing-sandbox/readme.md +++ b/manual-testing-sandbox/readme.md @@ -1,3 +1,3 @@ -The sole purpose of this folder is to open it when debugging the extension. +The sole purpose of this folder is to open it when debugging the extension. It is not used by the extension itself. -You can add more files that can be useful when manually testing the extension. \ No newline at end of file +You can add more files that can be useful when manually testing the extension. diff --git a/manual-testing-sandbox/test.css b/manual-testing-sandbox/test.css index d383e372f..c6d3ac8e3 100644 --- a/manual-testing-sandbox/test.css +++ b/manual-testing-sandbox/test.css @@ -33,4 +33,4 @@ a { .button:hover { background-color: #0056b3; -} \ No newline at end of file +} diff --git a/manual-testing-sandbox/test.html b/manual-testing-sandbox/test.html new file mode 100644 index 000000000..6c19f414b --- /dev/null +++ b/manual-testing-sandbox/test.html @@ -0,0 +1,25 @@ + + + + + + + Sample Page + + + + +
+

Welcome to the Sample Page

+ +
+
+

This is a sample paragraph.

+
+ + + \ No newline at end of file diff --git a/manual-testing-sandbox/test.java b/manual-testing-sandbox/test.java new file mode 100644 index 000000000..0f22df25a --- /dev/null +++ b/manual-testing-sandbox/test.java @@ -0,0 +1,28 @@ +public class Calculator { + private double result; + + public Calculator add(double number) { + result += number; + return this; + } + + public Calculator subtract(double number) { + result -= number; + return this; + } + + public double getResult() { + return result; + } + + public Calculator reset() { + result = 0; + return this; + } + + public static void main(String[] args) { + Calculator calc = new Calculator(); + calc.add(10).subtract(5); + System.out.println("Result: " + calc.getResult()); + } +} diff --git a/manual-testing-sandbox/test.php b/manual-testing-sandbox/test.php new file mode 100644 index 000000000..7bc4bd63c --- /dev/null +++ b/manual-testing-sandbox/test.php @@ -0,0 +1,44 @@ +result += $number; + return $this; + } + + public function subtract($number) { + $this->result -= $number; + return $this; + } + + public function multiply($number) { + $this->result *= $number; + return $this; + } + + public function divide($number) { + if ($number != 0) { + $this->result /= $number; + } else { + echo "Division by zero error."; + } + return $this; + } + + public function getResult() { + return $this->result; + } + + public function reset() { + $this->result = 0.0; + return $this; + } +} + +$calc = new Calculator(); +$calc->add(10)->subtract(5); +echo "Result: " . $calc->getResult() . "\n"; + +?> diff --git a/manual-testing-sandbox/test.py b/manual-testing-sandbox/test.py new file mode 100644 index 000000000..4478e7b3d --- /dev/null +++ b/manual-testing-sandbox/test.py @@ -0,0 +1,18 @@ +class Calculator: + def __init__(self): + self.result = 0 + + def add(self, number): + self.result += number + return self + + def subtract(self, number): + self.result -= number + return self + + def reset(self): + self.result = 0 + return self + + def get_result(self): + return self.result diff --git a/manual-testing-sandbox/test.rb b/manual-testing-sandbox/test.rb new file mode 100644 index 000000000..8ec83d1ba --- /dev/null +++ b/manual-testing-sandbox/test.rb @@ -0,0 +1,30 @@ +class Calculator + attr_accessor :result + + def initialize + @result = 0 + end + + def add(number) + @result += number + self + end + + def subtract(number) + @result -= number + self + end + + def get_result + @result + end + + def reset + @result = 0 + self + end +end + +calc = Calculator.new +calc.add(5).subtract(3) +puts "Result: #{calc.get_result}" diff --git a/manual-testing-sandbox/test.sh b/manual-testing-sandbox/test.sh new file mode 100644 index 000000000..fb2ec6dc4 --- /dev/null +++ b/manual-testing-sandbox/test.sh @@ -0,0 +1,21 @@ +#!/bin/bash + +function calculate { + local a=$1 + local b=$2 + local op=$3 + local result + + case $op in + "+") result=$((a + b)) ;; + "-") result=$((a - b)) ;; + "*") result=$((a * b)) ;; + "/") result=$((a / b)) ;; + *) echo "Invalid operator"; exit 1 ;; + esac + + echo "Result: $result" +} + +calculate 10 5 "+" +calculate 10 3 "-" From 91ea00d284227f3875daf17591b15409004372ac Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 24 Oct 2024 17:40:42 +0700 Subject: [PATCH 10/34] fix: restore cache --- core/util/parameters.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/util/parameters.ts b/core/util/parameters.ts index c12244452..88c7d38a6 100644 --- a/core/util/parameters.ts +++ b/core/util/parameters.ts @@ -13,7 +13,7 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { slidingWindowSize: 500, maxSnippetPercentage: 0.6, recentlyEditedSimilarityThreshold: 0.3, - useCache: false, + useCache: true, onlyMyCode: true, useOtherFiles: true, useRecentlyEdited: true, From 4cb84c11b09dac6eb0791e35b95ff6f571130391 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 24 Oct 2024 18:01:29 +0700 Subject: [PATCH 11/34] fix: pause between tests to avoid db lock --- core/autocomplete/test/filter.test.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/core/autocomplete/test/filter.test.ts b/core/autocomplete/test/filter.test.ts index 98cef6be6..502c0aaa3 100644 --- a/core/autocomplete/test/filter.test.ts +++ b/core/autocomplete/test/filter.test.ts @@ -3,6 +3,10 @@ import { testCases } from "./testCases"; describe("llms/Mock", () => { describe("Autocomplete Filtering Tests", () => { + beforeEach(async () => { + await new Promise((resolve) => setTimeout(resolve, 50)); + }); + it.each(testCases)("$description", async (testCase) => { await testAutocompleteFiltering(testCase); }); From d12395838bd5e529015dd45484ff5384e99cde5e Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Fri, 25 Oct 2024 10:57:55 +0700 Subject: [PATCH 12/34] improv: fix failing tests, add 'transform' autocomplete option --- core/autocomplete/completionProvider.ts | 113 ++++++++++-------- core/autocomplete/test/filter.test.ts | 24 +++- core/autocomplete/test/testCases.ts | 51 ++++---- core/autocomplete/test/util.ts | 3 + core/diff/util.ts | 5 + core/index.d.ts | 2 +- core/util/parameters.ts | 1 + docs/static/schemas/config.json | 10 +- .../src/main/resources/config_schema.json | 10 +- extensions/vscode/config_schema.json | 10 +- extensions/vscode/continue_rc_schema.json | 4 + packages/config-types/src/index.ts | 1 + 12 files changed, 138 insertions(+), 96 deletions(-) diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index 893f9bc36..30d706c56 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -95,6 +95,7 @@ const autocompleteCache = AutocompleteLruCache.get(); const DOUBLE_NEWLINE = "\n\n"; const WINDOWS_DOUBLE_NEWLINE = "\r\n\r\n"; +// TODO: Do we want to stop completions when reaching a `/src/` string? const SRC_DIRECTORY = "/src/"; // Starcoder2 tends to output artifacts starting with the letter "t" const STARCODER2_T_ARTIFACTS = ["t.", "\nt", ""]; @@ -360,7 +361,7 @@ export class CompletionProvider { * elsewhere in the code. That said, I'm not yet confident enough to * remove this. */ - if (isOnlyWhitespace(outcome.completion)) { + if (options.transform && isOnlyWhitespace(outcome.completion)) { return undefined; } @@ -480,10 +481,13 @@ export class CompletionProvider { // Filter const lang = languageForFilepath(filepath); - const line = fileLines[pos.line] ?? ""; - for (const endOfLine of lang.endOfLine) { - if (line.endsWith(endOfLine) && pos.character >= line.length) { - return undefined; + + if (options.transform) { + const line = fileLines[pos.line] ?? ""; + for (const endOfLine of lang.endOfLine) { + if (line.endsWith(endOfLine) && pos.character >= line.length) { + return undefined; + } } } @@ -667,23 +671,25 @@ export class CompletionProvider { } else { const stop = [ ...(completionOptions?.stop || []), - ...multilineStops, + // ...multilineStops, ...commonStops, ...(llm.model.toLowerCase().includes("starcoder2") ? STARCODER2_T_ARTIFACTS : []), ...(lang.stopWords ?? []), - ...lang.topLevelKeywords.map((word) => `\n${word}`), + // ...lang.topLevelKeywords.map((word) => `\n${word}`), ]; - const multiline = this.isMultiline({ - multilineCompletions: options.multilineCompletions, - language: lang, - selectedCompletionInfo: input.selectedCompletionInfo, - prefix, - suffix, - completeMultiline, - }); + const multiline = + !options.transform || + this.isMultiline({ + multilineCompletions: options.multilineCompletions, + language: lang, + selectedCompletionInfo: input.selectedCompletionInfo, + prefix, + suffix, + completeMultiline, + }); // Try to reuse pending requests if what the user typed matches start of completion const generator = this.generatorReuseManager.getGenerator( @@ -718,39 +724,44 @@ export class CompletionProvider { } }; let charGenerator = generatorWithCancellation(); - charGenerator = noFirstCharNewline(charGenerator); - charGenerator = onlyWhitespaceAfterEndOfLine( - charGenerator, - lang.endOfLine, - fullStop, - ); - charGenerator = stopAtStopTokens(charGenerator, stop); - let lineGenerator = streamLines(charGenerator); - lineGenerator = stopAtLines(lineGenerator, fullStop); - lineGenerator = stopAtRepeatingLines(lineGenerator, fullStop); - lineGenerator = avoidPathLineAndEmptyComments( - lineGenerator, - lang.singleLineComment, - ); - lineGenerator = skipPrefixes(lineGenerator); - lineGenerator = noTopLevelKeywordsMidline( - lineGenerator, - lang.topLevelKeywords, - fullStop, - ); - - for (const lineFilter of lang.lineFilters ?? []) { - lineGenerator = lineFilter({ lines: lineGenerator, fullStop }); + if (options.transform) { + // charGenerator = noFirstCharNewline(charGenerator); + // charGenerator = onlyWhitespaceAfterEndOfLine( + // charGenerator, + // lang.endOfLine, + // fullStop, + // ); + charGenerator = stopAtStopTokens(charGenerator, stop); } - lineGenerator = streamWithNewLines(lineGenerator); + let lineGenerator = streamLines(charGenerator); + if (options.transform) { + lineGenerator = stopAtLines(lineGenerator, fullStop); + lineGenerator = stopAtRepeatingLines(lineGenerator, fullStop); + lineGenerator = avoidPathLineAndEmptyComments( + lineGenerator, + lang.singleLineComment, + ); + lineGenerator = skipPrefixes(lineGenerator); - const finalGenerator = stopAtSimilarLine( - lineGenerator, - lineBelowCursor, - fullStop, - ); + // lineGenerator = noTopLevelKeywordsMidline( + // lineGenerator, + // lang.topLevelKeywords, + // fullStop, + // ); + for (const lineFilter of lang.lineFilters ?? []) { + lineGenerator = lineFilter({ lines: lineGenerator, fullStop }); + } + + lineGenerator = stopAtSimilarLine( + lineGenerator, + lineBelowCursor, + fullStop, + ); + } + + const finalGenerator = streamWithNewLines(lineGenerator); try { for await (const update of finalGenerator) { @@ -767,12 +778,14 @@ export class CompletionProvider { return undefined; } - const processedCompletion = postprocessCompletion({ - completion, - prefix, - suffix, - llm, - }); + const processedCompletion = options.transform + ? postprocessCompletion({ + completion, + prefix, + suffix, + llm, + }) + : completion; if (!processedCompletion) { return undefined; diff --git a/core/autocomplete/test/filter.test.ts b/core/autocomplete/test/filter.test.ts index 502c0aaa3..171b1cb44 100644 --- a/core/autocomplete/test/filter.test.ts +++ b/core/autocomplete/test/filter.test.ts @@ -1,5 +1,16 @@ -import { testAutocompleteFiltering } from "./util"; -import { testCases } from "./testCases"; +import { + AutocompleteFileringTestInput, + testAutocompleteFiltering, +} from "./util"; +import { TEST_CASES } from "./testCases"; + +const filterTestCases = (tests: AutocompleteFileringTestInput[]) => { + if (tests.some((test) => test.options?.only)) { + return tests.filter((test) => test.options?.only); + } + + return tests; +}; describe("llms/Mock", () => { describe("Autocomplete Filtering Tests", () => { @@ -7,8 +18,13 @@ describe("llms/Mock", () => { await new Promise((resolve) => setTimeout(resolve, 50)); }); - it.each(testCases)("$description", async (testCase) => { - await testAutocompleteFiltering(testCase); + describe("Should return unmodified LLM output", () => { + it.each(filterTestCases(TEST_CASES))("$description", async (testCase) => { + await testAutocompleteFiltering(testCase); + }); }); + + // TODO: Add test cases where modifying LLM output is desirable + describe.skip("Should return modified LLM output", () => {}); }); }); diff --git a/core/autocomplete/test/testCases.ts b/core/autocomplete/test/testCases.ts index d171c9f5d..2deeec9de 100644 --- a/core/autocomplete/test/testCases.ts +++ b/core/autocomplete/test/testCases.ts @@ -1,7 +1,7 @@ import { dedent } from "../../util"; import { AutocompleteFileringTestInput } from "./util"; -export const testCases: AutocompleteFileringTestInput[] = [ +export const TEST_CASES: AutocompleteFileringTestInput[] = [ { description: "should pass", filename: "test.js", @@ -188,7 +188,6 @@ input:focus { llmOutput: `--primary-color`, expectedCompletion: `--primary-color`, }, - { description: "Should complete CSS grid template columns", filename: "grid.css", @@ -199,8 +198,8 @@ input:focus { grid-gap: 10px; } `, - llmOutput: `3, 1fr);`, - expectedCompletion: `3, 1fr);`, + llmOutput: `3, 1fr`, + expectedCompletion: `3, 1fr`, }, { @@ -1007,7 +1006,8 @@ fn get_status_code_description(code: u16) -> &'static str { `, expectedCompletion: `403 => "Forbidden", 401 => "Unauthorized", - _ => "Unknown Status",`, + _ => "Unknown Status", +`, }, { description: "Should autocomplete Rust struct definition", @@ -1955,9 +1955,9 @@ export default { expectedCompletion: `this.completed`, }, { - description: "Should autocomplete Svelte reactive statement", - filename: "Counter.svelte", - input: ` + description: "Should autocomplete Svelte reactive statement", + filename: "Counter.svelte", + input: ` @@ -1989,14 +1989,14 @@ export default { /> `, - llmOutput: `name="World"`, - expectedCompletion: `name="World"`, -}, + llmOutput: `name="World"`, + expectedCompletion: `name="World"`, + }, -{ - description: "Should handle autocomplete in Svelte each block", - filename: "List.svelte", - input: ` + { + description: "Should handle autocomplete in Svelte each block", + filename: "List.svelte", + input: ` @@ -2007,8 +2007,7 @@ export default { {/each<|fim|> `, - llmOutput: `}`, - expectedCompletion: `}`, -}, - + llmOutput: `}`, + expectedCompletion: `}`, + }, ]; diff --git a/core/autocomplete/test/util.ts b/core/autocomplete/test/util.ts index 8a65031a1..60e7b3f93 100644 --- a/core/autocomplete/test/util.ts +++ b/core/autocomplete/test/util.ts @@ -17,6 +17,9 @@ export interface AutocompleteFileringTestInput { input: string; llmOutput: string; expectedCompletion: string | null; + options?: { + only?: boolean; + }; } export async function testAutocompleteFiltering( diff --git a/core/diff/util.ts b/core/diff/util.ts index 6d218bcbf..1758bb704 100644 --- a/core/diff/util.ts +++ b/core/diff/util.ts @@ -110,6 +110,11 @@ export async function* streamLines( yield line; allLines.push(line); } + + if (buffer === "" && chunk.endsWith("\n")) { + yield ""; + allLines.push(""); + } } if (buffer.length > 0) { yield buffer; diff --git a/core/index.d.ts b/core/index.d.ts index e7c22db2f..7bbbaf8e0 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -650,7 +650,6 @@ type ModelProvider = | "mock" | "cerebras"; - export type ModelName = | "AUTODETECT" // OpenAI @@ -878,6 +877,7 @@ export interface TabAutocompleteOptions { debounceDelay: number; maxSuffixPercentage: number; prefixPercentage: number; + transform?: boolean; template?: string; multilineCompletions: "always" | "never" | "auto"; slidingWindowPrefixPercentage: number; diff --git a/core/util/parameters.ts b/core/util/parameters.ts index 88c7d38a6..4a99dec8c 100644 --- a/core/util/parameters.ts +++ b/core/util/parameters.ts @@ -21,6 +21,7 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { disableInFiles: undefined, useImports: true, useRootPathContext: true, + transform: true, }; export const COUNT_COMPLETION_REJECTED_AFTER = 10_000; diff --git a/docs/static/schemas/config.json b/docs/static/schemas/config.json index ce4e8e1a4..077bdcf93 100644 --- a/docs/static/schemas/config.json +++ b/docs/static/schemas/config.json @@ -1162,11 +1162,7 @@ "model": { "anyOf": [ { - "enum": [ - "codestral", - "mistral-nemo", - "mistral-large" - ] + "enum": ["codestral", "mistral-nemo", "mistral-large"] }, { "type": "string" } ] @@ -2712,6 +2708,10 @@ "type": "number", "description": "The percentage of the input that should be dedicated to the prefix." }, + "transform": { + "type": "boolean", + "description": "Whether LLM output should be transformed to correct common model pitfalls." + }, "template": { "type": "string", "description": "An optional template string to be used for autocomplete. It will be rendered with the Mustache templating language, and is passed the 'prefix' and 'suffix' variables." diff --git a/extensions/intellij/src/main/resources/config_schema.json b/extensions/intellij/src/main/resources/config_schema.json index ce4e8e1a4..077bdcf93 100644 --- a/extensions/intellij/src/main/resources/config_schema.json +++ b/extensions/intellij/src/main/resources/config_schema.json @@ -1162,11 +1162,7 @@ "model": { "anyOf": [ { - "enum": [ - "codestral", - "mistral-nemo", - "mistral-large" - ] + "enum": ["codestral", "mistral-nemo", "mistral-large"] }, { "type": "string" } ] @@ -2712,6 +2708,10 @@ "type": "number", "description": "The percentage of the input that should be dedicated to the prefix." }, + "transform": { + "type": "boolean", + "description": "Whether LLM output should be transformed to correct common model pitfalls." + }, "template": { "type": "string", "description": "An optional template string to be used for autocomplete. It will be rendered with the Mustache templating language, and is passed the 'prefix' and 'suffix' variables." diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index ce4e8e1a4..077bdcf93 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -1162,11 +1162,7 @@ "model": { "anyOf": [ { - "enum": [ - "codestral", - "mistral-nemo", - "mistral-large" - ] + "enum": ["codestral", "mistral-nemo", "mistral-large"] }, { "type": "string" } ] @@ -2712,6 +2708,10 @@ "type": "number", "description": "The percentage of the input that should be dedicated to the prefix." }, + "transform": { + "type": "boolean", + "description": "Whether LLM output should be transformed to correct common model pitfalls." + }, "template": { "type": "string", "description": "An optional template string to be used for autocomplete. It will be rendered with the Mustache templating language, and is passed the 'prefix' and 'suffix' variables." diff --git a/extensions/vscode/continue_rc_schema.json b/extensions/vscode/continue_rc_schema.json index b2b7dbb78..4ee643f5c 100644 --- a/extensions/vscode/continue_rc_schema.json +++ b/extensions/vscode/continue_rc_schema.json @@ -3057,6 +3057,10 @@ "type": "number", "description": "The percentage of the input that should be dedicated to the prefix." }, + "transform": { + "type": "boolean", + "description": "Whether LLM output should be transformed to correct common model pitfalls." + }, "template": { "type": "string", "description": "An optional template string to be used for autocomplete. It will be rendered with the Mustache templating language, and is passed the 'prefix' and 'suffix' variables." diff --git a/packages/config-types/src/index.ts b/packages/config-types/src/index.ts index 26130c4ba..ee5699996 100644 --- a/packages/config-types/src/index.ts +++ b/packages/config-types/src/index.ts @@ -133,6 +133,7 @@ export const tabAutocompleteOptionsSchema = z.object({ debounceDelay: z.number(), maxSuffixPercentage: z.number(), prefixPercentage: z.number(), + transform: z.boolean().optional(), template: z.string().optional(), multilineCompletions: z.enum(["always", "never", "auto"]), slidingWindowPrefixPercentage: z.number(), From 15bd3dd22b9c89b5c34deb98bfe8310c9f1c124c Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Fri, 25 Oct 2024 17:16:47 +0700 Subject: [PATCH 13/34] Create NEGATIVE_CASES_STARCODER.tsx --- .../test/NEGATIVE_CASES_STARCODER.tsx | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 core/autocomplete/test/NEGATIVE_CASES_STARCODER.tsx diff --git a/core/autocomplete/test/NEGATIVE_CASES_STARCODER.tsx b/core/autocomplete/test/NEGATIVE_CASES_STARCODER.tsx new file mode 100644 index 000000000..269d25f0f --- /dev/null +++ b/core/autocomplete/test/NEGATIVE_CASES_STARCODER.tsx @@ -0,0 +1,51 @@ +##### Prompt ##### +class Calculator { + constructor() { + this.result = 0; + } + + add(number) { + this.result += number; + return this; + } + + subtract(number) { + this.result -= number; + return this; + } + + multiply(number) { + this.result *= number; + return this; + } + + divide(number) { + if (number === 0) { + throw new Error("Cannot divide by zero"); + } + + + + this.result /= number; + return this; + } + + getResult() { + return this.result; + } + + reset() { + this.result = 0; + return this; + } +} +========================================================================== +========================================================================== +Completion: + + this.result /= number; + return this; + } +} + +module.exports = Calculator; \ No newline at end of file From 9662b18a1ff36d8eaf743003f4df501245a31be2 Mon Sep 17 00:00:00 2001 From: Replexica Date: Fri, 25 Oct 2024 22:40:47 +0530 Subject: [PATCH 14/34] fix: add hover effect and restrict clickable area for the history and more back buttons --- gui/src/pages/More/More.tsx | 9 +++++---- gui/src/pages/history/HistoryHeader.tsx | 15 ++++++++------- 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/gui/src/pages/More/More.tsx b/gui/src/pages/More/More.tsx index 1deb62667..4e6f3cd0f 100644 --- a/gui/src/pages/More/More.tsx +++ b/gui/src/pages/More/More.tsx @@ -26,14 +26,15 @@ function MorePage() { return (
navigate("/")} - className="sticky top-0 m-0 flex cursor-pointer items-center border-0 border-b border-solid border-b-zinc-700 bg-inherit p-0" + className="sticky top-0 m-0 flex items-center border-0 border-b border-solid border-b-zinc-700 bg-inherit p-0" style={{ backgroundColor: vscBackground, }} > - - Chat +
navigate("/")}> + + Chat +
diff --git a/gui/src/pages/history/HistoryHeader.tsx b/gui/src/pages/history/HistoryHeader.tsx index 2682af7c5..e93a68520 100644 --- a/gui/src/pages/history/HistoryHeader.tsx +++ b/gui/src/pages/history/HistoryHeader.tsx @@ -19,13 +19,14 @@ export const HistoryHeader = () => { borderBottom: `0.5px solid ${lightGray}`, }} > - navigate("/")} - className="ml-4 inline-block cursor-pointer" - /> - Chat +
navigate("/")}> + + Chat +
{/* {workspacePaths && workspacePaths.length > 0 && ( Date: Sat, 26 Oct 2024 21:57:19 -0400 Subject: [PATCH 15/34] Apply suggestions from code review Co-authored-by: Patrick Erichsen --- gui/src/pages/AddNewModel/configs/providers.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/gui/src/pages/AddNewModel/configs/providers.ts b/gui/src/pages/AddNewModel/configs/providers.ts index dfaac3ffd..d23989efb 100644 --- a/gui/src/pages/AddNewModel/configs/providers.ts +++ b/gui/src/pages/AddNewModel/configs/providers.ts @@ -629,9 +629,9 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo vertexai: { title: "VertexAI", provider: "vertexai", - description: "Use supported vertex AI models", + description: "Use supported Vertex AI models", longDescription: - "Use the supported vertex AI models - see [here](https://cloud.google.com/docs/authentication/provide-credentials-adc) to authenticate", + "Use the supported Vertex AI models - see [here](https://cloud.google.com/docs/authentication/provide-credentials-adc) to authenticate", icon: "vertexai.png", packages: [ models.VertexGemini15Pro, @@ -643,7 +643,7 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo inputType: "project", key: "projectId", label: "Project Id", - placeholder: "Enter your Vertex AI project id", + placeholder: "Enter your Vertex AI project Id", required: true, }, { From 4004e2e301fffc9ef3bcb79e8871bcc66d424d75 Mon Sep 17 00:00:00 2001 From: Luke Date: Sat, 26 Oct 2024 23:21:30 -0400 Subject: [PATCH 16/34] Use some base class functions --- core/llm/llms/Anthropic.ts | 8 +- core/llm/llms/Gemini.ts | 10 +- core/llm/llms/VertexAI.ts | 138 +++--------------- .../model-providers/top-level/vertexai.md | 43 +----- gui/src/pages/AddNewModel/configs/models.ts | 14 ++ .../pages/AddNewModel/configs/providers.ts | 1 + 6 files changed, 47 insertions(+), 167 deletions(-) diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index f2182d851..2ad990e98 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -20,7 +20,7 @@ class Anthropic extends BaseLLM { apiBase: "https://api.anthropic.com/v1/", }; - private _convertArgs(options: CompletionOptions) { + public convertArgs(options: CompletionOptions) { // should be public for use within VertexAI const finalOptions = { top_k: options.topK, top_p: options.topP, @@ -34,7 +34,7 @@ class Anthropic extends BaseLLM { return finalOptions; } - private _convertMessages(msgs: ChatMessage[]): any[] { + public convertMessages(msgs: ChatMessage[]): any[] { // should be public for use within VertexAI const filteredmessages = msgs.filter((m) => m.role !== "system") const lastTwoUserMsgIndices = filteredmessages .map((msg, index) => (msg.role === "user" ? index : -1)) @@ -115,8 +115,8 @@ class Anthropic extends BaseLLM { : {}), }, body: JSON.stringify({ - ...this._convertArgs(options), - messages: this._convertMessages(messages), + ...this.convertArgs(options), + messages: this.convertMessages(messages), system: shouldCacheSystemMessage ? [ { diff --git a/core/llm/llms/Gemini.ts b/core/llm/llms/Gemini.ts index 4bfed0420..355ae1326 100644 --- a/core/llm/llms/Gemini.ts +++ b/core/llm/llms/Gemini.ts @@ -18,7 +18,7 @@ class Gemini extends BaseLLM { }; // Function to convert completion options to Gemini format - private _convertArgs(options: CompletionOptions) { + public convertArgs(options: CompletionOptions) { // should be public for use within VertexAI const finalOptions: any = {}; // Initialize an empty object // Map known options @@ -53,7 +53,7 @@ class Gemini extends BaseLLM { } } - private removeSystemMessage(messages: ChatMessage[]) { + public removeSystemMessage(messages: ChatMessage[]) { // should be public for use within VertexAI const msgs = [...messages]; if (msgs[0]?.role === "system") { @@ -100,7 +100,7 @@ class Gemini extends BaseLLM { } } - private _continuePartToGeminiPart(part: MessagePart) { + continuePartToGeminiPart(part: MessagePart) { return part.type === "text" ? { text: part.text, @@ -139,13 +139,13 @@ class Gemini extends BaseLLM { parts: typeof msg.content === "string" ? [{ text: msg.content }] - : msg.content.map(this._continuePartToGeminiPart), + : msg.content.map(this.continuePartToGeminiPart), }; }) .filter((c) => c !== null); const body = { - ...this._convertArgs(options), + ...this.convertArgs(options), contents, // if this.systemMessage is defined, reformat it for Gemini API ...(this.systemMessage && diff --git a/core/llm/llms/VertexAI.ts b/core/llm/llms/VertexAI.ts index 6c94a9a77..e3435b6ae 100644 --- a/core/llm/llms/VertexAI.ts +++ b/core/llm/llms/VertexAI.ts @@ -10,11 +10,15 @@ import { ModelProvider, } from "../../index.js"; import { streamResponse } from "../stream.js"; +import Anthropic from "./Anthropic.js"; +import Gemini from "./Gemini.js"; class VertexAI extends BaseLLM { static providerName: ModelProvider = "vertexai"; declare apiBase: string; declare vertexProvider: string; + declare anthropicInstance: Anthropic; + declare geminiInstance: Gemini; private clientPromise = new GoogleAuth({ scopes: "https://www.googleapis.com/auth/cloud-platform", @@ -35,12 +39,15 @@ class VertexAI extends BaseLLM { this.apiBase ??= VertexAI.getDefaultApiBaseFrom(_options); this.vertexProvider = _options.model.includes("mistral") || _options.model.includes("codestral") || _options.model.includes("mixtral") - ? "Mistral" + ? "mistral" : _options.model.includes("claude") ? "anthropic" : _options.model.includes("gemini") ? "gemini" : "unknown"; + this.anthropicInstance = new Anthropic(_options); + this.geminiInstance = new Gemini(_options) + } async fetch(url: RequestInfo | URL, init?: RequestInit) { @@ -63,68 +70,16 @@ class VertexAI extends BaseLLM { // Anthropic functions private _anthropicConvertArgs(options: CompletionOptions) { - const finalOptions = { + const convertedArgs = this.anthropicInstance.convertArgs(options); + + // Remove the `model` property and add `anthropic_version` + const { model, ...finalOptions } = convertedArgs; + return { + ...finalOptions, anthropic_version: "vertex-2023-10-16", - top_k: options.topK, - top_p: options.topP, - temperature: options.temperature, - max_tokens: options.maxTokens ?? 2048, - stop_sequences: options.stop?.filter((x) => x.trim() !== ""), - stream: options.stream ?? true, }; - - return finalOptions; } - private _anthropicConvertMessages(msgs: ChatMessage[]): any[] { - const filteredmessages = msgs.filter((m) => m.role !== "system") - const lastTwoUserMsgIndices = filteredmessages - .map((msg, index) => (msg.role === "user" ? index : -1)) - .filter((index) => index !== -1).slice(-2); - - const messages = filteredmessages.map((message, filteredMsgIdx) => { - // Add cache_control parameter to the last two user messages - // The second-to-last because it retrieves potentially already cached contents, - // The last one because we want it cached for later retrieval. - // See: https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching - const addCaching = this.cacheBehavior?.cacheConversation && lastTwoUserMsgIndices.includes(filteredMsgIdx); - - if (typeof message.content === "string") { - var chatMessage = { - ...message, - content: [{ - type: "text", - text: message.content, - ...(addCaching ? { cache_control: { type: "ephemeral" } } : {}) - }] - }; - return chatMessage; - } - - return { - ...message, - content: message.content.map((part, contentIdx) => { - if (part.type === "text") { - const newpart = { - ...part, - // If multiple text parts, only add cache_control to the last one - ...((addCaching && contentIdx == message.content.length - 1) ? { cache_control: { type: "ephemeral" } } : {}) - }; - return newpart; - } - return { - type: "image", - source: { - type: "base64", - media_type: "image/jpeg", - data: part.imageUrl?.url.split(",")[1], - }, - }; - }), - }; - }); - return messages; - } protected async *StreamChatAnthropic( messages: ChatMessage[], @@ -148,7 +103,7 @@ class VertexAI extends BaseLLM { }, body: JSON.stringify({ ...this._anthropicConvertArgs(options), - messages: this._anthropicConvertMessages(messages), + messages: this.anthropicInstance.convertMessages(messages), system: shouldCacheSystemMessage ? [ { @@ -177,58 +132,6 @@ class VertexAI extends BaseLLM { //Gemini - // Function to convert completion options to Gemini format - private _geminiConvertArgs(options: CompletionOptions) { - const finalOptions: any = {}; // Initialize an empty object - - // Map known options - if (options.topK) { - finalOptions.topK = options.topK; - } - if (options.topP) { - finalOptions.topP = options.topP; - } - if (options.temperature !== undefined && options.temperature !== null) { - finalOptions.temperature = options.temperature; - } - if (options.maxTokens) { - finalOptions.maxOutputTokens = options.maxTokens; - } - if (options.stop) { - finalOptions.stopSequences = options.stop.filter((x) => x.trim() !== ""); - } - - return { generationConfig: finalOptions }; // Wrap options under 'generationConfig' - } - - - private removeSystemMessage(messages: ChatMessage[]) { - const msgs = [...messages]; - - if (msgs[0]?.role === "system") { - const sysMsg = msgs.shift()?.content; - // @ts-ignore - if (msgs[0]?.role === "user") { - msgs[0].content = `System message - follow these instructions in every response: ${sysMsg}\n\n---\n\n${msgs[0].content}`; - } - } - - return msgs; - } - - - private _continuePartToGeminiPart(part: MessagePart) { - return part.type === "text" - ? { - text: part.text, - } - : { - inlineData: { - mimeType: "image/jpeg", - data: part.imageUrl?.url.split(",")[1], - }, - }; - } private async *streamChatGemini( messages: ChatMessage[], @@ -252,13 +155,13 @@ class VertexAI extends BaseLLM { parts: typeof msg.content === "string" ? [{ text: msg.content }] - : msg.content.map(this._continuePartToGeminiPart), + : msg.content.map(this.geminiInstance.continuePartToGeminiPart), }; }) .filter((c) => c !== null); const body = { - ...this._geminiConvertArgs(options), + ...this.geminiInstance.convertArgs(options), contents, // if this.systemMessage is defined, reformat it for Gemini API ...(this.systemMessage && @@ -392,7 +295,10 @@ class VertexAI extends BaseLLM { }); for await (const chunk of streamSse(response)) { - yield chunk.choices[0].delta; + if (chunk.choices?.[0]) { + // At the end vertexai will return a empty chunk. + yield chunk.choices[0].delta; + } } } @@ -471,7 +377,7 @@ class VertexAI extends BaseLLM { // Conditionally apply removeSystemMessage const convertedMsgs = isV1API - ? this.removeSystemMessage(messages) + ? this.geminiInstance.removeSystemMessage(messages) : messages; if (this.vertexProvider == "gemini") { yield* this.streamChatGemini(convertedMsgs, options); diff --git a/docs/docs/customize/model-providers/top-level/vertexai.md b/docs/docs/customize/model-providers/top-level/vertexai.md index 5e3dbbbbe..1778ce3c6 100644 --- a/docs/docs/customize/model-providers/top-level/vertexai.md +++ b/docs/docs/customize/model-providers/top-level/vertexai.md @@ -11,35 +11,7 @@ You need to enable the [Vertex AI API](https://console.cloud.google.com/marketpl ## Chat model -We recommend configuring **Mistral Large**, **Gemini 1.5 Pro**, or **Claude 3.5 Sonnet** as your chat model. - -```json title="config.json" -{ - "models": [ - { - "title": "Mistral Large (Vertex AI)", - "provider": "vertexai", - "model": "mistral-large", - "projectId": "[PROJECT_ID]", - "region": "us-central1" - } - ] -} -``` - -```json title="config.json" -{ - "models": [ - { - "title": "Gemini 1.5 Pro (Vertex AI)", - "provider": "vertexai", - "model": "gemini-1.5-pro", - "projectId": "[PROJECT_ID]", - "region": "us-central1" - } - ] -} -``` +We recommend configuring **Claude 3.5 Sonnet** as your chat model. ```json title="config.json" { @@ -71,19 +43,6 @@ We recommend configuring **Codestral** or **code-gecko** as your autocomplete mo } } ``` - -```json title="config.json" -{ - "tabAutocompleteModel": { - "title": "Code Gecko (Vertex AI)", - "provider": "vertexai", - "model": "codestral", - "projectId": "[PROJECT_ID]", - "region": "us-central1" - } -} -``` - ## Embeddings model We recommend configuring **text-embedding-004** as your embeddings model. diff --git a/gui/src/pages/AddNewModel/configs/models.ts b/gui/src/pages/AddNewModel/configs/models.ts index ca6844667..383d87c98 100644 --- a/gui/src/pages/AddNewModel/configs/models.ts +++ b/gui/src/pages/AddNewModel/configs/models.ts @@ -816,6 +816,20 @@ export const models: { [key: string]: ModelPackage } = { providerOptions: ["vertexai"], isOpenSource: false, }, + vertexMistralLarge: { + title: "Mistral Large", + description: + "Mistral's flagship model that's ideal for complex tasks that require large reasoning capabilities or are highly specialized (Synthetic Text Generation, Code Generation, RAG, or Agents).", + params: { + title: "Mistral Large", + model: "mistral-large", + contextLength: 32000, + }, + icon: "mistral.png", + providerOptions: ["vertexai"], + isOpenSource: false, + }, + AUTODETECT: { diff --git a/gui/src/pages/AddNewModel/configs/providers.ts b/gui/src/pages/AddNewModel/configs/providers.ts index dfaac3ffd..2b1dcf1bd 100644 --- a/gui/src/pages/AddNewModel/configs/providers.ts +++ b/gui/src/pages/AddNewModel/configs/providers.ts @@ -636,6 +636,7 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo packages: [ models.VertexGemini15Pro, models.VertexGemini15Flash, + models.mistralLarge ], collectInputFor: [ From 290a30039b6644f669d46eaf5d61d2ed898ccc89 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sat, 26 Oct 2024 23:32:55 -0700 Subject: [PATCH 17/34] truncate like pattern to 50000 bytes --- core/autocomplete/cache.ts | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/core/autocomplete/cache.ts b/core/autocomplete/cache.ts index 4886feb23..8f126e409 100644 --- a/core/autocomplete/cache.ts +++ b/core/autocomplete/cache.ts @@ -4,11 +4,19 @@ import sqlite3 from "sqlite3"; import { DatabaseConnection } from "../indexing/refreshIndex.js"; import { getTabAutocompleteCacheSqlitePath } from "../util/paths.js"; +const SQLITE_MAX_LIKE_PATTERN_LENGTH = 50000; + +function truncateToBytes(input: string, maxBytes: number): string { + let bytes = 0; + return input.split("").filter(char => (bytes += new TextEncoder().encode(char).length) <= maxBytes).join(""); +} + + export class AutocompleteLruCache { private static capacity = 1000; private mutex = new Mutex(); - constructor(private db: DatabaseConnection) {} + constructor(private db: DatabaseConnection) { } static async get(): Promise { const db = await open({ @@ -35,9 +43,10 @@ export class AutocompleteLruCache { // If the query is "co" and we have "c" -> "ontinue" in the cache, // we should return "ntinue" as the completion. // Have to make sure we take the key with shortest length + const truncatedPrefix = truncateToBytes(prefix, SQLITE_MAX_LIKE_PATTERN_LENGTH); const result = await this.db.get( "SELECT key, value FROM cache WHERE ? LIKE key || '%' ORDER BY LENGTH(key) DESC LIMIT 1", - prefix, + truncatedPrefix, ); // Validate that the cached compeltion is a valid completion for the prefix From 334705c0a3c4fd081c22faf13f9f5478a57600d4 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sat, 26 Oct 2024 23:41:01 -0700 Subject: [PATCH 18/34] rearrange truncateSqliteLikePattern --- core/autocomplete/cache.ts | 13 ++----------- core/indexing/CodeSnippetsIndex.ts | 6 +++--- core/indexing/refreshIndex.ts | 15 +++++++++++++-- 3 files changed, 18 insertions(+), 16 deletions(-) diff --git a/core/autocomplete/cache.ts b/core/autocomplete/cache.ts index 8f126e409..c04770a4c 100644 --- a/core/autocomplete/cache.ts +++ b/core/autocomplete/cache.ts @@ -1,17 +1,9 @@ import { Mutex } from "async-mutex"; import { open } from "sqlite"; import sqlite3 from "sqlite3"; -import { DatabaseConnection } from "../indexing/refreshIndex.js"; +import { DatabaseConnection, truncateSqliteLikePattern } from "../indexing/refreshIndex.js"; import { getTabAutocompleteCacheSqlitePath } from "../util/paths.js"; -const SQLITE_MAX_LIKE_PATTERN_LENGTH = 50000; - -function truncateToBytes(input: string, maxBytes: number): string { - let bytes = 0; - return input.split("").filter(char => (bytes += new TextEncoder().encode(char).length) <= maxBytes).join(""); -} - - export class AutocompleteLruCache { private static capacity = 1000; private mutex = new Mutex(); @@ -43,10 +35,9 @@ export class AutocompleteLruCache { // If the query is "co" and we have "c" -> "ontinue" in the cache, // we should return "ntinue" as the completion. // Have to make sure we take the key with shortest length - const truncatedPrefix = truncateToBytes(prefix, SQLITE_MAX_LIKE_PATTERN_LENGTH); const result = await this.db.get( "SELECT key, value FROM cache WHERE ? LIKE key || '%' ORDER BY LENGTH(key) DESC LIMIT 1", - truncatedPrefix, + truncateSqliteLikePattern(prefix), ); // Validate that the cached compeltion is a valid completion for the prefix diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index a8b41cafe..70872aff9 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -14,7 +14,7 @@ import { getParserForFile, getQueryForFile, } from "../util/treeSitter"; -import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex"; +import { DatabaseConnection, SqliteDb, tagToString, truncateSqliteLikePattern } from "./refreshIndex"; import { IndexResultType, MarkCompleteCallback, @@ -28,7 +28,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { relativeExpectedTime: number = 1; artifactId = "codeSnippets"; - constructor(private readonly ide: IDE) {} + constructor(private readonly ide: IDE) { } private static async _createTables(db: DatabaseConnection) { await db.exec(`CREATE TABLE IF NOT EXISTS code_snippets ( @@ -383,7 +383,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { const db = await SqliteDb.get(); await CodeSnippetsCodebaseIndex._createTables(db); - const likePatterns = workspaceDirs.map((dir) => `${dir}%`); + const likePatterns = workspaceDirs.map((dir) => truncateSqliteLikePattern(`${dir}%`)); const placeholders = likePatterns.map(() => "?").join(" OR path LIKE "); const query = ` diff --git a/core/indexing/refreshIndex.ts b/core/indexing/refreshIndex.ts index cf59899f1..d82a690ca 100644 --- a/core/indexing/refreshIndex.ts +++ b/core/indexing/refreshIndex.ts @@ -406,7 +406,7 @@ export async function getComputeDeleteAddRemove( for await (const _ of globalCacheIndex.update( tag, results, - async () => {}, + async () => { }, repoName, )) { } @@ -417,7 +417,7 @@ export async function getComputeDeleteAddRemove( export class GlobalCacheCodeBaseIndex implements CodebaseIndex { relativeExpectedTime: number = 1; - constructor(private db: DatabaseConnection) {} + constructor(private db: DatabaseConnection) { } artifactId = "globalCache"; @@ -469,3 +469,14 @@ export class GlobalCacheCodeBaseIndex implements CodebaseIndex { ); } } + +const SQLITE_MAX_LIKE_PATTERN_LENGTH = 50000; + +function truncateToBytes(input: string, maxBytes: number): string { + let bytes = 0; + return input.split("").filter(char => (bytes += new TextEncoder().encode(char).length) <= maxBytes).join(""); +} + +export function truncateSqliteLikePattern(input: string) { + return truncateToBytes(input, SQLITE_MAX_LIKE_PATTERN_LENGTH); +} \ No newline at end of file From 56313d83eb563ebf15e861273fe132a0fbb63267 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 28 Oct 2024 15:02:29 -0700 Subject: [PATCH 19/34] if file empty insert and return --- core/edit/lazy/streamLazyApply.ts | 2 +- .../continue/IdeProtocolClient.kt | 24 ++++++++++++------- .../vscode/src/extension/VsCodeMessenger.ts | 10 ++++++++ 3 files changed, 27 insertions(+), 9 deletions(-) diff --git a/core/edit/lazy/streamLazyApply.ts b/core/edit/lazy/streamLazyApply.ts index 6dd9cef6d..dece697ca 100644 --- a/core/edit/lazy/streamLazyApply.ts +++ b/core/edit/lazy/streamLazyApply.ts @@ -43,7 +43,7 @@ export async function* streamLazyApply( let lazyCompletionLines = streamLines(lazyCompletion, true); // Process line output // lazyCompletionLines = filterEnglishLinesAtStart(lazyCompletionLines); - lazyCompletionLines = stopAtLines(lazyCompletionLines, () => {}, ["```"]); + lazyCompletionLines = stopAtLines(lazyCompletionLines, () => { }, ["```"]); lazyCompletionLines = filterLeadingNewline(lazyCompletionLines); // Fill in unchanged code diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index a165cc96d..672a7502f 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -635,6 +635,22 @@ class IdeProtocolClient( val text = msg["text"] as String val curSelectedModelTitle = msg["curSelectedModelTitle"] as String + val editor = FileEditorManager.getInstance(project).selectedTextEditor + + if (editor == null) { + showToast("error", "No active editor to apply edits to") + respond(null) + return@launch + } + + if (editor.document.text.trim().isEmpty()) { + WriteCommandAction.runWriteCommandAction(project) { + document.insertString(0, text) + } + respond(null) + return@launch + } + val config = readConfigJson() var llm = getModelByRole(config, "applyCodeBlock") @@ -654,14 +670,6 @@ class IdeProtocolClient( val prompt = "The following code was suggested as an edit:\n```\n${text}\n```\nPlease apply it to the previous code." - val editor = FileEditorManager.getInstance(project).selectedTextEditor - - if (editor == null) { - showToast("error", "No active editor to apply edits to") - respond(null) - return@launch - } - val rif = getHighlightedCode() val (prefix, highlighted, suffix) = if (rif == null) { diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 524b61801..6ba5f1279 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -158,6 +158,16 @@ export class VsCodeMessenger { return; } + // If document is empty, insert at 0,0 and finish + if (!editor.document.getText().trim()) { + editor.edit(builder => builder.insert(new vscode.Position(0, 0), data.text)); + await webviewProtocol.request("updateApplyState", { + streamId: data.streamId, + status: "done", + }); + return; + } + // Get LLM from config const configHandler = await configHandlerPromise; const config = await configHandler.loadConfig(); From c9d38cfee15c39f951a4c710803cafdce3ce8c12 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 28 Oct 2024 15:33:32 -0700 Subject: [PATCH 20/34] truncate first bytes --- core/indexing/refreshIndex.ts | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/core/indexing/refreshIndex.ts b/core/indexing/refreshIndex.ts index d82a690ca..a2072c60e 100644 --- a/core/indexing/refreshIndex.ts +++ b/core/indexing/refreshIndex.ts @@ -472,11 +472,21 @@ export class GlobalCacheCodeBaseIndex implements CodebaseIndex { const SQLITE_MAX_LIKE_PATTERN_LENGTH = 50000; -function truncateToBytes(input: string, maxBytes: number): string { +function truncateFirstNBytes(input: string, maxBytes: number): string { let bytes = 0; - return input.split("").filter(char => (bytes += new TextEncoder().encode(char).length) <= maxBytes).join(""); + let startIndex = 0; + + for (let i = 0; i < input.length; i++) { + bytes += new TextEncoder().encode(input[i]).length; + if (bytes > maxBytes) { + startIndex = i; + break; + } + } + + return input.substring(startIndex); } export function truncateSqliteLikePattern(input: string) { - return truncateToBytes(input, SQLITE_MAX_LIKE_PATTERN_LENGTH); + return truncateFirstNBytes(input, SQLITE_MAX_LIKE_PATTERN_LENGTH); } \ No newline at end of file From d84bfecbcdbe69c43b114fc9ffbd972dc069cd55 Mon Sep 17 00:00:00 2001 From: Test Date: Tue, 29 Oct 2024 12:15:00 -0700 Subject: [PATCH 21/34] update run configs --- .idea/modules.xml | 8 -------- .idea/modules/continue-intellij-extension.iml | 8 -------- .../intellij/.run/Start Dev Server (gui).run.xml | 15 +++++++++++++++ 3 files changed, 15 insertions(+), 16 deletions(-) delete mode 100644 .idea/modules.xml delete mode 100644 .idea/modules/continue-intellij-extension.iml create mode 100644 extensions/intellij/.run/Start Dev Server (gui).run.xml diff --git a/.idea/modules.xml b/.idea/modules.xml deleted file mode 100644 index ba5b279fb..000000000 --- a/.idea/modules.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/.idea/modules/continue-intellij-extension.iml b/.idea/modules/continue-intellij-extension.iml deleted file mode 100644 index 713a88bca..000000000 --- a/.idea/modules/continue-intellij-extension.iml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/extensions/intellij/.run/Start Dev Server (gui).run.xml b/extensions/intellij/.run/Start Dev Server (gui).run.xml new file mode 100644 index 000000000..638e7bb31 --- /dev/null +++ b/extensions/intellij/.run/Start Dev Server (gui).run.xml @@ -0,0 +1,15 @@ + + + + + + + + + +
+ + + + From eb354659b4a9144660275bbe9442615384f12a9b Mon Sep 17 00:00:00 2001 From: Test Date: Tue, 29 Oct 2024 18:05:07 -0700 Subject: [PATCH 24/34] Update index.tsx --- gui/src/pages/gui/index.tsx | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/gui/src/pages/gui/index.tsx b/gui/src/pages/gui/index.tsx index 2f37027ee..aa36355b2 100644 --- a/gui/src/pages/gui/index.tsx +++ b/gui/src/pages/gui/index.tsx @@ -3,12 +3,11 @@ import { History } from "../../components/History"; export default function GUI() { return ( -
-