diff --git a/.eslintrc.shared.json b/.eslintrc.shared.json new file mode 100644 index 000000000..f4b9c4c78 --- /dev/null +++ b/.eslintrc.shared.json @@ -0,0 +1,36 @@ +{ + "parser": "@typescript-eslint/parser", + "parserOptions": { + "ecmaVersion": 6, + "sourceType": "module" + }, + "plugins": ["@typescript-eslint", "import"], + "rules": { + "@typescript-eslint/semi": "warn", + "curly": "warn", + "eqeqeq": "warn", + "no-throw-literal": "warn", + "semi": "off", + "import/order": [ + "warn", + { + "groups": [ + "builtin", + "external", + "internal", + "parent", + "sibling", + "index", + "object", + "type" + ], + "alphabetize": { + "order": "asc", + "caseInsensitive": true + }, + "newlines-between": "always" + } + ] + }, + "ignorePatterns": ["out", "dist", "**/*.d.ts"] +} diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 1fed6b72b..dce9178bf 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -4,8 +4,8 @@ ## Checklist -- [ ] The base branch of this PR is `dev`, rather than `main` -- [ ] The relevant docs, if any, have been updated or created +- [] The base branch of this PR is `dev`, rather than `main` +- [] The relevant docs, if any, have been updated or created ## Screenshots diff --git a/.github/workflows/dev_pr.yaml b/.github/workflows/dev_pr.yaml index d909a279a..12607a0b9 100644 --- a/.github/workflows/dev_pr.yaml +++ b/.github/workflows/dev_pr.yaml @@ -20,6 +20,12 @@ jobs: with: node-version-file: ".nvmrc" + - name: Cache root node_modules + uses: actions/cache@v3 + with: + path: node_modules + key: ${{ runner.os }}-node-${{ hashFiles('package-lock.json') }} + - name: Cache extension node_modules uses: actions/cache@v3 with: @@ -44,6 +50,10 @@ jobs: path: binary/node_modules key: ${{ runner.os }}-node-${{ hashFiles('binary/package-lock.json') }} + - name: root install + run: | + npm ci + - name: extensions/vscode install run: | cd extensions/vscode @@ -71,6 +81,7 @@ jobs: run: | cd extensions/vscode npx tsc --noEmit + npm run lint - name: core checks run: | diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 9fc410b38..b28e29c0c 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -97,7 +97,6 @@ jobs: with: node-version-file: ".nvmrc" - # Cache node_modules - name: Cache core node_modules uses: actions/cache@v3 with: diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index 459774b74..31b64bae1 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -255,11 +255,3 @@ jobs: # with: # github_token: ${{ secrets.GITHUB_TOKEN }} # branch: ${{ github.ref }} - - # 5 Send to Discord Webhook - - name: Discord Commits - uses: Sniddl/discord-commits@1.7 - with: - webhook: ${{ secrets.DISCORD_WEBHOOK }} - template: "avatar-with-link" - include-extras: true diff --git a/.github/workflows/ts-check.yaml b/.github/workflows/ts-check.yaml index f73016fa5..97bc39d7c 100644 --- a/.github/workflows/ts-check.yaml +++ b/.github/workflows/ts-check.yaml @@ -21,6 +21,12 @@ jobs: with: node-version-file: ".nvmrc" + - name: Cache root node_modules + uses: actions/cache@v3 + with: + path: node_modules + key: ${{ runner.os }}-node-${{ hashFiles('package-lock.json') }} + - name: Cache extension node_modules uses: actions/cache@v3 with: @@ -45,6 +51,10 @@ jobs: path: binary/node_modules key: ${{ runner.os }}-node-${{ hashFiles('binary/package-lock.json') }} + - name: Install Root Dependencies + run: | + npm ci + - name: Install extension Dependencies run: | cd extensions/vscode @@ -72,11 +82,13 @@ jobs: run: | cd core npx tsc --noEmit + npm run lint - name: tsc extensions/vscode run: | cd extensions/vscode npx tsc --noEmit + npm run lint - name: tsc binary run: | diff --git a/.gitignore b/.gitignore index bc9856690..106cef892 100644 --- a/.gitignore +++ b/.gitignore @@ -166,3 +166,6 @@ extensions/intellij/.idea/** **/.idea/workspace.xml **/.idea/usage.statistics.xml **/.idea/shelf/ + +extensions/intellij/bin +extensions/.continue-debug/ \ No newline at end of file diff --git a/.idea/.name b/.idea/.name index c0d78d1d5..389f6bc71 100644 --- a/.idea/.name +++ b/.idea/.name @@ -1 +1 @@ -Continue IntelliJ Extension \ No newline at end of file +continue-intellij-extension \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml index efa79f7df..2b4b06721 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -4,7 +4,7 @@ - + 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/.vscode/launch.json b/.vscode/launch.json index a2450e67c..dfe474f40 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -20,7 +20,8 @@ "outFiles": ["${workspaceFolder}/extensions/vscode/out/extension.js"], "preLaunchTask": "vscode-extension:build", "env": { - // "staging" for the preview deployment + "CONTINUE_GLOBAL_DIR": "${workspaceFolder}/extensions/.continue-debug" + // "staging" for the preview deployment "CONTINUE_GLOBAL_DIR": "${workspaceFolder}/extensions/.continue-debug" // "local" for entirely local development of control plane/proxy // "CONTROL_PLANE_ENV": "staging" } @@ -38,7 +39,7 @@ "cwd": "${workspaceFolder}/binary", "env": { "CONTINUE_DEVELOPMENT": "true", - "CONTINUE_GLOBAL_DIR": "${workspaceFolder}/binary/.continue" + "CONTINUE_GLOBAL_DIR": "${workspaceFolder}/extensions/.continue-debug" } }, { diff --git a/.vscode/settings.json b/.vscode/settings.json index eaf1da238..b302a1157 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -17,7 +17,8 @@ "**/core/vendor/**": true, "**/gui/dist": true, "**/extensions/vscode/gui/**": true, - "**/extensions/vscode/out/**": true + "**/extensions/vscode/out/**": true, + "**/extensions/intellij/build/**": true }, "eslint.workingDirectories": ["./core"] } diff --git a/.vscode/tasks.json b/.vscode/tasks.json index cbf610b11..1beef2615 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -5,7 +5,7 @@ { "label": "vscode-extension:build", "dependsOn": [ - // To detect compile errors + // To detect compile errors and output extensions.js "vscode-extension:tsc", // To build the React app that is used in the extension "vscode-extension:continue-ui:build", @@ -21,7 +21,10 @@ }, { "label": "vscode-extension:esbuild", - "dependsOn": ["vscode-extension:continue-ui:build"], + "dependsOn": [ + "vscode-extension:continue-ui:build", + "vscode-extension:tsc" + ], "type": "npm", "script": "esbuild-watch", "path": "extensions/vscode", diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d813a18a2..d1ca16637 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -200,10 +200,9 @@ Continue has support for more than a dozen different LLM "providers", making it While any model that works with a supported provider can be used with Continue, we keep a list of recommended models that can be automatically configured from the UI or `config.json`. The following files should be updated when adding a model: - [config_schema.json](./extensions/vscode/config_schema.json) - This is the JSON Schema definition that is used to validate `config.json`. You'll notice a number of rules defined in "definitions.ModelDescription.allOf". Here is where you write rules that can specify something like "for the provider 'anthropic', only models 'claude-2' and 'claude-instant-1' are allowed. Look through all of these rules and make sure that your model is included for providers that support it. -- [modelData.ts](./gui/src/util/modelData.ts) - This file defines that information that is shown in the model selection UI in the side bar. To add a new model: - 1. create a `ModelPackage` object, following the lead of the many examples near the top of the file - 2. add the `ModelPackage` to the `MODEL_INFO` array if you would like it to be displayed in the "Models" tab - 3. if you would like it to be displayed as an option under any of the providers, go to the `PROVIDER_INFO` object and add it to the `packages` array for each provider that you want it to be displayed under. If it is an OS model that should be valid for most providers offering OS models, you might just be able to add it to the `osModels` array as shorthand. +- [AddNewModel page](./gui/src/pages/AddNewModel) - This directory defines which model options are shown in the side bar model selection UI. To add a new model: + 1. Add a `ModelPackage` entry for the model into [configs/models.ts](./gui/src/pages/AddNewModel/configs/models.ts), following the lead of the many examples near the top of the file + 2. Add the model within its provider's array to [AddNewModel.tsx](./gui/src/pages/AddNewModel/AddNewModel.tsx) (add provider if needed) - [index.d.ts](./core/index.d.ts) - This file defines the TypeScript types used throughout Continue. You'll find a `ModelName` type. Be sure to add the name of your model to this. - LLM Providers: Since many providers use their own custom strings to identify models, you'll have to add the translation from Continue's model name (the one you added to `index.d.ts`) and the model string for each of these providers: [Ollama](./core/llm/llms/Ollama.ts), [Together](./core/llm/llms/Together.ts), and [Replicate](./core/llm/llms/Replicate.ts). You can find their full model lists here: [Ollama](https://ollama.ai/library), [Together](https://docs.together.ai/docs/inference-models), [Replicate](https://replicate.com/collections/streaming-language-models). - [Prompt Templates](./core/llm/index.ts) - In this file you'll find the `autodetectTemplateType` function. Make sure that for the model name you just added, this function returns the correct template type. This is assuming that the chat template for that model is already built in Continue. If not, you will have to add the template type and corresponding edit and chat templates. diff --git a/binary/package-lock.json b/binary/package-lock.json index e4844b8ed..0d67a4725 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -47,12 +47,11 @@ "@aws-sdk/client-bedrock-runtime": "^3.620.1", "@aws-sdk/client-sagemaker-runtime": "^3.621.0", "@aws-sdk/credential-providers": "^3.620.1", - "@continuedev/config-types": "^1.0.10", + "@continuedev/config-types": "^1.0.13", "@continuedev/llm-info": "^1.0.2", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", "@typescript-eslint/eslint-plugin": "^7.8.0", - "@typescript-eslint/parser": "^7.8.0", "@xenova/transformers": "2.14.0", "adf-to-md": "^1.1.0", "async-mutex": "^0.5.0", @@ -124,7 +123,6 @@ "cross-env": "^7.0.3", "esbuild": "0.17.19", "eslint": "^8", - "eslint-plugin-import": "^2.29.1", "jest": "^29.7.0", "jest-environment-jsdom": "^29.7.0", "myers-diff": "^2.1.0", diff --git a/core/.eslintrc.json b/core/.eslintrc.json index 04097f4db..ce1bc2575 100644 --- a/core/.eslintrc.json +++ b/core/.eslintrc.json @@ -1,21 +1,12 @@ { "root": true, - "parser": "@typescript-eslint/parser", + "extends": ["../.eslintrc.shared.json"], "parserOptions": { - "ecmaVersion": 6, - "sourceType": "module", "project": "./tsconfig.json" }, - "plugins": ["@typescript-eslint", "import"], "rules": { "quotes": ["warn", "double", {}], "@typescript-eslint/naming-convention": "off", - "@typescript-eslint/semi": "warn", - "curly": "warn", - "eqeqeq": "warn", - "no-throw-literal": "warn", - "semi": "off", "@typescript-eslint/no-floating-promises": "warn" - }, - "ignorePatterns": ["out", "dist", "**/*.d.ts"] + } } diff --git a/core/autocomplete/cache.ts b/core/autocomplete/cache.ts index 5005480bf..c04770a4c 100644 --- a/core/autocomplete/cache.ts +++ b/core/autocomplete/cache.ts @@ -1,18 +1,14 @@ 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"; export class AutocompleteLruCache { private static capacity = 1000; private mutex = new Mutex(); - db: DatabaseConnection; - - constructor(db: DatabaseConnection) { - this.db = db; - } + constructor(private db: DatabaseConnection) { } static async get(): Promise { const db = await open({ @@ -41,7 +37,7 @@ export class AutocompleteLruCache { // Have to make sure we take the key with shortest length const result = await this.db.get( "SELECT key, value FROM cache WHERE ? LIKE key || '%' ORDER BY LENGTH(key) DESC LIMIT 1", - prefix, + truncateSqliteLikePattern(prefix), ); // Validate that the cached compeltion is a valid completion for the prefix diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index 7e863e1c4..4fae89003 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -36,7 +36,6 @@ import { RecentlyEditedRange } from "./recentlyEdited.js"; import { RootPathContextService } from "./services/RootPathContextService.js"; import { avoidPathLineAndEmptyComments, - noTopLevelKeywordsMidline, skipPrefixes, stopAtLines, stopAtRepeatingLines, @@ -50,11 +49,7 @@ import Handlebars from "handlebars"; import { getConfigJsonPath } from "../util/paths.js"; import { BracketMatchingService } from "./services/BracketMatchingService.js"; import { ImportDefinitionsService } from "./services/ImportDefinitionsService.js"; -import { - noFirstCharNewline, - onlyWhitespaceAfterEndOfLine, - stopAtStopTokens, -} from "./streamTransforms/charStream.js"; +import { stopAtStopTokens } from "./streamTransforms/charStream.js"; export interface AutocompleteInput { completionId: string; @@ -95,6 +90,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", ""]; @@ -111,6 +107,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, @@ -128,14 +132,6 @@ function formatExternalSnippet( return lines.join("\n"); } -let shownGptClaudeWarning = false; -const nonAutocompleteModels = [ - // "gpt", - // "claude", - "mistral", - "instruct", -]; - export type GetLspDefinitionsFunction = ( filepath: string, contents: string, @@ -268,7 +264,10 @@ export class CompletionProvider { const workspaceDirs = await this.ide.getWorkspaceDirs(); let filepath = input.filepath; for (const workspaceDir of workspaceDirs) { - if (filepath.startsWith(workspaceDir)) { + const relativePath = path.relative(workspaceDir, filepath); + const relativePathBase = relativePath.split(path.sep).at(0); + const isInWorkspace = !path.isAbsolute(relativePath) && relativePathBase !== ".."; + if (isInWorkspace) { filepath = path.relative(workspaceDir, filepath); break; } @@ -334,14 +333,6 @@ export class CompletionProvider { llm.completionOptions.temperature = 0.01; } - // 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) @@ -360,7 +351,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; } @@ -442,6 +433,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, @@ -465,10 +483,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; + } } } @@ -485,18 +506,6 @@ export class CompletionProvider { llm.model = TRIAL_FIM_MODEL; } - if ( - !shownGptClaudeWarning && - nonAutocompleteModels.some((model) => llm.model.includes(model)) && - !llm.model.toLowerCase().includes("deepseek") && - !llm.model.toLowerCase().includes("codestral") - ) { - shownGptClaudeWarning = true; - throw new Error( - `Warning: ${llm.model} is not trained for tab-autocomplete, and will result in low-quality suggestions. See the docs to learn more about why: https://docs.continue.dev/features/tab-autocomplete#i-want-better-completions-should-i-use-gpt-4`, - ); - } - // Prompt let fullPrefix = getRangeInString(fileContents, { @@ -506,11 +515,10 @@ export class CompletionProvider { if (input.injectDetails) { const lines = fullPrefix.split("\n"); - fullPrefix = `${lines.slice(0, -1).join("\n")}\n${ - lang.singleLineComment - } ${input.injectDetails - .split("\n") - .join(`\n${lang.singleLineComment} `)}\n${lines[lines.length - 1]}`; + fullPrefix = `${lines.slice(0, -1).join("\n")}\n${lang.singleLineComment + } ${input.injectDetails + .split("\n") + .join(`\n${lang.singleLineComment} `)}\n${lines[lines.length - 1]}`; } const fullSuffix = getRangeInString(fileContents, { @@ -531,17 +539,17 @@ export class CompletionProvider { let extrasSnippets = options.useOtherFiles ? ((await Promise.race([ - this.getDefinitionsFromLsp( - filepath, - fullPrefix + fullSuffix, - fullPrefix.length, - this.ide, - lang, - ), - new Promise((resolve) => { - setTimeout(() => resolve([]), 100); - }), - ])) as AutocompleteSnippet[]) + this.getDefinitionsFromLsp( + filepath, + fullPrefix + fullSuffix, + fullPrefix.length, + this.ide, + lang, + ), + new Promise((resolve) => { + setTimeout(() => resolve([]), 100); + }), + ])) as AutocompleteSnippet[]) : []; const workspaceDirs = await this.ide.getWorkspaceDirs(); @@ -580,8 +588,8 @@ export class CompletionProvider { completionOptions, compilePrefixSuffix = undefined, } = options.template - ? { template: options.template, completionOptions: {} } - : getTemplateForModel(llm.model); + ? { template: options.template, completionOptions: {} } + : getTemplateForModel(llm.model); let prompt: string; const filename = getBasename(filepath); @@ -652,25 +660,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}`), ]; - 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 = + !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( @@ -678,14 +686,14 @@ export class CompletionProvider { () => llm.supportsFim() ? llm.streamFim(prefix, suffix, { - ...completionOptions, - stop, - }) + ...completionOptions, + stop, + }) : llm.streamComplete(prompt, { - ...completionOptions, - raw: true, - stop, - }), + ...completionOptions, + raw: true, + stop, + }), multiline, ); @@ -705,46 +713,52 @@ export class CompletionProvider { } }; let charGenerator = generatorWithCancellation(); - charGenerator = noFirstCharNewline(charGenerator); - charGenerator = onlyWhitespaceAfterEndOfLine( - charGenerator, - lang.endOfLine, - fullStop, - ); - charGenerator = stopAtStopTokens(charGenerator, stop); - charGenerator = this.bracketMatchingService.stopOnUnmatchedClosingBracket( - charGenerator, - prefix, - suffix, - filepath, - multiline, - ); - 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); + charGenerator = + this.bracketMatchingService.stopOnUnmatchedClosingBracket( + charGenerator, + prefix, + suffix, + filepath, + multiline, + ); } - 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) { @@ -761,12 +775,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/services/BracketMatchingService.ts b/core/autocomplete/services/BracketMatchingService.ts index 3734df2be..d4415259e 100644 --- a/core/autocomplete/services/BracketMatchingService.ts +++ b/core/autocomplete/services/BracketMatchingService.ts @@ -84,9 +84,13 @@ export class BracketMatchingService { // 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;} + if (suffix[i] === " ") { + continue; + } const openBracket = BracketMatchingService.BRACKETS_REVERSE[suffix[i]]; - if (!openBracket) {break;} + if (!openBracket) { + break; + } stack.unshift(openBracket); } 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/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 diff --git a/core/autocomplete/test/filter.test.ts b/core/autocomplete/test/filter.test.ts new file mode 100644 index 000000000..171b1cb44 --- /dev/null +++ b/core/autocomplete/test/filter.test.ts @@ -0,0 +1,30 @@ +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", () => { + beforeEach(async () => { + await new Promise((resolve) => setTimeout(resolve, 50)); + }); + + 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 new file mode 100644 index 000000000..2deeec9de --- /dev/null +++ b/core/autocomplete/test/testCases.ts @@ -0,0 +1,2013 @@ +import { dedent } from "../../util"; +import { AutocompleteFileringTestInput } from "./util"; + +export const TEST_CASES: 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.", + 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; + } + } + `, + llmOutput: dedent`if (number === 0) { + throw new Error("Cannot divide by zero"); + } + this.result /= number; + return this; + }`, + expectedCompletion: dedent`if (number === 0) { + throw new Error("Cannot divide by zero"); + } + this.result /= number; + return this; + }`, + }, + { + 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", + }, + { + 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/autocomplete/test/util.ts b/core/autocomplete/test/util.ts new file mode 100644 index 000000000..60e7b3f93 --- /dev/null +++ b/core/autocomplete/test/util.ts @@ -0,0 +1,74 @@ +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 }; +} + +export interface AutocompleteFileringTestInput { + description: string; + filename: string; + input: string; + llmOutput: string; + expectedCompletion: string | null; + options?: { + only?: boolean; + }; +} + +export async function testAutocompleteFiltering( + test: AutocompleteFileringTestInput, +) { + const { prefix, suffix } = parseFimExample(test.input); + + // Setup necessary objects + const llm = new Mock({ + model: "mock", + }); + llm.completion = test.llmOutput; + 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.expectedCompletion); +} diff --git a/core/commands/slash/edit.ts b/core/commands/slash/edit.ts index c39fb2dc0..aafafa67e 100644 --- a/core/commands/slash/edit.ts +++ b/core/commands/slash/edit.ts @@ -95,10 +95,10 @@ export async function getPromptParts( } let filePrefix = fullFileContentsList - .slice(curStartLine, maxStartLine) + .slice(curStartLine, maxStartLine - 1) .join("\n"); let fileSuffix = fullFileContentsList - .slice(minEndLine, curEndLine - 1) + .slice(minEndLine, curEndLine + 1) .join("\n"); if (rif.contents.length > 0) { diff --git a/core/config/profile/ControlPlaneProfileLoader.ts b/core/config/profile/ControlPlaneProfileLoader.ts index ec407974a..5862fab6c 100644 --- a/core/config/profile/ControlPlaneProfileLoader.ts +++ b/core/config/profile/ControlPlaneProfileLoader.ts @@ -6,9 +6,9 @@ import { IdeSettings, SerializedContinueConfig, } from "../../index.js"; +import { ConfigResult } from "../load.js"; import { IProfileLoader } from "./IProfileLoader.js"; import doLoadConfig from "./doLoadConfig.js"; -import { ConfigResult } from "../load.js"; export default class ControlPlaneProfileLoader implements IProfileLoader { private static RELOAD_INTERVAL = 1000 * 60 * 15; // every 15 minutes @@ -45,7 +45,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader { )) as any); const serializedConfig: SerializedContinueConfig = settings; - return doLoadConfig( + const results = await doLoadConfig( this.ide, this.ideSettingsPromise, this.controlPlaneClient, @@ -53,6 +53,11 @@ export default class ControlPlaneProfileLoader implements IProfileLoader { serializedConfig, this.workspaceId, ); + + return { + ...results, + errors: [], // Don't do config validation here, it happens in admin panel + }; } setIsActive(isActive: boolean): void {} diff --git a/core/config/types.ts b/core/config/types.ts index 390bc5519..0caf0e12e 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -338,11 +338,7 @@ declare global { capabilities?: ModelCapability; // IBM watsonx options - watsonxUrl?: string; - watsonxCreds?: string; - watsonxProjectId?: string; - watsonxStopToken?: string; - watsonxApiVersion?: string; + deploymentId?: string; } type RequireAtLeastOne = Pick< T, @@ -768,7 +764,8 @@ declare global { | "gemini" | "continue-proxy" | "deepinfra" - | "voyage"; + | "voyage" + | "watsonx"; export interface EmbedOptions { apiBase?: string; @@ -779,6 +776,7 @@ declare global { apiVersion?: string; requestOptions?: RequestOptions; maxChunkSize?: number; + projectId?: string; } export interface EmbeddingsProviderDescription extends EmbedOptions { diff --git a/core/config/validation.ts b/core/config/validation.ts index 9da86c6ef..ebcbb623d 100644 --- a/core/config/validation.ts +++ b/core/config/validation.ts @@ -1,4 +1,4 @@ -import { SerializedContinueConfig } from "../"; +import { ModelDescription, SerializedContinueConfig } from "../"; import { Telemetry } from "../util/posthog"; export interface ConfigValidationError { @@ -14,11 +14,11 @@ export interface ConfigValidationError { export function validateConfig(config: SerializedContinueConfig) { const errors: ConfigValidationError[] = []; - // Validate models - if (!Array.isArray(config.models) || config.models.length === 0) { + // Validate chat models + if (!Array.isArray(config.models)) { errors.push({ fatal: true, - message: "The 'models' field should be a non-empty array.", + message: "The 'models' field should be an array.", }); } else { config.models.forEach((model, index) => { @@ -37,6 +37,36 @@ export function validateConfig(config: SerializedContinueConfig) { }); } + // Validate tab autocomplete model(s) + if (config.tabAutocompleteModel) { + function validateTabAutocompleteModel(modelDescription: ModelDescription) { + const modelName = modelDescription.model.toLowerCase(); + const nonAutocompleteModels = [ + // "gpt", + // "claude", + "mistral", + "instruct", + ]; + + if ( + nonAutocompleteModels.some((m) => modelName.includes(m)) && + !modelName.includes("deepseek") && + !modelName.includes("codestral") + ) { + errors.push({ + fatal: false, + message: `${modelDescription.model} is not trained for tab-autocomplete, and will result in low-quality suggestions. See the docs to learn more about why: https://docs.continue.dev/features/tab-autocomplete#i-want-better-completions-should-i-use-gpt-4`, + }); + } + } + + if (Array.isArray(config.tabAutocompleteModel)) { + config.tabAutocompleteModel.forEach(validateTabAutocompleteModel); + } else { + validateTabAutocompleteModel(config.tabAutocompleteModel); + } + } + // Validate slashCommands if (config.slashCommands) { if (!Array.isArray(config.slashCommands)) { diff --git a/core/context/providers/CustomContextProvider.ts b/core/context/providers/CustomContextProvider.ts index ac14dc9f4..f87a4554f 100644 --- a/core/context/providers/CustomContextProvider.ts +++ b/core/context/providers/CustomContextProvider.ts @@ -8,10 +8,7 @@ import type { } from "../../"; class CustomContextProviderClass implements IContextProvider { - custom: CustomContextProvider; - constructor(custom: CustomContextProvider) { - this.custom = custom; - } + constructor(private custom: CustomContextProvider) {} get description(): ContextProviderDescription { return { diff --git a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts index 7fdf8ec31..9495f1608 100644 --- a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts @@ -14,13 +14,13 @@ export interface RetrievalPipelineOptions { llm: ILLM; config: ContinueConfig; ide: IDE; - input: string; nRetrieve: number; nFinal: number; tags: BranchAndDir[]; pathSep: string; filterDirectory?: string; + includeEmbeddings?: boolean; // Used to handle JB w/o an embeddings model } export interface IRetrievalPipeline { @@ -29,6 +29,7 @@ export interface IRetrievalPipeline { export default class BaseRetrievalPipeline implements IRetrievalPipeline { private lanceDbIndex: LanceDbIndex; + constructor(protected readonly options: RetrievalPipelineOptions) { this.lanceDbIndex = new LanceDbIndex( options.config.embeddingsProvider, @@ -71,7 +72,7 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline { } } - return chunks; + return chunks.slice(0, n); } protected async retrieveFts(input: string, n: number): Promise { diff --git a/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts index f6f83a4f2..6caef72dd 100644 --- a/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts @@ -5,7 +5,7 @@ import BaseRetrievalPipeline from "./BaseRetrievalPipeline.js"; export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline { async run(): Promise { - const { input, nFinal, filterDirectory } = this.options; + const { input, nFinal, filterDirectory, includeEmbeddings } = this.options; // We give 1/4 weight to recently edited files, 1/4 to full text search, // and the remaining 1/2 to embeddings @@ -17,10 +17,9 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline { const ftsChunks = await this.retrieveFts(input, ftsNFinal); - const embeddingsChunks = await this.retrieveEmbeddings( - input, - embeddingsNFinal, - ); + const embeddingsChunks = includeEmbeddings + ? await this.retrieveEmbeddings(input, embeddingsNFinal) + : []; const recentlyEditedFilesChunks = await this.retrieveAndChunkRecentlyEditedFiles(recentlyEditedNFinal); diff --git a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts index faac97957..375f1b17b 100644 --- a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts @@ -6,12 +6,15 @@ import BaseRetrievalPipeline from "./BaseRetrievalPipeline.js"; export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { private async _retrieveInitial(): Promise { - const { input, nRetrieve, filterDirectory } = this.options; + const { input, nRetrieve, filterDirectory, includeEmbeddings } = + this.options; let retrievalResults: Chunk[] = []; const ftsChunks = await this.retrieveFts(input, nRetrieve); - const embeddingsChunks = await this.retrieveEmbeddings(input, nRetrieve); + const embeddingsChunks = includeEmbeddings + ? await this.retrieveEmbeddings(input, nRetrieve) + : []; const recentlyEditedFilesChunks = await this.retrieveAndChunkRecentlyEditedFiles(nRetrieve); diff --git a/core/context/retrieval/repoMapRequest.ts b/core/context/retrieval/repoMapRequest.ts index 618be4808..e4b3e072e 100644 --- a/core/context/retrieval/repoMapRequest.ts +++ b/core/context/retrieval/repoMapRequest.ts @@ -6,6 +6,7 @@ import generateRepoMap from "../../util/generateRepoMap"; const SUPPORTED_MODEL_TITLE_FAMILIES = [ "claude-3", "llama3.1", + "llama3.2", "gemini-1.5", "gpt-4", ]; diff --git a/core/context/retrieval/retrieval.ts b/core/context/retrieval/retrieval.ts index 2652bfa0f..a40e163a0 100644 --- a/core/context/retrieval/retrieval.ts +++ b/core/context/retrieval/retrieval.ts @@ -1,8 +1,10 @@ import path from "path"; + import { BranchAndDir, ContextItem, ContextProviderExtras } from "../../"; import TransformersJsEmbeddingsProvider from "../../indexing/embeddings/TransformersJsEmbeddingsProvider"; import { resolveRelativePathInWorkspace } from "../../util/ideUtils"; import { INSTRUCTIONS_BASE_ITEM } from "../providers/utils"; + import { RetrievalPipelineOptions } from "./pipelines/BaseRetrievalPipeline"; import NoRerankerRetrievalPipeline from "./pipelines/NoRerankerRetrievalPipeline"; import RerankerRetrievalPipeline from "./pipelines/RerankerRetrievalPipeline"; @@ -21,15 +23,17 @@ export async function retrieveContextItemsFromEmbeddings( // transformers.js not supported in JetBrains IDEs right now const isJetBrainsAndTransformersJs = - extras.embeddingsProvider.id === TransformersJsEmbeddingsProvider.model && + extras.embeddingsProvider.providerName === + TransformersJsEmbeddingsProvider.providerName && (await extras.ide.getIdeInfo()).ideType === "jetbrains"; if (isJetBrainsAndTransformersJs) { - throw new Error( - "The 'transformers.js' context provider is not currently supported in JetBrains. " + - "For now, you can use Ollama to set up local embeddings, or use our 'free-trial' " + - "embeddings provider. See here to learn more: " + - "https://docs.continue.dev/walkthroughs/codebase-embeddings#embeddings-providers", + void extras.ide.showToast( + "warning", + "Codebase retrieval is limited when `embeddingsProvider` is empty or set to `transformers.js` in JetBrains. " + + "You can use Ollama to set up local embeddings, use our 'free-trial', " + + "or configure your own. See here to learn more: " + + "https://docs.continue.dev/customize/model-types/embeddings", ); } @@ -85,6 +89,7 @@ export async function retrieveContextItemsFromEmbeddings( input: extras.fullInput, llm: extras.llm, config: extras.config, + includeEmbeddings: !isJetBrainsAndTransformersJs, }; const pipeline = new pipelineType(pipelineOptions); diff --git a/core/core.ts b/core/core.ts index 415540a74..8ce7c7a5d 100644 --- a/core/core.ts +++ b/core/core.ts @@ -20,15 +20,15 @@ import DocsService from "./indexing/docs/DocsService"; import Ollama from "./llm/llms/Ollama"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import { GlobalContext } from "./util/GlobalContext"; +import { ChatDescriber } from "./util/chatDescriber"; import { logDevData } from "./util/devdata"; import { DevDataSqliteDb } from "./util/devdataSqlite"; import { fetchwithRequestOptions } from "./util/fetchWithOptions"; import historyManager from "./util/history"; import type { IMessenger, Message } from "./util/messenger"; -import { editConfigJson } from "./util/paths"; +import { editConfigJson, setupInitialDotContinueDirectory } from "./util/paths"; import { Telemetry } from "./util/posthog"; import { TTS } from "./util/tts"; -import { ChatDescriber } from "./util/chatDescriber"; export class Core { // implements IMessenger @@ -79,6 +79,9 @@ export class Core { private readonly ide: IDE, private readonly onWrite: (text: string) => Promise = async () => {}, ) { + // Ensure .continue directory is created + setupInitialDotContinueDirectory(); + this.indexingState = { status: "loading", desc: "loading", progress: 0 }; const ideSettingsPromise = messenger.request("getIdeSettings", undefined); @@ -483,7 +486,7 @@ export class Core { on("tts/kill", async () => { void TTS.kill(); }); - + on("chatDescriber/describe", async (msg) => { const currentModel = await this.getSelectedModel(); return await ChatDescriber.describe(currentModel, {}, msg.data); diff --git a/core/diff/util.ts b/core/diff/util.ts index 6d218bcbf..9dda0ff02 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/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/core/edit/streamDiffLines.ts b/core/edit/streamDiffLines.ts index cad33b3a2..dbab5841c 100644 --- a/core/edit/streamDiffLines.ts +++ b/core/edit/streamDiffLines.ts @@ -60,7 +60,7 @@ export async function* streamDiffLines( language: string | undefined, onlyOneInsertion?: boolean, ): AsyncGenerator { - Telemetry.capture( + void Telemetry.capture( "inlineEdit", { model: llm.model, @@ -94,7 +94,6 @@ export async function* streamDiffLines( ); const inept = modelIsInept(llm.model); - const options: LLMFullCompletionOptions = {}; const completion = typeof prompt === "string" ? llm.streamComplete(prompt, { raw: true }) diff --git a/core/index.d.ts b/core/index.d.ts index 183d5e427..6d0d8a46b 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -363,16 +363,13 @@ export interface LLMOptions { region?: string; // GCP Options - projectId?: string; capabilities?: ModelCapability; - // IBM watsonx options - watsonxUrl?: string; - watsonxCreds?: string; - watsonxProjectId?: string; - watsonxStopToken?: string; - watsonxApiVersion?: string; - watsonxFullUrl?: string; + // GCP and Watsonx Options + projectId?: string; + + // IBM watsonx Options + deploymentId?: string; } type RequireAtLeastOne = Pick< T, @@ -606,13 +603,13 @@ type TemplateType = | "codellama-70b" | "llava" | "gemma" + | "granite" | "llama3"; type ModelProvider = | "openai" | "free-trial" | "anthropic" - | "anthropic-vertexai" | "cohere" | "together" | "ollama" @@ -625,9 +622,7 @@ type ModelProvider = | "lmstudio" | "llamafile" | "gemini" - | "gemini-vertexai" | "mistral" - | "mistral-vertexai" | "bedrock" | "bedrockimport" | "sagemaker" @@ -648,8 +643,9 @@ type ModelProvider = | "nvidia" | "vllm" | "mock" - | "cerebras"; - + | "cerebras" + | "vertexai" + | "askSage"; export type ModelName = | "AUTODETECT" @@ -664,6 +660,8 @@ export type ModelName = | "gpt-4-turbo" | "gpt-4-turbo-preview" | "gpt-4-vision-preview" + | "o1-preview" + | "o1-mini" // Mistral | "codestral-latest" | "open-mistral-7b" @@ -691,6 +689,12 @@ export type ModelName = // Llama 3.1 | "llama3.1-8b" | "llama3.1-70b" + | "llama3.1-405b" + // Llama 3.2 + | "llama3.2-1b" + | "llama3.2-3b" + | "llama3.2-11b" + | "llama3.2-90b" // Other Open-source | "phi2" | "phind-codellama-34b" @@ -823,7 +827,8 @@ export type EmbeddingsProviderName = | "nvidia" | "voyage" | "mistral" - | "vertex"; + | "vertexai" + | "watsonx"; export interface EmbedOptions { apiBase?: string; @@ -841,7 +846,7 @@ export interface EmbedOptions { // AWS and GCP Options region?: string; - // GCP Options + // GCP and Watsonx Options projectId?: string; } @@ -882,6 +887,7 @@ export interface TabAutocompleteOptions { debounceDelay: number; maxSuffixPercentage: number; prefixPercentage: number; + transform?: boolean; template?: string; multilineCompletions: "always" | "never" | "auto"; slidingWindowPrefixPercentage: number; 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/chunk/ChunkCodebaseIndex.ts b/core/indexing/chunk/ChunkCodebaseIndex.ts index cdf91f359..e2d316d67 100644 --- a/core/indexing/chunk/ChunkCodebaseIndex.ts +++ b/core/indexing/chunk/ChunkCodebaseIndex.ts @@ -23,9 +23,7 @@ export class ChunkCodebaseIndex implements CodebaseIndex { private readonly pathSep: string, private readonly continueServerClient: IContinueServerClient, private readonly maxChunkSize: number, - ) { - this.readFile = readFile; - } + ) {} async *update( tag: IndexTag, diff --git a/core/indexing/docs/preIndexedDocs.ts b/core/indexing/docs/preIndexedDocs.ts index 9da86ef85..83b439d42 100644 --- a/core/indexing/docs/preIndexedDocs.ts +++ b/core/indexing/docs/preIndexedDocs.ts @@ -299,6 +299,30 @@ const preIndexedDocs: Record< rootUrl: "https://docs.godotengine.org/en/latest/", faviconUrl: "https://godotengine.org/favicon.ico", }, + "https://docs.amplify.aws/react/": { + title: "AWS Amplify (Gen 2)", + startUrl: "https://docs.amplify.aws/react/start/", + rootUrl: "https://docs.amplify.aws/react/", + faviconUrl: "https://docs.amplify.aws/favicon.ico" + }, + "https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/": { + title: "AWS SDK for JavaScript v3", + startUrl: "https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/", + rootUrl: "https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/", + faviconUrl: "https://docs.aws.amazon.com/favicon.ico" + }, + "https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html": { + title: "AWS CDK v2", + startUrl: "https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html", + rootUrl: "https://docs.aws.amazon.com/cdk/api/v2/docs/", + faviconUrl: "https://docs.aws.amazon.com/cdk/api/v2/img/favicon-32x32.png" + }, + "https://awscli.amazonaws.com/v2/documentation/api/latest/index.html": { + title: "AWS CLI commands", + startUrl: "https://awscli.amazonaws.com/v2/documentation/api/latest/index.html", + rootUrl: "https://awscli.amazonaws.com/v2/documentation/api/latest/", + faviconUrl: "https://docs.aws.amazon.com/favicon.ico" + } }; export default preIndexedDocs; diff --git a/core/indexing/embeddings/BedrockEmbeddingsProvider.ts b/core/indexing/embeddings/BedrockEmbeddingsProvider.ts index bf3bcac88..a5cfce6c4 100644 --- a/core/indexing/embeddings/BedrockEmbeddingsProvider.ts +++ b/core/indexing/embeddings/BedrockEmbeddingsProvider.ts @@ -6,11 +6,14 @@ import { fromIni } from "@aws-sdk/credential-providers"; import { EmbeddingsProviderName, EmbedOptions, FetchFunction } from "../../index.js"; import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js"; +interface ModelConfig { + formatPayload: (text: string) => any; + extractEmbeddings: (responseBody: any) => number[][]; +} + class BedrockEmbeddingsProvider extends BaseEmbeddingsProvider { - static providerName: EmbeddingsProviderName = "bedrock"; - - static defaultOptions: Partial | undefined = { + static defaultOptions: Partial = { model: "amazon.titan-embed-text-v2:0", region: "us-east-1" }; @@ -18,6 +21,7 @@ class BedrockEmbeddingsProvider extends BaseEmbeddingsProvider { constructor(options: EmbedOptions, fetch: FetchFunction) { super(options, fetch); + this.options.model = this.options.model || BedrockEmbeddingsProvider.defaultOptions.model!; if (!options.apiBase) { options.apiBase = `https://bedrock-runtime.${options.region}.amazonaws.com`; } @@ -29,7 +33,7 @@ class BedrockEmbeddingsProvider extends BaseEmbeddingsProvider { } } - async embed(chunks: string[]) { + async embed(chunks: string[]): Promise { const credentials = await this._getCredentials(); const client = new BedrockRuntimeClient({ region: this.options.region, @@ -43,41 +47,64 @@ class BedrockEmbeddingsProvider extends BaseEmbeddingsProvider { return ( await Promise.all( chunks.map(async (chunk) => { - const input = this._generateInvokeModelCommandInput(chunk, this.options); + const input = this._generateInvokeModelCommandInput(chunk); const command = new InvokeModelCommand(input); const response = await client.send(command); - if (response.body) { const responseBody = JSON.parse(new TextDecoder().decode(response.body)); - return [responseBody.embedding]; + return this._extractEmbeddings(responseBody); } + return []; }), ) ).flat(); } - private _generateInvokeModelCommandInput( - prompt: string, - options: EmbedOptions, - ): any { - const payload = { - "inputText": prompt, - "dimensions": 512, - "normalize": true - }; + private _generateInvokeModelCommandInput(text: string): any { + const modelConfig = this._getModelConfig(); + const payload = modelConfig.formatPayload(text); return { body: JSON.stringify(payload), modelId: this.options.model, - accept: "application/json", - contentType: "application/json" + accept: "*/*", + contentType: "application/json", }; } + private _extractEmbeddings(responseBody: any): number[][] { + const modelConfig = this._getModelConfig(); + return modelConfig.extractEmbeddings(responseBody); + } + + private _getModelConfig() { + const modelConfigs: { [key: string]: ModelConfig } = { + 'cohere': { + formatPayload: (text: string) => ({ + texts: [text], + input_type: "search_document", + truncate: "END", + }), + extractEmbeddings: (responseBody: any) => responseBody.embeddings || [], + }, + 'amazon.titan-embed': { + formatPayload: (text: string) => ({ + inputText: text, + }), + extractEmbeddings: (responseBody: any) => responseBody.embedding ? [responseBody.embedding] : [], + }, + }; + + const modelPrefix = Object.keys(modelConfigs).find(prefix => this.options.model!.startsWith(prefix)); + if (!modelPrefix) { + throw new Error(`Unsupported model: ${this.options.model}`); + } + return modelConfigs[modelPrefix]; + } + private async _getCredentials() { try { - return await - fromIni({ + return await fromIni({ profile: this.profile, ignoreCache: true })(); @@ -88,7 +115,6 @@ class BedrockEmbeddingsProvider extends BaseEmbeddingsProvider { return await fromIni()(); } } - } export default BedrockEmbeddingsProvider; diff --git a/core/indexing/embeddings/SageMakerEmbeddingsProvider.ts b/core/indexing/embeddings/SageMakerEmbeddingsProvider.ts index 9b860f1ae..a8a3fb0a5 100644 --- a/core/indexing/embeddings/SageMakerEmbeddingsProvider.ts +++ b/core/indexing/embeddings/SageMakerEmbeddingsProvider.ts @@ -1,114 +1,114 @@ import { - InvokeEndpointCommand, - SageMakerRuntimeClient, - } from "@aws-sdk/client-sagemaker-runtime"; - import { fromIni } from "@aws-sdk/credential-providers"; - - import { - EmbeddingsProviderName, - EmbedOptions, - FetchFunction, - } from "../../index.js"; - import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js"; - - - class SageMakerEmbeddingsProvider extends BaseEmbeddingsProvider { - static providerName: EmbeddingsProviderName = "sagemaker"; - - static defaultOptions: Partial | undefined = { - region: "us-west-2", - maxBatchSize: 1, - }; - profile?: string | undefined; - - constructor(options: EmbedOptions, fetch: FetchFunction) { - super(options, fetch); - if (!options.apiBase) { - options.apiBase = `https://runtime.sagemaker.${options.region}.amazonaws.com`; - } - - if (options.profile) { - this.profile = options.profile; - } else { - this.profile = "sagemaker"; - } + InvokeEndpointCommand, + SageMakerRuntimeClient, +} from "@aws-sdk/client-sagemaker-runtime"; +import { fromIni } from "@aws-sdk/credential-providers"; + +import { + EmbeddingsProviderName, + EmbedOptions, + FetchFunction, +} from "../../index.js"; + +import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js"; + + +class SageMakerEmbeddingsProvider extends BaseEmbeddingsProvider { + static providerName: EmbeddingsProviderName = "sagemaker"; + + static defaultOptions: Partial | undefined = { + region: "us-west-2", + maxBatchSize: 1, + }; + profile?: string | undefined; + + constructor(options: EmbedOptions, fetch: FetchFunction) { + super(options, fetch); + if (!options.apiBase) { + options.apiBase = `https://runtime.sagemaker.${options.region}.amazonaws.com`; } - - async embed(chunks: string[]) { - const credentials = await this._getCredentials(); - const client = new SageMakerRuntimeClient({ - region: this.options.region, - credentials: { - accessKeyId: credentials.accessKeyId, - secretAccessKey: credentials.secretAccessKey, - sessionToken: credentials.sessionToken || "", - }, - }); - - const batchedChunks = this.getBatchedChunks(chunks); - return ( - await Promise.all( - batchedChunks.map(async (batch) => { - const input = this._generateInvokeModelCommandInput( - batch, - this.options, - ); - const command = new InvokeEndpointCommand(input); - const response = await client.send(command); - - if (response.Body) { - const responseBody = JSON.parse( - new TextDecoder().decode(response.Body), - ); - // If the body contains a key called "embedding" or "embeddings", return the value, otherwise return the whole body - if (responseBody.embedding) { - return responseBody.embedding; - } else if (responseBody.embeddings) { - return responseBody.embeddings; - } else { - return responseBody; - } - } - }), - ) - ).flat(); - } - private _generateInvokeModelCommandInput( - prompts: string | string[], - options: EmbedOptions, - ): any { - const payload = { - inputs: prompts, - normalize: true, - // ...(options.requestOptions?.extraBodyProperties || {}), - }; - - if (options.requestOptions?.extraBodyProperties) { - Object.assign(payload, options.requestOptions.extraBodyProperties); - } - - return { - EndpointName: this.options.model, - Body: JSON.stringify(payload), - ContentType: "application/json", - CustomAttributes: "accept_eula=false", - }; - } - - private async _getCredentials() { - try { - return await fromIni({ - profile: this.profile, - ignoreCache: true, - })(); - } catch (e) { - console.warn( - `AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`, - ); - return await fromIni()(); - } + + if (options.profile) { + this.profile = options.profile; + } else { + this.profile = "sagemaker"; } } - - export default SageMakerEmbeddingsProvider; - \ No newline at end of file + + async embed(chunks: string[]) { + const credentials = await this._getCredentials(); + const client = new SageMakerRuntimeClient({ + region: this.options.region, + credentials: { + accessKeyId: credentials.accessKeyId, + secretAccessKey: credentials.secretAccessKey, + sessionToken: credentials.sessionToken || "", + }, + }); + + const batchedChunks = this.getBatchedChunks(chunks); + return ( + await Promise.all( + batchedChunks.map(async (batch) => { + const input = this._generateInvokeModelCommandInput( + batch, + this.options, + ); + const command = new InvokeEndpointCommand(input); + const response = await client.send(command); + + if (response.Body) { + const responseBody = JSON.parse( + new TextDecoder().decode(response.Body), + ); + // If the body contains a key called "embedding" or "embeddings", return the value, otherwise return the whole body + if (responseBody.embedding) { + return responseBody.embedding; + } else if (responseBody.embeddings) { + return responseBody.embeddings; + } else { + return responseBody; + } + } + }), + ) + ).flat(); + } + private _generateInvokeModelCommandInput( + prompts: string | string[], + options: EmbedOptions, + ): any { + const payload = { + inputs: prompts, + normalize: true, + // ...(options.requestOptions?.extraBodyProperties || {}), + }; + + if (options.requestOptions?.extraBodyProperties) { + Object.assign(payload, options.requestOptions.extraBodyProperties); + } + + return { + EndpointName: this.options.model, + Body: JSON.stringify(payload), + ContentType: "application/json", + CustomAttributes: "accept_eula=false", + }; + } + + private async _getCredentials() { + try { + return await fromIni({ + profile: this.profile, + ignoreCache: true, + })(); + } catch (e) { + console.warn( + `AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`, + ); + return await fromIni()(); + } + } +} + +export default SageMakerEmbeddingsProvider; 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/WatsonxEmbeddingsProvider.ts b/core/indexing/embeddings/WatsonxEmbeddingsProvider.ts new file mode 100644 index 000000000..1c352697a --- /dev/null +++ b/core/indexing/embeddings/WatsonxEmbeddingsProvider.ts @@ -0,0 +1,150 @@ +import { + EmbeddingsProviderName, + EmbedOptions, + FetchFunction, +} from "../../index.js"; +import { withExponentialBackoff } from "../../util/withExponentialBackoff.js"; +import BaseEmbeddingsProvider, { + IBaseEmbeddingsProvider, +} from "./BaseEmbeddingsProvider.js"; + +let accessToken = { + expiration: 0, + token: "", +}; + + +class WatsonxEmbeddingsProvider extends BaseEmbeddingsProvider { + static providerName: EmbeddingsProviderName = "watsonx"; + static maxBatchSize = 1000; + static defaultOptions: Partial | undefined = { + model: "ibm/slate-125m-english-rtrvr-v2", + }; + + async getBearerToken(): Promise<{ token: string; expiration: number }> { + if ( + this.options.apiBase?.includes("cloud.ibm.com") + ) { + // watsonx SaaS + const wxToken = await ( + await fetch( + `https://iam.cloud.ibm.com/identity/token?apikey=${this.options.apiKey}&grant_type=urn:ibm:params:oauth:grant-type:apikey`, + { + method: "POST", + headers: { + "Content-Type": "application/x-www-form-urlencoded", + Accept: "application/json", + }, + }, + ) + ).json(); + return { + token: wxToken["access_token"], + expiration: wxToken["expiration"], + }; + } else { + // watsonx Software + if (!this.options.apiKey?.includes(":")) { + // Using ZenApiKey auth + return { + token: this.options.apiKey ?? "", + expiration: -1, + }; + } else { + // Using username/password auth + const userPass = this.options.apiKey?.split(":"); + const wxToken = await ( + await fetch(`${this.options.apiBase}/icp4d-api/v1/authorize`, { + method: "POST", + headers: { + "Content-Type": "application/json", + Accept: "application/json", + }, + body: JSON.stringify({ + username: userPass[0], + password: userPass[1], + }), + }) + ).json(); + const wxTokenExpiry = await ( + await fetch( + `${this.options.apiBase}/usermgmt/v1/user/tokenExpiry`, + { + method: "GET", + headers: { + Accept: "application/json", + Authorization: `Bearer ${wxToken["token"]}`, + }, + }, + ) + ).json(); + return { + token: wxToken["token"], + expiration: wxTokenExpiry["exp"], + }; + } + } + } + async getSingleBatchEmbedding(batch: string[]) { + var now = new Date().getTime() / 1000; + if ( + accessToken === undefined || + now > accessToken.expiration || + accessToken.token === undefined + ) { + accessToken = await this.getBearerToken(); + } else { + console.log( + `Reusing token (expires in ${(accessToken.expiration - now) / 60 + } mins)`, + ); + } + return await withExponentialBackoff(async () => { + const payload: any = { + inputs: batch, + parameters: { + truncate_input_tokens: 500, + return_options: { input_text: false }, + }, + model_id: this.options.model, + project_id: this.options.projectId, + }; + const headers = { + "Content-Type": "application/json", + Authorization: `${accessToken.expiration === -1 ? "ZenApiKey" : "Bearer" + } ${accessToken.token}`, + }; + const resp = await this.fetch( + new URL( + `${this.options.apiBase}/ml/v1/text/embeddings?version=${this.options.apiVersion}`, + ), + { + method: "POST", + body: JSON.stringify(payload), + headers: headers, + }, + ); + + if (!resp.ok) { + throw new Error(`Failed to embed chunk: ${await resp.text()}`); + } + const data = await resp.json(); + const embeddings = data.results; + + if (!embeddings || embeddings.length === 0) { + throw new Error("Watsonx generated empty embedding"); + } + return embeddings.map((e: any) => e.embedding); + }); + } + + async embed(chunks: string[]) { + const batchedChunks = this.getBatchedChunks(chunks); + const results = await Promise.all( + batchedChunks.map((batch) => this.getSingleBatchEmbedding(batch)), + ); + return results.flat(); + } +} + +export default WatsonxEmbeddingsProvider; diff --git a/core/indexing/embeddings/index.ts b/core/indexing/embeddings/index.ts index fe9309f73..c288ec9aa 100644 --- a/core/indexing/embeddings/index.ts +++ b/core/indexing/embeddings/index.ts @@ -15,6 +15,7 @@ import TransformersJsEmbeddingsProvider from "./TransformersJsEmbeddingsProvider import NvidiaEmbeddingsProvider from "./NvidiaEmbeddingsProvider.js"; import VoyageEmbeddingsProvider from "./VoyageEmbeddingsProvider.js"; import VertexEmbeddingsProvider from "./VertexEmbeddingsProvider.js"; +import WatsonxEmbeddingsProvider from "./WatsonxEmbeddingsProvider.js"; type EmbeddingsProviderConstructor = new ( ...args: any[] @@ -38,5 +39,6 @@ export const allEmbeddingsProviders: Record< nvidia: NvidiaEmbeddingsProvider, voyage: VoyageEmbeddingsProvider, mistral: MistralEmbeddingsProvider, - vertex: VertexEmbeddingsProvider + vertexai: VertexEmbeddingsProvider, + watsonx: WatsonxEmbeddingsProvider }; diff --git a/core/indexing/ignore.ts b/core/indexing/ignore.ts index 0b2714f1d..06b8cac51 100644 --- a/core/indexing/ignore.ts +++ b/core/indexing/ignore.ts @@ -1,4 +1,7 @@ import ignore from "ignore"; +import path from "path"; +import os from "os"; +import fs from "fs"; export const DEFAULT_IGNORE_FILETYPES = [ "*.DS_Store", @@ -114,3 +117,18 @@ export function gitIgArrayFromFile(file: string) { .map((l) => l.trim()) // Remove whitespace .filter((l) => !/^#|^$/.test(l)); // Remove empty lines } + +export const GLOBAL_CONTINUEIGNORE_PATH = path.join(os.homedir(), ".continue", ".continueignore"); + +export const getGlobalContinueIgArray = () => { + try { + const contents = fs.readFileSync(GLOBAL_CONTINUEIGNORE_PATH, "utf8"); + return gitIgArrayFromFile(contents); + } catch (error) { + // If the file doesn't exist, that's okay + if (error instanceof Error && ("code" in error) && error.code === "ENOENT") { + return []; + } + throw error; + } +}; \ No newline at end of file diff --git a/core/indexing/refreshIndex.test.ts b/core/indexing/refreshIndex.test.ts new file mode 100644 index 000000000..7eeb2c5d8 --- /dev/null +++ b/core/indexing/refreshIndex.test.ts @@ -0,0 +1,34 @@ +import { truncateToLastNBytes } from "./refreshIndex"; + +describe("truncateToLastNBytes", () => { + it("should return full string if maxBytes greater than string byte length", () => { + const input = "Hello World"; + const result = truncateToLastNBytes(input, 100); + expect(result).toBe("Hello World"); + }); + + it("should truncate ASCII string correctly", () => { + const input = "Hello World"; + const result = truncateToLastNBytes(input, 5); + expect(result).toBe("World"); + }); + + it("should handle empty string", () => { + const input = ""; + const result = truncateToLastNBytes(input, 5); + expect(result).toBe(""); + }); + + it("should handle UTF-8 characters correctly", () => { + const input = "👋 Hello"; + // 👋 is 4 bytes, space is 1 byte + const result = truncateToLastNBytes(input, 5); + expect(result).toBe("Hello"); + }); + + it("should handle maxBytes of 0", () => { + const input = "Hello World"; + const result = truncateToLastNBytes(input, 0); + expect(result).toBe(""); + }); +}); diff --git a/core/indexing/refreshIndex.ts b/core/indexing/refreshIndex.ts index 51cbdb646..ba2dbd820 100644 --- a/core/indexing/refreshIndex.ts +++ b/core/indexing/refreshIndex.ts @@ -416,11 +416,9 @@ export async function getComputeDeleteAddRemove( export class GlobalCacheCodeBaseIndex implements CodebaseIndex { relativeExpectedTime: number = 1; - private db: DatabaseConnection; - constructor(db: DatabaseConnection) { - this.db = db; - } + constructor(private db: DatabaseConnection) {} + artifactId = "globalCache"; static async create(): Promise { @@ -471,3 +469,24 @@ export class GlobalCacheCodeBaseIndex implements CodebaseIndex { ); } } + +const SQLITE_MAX_LIKE_PATTERN_LENGTH = 50000; + +export function truncateToLastNBytes(input: string, maxBytes: number): string { + let bytes = 0; + let startIndex = 0; + + for (let i = input.length - 1; i >= 0; i--) { + bytes += new TextEncoder().encode(input[i]).length; + if (bytes > maxBytes) { + startIndex = i + 1; + break; + } + } + + return input.substring(startIndex, input.length); +} + +export function truncateSqliteLikePattern(input: string) { + return truncateToLastNBytes(input, SQLITE_MAX_LIKE_PATTERN_LENGTH); +} diff --git a/core/indexing/walkDir.ts b/core/indexing/walkDir.ts index eeeb064d0..44f785ab4 100644 --- a/core/indexing/walkDir.ts +++ b/core/indexing/walkDir.ts @@ -6,6 +6,7 @@ import { DEFAULT_IGNORE_FILETYPES, defaultIgnoreDir, defaultIgnoreFile, + getGlobalContinueIgArray, gitIgArrayFromFile, } from "./ignore.js"; @@ -38,15 +39,13 @@ type IgnoreContext = { }; class DFSWalker { - private readonly path: string; - private readonly ide: IDE; - private readonly options: WalkerOptions; private readonly ignoreFileNames: Set; - constructor(path: string, ide: IDE, options: WalkerOptions) { - this.path = path; - this.ide = ide; - this.options = options; + constructor( + private readonly path: string, + private readonly ide: IDE, + private readonly options: WalkerOptions, + ) { this.ignoreFileNames = new Set(options.ignoreFiles); } @@ -85,6 +84,7 @@ class DFSWalker { } private newRootWalkContext(): WalkContext { + const globalIgnoreFile = getGlobalContinueIgArray(); return { walkableEntry: { relPath: "", @@ -94,7 +94,7 @@ class DFSWalker { }, ignoreContexts: [ { - ignore: ignore().add(defaultIgnoreDir).add(defaultIgnoreFile), + ignore: ignore().add(defaultIgnoreDir).add(defaultIgnoreFile).add(globalIgnoreFile), dirname: "", }, ], @@ -128,10 +128,7 @@ class DFSWalker { ignore: ignore().add(patterns), dirname: curDir.walkableEntry.relPath, }; - return [ - ...curDir.ignoreContexts, - newIgnoreContext - ]; + return [...curDir.ignoreContexts, newIgnoreContext]; } private async loadIgnoreFiles(entries: WalkableEntry[]): Promise { @@ -147,7 +144,10 @@ class DFSWalker { return this.ignoreFileNames.has(p); } - private shouldInclude(walkableEntry: WalkableEntry, ignoreContexts: IgnoreContext[]) { + private shouldInclude( + walkableEntry: WalkableEntry, + ignoreContexts: IgnoreContext[], + ) { if (this.entryIsSymlink(walkableEntry.entry)) { // If called from the root, a symlink either links to a real file in this repository, // and therefore will be walked OR it linksto something outside of the repository and diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index 369421406..ae58ed6fe 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -5,6 +5,7 @@ import { codeLlama70bTemplateMessages, deepseekTemplateMessages, gemmaTemplateMessage, + graniteTemplateMessages, llama2TemplateMessages, llama3TemplateMessages, llavaTemplateMessages, @@ -41,28 +42,27 @@ const PROVIDER_HANDLES_TEMPLATING: ModelProvider[] = [ "together", "msty", "anthropic", - "anthropic-vertexai", "bedrock", "sagemaker", "continue-proxy", "mistral", - "mistral-vertexai", "sambanova", + "vertexai", + "watsonx" ]; 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[] = [ @@ -79,6 +79,7 @@ const MODEL_SUPPORTS_IMAGES: string[] = [ "opus", "haiku", "pixtral", + "llama3.2", ]; function modelSupportsImages( @@ -107,20 +108,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( @@ -220,6 +219,10 @@ function autodetectTemplateType(model: string): TemplateType | undefined { return "neural-chat"; } + if (lower.includes("granite")) { + return "granite"; + } + return "chatml"; } @@ -253,6 +256,7 @@ function autodetectTemplateFunction( llava: llavaTemplateMessages, "codellama-70b": codeLlama70bTemplateMessages, gemma: gemmaTemplateMessage, + granite: graniteTemplateMessages, llama3: llama3TemplateMessages, none: null, }; diff --git a/core/llm/index.ts b/core/llm/index.ts index 53c984b43..e7f9de970 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -114,13 +114,8 @@ export abstract class BaseLLM implements ILLM { accountId?: string; aiGatewaySlug?: string; - // For IBM watsonx only. - watsonxUrl?: string; - watsonxCreds?: string; - watsonxProjectId?: string; - watsonxStopToken?: string; - watsonxApiVersion?: string; - watsonxFullUrl?: string; + // For IBM watsonx + deploymentId?: string; private _llmOptions: LLMOptions; @@ -186,13 +181,8 @@ export abstract class BaseLLM implements ILLM { this.apiBase = options.apiBase; this.cacheBehavior = options.cacheBehavior; - // for watsonx only - this.watsonxUrl = options.watsonxUrl; - this.watsonxCreds = options.watsonxCreds; - this.watsonxProjectId = options.watsonxProjectId; - this.watsonxStopToken = options.watsonxStopToken; - this.watsonxApiVersion = options.watsonxApiVersion; - this.watsonxFullUrl = options.watsonxFullUrl; + // watsonx deploymentId + this.deploymentId = options.deploymentId; if (this.apiBase && !this.apiBase.endsWith("/")) { this.apiBase = `${this.apiBase}/`; 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/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/Asksage.ts b/core/llm/llms/Asksage.ts new file mode 100644 index 000000000..85fb19184 --- /dev/null +++ b/core/llm/llms/Asksage.ts @@ -0,0 +1,168 @@ +import { + ChatMessage, + CompletionOptions, + LLMOptions, + ModelProvider, +} from "../../index.js"; +import { BaseLLM } from "../index.js"; + +class Asksage extends BaseLLM { + static providerName: ModelProvider = "askSage"; + static defaultOptions: Partial = { + apiBase: "https://api.asksage.ai/server/", + model: "gpt-4o", + }; + + private static modelConversion: { [key: string]: string } = { + "gpt-4o": "gpt-4o", + "gpt-4o-mini": "gpt-4o-mini", + "gpt4-gov": "gpt4-gov", + "gpt-4o-gov": "gpt-4o-gov", + "gpt-3.5-turbo": "gpt35-16k", + "mistral-large-latest": "mistral-large", + "llama3-70b": "llma3", + "gemini-1.5-pro-latest": "google-gemini-pro", + "claude-3-5-sonnet-20240620": "claude-35-sonnet", + "claude-3-opus-20240229": "claude-3-opus", + "claude-3-sonnet-20240229": "claude-3-sonnet", + }; + + constructor(options: LLMOptions) { + super(options); + this.apiVersion = options.apiVersion ?? "v1.2.4"; + } + + protected _convertModelName(model: string): string { + return Asksage.modelConversion[model] ?? model; + } + + protected _convertMessage(message: ChatMessage) { + return { + user: message.role === "assistant" ? "gpt" : "me", + message: + typeof message.content === "string" + ? message.content + : message.content.map((part) => part.text).join(""), + }; + } + + protected _convertArgs(options: any, messages: ChatMessage[]) { + let formattedMessage: any; + if (messages.length === 1) { + formattedMessage = messages[0].content; + } else { + formattedMessage = messages.map(this._convertMessage); + } + + const args: any = { + message: formattedMessage, + persona: options.persona ?? "default", + dataset: options.dataset ?? "none", + limit_references: options.limitReferences ?? 0, + temperature: options.temperature ?? 0.0, + live: options.live ?? 0, + model: this._convertModelName(options.model), + system_prompt: options.systemPrompt ?? "You are an expert software developer. You give helpful and concise responses.", + tools: options.tools, + tool_choice: options.toolChoice, + }; + + Object.keys(args).forEach( + (key) => args[key] === undefined && delete args[key] + ); + + return args; + } + + protected _getHeaders() { + const headers: Record = { + "Content-Type": "application/json", + }; + + if (this.apiKey) { + headers["x-access-tokens"] = this.apiKey; + } + + return headers; + } + + protected _getEndpoint(endpoint: string) { + if (!this.apiBase) { + throw new Error( + "No API base URL provided. Please set the 'apiBase' option." + ); + } + + return new URL(endpoint, this.apiBase); + } + + protected async _complete( + prompt: string, + options: CompletionOptions + ): Promise { + if (typeof prompt !== "string" || prompt.trim() === "") { + throw new Error("Prompt must be a non-empty string."); + } + + const messages: ChatMessage[] = [{ role: "user", content: prompt }]; + + const args = this._convertArgs(options, messages); + + const response = await this.fetch(this._getEndpoint("query"), { + method: "POST", + headers: this._getHeaders(), + body: JSON.stringify(args), + }); + + if (!response.ok) { + throw new Error( + `API request failed with status ${response.status}: ${response.statusText}` + ); + } + + const data = await response.json(); + return data.message; + } + + protected async *_streamComplete( + prompt: string, + options: CompletionOptions + ): AsyncGenerator { + const completion = await this._complete(prompt, options); + yield completion; + } + + protected async *_streamChat( + messages: ChatMessage[], + options: CompletionOptions + ): AsyncGenerator { + const args = this._convertArgs(options, messages); + + const response = await this.fetch(this._getEndpoint("query"), { + method: "POST", + headers: this._getHeaders(), + body: JSON.stringify(args), + }); + + if (!response.ok) { + throw new Error( + `API request failed with status ${response.status}: ${response.statusText}` + ); + } + + const data = await response.json(); + + const assistantMessage: ChatMessage = { + role: "assistant", + content: data.message, + }; + + yield assistantMessage; + } + + async listModels(): Promise { + return Object.keys(Asksage.modelConversion); + } +} + +export default Asksage; \ No newline at end of file diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 485b87015..c143fa412 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -111,7 +111,15 @@ class Bedrock extends BaseLLM { maxTokens: options.maxTokens, temperature: options.temperature, topP: options.topP, - stopSequences: options.stop?.filter((stop) => stop.trim() !== ""), + // TODO: The current approach selects the first 4 items from the list to comply with Bedrock's requirement + // of having at most 4 stop sequences, as per the AWS documentation: + // https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_InferenceConfiguration.html + // However, it might be better to implement a strategy that dynamically selects the most appropriate stop sequences + // based on the context. + // TODO: Additionally, consider implementing a global exception handler for the providers to give users clearer feedback. + // For example, differentiate between client-side errors (4XX status codes) and server-side issues (5XX status codes), + // providing meaningful error messages to improve the user experience. + stopSequences: options.stop?.filter((stop) => stop.trim() !== "").slice(0, 4), }, }; } diff --git a/core/llm/llms/DeepInfra.ts b/core/llm/llms/DeepInfra.ts index 6b33a4bdc..592d28009 100644 --- a/core/llm/llms/DeepInfra.ts +++ b/core/llm/llms/DeepInfra.ts @@ -6,6 +6,7 @@ class DeepInfra extends OpenAI { static defaultOptions: Partial = { apiBase: "https://api.deepinfra.com/v1/openai/", }; + maxStopWords: number | undefined = 16; } export default DeepInfra; diff --git a/core/llm/llms/Gemini.ts b/core/llm/llms/Gemini.ts index 4bfed0420..2e33968d5 100644 --- a/core/llm/llms/Gemini.ts +++ b/core/llm/llms/Gemini.ts @@ -15,10 +15,11 @@ class Gemini extends BaseLLM { static defaultOptions: Partial = { model: "gemini-pro", apiBase: "https://generativelanguage.googleapis.com/v1beta/", + maxStopWords: 5, }; // 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 @@ -35,7 +36,9 @@ class Gemini extends BaseLLM { finalOptions.maxOutputTokens = options.maxTokens; } if (options.stop) { - finalOptions.stopSequences = options.stop.filter((x) => x.trim() !== ""); + finalOptions.stopSequences = options.stop + .filter((x) => x.trim() !== "") + .slice(0, this.maxStopWords ?? Gemini.defaultOptions.maxStopWords); } return { generationConfig: finalOptions }; // Wrap options under 'generationConfig' @@ -53,7 +56,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 +103,7 @@ class Gemini extends BaseLLM { } } - private _continuePartToGeminiPart(part: MessagePart) { + continuePartToGeminiPart(part: MessagePart) { return part.type === "text" ? { text: part.text, @@ -139,13 +142,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/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/Groq.ts b/core/llm/llms/Groq.ts index bc05263c9..b69e2c020 100644 --- a/core/llm/llms/Groq.ts +++ b/core/llm/llms/Groq.ts @@ -18,6 +18,10 @@ class Groq extends OpenAI { "llama3.1-8b": "llama-3.1-8b-instant", "llama3.1-70b": "llama-3.1-70b-versatile", "llama3.1-405b": "llama-3.1-405b-reasoning", + "llama3.2-1b": "llama-3.2-1b-preview", + "llama3.2-3b": "llama-3.2-3b-preview", + "llama3.2-11b": "llama-3.2-11b-vision-preview", + "llama3.2-90b": "llama-3.2-90b-vision-preview", }; protected _convertModelName(model: string): string { return Groq.modelConversion[model] ?? model; 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/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/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index 75e973219..604c382b6 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -8,6 +8,59 @@ import { stripImages } from "../images.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; +interface OllamaChatMessage extends ChatMessage { + images?: string[]; +} + +// See https://github.com/ollama/ollama/blob/main/docs/modelfile.md for details on each parameter +interface ModelFileParams { + mirostat?: number; + mirostat_eta?: number; + mirostat_tau?: number; + num_ctx?: number; + repeat_last_n?: number; + repeat_penalty?: number; + temperature?: number; + seed?: number; + stop?: string | string[]; + tfs_z?: number; + num_predict?: number; + top_k?: number; + top_p?: number; + min_p?: number; + // deprecated? + num_thread?: number; + num_gqa?: number; + num_gpu?: number; +} + +// See https://github.com/ollama/ollama/blob/main/docs/api.md +interface BaseOptions { + model: string; // the model name + options?: ModelFileParams; // additional model parameters listed in the documentation for the Modelfile such as temperature + format?: "json"; // the format to return a response in. Currently, the only accepted value is json + stream?: boolean; // if false the response will be returned as a single response object, rather than a stream of objects + keep_alive?: number; // controls how long the model will stay loaded into memory following the request (default: 5m) +} + +interface GenerateOptions extends BaseOptions { + prompt: string; // the prompt to generate a response for + suffix?: string; // the text after the model response + images?: string[]; // a list of base64-encoded images (for multimodal models such as llava) + system?: string; // system message to (overrides what is defined in the Modelfile) + template?: string; // the prompt template to use (overrides what is defined in the Modelfile) + context?: string; // the context parameter returned from a previous request to /generate, this can be used to keep a short conversational memory + raw?: boolean; // if true no formatting will be applied to the prompt. You may choose to use the raw parameter if you are specifying a full templated prompt in your request to the API +} + +interface ChatOptions extends BaseOptions { + messages: OllamaChatMessage[]; // the messages of the chat, this can be used to keep a chat memory + // Not supported yet - tools: tools for the model to use if supported. Requires stream to be set to false + // And correspondingly, tool calls in OllamaChatMessage +} + + + class Ollama extends BaseLLM { static providerName: ModelProvider = "ollama"; static defaultOptions: Partial = { @@ -63,7 +116,7 @@ class Ollama extends BaseLLM { this.completionOptions.stop.push(JSON.parse(value)); } catch (e) { console.warn( - 'Error parsing stop parameter value "{value}: ${e}', + `Error parsing stop parameter value "{value}: ${e}`, ); } break; @@ -101,6 +154,10 @@ class Ollama extends BaseLLM { "llama3.1-8b": "llama3.1:8b", "llama3.1-70b": "llama3.1:70b", "llama3.1-405b": "llama3.1:405b", + "llama3.2-1b": "llama3.2:1b", + "llama3.2-3b": "llama3.2:3b", + "llama3.2-11b": "llama3.2:11b", + "llama3.2-90b": "llama3.2:90b", "phi-2": "phi:2.7b", "phind-codellama-34b": "phind-codellama:34b-v2", "wizardcoder-7b": "wizardcoder:7b-python", @@ -124,49 +181,73 @@ class Ollama extends BaseLLM { ); } - private _convertMessage(message: ChatMessage) { + private _getModelFileParams(options: CompletionOptions): ModelFileParams { + return { + temperature: options.temperature, + top_p: options.topP, + top_k: options.topK, + num_predict: options.maxTokens, + stop: options.stop, + num_ctx: this.contextLength, + mirostat: options.mirostat, + num_thread: options.numThreads, + min_p: options.minP, + }; + } + + private _convertMessage( + message: ChatMessage + ) { if (typeof message.content === "string") { return message; } + const images: string[] = []; + message.content.forEach((part) => { + if (part.type === "imageUrl" && part.imageUrl) { + const image = part.imageUrl?.url.split(",").at(-1); + if (image) { + images.push(image); + } + } + }); return { role: message.role, content: stripImages(message.content), - images: message.content - .filter((part) => part.type === "imageUrl") - .map((part) => part.imageUrl?.url.split(",").at(-1)), + images }; } - private _convertArgs( + private _getChatOptions( options: CompletionOptions, - prompt: string | ChatMessage[], - suffix?: string, - ) { - const finalOptions: any = { + messages: ChatMessage[] + ): ChatOptions { + return { model: this._getModel(), - raw: true, + messages: messages.map(this._convertMessage), + options: this._getModelFileParams(options), keep_alive: options.keepAlive ?? 60 * 30, // 30 minutes - suffix, - options: { - temperature: options.temperature, - top_p: options.topP, - top_k: options.topK, - num_predict: options.maxTokens, - stop: options.stop, - num_ctx: this.contextLength, - mirostat: options.mirostat, - num_thread: options.numThreads, - }, + stream: options.stream, + format: "json", }; + } - if (typeof prompt === "string") { - finalOptions.prompt = prompt; - } else { - finalOptions.messages = prompt.map(this._convertMessage); - } - - return finalOptions; + private _getGenerateOptions( + options: CompletionOptions, + prompt: string, + suffix?: string + ): GenerateOptions { + return { + model: this._getModel(), + prompt, + suffix, + raw: options.raw, + options: this._getModelFileParams(options), + keep_alive: options.keepAlive ?? 60 * 30, // 30 minutes + stream: options.stream, + format: "json" + // Not supported yet: context, images, system, template + }; } private getEndpoint(endpoint: string): URL { @@ -188,7 +269,7 @@ class Ollama extends BaseLLM { "Content-Type": "application/json", Authorization: `Bearer ${this.apiKey}`, }, - body: JSON.stringify(this._convertArgs(options, prompt)), + body: JSON.stringify(this._getGenerateOptions(options, prompt)), }); let buffer = ""; @@ -227,7 +308,7 @@ class Ollama extends BaseLLM { "Content-Type": "application/json", Authorization: `Bearer ${this.apiKey}`, }, - body: JSON.stringify(this._convertArgs(options, messages)), + body: JSON.stringify(this._getChatOptions(options, messages)), }); let buffer = ""; @@ -274,7 +355,7 @@ class Ollama extends BaseLLM { "Content-Type": "application/json", Authorization: `Bearer ${this.apiKey}`, }, - body: JSON.stringify(this._convertArgs(options, prefix, suffix)), + body: JSON.stringify(this._getGenerateOptions(options, prefix, suffix)), }); let buffer = ""; diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 0e2ab2ab7..82af7793f 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -37,6 +37,8 @@ const CHAT_ONLY_MODELS = [ "gpt-4-0125-preview", "gpt-4-1106-preview", "gpt-4o-mini", + "o1-preview", + "o1-mini", ]; class OpenAI extends BaseLLM { @@ -111,9 +113,9 @@ class OpenAI extends BaseLLM { : url.host === "api.deepseek.com" ? options.stop?.slice(0, 16) : url.port === "1337" || - url.host === "api.openai.com" || - url.host === "api.groq.com" || - this.apiType === "azure" + url.host === "api.openai.com" || + url.host === "api.groq.com" || + this.apiType === "azure" ? options.stop?.slice(0, 4) : options.stop, }; diff --git a/core/llm/llms/SageMaker.ts b/core/llm/llms/SageMaker.ts index 03b9a5b22..d5e9039de 100644 --- a/core/llm/llms/SageMaker.ts +++ b/core/llm/llms/SageMaker.ts @@ -59,10 +59,10 @@ class SageMaker extends BaseLLM { const data = JSON.parse(line.replace(/^data:/, '')); let text = undefined; if ("choices" in data) { - if ("delta" in data.choices[0]){ + if ("delta" in data.choices[0]) { text = data.choices[0].delta.content; } - else{ + else { text = data.choices[0].text; } } @@ -110,10 +110,10 @@ class SageMaker extends BaseLLM { const data = JSON.parse(line.replace(/^data:/, '')); let text = undefined; if ("choices" in data) { - if ("delta" in data.choices[0]){ + if ("delta" in data.choices[0]) { text = data.choices[0].delta.content; } - else{ + else { text = data.choices[0].text; } } diff --git a/core/llm/llms/SambaNova.ts b/core/llm/llms/SambaNova.ts index 2b409dcde..39a216681 100644 --- a/core/llm/llms/SambaNova.ts +++ b/core/llm/llms/SambaNova.ts @@ -12,6 +12,8 @@ class SambaNova extends OpenAI { "llama3.1-8b": "Meta-Llama-3.1-8B-Instruct", "llama3.1-70b": "Meta-Llama-3.1-70B-Instruct", "llama3.1-405b": "Meta-Llama-3.1-405B-Instruct", + "llama3.1-1b": "Meta-Llama-3.2-1B-Instruct", + "llama3.1-3b": "Meta-Llama-3.2-3B-Instruct", }; protected _convertModelName(model: string) { diff --git a/core/llm/llms/Together.ts b/core/llm/llms/Together.ts index eaa144277..862226394 100644 --- a/core/llm/llms/Together.ts +++ b/core/llm/llms/Together.ts @@ -22,6 +22,9 @@ class Together extends OpenAI { "llama3.1-8b": "meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo", "llama3.1-70b": "meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo", "llama3.1-405b": "meta-llama/Meta-Llama-3.1-405B-Instruct-Turbo", + "llama3.2-3b": "meta-llama/Llama-3.2-3B-Instruct-Turbo", + "llama3.2-11b": "meta-llama/Llama-3.2-11B-Vision-Instruct-Turbo", + "llama3.2-90b": "meta-llama/Llama-3.2-90B-Vision-Instruct-Turbo", "llama2-7b": "togethercomputer/llama-2-7b-chat", "llama2-13b": "togethercomputer/llama-2-13b-chat", "llama2-70b": "togethercomputer/llama-2-70b-chat", diff --git a/core/llm/llms/VertexAI.ts b/core/llm/llms/VertexAI.ts index 772b30ea7..e3435b6ae 100644 --- a/core/llm/llms/VertexAI.ts +++ b/core/llm/llms/VertexAI.ts @@ -1,9 +1,24 @@ import { GoogleAuth } from "google-auth-library"; -import { LLMOptions } from "../../index.js"; import { BaseLLM } from "../index.js"; +import { stripImages } from "../images.js"; +import { streamSse } from "../stream.js"; +import { + ChatMessage, + CompletionOptions, + LLMOptions, + MessagePart, + ModelProvider, +} from "../../index.js"; +import { streamResponse } from "../stream.js"; +import Anthropic from "./Anthropic.js"; +import Gemini from "./Gemini.js"; -abstract class VertexAI extends BaseLLM { +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", @@ -22,6 +37,17 @@ 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"; + this.anthropicInstance = new Anthropic(_options); + this.geminiInstance = new Gemini(_options) + } async fetch(url: RequestInfo | URL, init?: RequestInit) { @@ -41,6 +67,373 @@ abstract class VertexAI extends BaseLLM { }, }); } + + // Anthropic functions + private _anthropicConvertArgs(options: CompletionOptions) { + 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", + }; + } + + + 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.anthropicInstance.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 }; + } + } + } + + + //Gemini + + 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.geminiInstance.continuePartToGeminiPart), + }; + }) + .filter((c) => c !== null); + + const body = { + ...this.geminiInstance.convertArgs(options), + contents, + // if this.systemMessage is defined, reformat it for Gemini API + ...(this.systemMessage && + !isV1API && { + systemInstruction: { parts: [{ text: this.systemMessage }] }, + }), + }; + const 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)) { + if (chunk.choices?.[0]) { + // At the end vertexai will return a empty chunk. + 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, + ): 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; + } + + //Manager functions + + protected async *_streamChat( + messages: ChatMessage[], + options: CompletionOptions, + ): AsyncGenerator { + const isV1API = this.apiBase.includes("/v1/"); + + // Conditionally apply removeSystemMessage + const convertedMsgs = isV1API + ? this.geminiInstance.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/WatsonX.ts b/core/llm/llms/WatsonX.ts index 822e95cb5..94a7b66fa 100644 --- a/core/llm/llms/WatsonX.ts +++ b/core/llm/llms/WatsonX.ts @@ -7,26 +7,26 @@ import { import { stripImages } from "../images.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; -const watsonxConfig = { - accessToken: { - expiration: 0, - token: "", - }, -}; + +let watsonxToken = { + expiration: 0, + token: "" +} + class WatsonX extends BaseLLM { constructor(options: LLMOptions) { super(options); } + async getBearerToken(): Promise<{ token: string; expiration: number }> { if ( - this.watsonxFullUrl?.includes("cloud.ibm.com") || - this.watsonxUrl?.includes("cloud.ibm.com") + this.apiBase?.includes("cloud.ibm.com") ) { // watsonx SaaS const wxToken = await ( await fetch( - `https://iam.cloud.ibm.com/identity/token?apikey=${this.watsonxCreds}&grant_type=urn:ibm:params:oauth:grant-type:apikey`, + `https://iam.cloud.ibm.com/identity/token?apikey=${this.apiKey}&grant_type=urn:ibm:params:oauth:grant-type:apikey`, { method: "POST", headers: { @@ -42,17 +42,17 @@ class WatsonX extends BaseLLM { }; } else { // watsonx Software - if (!this.watsonxCreds?.includes(":")) { + if (!this.apiKey?.includes(":")) { // Using ZenApiKey auth return { - token: this.watsonxCreds ?? "", + token: this.apiKey ?? "", expiration: -1, }; } else { // Using username/password auth - const userPass = this.watsonxCreds?.split(":"); + const userPass = this.apiKey?.split(":"); const wxToken = await ( - await fetch(`${this.watsonxUrl}/icp4d-api/v1/authorize`, { + await fetch(`${this.apiBase}/icp4d-api/v1/authorize`, { method: "POST", headers: { "Content-Type": "application/json", @@ -65,7 +65,7 @@ class WatsonX extends BaseLLM { }) ).json(); const wxTokenExpiry = await ( - await fetch(`${this.watsonxUrl}/usermgmt/v1/user/tokenExpiry`, { + await fetch(`${this.apiBase}/usermgmt/v1/user/tokenExpiry`, { method: "GET", headers: { Accept: "application/json", @@ -83,8 +83,9 @@ class WatsonX extends BaseLLM { getWatsonxEndpoint(): string { return ( - this.watsonxFullUrl ?? - `${this.watsonxUrl}/ml/v1/text/generation_stream?version=${this.watsonxApiVersion}` + this.deploymentId ? + `${this.apiBase}/ml/v1/deployments/${this.deploymentId}/text/generation_stream?version=${this.apiVersion}`: + `${this.apiBase}/ml/v1/text/generation_stream?version=${this.apiVersion}` ); } @@ -132,8 +133,8 @@ class WatsonX extends BaseLLM { protected _getHeaders() { return { "Content-Type": "application/json", - Authorization: `${watsonxConfig.accessToken.expiration === -1 ? "ZenApiKey" : "Bearer" - } ${watsonxConfig.accessToken.token}`, + Authorization: `${watsonxToken.expiration === -1 ? "ZenApiKey" : "Bearer" + } ${watsonxToken.token}`, }; } @@ -170,24 +171,22 @@ class WatsonX extends BaseLLM { ): AsyncGenerator { var now = new Date().getTime() / 1000; if ( - watsonxConfig.accessToken === undefined || - now > watsonxConfig.accessToken.expiration || - watsonxConfig.accessToken.token === undefined + watsonxToken === undefined || + now > watsonxToken.expiration || + watsonxToken.token === undefined ) { - watsonxConfig.accessToken = await this.getBearerToken(); + watsonxToken = await this.getBearerToken(); } else { console.log( - `Reusing token (expires in ${(watsonxConfig.accessToken.expiration - now) / 60 + `Reusing token (expires in ${(watsonxToken.expiration - now) / 60 } mins)`, ); } - if (watsonxConfig.accessToken.token === undefined) { + if (watsonxToken.token === undefined) { throw new Error("Something went wrong. Check your credentials, please."); } - - const stopToken = - this.watsonxStopToken ?? - (options.model?.includes("granite") ? "<|im_end|>" : undefined); + const stopSequences = + options.stop?.slice(0,6) ?? (options.model?.includes("granite") ? ["Question:"] : []); const url = this.getWatsonxEndpoint(); const headers = this._getHeaders(); @@ -195,24 +194,25 @@ class WatsonX extends BaseLLM { decoding_method: "greedy", max_new_tokens: options.maxTokens ?? 1024, min_new_tokens: 1, - stop_sequences: stopToken ? [stopToken] : [], + stop_sequences: stopSequences, include_stop_sequence: false, - repetition_penalty: 1, + truncate_input_tokens: this.contextLength - (options.maxTokens ?? 1024), + repetition_penalty: options.frequencyPenalty || 1, }; if (!!options.temperature) { parameters.decoding_method = "sample"; parameters.temperature = options.temperature; parameters.top_p = options.topP || 1.0; - parameters.top_k = options.topK; + parameters.top_k = options.topK || 100; } const payload: any = { input: messages[messages.length - 1].content, parameters: parameters, }; - if (!this.watsonxFullUrl) { + if (!this.deploymentId) { payload.model_id = options.model; - payload.project_id = this.watsonxProjectId; + payload.project_id = this.projectId; } var response = await this.fetch(url, { @@ -245,7 +245,8 @@ class WatsonX extends BaseLLM { generatedChunk += result.generated_text || ""; }); } catch (e) { - console.error(`Error parsing JSON string: ${dataStr}`, e); + // parsing error is expected with streaming response + // console.error(`Error parsing JSON string: ${dataStr}`, e); } } }); diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index b504aa900..22fbd4c29 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,14 @@ import Together from "./Together"; import Vllm from "./Vllm"; import WatsonX from "./WatsonX"; import ContinueProxy from "./stubs/ContinueProxy"; +import VertexAI from "./VertexAI"; +import Asksage from "./Asksage"; const LLMs = [ Anthropic, - AnthropicVertexAI, Cohere, FreeTrial, Gemini, - GeminiVertexAI, Llamafile, Ollama, Replicate, @@ -65,7 +62,6 @@ const LLMs = [ OpenAI, LMStudio, Mistral, - MistralVertexAI, Bedrock, BedrockImport, SageMaker, @@ -85,6 +81,8 @@ const LLMs = [ SambaNova, Mock, Cerebras, + Asksage, + VertexAI ]; export async function llmFromDescription( diff --git a/core/llm/templates/chat.ts b/core/llm/templates/chat.ts index 17fae23cb..9d26620f4 100644 --- a/core/llm/templates/chat.ts +++ b/core/llm/templates/chat.ts @@ -274,12 +274,22 @@ const gemmaTemplateMessage = templateFactory( "\n", ); +const graniteTemplateMessages = templateFactory( + (msg) => (!!msg ? `\n\nSystem:\n ${msg.content}\n\n` : ""), + "Question:\n", + "Answer:\n", + "\n\n", + "", + "", +); + export { anthropicTemplateMessages, chatmlTemplateMessages, codeLlama70bTemplateMessages, deepseekTemplateMessages, gemmaTemplateMessage, + graniteTemplateMessages, llama2TemplateMessages, llama3TemplateMessages, llavaTemplateMessages, diff --git a/core/package-lock.json b/core/package-lock.json index 58eec1b51..9e3937c64 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -17,7 +17,6 @@ "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", "@typescript-eslint/eslint-plugin": "^7.8.0", - "@typescript-eslint/parser": "^7.8.0", "@xenova/transformers": "2.14.0", "adf-to-md": "^1.1.0", "async-mutex": "^0.5.0", @@ -89,7 +88,6 @@ "cross-env": "^7.0.3", "esbuild": "0.17.19", "eslint": "^8", - "eslint-plugin-import": "^2.29.1", "jest": "^29.7.0", "jest-environment-jsdom": "^29.7.0", "myers-diff": "^2.1.0", @@ -4969,7 +4967,8 @@ "node_modules/@types/json5": { "version": "0.0.29", "resolved": "https://registry.npmjs.org/@types/json5/-/json5-0.0.29.tgz", - "integrity": "sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==" + "integrity": "sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==", + "peer": true }, "node_modules/@types/long": { "version": "4.0.2", @@ -5224,6 +5223,7 @@ "version": "7.10.0", "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-7.10.0.tgz", "integrity": "sha512-2EjZMA0LUW5V5tGQiaa2Gys+nKdfrn2xiTIBLR4fxmPmVSvgPcKNW+AE/ln9k0A4zDUti0J/GZXMDupQoI+e1w==", + "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "7.10.0", "@typescript-eslint/types": "7.10.0", @@ -5645,6 +5645,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/array-buffer-byte-length/-/array-buffer-byte-length-1.0.1.tgz", "integrity": "sha512-ahC5W1xgou+KTXix4sAO8Ki12Q+jf4i0+tmk3sC+zgcynshkHxzpXdImBehiUYKKKDwvfFiJl1tZt6ewscS1Mg==", + "peer": true, "dependencies": { "call-bind": "^1.0.5", "is-array-buffer": "^3.0.4" @@ -5660,6 +5661,7 @@ "version": "3.1.8", "resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.1.8.tgz", "integrity": "sha512-itaWrbYbqpGXkGhZPGUulwnhVf5Hpy1xiCFsGqyIGglbBxmG5vSjxQen3/WGOjPpNEv1RtBLKxbmVXm8HpJStQ==", + "peer": true, "dependencies": { "call-bind": "^1.0.7", "define-properties": "^1.2.1", @@ -5692,6 +5694,7 @@ "version": "1.2.5", "resolved": "https://registry.npmjs.org/array.prototype.findlastindex/-/array.prototype.findlastindex-1.2.5.tgz", "integrity": "sha512-zfETvRFA8o7EiNn++N5f/kaCw221hrpGsDmcpndVupkPzEc1Wuf3VgC0qby1BbHs7f5DVYjgtEU2LLh5bqeGfQ==", + "peer": true, "dependencies": { "call-bind": "^1.0.7", "define-properties": "^1.2.1", @@ -5711,6 +5714,7 @@ "version": "1.3.2", "resolved": "https://registry.npmjs.org/array.prototype.flat/-/array.prototype.flat-1.3.2.tgz", "integrity": "sha512-djYB+Zx2vLewY8RWlNCUdHjDXs2XOgm602S9E7P/UpHgfeHL00cRiIF+IN/G/aUJ7kGPb6yO/ErDI5V2s8iycA==", + "peer": true, "dependencies": { "call-bind": "^1.0.2", "define-properties": "^1.2.0", @@ -5728,6 +5732,7 @@ "version": "1.3.2", "resolved": "https://registry.npmjs.org/array.prototype.flatmap/-/array.prototype.flatmap-1.3.2.tgz", "integrity": "sha512-Ewyx0c9PmpcsByhSW4r+9zDU7sGjFc86qf/kKtuSCRdhfbk0SNLLkaT5qvcHnRGgc5NP/ly/y+qkXkqONX54CQ==", + "peer": true, "dependencies": { "call-bind": "^1.0.2", "define-properties": "^1.2.0", @@ -5745,6 +5750,7 @@ "version": "1.0.3", "resolved": "https://registry.npmjs.org/arraybuffer.prototype.slice/-/arraybuffer.prototype.slice-1.0.3.tgz", "integrity": "sha512-bMxMKAjg13EBSVscxTaYA4mRc5t1UAXa2kXiGTNfZ079HIWXEkKmkgFrh/nJqamaLSrXO5H4WFFkPEaLJWbs3A==", + "peer": true, "dependencies": { "array-buffer-byte-length": "^1.0.1", "call-bind": "^1.0.5", @@ -5806,6 +5812,7 @@ "version": "1.0.7", "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz", "integrity": "sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==", + "peer": true, "dependencies": { "possible-typed-array-names": "^1.0.0" }, @@ -6901,6 +6908,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/data-view-buffer/-/data-view-buffer-1.0.1.tgz", "integrity": "sha512-0lht7OugA5x3iJLOWFhWK/5ehONdprk0ISXqVFn/NFrDu+cuc8iADFrGQz5BnRK7LLU3JmkbXSxaqX+/mXYtUA==", + "peer": true, "dependencies": { "call-bind": "^1.0.6", "es-errors": "^1.3.0", @@ -6917,6 +6925,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/data-view-byte-length/-/data-view-byte-length-1.0.1.tgz", "integrity": "sha512-4J7wRJD3ABAzr8wP+OcIcqq2dlUKp4DVflx++hs5h5ZKydWMI6/D/fAot+yh6g2tHh8fLFTvNOaVN357NvSrOQ==", + "peer": true, "dependencies": { "call-bind": "^1.0.7", "es-errors": "^1.3.0", @@ -6933,6 +6942,7 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/data-view-byte-offset/-/data-view-byte-offset-1.0.0.tgz", "integrity": "sha512-t/Ygsytq+R995EJ5PZlD4Cu56sWa8InXySaViRzw9apusqsOO2bQP+SbYzAhR0pFKoB+43lYy8rWban9JSuXnA==", + "peer": true, "dependencies": { "call-bind": "^1.0.6", "es-errors": "^1.3.0", @@ -7396,6 +7406,7 @@ "version": "1.23.3", "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.23.3.tgz", "integrity": "sha512-e+HfNH61Bj1X9/jLc5v1owaLYuHdeHHSQlkhCBiTK8rBvKaULl/beGMxwrMXjpYrv4pz22BlY570vVePA2ho4A==", + "peer": true, "dependencies": { "array-buffer-byte-length": "^1.0.1", "arraybuffer.prototype.slice": "^1.0.3", @@ -7485,6 +7496,7 @@ "version": "2.0.3", "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.0.3.tgz", "integrity": "sha512-3T8uNMC3OQTHkFUsFq8r/BwAXLHvU/9O9mE0fBc/MY5iq/8H7ncvO947LmYA6ldWw9Uh8Yhf25zu6n7nML5QWQ==", + "peer": true, "dependencies": { "get-intrinsic": "^1.2.4", "has-tostringtag": "^1.0.2", @@ -7498,6 +7510,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/es-shim-unscopables/-/es-shim-unscopables-1.0.2.tgz", "integrity": "sha512-J3yBRXCzDu4ULnQwxyToo/OjdMx6akgVC7K6few0a7F/0wLtmKKN7I73AH5T2836UuXRqN7Qg+IIUw/+YJksRw==", + "peer": true, "dependencies": { "hasown": "^2.0.0" } @@ -7506,6 +7519,7 @@ "version": "1.2.1", "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz", "integrity": "sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA==", + "peer": true, "dependencies": { "is-callable": "^1.1.4", "is-date-object": "^1.0.1", @@ -7690,6 +7704,7 @@ "version": "0.3.9", "resolved": "https://registry.npmjs.org/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.9.tgz", "integrity": "sha512-WFj2isz22JahUv+B788TlO3N6zL3nNJGU8CcZbPZvVEkBPaJdCV4vy5wyghty5ROFbCRnm132v8BScu5/1BQ8g==", + "peer": true, "dependencies": { "debug": "^3.2.7", "is-core-module": "^2.13.0", @@ -7700,6 +7715,7 @@ "version": "3.2.7", "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "peer": true, "dependencies": { "ms": "^2.1.1" } @@ -7708,6 +7724,7 @@ "version": "2.8.1", "resolved": "https://registry.npmjs.org/eslint-module-utils/-/eslint-module-utils-2.8.1.tgz", "integrity": "sha512-rXDXR3h7cs7dy9RNpUlQf80nX31XWJEyGq1tRMo+6GsO5VmTe4UTwtmonAD4ZkAsrfMVDA2wlGJ3790Ys+D49Q==", + "peer": true, "dependencies": { "debug": "^3.2.7" }, @@ -7724,6 +7741,7 @@ "version": "3.2.7", "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "peer": true, "dependencies": { "ms": "^2.1.1" } @@ -7732,6 +7750,7 @@ "version": "2.29.1", "resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.29.1.tgz", "integrity": "sha512-BbPC0cuExzhiMo4Ff1BTVwHpjjv28C5R+btTOGaCRC7UEz801up0JadwkeSk5Ued6TG34uaczuVuH6qyy5YUxw==", + "peer": true, "dependencies": { "array-includes": "^3.1.7", "array.prototype.findlastindex": "^1.2.3", @@ -7762,6 +7781,7 @@ "version": "1.1.11", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "peer": true, "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -7771,6 +7791,7 @@ "version": "3.2.7", "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "peer": true, "dependencies": { "ms": "^2.1.1" } @@ -7779,6 +7800,7 @@ "version": "2.1.0", "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", + "peer": true, "dependencies": { "esutils": "^2.0.2" }, @@ -7790,6 +7812,7 @@ "version": "3.1.2", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "peer": true, "dependencies": { "brace-expansion": "^1.1.7" }, @@ -7801,6 +7824,7 @@ "version": "6.3.1", "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "peer": true, "bin": { "semver": "bin/semver.js" } @@ -8258,6 +8282,7 @@ "version": "0.3.3", "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.3.tgz", "integrity": "sha512-jqYfLp7mo9vIyQf8ykW2v7A+2N4QjeCeI5+Dz9XraiO1ign81wjiH7Fb9vSOWvQfNtmSa4H2RoQTrrXivdUZmw==", + "peer": true, "dependencies": { "is-callable": "^1.1.3" } @@ -8413,6 +8438,7 @@ "version": "1.1.6", "resolved": "https://registry.npmjs.org/function.prototype.name/-/function.prototype.name-1.1.6.tgz", "integrity": "sha512-Z5kx79swU5P27WEayXM1tBi5Ze/lbIyiNgU3qyXUOf9b2rgXYyF9Dy9Cx+IQv/Lc8WCG6L82zwUPpSS9hGehIg==", + "peer": true, "dependencies": { "call-bind": "^1.0.2", "define-properties": "^1.2.0", @@ -8430,6 +8456,7 @@ "version": "1.2.3", "resolved": "https://registry.npmjs.org/functions-have-names/-/functions-have-names-1.2.3.tgz", "integrity": "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==", + "peer": true, "funding": { "url": "https://github.com/sponsors/ljharb" } @@ -8593,6 +8620,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/get-symbol-description/-/get-symbol-description-1.0.2.tgz", "integrity": "sha512-g0QYk1dZBxGwk+Ngc+ltRH2IBp2f7zBkBMBJZCDerh6EhlhSR6+9irMCuT/09zD6qkarHUSn529sK/yL4S27mg==", + "peer": true, "dependencies": { "call-bind": "^1.0.5", "es-errors": "^1.3.0", @@ -8708,6 +8736,7 @@ "version": "1.0.4", "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz", "integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==", + "peer": true, "dependencies": { "define-properties": "^1.2.1", "gopd": "^1.0.1" @@ -8904,6 +8933,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.0.2.tgz", "integrity": "sha512-tSvCKtBr9lkF0Ex0aQiP9N+OpV4zi2r/Nee5VkRDbaqv35RLYMzbwQfFSZZH0kR+Rd6302UJZ2p/bJCEoR3VoQ==", + "peer": true, "funding": { "url": "https://github.com/sponsors/ljharb" } @@ -8961,6 +8991,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "peer": true, "dependencies": { "has-symbols": "^1.0.3" }, @@ -9209,6 +9240,7 @@ "version": "1.0.7", "resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.0.7.tgz", "integrity": "sha512-NGnrKwXzSms2qUUih/ILZ5JBqNTSa1+ZmP6flaIp6KmSElgE9qdndzS3cqjrDovwFdmwsGsLdeFgB6suw+1e9g==", + "peer": true, "dependencies": { "es-errors": "^1.3.0", "hasown": "^2.0.0", @@ -9234,6 +9266,7 @@ "version": "3.0.4", "resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.4.tgz", "integrity": "sha512-wcjaerHw0ydZwfhiKbXJWLDY8A7yV7KhjQOpb83hGgGfId/aQa4TOvwyzn2PuswW2gPCYEL/nEAiSVpdOj1lXw==", + "peer": true, "dependencies": { "call-bind": "^1.0.2", "get-intrinsic": "^1.2.1" @@ -9254,6 +9287,7 @@ "version": "1.0.4", "resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.0.4.tgz", "integrity": "sha512-zB9CruMamjym81i2JZ3UMn54PKGsQzsJeo6xvN3HJJ4CAsQNB6iRutp2To77OfCNuoxspsIhzaPoO1zyCEhFOg==", + "peer": true, "dependencies": { "has-bigints": "^1.0.1" }, @@ -9265,6 +9299,7 @@ "version": "1.1.2", "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.1.2.tgz", "integrity": "sha512-gDYaKHJmnj4aWxyj6YHyXVpdQawtVLHU5cb+eztPGczf6cjuTdwve5ZIEfgXqH4e57An1D1AKf8CZ3kYrQRqYA==", + "peer": true, "dependencies": { "call-bind": "^1.0.2", "has-tostringtag": "^1.0.0" @@ -9280,6 +9315,7 @@ "version": "1.2.7", "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz", "integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==", + "peer": true, "engines": { "node": ">= 0.4" }, @@ -9302,6 +9338,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/is-data-view/-/is-data-view-1.0.1.tgz", "integrity": "sha512-AHkaJrsUVW6wq6JS8y3JnM/GJF/9cf+k20+iDzlSaJrinEo5+7vRiteOSwBhHRiAyQATN1AmY4hwzxJKPmYf+w==", + "peer": true, "dependencies": { "is-typed-array": "^1.1.13" }, @@ -9316,6 +9353,7 @@ "version": "1.0.5", "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.5.tgz", "integrity": "sha512-9YQaSxsAiSwcvS33MBk3wTCVnWK+HhF8VZR2jRxehM16QcVOdHqPn4VPHmRK4lSr38n9JriurInLcP90xsYNfQ==", + "peer": true, "dependencies": { "has-tostringtag": "^1.0.0" }, @@ -9377,6 +9415,7 @@ "version": "2.0.3", "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.3.tgz", "integrity": "sha512-5KoIu2Ngpyek75jXodFvnafB6DJgr3u8uuK0LEZJjrU19DrMD3EVERaR8sjz8CCGgpZvxPl9SuE1GMVPFHx1mw==", + "peer": true, "engines": { "node": ">= 0.4" }, @@ -9396,6 +9435,7 @@ "version": "1.0.7", "resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.0.7.tgz", "integrity": "sha512-k1U0IRzLMo7ZlYIfzRu23Oh6MiIFasgpb9X76eqfFZAqwH44UI4KTBvBYIZ1dSL9ZzChTB9ShHfLkR4pdW5krQ==", + "peer": true, "dependencies": { "has-tostringtag": "^1.0.0" }, @@ -9428,6 +9468,7 @@ "version": "1.1.4", "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.4.tgz", "integrity": "sha512-kvRdxDsxZjhzUX07ZnLydzS1TU/TJlTUHHY4YLL87e37oUA49DfkLqgy+VjFocowy29cKvcSiu+kIv728jTTVg==", + "peer": true, "dependencies": { "call-bind": "^1.0.2", "has-tostringtag": "^1.0.0" @@ -9443,6 +9484,7 @@ "version": "1.0.3", "resolved": "https://registry.npmjs.org/is-shared-array-buffer/-/is-shared-array-buffer-1.0.3.tgz", "integrity": "sha512-nA2hv5XIhLR3uVzDDfCIknerhx8XUKnstuOERPNNIinXG7v9u+ohXF67vxm4TPTEPU6lm61ZkwP3c9PCB97rhg==", + "peer": true, "dependencies": { "call-bind": "^1.0.7" }, @@ -9468,6 +9510,7 @@ "version": "1.0.7", "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.0.7.tgz", "integrity": "sha512-tE2UXzivje6ofPW7l23cjDOMa09gb7xlAqG6jG5ej6uPV32TlWP3NKPigtaGeHNu9fohccRYvIiZMfOOnOYUtg==", + "peer": true, "dependencies": { "has-tostringtag": "^1.0.0" }, @@ -9482,6 +9525,7 @@ "version": "1.0.4", "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.4.tgz", "integrity": "sha512-C/CPBqKWnvdcxqIARxyOh4v1UUEOCHpgDa0WYgpKDFMszcrPcffg5uhwSgPCLD2WWxmq6isisz87tzT01tuGhg==", + "peer": true, "dependencies": { "has-symbols": "^1.0.2" }, @@ -9496,6 +9540,7 @@ "version": "1.1.13", "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.13.tgz", "integrity": "sha512-uZ25/bUAlUY5fR4OKT4rZQEBrzQWYV9ZJYGGsUmEJ6thodVJ1HX64ePQ6Z0qPWP+m+Uq6e9UugrE38jeYsDSMw==", + "peer": true, "dependencies": { "which-typed-array": "^1.1.14" }, @@ -9515,6 +9560,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/is-weakref/-/is-weakref-1.0.2.tgz", "integrity": "sha512-qctsuLZmIQ0+vSSMfoVvyFe2+GSEvnmZ2ezTup1SBse9+twCCeial6EEi3Nc2KFcf6+qz2FBPnjXsk8xhKSaPQ==", + "peer": true, "dependencies": { "call-bind": "^1.0.2" }, @@ -9525,7 +9571,8 @@ "node_modules/isarray": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", - "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==" + "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==", + "peer": true }, "node_modules/isexe": { "version": "2.0.0", @@ -11569,6 +11616,7 @@ "version": "1.13.1", "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.1.tgz", "integrity": "sha512-5qoj1RUiKOMsCCNLV1CBiPYE10sziTsnmNxkAI/rZhiD63CF7IqdFGC/XzjWjpSgLf0LxXX3bDFIh0E18f6UhQ==", + "peer": true, "funding": { "url": "https://github.com/sponsors/ljharb" } @@ -11615,6 +11663,7 @@ "version": "2.0.8", "resolved": "https://registry.npmjs.org/object.fromentries/-/object.fromentries-2.0.8.tgz", "integrity": "sha512-k6E21FzySsSK5a21KRADBd/NGneRegFO5pLHfdQLpRDETUNJueLXs3WCzyQ3tFRDYgbq3KHGXfTbi2bs8WQ6rQ==", + "peer": true, "dependencies": { "call-bind": "^1.0.7", "define-properties": "^1.2.1", @@ -11632,6 +11681,7 @@ "version": "1.0.3", "resolved": "https://registry.npmjs.org/object.groupby/-/object.groupby-1.0.3.tgz", "integrity": "sha512-+Lhy3TQTuzXI5hevh8sBGqbmurHbbIjAi0Z4S63nthVLmLxfbj4T54a4CfZrXIrt9iP4mVAPYMo/v99taj3wjQ==", + "peer": true, "dependencies": { "call-bind": "^1.0.7", "define-properties": "^1.2.1", @@ -11645,6 +11695,7 @@ "version": "1.2.0", "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.2.0.tgz", "integrity": "sha512-yBYjY9QX2hnRmZHAjG/f13MzmBzxzYgQhFrke06TTyKY5zSTEqkOeukBzIdVA3j3ulu8Qa3MbVFShV7T2RmGtQ==", + "peer": true, "dependencies": { "call-bind": "^1.0.7", "define-properties": "^1.2.1", @@ -12294,6 +12345,7 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.0.0.tgz", "integrity": "sha512-d7Uw+eZoloe0EHDIYoe+bQ5WXnGMOpmiZFTuMWCwpjzzkL2nTjcKiAk4hh8TjnGye2TwWOk3UXucZ+3rbmBa8Q==", + "peer": true, "engines": { "node": ">= 0.4" } @@ -12869,6 +12921,7 @@ "version": "1.5.2", "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.5.2.tgz", "integrity": "sha512-NcDiDkTLuPR+++OCKB0nWafEmhg/Da8aUPLPMQbK+bxKKCm1/S5he+AqYa4PlMCVBalb4/yxIRub6qkEx5yJbw==", + "peer": true, "dependencies": { "call-bind": "^1.0.6", "define-properties": "^1.2.1", @@ -13142,6 +13195,7 @@ "version": "1.1.2", "resolved": "https://registry.npmjs.org/safe-array-concat/-/safe-array-concat-1.1.2.tgz", "integrity": "sha512-vj6RsCsWBCf19jIeHEfkRMw8DPiBb+DMXklQ/1SGDHOMlHdPUkZXFQ2YdplS23zESTijAcurb1aSgJA3AgMu1Q==", + "peer": true, "dependencies": { "call-bind": "^1.0.7", "get-intrinsic": "^1.2.4", @@ -13178,6 +13232,7 @@ "version": "1.0.3", "resolved": "https://registry.npmjs.org/safe-regex-test/-/safe-regex-test-1.0.3.tgz", "integrity": "sha512-CdASjNJPvRa7roO6Ra/gLYBTzYzzPyyBXxIMdGW3USQLyjWEls2RgW5UBTXaQVp+OrpeCK3bLem8smtmheoRuw==", + "peer": true, "dependencies": { "call-bind": "^1.0.6", "es-errors": "^1.3.0", @@ -13248,6 +13303,7 @@ "version": "2.0.2", "resolved": "https://registry.npmjs.org/set-function-name/-/set-function-name-2.0.2.tgz", "integrity": "sha512-7PGFlmtwsEADb0WYyvCMa1t+yke6daIG4Wirafur5kcf+MhUnPms1UeR0CKQdTZD81yESwMHbtn+TR+dMviakQ==", + "peer": true, "dependencies": { "define-data-property": "^1.1.4", "es-errors": "^1.3.0", @@ -13303,6 +13359,7 @@ "version": "1.0.6", "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.6.tgz", "integrity": "sha512-fDW/EZ6Q9RiO8eFG8Hj+7u/oW+XrPTIChwCOM2+th2A6OblDtYYIpve9m+KvI9Z4C9qSEXlaGR6bTEYHReuglA==", + "peer": true, "dependencies": { "call-bind": "^1.0.7", "es-errors": "^1.3.0", @@ -13724,6 +13781,7 @@ "version": "1.2.9", "resolved": "https://registry.npmjs.org/string.prototype.trim/-/string.prototype.trim-1.2.9.tgz", "integrity": "sha512-klHuCNxiMZ8MlsOihJhJEBJAiMVqU3Z2nEXWfWnIqjN0gEFS9J9+IxKozWWtQGcgoa1WUZzLjKPTr4ZHNFTFxw==", + "peer": true, "dependencies": { "call-bind": "^1.0.7", "define-properties": "^1.2.1", @@ -13741,6 +13799,7 @@ "version": "1.0.8", "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.8.tgz", "integrity": "sha512-p73uL5VCHCO2BZZ6krwwQE3kCzM7NKmis8S//xEC6fQonchbum4eP6kR4DLEjQFO3Wnj3Fuo8NM0kOSjVdHjZQ==", + "peer": true, "dependencies": { "call-bind": "^1.0.7", "define-properties": "^1.2.1", @@ -13754,6 +13813,7 @@ "version": "1.0.8", "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.8.tgz", "integrity": "sha512-UXSH262CSZY1tfu3G3Secr6uGLCFVPMhIqHjlgCUtCCcgihYc/xKs9djMTMUOb2j1mVSeU8EU6NWc/iQKU6Gfg==", + "peer": true, "dependencies": { "call-bind": "^1.0.7", "define-properties": "^1.2.1", @@ -14184,6 +14244,7 @@ "version": "3.15.0", "resolved": "https://registry.npmjs.org/tsconfig-paths/-/tsconfig-paths-3.15.0.tgz", "integrity": "sha512-2Ac2RgzDe/cn48GvOe3M+o82pEFewD3UPbyoUHHdKasHwJKjds4fLXWf/Ux5kATBKN20oaFGu+jbElp1pos0mg==", + "peer": true, "dependencies": { "@types/json5": "^0.0.29", "json5": "^1.0.2", @@ -14195,6 +14256,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.2.tgz", "integrity": "sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA==", + "peer": true, "dependencies": { "minimist": "^1.2.0" }, @@ -14206,6 +14268,7 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", "integrity": "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==", + "peer": true, "engines": { "node": ">=4" } @@ -14266,6 +14329,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/typed-array-buffer/-/typed-array-buffer-1.0.2.tgz", "integrity": "sha512-gEymJYKZtKXzzBzM4jqa9w6Q1Jjm7x2d+sh19AdsD4wqnMPDYyvwpsIc2Q/835kHuo3BEQ7CjelGhfTsoBb2MQ==", + "peer": true, "dependencies": { "call-bind": "^1.0.7", "es-errors": "^1.3.0", @@ -14279,6 +14343,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/typed-array-byte-length/-/typed-array-byte-length-1.0.1.tgz", "integrity": "sha512-3iMJ9q0ao7WE9tWcaYKIptkNBuOIcZCCT0d4MRvuuH88fEoEH62IuQe0OtraD3ebQEoTRk8XCBoknUNc1Y67pw==", + "peer": true, "dependencies": { "call-bind": "^1.0.7", "for-each": "^0.3.3", @@ -14297,6 +14362,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/typed-array-byte-offset/-/typed-array-byte-offset-1.0.2.tgz", "integrity": "sha512-Ous0vodHa56FviZucS2E63zkgtgrACj7omjwd/8lTEMEPFFyjfixMZ1ZXenpgCFBBt4EC1J2XsyVS2gkG0eTFA==", + "peer": true, "dependencies": { "available-typed-arrays": "^1.0.7", "call-bind": "^1.0.7", @@ -14316,6 +14382,7 @@ "version": "1.0.6", "resolved": "https://registry.npmjs.org/typed-array-length/-/typed-array-length-1.0.6.tgz", "integrity": "sha512-/OxDN6OtAk5KBpGb28T+HZc2M+ADtvRxXrKKbUwtsLgdoxgX13hyy7ek6bFRl5+aBs2yZzB0c4CnQfAtVypW/g==", + "peer": true, "dependencies": { "call-bind": "^1.0.7", "for-each": "^0.3.3", @@ -14374,6 +14441,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.0.2.tgz", "integrity": "sha512-61pPlCD9h51VoreyJ0BReideM3MDKMKnh6+V9L08331ipq6Q8OFXZYiqP6n/tbHx4s5I9uRhcye6BrbkizkBDw==", + "peer": true, "dependencies": { "call-bind": "^1.0.2", "has-bigints": "^1.0.2", @@ -14720,6 +14788,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.0.2.tgz", "integrity": "sha512-bwZdv0AKLpplFY2KZRX6TvyuN7ojjr7lwkg6ml0roIy9YeuSr7JS372qlNW18UQYzgYK9ziGcerWqZOmEn9VNg==", + "peer": true, "dependencies": { "is-bigint": "^1.0.1", "is-boolean-object": "^1.1.0", @@ -14735,6 +14804,7 @@ "version": "1.1.15", "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.15.tgz", "integrity": "sha512-oV0jmFtUky6CXfkqehVvBP/LSWJ2sy4vWMioiENyJLePrBO/yKyV9OyJySfAKosh+RYkIl5zJCNZ8/4JncrpdA==", + "peer": true, "dependencies": { "available-typed-arrays": "^1.0.7", "call-bind": "^1.0.7", diff --git a/core/package.json b/core/package.json index bdda48184..ed489d1f2 100644 --- a/core/package.json +++ b/core/package.json @@ -32,7 +32,6 @@ "cross-env": "^7.0.3", "esbuild": "0.17.19", "eslint": "^8", - "eslint-plugin-import": "^2.29.1", "jest": "^29.7.0", "jest-environment-jsdom": "^29.7.0", "myers-diff": "^2.1.0", @@ -49,7 +48,6 @@ "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", "@typescript-eslint/eslint-plugin": "^7.8.0", - "@typescript-eslint/parser": "^7.8.0", "@xenova/transformers": "2.14.0", "adf-to-md": "^1.1.0", "async-mutex": "^0.5.0", diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 3b357b679..b5d18e1e8 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -15,7 +15,12 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { }, ]; openUrl: [string, void]; - applyToCurrentFile: [{ text: string; streamId: string }, void]; + // We pass the `curSelectedModel` because we currently cannot access the + // default model title in the GUI from JB + applyToCurrentFile: [ + { text: string; streamId: string; curSelectedModelTitle: string }, + void, + ]; showTutorial: [undefined, void]; showFile: [{ filepath: string }, void]; openConfigJson: [undefined, void]; @@ -66,6 +71,7 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { * @deprecated Use navigateTo with a path instead. */ viewHistory: [undefined, void]; + focusContinueSessionId: [{ sessionId: string | undefined }, void]; newSession: [undefined, void]; setTheme: [{ theme: any }, void]; setColors: [{ [key: string]: string }, void]; diff --git a/core/util/GlobalContext.ts b/core/util/GlobalContext.ts index 9e5641332..f48e848a9 100644 --- a/core/util/GlobalContext.ts +++ b/core/util/GlobalContext.ts @@ -1,6 +1,6 @@ import fs from "node:fs"; -import { getGlobalContextFilePath } from "./paths"; import { EmbeddingsProvider } from "../"; +import { getGlobalContextFilePath } from "./paths"; export type GlobalContextType = { indexingPaused: boolean; @@ -37,7 +37,15 @@ export class GlobalContext { ); } else { const data = fs.readFileSync(getGlobalContextFilePath(), "utf-8"); - const parsed = JSON.parse(data); + + let parsed; + try { + parsed = JSON.parse(data); + } catch (e: any) { + console.warn(`Error updating global context: ${e}`); + return; + } + parsed[key] = value; fs.writeFileSync( getGlobalContextFilePath(), @@ -54,7 +62,12 @@ export class GlobalContext { } const data = fs.readFileSync(getGlobalContextFilePath(), "utf-8"); - const parsed = JSON.parse(data); - return parsed[key]; + try { + const parsed = JSON.parse(data); + return parsed[key]; + } catch (e: any) { + console.warn(`Error parsing global context: ${e}`); + return undefined; + } } } 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 { diff --git a/core/util/generateRepoMap.ts b/core/util/generateRepoMap.ts index 785a62c41..fb4be85d7 100644 --- a/core/util/generateRepoMap.ts +++ b/core/util/generateRepoMap.ts @@ -12,9 +12,6 @@ export interface RepoMapOptions { } class RepoMapGenerator { - private llm: ILLM; - private ide: IDE; - private options: RepoMapOptions; private maxRepoMapTokens: number; private repoMapPath: string = getRepoMapFilePath(); @@ -32,10 +29,11 @@ class RepoMapGenerator { "this map contains the name of the file, and the signature for any " + "classes, methods, or functions in the file.\n\n"; - constructor(llm: ILLM, ide: IDE, options: RepoMapOptions) { - this.llm = llm; - this.ide = ide; - this.options = options; + constructor( + private llm: ILLM, + private ide: IDE, + private options: RepoMapOptions, + ) { this.maxRepoMapTokens = llm.contextLength * this.REPO_MAX_CONTEXT_LENGTH_RATIO; } diff --git a/core/util/history.ts b/core/util/history.ts index 5f4a85e5d..08bc26994 100644 --- a/core/util/history.ts +++ b/core/util/history.ts @@ -3,6 +3,18 @@ import { PersistedSessionInfo, SessionInfo } from "../index.js"; import { ListHistoryOptions } from "../protocol/core.js"; import { getSessionFilePath, getSessionsListPath } from "./paths.js"; +function safeParseArray( + value: string, + errorMessage: string = "Error parsing array", +): T[] | undefined { + try { + return JSON.parse(value) as T[]; + } catch (e: any) { + console.warn(`${errorMessage}: ${e}`); + return undefined; + } +} + class HistoryManager { list(options: ListHistoryOptions): SessionInfo[] { const filepath = getSessionsListPath(); @@ -10,7 +22,9 @@ class HistoryManager { return []; } const content = fs.readFileSync(filepath, "utf8"); - let sessions = JSON.parse(content).filter((session: any) => { + + let sessions = safeParseArray(content) ?? []; + sessions = sessions.filter((session: any) => { // Filter out old format return typeof session.session_id !== "string"; }); @@ -35,14 +49,11 @@ class HistoryManager { // Read and update the sessions list const sessionsListFile = getSessionsListPath(); const sessionsListRaw = fs.readFileSync(sessionsListFile, "utf-8"); - let sessionsList: SessionInfo[]; - try { - sessionsList = JSON.parse(sessionsListRaw); - } catch (error) { - throw new Error( - `It looks like there is a JSON formatting error in your sessions.json file (${sessionsListFile}). Please fix this before creating a new session.`, - ); - } + let sessionsList = + safeParseArray( + sessionsListRaw, + "Error parsing sessions.json", + ) ?? []; sessionsList = sessionsList.filter( (session) => session.sessionId !== sessionId, 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/core/util/paths.ts b/core/util/paths.ts index 3002892ca..b10b7fca6 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -3,9 +3,9 @@ import dotenv from "dotenv"; import * as fs from "fs"; import * as os from "os"; import * as path from "path"; +import { IdeType, SerializedContinueConfig } from "../"; import { defaultConfig, defaultConfigJetBrains } from "../config/default"; import Types from "../config/types"; -import { IdeType, SerializedContinueConfig } from "../"; dotenv.config(); @@ -348,3 +348,18 @@ export function getRepoMapFilePath(): string { export function getEsbuildBinaryPath(): string { return path.join(getContinueUtilsPath(), "esbuild"); } + +export function setupInitialDotContinueDirectory() { + const devDataTypes = [ + "chat", + "autocomplete", + "quickEdit", + "tokens_generated", + ]; + devDataTypes.forEach((p) => { + const devDataPath = getDevDataFilePath(p); + if (!fs.existsSync(devDataPath)) { + fs.writeFileSync(devDataPath, ""); + } + }); +} diff --git a/core/util/posthog.ts b/core/util/posthog.ts index c9d329f2b..58828dacd 100644 --- a/core/util/posthog.ts +++ b/core/util/posthog.ts @@ -13,22 +13,34 @@ export class Telemetry { event: string, properties: { [key: string]: any }, sendToTeam: boolean = false, + isExtensionActivationError: boolean = false, ) { - if (process.env.NODE_ENV === "test") { - return; - } try { - Telemetry.client?.capture({ + const augmentedProperties = { + ...properties, + os: Telemetry.os, + extensionVersion: Telemetry.ideInfo?.extensionVersion, + ideName: Telemetry.ideInfo?.name, + ideType: Telemetry.ideInfo?.ideType, + }; + const payload = { distinctId: Telemetry.uniqueId, event, - properties: { - ...properties, - os: Telemetry.os, - extensionVersion: Telemetry.ideInfo?.extensionVersion, - ideName: Telemetry.ideInfo?.name, - ideType: Telemetry.ideInfo?.ideType, - }, - }); + properties: augmentedProperties, + }; + + // In cases where an extremely early fatal error occurs, we may not have initialized yet + if (isExtensionActivationError && !Telemetry.client) { + const client = await Telemetry.getTelemetryClient(); + client?.capture(payload); + return; + } + + if (process.env.NODE_ENV === "test") { + return; + } + + Telemetry.client?.capture(payload); if (sendToTeam) { void TeamAnalytics.capture(event, properties); @@ -42,6 +54,17 @@ export class Telemetry { Telemetry.client?.shutdown(); } + static async getTelemetryClient() { + try { + const { PostHog } = await import("posthog-node"); + return new PostHog("phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs", { + host: "https://app.posthog.com", + }); + } catch (e) { + console.error(`Failed to setup telemetry: ${e}`); + } + } + static async setup(allow: boolean, uniqueId: string, ideInfo: IdeInfo) { Telemetry.uniqueId = uniqueId; Telemetry.os = os.platform(); @@ -49,20 +72,8 @@ export class Telemetry { if (!allow || process.env.NODE_ENV === "test") { Telemetry.client = undefined; - } else { - try { - if (!Telemetry.client) { - const { PostHog } = await import("posthog-node"); - Telemetry.client = new PostHog( - "phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs", - { - host: "https://app.posthog.com", - }, - ); - } - } catch (e) { - console.error(`Failed to setup telemetry: ${e}`); - } + } else if (!Telemetry.client) { + Telemetry.client = await Telemetry.getTelemetryClient(); } } } diff --git a/docs/docs/actions/how-to-customize.md b/docs/docs/actions/how-to-customize.md index 0170283d9..01cf2d064 100644 --- a/docs/docs/actions/how-to-customize.md +++ b/docs/docs/actions/how-to-customize.md @@ -7,7 +7,7 @@ sidebar_position: 5 ## Built-in slash commands -Continue has a large library of built-in slash commands, but when you first install we only display the most commonly used ones, like “/edit”, “/comment”, and “/share”. To add more actions, you can open [config.json](../customize/config.mdx) and add them to the `slashCommands` array. +Continue has a large library of built-in slash commands, but when you first install we only display the most commonly used ones, like “/edit”, “/comment”, and “/share”. To add more actions, you can open [config.json](../reference.md) and add them to the `slashCommands` array. ## Custom slash commands @@ -20,7 +20,7 @@ There are two ways to add custom slash commands: If you want to go a step further than writing custom commands with natural language, you can write a custom function that returns the response. This requires using `config.ts` instead of `config.json`. diff --git a/docs/docs/actions/how-to-use-it.md b/docs/docs/actions/how-to-use-it.md index cffc0d65d..3e7c04644 100644 --- a/docs/docs/actions/how-to-use-it.md +++ b/docs/docs/actions/how-to-use-it.md @@ -14,7 +14,7 @@ Actions are shortcuts for common use cases. For example, you might want to revie ### Slash commands -The most common way to invoke an action is with a slash command. These are shortcuts that can be activated by typing '/' and selecting from the dropdown. For example, the built-in '/edit' slash command lets you stream edits directly into your editor. +The most common way to invoke an action is with a slash command. These are shortcuts that can be activated by typing '/' in a chat session (press cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains)), and selecting from the dropdown. For example, the built-in '/edit' slash command lets you stream edits directly into your editor. ![slash-commands](/img/slash-commands.png) diff --git a/docs/docs/autocomplete/how-to-customize.md b/docs/docs/autocomplete/how-to-customize.md index df95b3201..dcf6ba234 100644 --- a/docs/docs/autocomplete/how-to-customize.md +++ b/docs/docs/autocomplete/how-to-customize.md @@ -5,7 +5,7 @@ keywords: [customize] sidebar_position: 5 --- -Continue offers a handful of parameters in [`config.json`](../customize/config.mdx) that can be tuned to find the perfect balance between suggestion quality and system performance for your specific needs and hardware capabilities: +Continue offers a handful of parameters in [`config.json`](../reference.md) that can be tuned to find the perfect balance between suggestion quality and system performance for your specific needs and hardware capabilities: ```json title="config.json" "tabAutocompleteOptions": { diff --git a/docs/docs/chat/model-setup.mdx b/docs/docs/chat/model-setup.mdx index 023e875c1..6e9dbcf22 100644 --- a/docs/docs/chat/model-setup.mdx +++ b/docs/docs/chat/model-setup.mdx @@ -9,7 +9,7 @@ import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; :::info -This page recommends models and providers for Chat. Read more about how to set up your `config.json` [here](../customize/config.mdx). +This page recommends models and providers for Chat. Read more about how to set up your `config.json` [here](../reference.md). ::: ## Best overall experience diff --git a/docs/docs/customize/config.mdx b/docs/docs/customize/config.mdx deleted file mode 100644 index cac96ceb6..000000000 --- a/docs/docs/customize/config.mdx +++ /dev/null @@ -1,22 +0,0 @@ ---- -title: config.json Reference -keywords: [config.json, configuration, options] ---- - -import Schema from "@site/static/schemas/config.json"; -import JSONSchemaViewer from "@theme/JSONSchemaViewer"; - -# Configuration options - -The following shows the JSON Schema definition for `config.json`. - -You can also define a partial `config.json` object in a file called `.continuerc.json` at the root of your workspace. This will be applied on top of any configuration from `config.json`. - - - -[View the source](https://github.com/continuedev/continue/blob/main/extensions/vscode/config_schema.json) diff --git a/docs/docs/customize/deep-dives/autocomplete.md b/docs/docs/customize/deep-dives/autocomplete.md index 346ffb2d3..f945d79d4 100644 --- a/docs/docs/customize/deep-dives/autocomplete.md +++ b/docs/docs/customize/deep-dives/autocomplete.md @@ -44,7 +44,7 @@ All of the configuration options available for chat models are available to use } ``` -If you aren't yet familiar with the available options, you can find the full reference [here](../config.mdx). +If you aren't yet familiar with the available options, you can find the full reference [here](./ways-to-configure.md). ## Configuration Options diff --git a/docs/docs/customize/deep-dives/codebase.md b/docs/docs/customize/deep-dives/codebase.md index 8b757a11f..f106fea14 100644 --- a/docs/docs/customize/deep-dives/codebase.md +++ b/docs/docs/customize/deep-dives/codebase.md @@ -5,7 +5,11 @@ keywords: [talk, embeddings, reranker, codebase, experimental] # @Codebase -Continue indexes your codebase so that it can later automatically pull in the most relevant context from throughout your workspace. This is done via a combination of embeddings-based retrieval and keyword search. By default, all embeddings are calculated locally with `all-MiniLM-L6-v2` and stored locally in `~/.continue/index`. +Continue indexes your codebase so that it can later automatically pull in the most relevant context from throughout your workspace. This is done via a combination of embeddings-based retrieval and keyword search. By default, all embeddings are calculated locally using `transformers.js` and stored locally in `~/.continue/index`. + +:::info[`transformers.js cannot be used in JetBrains`] +Currently, `transformers.js` cannot be used in JetBrains IDEs. However, you can select a differet embeddings model from [the list here](../model-types/embeddings.md). +::: Currently, the codebase retrieval feature is available as the "codebase" and "folder" context providers. You can use them by typing `@Codebase` or `@Folder` in the input box, and then asking a question. The contents of the input box will be compared with the embeddings from the rest of the codebase (or folder) to determine relevant files. @@ -34,7 +38,7 @@ Here are use cases where it is not useful: ## Configuration -There are a few options that let you configure the behavior of the codebase context provider. These can be set in `config.json`, and are the same for the codebase and folder context providers: +There are a few options that let you configure the behavior of the codebase context provider. These can be set in `config.json`, and are the same for the codebase, docs, and folder context providers: ```json title="config.json" { @@ -67,10 +71,12 @@ Whether to use re-ranking, which will allow initial selection of `nRetrieve` res Continue respects `.gitignore` files in order to determine which files should not be indexed. If you'd like to exclude additional files, you can add them to a `.continueignore` file, which follows the exact same rules as `.gitignore`. +Continue also supports a **global** `.continueignore` file that will be respected for all workspaces, which can be created at `~/.continue/.continueignore`. + If you want to see exactly what files Continue has indexed, the metadata is stored in `~/.continue/index/index.sqlite`. You can use a tool like [DB Browser for SQLite](https://sqlitebrowser.org/) to view the `tag_catalog` table within this file. If you need to force a refresh of the index, reload the VS Code window with `cmd/ctrl + shift + p` + "Reload Window". ## Repository map -Models in the Claude 3, Llama 3.1, Gemini 1.5, and GPT-4o families will automatically use a [repository map](../context-providers.md#repository-map) during codebase retrieval, which allows the model to understand the structure of your codebase and use it to answer questions. Currently, the repository map only contains the filepaths in the codebase. +Models in the Claude 3, Llama 3.1/3.2, Gemini 1.5, and GPT-4o families will automatically use a [repository map](../context-providers.md#repository-map) during codebase retrieval, which allows the model to understand the structure of your codebase and use it to answer questions. Currently, the repository map only contains the filepaths in the codebase. diff --git a/docs/docs/customize/deep-dives/docs.md b/docs/docs/customize/deep-dives/docs.md index bc8968528..96604ca70 100644 --- a/docs/docs/customize/deep-dives/docs.md +++ b/docs/docs/customize/deep-dives/docs.md @@ -69,6 +69,25 @@ The [configuration schema for docs](https://github.com/continuedev/continue/blob - `rootUrl`: The base URL of the documentation site, used to determine which pages to index. - `faviconUrl`: The URL of the site's favicon, used for visual identification in the UI. +## Configuration + +As with [@Codebase context provider configuration](https://docs.continue.dev/customize/deep-dives/codebase#configuration), you can adjust the behavior of the docs context provider with the `nRetrieve`, `nFinal`, and `useReranking` + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "docs", + "params": { + "nRetrieve": 25, + "nFinal": 5, + "useReranking": true + } + } + ] +} +``` + ## Crawling dynamically generated sites with `useChromiumForDocsCrawling` By default, we use a lighter weight tool to crawl documentation sites that cannot render sites that are dynamically generated using JavaScript. diff --git a/docs/docs/customize/deep-dives/ways-to-configure.md b/docs/docs/customize/deep-dives/ways-to-configure.md new file mode 100644 index 000000000..d67b92147 --- /dev/null +++ b/docs/docs/customize/deep-dives/ways-to-configure.md @@ -0,0 +1,68 @@ +--- +description: Ways to configure +keywords: [config, settings, customize] +--- + +# Ways to configure + +Continue can be deeply customized. User-level configuration is stored and can be edited in your home directory in [`config.json`](#configjson): + +- `~/.continue/config.json` (MacOS / Linux) +- `%USERPROFILE%\.continue\config.json` (Windows) + +To open `config.json`, you can click the "gear" icon in the bottom right corner of the Continue Chat sidebar. When editing this file, you can see the available options suggested as you type, or check the reference below. + +When you save `config.json`, Continue will automatically refresh to take into account your changes. `config.json` is automatically created the first time you use Continue. `config.json` is automatically generated if it doesn't exist. + +In the vast majority of cases, you will only need to edit `config.json`. However, Continue offers two additional ways to customize configuration: + +- [`.continuerc.json`](#continuercjson) - Workspace-level configuration. If you'd like to scope certain settings to a particular workspace, you can add a `.continuerc.json` to the root of your project. This can be set to merge with _or_ override the user-level `config.json` +- [`config.ts`](#configts) - Advanced configuration (probably unnecessary) - a TypeScript file in your home directory that can be used to programmatically modify (_merged_) the `config.json` schema: + - `~/.continue/config.ts` (MacOS / Linux) + - `%USERPROFILE%\.continue\config.ts` (Windows) + +## `config.json` + +See the full reference for `config.json` [here](../../reference.md). + +## `.continuerc.json` + +The format of `.continuerc.json` is the same as `config.json`, plus one _additional_ property `mergeBehavior`, which can be set to either "merge" or "overwrite". If set to "merge" (the default), `.continuerc.json` will be applied on top of `config.json` (arrays and objects are merged). If set to "overwrite", then every top-level property of `.continuerc.json` will overwrite that property from `config.json`. + +Example + +```json title="config.json" +{ + "tabAutocompleteOptions": { + "disable": true + }, + "mergeBehavior": "overwrite" +} +``` + +## `config.ts` + +To programatically extend `config.json`, you can place a `config.ts` script in same directory as `config.json` and export a `modifyConfig` function, like: + +```ts title="config.ts" +export function modifyConfig(config: Config): Config { + config.slashCommands?.push({ + name: "commit", + description: "Write a commit message", + run: async function* (sdk) { + const diff = await sdk.ide.getDiff(); + for await (const message of sdk.llm.streamComplete( + `${diff}\n\nWrite a commit message for the above changes. Use no more than 20 tokens to give a brief description in the imperative mood (e.g. 'Add feature' not 'Added feature'):`, + { + maxTokens: 20, + }, + )) { + yield message; + } + }, + }); + return config; +} +``` + +This can be used for slash commands and custom context providers. 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/asksage.md b/docs/docs/customize/model-providers/more/asksage.md new file mode 100644 index 000000000..c5ba9218c --- /dev/null +++ b/docs/docs/customize/model-providers/more/asksage.md @@ -0,0 +1,61 @@ +# Ask Sage + +:::info + +To get an Ask Sage API key login to the Ask Sage platform (If you don't have an account, you can create one [here](https://chat.asksage.ai/)) and follow the instructions in the Ask Sage Docs:[Ask Sage API Key](https://docs.asksage.ai/docs/api-documentation/api-documentation.html) + +::: + +## Configuration + +To use the Ask Sage models, the following configuration is required to the `config.json` file: + +```json +{ + "models": [ + { + "apiKey": "YOUR_API_KEY", + "apiBase": "https://api.asksage.ai/server/", // apiBase will be the same for all models, but will vary based on tenant. + "model": "gpt4-gov", + "title": "GPT-4 gov", + "provider": "askSage" + } + ] +} +``` + +The `apiBase` will be listed on the Ask Sage platform when you generate an `API key`. You will see context as shown below: + +> Server API for query/training etc.: +> - Documentation: https://app.swaggerhub.com/apis-docs/NICOLASCHAILLAN_1/server_ask-sage_api/1.0 +> - URL for this API is: https://api.asksage.ai/server/ + +## Usage + +Currently, the setup for the models provided by Ask Sage is to support the following two functionalities provided by Continue.Dev: + +- `Chat` to understand and iterate on code in the sidebar +- `Edit` to modify code without leaving your current file + +More models, functionalities and documentation will be added in the future for Ask Sage Integration. + +> We recommend to utilize the`OpenAI` or `Anthropic` models for the best performance and results for the `Chat` and `Edit` functionalities. + +## Current Models From Ask Sage Supported + +The current Models available provided by Ask Sage are: + +| Model | Added | +|--------------------|-------| +| Gov GPT-4.0 | Yes | +| Gov GPT-4o | Yes | +| GPT-4o | Yes | +| GPT-4o-mini | Yes | +| GPT-3.5-16K | Yes | +| Calude 3 Opus | Yes | +| Calude 3 Sonet | Yes | +| Calude 3.5 Sonnet | Yes | +| Gemini Pro | Yes | +| llama 3 | Yes | +| Mistral Large | Yes | + diff --git a/docs/docs/customize/model-providers/more/cerebras.md b/docs/docs/customize/model-providers/more/cerebras.md index 57d549830..d9cbd31dc 100644 --- a/docs/docs/customize/model-providers/more/cerebras.md +++ b/docs/docs/customize/model-providers/more/cerebras.md @@ -1,6 +1,6 @@ # Cerebras Inference -Cerebras Inference uses specialized silicon to provides fast inference for the Llama3.1 8B and Llama3.1 70B models. +Cerebras Inference uses specialized silicon to provides fast inference. 1. Create an account in the portal [here](https://cloud.cerebras.ai/). 2. Create and copy the API key for use in Continue. diff --git a/docs/docs/customize/model-providers/more/cohere.md b/docs/docs/customize/model-providers/more/cohere.md index c2b3c631e..24f2a7f88 100644 --- a/docs/docs/customize/model-providers/more/cohere.md +++ b/docs/docs/customize/model-providers/more/cohere.md @@ -45,7 +45,7 @@ We recommend configuring **rerank-english-v3.0** as your reranking model. ```json title="config.json" { - "embeddingsProvider": { + "reranker": { "provider": "cohere", "params": { "model": "rerank-english-v3.0", 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/watsonx.md b/docs/docs/customize/model-providers/more/watsonx.md index 5cc6b33fa..eeeb6073f 100644 --- a/docs/docs/customize/model-providers/more/watsonx.md +++ b/docs/docs/customize/model-providers/more/watsonx.md @@ -10,35 +10,35 @@ Accessing watsonx models can be done either through watsonx SaaS on IBM Cloud or To get started with watsonx SaaS, visit the [registration page](https://dataplatform.cloud.ibm.com/registration/stepone?context=wx). If you do not have an existing IBM Cloud account, you can sign up for a free trial. -To authenticate to watsonx.ai SaaS with Continue, you will need to create a project and [setup an API key](https://www.ibm.com/docs/en/mas-cd/continuous-delivery?topic=cli-creating-your-cloud-api-key). Then, in continue: +To authenticate to watsonx.ai SaaS with Continue, you will need to create a project and [set up an API key](https://www.ibm.com/docs/en/mas-cd/continuous-delivery?topic=cli-creating-your-cloud-api-key). Then, in continue: -- Set **watsonx URL** to your watsonx SaaS endpoint, e.g. `https://us-south.ml.cloud.ibm.com` for US South region. -- Set **watsonx Project ID** to your watsonx project ID. -- Set **watsonx API Key** to your watsonx API Key. +- Set **apiBase** to your watsonx SaaS endpoint, e.g. `https://us-south.ml.cloud.ibm.com` for US South region. +- Set **projectId** to your watsonx project ID. +- Set **apiKey** to your watsonx API Key. ### watsonx.ai Software To authenticate to your watsonx.ai Software instance with Continue, you can use either `username/password` or `ZenApiKey` method: 1. _Option 1_ (Recommended): using `ZenApiKey` authentication: - - Set **watsonx URL** to your watsonx software endpoint, e.g. `https://cpd-watsonx.apps.example.com`. - - Set **watsonx Project ID** to your watsonx project ID. - - Set **watsonx API Key** to your watsonx Zen API Key. To generate it: - 1. Log in to the CPD web client. - 2. From the toolbar, click your avatar. - 3. Click **Profile and settings**. - 4. Click **API key** > **Generate new key**. - 5. Click **Generate**. - 6. Click **Copy** and save your key somewhere safe. You cannot recover this key if you lose it. - 7. Generate your ZenApiKey by running the following command in your preferred terminal: `echo ":" | base64`, replacing `` with your CPD username and `` with the API Key you just created. + - Set **apiBase** to your watsonx software endpoint, e.g. `https://cpd-watsonx.apps.example.com`. + - Set **projectId** to your watsonx project ID. + - Set **apiKey** to your watsonx Zen API Key. To generate it: + 1. Log in to the CPD web client. + 2. From the toolbar, click your avatar. + 3. Click **Profile and settings**. + 4. Click **API key** > **Generate new key**. + 5. Click **Generate**. + 6. Click **Copy** and save your key somewhere safe. You cannot recover this key if you lose it. + 7. Generate your ZenApiKey by running the following command in your preferred terminal: `echo ":" | base64`, replacing `` with your CPD username and `` with the API Key you just created. 2. _Option 2_: using `username/password` authentication: - - Set **watsonx URL** to your watsonx software endpoint, e.g. `https://cpd-watsonx.apps.example.com`. - - Set **watsonx Project ID** to your watsonx project ID. - - Set **watsonx API Key** to your watsonx Username and Password using `username:password` as format. + - Set **apiBase** to your watsonx software endpoint, e.g. `https://cpd-watsonx.apps.example.com`. + - Set **projectId** to your watsonx project ID. + - Set **API Key** to your watsonx Username and Password using `username:password` as format. ## Configuration -Add the following configuration to your `config.json` file to use the watsonx provider. Fill in the `watsonxCreds` with the authentication details you obtained in the setup step. +Add the following configuration to your `config.json` file to use the watsonx provider. ```json title="~/.continue/config.json" { @@ -46,39 +46,101 @@ Add the following configuration to your `config.json` file to use the watsonx pr { "model": "model ID", "title": "watsonx - Model Name", - "watsonxUrl": "watsonx endpoint e.g. https://us-south.ml.cloud.ibm.com", - "watsonxProjectId": "PROJECT_ID", - "watsonxCreds": "API_KEY/ZENAPI_KEY/USERNAME:PASSWORD", - "watsonxApiVersion": "2023-05-29", - "provider": "watsonx" + "provider": "watsonx", + "apiBase": "watsonx endpoint e.g. https://us-south.ml.cloud.ibm.com", + "projectId": "PROJECT_ID", + "apiKey": "API_KEY/ZENAPI_KEY/USERNAME:PASSWORD", + "apiVersion": "2024-03-14" } ] } ``` -`watsonxAPIVersion` is optional and defaults to the latest version. +`apiVersion` is optional and defaults to the latest version. + + +If you are using a custom deployment endpoint, set `deploymentID` to the model's deployment ID. You can find it in the watsonx.ai Prompt Lab UI by selecting the corresponding model and opening the `` tab on the right, which will display the endpoint's URL containing the deployment ID. + +```json title="~/.continue/config.json" +{ + "models": [ + { + "model": "model ID", + "title": "watsonx - Model Name", + "provider": "watsonx", + "apiBase": "watsonx endpoint e.g. https://us-south.ml.cloud.ibm.com", + "apiKey": "API_KEY/ZENAPI_KEY/USERNAME:PASSWORD", + "apiVersion": "2024-03-14", + "deploymentId": "DEPLOYMENT_ID" + } + ] +} +``` ### Configuration Options -Add the full watsonx URL to `watsonxFullUrl` if you are using a custom endpoint. When `watsonxFullUrl` is set, `watsonxUrl` and `watsonxApiVersion` are ignored. +Make sure to specify a template name, such as `granite` or `llama3`, and to set the `contextLength` to the model's context window size. +You can also configure generation parameters, such as temperature, topP, topK, frequency penalty, and stop sequences: ```json title="~/.continue/config.json" { "models": [ { - "model": "model ID", - "title": "watsonx - Model Name", - "watsonxUrl": "watsonx endpoint e.g. https://us-south.ml.cloud.ibm.com", - "watsonxProjectId": "PROJECT_ID", - "watsonxCreds": "API_KEY", - "watsonxApiVersion": "2023-05-29", + "model": "ibm/granite-20b-code-instruct", + "title": "Granite Code 20b", "provider": "watsonx", - "watsonxFullUrl": "https://us-south.ml.cloud.ibm.com/m1/v1/text/generation" + "apiBase": "watsonx endpoint e.g. https://us-south.ml.cloud.ibm.com", + "projectId": "PROJECT_ID", + "apiKey": "API_KEY/ZENAPI_KEY/USERNAME:PASSWORD", + "apiVersion": "2024-03-14", + "template": "granite", + "contextLength": 8000, + "completionOptions": { + "temperature": 0.1, + "topP": 0.3, + "topK": 20, + "maxTokens": 2000, + "frequencyPenalty": 1.1, + "stop": [ + "Question:", + "\n\n\n" + ] + } } ] } ``` -## Usage +## Tab Auto Complete Model -![usage-gif](../assets/watsonx2.gif) +Granite models are recommended for tab auto complete. The configuration is similar to that of the chat models: +```json title="~/.continue/config.json" +{ + "tabAutocompleteModel": { + "model": "ibm/granite-8b-code-instruct", + "title": "Granite Code 8b", + "provider": "watsonx", + "apiBase": "watsonx endpoint e.g. https://us-south.ml.cloud.ibm.com", + "projectId": "PROJECT_ID", + "apiKey": "API_KEY/ZENAPI_KEY/USERNAME:PASSWORD", + "apiVersion": "2024-03-14", + "contextLength": 4000 + } +} +``` + +## Embeddings Model + +To view the list of available embeddings models, visit [this page](https://dataplatform.cloud.ibm.com/docs/content/wsj/analyze-data/fm-models-embed.html?context=wx&pos=2#ibm-provided). +```json title="~/.continue/config.json +{ + "embeddingsProvider": { + "provider": "watsonx", + "model": "ibm/slate-30m-english-rtrvr-v2", + "apiBase": "watsonx endpoint e.g. https://us-south.ml.cloud.ibm.com", + "projectId": "PROJECT_ID", + "apiKey": "API_KEY/ZENAPI_KEY/USERNAME:PASSWORD", + "apiVersion": "2024-03-14" + } +} +``` diff --git a/docs/docs/customize/model-providers/top-level/openai.md b/docs/docs/customize/model-providers/top-level/openai.md index d594f4f39..6b31b0b22 100644 --- a/docs/docs/customize/model-providers/top-level/openai.md +++ b/docs/docs/customize/model-providers/top-level/openai.md @@ -63,6 +63,7 @@ OpenAI compatible servers - [llama-cpp-python](https://github.com/abetlen/llama-cpp-python#web-server) - [TensorRT-LLM](https://github.com/NVIDIA/trt-llm-as-openai-windows?tab=readme-ov-file#examples) - [vLLM](https://docs.vllm.ai/en/latest/serving/openai_compatible_server.html) +- [BerriAI/litellm](https://github.com/BerriAI/litellm) OpenAI compatible APIs diff --git a/docs/docs/customize/model-providers/more/mistral-vertexai.md b/docs/docs/customize/model-providers/top-level/vertexai.md similarity index 68% rename from docs/docs/customize/model-providers/more/mistral-vertexai.md rename to docs/docs/customize/model-providers/top-level/vertexai.md index 8d64c7ffe..1778ce3c6 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,38 +11,38 @@ 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 **Claude 3.5 Sonnet** as your chat model. ```json title="config.json" { "models": [ { - "title": "Mistral Large (Vertex AI)", - "provider": "mistral-vertexai", - "model": "mistral-large", + "title": "Claude 3.5 Sonnet", + "provider": "vertexai", + "model": "claude-3-5-sonnet-20240620", "projectId": "[PROJECT_ID]", - "region": "us-central1" + "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" } } ``` - ## Embeddings model We recommend configuring **text-embedding-004** as your embeddings model. @@ -50,7 +50,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 +60,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..4bcc88785 100644 --- a/docs/docs/customize/model-types/embeddings.md +++ b/docs/docs/customize/model-types/embeddings.md @@ -9,6 +9,10 @@ An "embeddings model" is trained to convert a piece of text into a vector, which In Continue, embeddings are generated during indexing and then used by [@Codebase](../deep-dives/codebase.md) to perform similarity search over your codebase. +:::info[Default model (VS Code only)] +`transformers.js` is used as a default embeddings model in VS Code. In JetBrains, there currently is no default. +::: + ## Recommended embedding models If you have the ability to use any model, we recommend `voyage-code-2`, which is listed below along with the rest of the options for embeddings models. @@ -35,7 +39,7 @@ See [here](../model-providers/top-level/ollama.md#embeddings-model) for instruct ### Transformers.js (currently VS Code only) -[Transformers.js](https://huggingface.co/docs/transformers.js/index) is a JavaScript port of the popular [Transformers](https://huggingface.co/transformers/) library. It allows embeddings to be calculated entirely locally. The model used is `all-MiniLM-L6-v2`, which is shipped alongside the Continue extension and used as the default when you have not explicitly configured an embeddings provider. +[Transformers.js](https://huggingface.co/docs/transformers.js/index) is a JavaScript port of the popular [Transformers](https://huggingface.co/transformers/) library. It allows embeddings to be calculated entirely locally. The model used is `all-MiniLM-L6-v2`, which is shipped alongside the Continue extension. ```json title="config.json" { @@ -72,4 +76,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. diff --git a/docs/docs/customize/overview.md b/docs/docs/customize/overview.md index 04183a427..4f231d55c 100644 --- a/docs/docs/customize/overview.md +++ b/docs/docs/customize/overview.md @@ -8,16 +8,16 @@ Continue can be deeply customized. This is primarily accomplished by editing a l ## Getting started -To open `config.json`, click the "gear" icon in the bottom right corner of the Continue Chat sidebar. When editing this file, you can use IntelliSense to see the available options as you type, or you can check the [full reference](./config.mdx). +To open `config.json`, click the "gear" icon in the bottom right corner of the Continue Chat sidebar. When editing this file, you can see the available options suggested as you type, or you can check the [full reference](./deep-dives/ways-to-configure.md). When you save `config.json`, Continue will automatically refresh to take into account your changes. ## Per-workspace configuration -If you'd like to scope certain settings to a particular workspace, you can add a `.continuerc.json` to the root of your project. It has the same [definition](./config.mdx) as `config.json`, and will automatically be applied on top of the local config.json. +If you'd like to scope certain settings to a particular workspace, you can add a `.continuerc.json` to the root of your project. It has the same [definition](./deep-dives/ways-to-configure.md) as `config.json`, and will automatically be applied on top of the local config.json. ## Programmatic configuration `config.json` can handle the vast majority of necessary configuration, so we recommend using it whenever possible. However, if you need to programmatically configure Continue, you can use `config.ts`, which is located at `~/.continue/config.ts` (MacOS / Linux) or `%USERPROFILE%\.continue\config.ts` (Windows). -For examples of how to use `config.ts`, see [writing custom slash commands](./tutorials/build-your-own-slash-command.md#custom-slash-commands) or [writing custom context providers](./tutorials/build-your-own-context-provider.md). \ No newline at end of file +For examples of how to use `config.ts`, see [writing custom slash commands](./tutorials/build-your-own-slash-command.md#custom-slash-commands) or [writing custom context providers](./tutorials/build-your-own-context-provider.md). diff --git a/docs/docs/customize/tutorials/llama3.1.md b/docs/docs/customize/tutorials/llama3.1.md index 1ad6a1dc9..2cec71cda 100644 --- a/docs/docs/customize/tutorials/llama3.1.md +++ b/docs/docs/customize/tutorials/llama3.1.md @@ -4,7 +4,7 @@ description: How to use Llama 3.1 with Continue keywords: [llama, meta, togetherai, ollama, replicate] --- -Continue makes it easy to code with the latest open-source models, including the entire Llama 3.1 family of models. +Continue makes it easy to code with the latest open-source models, including the entire Llama 3.1 family of models. Llama 3.2 models are also supported but not recommended for chat, because they are specifically designed to be small or multi-modal. If you haven't already installed Continue, you can do that [here for VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) or [here for JetBrains](https://plugins.jetbrains.com/plugin/22707-continue). For more general information on customizing Continue, read [our customization docs](../overview.md). diff --git a/docs/docs/edit/model-setup.md b/docs/docs/edit/model-setup.md index ce5e18e18..ded10c2a4 100644 --- a/docs/docs/edit/model-setup.md +++ b/docs/docs/edit/model-setup.md @@ -7,4 +7,4 @@ keywords: [edit, cmd l, model] By default, Edit uses the [same model as Chat](chat/model-setup.mdx) since we recommend a similar, 400B+ parameter model or one of the frontier model for code edits. -You can configure a different model to be used for edits by updating your [`config.json`](../customize/config.mdx). +You can configure a different model to be used for edits by updating your [`config.json`](../reference.md). diff --git a/docs/docs/reference.md b/docs/docs/reference.md new file mode 100644 index 000000000..71d0cc8b8 --- /dev/null +++ b/docs/docs/reference.md @@ -0,0 +1,449 @@ +--- +title: Reference +description: Reference for the Continue _config.json_ configuration file +keywords: [config, config_schema.json, json] +--- + +Below are details for each property that can be set in `config.json`. The config schema code is found in [`extensions/vscode/config_schema.json`](https://github.com/continuedev/continue/blob/main/extensions/vscode/config_schema.json). + +**All properties at all levels are optional unless explicitly marked required** + +### `models` + +Your **chat** models are defined here, which are used for [Chat](../chat/how-to-use-it.md), [Edit](../edit/how-to-use-it.md), and [Actions](../actions/how-to-use-it.md). +Each model has specific configuration options tailored to its provider and functionality, which can be seen as suggestions while editing the json. + +**Properties:** + +- `title` (**required**): The title to assign to your model, shown in dropdowns, etc. +- `provider` (**required**): The provider of the model, which determines the type and interaction method. Options inclued `openai`, `ollama`, etc., see intelliJ suggestions. +- `model` (**required**): The name of the model, used for prompt template auto-detection. +- `apiKey`: API key required by providers like OpenAI, Anthropic, and Cohere. +- `apiBase`: The base URL of the LLM API. +- `contextLength`: Maximum context length of the model, typically in tokens (default: 2048). +- `maxStopWords`: Maximum number of stop words allowed, to avoid API errors with extensive lists. +- `template`: Chat template to format messages. Auto-detected for most models but can be overridden. See intelliJ suggestions. +- `promptTemplates`: A mapping of prompt template names (e.g., `edit`) to template strings. [Customization Guide](https://docs.continue.dev/model-setup/configuration#customizing-the-edit-prompt). +- `completionOptions`: Model-specific completion options, same format as top-level [`completionOptions`](#completionoptions), which they override. +- `systemMessage`: A system message that will precede responses from the LLM. +- `requestOptions`: Model-specific HTTP request options, same format as top-level [`requestOptions`](#requestoptions), which they override. +- `apiType`: Specifies the type of API (`openai` or `azure`). +- `apiVersion`: Azure API version (e.g., `2023-07-01-preview`). +- `engine`: Engine for Azure OpenAI requests. +- `capabilities`: Override auto-detected capabilities: + - `uploadImage`: Boolean indicating if the model supports image uploads. + +_(AWS Only)_ + +- `profile`: AWS security profile for authorization. +- `modelArn`: AWS ARN for imported models (e.g., for `bedrockimport` provider). +- `region`: Region where the model is hosted (e.g., `us-east-1`, `eu-central-1`). + +Example: + +```json title="config.json" +{ + "models": [ + { + "title": "Ollama", + "provider": "ollama", + "model": "AUTODETECT" + }, + { + "model": "gpt-4o", + "contextLength": 128000, + "title": "GPT-4o", + "provider": "openai", + "apiKey": "YOUR_API_KEY" + } + ] +} +``` + +### `tabAutocompleteModel` + +Specifies the model or models for tab autocompletion, defaulting to an Ollama instance. This property uses the same format as `models`. Can be an array of models or an object for one model. + +Example + +```json title="config.json" +{ + "tabAutocompleteModel": { + "title": "My Starcoder", + "provider": "ollama", + "model": "starcoder2:3b" + } +} +``` + +### `tabAutocompleteOptions` + +Specifies options for tab autocompletion behavior. + +**Properties:** + +- `disable`: If `true`, disables tab autocomplete (default: `false`). +- `useCopyBuffer`: If `true`, includes the copy buffer in the prompt. +- `useFileSuffix`: If `true`, includes file suffix in the prompt. +- `maxPromptTokens`: Maximum number of tokens for the prompt. +- `debounceDelay`: Delay (in ms) before triggering autocomplete. +- `maxSuffixPercentage`: Maximum percentage of prompt for suffix. +- `prefixPercentage`: Percentage of input for prefix. +- `template`: Template string for autocomplete, using Mustache templating. +- `multilineCompletions`: Controls multiline completions (`"always"`, `"never"`, or `"auto"`). +- `useCache`: If `true`, caches completions. +- `onlyMyCode`: If `true`, only includes code within the repository. +- `useOtherFiles`: If `true`, includes snippets from other files (default: `true`). +- `disableInFiles`: Array of glob patterns for files where autocomplete is disabled. + +Example + +```json title="config.json" +{ + "tabAutocompleteOptions": { + "debounceDelay": 500, + "maxPromptTokens": 1500, + "disableInFiles": ["*.md"] + } +} +``` + +### `embeddingsProvider` + +Embeddings model settings - the model used for @Codebase and @docs. + +**Properties:** + +- `provider` (**required**): Specifies the embeddings provider, with options including `transformers.js`, `ollama`, `openai`, `cohere`, `free-trial`, `gemini`, etc +- `model`: Model name for embeddings. +- `apiKey`: API key for the provider. +- `apiBase`: Base URL for API requests. +- `requestOptions`: Additional HTTP request settings specific to the embeddings provider. +- `maxChunkSize`: Maximum tokens per document chunk. Minimum is 128 tokens. +- `maxBatchSize`: Maximum number of chunks per request. Minimum is 1 chunk. + +(AWS ONLY) + +- `region`: Specifies the region hosting the model. +- `profile`: AWS security profile. + +Example: + +```json title="config.json" +{ + "embeddingsProvider": { + "provider": "openai", + "model": "text-embedding-ada-002", + "apiKey": "", + "maxChunkSize": 256, + "maxBatchSize": 5 + } +} +``` + +### `completionOptions` + +Parameters that control the behavior of text generation and completion settings. Top-level `completionOptions` apply to all models, _unless overridden at the model level_. + +**Properties:** + +- `stream`: Whether to stream the LLM response. Currently only respected by the `anthropic` and `ollama` providers; other providers will always stream (default: `true`). +- `temperature`: Controls the randomness of the completion. Higher values result in more diverse outputs. +- `topP`: The cumulative probability for nucleus sampling. Lower values limit responses to tokens within the top probability mass. +- `topK`: The maximum number of tokens considered at each step. Limits the generated text to tokens within this probability. +- `presencePenalty`: Discourages the model from generating tokens that have already appeared in the output. +- `frequencePenalty`: Penalizes tokens based on their frequency in the text, reducing repetition. +- `mirostat`: Enables Mirostat sampling, which controls the perplexity during text generation. Supported by Ollama, LM Studio, and llama.cpp providers (default: `0`, where `0` = disabled, `1` = Mirostat, and `2` = Mirostat 2.0). +- `stop`: An array of stop tokens that, when encountered, will terminate the completion. Allows specifying multiple end conditions. +- `maxTokens`: The maximum number of tokens to generate in a completion (default: `2048`). +- `numThreads`: The number of threads used during the generation process. Available only for Ollama as `num_thread`. +- `keepAlive`: For Ollama, this parameter sets the number of seconds to keep the model loaded after the last request, unloading it from memory if inactive (default: `1800` seconds, or 30 minutes). + +Example + +```json title="config.json" +{ + "completionOptions": { + "stream": false, + "temperature": 0.5 + } +} +``` + +### `requestOptions` + +Default HTTP request options that apply to all models and context providers, unless overridden at the model level. + +**Properties:** + +- `timeout`: Timeout for each request to the LLM (default: 7200 seconds). +- `verifySsl`: Whether to verify SSL certificates for requests. +- `caBundlePath`: Path to a custom CA bundle for HTTP requests - path to `.pem` file (or array of paths) +- `proxy`: Proxy URL to use for HTTP requests. +- `headers`: Custom headers for HTTP requests. +- `extraBodyProperties`: Additional properties to merge with the HTTP request body. +- `noProxy`: List of hostnames that should bypass the specified proxy. +- `clientCertificate`: Client certificate for HTTP requests. + + - `cert`: Path to the client certificate file. + - `key`: Path to the client certificate key file. + - `passphrase`: Optional passphrase for the client certificate key file. + +Example + +```json title="config.json" +{ + "requestOptions": { + "headers": { + "X-Auth-Token": "xxx" + } + } +} +``` + +### `reranker` + +Configuration for the reranker model used in response ranking. + +**Properties:** + +- `name` (**required**): Reranker name, e.g., `cohere`, `voyage`, `llm`, `free-trial`, `huggingface-tei` +- `params`: + - `model`: Model name + - `apiKey`: Api key + +Example + +```json title="config.json" +{ + "reranker": { + "name": "voyage", + "params": { + "model": "rerank-2", + "apiKey": "" + } + } +} +``` + +### `docs` + +List of documentation sites to index. + +**Properties:** + +- `title` (**required**): Title of the documentation site, displayed in dropdowns, etc. +- `startUrl` (**required**): Start page for crawling - usually root or intro page for docs +- `rootUrl`: Crawler will only index docs within this domain - pages that contain this URL +- `maxDepth`: Maximum depth for crawling. Default `3` +- `favicon`: URL for site favicon (default is `/favicon.ico` from `startUrl`). + +Example + +```json title="config.json" +"docs": [ + { + "title": "Continue", + "startUrl": "https://docs.continue.dev/intro", + "rootUrl": "https://docs.continue.dev", + "faviconUrl": "https://docs.continue.dev/favicon.ico", + } +] +``` + +### `analytics` + +Configuration for analytics tracking. + +**Properties:** + +- `provider`: Analytics provider (`"posthog"` or `"logstash"`). +- `url`: URL for analytics data. +- `clientKey`: Client key for analytics. + +### `slashCommands` + +Custom commands initiated by typing "/" in the sidebar. Commands include predefined functionality or may be user-defined. + +**Properties:** + +- `name`: The command name. Options include "issue", "share", "cmd", "edit", "comment", "http", "commit", and "review". +- `description`: Brief description of the command. +- `step`: (Deprecated) Used for built-in commands; set the name for pre-configured options. +- `params`: Additional parameters to configure command behavior (command-specific - see code for command) + +Example: + +```json title="config.json" +{ + "slashCommands": [ + { + "name": "commit", + "description": "Generate a commit message" + }, + { + "name": "comment", + "description": "Write comments for the selected code" + }, + { + "name": "share", + "description": "Export this session as markdown" + }, + { + "name": "cmd", + "description": "Generate a shell command" + } + ] +} +``` + +### `customCommands` + +User-defined commands for prompt shortcuts in the sidebar, allowing quick access to common actions. + +**Properties:** + +- `name`: The name of the custom command. +- `prompt`: Text prompt for the command. +- `description`: Brief description explaining the command's function. + +Example: + +```json title="config.json" +{ + "customCommands": [ + { + "name": "test", + "prompt": "Write a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.", + "description": "Write unit tests for highlighted code" + } + ] +} +``` + +### `contextProviders` + +List of the pre-defined context providers that will show up as options while typing in the chat, and their customization with `params`. + +**Properties:** + +- `name`: Name of the context provider, e.g. `docs` or `web` +- `params`: A context-provider-specific record of params to configure the context behavior + +Example + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "code", + "params": {} + }, + { + "name": "docs", + "params": {} + }, + { + "name": "diff", + "params": {} + }, + { + "name": "open", + "params": {} + } + ] +} +``` + +### `disableSessionTitles` + +Prevents generating summary titles for each chat session when set to `true`. + +### `ui` + +Customizable UI settings to control interface appearance and behavior. + +**Properties:** + +- `codeBlockToolbarPosition`: Sets the toolbar position within code blocks, either `top` (default) or `bottom`. +- `fontSize`: Specifies font size for UI elements. +- `displayRawMarkdown`: If `true`, shows raw markdown in responses. +- `showChatScrollbar`: If `true`, enables a scrollbar in the chat window. + +Example: + +```json title="config.json" +{ + "ui": { + "codeBlockToolbarPosition": "bottom", + "fontSize": 14, + "displayRawMarkdown": false + } +} +``` + +### `allowAnonymousTelemetry` + +When `true`, anonymous usage data is collected using Posthog, to improve features. Default is `true`. + +### `userToken` + +An optional token that identifies the user, primarily for authenticated services. + +### `systemMessage` + +Defines a system message that appears before every response from the language model, providing guidance or context. + +### `disableIndexing` + +Prevents indexing of the codebase, useful primarily for debugging purposes. + +### `experimental` + +Several experimental config parameters are available, as described below: + +`experimental`: + +- `defaultContext`: Defines the default context for the LLM. Uses the same format as `contextProviders` but includes an additional `query` property to specify custom query parameters.= +- `modelRoles`: + - `inlineEdit`: Model title for inline edits. + - `applyCodeBlock`: Model title for applying code blocks. + - `repoMapFileSelection`: Model title for repo map selections. +- `readResponseTTS`: If `true`, reads LLM responses aloud with TTS. Default is `true`. +- `promptPath`: Change the path to custom prompt files from the default ".prompts" +- `quickActions`: Array of custom quick actions + - `title` (**required**): Display title for the quick action. + - `prompt` (**required**): Prompt for quick action. + - `sendToChat`: If `true`, sends result to chat; else inserts in document. Default is `false`. +- `contextMenuPrompts`: + - `comment`: Prompt for commenting code. + - `docstring`: Prompt for adding docstrings. + - `fix`: Prompt for fixing code. + - `optimize`: Prompt for optimizing code. + - `fixGrammar`: Prompt for fixing grammar or spelling. +- `useChromiumForDocsCrawling`: Use chromium to crawl docs instead of default lighter-weight tool that can't render sites. Downloads and installs Chromium to `~/.continue/.utils`. + +Example + +```json title="config.json" +{ + "experimental": { + "modelRoles": { + "inlineEdit": "Edit Model" + }, + "promptPath": "custom/.prompts", + "quickActions": [ + { + "title": "Tags", + "prompt": "Return a list of any function and class names from the included code block", + "sendToChat": true + } + ], + "contextMenuPrompts": { + "fixGrammar": "Fix grammar in the above but allow for typos." + }, + "readResponseTTS": false, + "useChromiumForDocsCrawling": true + } +} +``` diff --git a/docs/docusaurus.config.js b/docs/docusaurus.config.js index 5af3b8a2d..b4e5b7278 100644 --- a/docs/docusaurus.config.js +++ b/docs/docusaurus.config.js @@ -34,7 +34,7 @@ const config = { locales: ["en"], }, - themes: [["docusaurus-json-schema-plugin", {}]], + themes: [], presets: [ [ @@ -91,6 +91,13 @@ const config = { label: "Customize", href: "/customize/overview", }, + { + type: "docSidebar", + sidebarId: "customizingSidebar", + position: "left", + label: "Reference", + href: "/reference", + }, { to: "https://github.com/continuedev/continue", label: "GitHub", @@ -230,7 +237,7 @@ const config = { from: "/changelog", }, { - to: "/customize/config", + to: "/reference", from: ["/customization/code-config", "/reference/config"], }, { diff --git a/docs/package.json b/docs/package.json index 423c60bde..23af5df45 100644 --- a/docs/package.json +++ b/docs/package.json @@ -21,7 +21,6 @@ "@docusaurus/preset-classic": "^3.5.2", "@mdx-js/react": "^3.0.0", "clsx": "^2.1.0", - "docusaurus-json-schema-plugin": "^1.11.0", "prism-react-renderer": "^2.3.1", "react": "^18.2.0", "react-dom": "^18.2.0" @@ -46,4 +45,4 @@ "engines": { "node": ">=20.11.0" } -} +} \ No newline at end of file diff --git a/docs/sidebars.js b/docs/sidebars.js index 755d7f720..10db5727d 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -131,7 +131,6 @@ const sidebars = { }, ], }, - "customize/config", "customize/changelog", ], }; diff --git a/docs/static/schemas/config.json b/docs/static/schemas/config.json deleted file mode 100644 index 6da984ead..000000000 --- a/docs/static/schemas/config.json +++ /dev/null @@ -1,2946 +0,0 @@ -{ - "title": "config.json", - "$ref": "#/definitions/SerializedContinueConfig", - "definitions": { - "BaseCompletionOptions": { - "title": "BaseCompletionOptions", - "type": "object", - "properties": { - "stream": { - "title": "Stream", - "description": "Whether to stream the LLM response. Currently only respected by the 'anthropic' provider. Otherwise will always stream.", - "type": "boolean", - "default": true - }, - "temperature": { - "title": "Temperature", - "description": "The temperature of the completion.", - "type": "number" - }, - "topP": { - "title": "Top P", - "description": "The topP of the completion.", - "type": "number" - }, - "topK": { - "title": "Top K", - "description": "The topK of the completion.", - "type": "integer" - }, - "presencePenalty": { - "title": "Presence Penalty", - "description": "The presence penalty Aof the completion.", - "type": "number" - }, - "frequencePenalty": { - "title": "Frequency Penalty", - "description": "The frequency penalty of the completion.", - "type": "number" - }, - "mirostat": { - "title": "Mirostat", - "description": "Enable Mirostat sampling, controlling perplexity during text generation (default: 0, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0). Only available for Ollama, LM Studio, and llama.cpp providers", - "type": "number" - }, - "stop": { - "title": "Stop", - "description": "The stop tokens of the completion.", - "type": "array", - "items": { - "type": "string" - } - }, - "maxTokens": { - "title": "Max Tokens", - "description": "The maximum number of tokens to generate.", - "default": 600, - "type": "integer" - }, - "numThreads": { - "title": "Number of threads", - "description": "The number of threads used in the generation process. Only available for Ollama (this is the num_thread parameter)", - "type": "integer" - }, - "keepAlive": { - "title": "Ollama keep_alive", - "description": "The number of seconds after no requests are made to unload the model from memory. Defaults to 60*30 = 30min", - "type": "integer" - } - } - }, - "ClientCertificateOptions": { - "title": "ClientCertificateOptions", - "type": "object", - "properties": { - "cert": { - "title": "Cert Path", - "description": "Path to the client certificate file", - "type": "string" - }, - "key": { - "title": "Key Path", - "description": "Path to the client certificate key file", - "type": "string" - }, - "passphrase": { - "title": "Passphrase", - "description": "Passphrase for the client certificate key file", - "type": "string" - } - }, - "required": ["cert", "key"] - }, - "RequestOptions": { - "title": "RequestOptions", - "type": "object", - "properties": { - "timeout": { - "title": "Timeout", - "description": "Set the timeout for each request to the LLM. If you are running a local LLM that takes a while to respond, you might want to set this to avoid timeouts.", - "default": 7200, - "type": "integer" - }, - "verifySsl": { - "title": "Verify Ssl", - "description": "Whether to verify SSL certificates for requests.", - "type": "boolean" - }, - "caBundlePath": { - "title": "Ca Bundle Path", - "description": "Path to a custom CA bundle to use when making the HTTP request", - "anyOf": [ - { - "type": "string" - }, - { - "type": "array", - "items": { - "type": "string" - } - } - ] - }, - "proxy": { - "title": "Proxy", - "description": "Proxy URL to use when making the HTTP request", - "type": "string" - }, - "headers": { - "title": "Headers", - "description": "Headers to use when making the HTTP request", - "type": "object", - "additionalProperties": { - "type": "string" - } - }, - "extraBodyProperties": { - "title": "Extra Body Properties", - "description": "This object will be merged with the body when making the HTTP requests", - "type": "object" - }, - "noProxy": { - "title": "No Proxy", - "description": "A list of hostnames for which Continue should not use the proxy specified in requestOptions.proxy", - "type": "array", - "items": { - "type": "string" - } - }, - "clientCertificate": { - "title": "Client Certificate", - "description": "Client certificate to use when making the HTTP request", - "$ref": "#/definitions/ClientCertificateOptions" - } - } - }, - "ModelDescription": { - "title": "ModelDescription", - "type": "object", - "properties": { - "title": { - "title": "Title", - "description": "The title you wish to give your model.", - "type": "string" - }, - "provider": { - "title": "Provider", - "description": "The provider of the model. This is used to determine the type of model, and how to interact with it.", - "enum": [ - "openai", - "free-trial", - "anthropic", - "anthropic-vertexai", - "cohere", - "bedrock", - "bedrockimport", - "sagemaker", - "together", - "ollama", - "huggingface-tgi", - "huggingface-inference-api", - "llama.cpp", - "replicate", - "gemini", - "gemini-vertexai", - "lmstudio", - "llamafile", - "mistral", - "mistral-vertexai", - "deepinfra", - "groq", - "fireworks", - "cloudflare", - "deepseek", - "azure", - "msty", - "watsonx", - "openrouter", - "sambanova", - "nvidia", - "vllm", - "cerebras" - ], - "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)", - "### Free Trial\nNew users can try out Continue for free using a proxy server that securely makes calls to OpenAI using our API key. If you are ready to use your own API key or have used all 250 free uses, you can enter your API key in config.json where it says `apiKey=\"\"` or select another model provider.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/freetrial)", - "### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)", - "### Anthropic Vertex AI\nTo get started 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).", - "### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)", - "### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock)", - "### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock)", - "### Sagemaker\nSagemaker is AWS' machine learning platform.", - "### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/togetherllm)", - "### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run `. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)", - "### Huggingface TGI\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/huggingfacetgi)", - "### Huggingface Inference API\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/huggingfaceinferenceapi)", - "### Llama.cpp\nllama.cpp comes with a [built-in server](https://github.com/ggerganov/llama.cpp/tree/master/examples/server#llamacppexampleserver) that can be run from source. To do this:\n\n1. Clone the repository with `git clone https://github.com/ggerganov/llama.cpp`.\n2. `cd llama.cpp`\n3. Run `make` to build the server.\n4. Download the model you'd like to use and place it in the `llama.cpp/models` directory (the best place to find models is [The Bloke on HuggingFace](https://huggingface.co/TheBloke))\n5. Run the llama.cpp server with the command below (replacing with the model you downloaded):\n\n```shell\n.\\server.exe -c 4096 --host 0.0.0.0 -t 16 --mlock -m models/codellama-7b-instruct.Q8_0.gguf\n```\n\nAfter it's up and running, you can start using Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/llamacpp)", - "### Replicate\nReplicate is a hosted service that makes it easy to run ML models. To get started with Replicate:\n1. Obtain an API key from [here](https://replicate.com)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/replicatellm)", - "### Gemini API\nTo get started with Google Makersuite, obtain your API key from [here](https://makersuite.google.com) and paste it below.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/geminiapi)", - "### Gemini API on Vertex AI\nTo get started 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).", - "### LMStudio\nLMStudio provides a professional and well-designed GUI for exploring, configuring, and serving LLMs. It is available on both Mac and Windows. To get started:\n1. Download from [lmstudio.ai](https://lmstudio.ai/) and open the application\n2. Search for and download the desired model from the home screen of LMStudio.\n3. In the left-bar, click the '<->' icon to open the Local Inference Server and press 'Start Server'.\n4. Once your model is loaded and the server has started, you can begin using Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/lmstudio)", - "### Llamafile\nTo get started with llamafiles, find and download a binary on their [GitHub repo](https://github.com/Mozilla-Ocho/llamafile#binary-instructions). Then run it with the following command:\n\n```shell\nchmod +x ./llamafile\n./llamafile\n```\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/llamafile)", - "### Mistral API\n\nTo get access to the Mistral API, obtain your API key from the [Mistral platform](https://docs.mistral.ai/)", - "### Mistral API on Vertex AI\nTo get started 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).", - "### DeepInfra\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/deepinfra)", - "### Groq\nGroq provides extremely fast inference of open-source language models. To get started, obtain an API key from [their console](https://console.groq.com/keys).", - "### Fireworks\nFireworks is a fast inference engine for open-source language models. To get started, obtain an API key from [their console](https://fireworks.ai/api-keys).", - "### Cloudflare Workers AI\n\n[Reference](https://developers.cloudflare.com/workers-ai/)", - "### Deepseek\n Deepseek's API provides the best pricing for their state-of-the-art Deepseek Coder models. To get started, obtain an API key from [their console](https://platform.deepseek.com/api_keys)", - "### Azure OpenAI\n Azure OpenAI lets you securely run OpenAI's models on Azure. To get started, follow the steps [here](https://docs.continue.dev/reference/Model%20Providers/azure)", - "### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)", - "### IBM watsonx\nwatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.", - "### OpenRouter\nOpenRouter offers a single API to access almost any language model. To get started, obtain an API key from [their console](https://openrouter.ai/settings/keys).", - "### NVIDIA NIMs\nNVIDIA offers a single API to access almost any language model. To find out more, visit the [LLM APIs Documentation](https://docs.api.nvidia.com/nim/reference/llm-apis).\nFor information specific to getting a key, please check out the [docs here](https://docs.nvidia.com/nim/large-language-models/latest/getting-started.html#option-1-from-api-catalog)", - "### vLLM\nvLLM is a highly performant way of hosting LLMs for a team. To get started, follow their [quickstart](https://docs.vllm.ai/en/latest/getting_started/quickstart.html) to set up your server.", - "### Cerebras\nCerebras Inference uses specialized silicon to provides superfast inference. To get started, get your API keys from [their console](https://cloud.cerebras.ai/)." - ], - "type": "string" - }, - "model": { - "title": "Model", - "description": "The name of the model. Used to autodetect prompt template.", - "type": "string" - }, - "apiKey": { - "title": "Api Key", - "description": "OpenAI, Anthropic, Cohere, Together, or other API key", - "type": "string" - }, - "apiBase": { - "title": "Api Base", - "description": "The base URL of the LLM API.", - "type": "string" - }, - "region": { - "title": "Region", - "description": "The region where the model is hosted", - "anyOf": [ - { - "enum": [ - "us-east-1", - "us-east-2", - "us-west-1", - "us-west-2", - "eu-west-1", - "eu-central-1", - "ap-southeast-1", - "ap-northeast-1", - "ap-south-1", - "us-central1", - "us-east1", - "us-east4", - "us-east5", - "us-west1", - "us-west4", - "us-south1", - "northamerica-northeast1", - "southamerica-east1", - "europe-central2", - "europe-north1", - "europe-west1", - "europe-west2", - "europe-west3", - "europe-west4", - "europe-west6", - "europe-west8", - "europe-west9", - "europe-southwest1", - "asia-east1", - "asia-east2", - "asia-south1", - "asia-northeast1", - "asia-northeast3", - "asia-southeast1", - "australia-southeast1", - "me-central1", - "me-central2", - "me-west1" - ], - "type": "string" - }, - { - "type": "string" - } - ] - }, - "profile": { - "title": "Profile", - "description": "The AWS security profile to use", - "type": "string" - }, - "modelArn": { - "title": "Profile", - "description": "The AWS arn for the imported model", - "type": "string" - }, - "contextLength": { - "title": "Context Length", - "description": "The maximum context length of the LLM in tokens, as counted by countTokens.", - "default": 2048, - "type": "integer" - }, - "maxStopWords": { - "title": "Max Stop Words", - "description": "The maximum number of stop words that the API will accept. You can set this if you are receiving an error about the number of stop words, but otherwise should leave it undefined.", - "type": "integer" - }, - "template": { - "title": "Template", - "description": "The chat template used to format messages. This is auto-detected for most models, but can be overridden here. Choose none if you are using vLLM or another server that automatically handles prompting.", - "enum": [ - "llama2", - "alpaca", - "zephyr", - "phi2", - "phind", - "anthropic", - "chatml", - "none", - "deepseek", - "openchat", - "xwin-coder", - "neural-chat", - "codellama-70b", - "llava", - "gemma", - "llama3" - ], - "type": "string" - }, - "promptTemplates": { - "title": "Prompt Templates", - "markdownDescription": "A mapping of prompt template name ('edit' is currently the only one used in Continue) to a string giving the prompt template. See [here](https://docs.continue.dev/model-setup/configuration#customizing-the-edit-prompt) for an example.", - "type": "object", - "additionalProperties": { - "type": "string" - } - }, - "completionOptions": { - "title": "Completion Options", - "description": "Options for the completion endpoint. Read more about the completion options in the documentation.", - "default": { - "temperature": null, - "topP": null, - "topK": null, - "presencePenalty": null, - "frequencyPenalty": null, - "stop": null, - "maxTokens": 600 - }, - "allOf": [ - { - "$ref": "#/definitions/BaseCompletionOptions" - } - ] - }, - "systemMessage": { - "title": "System Message", - "description": "A system message that will always be followed by the LLM", - "type": "string" - }, - "requestOptions": { - "title": "Request Options", - "description": "Options for the HTTP request to the LLM.", - "default": { - "timeout": 7200, - "verifySsl": null, - "caBundlePath": null, - "proxy": null, - "headers": null, - "extraBodyProperties": null - }, - "allOf": [ - { - "$ref": "#/definitions/RequestOptions" - } - ] - }, - "apiType": { - "title": "Api Type", - "markdownDescription": "OpenAI API type, either `openai` or `azure`", - "enum": ["openai", "azure"] - }, - "apiVersion": { - "title": "Api Version", - "description": "Azure OpenAI API version (e.g. 2023-07-01-preview)", - "type": "string" - }, - "engine": { - "title": "Engine", - "description": "Azure OpenAI engine", - "type": "string" - }, - "capabilities": { - "type": "object", - "description": "We will attempt to automatically detect the capabilities of the model based on its title and provider, but this may not always be accurate. You can override the model's capabilities here.", - "properties": { - "uploadImage": { - "type": "boolean", - "description": "Indicates whether the model can upload images." - } - } - } - }, - "required": ["title", "provider", "model"], - "allOf": [ - { - "if": { - "properties": { - "provider": { - "type": "str" - } - }, - "not": { - "required": ["provider"] - } - }, - "then": { - "properties": { - "model": { - "description": "Choose a provider first, then model options will be shown here." - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "openai", - "anthropic", - "cohere", - "gemini", - "huggingface-inference-api", - "replicate", - "together", - "cloudflare", - "sambanova" - ] - } - }, - "required": ["provider"] - }, - "then": { - "required": ["apiKey"] - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["bedrockimport"] - } - }, - "required": ["provider"] - }, - "then": { - "required": ["modelArn"] - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["huggingface-tgi", "huggingface-inference-api"] - } - } - }, - "then": { - "required": ["apiBase"] - }, - "required": ["provider"] - }, - { - "if": { - "properties": { - "provider": { - "enum": ["openai"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "engine": { - "type": "string" - }, - "apiType": { - "type": "string" - }, - "apiVersion": { - "type": "string" - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["cloudflare"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "accountId": { - "type": "string" - }, - "aiGatewaySlug": { - "type": "string" - }, - "model": { - "anyOf": [ - { - "enum": [ - "@cf/meta/llama-3-8b-instruct", - "@hf/thebloke/deepseek-coder-6.7b-instruct-awq", - "@cf/deepseek-ai/deepseek-math-7b-instruct", - "@cf/thebloke/discolm-german-7b-v1-awq", - "@cf/tiiuae/falcon-7b-instruct", - "@cf/google/gemma-2b-it-lora", - "@hf/google/gemma-7b-it", - "@cf/google/gemma-7b-it-lora", - "@hf/nousresearch/hermes-2-pro-mistral-7b", - "@cf/meta/llama-2-7b-chat-fp16", - "@cf/meta/llama-2-7b-chat-int8", - "@cf/meta-llama/llama-2-7b-chat-hf-lora", - "@hf/thebloke/llama-2-13b-chat-awq", - "@hf/thebloke/llamaguard-7b-awq", - "@cf/mistral/mistral-7b-instruct-v0.1", - "@hf/mistral/mistral-7b-instruct-v0.2", - "@cf/mistral/mistral-7b-instruct-v0.2-lora", - "@hf/thebloke/neural-chat-7b-v3-1-awq", - "@cf/openchat/openchat-3.5-0106", - "@hf/thebloke/openhermes-2.5-mistral-7b-awq", - "@cf/microsoft/phi-2", - "@cf/qwen/qwen1.5-0.5b-chat", - "@cf/qwen/qwen1.5-1.8b-chat", - "@cf/qwen/qwen1.5-7b-chat-awq", - "@cf/qwen/qwen1.5-14b-chat-awq", - "@cf/defog/sqlcoder-7b-2", - "@hf/nexusflow/starling-lm-7b-beta", - "@cf/tinyllama/tinyllama-1.1b-chat-v1.0", - "@hf/thebloke/zephyr-7b-beta-awq", - "@hf/thebloke/deepseek-coder-6.7b-base-awq" - ] - }, - { - "type": "string" - } - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["openai"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-4o", - "gpt-4o-mini", - "gpt-4", - "gpt-3.5-turbo-0613", - "gpt-4-32k", - "gpt-4-0125-preview", - "gpt-4-turbo", - "AUTODETECT" - ] - }, - { - "type": "string" - } - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["replicate"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "llama3.1-8b", - "llama3.1-70b", - "llama3.1-405b", - "llama3-8b", - "llama3-70b", - "codellama-7b", - "codellama-13b", - "codellama-34b", - "llama2-7b", - "llama2-13b" - ] - }, - { - "type": "string" - } - ] - }, - "markdownDescription": "Select a pre-defined option, or find an exact model ID from Replicate [here](https://replicate.com/collections/streaming-language-models)." - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["free-trial"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "enum": [ - "gpt-4o", - "codestral-latest", - "llama3.1-70b", - "llama3.1-405b", - "gpt-3.5-turbo", - "gemini-pro", - "claude-3-5-sonnet-20240620", - "claude-3-haiku-20240307", - "AUTODETECT" - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["openai"] - }, - "apiType": { - "not": { - "const": "azure" - } - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-4o", - "gpt-4o-mini", - "gpt-4", - "gpt-3.5-turbo-0613", - "gpt-4-32k", - "gpt-4-turbo", - "gpt-4-vision-preview", - "mistral-7b", - "mistral-8x7b", - "llama2-7b", - "llama2-13b", - "codellama-7b", - "codellama-13b", - "codellama-34b", - "codellama-70b", - "llama3-8b", - "llama3-70b", - "llama3.1-8b", - "llama3.1-70b", - "llama3.1-405b", - "phind-codellama-34b", - "wizardcoder-7b", - "wizardcoder-13b", - "wizardcoder-34b", - "zephyr-7b", - "codeup-13b", - "deepseek-7b", - "deepseek-33b", - "neural-chat-7b", - "deepseek-1b", - "stable-code-3b", - "starcoder-1b", - "starcoder-3b", - "starcoder2-3b", - "mistral-tiny", - "mistral-small", - "mistral-medium", - "AUTODETECT" - ] - }, - { - "type": "string" - } - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["anthropic"] - } - }, - "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-2", - "claude-instant-1", - "claude-3-5-sonnet-20240620", - "claude-3-opus-20240229", - "claude-3-sonnet-20240229", - "claude-3-haiku-20240307", - "claude-2.1" - ] - }, - { - "type": "string" - } - ] - } - } - } - }, - { - "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": { - "provider": { - "enum": ["cohere"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "enum": ["command-r", "command-r-plus"] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["bedrock"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "claude-3-sonnet-20240229", - "claude-3-haiku-20240307", - "claude-2" - ] - }, - { - "type": "string" - } - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["sagemaker"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "markdownDescription": "SageMaker endpoint name" - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["gemini"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "cacheBehavior": { - "title": "Caching Behavior", - "description": "Options for the prompt caching", - "properties": { - "cacheSystemMessage": { - "type": "boolean" - } - } - }, - "model": { - "enum": [ - "chat-bison-001", - "gemini-pro", - "gemini-1.5-pro-latest", - "gemini-1.5-pro", - "gemini-1.5-flash-latest", - "gemini-1.5-flash" - ] - } - } - } - }, - { - "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": { - "provider": { - "enum": ["together"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "mistral-7b", - "mistral-8x7b", - "llama2-7b", - "llama2-13b", - "llama3-8b", - "llama3-70b", - "llama3.1-8b", - "llama3.1-70b", - "llama3.1-405b", - "codellama-7b", - "codellama-13b", - "codellama-34b", - "codellama-70b", - "phind-codellama-34b" - ] - }, - { - "type": "string" - } - ], - "markdownDescription": "Select a pre-defined option, or find an exact model string from Together AI [here](https://docs.together.ai/docs/inference-models)." - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["deepinfra"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "markdownDescription": "Find the model name you want to use from DeepInfra [here](https://deepinfra.com/models?type=text-generation)." - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "huggingface-tgi", - "huggingface-inference-api", - "llama.cpp", - "text-gen-webui", - "llamafile" - ] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "mistral-7b", - "mistral-8x7b", - "llama2-7b", - "llama2-13b", - "codellama-7b", - "codellama-13b", - "codellama-34b", - "codellama-70b", - "llama3-8b", - "llama3-70b", - "llama3.1-8b", - "llama3.1-70b", - "llama3.1-405b", - "phind-codellama-34b", - "wizardcoder-7b", - "wizardcoder-13b", - "wizardcoder-34b", - "zephyr-7b", - "codeup-13b", - "deepseek-7b", - "deepseek-33b", - "neural-chat-7b", - "deepseek-1b", - "stable-code-3b", - "starcoder-1b", - "starcoder-3b", - "starcoder2-3b" - ] - }, - { - "type": "string" - } - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["ollama"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "mistral-7b", - "llama2-7b", - "llama2-13b", - "codellama-7b", - "codellama-13b", - "codellama-34b", - "codellama-70b", - "llama3-8b", - "llama3-70b", - "llama3.1-8b", - "llama3.1-70b", - "llama3.1-405b", - "phi-2", - "phind-codellama-34b", - "wizardcoder-7b", - "wizardcoder-13b", - "wizardcoder-34b", - "zephyr-7b", - "codeup-13b", - "deepseek-7b", - "deepseek-33b", - "neural-chat-7b", - "deepseek-1b", - "stable-code-3b", - "starcoder-1b", - "starcoder-3b", - "starcoder2-3b", - "AUTODETECT" - ] - }, - { - "type": "string" - } - ], - "markdownDescription": "Select a pre-defined option, or find the exact model tag for an Ollama model [here](https://ollama.ai/library)." - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["mistral"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "enum": [ - "codestral-latest", - "codestral-mamba-latest", - "open-mistral-7b", - "open-mixtral-8x7b", - "open-mixtral-8x22b", - "mistral-small-latest", - "mistral-large-latest" - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["mistral-vertexai"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "codestral", - "mistral-nemo", - "mistral-large" - ] - }, - { "type": "string" } - ] - } - }, - "required": ["projectId", "region"] - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["deepseek"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "cacheBehavior": { - "title": "Caching Behavior", - "description": "Options for the prompt caching", - "properties": { - "cacheSystemMessage": { - "type": "boolean" - }, - "cacheConversation": { - "type": "boolean" - } - } - }, - "model": { - "enum": ["deepseek-chat", "deepseek-coder"] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["groq"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "enum": [ - "llama2-70b", - "mistral-8x7b", - "gemma", - "gemma2", - "llama3-8b", - "llama3-70b", - "llama3.1-8b", - "llama3.1-70b", - "llama3.1-405b", - "AUTODETECT" - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["fireworks"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "enum": ["starcoder-7b"] - } - } - } - }, - { - "if": { - "properties": { - "apiType": { - "const": "azure" - } - }, - "required": ["apiType"] - }, - "then": { - "required": ["engine", "apiVersion", "apiBase"] - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["openai"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "useLegacyCompletionsEndpoint": { - "type": "boolean" - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "const": "llamafile" - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "llamafileCommand": { - "type": "string" - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["cerebras"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "enum": ["llama3.1-8b", "llama3.1-70b"] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["text-gen-webui"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "streamingUrl": { - "type": "string" - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["flowise"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "timeout": { - "title": "Timeout", - "description": "Set the timeout for each request to Flowise. If you are running a local version of Flowise it might takes a while to respond, you might want to set this to avoid timeouts.", - "default": 5000, - "type": "integer" - }, - "additionalHeaders": { - "description": "A list of additional headers", - "type": "array", - "items": { - "type": "object", - "properties": { - "key": { - "title": "Key", - "description": "Header key", - "type": "string" - }, - "value": { - "title": "Value", - "description": "Header value", - "type": "string" - } - }, - "required": ["key", "value"] - } - }, - "additionalFlowiseConfiguration": { - "description": "A list of additional properties to be sent along `overrideConfig`", - "type": "array", - "items": { - "type": "object", - "properties": { - "key": { - "title": "Key", - "description": "Configuration Property key", - "type": "string" - }, - "value": { - "title": "Value", - "description": "Configuration Property value" - } - }, - "required": ["key", "value"] - } - }, - "model": { - "anyOf": [ - { - "enum": [ - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-4o", - "gpt-4o-mini", - "gpt-4", - "gpt-3.5-turbo-0613", - "gpt-4-32k", - "gpt-4-turbo", - "gpt-4-vision-preview", - "mistral-7b", - "mistral-8x7b", - "llama2-7b", - "llama2-13b", - "codellama-7b", - "codellama-13b", - "codellama-34b", - "codellama-70b", - "llama3-8b", - "llama3-70b", - "llama3.1-8b", - "llama3.1-70b", - "llama3.1-405b", - "phind-codellama-34b", - "wizardcoder-7b", - "wizardcoder-13b", - "wizardcoder-34b", - "zephyr-7b", - "codeup-13b", - "deepseek-7b", - "deepseek-33b", - "claude-2", - "claude-instant-1", - "claude-3-5-sonnet-20240620", - "claude-3-opus-20240229", - "claude-3-sonnet-20240229", - "claude-3-haiku-20240307", - "claude-2.1", - "command-r", - "command-r-plus", - "chat-bison-001", - "gemini-pro", - "gemini-1.5-pro-latest", - "gemini-1.5-pro", - "gemini-1.5-flash-latest", - "gemini-1.5-flash", - "mistral-tiny", - "mistral-small", - "mistral-medium", - "deepseek-1b", - "stable-code-3b", - "starcoder-1b", - "starcoder-3b", - "starcoder2-3b" - ] - }, - { - "type": "string" - } - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["watsonx"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "watsonxUrl": { - "type": "string" - }, - "watsonxApiKey": { - "type": "string" - }, - "watsonxApiVersion": { - "type": "string" - }, - "watsonxProjectId": { - "type": "string" - }, - "watsonxStopToken": { - "type": "string" - }, - "watsonxFullUrl": { - "type": "string" - }, - "model": { - "enum": [ - "ibm/granite-13b-chat-v2", - "ibm/granite-20b-code-instruct", - "mistralai/mistral-large", - "meta-llama/llama-3-8b-instruct", - "meta-llama/llama-3-70b-instruct" - ] - } - }, - "required": ["watsonxUrl", "watsonxProjectId"] - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["sambanova"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": ["llama3.1-8b", "llama3.1-70b", "llama3.1-405b"] - }, - { - "type": "string" - } - ], - "markdownDescription": "Select a pre-defined option." - } - } - } - } - ] - }, - "ModelRoles": { - "title": "ModelRoles", - "type": "object", - "properties": { - "default": { - "title": "Default", - "description": "The default model. If other model roles are not set, they will fall back to default.", - "type": "string" - }, - "chat": { - "title": "Chat", - "description": "The model to use for chat. If not set, will fall back to default.", - "type": "string" - }, - "edit": { - "title": "Edit", - "description": "The model to use for editing. If not set, will fall back to default.", - "type": "string" - }, - "summarize": { - "title": "Summarize", - "description": "The model to use for summarization. If not set, will fall back to default.", - "type": "string" - } - }, - "required": ["default"] - }, - "SlashCommand": { - "title": "SlashCommand", - "type": "object", - "properties": { - "name": { - "title": "Name", - "anyOf": [ - { - "enum": [ - "issue", - "share", - "cmd", - "edit", - "comment", - "http", - "commit", - "review" - ], - "type": "string", - "markdownEnumDescriptions": [ - "Generate a link to a drafted GitHub issue", - "Export the current chat session to markdown", - "Generate a terminal command and paste it into the terminal", - "Edit the highlighted code with given instructions", - "Add comments to the highlighted code", - "Write a custom slash command at your own HTTP endpoint. Set 'url' in the params object for the endpoint you have setup.", - "Generate a commit message for the current changes", - "Review code and give feedback" - ] - }, - { - "type": "string" - } - ] - }, - "description": { - "title": "Description", - "type": "string" - }, - "step": { - "title": "Step", - "description": "This property is no longer required and has no effect. To use a built-in slash command, instead set the 'name' property to one of the pre-configured options.", - "type": "string" - }, - "params": { - "title": "Params", - "default": {}, - "type": "object" - } - }, - "allOf": [ - { - "if": { - "properties": { - "name": { - "enum": ["issue"] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "repositoryUrl": { - "type": "string", - "description": "Enter the URL of the GitHub repository for which you want to generate the issue." - } - }, - "required": ["repositoryUrl"] - } - }, - "required": ["params"] - } - }, - { - "if": { - "properties": { - "name": { - "enum": ["edit"] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "recap": { - "type": "boolean", - "markdownDescription": "If recap is set to `true`, Continue will generate a summary of the changes after making the edit." - }, - "tokenLimit": { - "type": "integer", - "markdownDescription": "By default, Continue doesn't let you edit extremely large ranges (beyond 1,200 tokens), because the LLM is unlikely to succeed. But if you would like to override this limit with the understanding of possible failure you may do so here." - } - } - } - } - } - }, - { - "if": { - "properties": { - "name": { - "enum": ["share"] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "outputDir": { - "type": "string", - "markdownDescription": "If outputDir is set to `.` or begins with `./` or `.\\`, file will be saved to the current workspace or a subdirectory thereof, respectively. `~` can similarly be used to specify the user's home directory." - } - } - } - } - } - }, - { - "if": { - "properties": { - "name": { - "enum": ["commit"] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "includeUnstaged": { - "type": "boolean", - "markdownDescription": "If includeUnstaged is set to true, then unstaged changes are also included in the prompt, otherwise only staged changes are included. Default is false." - } - } - } - } - } - } - ], - "required": ["name", "description"] - }, - "CustomCommand": { - "title": "CustomCommand", - "type": "object", - "properties": { - "name": { - "title": "Name", - "type": "string" - }, - "prompt": { - "title": "Prompt", - "type": "string" - }, - "description": { - "title": "Description", - "type": "string" - } - }, - "required": ["name", "prompt", "description"] - }, - "ContextProviderWithParams": { - "title": "ContextProviderWithParams", - "type": "object", - "properties": { - "name": { - "title": "Name", - "anyOf": [ - { - "enum": [ - "diff", - "terminal", - "debugger", - "open", - "google", - "search", - "http", - "codebase", - "problems", - "folder", - "issue", - "docs", - "tree", - "highlights", - "outline", - "postgres", - "code", - "currentFile", - "url", - "database", - "os", - "repo-map", - "greptile", - "web" - ], - "markdownEnumDescriptions": [ - "Reference the contents of the current changes as given by `git diff`", - "Reference the last terminal command", - "Reference the contents of the local variables in the debugger with top n level (defaulting to 3) of call stack for that thread", - "Reference the contents of all open or pinned files.", - "Enter a search phrase and include the Google search results as context", - "Reference the results of a ripgrep search in your codebase", - "Write a custom context provider at your own HTTP endpoint. Set 'url' in the params object for the endpoint you have setup.", - "Use embeddings to automatically find relevant files from throughout the codebase", - "Reference all linting errors and warnings in the currently open file", - "Include important files from a folder in the prompt, as determined by similarity search", - "Reference GitHub issues from a repository", - "Retrieve important pages from a documentation website, as determined by similarity search", - "Display a file tree of the current workspace", - "Include important highlighted sections from your code", - "Include a repo map showing important code objects", - "References Postgres table schema and sample rows", - "Reference specific functions and classes from throughout your codebase", - "Reference the contents of the currently active file", - "Reference the contents of a page at a URL", - "Reference table schemas", - "Operating system and CPU Information", - "Map of files in the repository with important code highlights", - "Query your greptile index of the current repo", - "Search the web for sources related to your question" - ], - "type": "string" - }, - { - "type": "string" - } - ] - }, - "params": { - "title": "Params", - "default": {}, - "type": "object" - } - }, - "allOf": [ - { - "if": { - "properties": { - "name": { - "enum": ["discord"] - } - } - }, - "then": { - "allOf": [ - { - "properties": { - "params": { - "properties": { - "discordKey": { - "type": "string", - "description": "Your Discord bot token to access the Discord API. Required to fetch messages from servers." - }, - "guildId": { - "type": "string", - "description": "The ID of the guild (server) from which to fetch channels and messages." - }, - "channels": { - "type": "array", - "description": "A list of channel objects to search for messages", - "items": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "The unique ID of the channel" - }, - "name": { - "type": "string", - "description": "The name of the channel" - } - }, - "required": ["id"] - } - } - }, - "required": ["discordKey"] - } - } - }, - { - "oneOf": [ - { - "properties": { - "params": { - "required": ["guildId"] - } - } - }, - { - "properties": { - "params": { - "required": ["channels"] - } - } - } - ] - } - ] - } - }, - { - "if": { - "properties": { - "name": { - "enum": ["google"] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "serperApiKey": { - "type": "string", - "description": "Your API key for https://serper.dev in order to get Google search results" - } - }, - "required": ["serperApiKey"] - } - }, - "required": ["params"] - } - }, - { - "if": { "properties": { "name": { "enum": ["web"] } } }, - "then": { - "properties": { - "params": { - "properties": { - "n": { - "title": "N", - "description": "The number of results to return", - "default": 6, - "type": "integer" - } - } - } - }, - "required": ["params"] - } - }, - { - "if": { - "properties": { - "name": { - "enum": ["open"] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "onlyPinned": { - "type": "boolean", - "description": "If set to true, only 'pinned' files will be included.", - "default": false - } - } - } - } - } - }, - { - "if": { - "properties": { - "name": { - "enum": ["issue"] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "githubToken": { - "type": "string", - "description": "Your GitHub token to access the GitHub API. Required for private repositories." - }, - "repos": { - "type": "array", - "description": "A list of repositories to search for issues", - "items": { - "type": "object", - "properties": { - "owner": { - "type": "string", - "description": "The owner of the repository" - }, - "repo": { - "type": "string", - "description": "The name of the repository" - }, - "type": { - "type": "string", - "description": "The type of issues to search for", - "enum": ["open", "closed", "all"] - } - }, - "required": ["owner", "repo"] - } - } - }, - "required": ["repos"] - } - }, - "required": ["params"] - } - }, - { - "if": { - "properties": { - "name": { - "enum": ["database"] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "connections": { - "type": "array", - "description": "A list of database connections", - "items": { - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "A unique name for this database connection" - }, - "connection_type": { - "type": "string", - "description": "The type of database (e.g., 'postgres', 'mysql')", - "enum": ["postgres", "mysql", "sqlite"] - }, - "connection": { - "type": "object", - "properties": { - "user": { - "type": "string", - "description": "The database user name" - }, - "host": { - "type": "string", - "description": "The host address of the database server" - }, - "database": { - "type": "string", - "description": "The name of the database to connect to" - }, - "password": { - "type": "string", - "description": "The password for the database user" - }, - "port": { - "type": "integer", - "description": "The port number to connect to at the host" - }, - "filename": { - "type": "string", - "description": "File location for simple file DB's" - } - }, - "required": [] - } - }, - "required": ["name", "connection_type", "connection"] - } - } - }, - "required": ["connections"] - } - }, - "required": ["params"] - } - }, - { - "if": { - "properties": { - "name": { - "enum": ["gitlab-mr"] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "domain": { - "type": "string", - "description": "Your GitLab domain, will default to gitlab.com" - }, - "token": { - "type": "string", - "description": "Your private access token." - }, - "filterComments": { - "type": "boolean", - "description": "If you have code selected, filters out comments that aren't related to the selection." - } - }, - "required": ["token"] - } - }, - "required": ["params"] - } - }, - { - "if": { - "properties": { - "name": { - "enum": ["jira"] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "domain": { - "type": "string", - "description": "Your Jira domain, for example company.atlassian.net." - }, - "email": { - "type": "string", - "description": "The email that you log into Jira with" - }, - "token": { - "type": "string", - "description": "Your atlassian API token from https://id.atlassian.com/manage-profile/security/api-tokens" - }, - "issueQuery": { - "type": "string", - "description": "Customize the query used to find Jira issues" - }, - "apiVersion": { - "type": "integer", - "markdownDescription": "This context provider supports both Jira API version 2 and 3. It will use version 3 by default since that's what the cloud version uses, but if you have the datacenter version of Jira, you'll need to set the API Version to 2 using the `apiVersion` property." - }, - "requestOptions": { - "title": "Request Options", - "description": "Options for the HTTPS request to Jira.", - "default": { - "timeout": 7200, - "verifySsl": null, - "caBundlePath": null, - "proxy": null, - "headers": null, - "extraBodyProperties": null - }, - "allOf": [ - { - "$ref": "#/definitions/RequestOptions" - } - ] - } - }, - "required": ["domain", "token"] - } - }, - "required": ["params"] - } - }, - { - "if": { - "properties": { - "name": { - "enum": ["http"] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "url": { - "type": "string", - "description": "The HTTP endpoint of your context provider server." - }, - "options": { - "title": "Custom Options", - "description": "Additional options to pass to your custom HTTP server.", - "type": "object" - } - }, - "required": ["url"] - } - }, - "required": ["params"] - } - }, - { - "if": { - "properties": { - "name": { - "enum": ["codebase", "folder"] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "nRetrieve": { - "title": "N Retrieve", - "description": "Number of results to initially retrieve from vector database", - "default": 50, - "type": "integer" - }, - "nFinal": { - "title": "N Final", - "description": "Final number of results to use after re-ranking", - "default": 10, - "type": "integer" - }, - "useReranking": { - "title": "Use Reranking", - "description": "Whether to use re-ranking, which will allow initial selection of nRetrieve results, then will use an LLM to select the top nFinal results. Disabling re-ranking will give faster, but less accurate, results.", - "default": true, - "type": "boolean" - } - } - } - } - } - }, - { - "if": { - "properties": { - "name": { - "enum": ["postgres"] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "host": { - "title": "Host", - "description": "Database host", - "default": "localhost", - "type": "string" - }, - "port": { - "title": "Port", - "description": "Database port", - "default": 5432, - "type": "integer" - }, - "user": { - "title": "User", - "description": "Database user", - "default": "postgres", - "type": "string" - }, - "password": { - "title": "Password", - "description": "Database password", - "type": "string" - }, - "database": { - "title": "Database", - "description": "Database name", - "default": "postgres", - "type": "string" - }, - "schema": { - "title": "Schema", - "description": "Database schema", - "default": "public", - "type": "string" - }, - "sampleRows": { - "title": "Sample Rows", - "description": "Number of rows to sample from the database", - "default": 3, - "type": "integer" - } - } - } - }, - "required": ["host", "port", "user", "password", "database"] - } - }, - { - "if": { - "properties": { - "name": { - "enum": ["greptile"] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "GithubToken": { - "title": "GithubToken", - "description": "Your github access token", - "default": "", - "type": "string" - }, - "GreptileToken": { - "title": "GreptileToken", - "description": "Your greptile access token", - "default": "", - "type": "string" - } - } - } - }, - "required": ["GreptileToken", "GithubToken"] - } - } - ], - "required": ["name"] - }, - "SerializedContinueConfig": { - "title": "config.json", - "type": "object", - "properties": { - "docs": { - "title": "Docs", - "description": "A list of documentation sites to be indexed", - "type": "array", - "items": { - "type": "object", - "properties": { - "title": { - "type": "string", - "description": "The title of the documentation site" - }, - "startUrl": { - "type": "string", - "description": "The starting URL for indexing the documentation" - }, - "rootUrl": { - "type": "string", - "description": "The root URL of the documentation site" - }, - "maxDepth": { - "type": "integer", - "description": "The maximum depth to crawl the documentation site" - }, - "favicon": { - "type": "string", - "description": "The URL path to a favicon for the site - by default, it will be `/favicon.ico` path from the Start URL" - } - }, - "required": ["title", "startUrl"] - } - }, - "allowAnonymousTelemetry": { - "title": "Allow Anonymous Telemetry", - "markdownDescription": "If this field is set to True, we will collect anonymous telemetry as described in the documentation page on telemetry. If set to `false`, we will not collect any data. Learn more in [the docs](https://docs.continue.dev/telemetry).", - "default": true, - "type": "boolean" - }, - "models": { - "title": "Models", - "markdownDescription": "Learn about setting up models in [the documentation](https://docs.continue.dev/model-setup/overview).", - "default": [ - { - "title": "GPT-4 (trial)", - "provider": "free-trial", - "model": "gpt-4", - "apiKey": "" - } - ], - "type": "array", - "items": { - "$ref": "#/definitions/ModelDescription" - } - }, - "systemMessage": { - "title": "System Message", - "description": "A system message that will always be followed by the LLM", - "type": "string" - }, - "completionOptions": { - "title": "Completion Options", - "description": "Default options for completion. These will be overriden by any options set for a specific model.", - "default": { - "temperature": null, - "topP": null, - "topK": null, - "presencePenalty": null, - "frequencyPenalty": null, - "stop": null, - "maxTokens": 600 - }, - "allOf": [ - { - "$ref": "#/definitions/BaseCompletionOptions" - } - ] - }, - "requestOptions": { - "title": "Request Options", - "description": "Default request options for all fetch requests from models and context providers. These will be overriden by any model-specific request options.", - "allOf": [ - { - "$ref": "#/definitions/RequestOptions" - } - ] - }, - "slashCommands": { - "title": "Slash Commands", - "markdownDescription": "An array of slash commands that let you take custom actions from the sidebar. Learn more in the [documentation](https://docs.continue.dev/customization/slash-commands).", - "default": [], - "type": "array", - "items": { - "$ref": "#/definitions/SlashCommand" - } - }, - "customCommands": { - "title": "Custom Commands", - "markdownDescription": "An array of custom commands that allow you to reuse prompts. Each has name, description, and prompt properties. When you enter / in the text input, it will act as a shortcut to the prompt. Learn more in the [documentation](https://docs.continue.dev/customization/slash-commands#custom-commands-use-natural-language).", - "default": [ - { - "name": "test", - "prompt": "{{{ input }}}\n\nWrite a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.", - "description": "This is an example custom command. Open config.json to edit it and create more" - } - ], - "type": "array", - "items": { - "$ref": "#/definitions/CustomCommand" - } - }, - "contextProviders": { - "title": "Context Providers", - "markdownDescription": "A list of ContextProvider objects that can be used to provide context to the LLM by typing '@'. Read more about ContextProviders in [the documentation](https://docs.continue.dev/customization/context-providers).", - "default": [], - "type": "array", - "items": { - "$ref": "#/definitions/ContextProviderWithParams" - } - }, - "userToken": { - "title": "User Token", - "description": "An optional token to identify the user.", - "type": "string" - }, - "disableIndexing": { - "title": "Disable Indexing", - "markdownDescription": "If set to `true`, Continue will not index the codebase. This is mainly used for debugging purposes.", - "default": false, - "type": "boolean" - }, - "disableSessionTitles": { - "title": "Disable Session Titles", - "markdownDescription": "If set to `true`, Continue will not make extra requests to the LLM to generate a summary title of each session.", - "default": false, - "type": "boolean" - }, - "embeddingsProvider": { - "title": "Embeddings Provider", - "markdownDescription": "The method that will be used to generate codebase embeddings. The default is transformers.js, which will run locally in the browser. Learn about the other options [here](https://docs.continue.dev/features/codebase-embeddings#embeddings-providers).", - "type": "object", - "properties": { - "provider": { - "enum": [ - "huggingface-tei", - "transformers.js", - "ollama", - "openai", - "cohere", - "free-trial", - "gemini", - "voyage", - "nvidia", - "bedrock", - "sagemaker", - "vertex" - ] - }, - "model": { - "type": "string" - }, - "apiKey": { - "type": "string" - }, - "apiBase": { - "type": "string" - }, - "requestOptions": { - "title": "Request Options", - "description": "Request options to be used in any fetch requests made by the embeddings provider", - "$ref": "#/definitions/RequestOptions" - }, - "maxChunkSize": { - "title": "Maximum Chunk Size", - "description": "The maximum number of tokens that each chunk of a document is allowed to have", - "type": "integer", - "minimum": 128, - "exclusiveMaximum": 2147483647 - }, - "maxBatchSize": { - "title": "Maximum Batch Size", - "description": "The maximum number of chunks that can be sent to the embeddings provider in a single request", - "type": "integer", - "minimum": 1, - "exclusiveMaximum": 2147483647 - }, - "region": { - "title": "Region", - "description": "The region where the model is hosted", - "$ref": "#/definitions/ModelDescription/properties/region" - }, - "profile": { - "title": "Profile", - "description": "The AWS security profile to use", - "type": "string" - } - }, - "required": ["provider"], - "allOf": [ - { - "if": { - "properties": { - "provider": { - "enum": ["cohere", "voyage", "nvidia", "gemini"] - } - }, - "required": ["provider"] - }, - "then": { - "required": ["apiKey"] - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["sagemaker"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "markdownDescription": "SageMaker endpoint name" - } - }, - "required": ["model"] - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["vertex"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "projectId": { - "markdownDescription": "The name of your vertexAI project" - }, - "region": { - "markdownDescription": "The region your vertexAI model is hosted in - typically central1", - "default": "central1" - }, - "model": { - "default": "text-embedding-004" - } - }, - "required": ["projectId", "model", "region"] - } - } - ] - }, - "reranker": { - "title": "Reranker", - "markdownDescription": "The reranker is responsible for selecting the final results when retrieving snippets from your codebase.", - "type": "object", - "properties": { - "name": { - "enum": [ - "cohere", - "voyage", - "llm", - "free-trial", - "huggingface-tei" - ] - }, - "params": { - "type": "object" - } - }, - "required": ["name"], - "allOf": [ - { - "if": { - "properties": { - "name": { - "enum": ["cohere"] - } - }, - "required": ["name"] - }, - "then": { - "properties": { - "params": { - "type": "object", - "properties": { - "model": { - "enum": [ - "rerank-english-v3.0", - "rerank-multilingual-v3.0", - "rerank-english-v2.0", - "rerank-multilingual-v2.0" - ] - }, - "apiBase": { - "type": "string" - }, - "apiKey": { - "type": "string" - } - }, - "required": ["apiKey"] - } - } - } - }, - { - "if": { - "properties": { - "name": { - "enum": ["llm"] - } - }, - "required": ["name"] - }, - "then": { - "properties": { - "params": { - "type": "object", - "properties": { - "modelTitle": { - "type": "string" - } - }, - "required": ["modelTitle"] - } - } - } - }, - { - "if": { - "properties": { - "name": { - "enum": ["voyage"] - } - }, - "required": ["name"] - }, - "then": { - "properties": { - "params": { - "type": "object", - "properties": { - "apiKey": { - "type": "string" - }, - "model": { - "enum": [ - "rerank-lite-1", - "rerank-1", - "rerank-2", - "rerank-2-lite" - ] - } - }, - "required": ["apiKey"] - } - } - } - }, - { - "if": { - "properties": { - "name": { - "enum": ["huggingface-tei"] - } - }, - "required": ["name"] - }, - "then": { - "properties": { - "params": { - "type": "object", - "properties": { - "apiBase": { - "type": "string", - "default": "http://localhost:8080" - }, - "truncate": { - "type": "boolean", - "description": "Wether to truncate long sequences to the maximum allowed context length.", - "default": false - }, - "truncation_direction": { - "enum": ["Right", "Left"], - "markdownDescription": "Wether to truncate sequences from the `left` or `right`.", - "default": "Right" - } - }, - "required": ["apiBase"] - } - }, - "if": { - "properties": { - "truncate": { - "const": true - } - } - }, - "then": { - "required": ["truncation_direction"] - } - } - } - ] - }, - "tabAutocompleteModel": { - "title": "Tab Autocomplete Model", - "markdownDescription": "The model used for tab autocompletion. If undefined, Continue will default to using starcoder2:3b on a local Ollama instance.\n\n*IMPORTANT*:\n\nIf you use a custom model, ensure that it is one trained for fill-in-the-middle completions. An instruct model is typically not well-suited to autocomplete and you may receive unsatisfactory completions.", - "default": { - "title": "Tab Autocomplete Model", - "provider": "ollama", - "model": "deepseek-coder:1.3b-base" - }, - "oneOf": [ - { - "$ref": "#/definitions/ModelDescription" - }, - { - "type": "array", - "items": { - "$ref": "#/definitions/ModelDescription" - } - } - ] - }, - "tabAutocompleteOptions": { - "title": "TabAutocompleteOptions", - "type": "object", - "markdownDescription": "These options let you customize your tab-autocomplete experience. Read about all options in [the docs](https://docs.continue.dev/features/tab-autocomplete#configuration-options).", - "properties": { - "disable": { - "type": "boolean", - "description": "Disable tab autocomplete. This can also be done from the IDE settings.", - "default": false - }, - "useCopyBuffer": { - "type": "boolean", - "description": "Determines whether the copy buffer will be considered when contructing the prompt." - }, - "useFileSuffix": { - "type": "boolean", - "description": "Determines whether to use the file suffix in the prompt." - }, - "maxPromptTokens": { - "type": "number", - "description": "The maximum number of prompt tokens to use. A smaller number will yield faster completions, but less context." - }, - "debounceDelay": { - "type": "number", - "description": "The delay in milliseconds before triggering autocomplete after a keystroke." - }, - "maxSuffixPercentage": { - "type": "number", - "description": "The maximum percentage of the prompt that can be dedicated to the suffix." - }, - "prefixPercentage": { - "type": "number", - "description": "The percentage of the input that should be dedicated to the prefix." - }, - "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." - }, - "multilineCompletions": { - "enum": ["always", "never", "auto"], - "description": "If set to true, Continue will only complete a single line at a time." - }, - "useCache": { - "type": "boolean", - "description": "Whether to cache completions" - }, - "onlyMyCode": { - "type": "boolean", - "description": "If set to true, Continue will not include any snippets from go to definition unless they are within your repository" - }, - "useOtherFiles": { - "type": "boolean", - "description": "Defaults to true. If set to false, Continue will not attempt to include snippets from other files." - }, - "disableInFiles": { - "description": "A list of files / glob patterns in which to disable tab autocomplete. For example, *.csv if you'd like to disable autocomplete in .csv files.", - "type": "array", - "items": { - "type": "string" - } - } - }, - "required": [] - }, - "ui": { - "type": "object", - "properties": { - "codeBlockToolbarPosition": { - "enum": ["top", "bottom"], - "default": "top", - "description": "Whether to show the copy and apply code buttons at the top or bottom of code blocks in the sidebar." - }, - "fontSize": { - "type": "number" - }, - "displayRawMarkdown": { - "type": "boolean", - "description": "If set to true, we will display the model output as raw markdown.", - "default": false - }, - "showChatScrollbar": { - "title": "Show Chat Scrollbar", - "markdownDescription": "If set to `true`, a scrollbar will be displayed in the chat window to navigate through messages.", - "default": false, - "type": "boolean" - } - } - }, - "analytics": { - "type": "object", - "properties": { - "provider": { - "type": "string", - "enum": ["posthog", "logstash"], - "description": "The 3rd party analytics provider to use.", - "default": "posthog", - "markdownEnumDescriptions": [ - "### Posthog\nTo use Posthog, set up an account, obtain your client key, and enter it in the client key field.", - "### Logstash\nContinue's Logstash integration uses the TCP input at the specified URL" - ] - }, - "url": { - "type": "string", - "description": "The URL to which analytics will be sent" - }, - "clientKey": { - "type": "string", - "description": "The client key to use for analytics" - } - }, - "required": ["provider"], - "allOf": [ - { - "if": { - "properties": { - "provider": { - "enum": ["posthog"] - } - } - }, - "then": { - "required": ["clientKey"] - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["logstash"] - } - } - }, - "then": { - "required": ["url"] - } - } - ] - }, - "experimental": { - "type": "object", - "title": "Experimental", - "description": "Experimental properties are subject to change.", - "properties": { - "defaultContext": { - "type": "array", - "items": { - "allOf": [ - { - "$ref": "#/definitions/ContextProviderWithParams" - }, - { - "properties": { - "query": { - "type": "string", - "description": "Required for certain context providers, like 'url' in order to specify the input, or which of the dropdown items to select." - } - } - } - ] - } - }, - "modelRoles": { - "type": "object", - "properties": { - "inlineEdit": { - "description": "The 'title' property of the model you wish to use for inline edits", - "type": "string" - }, - "applyCodeBlock": { - "description": "The 'title' property of the model you wish to use for applying code blocks", - "type": "string" - }, - "repoMapFileSelection": { - "description": "The 'title' property of the model you wish to use for repo map file selections", - "type": "string" - } - } - }, - "readResponseTTS": { - "type": "boolean", - "default": true, - "description": "Automatically read LLM chat responses aloud using system TTS models" - }, - "promptPath": { - "type": "string" - }, - "quickActions": { - "type": "array", - "items": { - "type": "object", - "properties": { - "title": { - "type": "string", - "description": "The title of the quick action that will display in the Code Lens." - }, - "prompt": { - "type": "string", - "description": "The prompt that will be sent to the model when the quick action is invoked, with the function or class body concatenated." - }, - "sendToChat": { - "type": "boolean", - "description": "If true, the result of the quick action will be sent to the chat panel. If false, the streamed result will be inserted into the document.", - "default": false - } - }, - "required": ["prompt", "title"] - }, - "description": "Quick actions are a way to add custom commands to the Code Lens of function and class declarations." - }, - "contextMenuPrompts": { - "type": "object", - "properties": { - "comment": { - "type": "string", - "default": "Write comments for this code. Do not change anything about the code itself." - }, - "docstring": { - "type": "string", - "default": "Write a docstring for this code. Do not change anything about the code itself." - }, - "fix": { - "type": "string", - "default": "Fix this code" - }, - "optimize": { - "type": "string", - "default": "Optimize this code" - }, - "fixGrammar": { - "type": "string", - "default": "If there are any grammar or spelling mistakes in this writing, fix them. Do not make other large changes to the writing." - } - } - } - } - } - } - } - } -} diff --git a/extensions/intellij/.run/Prompt Logs.run.xml b/extensions/intellij/.run/Prompt Logs.run.xml new file mode 100644 index 000000000..23fec409a --- /dev/null +++ b/extensions/intellij/.run/Prompt Logs.run.xml @@ -0,0 +1,17 @@ + + + + \ No newline at end of file diff --git a/extensions/intellij/.run/Run Continue (CE).run.xml b/extensions/intellij/.run/Run Continue (CE).run.xml new file mode 100644 index 000000000..edca42d64 --- /dev/null +++ b/extensions/intellij/.run/Run Continue (CE).run.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/extensions/intellij/.run/Run Continue.run.xml b/extensions/intellij/.run/Run Continue.run.xml index cc705773b..2cc85210f 100644 --- a/extensions/intellij/.run/Run Continue.run.xml +++ b/extensions/intellij/.run/Run Continue.run.xml @@ -1,9 +1,9 @@ - - - + + + \ No newline at end of file diff --git a/extensions/intellij/.run/Start Core Dev Server (CE).run.xml b/extensions/intellij/.run/Start Core Dev Server (CE).run.xml new file mode 100644 index 000000000..4284b852f --- /dev/null +++ b/extensions/intellij/.run/Start Core Dev Server (CE).run.xml @@ -0,0 +1,16 @@ + + + + \ No newline at end of file diff --git a/extensions/intellij/.run/Start Dev Server (core).run.xml b/extensions/intellij/.run/Start Core Dev Server.run.xml similarity index 58% rename from extensions/intellij/.run/Start Dev Server (core).run.xml rename to extensions/intellij/.run/Start Core Dev Server.run.xml index e7fe0ccac..0fb8233ef 100644 --- a/extensions/intellij/.run/Start Dev Server (core).run.xml +++ b/extensions/intellij/.run/Start Core Dev Server.run.xml @@ -1,5 +1,5 @@ - + diff --git a/extensions/intellij/.run/Start GUI Dev Server.run.xml b/extensions/intellij/.run/Start GUI Dev Server.run.xml new file mode 100644 index 000000000..5f574019a --- /dev/null +++ b/extensions/intellij/.run/Start GUI Dev Server.run.xml @@ -0,0 +1,17 @@ + + + + \ No newline at end of file diff --git a/extensions/intellij/CONTRIBUTING.md b/extensions/intellij/CONTRIBUTING.md index 7dd776055..c1d1cdca2 100644 --- a/extensions/intellij/CONTRIBUTING.md +++ b/extensions/intellij/CONTRIBUTING.md @@ -30,11 +30,11 @@ packaging it in a binary in the `binary` directory. Communication occurs over st ### IDE Installation -We recommend using IntelliJ IDEA, which you can download from -the [JetBrains website](https://www.jetbrains.com/idea/download). +Continue is built with JDK version 17 (as specified in [`./build.gradle.kts`](./build.gradle.kts)), which can be downloaded from [Oracle](https://www.oracle.com/java/technologies/javase/jdk17-archive-downloads.html). -Both Ultimate and Community (free) editions are suitable for this project. Continue is built with JDK version 17, as -specified in [`./build.gradle.kts`](./build.gradle.kts). +We recommend using IntelliJ IDEA, which you can download from the [JetBrains website](https://www.jetbrains.com/idea/download). + +Both Ultimate and Community (free) editions are suitable for this project, although Ultimate has better debugging (see notes below). ### IDE configuration @@ -63,13 +63,15 @@ This project requires Node.js version 20.11.0 (LTS) or higher. You have two opti Select the `Run Continue` task in the top right corner of the IDE and then select the "Debug" option. +> In community edition, use `Run Continue (CE)` instead, which uses shell scripts instead of Ultimate-only node configs. If you want to debug the core in CE, you'll need to quit the `Start Core Dev Server (CE)` process and run the core in a different environment that supports debugging, such as VS Code (Launch "Core Binary"). + ![run-extension-screenshot](../../media/run-continue-intellij.png) This should open a new instance on IntelliJ with the extension installed. ### Accessing files in the `.continue` directory -When running the `Start Dev Server (core)` task, we set the location of your Continue directory to `./binary/.continue`. This is to +When running the `Start Core Dev Server` task, we set the location of your Continue directory to `./binary/.continue`. This is to allow for changes to your `config.json` and other files during development, without affecting your actual configuration. ### Reloading changes @@ -78,13 +80,13 @@ allow for changes to your `config.json` and other files during development, with _Run | Debugging Actions | Reload Changed Classes`_ - This will often fail on new imports, schema changes etc. In that case, you need to stop and restart the extension - `gui`: Changes will be reloaded automatically -- `core`: Run `npm run build` from the `binary` directory (requires restarting the `Start Dev Server (core)` task) +- `core`: Run `npm run build` from the `binary` directory (requires restarting the `Start Core Dev Server` task) ### Setting breakpoints - `extensions/intellij`: Breakpoints can be set in Intellij - `gui`: You'll need to set explicit `debugger` statements in the source code, or through the browser dev tools -- `core`: Breakpoints can be set in Intellij (requires restarting the `Start Dev Server (core)` task) +- `core`: Breakpoints can be set in Intellij (requires restarting the `Start Core Dev Server` task) ### Available Gradle tasks diff --git a/extensions/intellij/build.gradle.kts b/extensions/intellij/build.gradle.kts index 336b17bf8..4c6aba783 100644 --- a/extensions/intellij/build.gradle.kts +++ b/extensions/intellij/build.gradle.kts @@ -5,13 +5,13 @@ fun properties(key: String) = providers.gradleProperty(key) fun environment(key: String) = providers.environmentVariable(key) plugins { - id("java") // Java support - alias(libs.plugins.kotlin) // Kotlin support - alias(libs.plugins.gradleIntelliJPlugin) // Gradle IntelliJ Plugin - alias(libs.plugins.changelog) // Gradle Changelog Plugin - alias(libs.plugins.qodana) // Gradle Qodana Plugin - alias(libs.plugins.kover) // Gradle Kover Plugin - kotlin("plugin.serialization") version "1.8.0" + id("java") // Java support + alias(libs.plugins.kotlin) // Kotlin support + alias(libs.plugins.gradleIntelliJPlugin) // Gradle IntelliJ Plugin + alias(libs.plugins.changelog) // Gradle Changelog Plugin + alias(libs.plugins.qodana) // Gradle Qodana Plugin + alias(libs.plugins.kover) // Gradle Kover Plugin + kotlin("plugin.serialization") version "1.8.0" } group = properties("pluginGroup").get() @@ -24,23 +24,23 @@ repositories { mavenCentral() } // Dependencies are managed with Gradle version catalog - read more: // https://docs.gradle.org/current/userguide/platforms.html#sub:version-catalog dependencies { - // implementation(libs.annotations) - implementation("com.squareup.okhttp3:okhttp:4.9.1") { - exclude(group = "org.jetbrains.kotlin", module = "kotlin-stdlib") - } - implementation("org.jetbrains.kotlin:kotlin-stdlib:1.4.32") - implementation("io.ktor:ktor-server-core:2.3.7") { - exclude(group = "org.slf4j", module = "slf4j-api") - } - implementation("io.ktor:ktor-server-netty:2.3.7") { - exclude(group = "org.slf4j", module = "slf4j-api") - } - implementation("io.ktor:ktor-server-cors:2.3.7") { - exclude(group = "org.slf4j", module = "slf4j-api") - } - implementation("com.posthog.java:posthog:1.+") - implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.5.0") - // implementation("com.jetbrains.jsonSchema") + // implementation(libs.annotations) + implementation("com.squareup.okhttp3:okhttp:4.9.2") { + exclude(group = "org.jetbrains.kotlin", module = "kotlin-stdlib") + } + implementation("org.jetbrains.kotlin:kotlin-stdlib:1.4.32") + implementation("io.ktor:ktor-server-core:2.3.7") { + exclude(group = "org.slf4j", module = "slf4j-api") + } + implementation("io.ktor:ktor-server-netty:2.3.7") { + exclude(group = "org.slf4j", module = "slf4j-api") + } + implementation("io.ktor:ktor-server-cors:2.3.7") { + exclude(group = "org.slf4j", module = "slf4j-api") + } + implementation("com.posthog.java:posthog:1.+") + implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.5.0") + // implementation("com.jetbrains.jsonSchema") } // Set the JVM language level used to build the project. Use Java 11 for 2020.3+, and Java 17 for @@ -50,98 +50,100 @@ kotlin { jvmToolchain(17) } // Configure Gradle IntelliJ Plugin - read more: // https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html intellij { - pluginName = properties("pluginName") - version = properties("platformVersion") - type = properties("platformType") + pluginName = properties("pluginName") + version = properties("platformVersion") + type = properties("platformType") - // Plugin Dependencies. Uses `platformPlugins` property from the gradle.properties file. - plugins = - properties("platformPlugins").map { - it.split(',').map(String::trim).filter(String::isNotEmpty) - } + // Plugin Dependencies. Uses `platformPlugins` property from the gradle.properties file. + plugins = + properties("platformPlugins").map { + it.split(',').map(String::trim).filter(String::isNotEmpty) + } } // Configure Gradle Changelog Plugin - read more: // https://github.com/JetBrains/gradle-changelog-plugin changelog { - groups.empty() - repositoryUrl = properties("pluginRepositoryUrl") + groups.empty() + repositoryUrl = properties("pluginRepositoryUrl") } // Configure Gradle Qodana Plugin - read more: https://github.com/JetBrains/gradle-qodana-plugin qodana { - cachePath = provider { file(".qodana").canonicalPath } - reportPath = provider { file("build/reports/inspections").canonicalPath } - saveReport = true - showReport = environment("QODANA_SHOW_REPORT").map { it.toBoolean() }.getOrElse(false) + cachePath = provider { file(".qodana").canonicalPath } + reportPath = provider { file("build/reports/inspections").canonicalPath } + saveReport = true + showReport = environment("QODANA_SHOW_REPORT").map { it.toBoolean() }.getOrElse(false) } // Configure Gradle Kover Plugin - read more: https://github.com/Kotlin/kotlinx-kover#configuration koverReport { defaults { xml { onCheck = true } } } tasks { - prepareSandbox { - from("../../binary/bin") { into("${intellij.pluginName.get()}/core/") } - from("../vscode/node_modules/@vscode/ripgrep") { into("${intellij.pluginName.get()}/ripgrep/") } - } + prepareSandbox { + from("../../binary/bin") { into("${intellij.pluginName.get()}/core/") } + from("../vscode/node_modules/@vscode/ripgrep") { into("${intellij.pluginName.get()}/ripgrep/") } + } - wrapper { gradleVersion = properties("gradleVersion").get() } + wrapper { gradleVersion = properties("gradleVersion").get() } - patchPluginXml { - version = properties("pluginVersion") - sinceBuild = properties("pluginSinceBuild") - untilBuild = properties("pluginUntilBuild") + patchPluginXml { + version = properties("pluginVersion") + sinceBuild = properties("pluginSinceBuild") + untilBuild = properties("pluginUntilBuild") - // Extract the section from README.md and provide for the plugin's - // manifest - pluginDescription = - providers.fileContents(layout.projectDirectory.file("README.md")).asText.map { - val start = "" - val end = "" + // Extract the section from README.md and provide for the plugin's + // manifest + pluginDescription = + providers.fileContents(layout.projectDirectory.file("README.md")).asText.map { + val start = "" + val end = "" - with(it.lines()) { - if (!containsAll(listOf(start, end))) { - throw GradleException( - "Plugin description section not found in README.md:\n$start ... $end") + with(it.lines()) { + if (!containsAll(listOf(start, end))) { + throw GradleException( + "Plugin description section not found in README.md:\n$start ... $end" + ) + } + subList(indexOf(start) + 1, indexOf(end)).joinToString("\n").let(::markdownToHTML) + } } - subList(indexOf(start) + 1, indexOf(end)).joinToString("\n").let(::markdownToHTML) - } - } - } + } - // Configure UI tests plugin - // Read more: https://github.com/JetBrains/intellij-ui-test-robot - runIdeForUiTests { - systemProperty("robot-server.port", "8082") - systemProperty("ide.mac.message.dialogs.as.sheets", "false") - systemProperty("jb.privacy.policy.text", "") - systemProperty("jb.consents.confirmation.enabled", "false") - } + // Configure UI tests plugin + // Read more: https://github.com/JetBrains/intellij-ui-test-robot + runIdeForUiTests { + systemProperty("robot-server.port", "8082") + systemProperty("ide.mac.message.dialogs.as.sheets", "false") + systemProperty("jb.privacy.policy.text", "") + systemProperty("jb.consents.confirmation.enabled", "false") + } - signPlugin { - certificateChain = environment("CERTIFICATE_CHAIN") - privateKey = environment("PRIVATE_KEY") - password = environment("PRIVATE_KEY_PASSWORD") - } + signPlugin { + certificateChain = environment("CERTIFICATE_CHAIN") + privateKey = environment("PRIVATE_KEY") + password = environment("PRIVATE_KEY_PASSWORD") + } - publishPlugin { - // dependsOn("patchChangelog") - token = environment("PUBLISH_TOKEN") - // The pluginVersion is based on the SemVer (https://semver.org) and supports pre-release - // labels, like 2.1.7-alpha.3 - // Specify pre-release label to publish the plugin in a custom Release Channel automatically. - // Read more: - // https://plugins.jetbrains.com/docs/intellij/deployment.html#specifying-a-release-channel - channels.set(listOf(environment("RELEASE_CHANNEL").getOrElse("eap"))) + publishPlugin { + // dependsOn("patchChangelog") + token = environment("PUBLISH_TOKEN") + // The pluginVersion is based on the SemVer (https://semver.org) and supports pre-release + // labels, like 2.1.7-alpha.3 + // Specify pre-release label to publish the plugin in a custom Release Channel automatically. + // Read more: + // https://plugins.jetbrains.com/docs/intellij/deployment.html#specifying-a-release-channel + channels.set(listOf(environment("RELEASE_CHANNEL").getOrElse("eap"))) - // We always hide the stable releases until a few days of EAP have proven them stable - // hidden = environment("RELEASE_CHANNEL").map { it == "stable" }.getOrElse(false) - } + // We always hide the stable releases until a few days of EAP have proven them stable + // hidden = environment("RELEASE_CHANNEL").map { it == "stable" }.getOrElse(false) + } - runIde { - // Open the `manual-testing-sandbox` on start - args = - listOf("${rootProject.projectDir.parentFile.parentFile}/manual-testing-sandbox/test.kt") - .map { file(it).absolutePath } - } + runIde { + // Open the `manual-testing-sandbox` directory and the specific file on start + args = listOf( + "${rootProject.projectDir.parentFile.parentFile}/manual-testing-sandbox", + "${rootProject.projectDir.parentFile.parentFile}/manual-testing-sandbox/test.kt" + ).map { file(it).absolutePath } + } } diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index 5e79c0f95..3dbc8695d 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -3,7 +3,7 @@ pluginGroup=com.github.continuedev.continueintellijextension pluginName=continue-intellij-extension pluginRepositoryUrl=https://github.com/continuedev/continue # SemVer format -> https://semver.org -pluginVersion=0.0.77 +pluginVersion=0.0.79 # Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html pluginSinceBuild=223 # IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt index 8ca3648dd..135d13c8d 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt @@ -12,6 +12,7 @@ import com.github.continuedev.continueintellijextension.services.SettingsListene import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.KeyboardShortcut import com.intellij.openapi.application.ApplicationManager +import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.fileEditor.FileEditorManager @@ -31,24 +32,36 @@ import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.roots.ModuleRootManager fun showTutorial(project: Project) { - ContinuePluginStartupActivity::class.java.getClassLoader().getResourceAsStream("continue_tutorial.py").use { `is` -> - if (`is` == null) { - throw IOException("Resource not found: continue_tutorial.py") - } - var content = StreamUtil.readText(`is`, StandardCharsets.UTF_8) - if (!System.getProperty("os.name").toLowerCase().contains("mac")) { - content = content.replace("⌘", "⌃") - } - val filepath = Paths.get(getContinueGlobalPath(), "continue_tutorial.py").toString() - File(filepath).writeText(content) - val virtualFile = LocalFileSystem.getInstance().findFileByPath(filepath) + val tutorialFileName = getTutorialFileName() + ContinuePluginStartupActivity::class.java.getClassLoader().getResourceAsStream(tutorialFileName) + .use { `is` -> + if (`is` == null) { + throw IOException("Resource not found: $tutorialFileName") + } + var content = StreamUtil.readText(`is`, StandardCharsets.UTF_8) + if (!System.getProperty("os.name").lowercase().contains("mac")) { + content = content.replace("⌘", "⌃") + } + val filepath = Paths.get(getContinueGlobalPath(), tutorialFileName).toString() + File(filepath).writeText(content) + val virtualFile = LocalFileSystem.getInstance().findFileByPath(filepath) - ApplicationManager.getApplication().invokeLater { - if (virtualFile != null) { - FileEditorManager.getInstance(project).openFile(virtualFile, true) + ApplicationManager.getApplication().invokeLater { + if (virtualFile != null) { + FileEditorManager.getInstance(project).openFile(virtualFile, true) + } } } +} + +private fun getTutorialFileName(): String { + val appName = ApplicationNamesInfo.getInstance().fullProductName.lowercase() + return when { + appName.contains("intellij") -> "continue_tutorial.java" + appName.contains("pycharm") -> "continue_tutorial.py" + appName.contains("webstorm") -> "continue_tutorial.ts" + else -> "continue_tutorial.py" // Default to Python tutorial } } @@ -58,6 +71,7 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware { override fun runActivity(project: Project) { removeShortcutFromAction(getPlatformSpecificKeyStroke("J")) removeShortcutFromAction(getPlatformSpecificKeyStroke("shift J")) + removeShortcutFromAction(getPlatformSpecificKeyStroke("I")) initializePlugin(project) } @@ -101,7 +115,7 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware { ServiceManager.getService(ContinueExtensionSettings::class.java) if (!settings.continueState.shownWelcomeDialog) { settings.continueState.shownWelcomeDialog = true - // Open continue_tutorial.py + // Open tutorial file showTutorial(project) } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt index da6d74b43..22178004e 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt @@ -1,5 +1,6 @@ package com.github.continuedev.continueintellijextension.auth +import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.google.gson.Gson import com.intellij.credentialStore.Credentials @@ -37,7 +38,10 @@ class ContinueAuthService { } init { - setupRefreshTokenInterval() + val settings = service() + if (settings.continueState.enableContinueTeamsBeta) { + setupRefreshTokenInterval() + } } fun startAuthFlow(project: Project) { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/Diffs.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/Diffs.kt index 196af8e87..d7e912499 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/Diffs.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/Diffs.kt @@ -6,8 +6,6 @@ import com.intellij.diff.DiffContentFactory import com.intellij.diff.DiffManager import com.intellij.diff.DiffRequestPanel import com.intellij.diff.contents.DiffContent -import com.intellij.diff.contents.DocumentContent -import com.intellij.diff.requests.DiffRequest import com.intellij.diff.requests.SimpleDiffRequest import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.command.WriteCommandAction @@ -18,7 +16,6 @@ import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.util.Disposer import com.intellij.openapi.vfs.LocalFileSystem -import com.intellij.ui.content.ContentFactory import java.awt.Toolkit import java.io.File import java.nio.file.Paths @@ -51,10 +48,9 @@ interface DiffInfo { class DiffManager(private val project: Project) : DumbAware { - private val diffContentFactory = DiffContentFactory.getInstance() - // Mapping from file2 to relevant info private val diffInfoMap: MutableMap = mutableMapOf() + private var lastFile2: String? = null fun showDiff(filepath: String, replacement: String, stepIndex: Int) { val diffDir = getDiffDirectory() @@ -68,7 +64,7 @@ class DiffManager(private val project: Project) : DumbAware { openDiffWindow(filepath, file.path, stepIndex) } - fun cleanUpFile(file2: String) { + private fun cleanUpFile(file2: String) { diffInfoMap[file2]?.dialog?.close(0) diffInfoMap.remove(file2) File(file2).delete() @@ -77,7 +73,6 @@ class DiffManager(private val project: Project) : DumbAware { } } - private var lastFile2: String? = null fun acceptDiff(file2: String?) { val file = (file2 ?: lastFile2) ?: return @@ -128,7 +123,7 @@ class DiffManager(private val project: Project) : DumbAware { // Create a SimpleDiffRequest and populate it with the DiffContents and titles val diffRequest = SimpleDiffRequest("Continue Diff", content1, content2, "Old", "New") - + // Get a DiffRequestPanel from the DiffManager and set the DiffRequest to it val diffInfo = diffInfoMap[file2] @@ -176,10 +171,10 @@ class DiffManager(private val project: Project) : DumbAware { } override fun createActions(): Array { - val okAction = getOKAction() + val okAction = okAction okAction.putValue(Action.NAME, "Accept (${getAltKeyLabel()} ⇧ Y)") - val cancelAction = getCancelAction() + val cancelAction = cancelAction cancelAction.putValue(Action.NAME, "Reject (${getAltKeyLabel()} ⇧ N)") return arrayOf(okAction, cancelAction) 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 2b07229ae..1295d0002 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 @@ -5,6 +5,8 @@ import com.github.continuedev.continueintellijextension.auth.ContinueAuthService import com.github.continuedev.continueintellijextension.constants.getConfigJsPath import com.github.continuedev.continueintellijextension.constants.getConfigJsonPath import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath +import com.github.continuedev.continueintellijextension.editor.DiffStreamHandler +import com.github.continuedev.continueintellijextension.editor.DiffStreamService import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.google.gson.Gson @@ -16,9 +18,9 @@ import com.intellij.execution.util.ExecUtil import com.intellij.ide.plugins.PluginManager import com.intellij.ide.plugins.PluginManagerCore import com.intellij.lang.annotation.HighlightSeverity -import com.intellij.notification.NotificationType import com.intellij.notification.NotificationAction import com.intellij.notification.NotificationGroupManager +import com.intellij.notification.NotificationType import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.application.ApplicationManager @@ -34,6 +36,7 @@ import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.util.IconLoader +import com.intellij.openapi.util.TextRange import com.intellij.openapi.vfs.* import com.intellij.openapi.vfs.newvfs.events.VFileEvent import com.intellij.psi.PsiDocumentManager @@ -48,6 +51,7 @@ import java.nio.charset.Charset import java.nio.file.Paths import java.util.* + fun uuid(): String { return UUID.randomUUID().toString() } @@ -447,22 +451,26 @@ class IdeProtocolClient( } "getDiff" -> { - val builder = ProcessBuilder("git", "diff") - builder.directory(File(workspacePath ?: ".")) - val process = builder.start() - - val reader = BufferedReader(InputStreamReader(process.inputStream)) + val workspaceDirs = workspaceDirectories() val output = StringBuilder() - var line: String? = reader.readLine() - while (line != null) { - output.append(line) - output.append("\n") - line = reader.readLine() + + for (workspaceDir in workspaceDirs) { + val builder = ProcessBuilder("git", "diff") + builder.directory(File(workspaceDir)) + val process = builder.start() + + val reader = BufferedReader(InputStreamReader(process.inputStream)) + var line: String? = reader.readLine() + while (line != null) { + output.append(line) + output.append("\n") + line = reader.readLine() + } + + process.waitFor() } - process.waitFor() - - respond(output.toString()); + respond(output.toString()) } "getProblems" -> { @@ -550,7 +558,6 @@ class IdeProtocolClient( } "openFile" -> { - setFileOpen((data as Map)["path"] as String) respond(null) } @@ -572,10 +579,16 @@ class IdeProtocolClient( "listFolders" -> { val workspacePath = workspacePath ?: return@launch - val workspaceDir = File(workspacePath) - val folders = - workspaceDir.listFiles { file -> file.isDirectory }?.map { file -> file.absolutePath } - ?: emptyList() + val folders = mutableListOf() + fun findNestedFolders(dirPath: String) { + val dir = File(dirPath) + val nestedFolders = + dir.listFiles { file -> file.isDirectory }?.map { file -> file.absolutePath } + ?: emptyList() + folders.addAll(nestedFolders); + nestedFolders.forEach { folder -> findNestedFolders(folder) } + } + findNestedFolders(workspacePath) respond(folders) } @@ -619,7 +632,81 @@ class IdeProtocolClient( } } - "applyToFile" -> { + "applyToCurrentFile" -> { + val msg = data as Map; + 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) { + editor.document.insertString(0, text) + } + respond(null) + return@launch + } + + val config = readConfigJson() + var llm = getModelByRole(config, "applyCodeBlock") + + if (llm == null) { + val models = (config as? Map<*, *>)?.get("models") as? List> + llm = models?.find { model -> model["title"] == curSelectedModelTitle } as Map + + if (llm == null) { + showToast("error", "Model '$curSelectedModelTitle' not found in config.") + respond(null) + return@launch + } + } + + val llmTitle = (llm as? Map<*, *>)?.get("title") as? String ?: "" + + val prompt = + "The following code was suggested as an edit:\n```\n${text}\n```\nPlease apply it to the previous code." + + val rif = getHighlightedCode() + + val (prefix, highlighted, suffix) = if (rif == null) { + // If no highlight, use the whole document as highlighted + Triple("", editor.document.text, "") + } else { + val prefix = editor.document.getText(TextRange(0, rif.range.start.character)) + val highlighted = rif.contents + val suffix = + editor.document.getText(TextRange(rif.range.end.character, editor.document.textLength)) + + // Remove the selection after processing + ApplicationManager.getApplication().invokeLater { + editor.selectionModel.removeSelection() + } + + Triple(prefix, highlighted, suffix) + } + + val diffStreamHandler = + DiffStreamHandler( + project, + editor, + rif?.range?.start?.line ?: 0, + rif?.range?.end?.line ?: (editor.document.lineCount - 1), + {}, {}) + + val diffStreamService = project.service() + diffStreamService.register(diffStreamHandler, editor) + + diffStreamHandler.streamDiffLinesToEditor( + prompt, prefix, highlighted, suffix, llmTitle + ) + + respond(null) } "getGitHubAuthToken" -> { @@ -692,11 +779,11 @@ class IdeProtocolClient( ) } - fun uniqueId(): String { + private fun uniqueId(): String { return getMachineUniqueID() } - suspend fun getBranch(dir: String): String = withContext(Dispatchers.IO) { + private suspend fun getBranch(dir: String): String = withContext(Dispatchers.IO) { try { val builder = ProcessBuilder("git", "rev-parse", "--abbrev-ref", "HEAD") builder.directory(File(dir)) @@ -715,7 +802,7 @@ class IdeProtocolClient( data class IndexTag(val directory: String, val branch: String, val artifactId: String) - suspend fun getTags(artifactId: String): List { + private suspend fun getTags(artifactId: String): List { val workspaceDirs = workspaceDirectories() // Collect branches concurrently using Kotlin coroutines @@ -731,7 +818,7 @@ class IdeProtocolClient( } } - fun readFile(filepath: String): String { + private fun readFile(filepath: String): String { try { val content = ApplicationManager.getApplication().runReadAction { val virtualFile = LocalFileSystem.getInstance().findFileByPath(filepath) @@ -982,4 +1069,19 @@ class IdeProtocolClient( command.setWorkDirectory(project.basePath) return ExecUtil.execAndGetOutput(command).stdout ?: "" } + + private fun getModelByRole( + config: Any, + role: Any + ): Any? { + val experimental = (config as? Map<*, *>)?.get("experimental") as? Map<*, *> + val roleTitle = (experimental?.get("modelRoles") as? Map<*, *>)?.get(role) as? String ?: return null + + val models = (config as? Map<*, *>)?.get("models") as? List<*> + val matchingModel = models?.find { model -> + (model as? Map<*, *>)?.get("title") == roleTitle + } + + return matchingModel + } } \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt index 44da08365..bd1ac8072 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt @@ -48,7 +48,7 @@ fun makeTextArea(): JTextArea { isOpaque = false background = GetTheme().getSecondaryDark() maximumSize = Dimension(400, Short.MAX_VALUE.toInt()) - margin = JBUI.insets(6, 4, 6, 4) + margin = JBUI.insets(6, 8, 6, 4) font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE) preferredSize = Dimension(400, 75) } @@ -398,13 +398,32 @@ class CustomPanel( isEditable = true background = defaultBackground foreground = Color(128, 128, 128, 200) - font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11) - border = EmptyBorder(2, 4, 2, 4) + font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 12) + border = EmptyBorder(8, 8, 8, 8) isOpaque = false isEditable = false cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) - renderer = - DefaultListCellRenderer().apply { horizontalAlignment = SwingConstants.LEFT } + preferredSize = Dimension(200, 30) + + renderer = object : DefaultListCellRenderer() { + override fun getListCellRendererComponent( + list: JList<*>?, + value: Any?, + index: Int, + isSelected: Boolean, + cellHasFocus: Boolean + ): Component { + val component = + super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus) + if (component is JLabel) { + component.border = EmptyBorder(4, 6, 4, 6) + } + return component + } + }.apply { + horizontalAlignment = SwingConstants.LEFT + } + selectedIndex = continueSettingsService.continueState.lastSelectedInlineEditModel?.let { if (modelTitles.isEmpty()) -1 @@ -430,19 +449,16 @@ class CustomPanel( border = EmptyBorder(2, 6, 2, 6) } - val rightPanel = - JPanel(MigLayout("insets 0, fillx")).apply { - isOpaque = false - border = EmptyBorder(0, 0, 0, 0) - add(dropdown, "align right") - add(rightButton, "align right") - } + val rightPanel = JPanel(MigLayout("insets 0, fillx")).apply { + isOpaque = false + add(rightButton, "align right") + } border = EmptyBorder(0, 0, 16, 12) + isOpaque = false add(dropdown, "align left") - add(rightPanel, "align right, split 2") - isOpaque = false + add(rightPanel, "align right") cursor = Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR) } @@ -620,18 +636,7 @@ class CustomButton(text: String, onClick: () -> Unit) : JLabel(text, CENTER) { cornerRadius.toFloat(), cornerRadius.toFloat() ) - if (isHovered) { - val brightenFactor = 1.1f - val brighterColor = - Color( - (background.red * brightenFactor).coerceIn(0f, 255f).toInt(), - (background.green * brightenFactor).coerceIn(0f, 255f).toInt(), - (background.blue * brightenFactor).coerceIn(0f, 255f).toInt() - ) - g2.color = brighterColor - } else { - g2.color = background - } + g2.color = background g2.fill(roundRect) g2.color = foreground g2.drawString( @@ -653,7 +658,7 @@ class CustomTextArea(rows: Int, columns: Int) : JXTextArea("") { if (text.isEmpty()) { g.color = Color(128, 128, 128, 255) g.font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE) - g.drawString("Enter instructions...", 3, 20) + g.drawString("Enter instructions...", 8, 20) } super.paintComponent(g) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt index fda580ed1..bdfaba447 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt @@ -116,7 +116,7 @@ class VerticalDiffBlock( ) acceptButton.setBounds( - x + rejectButton.width + 5, + x + rejectButton.width + 2, y, acceptButton.preferredSize.width, acceptButton.preferredSize.height @@ -134,7 +134,7 @@ class VerticalDiffBlock( private fun createButtons(): Pair { val rejectBtn = - createButton("${getAltKeyLabel()}⇧N", JBColor(0x99FF0000.toInt(), 0x99FF0000.toInt())).apply { + createButton("${getAltKeyLabel()}↑N", JBColor(0x99FF0000.toInt(), 0x99FF0000.toInt())).apply { addActionListener { handleReject(); onAcceptReject(this@VerticalDiffBlock, false) @@ -143,7 +143,7 @@ class VerticalDiffBlock( } val acceptBtn = - createButton("${getAltKeyLabel()}⇧Y", JBColor(0x9900FF00.toInt(), 0x9900FF00.toInt())).apply { + createButton("${getAltKeyLabel()}↑Y", JBColor(0x9900FF00.toInt(), 0x9900FF00.toInt())).apply { addActionListener { handleAccept(); onAcceptReject(this@VerticalDiffBlock, true) @@ -215,18 +215,17 @@ class VerticalDiffBlock( val g2 = g.create() as Graphics2D g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) g2.color = backgroundColor - g2.fillRoundRect(0, 0, width - 1, height - 1, 8, 8) + g2.fillRoundRect(0, 0, width - 1, height - 1, 4, 4) super.paintComponent(g2) g2.dispose() } }.apply { - // This isn't working currently, font color is transparent - foreground = JBColor.WHITE + foreground = Color(240, 240, 240) font = Font("Arial", Font.BOLD, 9) isContentAreaFilled = false isOpaque = false - border = null - preferredSize = Dimension(preferredSize.width, 16) + border = BorderFactory.createEmptyBorder(4, 2, 4, 2) + preferredSize = Dimension(preferredSize.width - 30, 14) cursor = Cursor(Cursor.HAND_CURSOR) } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt index eae59e9cc..03d4f4715 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt @@ -18,6 +18,7 @@ import org.cef.CefApp import org.cef.browser.CefBrowser import org.cef.handler.CefLoadHandlerAdapter import com.intellij.openapi.application.ApplicationInfo +import com.intellij.openapi.util.SystemInfo class ContinueBrowser(val project: Project, url: String) { private val coroutineScope = CoroutineScope( @@ -292,6 +293,12 @@ class ContinueBrowser(val project: Project, url: String) { * it's a simple integer without dot notation, making it easier to compare. */ private fun shouldRenderOffScreen(): Boolean { + // With the 0.0.77 release, non-Mac users have been reporting issues with paste functionality + // in the browser. Disabling OSR for all non-Mac users for now. + if (!SystemInfo.isMac) { + return false + } + val minBuildNumber = 233 val applicationInfo = ApplicationInfo.getInstance() val currentBuildNumber = applicationInfo.build.baselineVersion diff --git a/extensions/intellij/src/main/resources/config_schema.json b/extensions/intellij/src/main/resources/config_schema.json index 6da984ead..f911def9e 100644 --- a/extensions/intellij/src/main/resources/config_schema.json +++ b/extensions/intellij/src/main/resources/config_schema.json @@ -88,7 +88,10 @@ "type": "string" } }, - "required": ["cert", "key"] + "required": [ + "cert", + "key" + ] }, "RequestOptions": { "title": "RequestOptions", @@ -169,7 +172,6 @@ "openai", "free-trial", "anthropic", - "anthropic-vertexai", "cohere", "bedrock", "bedrockimport", @@ -181,11 +183,9 @@ "llama.cpp", "replicate", "gemini", - "gemini-vertexai", "lmstudio", "llamafile", "mistral", - "mistral-vertexai", "deepinfra", "groq", "fireworks", @@ -198,7 +198,9 @@ "sambanova", "nvidia", "vllm", - "cerebras" + "cerebras", + "vertexai", + "askSage" ], "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)", @@ -232,7 +234,8 @@ "### OpenRouter\nOpenRouter offers a single API to access almost any language model. To get started, obtain an API key from [their console](https://openrouter.ai/settings/keys).", "### NVIDIA NIMs\nNVIDIA offers a single API to access almost any language model. To find out more, visit the [LLM APIs Documentation](https://docs.api.nvidia.com/nim/reference/llm-apis).\nFor information specific to getting a key, please check out the [docs here](https://docs.nvidia.com/nim/large-language-models/latest/getting-started.html#option-1-from-api-catalog)", "### vLLM\nvLLM is a highly performant way of hosting LLMs for a team. To get started, follow their [quickstart](https://docs.vllm.ai/en/latest/getting_started/quickstart.html) to set up your server.", - "### Cerebras\nCerebras Inference uses specialized silicon to provides superfast inference. To get started, get your API keys from [their console](https://cloud.cerebras.ai/)." + "### Cerebras\nCerebras Inference uses specialized silicon to provides superfast inference. To get started, get your API keys from [their console](https://cloud.cerebras.ai/).", + "### Ask Sage\nAsk Sage is an agnostic hosted service that provides language models. To get started with Ask Sage:\n1. Obtain an API key from your account. For more information, visit [Ask Sage](https://docs.asksage.ai/).\n2. Paste the API key below.\n3. Select a model preset.\n> [Reference](https://docs.asksage.ai/)" ], "type": "string" }, @@ -350,6 +353,7 @@ "promptTemplates": { "title": "Prompt Templates", "markdownDescription": "A mapping of prompt template name ('edit' is currently the only one used in Continue) to a string giving the prompt template. See [here](https://docs.continue.dev/model-setup/configuration#customizing-the-edit-prompt) for an example.", + "x-intellij-html-description": "A mapping of prompt template name ('edit' is currently the only one used in Continue) to a string giving the prompt template. See here for an example.", "type": "object", "additionalProperties": { "type": "string" @@ -398,7 +402,11 @@ "apiType": { "title": "Api Type", "markdownDescription": "OpenAI API type, either `openai` or `azure`", - "enum": ["openai", "azure"] + "x-intellij-html-description": "OpenAI API type, either openai or azure", + "enum": [ + "openai", + "azure" + ] }, "apiVersion": { "title": "Api Version", @@ -421,7 +429,11 @@ } } }, - "required": ["title", "provider", "model"], + "required": [ + "title", + "provider", + "model" + ], "allOf": [ { "if": { @@ -431,7 +443,9 @@ } }, "not": { - "required": ["provider"] + "required": [ + "provider" + ] } }, "then": { @@ -459,46 +473,67 @@ ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { - "required": ["apiKey"] + "required": [ + "apiKey" + ] } }, { "if": { "properties": { "provider": { - "enum": ["bedrockimport"] + "enum": [ + "bedrockimport" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { - "required": ["modelArn"] + "required": [ + "modelArn" + ] } }, { "if": { "properties": { "provider": { - "enum": ["huggingface-tgi", "huggingface-inference-api"] + "enum": [ + "huggingface-tgi", + "huggingface-inference-api" + ] } } }, "then": { - "required": ["apiBase"] + "required": [ + "apiBase" + ] }, - "required": ["provider"] + "required": [ + "provider" + ] }, { "if": { "properties": { "provider": { - "enum": ["openai"] + "enum": [ + "openai" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -518,10 +553,14 @@ "if": { "properties": { "provider": { - "enum": ["cloudflare"] + "enum": [ + "cloudflare" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -579,10 +618,14 @@ "if": { "properties": { "provider": { - "enum": ["openai"] + "enum": [ + "openai" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -614,10 +657,14 @@ "if": { "properties": { "provider": { - "enum": ["replicate"] + "enum": [ + "replicate" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -642,7 +689,8 @@ } ] }, - "markdownDescription": "Select a pre-defined option, or find an exact model ID from Replicate [here](https://replicate.com/collections/streaming-language-models)." + "markdownDescription": "Select a pre-defined option, or find an exact model ID from Replicate [here](https://replicate.com/collections/streaming-language-models).", + "x-intellij-html-description": "Select a pre-defined option, or find an exact model ID from Replicate here." } } }, @@ -650,10 +698,14 @@ "if": { "properties": { "provider": { - "enum": ["free-trial"] + "enum": [ + "free-trial" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -677,7 +729,9 @@ "if": { "properties": { "provider": { - "enum": ["openai"] + "enum": [ + "openai" + ] }, "apiType": { "not": { @@ -685,7 +739,9 @@ } } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -747,10 +803,14 @@ "if": { "properties": { "provider": { - "enum": ["anthropic"] + "enum": [ + "anthropic" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -791,40 +851,21 @@ "if": { "properties": { "provider": { - "enum": ["anthropic-vertexai"] + "enum": [ + "cohere" + ] } }, - "required": ["provider"] + "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" - } + "enum": [ + "command-r", + "command-r-plus" ] } } @@ -834,27 +875,14 @@ "if": { "properties": { "provider": { - "enum": ["cohere"] + "enum": [ + "bedrock" + ] } }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "enum": ["command-r", "command-r-plus"] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["bedrock"] - } - }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -879,15 +907,19 @@ "if": { "properties": { "provider": { - "enum": ["sagemaker"] + "enum": [ + "sagemaker" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { "model": { - "markdownDescription": "SageMaker endpoint name" + "description": "SageMaker endpoint name" } } } @@ -896,10 +928,14 @@ "if": { "properties": { "provider": { - "enum": ["gemini"] + "enum": [ + "gemini" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -929,39 +965,14 @@ "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" } + "enum": [ + "together" ] } }, - "required": ["projectId", "region"] - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["together"] - } - }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -989,7 +1000,8 @@ "type": "string" } ], - "markdownDescription": "Select a pre-defined option, or find an exact model string from Together AI [here](https://docs.together.ai/docs/inference-models)." + "markdownDescription": "Select a pre-defined option, or find an exact model string from Together AI [here](https://docs.together.ai/docs/inference-models).", + "x-intellij-html-description": "Select a pre-defined option, or find an exact model string from Together AI here." } } } @@ -998,15 +1010,20 @@ "if": { "properties": { "provider": { - "enum": ["deepinfra"] + "enum": [ + "deepinfra" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { "model": { - "markdownDescription": "Find the model name you want to use from DeepInfra [here](https://deepinfra.com/models?type=text-generation)." + "markdownDescription": "Find the model name you want to use from DeepInfra [here](https://deepinfra.com/models?type=text-generation).", + "x-intellij-html-description": "Find the model name you want to use from DeepInfra here." } } } @@ -1024,7 +1041,9 @@ ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -1073,10 +1092,14 @@ "if": { "properties": { "provider": { - "enum": ["ollama"] + "enum": [ + "ollama" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -1118,7 +1141,8 @@ "type": "string" } ], - "markdownDescription": "Select a pre-defined option, or find the exact model tag for an Ollama model [here](https://ollama.ai/library)." + "markdownDescription": "Select a pre-defined option, or find the exact model tag for an Ollama model [here](https://ollama.ai/library).", + "x-intellij-html-description": "Select a pre-defined option, or find the exact model tag for an Ollama model here." } } } @@ -1127,10 +1151,14 @@ "if": { "properties": { "provider": { - "enum": ["mistral"] + "enum": [ + "mistral" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -1152,37 +1180,34 @@ "if": { "properties": { "provider": { - "enum": ["mistral-vertexai"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "codestral", - "mistral-nemo", - "mistral-large" - ] - }, - { "type": "string" } + "enum": [ + "vertexai" ] } }, - "required": ["projectId", "region"] + "required": [ + "provider" + ] + }, + "then": { + "required": [ + "projectId", + "region" + ] } }, { "if": { "properties": { "provider": { - "enum": ["deepseek"] + "enum": [ + "deepseek" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -1199,7 +1224,10 @@ } }, "model": { - "enum": ["deepseek-chat", "deepseek-coder"] + "enum": [ + "deepseek-chat", + "deepseek-coder" + ] } } } @@ -1208,10 +1236,14 @@ "if": { "properties": { "provider": { - "enum": ["groq"] + "enum": [ + "groq" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -1236,15 +1268,21 @@ "if": { "properties": { "provider": { - "enum": ["fireworks"] + "enum": [ + "fireworks" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { "model": { - "enum": ["starcoder-7b"] + "enum": [ + "starcoder-7b" + ] } } } @@ -1256,20 +1294,30 @@ "const": "azure" } }, - "required": ["apiType"] + "required": [ + "apiType" + ] }, "then": { - "required": ["engine", "apiVersion", "apiBase"] + "required": [ + "engine", + "apiVersion", + "apiBase" + ] } }, { "if": { "properties": { "provider": { - "enum": ["openai"] + "enum": [ + "openai" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -1286,7 +1334,9 @@ "const": "llamafile" } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -1300,15 +1350,22 @@ "if": { "properties": { "provider": { - "enum": ["cerebras"] + "enum": [ + "cerebras" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { "model": { - "enum": ["llama3.1-8b", "llama3.1-70b"] + "enum": [ + "llama3.1-8b", + "llama3.1-70b" + ] } } } @@ -1317,10 +1374,14 @@ "if": { "properties": { "provider": { - "enum": ["text-gen-webui"] + "enum": [ + "text-gen-webui" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -1334,10 +1395,14 @@ "if": { "properties": { "provider": { - "enum": ["flowise"] + "enum": [ + "flowise" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -1364,7 +1429,10 @@ "type": "string" } }, - "required": ["key", "value"] + "required": [ + "key", + "value" + ] } }, "additionalFlowiseConfiguration": { @@ -1383,7 +1451,10 @@ "description": "Configuration Property value" } }, - "required": ["key", "value"] + "required": [ + "key", + "value" + ] } }, "model": { @@ -1457,10 +1528,14 @@ "if": { "properties": { "provider": { - "enum": ["watsonx"] + "enum": [ + "watsonx" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -1492,30 +1567,80 @@ ] } }, - "required": ["watsonxUrl", "watsonxProjectId"] + "required": [ + "watsonxUrl", + "watsonxProjectId" + ] } }, { "if": { "properties": { "provider": { - "enum": ["sambanova"] + "enum": [ + "sambanova" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { "model": { "anyOf": [ { - "enum": ["llama3.1-8b", "llama3.1-70b", "llama3.1-405b"] + "enum": [ + "llama3.1-8b", + "llama3.1-70b", + "llama3.1-405b" + ] }, { "type": "string" } ], - "markdownDescription": "Select a pre-defined option." + "description": "Select a pre-defined option." + } + } + } + }, + { + "if": { + "properties": { + "provider": { + "enum": [ + "ask-sage" + ] + } + }, + "required": [ + "provider" + ] + }, + "then": { + "properties": { + "model": { + "anyOf": [ + { + "enum": [ + "gpt-4o", + "gpt-4o-mini", + "gpt-4gov", + "gpt-4ogov", + "claude-3.5-sonnet", + "claude-3-opus", + "mistral-large", + "llama-3-chat", + "gemini-pro", + "AUTODETECT" + ] + }, + { + "type": "string" + } + ] } } } @@ -1547,7 +1672,9 @@ "type": "string" } }, - "required": ["default"] + "required": [ + "default" + ] }, "SlashCommand": { "title": "SlashCommand", @@ -1604,7 +1731,9 @@ "if": { "properties": { "name": { - "enum": ["issue"] + "enum": [ + "issue" + ] } } }, @@ -1617,17 +1746,23 @@ "description": "Enter the URL of the GitHub repository for which you want to generate the issue." } }, - "required": ["repositoryUrl"] + "required": [ + "repositoryUrl" + ] } }, - "required": ["params"] + "required": [ + "params" + ] } }, { "if": { "properties": { "name": { - "enum": ["edit"] + "enum": [ + "edit" + ] } } }, @@ -1637,11 +1772,12 @@ "properties": { "recap": { "type": "boolean", - "markdownDescription": "If recap is set to `true`, Continue will generate a summary of the changes after making the edit." + "markdownDescription": "If recap is set to `true`, Continue will generate a summary of the changes after making the edit.", + "x-intellij-html-description": "If recap is set to true, Continue will generate a summary of the changes after making the edit." }, "tokenLimit": { "type": "integer", - "markdownDescription": "By default, Continue doesn't let you edit extremely large ranges (beyond 1,200 tokens), because the LLM is unlikely to succeed. But if you would like to override this limit with the understanding of possible failure you may do so here." + "description": "By default, Continue doesn't let you edit extremely large ranges (beyond 1,200 tokens), because the LLM is unlikely to succeed. But if you would like to override this limit with the understanding of possible failure you may do so here." } } } @@ -1652,7 +1788,9 @@ "if": { "properties": { "name": { - "enum": ["share"] + "enum": [ + "share" + ] } } }, @@ -1662,7 +1800,8 @@ "properties": { "outputDir": { "type": "string", - "markdownDescription": "If outputDir is set to `.` or begins with `./` or `.\\`, file will be saved to the current workspace or a subdirectory thereof, respectively. `~` can similarly be used to specify the user's home directory." + "markdownDescription": "If outputDir is set to `.` or begins with `./` or `.\\`, file will be saved to the current workspace or a subdirectory thereof, respectively. `~` can similarly be used to specify the user's home directory.", + "x-intellij-html-description": "If outputDir is set to . or begins with ./ or .\\, file will be saved to the current workspace or a subdirectory thereof, respectively. ~ can similarly be used to specify the user's home directory." } } } @@ -1673,7 +1812,9 @@ "if": { "properties": { "name": { - "enum": ["commit"] + "enum": [ + "commit" + ] } } }, @@ -1683,7 +1824,8 @@ "properties": { "includeUnstaged": { "type": "boolean", - "markdownDescription": "If includeUnstaged is set to true, then unstaged changes are also included in the prompt, otherwise only staged changes are included. Default is false." + "markdownDescription": "If set to `true`, then unstaged changes are also included in the prompt, otherwise only staged changes are included. Default is `false`.", + "x-intellij-html-description": "If set to true, then unstaged changes are also included in the prompt, otherwise only staged changes are included. Default is false." } } } @@ -1691,7 +1833,10 @@ } } ], - "required": ["name", "description"] + "required": [ + "name", + "description" + ] }, "CustomCommand": { "title": "CustomCommand", @@ -1710,7 +1855,11 @@ "type": "string" } }, - "required": ["name", "prompt", "description"] + "required": [ + "name", + "prompt", + "description" + ] }, "ContextProviderWithParams": { "title": "ContextProviderWithParams", @@ -1790,7 +1939,9 @@ "if": { "properties": { "name": { - "enum": ["discord"] + "enum": [ + "discord" + ] } } }, @@ -1823,11 +1974,15 @@ "description": "The name of the channel" } }, - "required": ["id"] + "required": [ + "id" + ] } } }, - "required": ["discordKey"] + "required": [ + "discordKey" + ] } } }, @@ -1836,14 +1991,18 @@ { "properties": { "params": { - "required": ["guildId"] + "required": [ + "guildId" + ] } } }, { "properties": { "params": { - "required": ["channels"] + "required": [ + "channels" + ] } } } @@ -1856,7 +2015,9 @@ "if": { "properties": { "name": { - "enum": ["google"] + "enum": [ + "google" + ] } } }, @@ -1869,14 +2030,26 @@ "description": "Your API key for https://serper.dev in order to get Google search results" } }, - "required": ["serperApiKey"] + "required": [ + "serperApiKey" + ] } }, - "required": ["params"] + "required": [ + "params" + ] } }, { - "if": { "properties": { "name": { "enum": ["web"] } } }, + "if": { + "properties": { + "name": { + "enum": [ + "web" + ] + } + } + }, "then": { "properties": { "params": { @@ -1890,14 +2063,18 @@ } } }, - "required": ["params"] + "required": [ + "params" + ] } }, { "if": { "properties": { "name": { - "enum": ["open"] + "enum": [ + "open" + ] } } }, @@ -1919,7 +2096,9 @@ "if": { "properties": { "name": { - "enum": ["issue"] + "enum": [ + "issue" + ] } } }, @@ -1948,24 +2127,37 @@ "type": { "type": "string", "description": "The type of issues to search for", - "enum": ["open", "closed", "all"] + "enum": [ + "open", + "closed", + "all" + ] } }, - "required": ["owner", "repo"] + "required": [ + "owner", + "repo" + ] } } }, - "required": ["repos"] + "required": [ + "repos" + ] } }, - "required": ["params"] + "required": [ + "params" + ] } }, { "if": { "properties": { "name": { - "enum": ["database"] + "enum": [ + "database" + ] } } }, @@ -1986,7 +2178,11 @@ "connection_type": { "type": "string", "description": "The type of database (e.g., 'postgres', 'mysql')", - "enum": ["postgres", "mysql", "sqlite"] + "enum": [ + "postgres", + "mysql", + "sqlite" + ] }, "connection": { "type": "object", @@ -2019,21 +2215,31 @@ "required": [] } }, - "required": ["name", "connection_type", "connection"] + "required": [ + "name", + "connection_type", + "connection" + ] } } }, - "required": ["connections"] + "required": [ + "connections" + ] } }, - "required": ["params"] + "required": [ + "params" + ] } }, { "if": { "properties": { "name": { - "enum": ["gitlab-mr"] + "enum": [ + "gitlab-mr" + ] } } }, @@ -2054,17 +2260,23 @@ "description": "If you have code selected, filters out comments that aren't related to the selection." } }, - "required": ["token"] + "required": [ + "token" + ] } }, - "required": ["params"] + "required": [ + "params" + ] } }, { "if": { "properties": { "name": { - "enum": ["jira"] + "enum": [ + "jira" + ] } } }, @@ -2090,7 +2302,8 @@ }, "apiVersion": { "type": "integer", - "markdownDescription": "This context provider supports both Jira API version 2 and 3. It will use version 3 by default since that's what the cloud version uses, but if you have the datacenter version of Jira, you'll need to set the API Version to 2 using the `apiVersion` property." + "markdownDescription": "This context provider supports both Jira API version 2 and 3. It will use version 3 by default since that's what the cloud version uses, but if you have the datacenter version of Jira, you'll need to set the API Version to 2 using the `apiVersion` property.", + "x-intellij-html-description": "This context provider supports both Jira API version 2 and 3. It will use version 3 by default since that's what the cloud version uses, but if you have the datacenter version of Jira, you'll need to set the API Version to 2 using the apiVersion property." }, "requestOptions": { "title": "Request Options", @@ -2110,17 +2323,24 @@ ] } }, - "required": ["domain", "token"] + "required": [ + "domain", + "token" + ] } }, - "required": ["params"] + "required": [ + "params" + ] } }, { "if": { "properties": { "name": { - "enum": ["http"] + "enum": [ + "http" + ] } } }, @@ -2138,17 +2358,24 @@ "type": "object" } }, - "required": ["url"] + "required": [ + "url" + ] } }, - "required": ["params"] + "required": [ + "params" + ] } }, { "if": { "properties": { "name": { - "enum": ["codebase", "folder"] + "enum": [ + "codebase", + "folder" + ] } } }, @@ -2183,7 +2410,9 @@ "if": { "properties": { "name": { - "enum": ["postgres"] + "enum": [ + "postgres" + ] } } }, @@ -2235,14 +2464,22 @@ } } }, - "required": ["host", "port", "user", "password", "database"] + "required": [ + "host", + "port", + "user", + "password", + "database" + ] } }, { "if": { "properties": { "name": { - "enum": ["greptile"] + "enum": [ + "greptile" + ] } } }, @@ -2265,11 +2502,16 @@ } } }, - "required": ["GreptileToken", "GithubToken"] + "required": [ + "GreptileToken", + "GithubToken" + ] } } ], - "required": ["name"] + "required": [ + "name" + ] }, "SerializedContinueConfig": { "title": "config.json", @@ -2303,18 +2545,23 @@ "description": "The URL path to a favicon for the site - by default, it will be `/favicon.ico` path from the Start URL" } }, - "required": ["title", "startUrl"] + "required": [ + "title", + "startUrl" + ] } }, "allowAnonymousTelemetry": { "title": "Allow Anonymous Telemetry", - "markdownDescription": "If this field is set to True, we will collect anonymous telemetry as described in the documentation page on telemetry. If set to `false`, we will not collect any data. Learn more in [the docs](https://docs.continue.dev/telemetry).", + "markdownDescription": "If this field is set to `true`, we will collect anonymous telemetry as described in the documentation page on telemetry. If set to `false`, we will not collect any data. Learn more in [the docs](https://docs.continue.dev/telemetry).", + "x-intellij-html-description": "If this field is set to `true`, we will collect anonymous telemetry as described in the documentation page on telemetry. If set to `false`, we will not collect any data. Learn more in the docs.", "default": true, "type": "boolean" }, "models": { "title": "Models", "markdownDescription": "Learn about setting up models in [the documentation](https://docs.continue.dev/model-setup/overview).", + "x-intellij-html-description": "Learn about setting up models in the documentation.", "default": [ { "title": "GPT-4 (trial)", @@ -2363,6 +2610,7 @@ "slashCommands": { "title": "Slash Commands", "markdownDescription": "An array of slash commands that let you take custom actions from the sidebar. Learn more in the [documentation](https://docs.continue.dev/customization/slash-commands).", + "x-intellij-html-description": "An array of slash commands that let you take custom actions from the sidebar. Learn more in the documentation.", "default": [], "type": "array", "items": { @@ -2371,7 +2619,8 @@ }, "customCommands": { "title": "Custom Commands", - "markdownDescription": "An array of custom commands that allow you to reuse prompts. Each has name, description, and prompt properties. When you enter / in the text input, it will act as a shortcut to the prompt. Learn more in the [documentation](https://docs.continue.dev/customization/slash-commands#custom-commands-use-natural-language).", + "markdownDescription": "An array of custom commands that allow you to reuse prompts. Each has name, description, and prompt properties. When you enter `/` in the text input, it will act as a shortcut to the prompt. Learn more in the [documentation](https://docs.continue.dev/customization/slash-commands#custom-commands-use-natural-language).", + "x-intellij-html-description": "An array of custom commands that allow you to reuse prompts. Each has name, description, and prompt properties. When you enter / in the text input, it will act as a shortcut to the prompt. Learn more in the documentation.", "default": [ { "name": "test", @@ -2387,6 +2636,7 @@ "contextProviders": { "title": "Context Providers", "markdownDescription": "A list of ContextProvider objects that can be used to provide context to the LLM by typing '@'. Read more about ContextProviders in [the documentation](https://docs.continue.dev/customization/context-providers).", + "x-intellij-html-description": "A list of ContextProvider objects that can be used to provide context to the LLM by typing '@'. Read more about ContextProviders in the documentation.", "default": [], "type": "array", "items": { @@ -2401,18 +2651,21 @@ "disableIndexing": { "title": "Disable Indexing", "markdownDescription": "If set to `true`, Continue will not index the codebase. This is mainly used for debugging purposes.", + "x-intellij-html-description": "If set to true, Continue will not index the codebase. This is mainly used for debugging purposes.", "default": false, "type": "boolean" }, "disableSessionTitles": { "title": "Disable Session Titles", "markdownDescription": "If set to `true`, Continue will not make extra requests to the LLM to generate a summary title of each session.", + "x-intellij-html-description": "If set to true, Continue will not make extra requests to the LLM to generate a summary title of each session.", "default": false, "type": "boolean" }, "embeddingsProvider": { "title": "Embeddings Provider", - "markdownDescription": "The method that will be used to generate codebase embeddings. The default is transformers.js, which will run locally in the browser. Learn about the other options [here](https://docs.continue.dev/features/codebase-embeddings#embeddings-providers).", + "markdownDescription": "The method that will be used to generate codebase embeddings. The default is `transformers.js`, which will run locally in the browser. Learn about the other options [here](https://docs.continue.dev/features/codebase-embeddings#embeddings-providers).", + "x-intellij-html-description": "The method that will be used to generate codebase embeddings. The default is transformers.js, which will run locally in the browser. Learn about the other options here.

Note: transformers.js currently cannot be used in JetBrains.", "type": "object", "properties": { "provider": { @@ -2428,7 +2681,7 @@ "nvidia", "bedrock", "sagemaker", - "vertex" + "vertexai" ] }, "model": { @@ -2470,69 +2723,94 @@ "type": "string" } }, - "required": ["provider"], + "required": [ + "provider" + ], "allOf": [ { "if": { "properties": { "provider": { - "enum": ["cohere", "voyage", "nvidia", "gemini"] + "enum": [ + "cohere", + "voyage", + "nvidia", + "gemini" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { - "required": ["apiKey"] + "required": [ + "apiKey" + ] } }, { "if": { "properties": { "provider": { - "enum": ["sagemaker"] + "enum": [ + "sagemaker" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { "model": { - "markdownDescription": "SageMaker endpoint name" + "description": "SageMaker endpoint name" } }, - "required": ["model"] + "required": [ + "model" + ] } }, { "if": { "properties": { "provider": { - "enum": ["vertex"] + "enum": [ + "vertexai" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { "projectId": { - "markdownDescription": "The name of your vertexAI project" + "description": "The name of your VertexAI project" }, "region": { - "markdownDescription": "The region your vertexAI model is hosted in - typically central1", + "description": "The region your VertexAI model is hosted in - typically central1", "default": "central1" }, "model": { "default": "text-embedding-004" } }, - "required": ["projectId", "model", "region"] + "required": [ + "projectId", + "model", + "region" + ] } } ] }, "reranker": { "title": "Reranker", - "markdownDescription": "The reranker is responsible for selecting the final results when retrieving snippets from your codebase.", + "description": "The reranker is responsible for selecting the final results when retrieving snippets from your codebase.", "type": "object", "properties": { "name": { @@ -2548,16 +2826,22 @@ "type": "object" } }, - "required": ["name"], + "required": [ + "name" + ], "allOf": [ { "if": { "properties": { "name": { - "enum": ["cohere"] + "enum": [ + "cohere" + ] } }, - "required": ["name"] + "required": [ + "name" + ] }, "then": { "properties": { @@ -2579,7 +2863,9 @@ "type": "string" } }, - "required": ["apiKey"] + "required": [ + "apiKey" + ] } } } @@ -2588,10 +2874,14 @@ "if": { "properties": { "name": { - "enum": ["llm"] + "enum": [ + "llm" + ] } }, - "required": ["name"] + "required": [ + "name" + ] }, "then": { "properties": { @@ -2602,7 +2892,9 @@ "type": "string" } }, - "required": ["modelTitle"] + "required": [ + "modelTitle" + ] } } } @@ -2611,10 +2903,14 @@ "if": { "properties": { "name": { - "enum": ["voyage"] + "enum": [ + "voyage" + ] } }, - "required": ["name"] + "required": [ + "name" + ] }, "then": { "properties": { @@ -2633,7 +2929,9 @@ ] } }, - "required": ["apiKey"] + "required": [ + "apiKey" + ] } } } @@ -2642,10 +2940,14 @@ "if": { "properties": { "name": { - "enum": ["huggingface-tei"] + "enum": [ + "huggingface-tei" + ] } }, - "required": ["name"] + "required": [ + "name" + ] }, "then": { "properties": { @@ -2658,16 +2960,21 @@ }, "truncate": { "type": "boolean", - "description": "Wether to truncate long sequences to the maximum allowed context length.", + "description": "Whether to truncate long sequences to the maximum allowed context length.", "default": false }, "truncation_direction": { - "enum": ["Right", "Left"], - "markdownDescription": "Wether to truncate sequences from the `left` or `right`.", + "enum": [ + "Right", + "Left" + ], + "description": "Whether to truncate sequences from the left or right.", "default": "Right" } }, - "required": ["apiBase"] + "required": [ + "apiBase" + ] } }, "if": { @@ -2678,7 +2985,9 @@ } }, "then": { - "required": ["truncation_direction"] + "required": [ + "truncation_direction" + ] } } } @@ -2687,6 +2996,7 @@ "tabAutocompleteModel": { "title": "Tab Autocomplete Model", "markdownDescription": "The model used for tab autocompletion. If undefined, Continue will default to using starcoder2:3b on a local Ollama instance.\n\n*IMPORTANT*:\n\nIf you use a custom model, ensure that it is one trained for fill-in-the-middle completions. An instruct model is typically not well-suited to autocomplete and you may receive unsatisfactory completions.", + "x-intellij-html-description": "The model used for tab autocompletion. If undefined, Continue will default to using starcoder2:3b on a local Ollama instance.

IMPORTANT:

If you use a custom model, ensure that it is one trained for fill-in-the-middle completions. An instruct model is typically not well-suited to autocomplete and you may receive unsatisfactory completions.", "default": { "title": "Tab Autocomplete Model", "provider": "ollama", @@ -2708,6 +3018,7 @@ "title": "TabAutocompleteOptions", "type": "object", "markdownDescription": "These options let you customize your tab-autocomplete experience. Read about all options in [the docs](https://docs.continue.dev/features/tab-autocomplete#configuration-options).", + "x-intellij-html-description": "These options let you customize your tab-autocomplete experience. Read about all options in the docs.", "properties": { "disable": { "type": "boolean", @@ -2738,12 +3049,20 @@ "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." }, "multilineCompletions": { - "enum": ["always", "never", "auto"], + "enum": [ + "always", + "never", + "auto" + ], "description": "If set to true, Continue will only complete a single line at a time." }, "useCache": { @@ -2772,7 +3091,10 @@ "type": "object", "properties": { "codeBlockToolbarPosition": { - "enum": ["top", "bottom"], + "enum": [ + "top", + "bottom" + ], "default": "top", "description": "Whether to show the copy and apply code buttons at the top or bottom of code blocks in the sidebar." }, @@ -2787,6 +3109,7 @@ "showChatScrollbar": { "title": "Show Chat Scrollbar", "markdownDescription": "If set to `true`, a scrollbar will be displayed in the chat window to navigate through messages.", + "x-intellij-html-description": "If set to true, a scrollbar will be displayed in the chat window to navigate through messages.", "default": false, "type": "boolean" } @@ -2797,7 +3120,10 @@ "properties": { "provider": { "type": "string", - "enum": ["posthog", "logstash"], + "enum": [ + "posthog", + "logstash" + ], "description": "The 3rd party analytics provider to use.", "default": "posthog", "markdownEnumDescriptions": [ @@ -2814,30 +3140,40 @@ "description": "The client key to use for analytics" } }, - "required": ["provider"], + "required": [ + "provider" + ], "allOf": [ { "if": { "properties": { "provider": { - "enum": ["posthog"] + "enum": [ + "posthog" + ] } } }, "then": { - "required": ["clientKey"] + "required": [ + "clientKey" + ] } }, { "if": { "properties": { "provider": { - "enum": ["logstash"] + "enum": [ + "logstash" + ] } } }, "then": { - "required": ["url"] + "required": [ + "url" + ] } } ] @@ -2909,7 +3245,10 @@ "default": false } }, - "required": ["prompt", "title"] + "required": [ + "prompt", + "title" + ] }, "description": "Quick actions are a way to add custom commands to the Code Lens of function and class declarations." }, @@ -2943,4 +3282,4 @@ } } } -} +} \ No newline at end of file diff --git a/extensions/intellij/src/main/resources/continue_tutorial.java b/extensions/intellij/src/main/resources/continue_tutorial.java new file mode 100644 index 000000000..41ac854c0 --- /dev/null +++ b/extensions/intellij/src/main/resources/continue_tutorial.java @@ -0,0 +1,55 @@ +/* _________ _____ _____ + __ ____/______ _______ __ /____(_)_______ ____ _______ + _ / _ __ \__ __ \_ __/__ / __ __ \_ / / /_ _ \ + / /___ / /_/ /_ / / // /_ _ / _ / / // /_/ / / __/ + \____/ \____/ /_/ /_/ \__/ /_/ /_/ /_/ \__,_/ \___/ + + Chat, Edit, and Autocomplete tutorial +*/ + + +/* ————————————————————————————————————————————————— Chat ————————————————————————————————————————————————— */ + +// Highlight the code below +// Press [Cmd/Ctrl + J] to add to Chat +// Try asking Continue "what sorting algorithm is this?" +public static int[] sortingAlgorithm(int[] x) { + for (int i = 0; i < x.length; i++) { + for (int j = 0; j < x.length - 1; j++) { + if (x[j] > x[j + 1]) { + int temp = x[j]; + x[j] = x[j + 1]; + x[j + 1] = temp; + } + } + } + return x; +} + +/* ————————————————————————————————————————————————— Edit ————————————————————————————————————————————————— */ + +// Highlight the code below +// Press [Cmd/Ctrl + I] to Edit +// Try asking Continue to "make this more readable" +public static int[] sortingAlgorithm2(int[] x) { + for (int i = 0; i < x.length; i++) { + for (int j = 0; j < x.length - 1; j++) { + if (x[j] > x[j + 1]) { + int temp = x[j]; + x[j] = x[j + 1]; + x[j + 1] = temp; + } + } + } + return x; +} + +/* ————————————————————————————————————————————— Autocomplete —————————————————————————————————————————————— */ + +// Place cursor after `sortingAlgorithm...` below and press [Enter] +// Press [Tab] to accept the Autocomplete suggestion + +// Basic assertion for sortingAlgorithm... + + +/* —————————————————— Learn more at https://docs.continue.dev/getting-started/overview ——————————————————— */ diff --git a/extensions/intellij/src/main/resources/continue_tutorial.py b/extensions/intellij/src/main/resources/continue_tutorial.py index e2a4d59e7..16a297c16 100644 --- a/extensions/intellij/src/main/resources/continue_tutorial.py +++ b/extensions/intellij/src/main/resources/continue_tutorial.py @@ -7,8 +7,12 @@ Chat, Edit, and Autocomplete tutorial """ -# ———————————————————— Chat [Cmd/Ctrl + J]: Ask "what sorting algorithm is this?" ———————————————————— +# ————————————————————————————————————————————————— Chat ————————————————————————————————————————————————— # + +## Highlight the code below +## Press [Cmd/Ctrl + J] to add to Chat +## Try asking Continue "what sorting algorithm is this?" def sorting_algorithm(x): for i in range(len(x)): for j in range(len(x) - 1): @@ -16,8 +20,12 @@ def sorting_algorithm(x): x[j], x[j + 1] = x[j + 1], x[j] return x -# —————————————————— Edit [Cmd/Ctrl + I]: Tell Continue to "make this more readable" ————————————————— +# ————————————————————————————————————————————————— Edit ————————————————————————————————————————————————— # + +## Highlight the code below +## Press [Cmd/Ctrl + I] to Edit +## Try asking Continue to "make this more readable" def sorting_algorithm(x): for i in range(len(x)): for j in range(len(x) - 1): @@ -25,9 +33,12 @@ def sorting_algorithm(x): x[j], x[j + 1] = x[j + 1], x[j] return x -# ——————————————— Autocomplete [Tab]: Place cursor after `:` below and press [Enter] ————————————————— +# ————————————————————————————————————————————— Autocomplete —————————————————————————————————————————————— # -# Basic assertion for sorting_algorithm: +## Place cursor after `sorting_algorithm...` below and press [Enter] +## Press [Tab] to accept the Autocomplete suggestion + +# Basic assertion for sorting_algorithm... -"—————————————————— Learn more at https://docs.continue.dev/getting-started/overview ————————————————" \ No newline at end of file +# —————————————————— Learn more at https://docs.continue.dev/getting-started/overview ——————————————————— # diff --git a/extensions/intellij/src/main/resources/continue_tutorial.ts b/extensions/intellij/src/main/resources/continue_tutorial.ts new file mode 100644 index 000000000..301fc248c --- /dev/null +++ b/extensions/intellij/src/main/resources/continue_tutorial.ts @@ -0,0 +1,55 @@ +/* _________ _____ _____ + __ ____/______ _______ __ /____(_)_______ ____ _______ + _ / _ __ \__ __ \_ __/__ / __ __ \_ / / /_ _ \ + / /___ / /_/ /_ / / // /_ _ / _ / / // /_/ / / __/ + \____/ \____/ /_/ /_/ \__/ /_/ /_/ /_/ \__,_/ \___/ + + Chat, Edit, and Autocomplete tutorial +*/ + + +/* ————————————————————————————————————————————————— Chat ————————————————————————————————————————————————— */ + +// Highlight the code below +// Press [Cmd/Ctrl + J] to add to Chat +// Try asking Continue "what sorting algorithm is this?" +function sortingAlgorithm(x: number[]): number[] { + for (let i = 0; i < x.length; i++) { + for (let j = 0; j < x.length - 1; j++) { + if (x[j] > x[j + 1]) { + let temp = x[j]; + x[j] = x[j + 1]; + x[j + 1] = temp; + } + } + } + return x; +} + +/* ————————————————————————————————————————————————— Edit ————————————————————————————————————————————————— */ + +// Highlight the code below +// Press [Cmd/Ctrl + I] to Edit +// Try asking Continue to "make this more readable" +function sortingAlgorithm2(x: number[]): number[] { + for (let i = 0; i < x.length; i++) { + for (let j = 0; j < x.length - 1; j++) { + if (x[j] > x[j + 1]) { + let temp = x[j]; + x[j] = x[j + 1]; + x[j + 1] = temp; + } + } + } + return x; +} + +/* ————————————————————————————————————————————— Autocomplete —————————————————————————————————————————————— */ + +// Place cursor after `sortingAlgorithm...` below and press [Enter] +// Press [Tab] to accept the Autocomplete suggestion + +// Basic assertion for sortingAlgorithm... + + +/* —————————————————— Learn more at https://docs.continue.dev/getting-started/overview ——————————————————— */ diff --git a/extensions/intellij/src/main/resources/webview/index.html b/extensions/intellij/src/main/resources/webview/index.html index be67d62c9..dc4a91a3e 100644 --- a/extensions/intellij/src/main/resources/webview/index.html +++ b/extensions/intellij/src/main/resources/webview/index.html @@ -1,3 +1,4 @@ +@@ -1,18 +0,0 @@ diff --git a/extensions/intellij/src/main/resources/webview/logos/anthropic.png b/extensions/intellij/src/main/resources/webview/logos/anthropic.png deleted file mode 100644 index 9adf1b71b..000000000 Binary files a/extensions/intellij/src/main/resources/webview/logos/anthropic.png and /dev/null differ diff --git a/extensions/intellij/src/main/resources/webview/logos/google-palm.png b/extensions/intellij/src/main/resources/webview/logos/google-palm.png deleted file mode 100644 index 0f9dc3451..000000000 Binary files a/extensions/intellij/src/main/resources/webview/logos/google-palm.png and /dev/null differ diff --git a/extensions/intellij/src/main/resources/webview/logos/hf.png b/extensions/intellij/src/main/resources/webview/logos/hf.png deleted file mode 100644 index 49e2841dd..000000000 Binary files a/extensions/intellij/src/main/resources/webview/logos/hf.png and /dev/null differ diff --git a/extensions/intellij/src/main/resources/webview/logos/llamacpp.png b/extensions/intellij/src/main/resources/webview/logos/llamacpp.png deleted file mode 100644 index 119087b0e..000000000 Binary files a/extensions/intellij/src/main/resources/webview/logos/llamacpp.png and /dev/null differ diff --git a/extensions/intellij/src/main/resources/webview/logos/lmstudio.png b/extensions/intellij/src/main/resources/webview/logos/lmstudio.png deleted file mode 100644 index b2b73591f..000000000 Binary files a/extensions/intellij/src/main/resources/webview/logos/lmstudio.png and /dev/null differ diff --git a/extensions/intellij/src/main/resources/webview/logos/meta.png b/extensions/intellij/src/main/resources/webview/logos/meta.png deleted file mode 100644 index 84a15698e..000000000 Binary files a/extensions/intellij/src/main/resources/webview/logos/meta.png and /dev/null differ diff --git a/extensions/intellij/src/main/resources/webview/logos/mistral.png b/extensions/intellij/src/main/resources/webview/logos/mistral.png deleted file mode 100644 index 0f535f84e..000000000 Binary files a/extensions/intellij/src/main/resources/webview/logos/mistral.png and /dev/null differ diff --git a/extensions/intellij/src/main/resources/webview/logos/ollama.png b/extensions/intellij/src/main/resources/webview/logos/ollama.png deleted file mode 100644 index 56ef23f4a..000000000 Binary files a/extensions/intellij/src/main/resources/webview/logos/ollama.png and /dev/null differ diff --git a/extensions/intellij/src/main/resources/webview/logos/openai.png b/extensions/intellij/src/main/resources/webview/logos/openai.png deleted file mode 100644 index e24b90113..000000000 Binary files a/extensions/intellij/src/main/resources/webview/logos/openai.png and /dev/null differ diff --git a/extensions/intellij/src/main/resources/webview/logos/replicate.png b/extensions/intellij/src/main/resources/webview/logos/replicate.png deleted file mode 100644 index f71504f59..000000000 Binary files a/extensions/intellij/src/main/resources/webview/logos/replicate.png and /dev/null differ diff --git a/extensions/intellij/src/main/resources/webview/logos/together.png b/extensions/intellij/src/main/resources/webview/logos/together.png deleted file mode 100644 index e989afdde..000000000 Binary files a/extensions/intellij/src/main/resources/webview/logos/together.png and /dev/null differ diff --git a/extensions/intellij/src/main/resources/webview/logos/wizardlm.png b/extensions/intellij/src/main/resources/webview/logos/wizardlm.png deleted file mode 100644 index a420cf038..000000000 Binary files a/extensions/intellij/src/main/resources/webview/logos/wizardlm.png and /dev/null differ diff --git a/extensions/vscode/.eslintrc.json b/extensions/vscode/.eslintrc.json index 5dfecab7e..c25ccff20 100644 --- a/extensions/vscode/.eslintrc.json +++ b/extensions/vscode/.eslintrc.json @@ -1,18 +1,10 @@ { "root": true, - "parser": "@typescript-eslint/parser", "parserOptions": { - "ecmaVersion": 6, - "sourceType": "module" + "project": "./tsconfig.json" }, - "plugins": ["@typescript-eslint"], + "extends": ["../../.eslintrc.shared.json"], "rules": { - "@typescript-eslint/naming-convention": "warn", - "@typescript-eslint/semi": "warn", - "curly": "warn", - "eqeqeq": "warn", - "no-throw-literal": "warn", - "semi": "off" - }, - "ignorePatterns": ["out", "dist", "**/*.d.ts"] + "@typescript-eslint/naming-convention": "warn" + } } diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 6da984ead..40f7322f2 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -88,7 +88,10 @@ "type": "string" } }, - "required": ["cert", "key"] + "required": [ + "cert", + "key" + ] }, "RequestOptions": { "title": "RequestOptions", @@ -169,7 +172,6 @@ "openai", "free-trial", "anthropic", - "anthropic-vertexai", "cohere", "bedrock", "bedrockimport", @@ -181,11 +183,9 @@ "llama.cpp", "replicate", "gemini", - "gemini-vertexai", "lmstudio", "llamafile", "mistral", - "mistral-vertexai", "deepinfra", "groq", "fireworks", @@ -198,7 +198,9 @@ "sambanova", "nvidia", "vllm", - "cerebras" + "cerebras", + "vertexai", + "askSage" ], "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)", @@ -232,7 +234,8 @@ "### OpenRouter\nOpenRouter offers a single API to access almost any language model. To get started, obtain an API key from [their console](https://openrouter.ai/settings/keys).", "### NVIDIA NIMs\nNVIDIA offers a single API to access almost any language model. To find out more, visit the [LLM APIs Documentation](https://docs.api.nvidia.com/nim/reference/llm-apis).\nFor information specific to getting a key, please check out the [docs here](https://docs.nvidia.com/nim/large-language-models/latest/getting-started.html#option-1-from-api-catalog)", "### vLLM\nvLLM is a highly performant way of hosting LLMs for a team. To get started, follow their [quickstart](https://docs.vllm.ai/en/latest/getting_started/quickstart.html) to set up your server.", - "### Cerebras\nCerebras Inference uses specialized silicon to provides superfast inference. To get started, get your API keys from [their console](https://cloud.cerebras.ai/)." + "### Cerebras\nCerebras Inference uses specialized silicon to provides superfast inference. To get started, get your API keys from [their console](https://cloud.cerebras.ai/).", + "### Ask Sage\nAsk Sage is an agnostic hosted service that provides language models. To get started with Ask Sage:\n1. Obtain an API key from your account. For more information, visit [Ask Sage](https://docs.asksage.ai/).\n2. Paste the API key below.\n3. Select a model preset.\n> [Reference](https://docs.asksage.ai/)" ], "type": "string" }, @@ -350,6 +353,7 @@ "promptTemplates": { "title": "Prompt Templates", "markdownDescription": "A mapping of prompt template name ('edit' is currently the only one used in Continue) to a string giving the prompt template. See [here](https://docs.continue.dev/model-setup/configuration#customizing-the-edit-prompt) for an example.", + "x-intellij-html-description": "A mapping of prompt template name ('edit' is currently the only one used in Continue) to a string giving the prompt template. See here for an example.", "type": "object", "additionalProperties": { "type": "string" @@ -365,7 +369,7 @@ "presencePenalty": null, "frequencyPenalty": null, "stop": null, - "maxTokens": 600 + "maxTokens": 2048 }, "allOf": [ { @@ -398,7 +402,11 @@ "apiType": { "title": "Api Type", "markdownDescription": "OpenAI API type, either `openai` or `azure`", - "enum": ["openai", "azure"] + "x-intellij-html-description": "OpenAI API type, either openai or azure", + "enum": [ + "openai", + "azure" + ] }, "apiVersion": { "title": "Api Version", @@ -421,7 +429,11 @@ } } }, - "required": ["title", "provider", "model"], + "required": [ + "title", + "provider", + "model" + ], "allOf": [ { "if": { @@ -431,7 +443,9 @@ } }, "not": { - "required": ["provider"] + "required": [ + "provider" + ] } }, "then": { @@ -459,46 +473,67 @@ ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { - "required": ["apiKey"] + "required": [ + "apiKey" + ] } }, { "if": { "properties": { "provider": { - "enum": ["bedrockimport"] + "enum": [ + "bedrockimport" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { - "required": ["modelArn"] + "required": [ + "modelArn" + ] } }, { "if": { "properties": { "provider": { - "enum": ["huggingface-tgi", "huggingface-inference-api"] + "enum": [ + "huggingface-tgi", + "huggingface-inference-api" + ] } } }, "then": { - "required": ["apiBase"] + "required": [ + "apiBase" + ] }, - "required": ["provider"] + "required": [ + "provider" + ] }, { "if": { "properties": { "provider": { - "enum": ["openai"] + "enum": [ + "openai" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -518,10 +553,14 @@ "if": { "properties": { "provider": { - "enum": ["cloudflare"] + "enum": [ + "cloudflare" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -579,10 +618,14 @@ "if": { "properties": { "provider": { - "enum": ["openai"] + "enum": [ + "openai" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -614,10 +657,14 @@ "if": { "properties": { "provider": { - "enum": ["replicate"] + "enum": [ + "replicate" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -642,7 +689,8 @@ } ] }, - "markdownDescription": "Select a pre-defined option, or find an exact model ID from Replicate [here](https://replicate.com/collections/streaming-language-models)." + "markdownDescription": "Select a pre-defined option, or find an exact model ID from Replicate [here](https://replicate.com/collections/streaming-language-models).", + "x-intellij-html-description": "Select a pre-defined option, or find an exact model ID from Replicate here." } } }, @@ -650,10 +698,14 @@ "if": { "properties": { "provider": { - "enum": ["free-trial"] + "enum": [ + "free-trial" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -677,7 +729,9 @@ "if": { "properties": { "provider": { - "enum": ["openai"] + "enum": [ + "openai" + ] }, "apiType": { "not": { @@ -685,7 +739,9 @@ } } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -747,10 +803,14 @@ "if": { "properties": { "provider": { - "enum": ["anthropic"] + "enum": [ + "anthropic" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -791,40 +851,21 @@ "if": { "properties": { "provider": { - "enum": ["anthropic-vertexai"] + "enum": [ + "cohere" + ] } }, - "required": ["provider"] + "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" - } + "enum": [ + "command-r", + "command-r-plus" ] } } @@ -834,27 +875,14 @@ "if": { "properties": { "provider": { - "enum": ["cohere"] + "enum": [ + "bedrock" + ] } }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "enum": ["command-r", "command-r-plus"] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["bedrock"] - } - }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -879,15 +907,19 @@ "if": { "properties": { "provider": { - "enum": ["sagemaker"] + "enum": [ + "sagemaker" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { "model": { - "markdownDescription": "SageMaker endpoint name" + "description": "SageMaker endpoint name" } } } @@ -896,10 +928,14 @@ "if": { "properties": { "provider": { - "enum": ["gemini"] + "enum": [ + "gemini" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -929,39 +965,14 @@ "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" } + "enum": [ + "together" ] } }, - "required": ["projectId", "region"] - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["together"] - } - }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -989,7 +1000,8 @@ "type": "string" } ], - "markdownDescription": "Select a pre-defined option, or find an exact model string from Together AI [here](https://docs.together.ai/docs/inference-models)." + "markdownDescription": "Select a pre-defined option, or find an exact model string from Together AI [here](https://docs.together.ai/docs/inference-models).", + "x-intellij-html-description": "Select a pre-defined option, or find an exact model string from Together AI here." } } } @@ -998,15 +1010,20 @@ "if": { "properties": { "provider": { - "enum": ["deepinfra"] + "enum": [ + "deepinfra" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { "model": { - "markdownDescription": "Find the model name you want to use from DeepInfra [here](https://deepinfra.com/models?type=text-generation)." + "markdownDescription": "Find the model name you want to use from DeepInfra [here](https://deepinfra.com/models?type=text-generation).", + "x-intellij-html-description": "Find the model name you want to use from DeepInfra here." } } } @@ -1024,7 +1041,9 @@ ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -1073,10 +1092,14 @@ "if": { "properties": { "provider": { - "enum": ["ollama"] + "enum": [ + "ollama" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -1118,7 +1141,8 @@ "type": "string" } ], - "markdownDescription": "Select a pre-defined option, or find the exact model tag for an Ollama model [here](https://ollama.ai/library)." + "markdownDescription": "Select a pre-defined option, or find the exact model tag for an Ollama model [here](https://ollama.ai/library).", + "x-intellij-html-description": "Select a pre-defined option, or find the exact model tag for an Ollama model here." } } } @@ -1127,10 +1151,14 @@ "if": { "properties": { "provider": { - "enum": ["mistral"] + "enum": [ + "mistral" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -1152,37 +1180,34 @@ "if": { "properties": { "provider": { - "enum": ["mistral-vertexai"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "codestral", - "mistral-nemo", - "mistral-large" - ] - }, - { "type": "string" } + "enum": [ + "vertexai" ] } }, - "required": ["projectId", "region"] + "required": [ + "provider" + ] + }, + "then": { + "required": [ + "projectId", + "region" + ] } }, { "if": { "properties": { "provider": { - "enum": ["deepseek"] + "enum": [ + "deepseek" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -1199,7 +1224,10 @@ } }, "model": { - "enum": ["deepseek-chat", "deepseek-coder"] + "enum": [ + "deepseek-chat", + "deepseek-coder" + ] } } } @@ -1208,10 +1236,14 @@ "if": { "properties": { "provider": { - "enum": ["groq"] + "enum": [ + "groq" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -1236,15 +1268,21 @@ "if": { "properties": { "provider": { - "enum": ["fireworks"] + "enum": [ + "fireworks" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { "model": { - "enum": ["starcoder-7b"] + "enum": [ + "starcoder-7b" + ] } } } @@ -1256,20 +1294,30 @@ "const": "azure" } }, - "required": ["apiType"] + "required": [ + "apiType" + ] }, "then": { - "required": ["engine", "apiVersion", "apiBase"] + "required": [ + "engine", + "apiVersion", + "apiBase" + ] } }, { "if": { "properties": { "provider": { - "enum": ["openai"] + "enum": [ + "openai" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -1286,7 +1334,9 @@ "const": "llamafile" } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -1300,15 +1350,22 @@ "if": { "properties": { "provider": { - "enum": ["cerebras"] + "enum": [ + "cerebras" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { "model": { - "enum": ["llama3.1-8b", "llama3.1-70b"] + "enum": [ + "llama3.1-8b", + "llama3.1-70b" + ] } } } @@ -1317,10 +1374,14 @@ "if": { "properties": { "provider": { - "enum": ["text-gen-webui"] + "enum": [ + "text-gen-webui" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -1334,10 +1395,14 @@ "if": { "properties": { "provider": { - "enum": ["flowise"] + "enum": [ + "flowise" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -1364,7 +1429,10 @@ "type": "string" } }, - "required": ["key", "value"] + "required": [ + "key", + "value" + ] } }, "additionalFlowiseConfiguration": { @@ -1383,7 +1451,10 @@ "description": "Configuration Property value" } }, - "required": ["key", "value"] + "required": [ + "key", + "value" + ] } }, "model": { @@ -1457,10 +1528,14 @@ "if": { "properties": { "provider": { - "enum": ["watsonx"] + "enum": [ + "watsonx" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { @@ -1492,30 +1567,80 @@ ] } }, - "required": ["watsonxUrl", "watsonxProjectId"] + "required": [ + "watsonxUrl", + "watsonxProjectId" + ] } }, { "if": { "properties": { "provider": { - "enum": ["sambanova"] + "enum": [ + "sambanova" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { "model": { "anyOf": [ { - "enum": ["llama3.1-8b", "llama3.1-70b", "llama3.1-405b"] + "enum": [ + "llama3.1-8b", + "llama3.1-70b", + "llama3.1-405b" + ] }, { "type": "string" } ], - "markdownDescription": "Select a pre-defined option." + "description": "Select a pre-defined option." + } + } + } + }, + { + "if": { + "properties": { + "provider": { + "enum": [ + "ask-sage" + ] + } + }, + "required": [ + "provider" + ] + }, + "then": { + "properties": { + "model": { + "anyOf": [ + { + "enum": [ + "gpt-4o", + "gpt-4o-mini", + "gpt-4gov", + "gpt-4ogov", + "claude-3.5-sonnet", + "claude-3-opus", + "mistral-large", + "llama-3-chat", + "gemini-pro", + "AUTODETECT" + ] + }, + { + "type": "string" + } + ] } } } @@ -1547,7 +1672,9 @@ "type": "string" } }, - "required": ["default"] + "required": [ + "default" + ] }, "SlashCommand": { "title": "SlashCommand", @@ -1604,7 +1731,9 @@ "if": { "properties": { "name": { - "enum": ["issue"] + "enum": [ + "issue" + ] } } }, @@ -1617,17 +1746,23 @@ "description": "Enter the URL of the GitHub repository for which you want to generate the issue." } }, - "required": ["repositoryUrl"] + "required": [ + "repositoryUrl" + ] } }, - "required": ["params"] + "required": [ + "params" + ] } }, { "if": { "properties": { "name": { - "enum": ["edit"] + "enum": [ + "edit" + ] } } }, @@ -1637,11 +1772,12 @@ "properties": { "recap": { "type": "boolean", - "markdownDescription": "If recap is set to `true`, Continue will generate a summary of the changes after making the edit." + "markdownDescription": "If recap is set to `true`, Continue will generate a summary of the changes after making the edit.", + "x-intellij-html-description": "If recap is set to true, Continue will generate a summary of the changes after making the edit." }, "tokenLimit": { "type": "integer", - "markdownDescription": "By default, Continue doesn't let you edit extremely large ranges (beyond 1,200 tokens), because the LLM is unlikely to succeed. But if you would like to override this limit with the understanding of possible failure you may do so here." + "description": "By default, Continue doesn't let you edit extremely large ranges (beyond 1,200 tokens), because the LLM is unlikely to succeed. But if you would like to override this limit with the understanding of possible failure you may do so here." } } } @@ -1652,7 +1788,9 @@ "if": { "properties": { "name": { - "enum": ["share"] + "enum": [ + "share" + ] } } }, @@ -1662,7 +1800,8 @@ "properties": { "outputDir": { "type": "string", - "markdownDescription": "If outputDir is set to `.` or begins with `./` or `.\\`, file will be saved to the current workspace or a subdirectory thereof, respectively. `~` can similarly be used to specify the user's home directory." + "markdownDescription": "If outputDir is set to `.` or begins with `./` or `.\\`, file will be saved to the current workspace or a subdirectory thereof, respectively. `~` can similarly be used to specify the user's home directory.", + "x-intellij-html-description": "If outputDir is set to . or begins with ./ or .\\, file will be saved to the current workspace or a subdirectory thereof, respectively. ~ can similarly be used to specify the user's home directory." } } } @@ -1673,7 +1812,9 @@ "if": { "properties": { "name": { - "enum": ["commit"] + "enum": [ + "commit" + ] } } }, @@ -1683,7 +1824,8 @@ "properties": { "includeUnstaged": { "type": "boolean", - "markdownDescription": "If includeUnstaged is set to true, then unstaged changes are also included in the prompt, otherwise only staged changes are included. Default is false." + "markdownDescription": "If set to `true`, then unstaged changes are also included in the prompt, otherwise only staged changes are included. Default is `false`.", + "x-intellij-html-description": "If set to true, then unstaged changes are also included in the prompt, otherwise only staged changes are included. Default is false." } } } @@ -1691,7 +1833,10 @@ } } ], - "required": ["name", "description"] + "required": [ + "name", + "description" + ] }, "CustomCommand": { "title": "CustomCommand", @@ -1710,7 +1855,11 @@ "type": "string" } }, - "required": ["name", "prompt", "description"] + "required": [ + "name", + "prompt", + "description" + ] }, "ContextProviderWithParams": { "title": "ContextProviderWithParams", @@ -1790,7 +1939,9 @@ "if": { "properties": { "name": { - "enum": ["discord"] + "enum": [ + "discord" + ] } } }, @@ -1823,11 +1974,15 @@ "description": "The name of the channel" } }, - "required": ["id"] + "required": [ + "id" + ] } } }, - "required": ["discordKey"] + "required": [ + "discordKey" + ] } } }, @@ -1836,14 +1991,18 @@ { "properties": { "params": { - "required": ["guildId"] + "required": [ + "guildId" + ] } } }, { "properties": { "params": { - "required": ["channels"] + "required": [ + "channels" + ] } } } @@ -1856,7 +2015,9 @@ "if": { "properties": { "name": { - "enum": ["google"] + "enum": [ + "google" + ] } } }, @@ -1869,14 +2030,26 @@ "description": "Your API key for https://serper.dev in order to get Google search results" } }, - "required": ["serperApiKey"] + "required": [ + "serperApiKey" + ] } }, - "required": ["params"] + "required": [ + "params" + ] } }, { - "if": { "properties": { "name": { "enum": ["web"] } } }, + "if": { + "properties": { + "name": { + "enum": [ + "web" + ] + } + } + }, "then": { "properties": { "params": { @@ -1890,14 +2063,18 @@ } } }, - "required": ["params"] + "required": [ + "params" + ] } }, { "if": { "properties": { "name": { - "enum": ["open"] + "enum": [ + "open" + ] } } }, @@ -1919,7 +2096,9 @@ "if": { "properties": { "name": { - "enum": ["issue"] + "enum": [ + "issue" + ] } } }, @@ -1948,24 +2127,37 @@ "type": { "type": "string", "description": "The type of issues to search for", - "enum": ["open", "closed", "all"] + "enum": [ + "open", + "closed", + "all" + ] } }, - "required": ["owner", "repo"] + "required": [ + "owner", + "repo" + ] } } }, - "required": ["repos"] + "required": [ + "repos" + ] } }, - "required": ["params"] + "required": [ + "params" + ] } }, { "if": { "properties": { "name": { - "enum": ["database"] + "enum": [ + "database" + ] } } }, @@ -1986,7 +2178,11 @@ "connection_type": { "type": "string", "description": "The type of database (e.g., 'postgres', 'mysql')", - "enum": ["postgres", "mysql", "sqlite"] + "enum": [ + "postgres", + "mysql", + "sqlite" + ] }, "connection": { "type": "object", @@ -2019,21 +2215,31 @@ "required": [] } }, - "required": ["name", "connection_type", "connection"] + "required": [ + "name", + "connection_type", + "connection" + ] } } }, - "required": ["connections"] + "required": [ + "connections" + ] } }, - "required": ["params"] + "required": [ + "params" + ] } }, { "if": { "properties": { "name": { - "enum": ["gitlab-mr"] + "enum": [ + "gitlab-mr" + ] } } }, @@ -2054,17 +2260,23 @@ "description": "If you have code selected, filters out comments that aren't related to the selection." } }, - "required": ["token"] + "required": [ + "token" + ] } }, - "required": ["params"] + "required": [ + "params" + ] } }, { "if": { "properties": { "name": { - "enum": ["jira"] + "enum": [ + "jira" + ] } } }, @@ -2090,7 +2302,8 @@ }, "apiVersion": { "type": "integer", - "markdownDescription": "This context provider supports both Jira API version 2 and 3. It will use version 3 by default since that's what the cloud version uses, but if you have the datacenter version of Jira, you'll need to set the API Version to 2 using the `apiVersion` property." + "markdownDescription": "This context provider supports both Jira API version 2 and 3. It will use version 3 by default since that's what the cloud version uses, but if you have the datacenter version of Jira, you'll need to set the API Version to 2 using the `apiVersion` property.", + "x-intellij-html-description": "This context provider supports both Jira API version 2 and 3. It will use version 3 by default since that's what the cloud version uses, but if you have the datacenter version of Jira, you'll need to set the API Version to 2 using the apiVersion property." }, "requestOptions": { "title": "Request Options", @@ -2110,17 +2323,24 @@ ] } }, - "required": ["domain", "token"] + "required": [ + "domain", + "token" + ] } }, - "required": ["params"] + "required": [ + "params" + ] } }, { "if": { "properties": { "name": { - "enum": ["http"] + "enum": [ + "http" + ] } } }, @@ -2138,17 +2358,24 @@ "type": "object" } }, - "required": ["url"] + "required": [ + "url" + ] } }, - "required": ["params"] + "required": [ + "params" + ] } }, { "if": { "properties": { "name": { - "enum": ["codebase", "folder"] + "enum": [ + "codebase", + "folder" + ] } } }, @@ -2183,7 +2410,9 @@ "if": { "properties": { "name": { - "enum": ["postgres"] + "enum": [ + "postgres" + ] } } }, @@ -2235,14 +2464,22 @@ } } }, - "required": ["host", "port", "user", "password", "database"] + "required": [ + "host", + "port", + "user", + "password", + "database" + ] } }, { "if": { "properties": { "name": { - "enum": ["greptile"] + "enum": [ + "greptile" + ] } } }, @@ -2265,11 +2502,16 @@ } } }, - "required": ["GreptileToken", "GithubToken"] + "required": [ + "GreptileToken", + "GithubToken" + ] } } ], - "required": ["name"] + "required": [ + "name" + ] }, "SerializedContinueConfig": { "title": "config.json", @@ -2303,18 +2545,23 @@ "description": "The URL path to a favicon for the site - by default, it will be `/favicon.ico` path from the Start URL" } }, - "required": ["title", "startUrl"] + "required": [ + "title", + "startUrl" + ] } }, "allowAnonymousTelemetry": { "title": "Allow Anonymous Telemetry", - "markdownDescription": "If this field is set to True, we will collect anonymous telemetry as described in the documentation page on telemetry. If set to `false`, we will not collect any data. Learn more in [the docs](https://docs.continue.dev/telemetry).", + "markdownDescription": "If this field is set to `true`, we will collect anonymous telemetry as described in the documentation page on telemetry. If set to `false`, we will not collect any data. Learn more in [the docs](https://docs.continue.dev/telemetry).", + "x-intellij-html-description": "If this field is set to `true`, we will collect anonymous telemetry as described in the documentation page on telemetry. If set to `false`, we will not collect any data. Learn more in the docs.", "default": true, "type": "boolean" }, "models": { "title": "Models", "markdownDescription": "Learn about setting up models in [the documentation](https://docs.continue.dev/model-setup/overview).", + "x-intellij-html-description": "Learn about setting up models in the documentation.", "default": [ { "title": "GPT-4 (trial)", @@ -2363,6 +2610,7 @@ "slashCommands": { "title": "Slash Commands", "markdownDescription": "An array of slash commands that let you take custom actions from the sidebar. Learn more in the [documentation](https://docs.continue.dev/customization/slash-commands).", + "x-intellij-html-description": "An array of slash commands that let you take custom actions from the sidebar. Learn more in the documentation.", "default": [], "type": "array", "items": { @@ -2371,7 +2619,8 @@ }, "customCommands": { "title": "Custom Commands", - "markdownDescription": "An array of custom commands that allow you to reuse prompts. Each has name, description, and prompt properties. When you enter / in the text input, it will act as a shortcut to the prompt. Learn more in the [documentation](https://docs.continue.dev/customization/slash-commands#custom-commands-use-natural-language).", + "markdownDescription": "An array of custom commands that allow you to reuse prompts. Each has name, description, and prompt properties. When you enter `/` in the text input, it will act as a shortcut to the prompt. Learn more in the [documentation](https://docs.continue.dev/customization/slash-commands#custom-commands-use-natural-language).", + "x-intellij-html-description": "An array of custom commands that allow you to reuse prompts. Each has name, description, and prompt properties. When you enter / in the text input, it will act as a shortcut to the prompt. Learn more in the documentation.", "default": [ { "name": "test", @@ -2387,6 +2636,7 @@ "contextProviders": { "title": "Context Providers", "markdownDescription": "A list of ContextProvider objects that can be used to provide context to the LLM by typing '@'. Read more about ContextProviders in [the documentation](https://docs.continue.dev/customization/context-providers).", + "x-intellij-html-description": "A list of ContextProvider objects that can be used to provide context to the LLM by typing '@'. Read more about ContextProviders in the documentation.", "default": [], "type": "array", "items": { @@ -2401,18 +2651,21 @@ "disableIndexing": { "title": "Disable Indexing", "markdownDescription": "If set to `true`, Continue will not index the codebase. This is mainly used for debugging purposes.", + "x-intellij-html-description": "If set to true, Continue will not index the codebase. This is mainly used for debugging purposes.", "default": false, "type": "boolean" }, "disableSessionTitles": { "title": "Disable Session Titles", "markdownDescription": "If set to `true`, Continue will not make extra requests to the LLM to generate a summary title of each session.", + "x-intellij-html-description": "If set to true, Continue will not make extra requests to the LLM to generate a summary title of each session.", "default": false, "type": "boolean" }, "embeddingsProvider": { "title": "Embeddings Provider", - "markdownDescription": "The method that will be used to generate codebase embeddings. The default is transformers.js, which will run locally in the browser. Learn about the other options [here](https://docs.continue.dev/features/codebase-embeddings#embeddings-providers).", + "markdownDescription": "The method that will be used to generate codebase embeddings. The default is `transformers.js`, which will run locally in the browser. Learn about the other options [here](https://docs.continue.dev/features/codebase-embeddings#embeddings-providers).", + "x-intellij-html-description": "The method that will be used to generate codebase embeddings. The default is transformers.js, which will run locally in the browser. Learn about the other options here.

Note: transformers.js currently cannot be used in JetBrains.", "type": "object", "properties": { "provider": { @@ -2428,7 +2681,7 @@ "nvidia", "bedrock", "sagemaker", - "vertex" + "vertexai" ] }, "model": { @@ -2470,69 +2723,94 @@ "type": "string" } }, - "required": ["provider"], + "required": [ + "provider" + ], "allOf": [ { "if": { "properties": { "provider": { - "enum": ["cohere", "voyage", "nvidia", "gemini"] + "enum": [ + "cohere", + "voyage", + "nvidia", + "gemini" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { - "required": ["apiKey"] + "required": [ + "apiKey" + ] } }, { "if": { "properties": { "provider": { - "enum": ["sagemaker"] + "enum": [ + "sagemaker" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { "model": { - "markdownDescription": "SageMaker endpoint name" + "description": "SageMaker endpoint name" } }, - "required": ["model"] + "required": [ + "model" + ] } }, { "if": { "properties": { "provider": { - "enum": ["vertex"] + "enum": [ + "vertexai" + ] } }, - "required": ["provider"] + "required": [ + "provider" + ] }, "then": { "properties": { "projectId": { - "markdownDescription": "The name of your vertexAI project" + "description": "The name of your VertexAI project" }, "region": { - "markdownDescription": "The region your vertexAI model is hosted in - typically central1", + "description": "The region your VertexAI model is hosted in - typically central1", "default": "central1" }, "model": { "default": "text-embedding-004" } }, - "required": ["projectId", "model", "region"] + "required": [ + "projectId", + "model", + "region" + ] } } ] }, "reranker": { "title": "Reranker", - "markdownDescription": "The reranker is responsible for selecting the final results when retrieving snippets from your codebase.", + "description": "The reranker is responsible for selecting the final results when retrieving snippets from your codebase.", "type": "object", "properties": { "name": { @@ -2548,16 +2826,22 @@ "type": "object" } }, - "required": ["name"], + "required": [ + "name" + ], "allOf": [ { "if": { "properties": { "name": { - "enum": ["cohere"] + "enum": [ + "cohere" + ] } }, - "required": ["name"] + "required": [ + "name" + ] }, "then": { "properties": { @@ -2579,7 +2863,9 @@ "type": "string" } }, - "required": ["apiKey"] + "required": [ + "apiKey" + ] } } } @@ -2588,10 +2874,14 @@ "if": { "properties": { "name": { - "enum": ["llm"] + "enum": [ + "llm" + ] } }, - "required": ["name"] + "required": [ + "name" + ] }, "then": { "properties": { @@ -2602,7 +2892,9 @@ "type": "string" } }, - "required": ["modelTitle"] + "required": [ + "modelTitle" + ] } } } @@ -2611,10 +2903,14 @@ "if": { "properties": { "name": { - "enum": ["voyage"] + "enum": [ + "voyage" + ] } }, - "required": ["name"] + "required": [ + "name" + ] }, "then": { "properties": { @@ -2633,7 +2929,9 @@ ] } }, - "required": ["apiKey"] + "required": [ + "apiKey" + ] } } } @@ -2642,10 +2940,14 @@ "if": { "properties": { "name": { - "enum": ["huggingface-tei"] + "enum": [ + "huggingface-tei" + ] } }, - "required": ["name"] + "required": [ + "name" + ] }, "then": { "properties": { @@ -2658,16 +2960,21 @@ }, "truncate": { "type": "boolean", - "description": "Wether to truncate long sequences to the maximum allowed context length.", + "description": "Whether to truncate long sequences to the maximum allowed context length.", "default": false }, "truncation_direction": { - "enum": ["Right", "Left"], - "markdownDescription": "Wether to truncate sequences from the `left` or `right`.", + "enum": [ + "Right", + "Left" + ], + "description": "Whether to truncate sequences from the left or right.", "default": "Right" } }, - "required": ["apiBase"] + "required": [ + "apiBase" + ] } }, "if": { @@ -2678,7 +2985,9 @@ } }, "then": { - "required": ["truncation_direction"] + "required": [ + "truncation_direction" + ] } } } @@ -2687,6 +2996,7 @@ "tabAutocompleteModel": { "title": "Tab Autocomplete Model", "markdownDescription": "The model used for tab autocompletion. If undefined, Continue will default to using starcoder2:3b on a local Ollama instance.\n\n*IMPORTANT*:\n\nIf you use a custom model, ensure that it is one trained for fill-in-the-middle completions. An instruct model is typically not well-suited to autocomplete and you may receive unsatisfactory completions.", + "x-intellij-html-description": "The model used for tab autocompletion. If undefined, Continue will default to using starcoder2:3b on a local Ollama instance.

IMPORTANT:

If you use a custom model, ensure that it is one trained for fill-in-the-middle completions. An instruct model is typically not well-suited to autocomplete and you may receive unsatisfactory completions.", "default": { "title": "Tab Autocomplete Model", "provider": "ollama", @@ -2708,6 +3018,7 @@ "title": "TabAutocompleteOptions", "type": "object", "markdownDescription": "These options let you customize your tab-autocomplete experience. Read about all options in [the docs](https://docs.continue.dev/features/tab-autocomplete#configuration-options).", + "x-intellij-html-description": "These options let you customize your tab-autocomplete experience. Read about all options in the docs.", "properties": { "disable": { "type": "boolean", @@ -2738,12 +3049,20 @@ "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." }, "multilineCompletions": { - "enum": ["always", "never", "auto"], + "enum": [ + "always", + "never", + "auto" + ], "description": "If set to true, Continue will only complete a single line at a time." }, "useCache": { @@ -2772,7 +3091,10 @@ "type": "object", "properties": { "codeBlockToolbarPosition": { - "enum": ["top", "bottom"], + "enum": [ + "top", + "bottom" + ], "default": "top", "description": "Whether to show the copy and apply code buttons at the top or bottom of code blocks in the sidebar." }, @@ -2787,6 +3109,7 @@ "showChatScrollbar": { "title": "Show Chat Scrollbar", "markdownDescription": "If set to `true`, a scrollbar will be displayed in the chat window to navigate through messages.", + "x-intellij-html-description": "If set to true, a scrollbar will be displayed in the chat window to navigate through messages.", "default": false, "type": "boolean" } @@ -2797,12 +3120,20 @@ "properties": { "provider": { "type": "string", - "enum": ["posthog", "logstash"], +<<<<<<< HEAD + "enum": [ + "posthog" + ], +======= + "enum": [ + "posthog", + "logstash" + ], +>>>>>>> 6e622157f1a727ba54d3bc22b337079e832c7556 "description": "The 3rd party analytics provider to use.", "default": "posthog", "markdownEnumDescriptions": [ - "### Posthog\nTo use Posthog, set up an account, obtain your client key, and enter it in the client key field.", - "### Logstash\nContinue's Logstash integration uses the TCP input at the specified URL" + "### Posthog\nTo use Posthog, set up an account, obtain your client key, and enter it in the client key field." ] }, "url": { @@ -2814,30 +3145,40 @@ "description": "The client key to use for analytics" } }, - "required": ["provider"], + "required": [ + "provider" + ], "allOf": [ { "if": { "properties": { "provider": { - "enum": ["posthog"] + "enum": [ + "posthog" + ] } } }, "then": { - "required": ["clientKey"] + "required": [ + "clientKey" + ] } }, { "if": { "properties": { "provider": { - "enum": ["logstash"] + "enum": [ + "logstash" + ] } } }, "then": { - "required": ["url"] + "required": [ + "url" + ] } } ] @@ -2909,7 +3250,10 @@ "default": false } }, - "required": ["prompt", "title"] + "required": [ + "prompt", + "title" + ] }, "description": "Quick actions are a way to add custom commands to the Code Lens of function and class declarations." }, @@ -2943,4 +3287,4 @@ } } } -} +} \ No newline at end of file diff --git a/extensions/vscode/continue_rc_schema.json b/extensions/vscode/continue_rc_schema.json index 86304fa6e..dc9e111ba 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,9 @@ "sambanova", "nvidia", "vllm", - "cerebras" + "cerebras", + "vertexai", + "askSage" ], "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)", @@ -235,7 +234,8 @@ "### OpenRouter\nOpenRouter offers a single API to access almost any language model. To get started, obtain an API key from [their console](https://openrouter.ai/settings/keys).", "### NVIDIA NIMs\nNVIDIA offers a single API to access almost any language model. To find out more, visit the [LLM APIs Documentation](https://docs.api.nvidia.com/nim/reference/llm-apis).\nFor information specific to getting a key, please check out the [docs here](https://docs.nvidia.com/nim/large-language-models/latest/getting-started.html#option-1-from-api-catalog)", "### vLLM\nvLLM is a highly performant way of hosting LLMs for a team. To get started, follow their [quickstart](https://docs.vllm.ai/en/latest/getting_started/quickstart.html) to set up your server.", - "### Cerebras\nCerebras Inference uses specialized silicon to provides superfast inference. To get started, get your API keys from [their console](https://cloud.cerebras.ai/)." + "### Cerebras\nCerebras Inference uses specialized silicon to provides superfast inference. To get started, get your API keys from [their console](https://cloud.cerebras.ai/).", + "### Ask Sage\nAsk Sage is an agnostic hosted service that provides language models. To get started with Ask Sage:\n1. Obtain an API key from your account. For more information, visit [Ask Sage](https://docs.asksage.ai/).\n2. Paste the API key below.\n3. Select a model preset.\n> [Reference](https://docs.asksage.ai/)" ], "type": "string" }, @@ -353,6 +353,7 @@ "promptTemplates": { "title": "Prompt Templates", "markdownDescription": "A mapping of prompt template name ('edit' is currently the only one used in Continue) to a string giving the prompt template. See [here](https://docs.continue.dev/model-setup/configuration#customizing-the-edit-prompt) for an example.", + "x-intellij-html-description": "A mapping of prompt template name ('edit' is currently the only one used in Continue) to a string giving the prompt template. See here for an example.", "type": "object", "additionalProperties": { "type": "string" @@ -401,6 +402,7 @@ "apiType": { "title": "Api Type", "markdownDescription": "OpenAI API type, either `openai` or `azure`", + "x-intellij-html-description": "OpenAI API type, either openai or azure", "enum": [ "openai", "azure" @@ -687,7 +689,8 @@ } ] }, - "markdownDescription": "Select a pre-defined option, or find an exact model ID from Replicate [here](https://replicate.com/collections/streaming-language-models)." + "markdownDescription": "Select a pre-defined option, or find an exact model ID from Replicate [here](https://replicate.com/collections/streaming-language-models).", + "x-intellij-html-description": "Select a pre-defined option, or find an exact model ID from Replicate here." } } }, @@ -844,53 +847,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": { @@ -963,7 +919,7 @@ "then": { "properties": { "model": { - "markdownDescription": "SageMaker endpoint name" + "description": "SageMaker endpoint name" } } } @@ -1005,44 +961,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": { @@ -1082,7 +1000,8 @@ "type": "string" } ], - "markdownDescription": "Select a pre-defined option, or find an exact model string from Together AI [here](https://docs.together.ai/docs/inference-models)." + "markdownDescription": "Select a pre-defined option, or find an exact model string from Together AI [here](https://docs.together.ai/docs/inference-models).", + "x-intellij-html-description": "Select a pre-defined option, or find an exact model string from Together AI here." } } } @@ -1103,7 +1022,8 @@ "then": { "properties": { "model": { - "markdownDescription": "Find the model name you want to use from DeepInfra [here](https://deepinfra.com/models?type=text-generation)." + "markdownDescription": "Find the model name you want to use from DeepInfra [here](https://deepinfra.com/models?type=text-generation).", + "x-intellij-html-description": "Find the model name you want to use from DeepInfra here." } } } @@ -1221,7 +1141,8 @@ "type": "string" } ], - "markdownDescription": "Select a pre-defined option, or find the exact model tag for an Ollama model [here](https://ollama.ai/library)." + "markdownDescription": "Select a pre-defined option, or find the exact model tag for an Ollama model [here](https://ollama.ai/library).", + "x-intellij-html-description": "Select a pre-defined option, or find the exact model tag for an Ollama model here." } } } @@ -1260,7 +1181,7 @@ "properties": { "provider": { "enum": [ - "mistral-vertexai" + "vertexai" ] } }, @@ -1269,22 +1190,6 @@ ] }, "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "codestral", - "mistral-nemo", - "mistral-large" - ] - }, - { - "type": "string" - } - ] - } - }, "required": [ "projectId", "region" @@ -1696,7 +1601,46 @@ "type": "string" } ], - "markdownDescription": "Select a pre-defined option." + "description": "Select a pre-defined option." + } + } + } + }, + { + "if": { + "properties": { + "provider": { + "enum": [ + "ask-sage" + ] + } + }, + "required": [ + "provider" + ] + }, + "then": { + "properties": { + "model": { + "anyOf": [ + { + "enum": [ + "gpt-4o", + "gpt-4o-mini", + "gpt-4gov", + "gpt-4ogov", + "claude-3.5-sonnet", + "claude-3-opus", + "mistral-large", + "llama-3-chat", + "gemini-pro", + "AUTODETECT" + ] + }, + { + "type": "string" + } + ] } } } @@ -1828,11 +1772,12 @@ "properties": { "recap": { "type": "boolean", - "markdownDescription": "If recap is set to `true`, Continue will generate a summary of the changes after making the edit." + "markdownDescription": "If recap is set to `true`, Continue will generate a summary of the changes after making the edit.", + "x-intellij-html-description": "If recap is set to true, Continue will generate a summary of the changes after making the edit." }, "tokenLimit": { "type": "integer", - "markdownDescription": "By default, Continue doesn't let you edit extremely large ranges (beyond 1,200 tokens), because the LLM is unlikely to succeed. But if you would like to override this limit with the understanding of possible failure you may do so here." + "description": "By default, Continue doesn't let you edit extremely large ranges (beyond 1,200 tokens), because the LLM is unlikely to succeed. But if you would like to override this limit with the understanding of possible failure you may do so here." } } } @@ -1855,7 +1800,8 @@ "properties": { "outputDir": { "type": "string", - "markdownDescription": "If outputDir is set to `.` or begins with `./` or `.\\`, file will be saved to the current workspace or a subdirectory thereof, respectively. `~` can similarly be used to specify the user's home directory." + "markdownDescription": "If outputDir is set to `.` or begins with `./` or `.\\`, file will be saved to the current workspace or a subdirectory thereof, respectively. `~` can similarly be used to specify the user's home directory.", + "x-intellij-html-description": "If outputDir is set to . or begins with ./ or .\\, file will be saved to the current workspace or a subdirectory thereof, respectively. ~ can similarly be used to specify the user's home directory." } } } @@ -1878,7 +1824,8 @@ "properties": { "includeUnstaged": { "type": "boolean", - "markdownDescription": "If includeUnstaged is set to true, then unstaged changes are also included in the prompt, otherwise only staged changes are included. Default is false." + "markdownDescription": "If set to `true`, then unstaged changes are also included in the prompt, otherwise only staged changes are included. Default is `false`.", + "x-intellij-html-description": "If set to true, then unstaged changes are also included in the prompt, otherwise only staged changes are included. Default is false." } } } @@ -2355,7 +2302,8 @@ }, "apiVersion": { "type": "integer", - "markdownDescription": "This context provider supports both Jira API version 2 and 3. It will use version 3 by default since that's what the cloud version uses, but if you have the datacenter version of Jira, you'll need to set the API Version to 2 using the `apiVersion` property." + "markdownDescription": "This context provider supports both Jira API version 2 and 3. It will use version 3 by default since that's what the cloud version uses, but if you have the datacenter version of Jira, you'll need to set the API Version to 2 using the `apiVersion` property.", + "x-intellij-html-description": "This context provider supports both Jira API version 2 and 3. It will use version 3 by default since that's what the cloud version uses, but if you have the datacenter version of Jira, you'll need to set the API Version to 2 using the apiVersion property." }, "requestOptions": { "title": "Request Options", @@ -2605,13 +2553,15 @@ }, "allowAnonymousTelemetry": { "title": "Allow Anonymous Telemetry", - "markdownDescription": "If this field is set to True, we will collect anonymous telemetry as described in the documentation page on telemetry. If set to `false`, we will not collect any data. Learn more in [the docs](https://docs.continue.dev/telemetry).", + "markdownDescription": "If this field is set to `true`, we will collect anonymous telemetry as described in the documentation page on telemetry. If set to `false`, we will not collect any data. Learn more in [the docs](https://docs.continue.dev/telemetry).", + "x-intellij-html-description": "If this field is set to `true`, we will collect anonymous telemetry as described in the documentation page on telemetry. If set to `false`, we will not collect any data. Learn more in the docs.", "default": true, "type": "boolean" }, "models": { "title": "Models", "markdownDescription": "Learn about setting up models in [the documentation](https://docs.continue.dev/model-setup/overview).", + "x-intellij-html-description": "Learn about setting up models in the documentation.", "default": [ { "title": "GPT-4 (trial)", @@ -2660,6 +2610,7 @@ "slashCommands": { "title": "Slash Commands", "markdownDescription": "An array of slash commands that let you take custom actions from the sidebar. Learn more in the [documentation](https://docs.continue.dev/customization/slash-commands).", + "x-intellij-html-description": "An array of slash commands that let you take custom actions from the sidebar. Learn more in the documentation.", "default": [], "type": "array", "items": { @@ -2668,7 +2619,8 @@ }, "customCommands": { "title": "Custom Commands", - "markdownDescription": "An array of custom commands that allow you to reuse prompts. Each has name, description, and prompt properties. When you enter / in the text input, it will act as a shortcut to the prompt. Learn more in the [documentation](https://docs.continue.dev/customization/slash-commands#custom-commands-use-natural-language).", + "markdownDescription": "An array of custom commands that allow you to reuse prompts. Each has name, description, and prompt properties. When you enter `/` in the text input, it will act as a shortcut to the prompt. Learn more in the [documentation](https://docs.continue.dev/customization/slash-commands#custom-commands-use-natural-language).", + "x-intellij-html-description": "An array of custom commands that allow you to reuse prompts. Each has name, description, and prompt properties. When you enter / in the text input, it will act as a shortcut to the prompt. Learn more in the documentation.", "default": [ { "name": "test", @@ -2684,6 +2636,7 @@ "contextProviders": { "title": "Context Providers", "markdownDescription": "A list of ContextProvider objects that can be used to provide context to the LLM by typing '@'. Read more about ContextProviders in [the documentation](https://docs.continue.dev/customization/context-providers).", + "x-intellij-html-description": "A list of ContextProvider objects that can be used to provide context to the LLM by typing '@'. Read more about ContextProviders in the documentation.", "default": [], "type": "array", "items": { @@ -2698,18 +2651,21 @@ "disableIndexing": { "title": "Disable Indexing", "markdownDescription": "If set to `true`, Continue will not index the codebase. This is mainly used for debugging purposes.", + "x-intellij-html-description": "If set to true, Continue will not index the codebase. This is mainly used for debugging purposes.", "default": false, "type": "boolean" }, "disableSessionTitles": { "title": "Disable Session Titles", "markdownDescription": "If set to `true`, Continue will not make extra requests to the LLM to generate a summary title of each session.", + "x-intellij-html-description": "If set to true, Continue will not make extra requests to the LLM to generate a summary title of each session.", "default": false, "type": "boolean" }, "embeddingsProvider": { "title": "Embeddings Provider", - "markdownDescription": "The method that will be used to generate codebase embeddings. The default is transformers.js, which will run locally in the browser. Learn about the other options [here](https://docs.continue.dev/features/codebase-embeddings#embeddings-providers).", + "markdownDescription": "The method that will be used to generate codebase embeddings. The default is `transformers.js`, which will run locally in the browser. Learn about the other options [here](https://docs.continue.dev/features/codebase-embeddings#embeddings-providers).", + "x-intellij-html-description": "The method that will be used to generate codebase embeddings. The default is transformers.js, which will run locally in the browser. Learn about the other options here.

Note: transformers.js currently cannot be used in JetBrains.", "type": "object", "properties": { "provider": { @@ -2725,7 +2681,7 @@ "nvidia", "bedrock", "sagemaker", - "vertex" + "vertexai" ] }, "model": { @@ -2809,7 +2765,7 @@ "then": { "properties": { "model": { - "markdownDescription": "SageMaker endpoint name" + "description": "SageMaker endpoint name" } }, "required": [ @@ -2822,7 +2778,7 @@ "properties": { "provider": { "enum": [ - "vertex" + "vertexai" ] } }, @@ -2833,10 +2789,10 @@ "then": { "properties": { "projectId": { - "markdownDescription": "The name of your vertexAI project" + "description": "The name of your VertexAI project" }, "region": { - "markdownDescription": "The region your vertexAI model is hosted in - typically central1", + "description": "The region your VertexAI model is hosted in - typically central1", "default": "central1" }, "model": { @@ -2854,7 +2810,7 @@ }, "reranker": { "title": "Reranker", - "markdownDescription": "The reranker is responsible for selecting the final results when retrieving snippets from your codebase.", + "description": "The reranker is responsible for selecting the final results when retrieving snippets from your codebase.", "type": "object", "properties": { "name": { @@ -3004,7 +2960,7 @@ }, "truncate": { "type": "boolean", - "description": "Wether to truncate long sequences to the maximum allowed context length.", + "description": "Whether to truncate long sequences to the maximum allowed context length.", "default": false }, "truncation_direction": { @@ -3012,7 +2968,7 @@ "Right", "Left" ], - "markdownDescription": "Wether to truncate sequences from the `left` or `right`.", + "description": "Whether to truncate sequences from the left or right.", "default": "Right" } }, @@ -3040,6 +2996,7 @@ "tabAutocompleteModel": { "title": "Tab Autocomplete Model", "markdownDescription": "The model used for tab autocompletion. If undefined, Continue will default to using starcoder2:3b on a local Ollama instance.\n\n*IMPORTANT*:\n\nIf you use a custom model, ensure that it is one trained for fill-in-the-middle completions. An instruct model is typically not well-suited to autocomplete and you may receive unsatisfactory completions.", + "x-intellij-html-description": "The model used for tab autocompletion. If undefined, Continue will default to using starcoder2:3b on a local Ollama instance.

IMPORTANT:

If you use a custom model, ensure that it is one trained for fill-in-the-middle completions. An instruct model is typically not well-suited to autocomplete and you may receive unsatisfactory completions.", "default": { "title": "Tab Autocomplete Model", "provider": "ollama", @@ -3061,6 +3018,7 @@ "title": "TabAutocompleteOptions", "type": "object", "markdownDescription": "These options let you customize your tab-autocomplete experience. Read about all options in [the docs](https://docs.continue.dev/features/tab-autocomplete#configuration-options).", + "x-intellij-html-description": "These options let you customize your tab-autocomplete experience. Read about all options in the docs.", "properties": { "disable": { "type": "boolean", @@ -3091,6 +3049,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." @@ -3147,6 +3109,7 @@ "showChatScrollbar": { "title": "Show Chat Scrollbar", "markdownDescription": "If set to `true`, a scrollbar will be displayed in the chat window to navigate through messages.", + "x-intellij-html-description": "If set to true, a scrollbar will be displayed in the chat window to navigate through messages.", "default": false, "type": "boolean" } diff --git a/extensions/vscode/continue_tutorial.py b/extensions/vscode/continue_tutorial.py index c10e5c209..16a297c16 100644 --- a/extensions/vscode/continue_tutorial.py +++ b/extensions/vscode/continue_tutorial.py @@ -7,8 +7,12 @@ Chat, Edit, and Autocomplete tutorial """ -# ———————————————————— Chat [Cmd/Ctrl + L]: Ask "what sorting algorithm is this?" ———————————————————— +# ————————————————————————————————————————————————— Chat ————————————————————————————————————————————————— # + +## Highlight the code below +## Press [Cmd/Ctrl + J] to add to Chat +## Try asking Continue "what sorting algorithm is this?" def sorting_algorithm(x): for i in range(len(x)): for j in range(len(x) - 1): @@ -16,8 +20,12 @@ def sorting_algorithm(x): x[j], x[j + 1] = x[j + 1], x[j] return x -# —————————————————— Edit [Cmd/Ctrl + I]: Tell Continue to "make this more readable" ————————————————— +# ————————————————————————————————————————————————— Edit ————————————————————————————————————————————————— # + +## Highlight the code below +## Press [Cmd/Ctrl + I] to Edit +## Try asking Continue to "make this more readable" def sorting_algorithm(x): for i in range(len(x)): for j in range(len(x) - 1): @@ -25,9 +33,12 @@ def sorting_algorithm(x): x[j], x[j + 1] = x[j + 1], x[j] return x -# ——————————————— Autocomplete [Tab]: Place cursor after `:` below and press [Enter] ————————————————— +# ————————————————————————————————————————————— Autocomplete —————————————————————————————————————————————— # -# Basic assertion for sorting_algorithm: +## Place cursor after `sorting_algorithm...` below and press [Enter] +## Press [Tab] to accept the Autocomplete suggestion + +# Basic assertion for sorting_algorithm... -"—————————————————— Learn more at https://docs.continue.dev/getting-started/overview ————————————————" \ No newline at end of file +# —————————————————— Learn more at https://docs.continue.dev/getting-started/overview ——————————————————— # diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 4c137be21..7ebbfdcff 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.220", + "version": "0.9.222", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.220", + "version": "0.9.222", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", @@ -71,7 +71,6 @@ "@types/vscode": "1.70", "@types/ws": "^8.5.4", "@typescript-eslint/eslint-plugin": "^5.45.0", - "@typescript-eslint/parser": "^5.45.0", "@vscode/vsce": "^2.22.0", "cargo-cp-artifact": "^0.1", "esbuild": "0.17.19", @@ -103,7 +102,6 @@ "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", "@typescript-eslint/eslint-plugin": "^7.8.0", - "@typescript-eslint/parser": "^7.8.0", "@xenova/transformers": "2.14.0", "adf-to-md": "^1.1.0", "async-mutex": "^0.5.0", @@ -175,7 +173,6 @@ "cross-env": "^7.0.3", "esbuild": "0.17.19", "eslint": "^8", - "eslint-plugin-import": "^2.29.1", "jest": "^29.7.0", "jest-environment-jsdom": "^29.7.0", "myers-diff": "^2.1.0", @@ -2152,6 +2149,7 @@ "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-5.62.0.tgz", "integrity": "sha512-VlJEV0fOQ7BExOsHYAGrgbEiZoi8D+Bl2+f6V2RrXerRSylnp+ZBHmPvaIa8cz0Ajx7WO7Z5RqfgYg7ED1nRhA==", "dev": true, + "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "5.62.0", "@typescript-eslint/types": "5.62.0", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 863630d9c..f986112c2 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "0.9.221", + "version": "0.9.222", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" @@ -280,6 +280,12 @@ "category": "Continue", "title": "Docs Force Re-Index", "group": "Continue" + }, + { + "command": "continue.focusContinueSessionId", + "category": "Continue", + "title": "Focus Continue Chat", + "group": "Continue" } ], "keybindings": [ @@ -539,7 +545,6 @@ "@types/vscode": "1.70", "@types/ws": "^8.5.4", "@typescript-eslint/eslint-plugin": "^5.45.0", - "@typescript-eslint/parser": "^5.45.0", "@vscode/vsce": "^2.22.0", "cargo-cp-artifact": "^0.1", "esbuild": "0.17.19", diff --git a/extensions/vscode/scripts/prepackage-cross-platform.js b/extensions/vscode/scripts/prepackage-cross-platform.js index 1146d7399..c8d7624de 100644 --- a/extensions/vscode/scripts/prepackage-cross-platform.js +++ b/extensions/vscode/scripts/prepackage-cross-platform.js @@ -85,7 +85,7 @@ function isWin() { async function package(target, os, arch, exe) { console.log("[info] Packaging extension for target ", target); - // Copy config_schema to docs and intellij + // Copy config_schema to intellij copyConfigSchema(); // Install node_modules diff --git a/extensions/vscode/scripts/prepackage.js b/extensions/vscode/scripts/prepackage.js index 3cfeb26e9..5bd1d6da7 100644 --- a/extensions/vscode/scripts/prepackage.js +++ b/extensions/vscode/scripts/prepackage.js @@ -49,7 +49,7 @@ const exe = os === "win32" ? ".exe" : ""; (async () => { console.log("[info] Packaging extension for target ", target); - // Copy config schemas to docs and intellij + // Copy config schemas to intellij copyConfigSchema(); if (!process.cwd().endsWith("vscode")) { diff --git a/extensions/vscode/scripts/utils.js b/extensions/vscode/scripts/utils.js index 367c17708..fc4e1e020 100644 --- a/extensions/vscode/scripts/utils.js +++ b/extensions/vscode/scripts/utils.js @@ -23,11 +23,7 @@ function copyConfigSchema() { }; fs.writeFileSync("continue_rc_schema.json", JSON.stringify(schema, null, 2)); - // Copy config schemas to docs and intellij - fs.copyFileSync( - "config_schema.json", - path.join("..", "..", "docs", "static", "schemas", "config.json"), - ); + // Copy config schemas to intellij fs.copyFileSync( "config_schema.json", path.join( @@ -50,7 +46,6 @@ function copyConfigSchema() { "continue_rc_schema.json", ), ); - } function copyTokenizers() { diff --git a/extensions/vscode/src/ContinueGUIWebviewViewProvider.ts b/extensions/vscode/src/ContinueGUIWebviewViewProvider.ts index f685f942d..a923ca422 100644 --- a/extensions/vscode/src/ContinueGUIWebviewViewProvider.ts +++ b/extensions/vscode/src/ContinueGUIWebviewViewProvider.ts @@ -58,6 +58,7 @@ export class ContinueGUIWebviewViewProvider _context: vscode.WebviewViewResolveContext, _token: vscode.CancellationToken, ): void | Thenable { + this._webviewView = webviewView; this._webview = webviewView.webview; this._webview.onDidReceiveMessage((message) => this.handleWebviewMessage(message), diff --git a/extensions/vscode/src/activation/activate.ts b/extensions/vscode/src/activation/activate.ts index cce7bcfbe..864b07cc4 100644 --- a/extensions/vscode/src/activation/activate.ts +++ b/extensions/vscode/src/activation/activate.ts @@ -1,11 +1,9 @@ -import { getContinueRcPath, getTsConfigPath, migrate } from "core/util/paths"; +import { getContinueRcPath, getTsConfigPath } from "core/util/paths"; import { Telemetry } from "core/util/posthog"; -import path from "node:path"; import * as vscode from "vscode"; import { VsCodeExtension } from "../extension/VsCodeExtension"; import registerQuickFixProvider from "../lang-server/codeActions"; import { getExtensionVersion } from "../util/util"; -import { getExtensionUri } from "../util/vscode"; import { VsCodeContinueApi } from "./api"; import { setupInlineTips } from "./inlineTips"; diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index e81ae2380..2a93e9154 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -480,6 +480,14 @@ const commandsMap: ( "continue.viewHistory": () => { sidebar.webviewProtocol?.request("viewHistory", undefined); }, + "continue.focusContinueSessionId": async (sessionId: string | undefined) => { + if (!sessionId) { + sessionId = await vscode.window.showInputBox({ + prompt: "Enter the Session ID" + }); + } + sidebar.webviewProtocol?.request("focusContinueSessionId", { sessionId }); + }, "continue.applyCodeFromChat": () => { sidebar.webviewProtocol.request("applyCodeFromChat", undefined); }, diff --git a/extensions/vscode/src/diff/vertical/decorations.ts b/extensions/vscode/src/diff/vertical/decorations.ts index 276145207..5d3ae7525 100644 --- a/extensions/vscode/src/diff/vertical/decorations.ts +++ b/extensions/vscode/src/diff/vertical/decorations.ts @@ -36,16 +36,10 @@ export const belowIndexDecorationType = }); export class DecorationTypeRangeManager { - private decorationType: vscode.TextEditorDecorationType; - private editor: vscode.TextEditor; - constructor( - decorationType: vscode.TextEditorDecorationType, - editor: vscode.TextEditor, - ) { - this.decorationType = decorationType; - this.editor = editor; - } + private decorationType: vscode.TextEditorDecorationType, + private editor: vscode.TextEditor, + ) {} private ranges: vscode.Range[] = []; diff --git a/extensions/vscode/src/diff/vertical/handler.ts b/extensions/vscode/src/diff/vertical/handler.ts index 125bf065d..fbaddd964 100644 --- a/extensions/vscode/src/diff/vertical/handler.ts +++ b/extensions/vscode/src/diff/vertical/handler.ts @@ -17,9 +17,6 @@ export interface VerticalDiffHandlerOptions { } export class VerticalDiffHandler implements vscode.Disposable { - private editor: vscode.TextEditor; - private startLine: number; - private endLine: number; private currentLineIndex: number; private cancelled = false; @@ -31,12 +28,10 @@ export class VerticalDiffHandler implements vscode.Disposable { private newLinesAdded = 0; - public options: VerticalDiffHandlerOptions; - constructor( - startLine: number, - endLine: number, - editor: vscode.TextEditor, + private startLine: number, + private endLine: number, + private editor: vscode.TextEditor, private readonly editorToVerticalDiffCodeLens: Map< string, VerticalDiffCodeLens[] @@ -46,18 +41,15 @@ export class VerticalDiffHandler implements vscode.Disposable { accept: boolean, ) => void, private readonly refreshCodeLens: () => void, - options: VerticalDiffHandlerOptions, + public options: VerticalDiffHandlerOptions, ) { this.currentLineIndex = startLine; - this.startLine = startLine; - this.endLine = endLine; - this.editor = editor; - this.options = options; this.redDecorationManager = new DecorationTypeRangeManager( redDecorationType, this.editor, ); + this.greenDecorationManager = new DecorationTypeRangeManager( greenDecorationType, this.editor, @@ -344,6 +336,7 @@ export class VerticalDiffHandler implements vscode.Disposable { } async run(diffLineGenerator: AsyncGenerator) { + let diffLines = [] try { // As an indicator of loading this.updateIndexLineDecorations(); @@ -352,6 +345,7 @@ export class VerticalDiffHandler implements vscode.Disposable { if (this.isCancelled) { return; } + diffLines.push(diffLine) await this.queueDiffLine(diffLine); } @@ -374,6 +368,7 @@ export class VerticalDiffHandler implements vscode.Disposable { this.clearForFilepath(this.filepath, false); throw e; } + return diffLines } async acceptRejectBlock( diff --git a/extensions/vscode/src/diff/vertical/manager.ts b/extensions/vscode/src/diff/vertical/manager.ts index 985a6ba29..5a6f8a96d 100644 --- a/extensions/vscode/src/diff/vertical/manager.ts +++ b/extensions/vscode/src/diff/vertical/manager.ts @@ -22,6 +22,8 @@ export class VerticalDiffManager { private userChangeListener: vscode.Disposable | undefined; + logDiffs: DiffLine[] | undefined; + constructor( private readonly configHandler: ConfigHandler, private readonly webviewProtocol: VsCodeWebviewProtocol, @@ -237,8 +239,8 @@ export class VerticalDiffManager { ); try { - await diffHandler.run(diffStream); - + this.logDiffs = await diffHandler.run(diffStream); + // enable a listener for user edits to file while diff is open this.enableDocumentChangeListener(); } catch (e) { @@ -410,7 +412,7 @@ export class VerticalDiffManager { ); try { - await diffHandler.run( + this.logDiffs = await diffHandler.run( streamDiffLines( prefix, rangeContent, diff --git a/extensions/vscode/src/extension.ts b/extensions/vscode/src/extension.ts index e3967bdb2..9fa7cfb49 100644 --- a/extensions/vscode/src/extension.ts +++ b/extensions/vscode/src/extension.ts @@ -3,18 +3,31 @@ */ import { setupCa } from "core/util/ca"; +import { extractMinimalStackTraceInfo } from "core/util/extractMinimalStackTraceInfo"; import { Telemetry } from "core/util/posthog"; import * as vscode from "vscode"; import { getExtensionVersion } from "./util/util"; async function dynamicImportAndActivate(context: vscode.ExtensionContext) { + await setupCa(); const { activateExtension } = await import("./activation/activate"); - try { - return activateExtension(context); - } catch (e) { + return await activateExtension(context); +} + +export function activate(context: vscode.ExtensionContext) { + return dynamicImportAndActivate(context).catch((e) => { console.log("Error activating extension: ", e); + Telemetry.capture( + "vscode_extension_activation_error", + { + stack: extractMinimalStackTraceInfo(e.stack), + message: e.message, + }, + false, + true, + ); vscode.window - .showInformationMessage( + .showWarningMessage( "Error activating the Continue extension.", "View Logs", "Retry", @@ -27,12 +40,7 @@ async function dynamicImportAndActivate(context: vscode.ExtensionContext) { vscode.commands.executeCommand("workbench.action.reloadWindow"); } }); - } -} - -export function activate(context: vscode.ExtensionContext) { - setupCa(); - return dynamicImportAndActivate(context); + }); } export function deactivate() { diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index cd4e36a99..6ba5f1279 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -35,6 +35,7 @@ import { VsCodeWebviewProtocol } from "../webviewProtocol"; type TODO = any; type ToIdeOrWebviewFromCoreProtocol = ToIdeFromCoreProtocol & ToWebviewFromCoreProtocol; + export class VsCodeMessenger { onWebview( messageType: T, @@ -149,7 +150,7 @@ export class VsCodeMessenger { await vscode.commands.executeCommand("continue.rejectDiff", filepath); }); - this.onWebview("applyToCurrentFile", async (msg) => { + this.onWebview("applyToCurrentFile", async ({ data }) => { // Get active text editor const editor = vscode.window.activeTextEditor; if (!editor) { @@ -157,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(); @@ -164,16 +175,11 @@ export class VsCodeMessenger { let llm = getModelByRole(config, "applyCodeBlock"); if (!llm) { - const defaultModelTitle = await this.webviewProtocol.request( - "getDefaultModelTitle", - undefined, - ); - - llm = config.models.find((model) => model.title === defaultModelTitle); + llm = config.models.find((model) => model.title === data.curSelectedModelTitle); if (!llm) { vscode.window.showErrorMessage( - `Model ${defaultModelTitle} not found in config.`, + `Model ${data.curSelectedModelTitle} not found in config.`, ); return; } @@ -184,20 +190,20 @@ export class VsCodeMessenger { // Generate the diff and pass through diff manager const [instant, diffLines] = await applyCodeBlock( editor.document.getText(), - msg.data.text, + data.text, getBasename(editor.document.fileName), llm, fastLlm, ); const verticalDiffManager = await this.verticalDiffManagerPromise; if (instant) { - verticalDiffManager.streamDiffLines( + await verticalDiffManager.streamDiffLines( diffLines, instant, - msg.data.streamId, + data.streamId, ); } else { - const prompt = `The following code was suggested as an edit:\n\`\`\`\n${msg.data.text}\n\`\`\`\nPlease apply it to the previous code.`; + const prompt = `The following code was suggested as an edit:\n\`\`\`\n${data.text}\n\`\`\`\nPlease apply it to the previous code.`; const fullEditorRange = new vscode.Range( 0, 0, @@ -207,10 +213,11 @@ export class VsCodeMessenger { const rangeToApplyTo = editor.selection.isEmpty ? fullEditorRange : editor.selection; - verticalDiffManager.streamEdit( + + await verticalDiffManager.streamEdit( prompt, llm.title, - msg.data.streamId, + data.streamId, undefined, undefined, rangeToApplyTo, diff --git a/extensions/vscode/src/lang-server/codeLens/providers/DiffViewerCodeLensProvider.ts b/extensions/vscode/src/lang-server/codeLens/providers/DiffViewerCodeLensProvider.ts index 405df9a24..b67db0e52 100644 --- a/extensions/vscode/src/lang-server/codeLens/providers/DiffViewerCodeLensProvider.ts +++ b/extensions/vscode/src/lang-server/codeLens/providers/DiffViewerCodeLensProvider.ts @@ -4,11 +4,7 @@ import { DiffManager, DIFF_DIRECTORY } from "../../../diff/horizontal"; import { getMetaKeyLabel } from "../../../util/util"; export class DiffViewerCodeLensProvider implements vscode.CodeLensProvider { - diffManager: DiffManager; - - constructor(diffManager: DiffManager) { - this.diffManager = diffManager; - } + constructor(private diffManager: DiffManager) {} public provideCodeLenses( document: vscode.TextDocument, diff --git a/extensions/vscode/src/lang-server/codeLens/providers/QuickActionsCodeLensProvider.ts b/extensions/vscode/src/lang-server/codeLens/providers/QuickActionsCodeLensProvider.ts index 5f6748b61..08decb215 100644 --- a/extensions/vscode/src/lang-server/codeLens/providers/QuickActionsCodeLensProvider.ts +++ b/extensions/vscode/src/lang-server/codeLens/providers/QuickActionsCodeLensProvider.ts @@ -62,13 +62,7 @@ export class QuickActionsCodeLensProvider implements vscode.CodeLensProvider { vscode.SymbolKind.Constructor, ]; - customQuickActionsConfig?: QuickActionConfig[]; - - constructor(customQuickActionsConfigs?: QuickActionConfig[]) { - if (customQuickActionsConfigs) { - this.customQuickActionsConfig = customQuickActionsConfigs; - } - } + constructor(private customQuickActionsConfigs?: QuickActionConfig[]) {} getCustomCommands( range: vscode.Range, @@ -145,8 +139,8 @@ export class QuickActionsCodeLensProvider implements vscode.CodeLensProvider { const symbols = await this.getTopLevelAndChildrenSymbols(document.uri); return symbols.flatMap(({ range }) => { - const commands: vscode.Command[] = !!this.customQuickActionsConfig - ? this.getCustomCommands(range, this.customQuickActionsConfig) + const commands: vscode.Command[] = !!this.customQuickActionsConfigs + ? this.getCustomCommands(range, this.customQuickActionsConfigs) : this.getDefaultCommand(range); return commands.map((command) => new vscode.CodeLens(range, command)); diff --git a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts index 0cc11a0ad..2ec7aa515 100644 --- a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts +++ b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts @@ -15,6 +15,7 @@ import { ConfigHandler } from "core/config/ConfigHandler"; import { getModelByRole } from "core/config/util"; // @ts-ignore import MiniSearch from "minisearch"; +import { logDevData } from "core/util/devdata"; /** * Used to track what action to take after a user interacts @@ -236,7 +237,8 @@ export class QuickEdit { default: break; } - + let model = await this.getCurModelTitle(); + logDevData('quickEdit', {prompt, path, label, diffs: this.verticalDiffManager.logDiffs, model}); quickPick.dispose(); }); } @@ -319,9 +321,8 @@ export class QuickEdit { return isSelectionEmpty ? `Edit ${fileName}` - : `Edit ${fileName}:${start.line}${ - end.line > start.line ? `-${end.line}` : "" - }`; + : `Edit ${fileName}:${start.line}${end.line > start.line ? `-${end.line}` : "" + }`; }; private async _streamEditWithInputAndContext( @@ -385,7 +386,7 @@ export class QuickEdit { const modelTitle = await this.getCurModelTitle(); if (!modelTitle) { - this.ide.showToast("info", "Please configure a model to use Quick Edit"); + this.ide.showToast("error", "Please configure a model to use Quick Edit"); return { label: undefined, value: undefined }; } diff --git a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts index da9ae55f8..c8f5ee79a 100644 --- a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts +++ b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts @@ -94,31 +94,42 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { this.secretStorage = new SecretStorage(context); } - private decodeJwt(jwt: string): any { - const decodedToken = JSON.parse( - Buffer.from(jwt.split(".")[1], "base64").toString(), - ); - return decodedToken; + private decodeJwt(jwt: string): Record | null { + try { + const decodedToken = JSON.parse( + Buffer.from(jwt.split(".")[1], "base64").toString(), + ); + return decodedToken; + } catch (e: any) { + console.warn(`Error decoding JWT: ${e}`); + return null; + } } private getExpirationTimeMs(jwt: string): number { const decodedToken = this.decodeJwt(jwt); + if (!decodedToken) { + return WorkOsAuthProvider.EXPIRATION_TIME_MS; + } return decodedToken.exp && decodedToken.iat ? (decodedToken.exp - decodedToken.iat) * 1000 : WorkOsAuthProvider.EXPIRATION_TIME_MS; } - private jwtIsExpired(jwt: string): boolean { + private jwtIsExpiredOrInvalid(jwt: string): boolean { const decodedToken = this.decodeJwt(jwt); + if (!decodedToken) { + return true; + } return decodedToken.exp * 1000 < Date.now(); } private async debugAccessTokenValidity(jwt: string, refreshToken: string) { - const expired = this.jwtIsExpired(jwt); - if (expired) { - console.debug(`Invalid JWT: ${expired}`); + const expiredOrInvalid = this.jwtIsExpiredOrInvalid(jwt); + if (expiredOrInvalid) { + console.debug("Invalid JWT"); } else { - console.debug(`Valid JWT: ${expired}`); + console.debug("Valid JWT"); } } @@ -135,8 +146,13 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { return []; } - const value = JSON.parse(data) as ContinueAuthenticationSession[]; - return value; + try { + const value = JSON.parse(data) as ContinueAuthenticationSession[]; + return value; + } catch (e: any) { + console.warn(`Error parsing sessions.json: ${e}`); + return []; + } } get onDidChangeSessions() { @@ -160,7 +176,11 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { } async refreshSessions() { - await this._refreshSessions(); + try { + await this._refreshSessions(); + } catch (e) { + console.error(`Error refreshing sessions: ${e}`); + } } private async _refreshSessions(): Promise { diff --git a/extensions/vscode/src/terminal/terminalEmulator.ts b/extensions/vscode/src/terminal/terminalEmulator.ts index d76823da6..b2a7a99a9 100644 --- a/extensions/vscode/src/terminal/terminalEmulator.ts +++ b/extensions/vscode/src/terminal/terminalEmulator.ts @@ -129,7 +129,6 @@ export class CapturedTerminal { private readonly writeEmitter: vscode.EventEmitter; private splitByCommandsBuffer = ""; - private readonly onCommandOutput: ((output: string) => void) | undefined; splitByCommandsListener(data: string) { // Split the output by commands so it can be sent to Continue Server @@ -164,10 +163,8 @@ export class CapturedTerminal { constructor( options: { name: string } & Partial, - onCommandOutput?: (output: string) => void, + private readonly onCommandOutput?: (output: string) => void, ) { - this.onCommandOutput = onCommandOutput; - // this.shellCmd = "bash"; // getDefaultShell(); this.shellCmd = getDefaultShell(); diff --git a/extensions/vscode/src/util/loadAutocompleteModel.ts b/extensions/vscode/src/util/loadAutocompleteModel.ts index 4437c11d1..9b86c7751 100644 --- a/extensions/vscode/src/util/loadAutocompleteModel.ts +++ b/extensions/vscode/src/util/loadAutocompleteModel.ts @@ -13,11 +13,7 @@ export class TabAutocompleteModel { private shownOllamaWarning = false; private shownDeepseekWarning = false; - private configHandler: ConfigHandler; - - constructor(configHandler: ConfigHandler) { - this.configHandler = configHandler; - } + constructor(private configHandler: ConfigHandler) {} clearLlm() { this._llm = undefined; diff --git a/extensions/vscode/src/webviewProtocol.ts b/extensions/vscode/src/webviewProtocol.ts index 89524a371..be309e390 100644 --- a/extensions/vscode/src/webviewProtocol.ts +++ b/extensions/vscode/src/webviewProtocol.ts @@ -30,8 +30,7 @@ export async function showTutorial() { } export class VsCodeWebviewProtocol - implements IMessenger -{ + implements IMessenger { listeners = new Map< keyof FromWebviewProtocol, ((message: Message) => any)[] @@ -125,7 +124,7 @@ export class VsCodeWebviewProtocol message = message.split("\n").filter((l: string) => l !== "")[1]; try { message = JSON.parse(message).message; - } catch {} + } catch { } if (message.includes("exceeded")) { message += " To keep using Continue, you can set up a local model or use your own API key."; @@ -179,7 +178,7 @@ export class VsCodeWebviewProtocol }); } - constructor(private readonly reloadConfig: () => void) {} + constructor(private readonly reloadConfig: () => void) { } invoke( messageType: T, data: FromWebviewProtocol[T][0], 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" ] } diff --git a/gui/package-lock.json b/gui/package-lock.json index 25a992592..ef9f8cda9 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -104,7 +104,6 @@ "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", "@typescript-eslint/eslint-plugin": "^7.8.0", - "@typescript-eslint/parser": "^7.8.0", "@xenova/transformers": "2.14.0", "adf-to-md": "^1.1.0", "async-mutex": "^0.5.0", @@ -176,7 +175,6 @@ "cross-env": "^7.0.3", "esbuild": "0.17.19", "eslint": "^8", - "eslint-plugin-import": "^2.29.1", "jest": "^29.7.0", "jest-environment-jsdom": "^29.7.0", "myers-diff": "^2.1.0", diff --git a/gui/public/logos/ask-sage.png b/gui/public/logos/ask-sage.png new file mode 100644 index 000000000..6700221ba Binary files /dev/null and b/gui/public/logos/ask-sage.png differ diff --git a/gui/public/logos/ibm.png b/gui/public/logos/ibm.png index be88ec2ed..7a465290a 100644 Binary files a/gui/public/logos/ibm.png and b/gui/public/logos/ibm.png differ diff --git a/gui/public/logos/ibmold.png b/gui/public/logos/ibmold.png new file mode 100644 index 000000000..be88ec2ed Binary files /dev/null and b/gui/public/logos/ibmold.png differ diff --git a/gui/public/logos/vertexai.png b/gui/public/logos/vertexai.png new file mode 100644 index 000000000..1744c1f07 Binary files /dev/null and b/gui/public/logos/vertexai.png differ diff --git a/gui/src/components/Footer.tsx b/gui/src/components/Footer.tsx index 4b6b012a8..21b9df4f6 100644 --- a/gui/src/components/Footer.tsx +++ b/gui/src/components/Footer.tsx @@ -5,15 +5,15 @@ import { } from "@heroicons/react/24/outline"; import { useContext } from "react"; import { useSelector } from "react-redux"; -import { useLocation, useNavigate, useResolvedPath } from "react-router-dom"; +import { useLocation, useNavigate } from "react-router-dom"; import { IdeMessengerContext } from "../context/IdeMessenger"; import { defaultModelSelector } from "../redux/selectors/modelSelectors"; import { RootState } from "../redux/store"; import { FREE_TRIAL_LIMIT_REQUESTS } from "../util/freeTrial"; +import { ROUTES } from "../util/navigation"; import ButtonWithTooltip from "./ButtonWithTooltip"; import FreeTrialProgressBar from "./loaders/FreeTrialProgressBar"; import ProfileSwitcher from "./ProfileSwitcher"; -import { ROUTES } from "../util/navigation"; function Footer() { const navigate = useNavigate(); @@ -41,14 +41,14 @@ function Footer() { } else { ideMessenger.post( "openUrl", - `http://app.continue.dev/workspaces/${selectedProfileId}/config`, + `http://app.continue.dev/workspaces/${selectedProfileId}/chat`, ); } } return ( -