diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 93c04fe38..c6e087b38 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -27,14 +27,15 @@ body: - **Continue version**: v0.9.4 - **IDE version**: VSCode 1.85.1 - Model: Claude Sonnet 3.5 - - config.json: `{ "models": ... }` + - config.yaml: `models: ...` + - OR config.json: `{ "models": ... }` value: | - OS: - Continue version: - IDE version: - Model: - - config.json: - ```json + - config: + ```yaml ``` render: Markdown diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 9b79be9c1..ffc4a967f 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -6,11 +6,11 @@ name: JetBrains Release on: release: - types: [ prereleased ] + types: [prereleased] workflow_dispatch: inputs: publish_build: - description: 'Whether or not to publish the built extension to the JetBrains marketplace' + description: "Whether or not to publish the built extension to the JetBrains marketplace" required: true default: false @@ -241,6 +241,12 @@ jobs: name: continue-binary-win32-x64 path: ./binary/bin/win32-x64/ + - name: Upload artifact (win32-arm64) + uses: actions/upload-artifact@v4 + with: + name: continue-binary-win32-arm64 + path: ./binary/bin/win32-arm64/ + - name: Upload artifact (linux-arm64) uses: actions/upload-artifact@v4 with: @@ -345,7 +351,7 @@ jobs: # Run tests and upload a code coverage report test: name: Test - needs: [ build ] + needs: [build] runs-on: ubuntu-latest steps: # Check out current repository @@ -387,7 +393,7 @@ jobs: inspectCode: if: false name: Inspect code - needs: [ build ] + needs: [build] runs-on: ubuntu-latest permissions: contents: write @@ -422,7 +428,7 @@ jobs: verify: if: false name: Verify plugin - needs: [ build ] + needs: [build] runs-on: ubuntu-latest steps: # Free GitHub Actions Environment Disk Space diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index d10d58ef1..46209d364 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -208,7 +208,7 @@ jobs: runs-on: ubuntu-latest needs: - build - if: github.event.inputs.publish_build == 'true' + if: github.event_name != 'workflow_dispatch' || github.event.inputs.publish_build == 'true' permissions: contents: write steps: diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index 578e0974b..7c005de7b 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -4,22 +4,10 @@ on: pull_request: branches: - main - paths: - - "extensions/intellij/**" - - "extensions/vscode/**" - - "core/**" - - "gui/**" - - ".github/workflows/**" push: branches: - main - paths: - - "extensions/intellij/**" - - "extensions/vscode/**" - - "core/**" - - "gui/**" - - ".github/workflows/**" jobs: install-root: @@ -290,6 +278,8 @@ jobs: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }} + AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }} + AZURE_FOUNDRY_API_KEY: ${{ secrets.AZURE_FOUNDRY_API_KEY }} vscode-get-test-file-matrix: runs-on: ubuntu-latest diff --git a/.github/workflows/preview.yaml b/.github/workflows/preview.yaml index bd5f4b7ac..abf58e6e8 100644 --- a/.github/workflows/preview.yaml +++ b/.github/workflows/preview.yaml @@ -4,6 +4,13 @@ on: release: types: [prereleased] + workflow_dispatch: + inputs: + publish_build: + description: "Whether or not to publish the built extension to the VS Code marketplace" + required: true + default: false + jobs: check_release_name: runs-on: ubuntu-latest @@ -21,7 +28,7 @@ jobs: build: needs: check_release_name - if: needs.check_release_name.outputs.should_run == 'true' + if: needs.check_release_name.outputs.should_run == 'true' || github.event_name == 'workflow_dispatch' strategy: matrix: include: @@ -197,6 +204,7 @@ jobs: runs-on: ubuntu-latest needs: - build + if: github.event_name != 'workflow_dispatch' || github.event.inputs.publish_build == 'true' permissions: contents: write steps: diff --git a/.vscode/tasks.json b/.vscode/tasks.json index e3250d80a..84ee4e60f 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -6,16 +6,14 @@ "type": "npm", "script": "tsc:watch", "isBackground": true, - "problemMatcher": { - "base": "$tsc-watch", - "background": { - "activeOnStart": true, - "beginsPattern": "Starting compilation in watch mode...", - "endsPattern": "Found 0 errors" - } + "problemMatcher": ["$tsc-watch"], + "group": { + "kind": "build", + "isDefault": true }, "presentation": { - "revealProblems": "onProblem" + "reveal": "always", + "panel": "new" } }, // Compile and bundle the extension @@ -186,6 +184,55 @@ "command": "node", "args": ["${workspaceFolder}/scripts/uninstall.js"], "problemMatcher": [] + }, + { + "label": "refresh-dependencies:core", + "type": "shell", + "command": "npm", + "args": ["install"], + "problemMatcher": [], + "options": { + "cwd": "${workspaceFolder}/core" + }, + "presentation": { + "close": true + } + }, + { + "label": "refresh-dependencies:vscode", + "type": "shell", + "command": "npm", + "args": ["install"], + "problemMatcher": [], + "options": { + "cwd": "${workspaceFolder}/extensions/vscode" + }, + "presentation": { + "close": true + } + }, + { + "label": "refresh-dependencies:gui", + "type": "shell", + "command": "npm", + "args": ["install"], + "problemMatcher": [], + "options": { + "cwd": "${workspaceFolder}/gui" + }, + "presentation": { + "close": true + } + }, + { + "label": "refresh-dependencies:all", + "dependsOn": [ + "refresh-dependencies:core", + "refresh-dependencies:gui", + "refresh-dependencies:vscode" + ], + "type": "shell", + "problemMatcher": [] } ] } diff --git a/binary/build.js b/binary/build.js index 11aaf5c59..609a4b68c 100644 --- a/binary/build.js +++ b/binary/build.js @@ -53,7 +53,7 @@ const targetToLanceDb = { "linux-arm64": "@lancedb/vectordb-linux-arm64-gnu", "linux-x64": "@lancedb/vectordb-linux-x64-gnu", "win32-x64": "@lancedb/vectordb-win32-x64-msvc", - "win32-arm64": "@lancedb/vectordb-win32-x64-msvc", // they don't have a win32-arm64 build + "win32-arm64": "@lancedb/vectordb-win32-arm64-msvc", }; async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) { @@ -248,9 +248,15 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) { // Download and unzip prebuilt sqlite3 binary for the target console.log("[info] Downloading node-sqlite3"); - const downloadUrl = `https://github.com/TryGhost/node-sqlite3/releases/download/v5.1.7/sqlite3-v5.1.7-napi-v6-${ - target === "win32-arm64" ? "win32-ia32" : target - }.tar.gz`; + + const downloadUrl = + // node-sqlite3 doesn't have a pre-built binary for win32-arm64 + target === "win32-arm64" + ? "https://continue-server-binaries.s3.us-west-1.amazonaws.com/win32-arm64/node_sqlite3.tar.gz" + : `https://github.com/TryGhost/node-sqlite3/releases/download/v5.1.7/sqlite3-v5.1.7-napi-v6-${ + target + }.tar.gz`; + execCmdSync(`curl -L -o ${targetDir}/build.tar.gz ${downloadUrl}`); execCmdSync(`cd ${targetDir} && tar -xvzf build.tar.gz`); diff --git a/binary/package-lock.json b/binary/package-lock.json index 84b831ecf..367b0eb93 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -48,11 +48,11 @@ "@aws-sdk/client-sagemaker-runtime": "^3.621.0", "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.23", + "@continuedev/config-yaml": "^1.0.28", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", "@continuedev/openai-adapters": "^1.0.10", - "@modelcontextprotocol/sdk": "^1.0.0", + "@modelcontextprotocol/sdk": "^1.5.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", "@typescript-eslint/eslint-plugin": "^7.8.0", @@ -128,7 +128,7 @@ "@types/uuid": "^9.0.7", "@types/win-ca": "^3.5.4", "cross-env": "^7.0.3", - "esbuild": "0.17.19", + "esbuild": "0.24.0", "eslint": "^8", "jest": "^29.7.0", "jest-environment-jsdom": "^29.7.0", @@ -2556,9 +2556,10 @@ } }, "node_modules/axios": { - "version": "1.6.8", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.6.8.tgz", - "integrity": "sha512-v/ZHtJDU39mDpyBoFVkETcd/uNdxrWRrg3bKpOKzXFA6Bvqopts6ALSMU3y6ijYxbw2B+wPrIv46egTzJXCLGQ==", + "version": "1.7.9", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.9.tgz", + "integrity": "sha512-LhLcE7Hbiryz8oMDdDptSrWowmB4Bl6RCt6sIJKpRB4XtVf0iEgewX3au/pJqm+Py1kCASkb/FFKjxQaLtxJvw==", + "license": "MIT", "dependencies": { "follow-redirects": "^1.15.6", "form-data": "^4.0.0", @@ -3166,10 +3167,11 @@ } }, "node_modules/cross-spawn": { - "version": "7.0.3", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", - "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", "dev": true, + "license": "MIT", "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", @@ -5135,12 +5137,13 @@ } }, "node_modules/micromatch": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.5.tgz", - "integrity": "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==", + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", "dev": true, + "license": "MIT", "dependencies": { - "braces": "^3.0.2", + "braces": "^3.0.3", "picomatch": "^2.3.1" }, "engines": { diff --git a/binary/src/IpcMessenger.ts b/binary/src/IpcMessenger.ts index e90fbeb84..b92a8e6a2 100644 --- a/binary/src/IpcMessenger.ts +++ b/binary/src/IpcMessenger.ts @@ -75,7 +75,7 @@ class IPCMessengerBase< console.warn(`Error running handler for "${msg.messageType}": `, e); this._onErrorHandlers.forEach((handler) => { - handler(e); + handler(msg, e); }); } }); @@ -112,9 +112,9 @@ class IPCMessengerBase< lines.forEach((line) => this._handleLine(line)); } - private _onErrorHandlers: ((error: Error) => void)[] = []; + private _onErrorHandlers: ((message: Message, error: Error) => void)[] = []; - onError(handler: (error: Error) => void) { + onError(handler: (message: Message, error: Error) => void) { this._onErrorHandlers.push(handler); } @@ -217,7 +217,7 @@ export class CoreBinaryMessenger< extends IPCMessengerBase implements IMessenger { - private errorHandler: (error: Error) => void = () => {}; + private errorHandler: (message: Message, error: Error) => void = () => {}; private messageHandlers: Map< keyof ToProtocol, (message: Message) => Promise | any diff --git a/binary/src/TcpMessenger.ts b/binary/src/TcpMessenger.ts index ad4713473..907e32ed7 100644 --- a/binary/src/TcpMessenger.ts +++ b/binary/src/TcpMessenger.ts @@ -41,9 +41,9 @@ export class TcpMessenger< }); } - private _onErrorHandlers: ((error: Error) => void)[] = []; + private _onErrorHandlers: ((message: Message, error: Error) => void)[] = []; - onError(handler: (error: Error) => void) { + onError(handler: (message: Message, error: Error) => void) { this._onErrorHandlers.push(handler); } @@ -111,7 +111,7 @@ export class TcpMessenger< console.warn(`Error running handler for "${msg.messageType}": `, e); this._onErrorHandlers.forEach((handler) => { - handler(e); + handler(msg, e); }); } }); diff --git a/core/autocomplete/snippets/getAllSnippets.ts b/core/autocomplete/snippets/getAllSnippets.ts index 198bf16c6..dce9c9ff4 100644 --- a/core/autocomplete/snippets/getAllSnippets.ts +++ b/core/autocomplete/snippets/getAllSnippets.ts @@ -11,6 +11,8 @@ import { AutocompleteSnippetType, } from "./types"; +const IDE_SNIPPETS_ENABLED = false; // ideSnippets is not used, so it's temporarily disabled + export interface SnippetPayload { rootPathSnippets: AutocompleteCodeSnippet[]; importDefinitionSnippets: AutocompleteCodeSnippet[]; @@ -29,6 +31,27 @@ function racePromise(promise: Promise): Promise { return Promise.race([promise, timeoutPromise]); } +class DiffSnippetsCache { + private cache: Map = new Map(); + private lastTimestamp: number = 0; + + public set(timestamp: number, value: T): T { + // Clear old cache entry if exists + if (this.lastTimestamp !== timestamp) { + this.cache.clear(); + } + this.lastTimestamp = timestamp; + this.cache.set(timestamp, value); + return value; + } + + public get(timestamp: number): any | undefined { + return this.cache.get(timestamp); + } +} + +const diffSnippetsCache = new DiffSnippetsCache(); + // Some IDEs might have special ways of finding snippets (e.g. JetBrains and VS Code have different "LSP-equivalent" systems, // or they might separately track recently edited ranges) async function getIdeSnippets( @@ -90,14 +113,31 @@ const getClipboardSnippets = async ( const getDiffSnippets = async ( ide: IDE, ): Promise => { - const diff = await ide.getDiff(true); + const currentTimestamp = ide.getLastFileSaveTimestamp ? + ide.getLastFileSaveTimestamp() : + Math.floor(Date.now() / 10000) * 10000; // Defaults to update once in every 10 seconds - return diff.map((item) => { + // Check cache first + const cached = diffSnippetsCache.get(currentTimestamp) as AutocompleteDiffSnippet[]; + + if (cached) { + return cached; + } + + let diff: string[] = []; + try { + diff = await ide.getDiff(true); + } catch (e) { + console.error("Error getting diff for autocomplete", e); + } + + return diffSnippetsCache.set(currentTimestamp, diff.map((item) => { return { content: item, type: AutocompleteSnippetType.Diff, }; - }); + })); + }; export const getAllSnippets = async ({ @@ -122,10 +162,8 @@ export const getAllSnippets = async ({ clipboardSnippets, ] = await Promise.all([ racePromise(contextRetrievalService.getRootPathSnippets(helper)), - racePromise( - contextRetrievalService.getSnippetsFromImportDefinitions(helper), - ), - racePromise(getIdeSnippets(helper, ide, getDefinitionsFromLsp)), + racePromise(contextRetrievalService.getSnippetsFromImportDefinitions(helper)), + IDE_SNIPPETS_ENABLED ? racePromise(getIdeSnippets(helper, ide, getDefinitionsFromLsp)) : [], racePromise(getDiffSnippets(ide)), racePromise(getClipboardSnippets(ide)), ]); diff --git a/core/autocomplete/templating/AutocompleteTemplate.ts b/core/autocomplete/templating/AutocompleteTemplate.ts index 8f7bbd66d..7f5366df0 100644 --- a/core/autocomplete/templating/AutocompleteTemplate.ts +++ b/core/autocomplete/templating/AutocompleteTemplate.ts @@ -51,6 +51,8 @@ const stableCodeFimTemplate: AutocompleteTemplate = { }; // https://github.com/QwenLM/Qwen2.5-Coder?tab=readme-ov-file#3-file-level-code-completion-fill-in-the-middle +// This issue asks about the use of <|repo_name|> and <|file_sep|> together with <|fim_prefix|>, <|fim_suffix|> and <|fim_middle|> +// https://github.com/QwenLM/Qwen2.5-Coder/issues/343 const qwenCoderFimTemplate: AutocompleteTemplate = { template: "<|fim_prefix|>{{{prefix}}}<|fim_suffix|>{{{suffix}}}<|fim_middle|>", @@ -85,6 +87,11 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = { snippets, workspaceUris, ): [string, string] => { + + function getFileName(snippet: { uri: string, uniquePath: string }) { + return snippet.uri.startsWith("file://") ? snippet.uniquePath : snippet.uri + } + if (snippets.length === 0) { if (suffix.trim().length === 0 && prefix.trim().length === 0) { return [ @@ -111,14 +118,12 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = { return snippet.content; } - return `+++++ ${relativePaths[i].uri} \n${snippet.content}`; + return `+++++ ${getFileName(relativePaths[i])} \n${snippet.content}`; }) .join("\n\n"); return [ - `${otherFiles}\n\n+++++ ${ - relativePaths[relativePaths.length - 1].uri - }\n${prefix}`, + `${otherFiles}\n\n+++++ ${getFileName(relativePaths[relativePaths.length - 1])}\n${prefix}`, suffix, ]; }, @@ -126,7 +131,7 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = { return `[SUFFIX]${suffix}[PREFIX]${prefix}`; }, completionOptions: { - stop: ["[PREFIX]", "[SUFFIX]"], + stop: ["[PREFIX]", "[SUFFIX]", "\n+++++ "], }, }; @@ -218,9 +223,8 @@ const codegeexFimTemplate: AutocompleteTemplate = { [...snippets.map((snippet) => snippet.filepath), filepath], workspaceUris, ); - const baseTemplate = `###PATH:${ - relativePaths[relativePaths.length - 1] - }\n###LANGUAGE:${language}\n###MODE:BLOCK\n<|code_suffix|>${suffix}<|code_prefix|>${prefix}<|code_middle|>`; + const baseTemplate = `###PATH:${relativePaths[relativePaths.length - 1] + }\n###LANGUAGE:${language}\n###MODE:BLOCK\n<|code_suffix|>${suffix}<|code_prefix|>${prefix}<|code_middle|>`; if (snippets.length === 0) { return `<|user|>\n${baseTemplate}<|assistant|>\n`; } diff --git a/core/autocomplete/templating/filtering.ts b/core/autocomplete/templating/filtering.ts index c741dedc8..02dbade36 100644 --- a/core/autocomplete/templating/filtering.ts +++ b/core/autocomplete/templating/filtering.ts @@ -42,24 +42,100 @@ export const getSnippets = ( helper: HelperVars, payload: SnippetPayload, ): AutocompleteSnippet[] => { - const snippets = [ - ...payload.diffSnippets, - ...payload.clipboardSnippets, - ...payload.recentlyVisitedRangesSnippets, - ...shuffleArray( - filterSnippetsAlreadyInCaretWindow( - [...payload.rootPathSnippets, ...payload.importDefinitionSnippets], - helper.prunedCaretWindow, - ), - ), - ]; + + const snippets = { + "clipboard": payload.clipboardSnippets, + "recentlyVisitedRanges": payload.recentlyVisitedRangesSnippets, + "recentlyEditedRanges": payload.recentlyEditedRangeSnippets, + "diff": payload.diffSnippets, + "base": shuffleArray(filterSnippetsAlreadyInCaretWindow( + [...payload.rootPathSnippets, ...payload.importDefinitionSnippets], + helper.prunedCaretWindow, + )), + } + + // Define snippets with their priorities + const snippetConfigs: { + key: keyof typeof snippets; + enabledOrPriority: boolean | number; + defaultPriority: number; + snippets: AutocompleteSnippet[]; + }[] = [ + { + key: "clipboard", + enabledOrPriority: helper.options.experimental_includeClipboard, + defaultPriority: 1, + snippets: payload.clipboardSnippets, + }, + { + key: "recentlyVisitedRanges", + enabledOrPriority: helper.options.experimental_includeRecentlyVisitedRanges, + defaultPriority: 2, + snippets: payload.recentlyVisitedRangesSnippets, + /* TODO: recentlyVisitedRanges also contain contents from other windows like terminal or output + if they are visible. We should handle them separately so that we can control their priority + and whether they should be included or not. */ + }, + { + key: "recentlyEditedRanges", + enabledOrPriority: helper.options.experimental_includeRecentlyEditedRanges, + defaultPriority: 3, + snippets: payload.recentlyEditedRangeSnippets, + }, + { + key: "diff", + enabledOrPriority: helper.options.experimental_includeDiff, + defaultPriority: 4, + snippets: payload.diffSnippets, + // TODO: diff is commonly too large, thus anything lower in priority is not included. + }, + { + key: "base", + enabledOrPriority: true, + defaultPriority: 99, // make sure it's the last one to be processed, but still possible to override + snippets: shuffleArray(filterSnippetsAlreadyInCaretWindow( + [...payload.rootPathSnippets, ...payload.importDefinitionSnippets], + helper.prunedCaretWindow, + )), + // TODO: Add this too to experimental config, maybe move upper in the order, since it's almost + // always not inlucded due to diff being commonly large + }, + ]; + + // Create a readable order of enabled snippets + const snippetOrder = snippetConfigs + .filter(({ enabledOrPriority }) => enabledOrPriority) + .map(({ key, enabledOrPriority, defaultPriority }) => ({ + key, + priority: typeof enabledOrPriority === 'number' ? enabledOrPriority : defaultPriority, + })) + .sort((a, b) => a.priority - b.priority); + + // Log the snippet order for debugging - uncomment if needed + /* console.log( + 'Snippet processing order:', + snippetOrder + .map(({ key, priority }) => `${key} (priority: ${priority})`).join("\n") + ); */ + + // Convert configs to prioritized snippets + let prioritizedSnippets = snippetOrder + .flatMap(({ key, priority }) => + snippets[key].map(snippet => ({ snippet, priority })) + ) + .sort((a, b) => a.priority - b.priority) + .map(({ snippet }) => snippet); + + // Exclude Continue's own output as it makes it super-hard for users to test the autocomplete feature + // while looking at the prompts in the Continue's output + prioritizedSnippets = prioritizedSnippets.filter((snippet) => + !(snippet as AutocompleteCodeSnippet).filepath?.startsWith("output:extension-output-Continue.continue")); const finalSnippets = []; - let remainingTokenCount = getRemainingTokenCount(helper); - while (remainingTokenCount > 0 && snippets.length > 0) { - const snippet = snippets.shift(); + while (remainingTokenCount > 0 && prioritizedSnippets.length > 0) { + const snippet = prioritizedSnippets.shift(); if (!snippet || !isValidSnippet(snippet)) { continue; } diff --git a/core/autocomplete/util/AutocompleteLoggingService.ts b/core/autocomplete/util/AutocompleteLoggingService.ts index 7fd49cfaf..96bf4b4bc 100644 --- a/core/autocomplete/util/AutocompleteLoggingService.ts +++ b/core/autocomplete/util/AutocompleteLoggingService.ts @@ -113,6 +113,7 @@ export class AutocompleteLoggingService { multilineCompletions: restOfOutcome.multilineCompletions, time: restOfOutcome.time, useRecentlyEdited: restOfOutcome.useRecentlyEdited, + numLines: restOfOutcome.numLines, }, true, ); diff --git a/core/config/ConfigHandler.test.ts b/core/config/ConfigHandler.test.ts index deb1deded..eadaa137f 100644 --- a/core/config/ConfigHandler.test.ts +++ b/core/config/ConfigHandler.test.ts @@ -10,11 +10,11 @@ import { defaultConfig } from "./default"; describe.skip("Test the ConfigHandler and E2E config loading", () => { test("should show only local profile", () => { const profiles = testConfigHandler.listProfiles(); - expect(profiles.length).toBe(1); - expect(profiles[0].id).toBe("local"); + expect(profiles?.length).toBe(1); + expect(profiles?.[0].id).toBe("local"); const currentProfile = testConfigHandler.currentProfile; - expect(currentProfile.profileDescription.id).toBe("local"); + expect(currentProfile?.profileDescription.id).toBe("local"); }); test("should load the default config successfully", async () => { diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index e1c2a17e4..e4360b761 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -27,7 +27,7 @@ import { localPathToUri } from "../util/pathToUri.js"; import { LOCAL_ONBOARDING_CHAT_MODEL, - ONBOARDING_LOCAL_MODEL_TITLE, + LOCAL_ONBOARDING_PROVIDER_TITLE, } from "./onboarding.js"; import ControlPlaneProfileLoader from "./profile/ControlPlaneProfileLoader.js"; import LocalProfileLoader from "./profile/LocalProfileLoader.js"; @@ -47,55 +47,83 @@ type ConfigUpdateFunction = (payload: ConfigResult) => void; export class ConfigHandler { private readonly globalContext = new GlobalContext(); private additionalContextProviders: IContextProvider[] = []; - private profiles: ProfileLifecycleManager[]; - private selectedProfileId: string; + private profiles: ProfileLifecycleManager[] | null = null; // null until profiles are loaded + private selectedProfileId: string | null = null; + private localProfileManager: ProfileLifecycleManager; + private controlPlaneClient: ControlPlaneClient; + + initializedPromise: Promise; constructor( private readonly ide: IDE, private ideSettingsPromise: Promise, private readonly writeLog: (text: string) => Promise, - private controlPlaneClient: ControlPlaneClient, + sessionInfoPromise: Promise, ) { this.ide = ide; this.ideSettingsPromise = ideSettingsPromise; this.writeLog = writeLog; + this.controlPlaneClient = new ControlPlaneClient( + sessionInfoPromise, + ideSettingsPromise, + ); // Set local profile as default const localProfileLoader = new LocalProfileLoader( ide, ideSettingsPromise, - controlPlaneClient, + this.controlPlaneClient, writeLog, ); - this.profiles = [new ProfileLifecycleManager(localProfileLoader, this.ide)]; - this.selectedProfileId = localProfileLoader.description.id; + this.localProfileManager = new ProfileLifecycleManager( + localProfileLoader, + this.ide, + ); - // Always load local profile immediately in case control plane doesn't load + // Profiles are loaded asynchronously + this.initializedPromise = new Promise((resolve, reject) => { + this.init() + .then(() => { + resolve(); + }) + .catch((e) => { + reject(e); + }); + }); + } + + private async init() { try { - void this.loadConfig(); + await this.fetchControlPlaneProfiles(); + } catch (e) { + // If this fails, make sure at least local profile is loaded + console.error("Failed to fetch control plane profiles: ", e); + await this.updateAvailableProfiles([this.localProfileManager]); + } + try { + const configResult = await this.loadConfig(); + this.notifyConfigListeners(configResult); } catch (e) { console.error("Failed to load config: ", e); } - - // Load control plane profiles - void this.fetchControlPlaneProfiles(); - } - - // This will be the local profile - private get fallbackProfile() { - return this.profiles[0]; } get currentProfile() { + if (!this.selectedProfileId) { + return null; + } + // IMPORTANT + // We must fall back to null, not the first or local profiles + // Because GUI must be the source of truth for selected profile return ( - this.profiles.find( + this.profiles?.find( (p) => p.profileDescription.id === this.selectedProfileId, - ) ?? this.fallbackProfile + ) ?? null ); } get inactiveProfiles() { - return this.profiles.filter( + return (this.profiles ?? []).filter( (p) => p.profileDescription.id !== this.selectedProfileId, ); } @@ -112,74 +140,87 @@ export class ConfigHandler { } } else { const env = await getControlPlaneEnv(this.ide.getIdeSettings()); - await this.ide.openUrl(`${env.APP_URL}platform/${openProfileId}`); + await this.ide.openUrl(`${env.APP_URL}${openProfileId}`); } } - private async loadPlatformProfiles() { + async listOrganizations() { + return await this.controlPlaneClient.listOrganizations(); + } + + async loadAssistantsForSelectedOrg() { // Get the profiles and create their lifecycle managers - this.controlPlaneClient - .listAssistants() - .then(async (assistants) => { - const hubProfiles = await Promise.all( - assistants.map(async (assistant) => { - let renderedConfig: AssistantUnrolled | undefined = undefined; - if (assistant.configResult.config) { - renderedConfig = await clientRenderHelper( - YAML.stringify(assistant.configResult.config), - this.ide, - this.controlPlaneClient, - ); - } + const userId = await this.controlPlaneClient.userId; + const selectedOrgId = await this.getSelectedOrgId(); - const profileLoader = new PlatformProfileLoader( - { ...assistant.configResult, config: renderedConfig }, - assistant.ownerSlug, - assistant.packageSlug, - assistant.iconUrl, - assistant.configResult.config?.version ?? "latest", - this.controlPlaneClient, + let profiles: ProfileLifecycleManager[] | null = null; + if (!userId) { + // Not logged in + profiles = [this.localProfileManager]; + } else { + // Logged in + const assistants = + await this.controlPlaneClient.listAssistants(selectedOrgId); + const hubProfiles = await Promise.all( + assistants.map(async (assistant) => { + let renderedConfig: AssistantUnrolled | undefined = undefined; + if (assistant.configResult.config) { + renderedConfig = await clientRenderHelper( + { + ownerSlug: assistant.ownerSlug, + packageSlug: assistant.packageSlug, + }, + YAML.stringify(assistant.configResult.config), this.ide, - this.ideSettingsPromise, - this.writeLog, - this.reloadConfig.bind(this), + this.controlPlaneClient, ); + } - return new ProfileLifecycleManager(profileLoader, this.ide); - }), - ); - - this.profiles = [ - ...this.profiles.filter( - (profile) => profile.profileDescription.id === "local", - ), - ...hubProfiles, - ]; - - this.notifyProfileListeners( - this.profiles.map((profile) => profile.profileDescription), - ); - - // Check the last selected workspace, and reload if it isn't local - const workspaceId = await this.getWorkspaceId(); - const lastSelectedWorkspaceIds = - this.globalContext.get("lastSelectedProfileForWorkspace") ?? {}; - const selectedWorkspaceId = lastSelectedWorkspaceIds[workspaceId]; - if (selectedWorkspaceId) { - this.selectedProfileId = selectedWorkspaceId; - await this.loadConfig(); - } else { - // Otherwise we stick with local profile, and record choice - lastSelectedWorkspaceIds[workspaceId] = this.selectedProfileId; - this.globalContext.update( - "lastSelectedProfileForWorkspace", - lastSelectedWorkspaceIds, + const profileLoader = new PlatformProfileLoader( + { ...assistant.configResult, config: renderedConfig }, + assistant.ownerSlug, + assistant.packageSlug, + assistant.iconUrl, + assistant.configResult.config?.version ?? "latest", + this.controlPlaneClient, + this.ide, + this.ideSettingsPromise, + this.writeLog, + this.reloadConfig.bind(this), ); - } - }) - .catch((e) => { - console.error("Failed to list assistants: ", e); - }); + + return new ProfileLifecycleManager(profileLoader, this.ide); + }), + ); + + if (selectedOrgId === null) { + // Personal + profiles = [...hubProfiles, this.localProfileManager]; + } else { + // Organization + profiles = hubProfiles; + } + } + + await this.updateAvailableProfiles(profiles); + } + + private async updateAvailableProfiles(profiles: ProfileLifecycleManager[]) { + this.profiles = profiles; + + // If the last selected profile is in the list choose that + // Otherwise, choose the first profile + const previouslySelectedProfileId = + await this.getPersistedSelectedProfileId(); + const selectedProfileId = + previouslySelectedProfileId ?? profiles[0].profileDescription.id ?? null; + + // Notify listeners + const profileDescriptions = profiles.map( + (profile) => profile.profileDescription, + ); + this.notifyProfileListeners(profileDescriptions, selectedProfileId); + await this.setSelectedProfile(selectedProfileId); } private platformProfilesRefreshInterval: NodeJS.Timeout | undefined; @@ -204,78 +245,81 @@ export class ConfigHandler { return false; } - private async fetchControlPlaneProfiles() { - if (await useHub(this.ideSettingsPromise)) { - clearInterval(this.platformProfilesRefreshInterval); - await this.loadPlatformProfiles(); + private async reloadHubAssistants() { + const selectedOrgId = await this.getSelectedOrgId(); + const newFullSlugsList = + await this.controlPlaneClient.listAssistantFullSlugs(selectedOrgId); - // Every 5 seconds we ask the platform whether there are any assistant updates in the last 5 seconds - // If so, we do the full (more expensive) reload - this.platformProfilesRefreshInterval = setInterval(async () => { - const newFullSlugsList = - await this.controlPlaneClient.listAssistantFullSlugs(); - - if (newFullSlugsList) { - const shouldReload = this.fullSlugsListsDiffer( - newFullSlugsList, - this.lastFullSlugsList, - ); - if (shouldReload) { - await this.loadPlatformProfiles(); - } - this.lastFullSlugsList = newFullSlugsList; - } - }, PlatformProfileLoader.RELOAD_INTERVAL); - } else { - this.controlPlaneClient - .listWorkspaces() - .then(async (workspaces) => { - this.profiles = this.profiles.filter( - (profile) => profile.profileDescription.id === "local", - ); - workspaces.forEach((workspace) => { - const profileLoader = new ControlPlaneProfileLoader( - workspace.id, - workspace.name, - this.controlPlaneClient, - this.ide, - this.ideSettingsPromise, - this.writeLog, - this.reloadConfig.bind(this), - ); - this.profiles.push( - new ProfileLifecycleManager(profileLoader, this.ide), - ); - }); - - this.notifyProfileListeners( - this.profiles.map((profile) => profile.profileDescription), - ); - - // Check the last selected workspace, and reload if it isn't local - const workspaceId = await this.getWorkspaceId(); - const lastSelectedWorkspaceIds = - this.globalContext.get("lastSelectedProfileForWorkspace") ?? {}; - const selectedWorkspaceId = lastSelectedWorkspaceIds[workspaceId]; - if (selectedWorkspaceId) { - this.selectedProfileId = selectedWorkspaceId; - await this.loadConfig(); - } else { - // Otherwise we stick with local profile, and record choice - lastSelectedWorkspaceIds[workspaceId] = this.selectedProfileId; - this.globalContext.update( - "lastSelectedProfileForWorkspace", - lastSelectedWorkspaceIds, - ); - } - }) - .catch((e) => { - console.error(e); - }); + if (newFullSlugsList) { + const shouldReload = this.fullSlugsListsDiffer( + newFullSlugsList, + this.lastFullSlugsList, + ); + if (shouldReload) { + await this.loadAssistantsForSelectedOrg(); + } + this.lastFullSlugsList = newFullSlugsList; } } - async setSelectedProfile(profileId: string) { + private async fetchControlPlaneProfiles() { + if (await useHub(this.ideSettingsPromise)) { + clearInterval(this.platformProfilesRefreshInterval); + await this.loadAssistantsForSelectedOrg(); + + // Every 5 seconds we ask the platform whether there are any assistant updates in the last 5 seconds + // If so, we do the full (more expensive) reload + this.platformProfilesRefreshInterval = setInterval( + this.reloadHubAssistants.bind(this), + PlatformProfileLoader.RELOAD_INTERVAL, + ); + } else { + try { + const workspaces = await this.controlPlaneClient.listWorkspaces(); + const profiles = [this.localProfileManager]; + workspaces.forEach((workspace) => { + const profileLoader = new ControlPlaneProfileLoader( + workspace.id, + workspace.name, + this.controlPlaneClient, + this.ide, + this.ideSettingsPromise, + this.writeLog, + this.reloadConfig.bind(this), + ); + + profiles.push(new ProfileLifecycleManager(profileLoader, this.ide)); + }); + + await this.updateAvailableProfiles(profiles); + } catch (e: any) { + console.error("Failed to load profiles: ", e); + await this.updateAvailableProfiles([this.localProfileManager]); + } + } + } + + async getPersistedSelectedProfileId(): Promise { + const workspaceId = await this.getWorkspaceId(); + const lastSelectedIds = + this.globalContext.get("lastSelectedProfileForWorkspace") ?? {}; + return lastSelectedIds[workspaceId] ?? null; + } + + async getSelectedOrgId(): Promise { + const selectedOrgs = + this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {}; + return selectedOrgs[await this.getWorkspaceId()] ?? null; + } + + async setSelectedOrgId(orgId: string | null) { + const selectedOrgs = + this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {}; + selectedOrgs[await this.getWorkspaceId()] = orgId; + this.globalContext.update("lastSelectedOrgIdForWorkspace", selectedOrgs); + } + + async setSelectedProfile(profileId: string | null) { this.selectedProfileId = profileId; const result = await this.loadConfig(); this.notifyConfigListeners(result); @@ -312,16 +356,25 @@ export class ConfigHandler { }); } - private profilesListeners: ((profiles: ProfileDescription[]) => void)[] = []; + private profilesListeners: (( + profiles: ProfileDescription[], + selectedProfileId: string | null, + ) => void)[] = []; onDidChangeAvailableProfiles( - listener: (profiles: ProfileDescription[]) => void, + listener: ( + profiles: ProfileDescription[], + selectedProfileId: string | null, + ) => void, ) { this.profilesListeners.push(listener); } - private notifyProfileListeners(profiles: ProfileDescription[]) { + private notifyProfileListeners( + profiles: ProfileDescription[], + selectedProfileId: string | null, + ) { for (const listener of this.profilesListeners) { - listener(profiles); + listener(profiles, selectedProfileId); } } @@ -338,33 +391,54 @@ export class ConfigHandler { this.updateListeners.push(listener); } - async reloadConfig(additionalContextProviders: IContextProvider[] = []) { - // TODO: this isn't right, there are two different senses in which you want to "reload" + // TODO: this isn't right, there are two different senses in which you want to "reload" + async reloadConfig() { + if (!this.currentProfile) { + return { + config: undefined, + errors: [], + configLoadInterrupted: true, + }; + } const { config, errors, configLoadInterrupted } = - await this.currentProfile.reloadConfig(additionalContextProviders); + await this.currentProfile.reloadConfig(this.additionalContextProviders); if (config) { this.inactiveProfiles.forEach((profile) => profile.clearConfig()); } this.notifyConfigListeners({ config, errors, configLoadInterrupted }); - return { config, errors }; + return { config, errors, configLoadInterrupted }; } - getSerializedConfig(): Promise< + async getSerializedConfig(): Promise< ConfigResult > { - return this.currentProfile.getSerializedConfig( + if (!this.currentProfile) { + return { + config: undefined, + errors: [], + configLoadInterrupted: true, + }; + } + return await this.currentProfile.getSerializedConfig( this.additionalContextProviders, ); } - listProfiles(): ProfileDescription[] { - return this.profiles.map((p) => p.profileDescription); + listProfiles(): ProfileDescription[] | null { + return this.profiles?.map((p) => p.profileDescription) ?? null; } async loadConfig(): Promise> { + if (!this.currentProfile) { + return { + config: undefined, + errors: [], + configLoadInterrupted: true, + }; + } return await this.currentProfile.loadConfig( this.additionalContextProviders, ); @@ -374,7 +448,7 @@ export class ConfigHandler { const { config } = await this.loadConfig(); const model = config?.models.find((m) => m.title === title); if (!model) { - if (title === ONBOARDING_LOCAL_MODEL_TITLE) { + if (title === LOCAL_ONBOARDING_PROVIDER_TITLE) { // Special case, make calls to Ollama before we have it in the config const ollama = new Ollama({ model: LOCAL_ONBOARDING_CHAT_MODEL, @@ -392,6 +466,6 @@ export class ConfigHandler { registerCustomContextProvider(contextProvider: IContextProvider) { this.additionalContextProviders.push(contextProvider); - void this.reloadConfig(this.additionalContextProviders); + void this.reloadConfig(); } } diff --git a/core/config/ProfileLifecycleManager.ts b/core/config/ProfileLifecycleManager.ts index fc18f34b0..deaf5f40e 100644 --- a/core/config/ProfileLifecycleManager.ts +++ b/core/config/ProfileLifecycleManager.ts @@ -27,6 +27,7 @@ export interface OrganizationDescription { id: string; iconUrl: string; name: string; + slug: string | undefined; // TODO: This doesn't need to be undefined, just doing while transitioning the backend } export class ProfileLifecycleManager { @@ -50,7 +51,9 @@ export class ProfileLifecycleManager { } // Clear saved config and reload - async reloadConfig(additionalContextProviders: IContextProvider[] = []): Promise> { + async reloadConfig( + additionalContextProviders: IContextProvider[] = [], + ): Promise> { this.savedConfigResult = undefined; this.savedBrowserConfigResult = undefined; this.pendingConfigPromise = undefined; @@ -73,7 +76,21 @@ export class ProfileLifecycleManager { // Set pending config promise this.pendingConfigPromise = new Promise(async (resolve, reject) => { - const result = await this.profileLoader.doLoadConfig(); + let result: ConfigResult; + try { + result = await this.profileLoader.doLoadConfig(); + } catch (e: any) { + result = { + errors: [ + { + fatal: true, + message: e.message, + }, + ], + config: undefined, + configLoadInterrupted: true, + }; + } if (result.config) { // Add registered context providers diff --git a/core/config/default.ts b/core/config/default.ts index 8662be678..23e709603 100644 --- a/core/config/default.ts +++ b/core/config/default.ts @@ -5,20 +5,6 @@ import { SlashCommandDescription, } from "../"; -export const DEFAULT_CHAT_MODEL_CONFIG: ModelDescription = { - model: "claude-3-5-sonnet-latest", - provider: "anthropic", - apiKey: "", - title: "Claude 3.5 Sonnet", -}; - -export const DEFAULT_AUTOCOMPLETE_MODEL_CONFIG: ModelDescription = { - title: "Codestral", - provider: "mistral", - model: "codestral-latest", - apiKey: "", -}; - export const FREE_TRIAL_MODELS: ModelDescription[] = [ { title: "Claude 3.5 Sonnet (Free Trial)", @@ -93,15 +79,13 @@ export const defaultSlashCommandsJetBrains = [ ]; export const defaultConfig: SerializedContinueConfig = { - models: [DEFAULT_CHAT_MODEL_CONFIG], - tabAutocompleteModel: DEFAULT_AUTOCOMPLETE_MODEL_CONFIG, + models: [], contextProviders: defaultContextProvidersVsCode, slashCommands: defaultSlashCommandsVscode, }; export const defaultConfigJetBrains: SerializedContinueConfig = { - models: [DEFAULT_CHAT_MODEL_CONFIG], - tabAutocompleteModel: DEFAULT_AUTOCOMPLETE_MODEL_CONFIG, + models: [], contextProviders: defaultContextProvidersJetBrains, slashCommands: defaultSlashCommandsJetBrains, }; diff --git a/core/config/load.ts b/core/config/load.ts index da95ec5a8..c8499dc8b 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -63,6 +63,8 @@ import { } from "../util/paths"; import { ConfigResult, ConfigValidationError } from "@continuedev/config-yaml"; +import { useHub } from "../control-plane/env"; +import { localPathToUri } from "../util/pathToUri"; import { defaultContextProvidersJetBrains, defaultContextProvidersVsCode, @@ -70,8 +72,6 @@ import { defaultSlashCommandsVscode, } from "./default"; import { getSystemPromptDotFile } from "./getSystemPromptDotFile"; -import { useHub } from "../control-plane/env"; -import { localPathToUri } from "../util/pathToUri"; import { modifyContinueConfigWithSharedConfig } from "./sharedConfig"; import { validateConfig } from "./validation.js"; @@ -326,6 +326,7 @@ async function intermediateToFinalConfig( ...model.requestOptions, ...config.requestOptions, }; + model.roles = model.roles ?? ["chat"]; // Default to chat role if not specified } if (allowFreeTrial) { @@ -517,6 +518,8 @@ async function intermediateToFinalConfig( continueConfig, mcpId, abortController.signal, + "MCP Server", + server.faviconUrl, ); if (mcpError) { errors.push(mcpError); @@ -557,6 +560,7 @@ async function finalToBrowserConfig( requestOptions: m.requestOptions, promptTemplates: m.promptTemplates as any, capabilities: m.capabilities, + roles: m.roles, })), systemMessage: final.systemMessage, completionOptions: final.completionOptions, diff --git a/core/config/migrateSharedConfig.ts b/core/config/migrateSharedConfig.ts index b68e3adec..189bb21ed 100644 --- a/core/config/migrateSharedConfig.ts +++ b/core/config/migrateSharedConfig.ts @@ -1,13 +1,9 @@ -import * as fs from "fs"; - -import * as JSONC from "comment-json"; - -import { IDE, SerializedContinueConfig } from ".."; -import { SharedConfigSchema } from "./sharedConfig"; +import { IDE } from ".."; +import { deduplicateArray } from "../util"; import { GlobalContext } from "../util/GlobalContext"; import { editConfigJson } from "../util/paths"; import { resolveSerializedConfig } from "./load"; -import { deduplicateArray } from "../util"; +import { SharedConfigSchema } from "./sharedConfig"; /* This migration function eliminates deprecated values from the json file @@ -201,10 +197,10 @@ export function migrateJsonSharedConfig(filepath: string, ide: IDE): void { if (effected) { new GlobalContext().updateSharedConfig(shareConfigUpdates); editConfigJson(() => config); - void ide.showToast( - "warning", - "Migrated deprecated Continue JSON settings. Edit in the Settings Page", - ); + // void ide.showToast( + // "warning", + // "Migrated deprecated Continue JSON settings. Edit in the Settings Page", + // ); } } catch (e) { throw new Error(`Migration: Failed to parse config.json: ${e}`); diff --git a/core/config/onboarding.ts b/core/config/onboarding.ts index 426a7a4ba..8babfffde 100644 --- a/core/config/onboarding.ts +++ b/core/config/onboarding.ts @@ -3,10 +3,12 @@ import { SerializedContinueConfig } from "../"; import { FREE_TRIAL_MODELS } from "./default"; export const TRIAL_FIM_MODEL = "codestral-latest"; -export const ONBOARDING_LOCAL_MODEL_TITLE = "Ollama"; +export const LOCAL_ONBOARDING_PROVIDER_TITLE = "Ollama"; export const LOCAL_ONBOARDING_FIM_MODEL = "qwen2.5-coder:1.5b-base"; +export const LOCAL_ONBOARDING_FIM_TITLE = "Qwen2.5-Coder 1.5B"; export const LOCAL_ONBOARDING_CHAT_MODEL = "llama3.1:8b"; export const LOCAL_ONBOARDING_CHAT_TITLE = "Llama 3.1 8B"; +export const LOCAL_ONBOARDING_EMBEDDINGS_MODEL = "nomic-embed-text:latest"; /** * We set the "best" chat + autocopmlete models by default @@ -35,13 +37,13 @@ export function setupLocalConfig( ...config.models.filter((model) => model.provider !== "free-trial"), ], tabAutocompleteModel: { - title: "Qwen2.5-Coder 1.5B", + title: LOCAL_ONBOARDING_FIM_TITLE, provider: "ollama", model: LOCAL_ONBOARDING_FIM_MODEL, }, embeddingsProvider: { provider: "ollama", - model: "nomic-embed-text", + model: LOCAL_ONBOARDING_EMBEDDINGS_MODEL, }, }; } @@ -68,24 +70,3 @@ export function setupQuickstartConfig( }, }; } - -export function setupLocalConfigAfterFreeTrial( - config: SerializedContinueConfig, -): SerializedContinueConfig { - return { - ...config, - models: [ - { - title: LOCAL_ONBOARDING_CHAT_TITLE, - provider: "ollama", - model: LOCAL_ONBOARDING_CHAT_MODEL, - }, - { - title: ONBOARDING_LOCAL_MODEL_TITLE, - provider: "ollama", - model: "AUTODETECT", - }, - ...config.models.filter((model) => model.provider !== "free-trial"), - ], - }; -} diff --git a/core/config/profile/PlatformProfileLoader.ts b/core/config/profile/PlatformProfileLoader.ts index 7650cb0e3..04f1d3acf 100644 --- a/core/config/profile/PlatformProfileLoader.ts +++ b/core/config/profile/PlatformProfileLoader.ts @@ -1,5 +1,4 @@ -import { ConfigResult } from "@continuedev/config-yaml"; -import { AssistantUnrolled } from "@continuedev/config-yaml/dist/schemas/index.js"; +import { ConfigResult, AssistantUnrolled } from "@continuedev/config-yaml"; import { ControlPlaneClient } from "../../control-plane/client.js"; import { ContinueConfig, IDE, IdeSettings } from "../../index.js"; diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 86f975965..af8c59c97 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -21,9 +21,9 @@ import { getConfigJsonPath, getConfigYamlPath } from "../../util/paths"; import { Telemetry } from "../../util/posthog"; import { TTS } from "../../util/tts"; import { loadContinueConfigFromJson } from "../load"; +import { migrateJsonSharedConfig } from "../migrateSharedConfig"; import { loadContinueConfigFromYaml } from "../yaml/loadYaml"; import { PlatformConfigMetadata } from "./PlatformProfileLoader"; -import { migrateJsonSharedConfig } from "../migrateSharedConfig"; export default async function doLoadConfig( ide: IDE, diff --git a/core/config/types.ts b/core/config/types.ts index 384da0c8f..2a68c4c35 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -956,7 +956,7 @@ declare global { fixGrammar?: string; } - interface ModelRoles { + interface ExperimentalModelRoles { inlineEdit?: string; applyCodeBlock?: string; repoMapFileSelection?: string; @@ -1024,7 +1024,7 @@ declare global { interface ExperimentalConfig { contextMenuPrompts?: ContextMenuConfig; - modelRoles?: ModelRoles; + modelRoles?: ExperimentalModelRoles; defaultContext?: DefaultContextProvider[]; promptPath?: string; diff --git a/core/config/util.ts b/core/config/util.ts index 6d28dcbcb..f55848586 100644 --- a/core/config/util.ts +++ b/core/config/util.ts @@ -7,11 +7,13 @@ import { IDE, ILLM, ModelDescription, - ModelRoles, + ExperimentalModelRoles, } from "../"; import { GlobalContext } from "../util/GlobalContext"; import { editConfigJson } from "../util/paths"; +import { ConfigHandler } from "./ConfigHandler"; + function stringify(obj: any, indentation?: number): string { return JSON.stringify( obj, @@ -22,19 +24,30 @@ function stringify(obj: any, indentation?: number): string { ); } -export function addContextProvider(provider: ContextProviderWithParams) { +export function addContextProvider(provider: ContextProviderWithParams, configHandler?: ConfigHandler) { + let isAdded = false; editConfigJson((config) => { + if (!config.contextProviders) { - config.contextProviders = [provider]; - } else { + config.contextProviders = []; + } + if (!config.contextProviders.some((p) => p.name === provider.name)) { config.contextProviders.push(provider); + isAdded = true; } return config; }); + + if (isAdded && configHandler) { + void configHandler.reloadConfig(); + } } -export function addModel(model: ModelDescription, role?: keyof ModelRoles) { +export function addModel( + model: ModelDescription, + role?: keyof ExperimentalModelRoles, +) { editConfigJson((config) => { if (config.models?.some((m: any) => stringify(m) === stringify(model))) { return config; @@ -85,7 +98,7 @@ export function deleteModel(title: string) { }); } -export function getModelByRole( +export function getModelByRole( config: ContinueConfig, role: T, ): ILLM | undefined { diff --git a/core/config/yaml/clientRender.ts b/core/config/yaml/clientRender.ts index 8cb727456..14f7e718f 100644 --- a/core/config/yaml/clientRender.ts +++ b/core/config/yaml/clientRender.ts @@ -1,5 +1,6 @@ import { clientRender, + PackageSlug, PlatformClient, SecretStore, } from "@continuedev/config-yaml"; @@ -8,6 +9,7 @@ import { IDE } from "../.."; import { ControlPlaneClient } from "../../control-plane/client"; export async function clientRenderHelper( + packageSlug: PackageSlug, unrolledAssistant: string, ide: IDE, controlPlaneClient: ControlPlaneClient, @@ -33,6 +35,7 @@ export async function clientRenderHelper( const userId = await controlPlaneClient.userId; return await clientRender( + packageSlug, unrolledAssistant, ideSecretStore, userId ? platformClient : undefined, diff --git a/core/config/yaml/convertFromJson.ts b/core/config/yaml/convertFromJson.ts index 576e196c8..a989d2631 100644 --- a/core/config/yaml/convertFromJson.ts +++ b/core/config/yaml/convertFromJson.ts @@ -1,5 +1,4 @@ -import { ModelConfig } from "@continuedev/config-yaml"; -import { AssistantUnrolled } from "@continuedev/config-yaml/dist/schemas"; +import { ModelConfig, AssistantUnrolled } from "@continuedev/config-yaml"; import { SerializedContinueConfig } from "../.."; diff --git a/core/config/yaml/default.ts b/core/config/yaml/default.ts index 0bc872f88..c9ca4dc8e 100644 --- a/core/config/yaml/default.ts +++ b/core/config/yaml/default.ts @@ -1,4 +1,4 @@ -import { AssistantUnrolled } from "@continuedev/config-yaml/dist/schemas"; +import { AssistantUnrolled } from "@continuedev/config-yaml"; // TODO export const defaultConfigYaml: AssistantUnrolled = { diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index 9503c0865..37abaf83e 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -3,12 +3,14 @@ import fs from "node:fs"; import { AssistantUnrolled, ConfigResult, + ConfigValidationError, + ModelRole, + parseAssistantUnrolled, validateConfigYaml, } from "@continuedev/config-yaml"; import { fetchwithRequestOptions } from "@continuedev/fetch"; import { - BrowserSerializedContinueConfig, ContinueConfig, IContextProvider, IDE, @@ -16,9 +18,11 @@ import { IdeType, SlashCommand, } from "../.."; +import { slashFromCustomCommand } from "../../commands"; import { AllRerankers } from "../../context/allRerankers"; import { MCPManagerSingleton } from "../../context/mcp"; import CodebaseContextProvider from "../../context/providers/CodebaseContextProvider"; +import DocsContextProvider from "../../context/providers/DocsContextProvider"; import FileContextProvider from "../../context/providers/FileContextProvider"; import { contextProviderClassFromName } from "../../context/providers/index"; import PromptFilesContextProvider from "../../context/providers/PromptFilesContextProvider"; @@ -28,17 +32,15 @@ import FreeTrial from "../../llm/llms/FreeTrial"; import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider"; import { slashCommandFromPromptFileV1 } from "../../promptFiles/v1/slashCommandFromPromptFile"; import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles"; +import { allTools } from "../../tools"; +import { GlobalContext } from "../../util/GlobalContext"; import { getConfigYamlPath } from "../../util/paths"; import { getSystemPromptDotFile } from "../getSystemPromptDotFile"; import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader"; - -import { slashFromCustomCommand } from "../../commands"; -import { allTools } from "../../tools"; -import { clientRenderHelper } from "./clientRender"; -import { llmsFromModelConfig } from "./models"; -import { GlobalContext } from "../../util/GlobalContext"; import { modifyContinueConfigWithSharedConfig } from "../sharedConfig"; +import { llmsFromModelConfig } from "./models"; + async function loadConfigYaml( workspaceConfigs: string[], rawYaml: string, @@ -46,9 +48,14 @@ async function loadConfigYaml( ide: IDE, controlPlaneClient: ControlPlaneClient, ): Promise> { + const ideSettings = await ide.getIdeSettings(); let config = overrideConfigYaml ?? - (await clientRenderHelper(rawYaml, ide, controlPlaneClient)); + // (ideSettings.continueTestEnvironment === "production" + // ? await clientRenderHelper(rawYaml, ide, controlPlaneClient) + // : + parseAssistantUnrolled(rawYaml); + // ); const errors = validateConfigYaml(config); if (errors?.some((error) => error.fatal)) { @@ -96,7 +103,8 @@ async function configYamlToContinueConfig( workOsAccessToken: string | undefined, platformConfigMetadata: PlatformConfigMetadata | undefined, allowFreeTrial: boolean = true, -): Promise { +): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> { + const errors: ConfigValidationError[] = []; const continueConfig: ContinueConfig = { slashCommands: [ ...(await slashCommandsFromV1PromptFiles(ide)), @@ -127,12 +135,10 @@ async function configYamlToContinueConfig( }; // Models + const modelsArrayRoles: ModelRole[] = ["chat", "summarize", "apply", "edit"]; for (const model of config.models ?? []) { - if ( - ["chat", "summarize", "apply", "edit"].some((role: any) => - model.roles?.includes(role), - ) - ) { + model.roles = model.roles ?? ["chat"]; // Default to chat role if not specified + if (modelsArrayRoles.some((role) => model.roles?.includes(role))) { // Main model array const llms = await llmsFromModelConfig( model, @@ -159,6 +165,24 @@ async function configYamlToContinueConfig( ); continueConfig.tabAutocompleteModels?.push(...llms); } + + if ( + model.roles?.includes("apply") && + !continueConfig.experimental?.modelRoles?.applyCodeBlock + ) { + continueConfig.experimental ??= {}; + continueConfig.experimental!.modelRoles ??= {}; + continueConfig.experimental!.modelRoles!.applyCodeBlock = model.name; + } + + if ( + model.roles?.includes("edit") && + !continueConfig.experimental?.modelRoles?.inlineEdit + ) { + continueConfig.experimental ??= {}; + continueConfig.experimental!.modelRoles ??= {}; + continueConfig.experimental!.modelRoles!.inlineEdit = model.name; + } } if (allowFreeTrial) { @@ -210,7 +234,17 @@ async function configYamlToContinueConfig( .filter((p) => !!p) ?? []) as IContextProvider[]; continueConfig.contextProviders.push(...DEFAULT_CONTEXT_PROVIDERS); + if ( + continueConfig.docs?.length && + !continueConfig.contextProviders?.some( + (cp) => cp.description.title === "docs", + ) + ) { + continueConfig.contextProviders.push(new DocsContextProvider({})); + } + // Embeddings Provider + // IMPORTANT this currently will grab the first model found with an embed role const embedConfig = config.models?.find((model) => model.roles?.includes("embed"), ); @@ -235,6 +269,7 @@ async function configYamlToContinueConfig( } // Reranker + // IMPORTANT this currently will grab the first model found with a rerank role const rerankConfig = config.models?.find((model) => model.roles?.includes("rerank"), ); @@ -255,40 +290,51 @@ async function configYamlToContinueConfig( // Apply MCP if specified const mcpManager = MCPManagerSingleton.getInstance(); - config.mcpServers?.forEach(async (server) => { - const mcpId = server.name; - const mcpConnection = mcpManager.createConnection(mcpId, { - transport: { - type: "stdio", - args: [], - ...server, - }, - }); - if (!mcpConnection) { - return; - } - - const abortController = new AbortController(); - const mcpConnectionTimeout = setTimeout( - () => abortController.abort(), - 2000, - ); - - try { - await mcpConnection.modifyConfig( - continueConfig, - mcpId, - abortController.signal, - ); - } catch (e: any) { - if (e.name !== "AbortError") { - throw e; + await Promise.all( + config.mcpServers?.map(async (server) => { + const mcpId = server.name; + const mcpConnection = mcpManager.createConnection(mcpId, { + transport: { + type: "stdio", + args: [], + ...server, + }, + }); + if (!mcpConnection) { + return; } - } - clearTimeout(mcpConnectionTimeout); - }); - return continueConfig; + const abortController = new AbortController(); + const mcpConnectionTimeout = setTimeout( + () => abortController.abort(), + 5000, + ); + + try { + const mcpError = await mcpConnection.modifyConfig( + continueConfig, + mcpId, + abortController.signal, + server.name, + server.faviconUrl, + ); + if (mcpError) { + errors.push(mcpError); + } + } catch (e: any) { + errors.push({ + fatal: false, + message: `Failed to load MCP server: ${e.message}`, + }); + if (e.name !== "AbortError") { + throw e; + } + } + clearTimeout(mcpConnectionTimeout); + }) ?? [], + ); + + return { config: continueConfig, errors }; } export async function loadContinueConfigFromYaml( @@ -324,7 +370,7 @@ export async function loadContinueConfigFromYaml( }; } - const continueConfig = await configYamlToContinueConfig( + const { config: continueConfig, errors } = await configYamlToContinueConfig( configYamlResult.config, ide, ideSettings, @@ -353,9 +399,7 @@ export async function loadContinueConfigFromYaml( return { config: withShared, - errors: configYamlResult.errors, + errors: [...(configYamlResult.errors ?? []), ...errors], configLoadInterrupted: false, }; } - -export { type BrowserSerializedContinueConfig }; diff --git a/core/config/yaml/models.ts b/core/config/yaml/models.ts index 8fe34677f..e6d0ef00a 100644 --- a/core/config/yaml/models.ts +++ b/core/config/yaml/models.ts @@ -35,15 +35,6 @@ async function modelConfigToBaseLLM( return undefined; } - const usingContinueProxy = model.provider === "continue-proxy"; - const modelName = usingContinueProxy - ? getContinueProxyModelName( - platformConfigMetadata!.ownerSlug, - platformConfigMetadata!.packageSlug, - model, - ) - : model.model; - let options: LLMOptions = { ...model, completionOptions: { @@ -56,8 +47,8 @@ async function modelConfigToBaseLLM( writeLog, uniqueId, title: model.name, - model: modelName, systemMessage, + promptTemplates: model.promptTemplates, }; const llm = new cls(options); diff --git a/core/context/mcp/index.ts b/core/context/mcp/index.ts index 304c2a8c4..19de5434a 100644 --- a/core/context/mcp/index.ts +++ b/core/context/mcp/index.ts @@ -69,10 +69,14 @@ class MCPConnection { private constructTransport(options: MCPOptions): Transport { switch (options.transport.type) { case "stdio": + const env: Record = options.transport.env || {}; + if (process.env.PATH !== undefined) { + env.PATH = process.env.PATH; + } return new StdioClientTransport({ command: options.transport.command, args: options.transport.args, - env: options.transport.env, + env, }); case "websocket": return new WebSocketClientTransport(new URL(options.transport.url)); @@ -117,6 +121,8 @@ class MCPConnection { config: ContinueConfig, mcpId: string, signal: AbortSignal, + name: string, + faviconUrl: string | undefined, ): Promise { try { await Promise.race([ @@ -148,6 +154,7 @@ class MCPConnection { title: resource.name, description: resource.description, id: resource.uri, + icon: faviconUrl, })); if (!config.contextProviders) { @@ -157,6 +164,7 @@ class MCPConnection { config.contextProviders.push( new MCPContextProvider({ submenuItems, + mcpId, }), ); } @@ -165,19 +173,20 @@ class MCPConnection { if (capabilities?.tools) { const { tools } = await this.client.listTools({}, { signal }); const continueTools: Tool[] = tools.map((tool: any) => ({ - displayTitle: tool.name, + displayTitle: name + " " + tool.name, function: { description: tool.description, name: tool.name, parameters: tool.inputSchema, }, + faviconUrl, readonly: false, type: "function", - wouldLikeTo: `use the ${tool.name} tool`, + wouldLikeTo: `use the ${name} ${tool.name} tool`, uri: encodeMCPToolUri(mcpId, tool.name), })); - config.tools = [...config.tools, ...continueTools]; + config.tools = [...continueTools, ...config.tools]; } // Prompts <—> Slash commands diff --git a/core/context/providers/CodeContextProvider.ts b/core/context/providers/CodeContextProvider.ts index 837e4d05d..b746199b0 100644 --- a/core/context/providers/CodeContextProvider.ts +++ b/core/context/providers/CodeContextProvider.ts @@ -24,8 +24,12 @@ class CodeContextProvider extends BaseContextProvider { extras: ContextProviderExtras, ): Promise { // Assume the query is the id as returned by loadSubmenuItems + const workspaceDirs = await extras.ide.getWorkspaceDirs(); return [ - await CodeSnippetsCodebaseIndex.getForId(Number.parseInt(query, 10)), + await CodeSnippetsCodebaseIndex.getForId( + Number.parseInt(query, 10), + workspaceDirs, + ), ]; } diff --git a/core/context/providers/CurrentFileContextProvider.ts b/core/context/providers/CurrentFileContextProvider.ts index d3cef2dc1..e624f539a 100644 --- a/core/context/providers/CurrentFileContextProvider.ts +++ b/core/context/providers/CurrentFileContextProvider.ts @@ -4,7 +4,7 @@ import { ContextProviderDescription, ContextProviderExtras, } from "../../"; -import { getUriPathBasename } from "../../util/uri"; +import { getUriDescription } from "../../util/uri"; class CurrentFileContextProvider extends BaseContextProvider { static description: ContextProviderDescription = { @@ -23,12 +23,27 @@ class CurrentFileContextProvider extends BaseContextProvider { if (!currentFile) { return []; } - const baseName = getUriPathBasename(currentFile.path); + + const { relativePathOrBasename, last2Parts, baseName } = getUriDescription( + currentFile.path, + await extras.ide.getWorkspaceDirs(), + ); + + let prefix = "This is the currently open file:"; + let name = baseName; + + // This allows frontend to retrieve when using alt + enter or default context with slightly different copy + if (query === "non-mention-usage") { + prefix = + "The following file is currently open. Don't reference it if it's not relevant to the user's message:"; + name = "Active file: " + baseName; + } + return [ { - description: currentFile.path, - content: `This is the currently open file:\n\n\`\`\`${baseName}\n${currentFile.contents}\n\`\`\``, - name: baseName, + description: last2Parts, + content: `${prefix}\n\n\`\`\`${relativePathOrBasename}\n${currentFile.contents}\n\`\`\``, + name, uri: { type: "file", value: currentFile.path, diff --git a/core/context/providers/FileContextProvider.ts b/core/context/providers/FileContextProvider.ts index 674cc1a00..4953f5bdc 100644 --- a/core/context/providers/FileContextProvider.ts +++ b/core/context/providers/FileContextProvider.ts @@ -10,6 +10,7 @@ import { walkDirs } from "../../indexing/walkDir"; import { getUriPathBasename, getShortestUniqueRelativeUriPaths, + getUriDescription, } from "../../util/uri"; const MAX_SUBMENU_ITEMS = 10_000; @@ -27,16 +28,22 @@ class FileContextProvider extends BaseContextProvider { extras: ContextProviderExtras, ): Promise { // Assume the query is a filepath - query = query.trim(); - const content = await extras.ide.readFile(query); + const fileUri = query.trim(); + const content = await extras.ide.readFile(fileUri); + + const { relativePathOrBasename, last2Parts, baseName } = getUriDescription( + fileUri, + await extras.ide.getWorkspaceDirs(), + ); + return [ { - name: query.split(/[\\/]/).pop() ?? query, - description: query, - content: `\`\`\`${query}\n${content}\n\`\`\``, + name: baseName, + description: last2Parts, + content: `\`\`\`${relativePathOrBasename}\n${content}\n\`\`\``, uri: { type: "file", - value: query, + value: fileUri, }, }, ]; diff --git a/core/context/providers/MCPContextProvider.ts b/core/context/providers/MCPContextProvider.ts index f239e3ee1..0cb8e2c66 100644 --- a/core/context/providers/MCPContextProvider.ts +++ b/core/context/providers/MCPContextProvider.ts @@ -9,6 +9,7 @@ import { import { MCPManagerSingleton } from "../mcp"; interface MCPContextProviderOptions { + mcpId: string; submenuItems: ContextSubmenuItem[]; } @@ -74,10 +75,10 @@ class MCPContextProvider extends BaseContextProvider { args: LoadSubmenuItemsArgs, ): Promise { return (this.options as MCPContextProviderOptions).submenuItems.map( - (item, index) => ({ + (item) => ({ ...item, id: JSON.stringify({ - mcpId: String(index), + mcpId: (this.options as MCPContextProviderOptions).mcpId, uri: item.id, }), }), diff --git a/core/context/providers/OpenFilesContextProvider.ts b/core/context/providers/OpenFilesContextProvider.ts index 318ebb648..8267bf1c9 100644 --- a/core/context/providers/OpenFilesContextProvider.ts +++ b/core/context/providers/OpenFilesContextProvider.ts @@ -3,7 +3,7 @@ import { ContextProviderDescription, ContextProviderExtras, } from "../../index.js"; -import { findUriInDirs, getUriPathBasename } from "../../util/uri.js"; +import { getUriDescription } from "../../util/uri.js"; import { BaseContextProvider } from "../index.js"; class OpenFilesContextProvider extends BaseContextProvider { @@ -24,14 +24,17 @@ class OpenFilesContextProvider extends BaseContextProvider { ? await ide.getPinnedFiles() : await ide.getOpenFiles(); const workspaceDirs = await extras.ide.getWorkspaceDirs(); + return await Promise.all( openFiles.map(async (filepath: string) => { + const content = await ide.readFile(filepath); + const { relativePathOrBasename, last2Parts, baseName } = + getUriDescription(filepath, workspaceDirs); + return { - description: filepath, - content: `\`\`\`${ - findUriInDirs(filepath, workspaceDirs).relativePathOrBasename - }\n${await ide.readFile(filepath)}\n\`\`\``, - name: getUriPathBasename(filepath), + description: last2Parts, + content: `\`\`\`${relativePathOrBasename}\n${content}\n\`\`\``, + name: baseName, uri: { type: "file", value: filepath, diff --git a/core/context/providers/ProblemsContextProvider.ts b/core/context/providers/ProblemsContextProvider.ts index b1a0372a5..d8df5687f 100644 --- a/core/context/providers/ProblemsContextProvider.ts +++ b/core/context/providers/ProblemsContextProvider.ts @@ -3,7 +3,7 @@ import { ContextProviderDescription, ContextProviderExtras, } from "../../index.js"; -import { getUriPathBasename } from "../../util/uri.js"; +import { getUriDescription } from "../../util/uri.js"; import { BaseContextProvider } from "../index.js"; class ProblemsContextProvider extends BaseContextProvider { @@ -20,10 +20,14 @@ class ProblemsContextProvider extends BaseContextProvider { ): Promise { const ide = extras.ide; const problems = await ide.getProblems(); + const workspaceDirs = await ide.getWorkspaceDirs(); const items = await Promise.all( problems.map(async (problem) => { - const fileName = getUriPathBasename(problem.filepath); + const { relativePathOrBasename, baseName } = getUriDescription( + problem.filepath, + workspaceDirs, + ); const content = await ide.readFile(problem.filepath); const lines = content.split("\n"); const rangeContent = lines @@ -35,8 +39,8 @@ class ProblemsContextProvider extends BaseContextProvider { return { description: "Problems in current file", - content: `\`\`\`${fileName}\n${rangeContent}\n\`\`\`\n${problem.message}\n\n`, - name: `Warning in ${fileName}`, + content: `\`\`\`${relativePathOrBasename}\n${rangeContent}\n\`\`\`\n${problem.message}\n\n`, + name: `Warning in ${baseName}`, }; }), ); diff --git a/core/context/providers/_context-providers.test.ts b/core/context/providers/_context-providers.test.ts index 22f1dffbc..e877c10e7 100644 --- a/core/context/providers/_context-providers.test.ts +++ b/core/context/providers/_context-providers.test.ts @@ -7,7 +7,6 @@ import { IContextProvider, } from "../.."; import { ConfigHandler } from "../../config/ConfigHandler"; -import { ControlPlaneClient } from "../../control-plane/client"; import { TEST_DIR } from "../../test/testDir"; import FileSystemIde from "../../util/filesystem"; @@ -31,8 +30,9 @@ async function getContextProviderExtras( ide, ideSettingsPromise, async (text) => {}, - new ControlPlaneClient(Promise.resolve(undefined), ideSettingsPromise), + Promise.resolve(undefined), ); + await configHandler.initializedPromise; const { config } = await configHandler.loadConfig(); if (!config) { throw new Error("Config not found"); diff --git a/core/context/retrieval/retrieval.ts b/core/context/retrieval/retrieval.ts index 14dba3341..0f0a238eb 100644 --- a/core/context/retrieval/retrieval.ts +++ b/core/context/retrieval/retrieval.ts @@ -1,6 +1,6 @@ import { BranchAndDir, ContextItem, ContextProviderExtras } from "../../"; import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider"; -import { getUriPathBasename } from "../../util/uri"; +import { getUriDescription } from "../../util/uri"; import { INSTRUCTIONS_BASE_ITEM } from "../providers/utils"; import { RetrievalPipelineOptions } from "./pipelines/BaseRetrievalPipeline"; @@ -111,18 +111,17 @@ export async function retrieveContextItemsFromEmbeddings( ...results .sort((a, b) => a.filepath.localeCompare(b.filepath)) .map((r) => { - const basename = getUriPathBasename(r.filepath); - const name = `${basename} (${r.startLine}-${r.endLine})`; - const description = `${r.filepath}`; + const { relativePathOrBasename, last2Parts, baseName } = + getUriDescription(r.filepath, workspaceDirs); - if (basename === "package.json") { + if (baseName === "package.json") { console.warn("Retrieval pipeline: package.json detected"); } return { - name, - description, - content: `\`\`\`${name}\n${r.content}\n\`\`\``, + name: `${baseName} (${r.startLine + 1}-${r.endLine + 1})`, + description: last2Parts, + content: `\`\`\`${relativePathOrBasename}\n${r.content}\n\`\`\``, uri: { type: "file" as const, value: r.filepath, diff --git a/core/control-plane/auth/index.ts b/core/control-plane/auth/index.ts index 8965f4fdb..a3441ab65 100644 --- a/core/control-plane/auth/index.ts +++ b/core/control-plane/auth/index.ts @@ -4,13 +4,14 @@ import { getControlPlaneEnv } from "../env"; export async function getAuthUrlForTokenPage( ideSettingsPromise: Promise, + useOnboarding: boolean, ): Promise { const env = await getControlPlaneEnv(ideSettingsPromise); const url = new URL("https://api.workos.com/user_management/authorize"); const params = { response_type: "code", client_id: env.WORKOS_CLIENT_ID, - redirect_uri: `${env.APP_URL}tokens/callback`, + redirect_uri: `${env.APP_URL}tokens/${useOnboarding ? "onboarding-" : ""}callback`, // redirect_uri: "http://localhost:3000/tokens/callback", state: uuidv4(), provider: "authkit", diff --git a/core/control-plane/client.ts b/core/control-plane/client.ts index 7c15c8910..7d0e03cc8 100644 --- a/core/control-plane/client.ts +++ b/core/control-plane/client.ts @@ -104,7 +104,7 @@ export class ControlPlaneClient { } } - public async listAssistants(organizationId?: string): Promise< + public async listAssistants(organizationId: string | null): Promise< { configResult: ConfigResult; ownerSlug: string; @@ -132,38 +132,37 @@ export class ControlPlaneClient { } public async listOrganizations(): Promise> { - return [ - { - id: "1", - iconUrl: - "https://cdn.prod.website-files.com/663e06c56841363663ffbbcf/663e1b9fb023f0b622ad3608_log-text.svg", - name: "Continue", - }, - ]; - // const userId = await this.userId; - // if (!userId) { - // return []; - // } + const userId = await this.userId; - // try { - // const resp = await this.request("ide/list-organizations", { - // method: "GET", - // }); - // const { organizations } = (await resp.json()) as any; - // return organizations; - // } catch (e) { - // return []; - // } + if (!userId) { + return []; + } + + try { + const resp = await this.request("ide/list-organizations", { + method: "GET", + }); + const { organizations } = (await resp.json()) as any; + return organizations; + } catch (e) { + return []; + } } - public async listAssistantFullSlugs(): Promise { + public async listAssistantFullSlugs( + organizationId: string | null, + ): Promise { const userId = await this.userId; if (!userId) { return null; } + const url = organizationId + ? `ide/list-assistant-full-slugs?organizationId=${organizationId}` + : "ide/list-assistant-full-slugs"; + try { - const resp = await this.request("ide/list-assistant-full-slugs", { + const resp = await this.request(url, { method: "GET", }); const { fullSlugs } = (await resp.json()) as any; diff --git a/core/control-plane/env.ts b/core/control-plane/env.ts index 8f5bb40a4..ca8a85a12 100644 --- a/core/control-plane/env.ts +++ b/core/control-plane/env.ts @@ -1,4 +1,7 @@ +import fetch from "node-fetch"; +import * as fs from "node:fs"; import { IdeSettings } from ".."; +import { getStagingEnvironmentDotFilePath } from "../util/paths"; export interface ControlPlaneEnv { DEFAULT_CONTROL_PLANE_PROXY_URL: string; @@ -35,13 +38,11 @@ const PRODUCTION_HUB_ENV: ControlPlaneEnv = { }; const STAGING_ENV: ControlPlaneEnv = { - DEFAULT_CONTROL_PLANE_PROXY_URL: - "https://control-plane-api-service-537175798139.us-central1.run.app/", - CONTROL_PLANE_URL: - "https://control-plane-api-service-537175798139.us-central1.run.app/", - AUTH_TYPE: WORKOS_CLIENT_ID_STAGING, + DEFAULT_CONTROL_PLANE_PROXY_URL: "https://api.continue-stage.tools/", + CONTROL_PLANE_URL: "https://api.continue-stage.tools/", + AUTH_TYPE: WORKOS_ENV_ID_STAGING, WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_STAGING, - APP_URL: "https://app-preview.continue.dev/", + APP_URL: "https://hub.continue-stage.tools/", }; const TEST_ENV: ControlPlaneEnv = { @@ -60,6 +61,17 @@ const LOCAL_ENV: ControlPlaneEnv = { APP_URL: "http://localhost:3000/", }; +export async function enableHubContinueDev() { + try { + const resp = await fetch("https://api.continue.dev/features/hub"); + const data = (await resp.json()) as any; + if ("enabled" in data && data.enabled === true) { + return true; + } + } catch (e: any) {} + return false; +} + export async function getControlPlaneEnv( ideSettingsPromise: Promise, ): Promise { @@ -70,11 +82,15 @@ export async function getControlPlaneEnv( export function getControlPlaneEnvSync( ideTestEnvironment: IdeSettings["continueTestEnvironment"], ): ControlPlaneEnv { + if (fs.existsSync(getStagingEnvironmentDotFilePath())) { + return STAGING_ENV; + } + const env = ideTestEnvironment === "production" ? "hub" - : ideTestEnvironment === "test" - ? "test" + : ideTestEnvironment === "staging" + ? "staging" : ideTestEnvironment === "local" ? "local" : process.env.CONTROL_PLANE_ENV; diff --git a/core/core.ts b/core/core.ts index 52e5a58cd..8316068d5 100644 --- a/core/core.ts +++ b/core/core.ts @@ -11,14 +11,12 @@ import { SYSTEM_PROMPT_DOT_FILE } from "./config/getSystemPromptDotFile"; import { setupBestConfig, setupLocalConfig, - setupLocalConfigAfterFreeTrial, setupQuickstartConfig, } from "./config/onboarding"; import { addContextProvider, addModel, deleteModel } from "./config/util"; import { recentlyEditedFilesCache } from "./context/retrieval/recentlyEditedFilesCache"; import { ContinueServerClient } from "./continueServer/stubs/client"; import { getAuthUrlForTokenPage } from "./control-plane/auth/index"; -import { ControlPlaneClient } from "./control-plane/client"; import { getControlPlaneEnv } from "./control-plane/env"; import { streamDiffLines } from "./edit/streamDiffLines"; import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer"; @@ -53,17 +51,17 @@ import { type IndexingProgressUpdate, } from "."; +import CodebaseContextProvider from "./context/providers/CodebaseContextProvider"; +import CurrentFileContextProvider from "./context/providers/CurrentFileContextProvider"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import type { IMessenger, Message } from "./protocol/messenger"; export class Core { - // implements IMessenger configHandler: ConfigHandler; codebaseIndexerPromise: Promise; completionProvider: CompletionProvider; continueServerClientPromise: Promise; codebaseIndexingState: IndexingProgressUpdate; - controlPlaneClient: ControlPlaneClient; private docsService: DocsService; private globalContext = new GlobalContext(); @@ -73,10 +71,6 @@ export class Core { private abortedMessageIds: Set = new Set(); - private async config() { - return (await this.configHandler.loadConfig()).config; - } - invoke( messageType: T, data: ToCoreProtocol[T][0], @@ -114,16 +108,11 @@ export class Core { useOnboarding: false, }); - this.controlPlaneClient = new ControlPlaneClient( - sessionInfoPromise, - ideSettingsPromise, - ); - this.configHandler = new ConfigHandler( this.ide, ideSettingsPromise, this.onWrite, - this.controlPlaneClient, + sessionInfoPromise, ); this.docsService = DocsService.createSingleton( @@ -136,12 +125,17 @@ export class Core { const serializedResult = await this.configHandler.getSerializedConfig(); this.messenger.send("configUpdate", { result: serializedResult, - profileId: this.configHandler.currentProfile.profileDescription.id, + profileId: + this.configHandler.currentProfile?.profileDescription.id ?? null, }); }); - this.configHandler.onDidChangeAvailableProfiles((profiles) => - this.messenger.send("didChangeAvailableProfiles", { profiles }), + this.configHandler.onDidChangeAvailableProfiles( + (profiles, selectedProfileId) => + this.messenger.send("didChangeAvailableProfiles", { + profiles, + selectedProfileId, + }), ); // Codebase Indexer and ContinueServerClient depend on IdeSettings @@ -209,13 +203,24 @@ export class Core { // Note, VsCode's in-process messenger doesn't do anything with this // It will only show for jetbrains - this.messenger.onError((err) => { - console.error(err); + this.messenger.onError((message, err) => { void Telemetry.capture("core_messenger_error", { message: err.message, stack: err.stack, }); - void this.ide.showToast("error", err.message); + + // Again, specifically for jetbrains to prevent duplicate error messages + // The same logic can currently be found in the webview protocol + // bc streaming errors are handled in the GUI + if ( + ["llm/streamChat", "chatDescriber/describe"].includes( + message.messageType, + ) + ) { + return; + } else { + void this.ide.showToast("error", err.message); + } }); on("update/selectTabAutocompleteModel", async (msg) => { @@ -270,10 +275,8 @@ export class Core { }); on("config/newPromptFile", async (msg) => { - await createNewPromptFileV2( - this.ide, - (await this.config())?.experimental?.promptPath, - ); + const { config } = await this.configHandler.loadConfig(); + await createNewPromptFileV2(this.ide, config?.experimental?.promptPath); await this.configHandler.reloadConfig(); }); @@ -295,7 +298,7 @@ export class Core { }); on("config/addContextProvider", async (msg) => { - addContextProvider(msg.data); + addContextProvider(msg.data, this.configHandler); }); on("config/updateSharedConfig", async (msg) => { @@ -305,11 +308,15 @@ export class Core { on("controlPlane/openUrl", async (msg) => { const env = await getControlPlaneEnv(this.ide.getIdeSettings()); - await this.messenger.request("openUrl", `${env.APP_URL}${msg.data.path}`); + let url = `${env.APP_URL}${msg.data.path}`; + if (msg.data.orgSlug) { + url += `?org=${msg.data.orgSlug}`; + } + await this.messenger.request("openUrl", url); }); on("controlPlane/listOrganizations", async (msg) => { - return await this.controlPlaneClient.listOrganizations(); + return await this.configHandler.listOrganizations(); }); // Context providers @@ -326,7 +333,7 @@ export class Core { }); on("context/loadSubmenuItems", async (msg) => { - const config = await this.config(); + const { config } = await this.configHandler.loadConfig(); if (!config) { return []; } @@ -343,17 +350,26 @@ export class Core { }); on("context/getContextItems", async (msg) => { - const { name, query, fullInput, selectedCode, selectedModelTitle } = - msg.data; - const config = await this.config(); + const { config } = await this.configHandler.loadConfig(); if (!config) { return []; } + const { name, query, fullInput, selectedCode, selectedModelTitle } = + msg.data; + const llm = await this.configHandler.llmFromTitle(selectedModelTitle); - const provider = config.contextProviders?.find( - (provider) => provider.description.title === name, - ); + const provider = + config.contextProviders?.find( + (provider) => provider.description.title === name, + ) ?? + [ + // user doesn't need these in their config.json for the shortcuts to work + // option+enter + new CurrentFileContextProvider({}), + // cmd+enter + new CodebaseContextProvider({}), + ].find((provider) => provider.description.title === name); if (!provider) { return []; } @@ -389,10 +405,36 @@ export class Core { id, })); } catch (e) { - void this.ide.showToast( - "error", - `Error getting context items from ${name}: ${e}`, - ); + let knownError = false; + + if (e instanceof Error) { + // A specific error where we're forcing the presence of embeddings provider on the config + // But Jetbrains doesn't support transformers JS + // So if a context provider needs it it will throw this error when the file isn't found + if (e.message.includes("all-MiniLM-L6-v2")) { + knownError = true; + const toastOption = "See Docs"; + void this.ide + .showToast( + "error", + `Set up an embeddings model to use @${name}`, + toastOption, + ) + .then((userSelection) => { + if (userSelection === toastOption) { + void this.ide.openUrl( + "https://docs.continue.dev/customize/model-types/embeddings", + ); + } + }); + } + } + if (!knownError) { + void this.ide.showToast( + "error", + `Error getting context items from ${name}: ${e}`, + ); + } return []; } }); @@ -405,7 +447,8 @@ export class Core { on("config/getSerializedProfileInfo", async (msg) => { return { result: await this.configHandler.getSerializedConfig(), - profileId: this.configHandler.currentProfile.profileDescription.id, + profileId: + this.configHandler.currentProfile?.profileDescription.id ?? null, }; }); @@ -693,6 +736,8 @@ export class Core { llm, data.input, data.language, + false, + undefined, )) { if (abortedMessageIds.has(msg.messageId)) { abortedMessageIds.delete(msg.messageId); @@ -724,10 +769,6 @@ export class Core { editConfigJsonCallback = setupQuickstartConfig; break; - case "LocalAfterFreeTrial": - editConfigJsonCallback = setupLocalConfigAfterFreeTrial; - break; - case "Best": editConfigJsonCallback = setupBestConfig; break; @@ -831,12 +872,18 @@ export class Core { on("files/created", async ({ data }) => { if (data?.uris?.length) { + this.messenger.send("refreshSubmenuItems", { + providers: ["file"], + }); await this.refreshCodebaseIndexFiles(data.uris); } }); on("files/deleted", async ({ data }) => { if (data?.uris?.length) { + this.messenger.send("refreshSubmenuItems", { + providers: ["file"], + }); await this.refreshCodebaseIndexFiles(data.uris); } }); @@ -882,11 +929,23 @@ export class Core { void this.configHandler.setSelectedProfile(msg.data.id); void this.configHandler.reloadConfig(); }); + + on("didChangeSelectedOrg", (msg) => { + void this.configHandler.setSelectedOrgId(msg.data.id); + void this.configHandler.reloadConfig(); + void this.configHandler.loadAssistantsForSelectedOrg(); + }); + on("didChangeControlPlaneSessionInfo", async (msg) => { - this.configHandler.updateControlPlaneSessionInfo(msg.data.sessionInfo); + await this.configHandler.updateControlPlaneSessionInfo( + msg.data.sessionInfo, + ); }); on("auth/getAuthUrl", async (msg) => { - const url = await getAuthUrlForTokenPage(ideSettingsPromise); + const url = await getAuthUrlForTokenPage( + ideSettingsPromise, + msg.data.useOnboarding, + ); return { url }; }); @@ -924,16 +983,23 @@ export class Core { const llm = await this.configHandler.llmFromTitle(selectedModelTitle); const contextItems = await callTool( - tool.uri ?? tool.function.name, + tool, JSON.parse(toolCall.function.arguments || "{}"), { ide: this.ide, llm, fetch: (url, init) => fetchwithRequestOptions(url, init, config.requestOptions), + tool, }, ); + if (tool.faviconUrl) { + contextItems.forEach((item) => { + item.icon = tool.faviconUrl; + }); + } + return { contextItems }; }); } diff --git a/core/edit/streamDiffLines.ts b/core/edit/streamDiffLines.ts index 1d1202b91..f7b54dff6 100644 --- a/core/edit/streamDiffLines.ts +++ b/core/edit/streamDiffLines.ts @@ -54,7 +54,8 @@ export async function* streamDiffLines( llm: ILLM, input: string, language: string | undefined, - onlyOneInsertion?: boolean, + onlyOneInsertion: boolean, + overridePrompt: ChatMessage[] | undefined, ): AsyncGenerator { void Telemetry.capture( "inlineEdit", @@ -80,14 +81,9 @@ export async function* streamDiffLines( // Trim end of oldLines, otherwise we have trailing \r on every line for CRLF files oldLines = oldLines.map((line) => line.trimEnd()); - const prompt = constructPrompt( - prefix, - highlighted, - suffix, - llm, - input, - language, - ); + const prompt = + overridePrompt ?? + constructPrompt(prefix, highlighted, suffix, llm, input, language); const inept = modelIsInept(llm.model); const prediction: Prediction = { diff --git a/core/index.d.ts b/core/index.d.ts index 1184b412b..7d882cb27 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1,6 +1,6 @@ +import { ModelRole } from "@continuedev/config-yaml"; import Parser from "web-tree-sitter"; import { GetGhTokenArgs } from "./protocol/ide"; - declare global { interface Window { ide?: "vscode"; @@ -43,13 +43,13 @@ export interface IndexingProgressUpdate { desc: string; shouldClearIndexes?: boolean; status: - | "loading" - | "indexing" - | "done" - | "failed" - | "paused" - | "disabled" - | "cancelled"; + | "loading" + | "indexing" + | "done" + | "failed" + | "paused" + | "disabled" + | "cancelled"; debugInfo?: string; } @@ -94,6 +94,8 @@ export interface ILLM extends LLMOptions { apiKey?: string; apiBase?: string; cacheBehavior?: CacheBehavior; + capabilities?: ModelCapability; + roles?: ModelRole[]; deployment?: string; apiVersion?: string; @@ -480,6 +482,8 @@ export interface LLMOptions { aiGatewaySlug?: string; apiBase?: string; cacheBehavior?: CacheBehavior; + capabilities?: ModelCapability; + roles?: ModelRole[]; useLegacyCompletionsEndpoint?: boolean; @@ -503,9 +507,6 @@ export interface LLMOptions { // AWS and GCP Options region?: string; - // GCP Options - capabilities?: ModelCapability; - // GCP and Watsonx Options projectId?: string; @@ -599,7 +600,7 @@ export interface IdeSettings { remoteConfigSyncPeriod: number; userToken: string; enableControlServerBeta: boolean; - continueTestEnvironment: "none" | "production" | "test" | "local"; + continueTestEnvironment: "none" | "production" | "staging" | "local"; pauseCodebaseIndexOnStart: boolean; } @@ -666,12 +667,16 @@ export interface IDE { getCurrentFile(): Promise< | undefined | { - isUntitled: boolean; - path: string; - contents: string; - } + isUntitled: boolean; + path: string; + contents: string; + } >; + getLastFileSaveTimestamp?(): number; + + updateLastFileSaveTimestamp?(): void; + getPinnedFiles(): Promise; getSearchResults(query: string): Promise; @@ -848,17 +853,18 @@ export interface CustomCommand { export interface Prediction { type: "content"; content: - | string - | { - type: "text"; - text: string; - }[]; + | string + | { + type: "text"; + text: string; + }[]; } export interface ToolExtras { ide: IDE; llm: ILLM; fetch: FetchFunction; + tool: Tool; } export interface Tool { @@ -874,6 +880,7 @@ export interface Tool { wouldLikeTo: string; readonly: boolean; uri?: string; + faviconUrl?: string; } interface ToolChoice { @@ -905,6 +912,7 @@ export interface BaseCompletionOptions { export interface ModelCapability { uploadImage?: boolean; + tools?: boolean; } export interface ModelDescription { @@ -921,8 +929,9 @@ export interface ModelDescription { systemMessage?: string; requestOptions?: RequestOptions; promptTemplates?: { [key: string]: string }; - capabilities?: ModelCapability; cacheBehavior?: CacheBehavior; + capabilities?: ModelCapability; + roles?: ModelRole[]; } export interface EmbedOptions { @@ -971,6 +980,11 @@ export interface TabAutocompleteOptions { disableInFiles?: string[]; useImports?: boolean; showWhateverWeHaveAtXMs?: number; + // true = enabled, false = disabled, number = enabled with priority + experimental_includeClipboard: boolean | number; + experimental_includeRecentlyVisitedRanges: boolean | number; + experimental_includeRecentlyEditedRanges: boolean | number; + experimental_includeDiff: boolean | number; } export interface StdioOptions { @@ -994,6 +1008,7 @@ export type TransportOptions = StdioOptions | WebSocketOptions | SSEOptions; export interface MCPOptions { transport: TransportOptions; + faviconUrl?: string; } export interface ContinueUIConfig { @@ -1012,7 +1027,7 @@ export interface ContextMenuConfig { fixGrammar?: string; } -export interface ModelRoles { +export interface ExperimentalModelRoles { inlineEdit?: string; applyCodeBlock?: string; repoMapFileSelection?: string; @@ -1080,7 +1095,7 @@ export type DefaultContextProvider = ContextProviderWithParams & { export interface ExperimentalConfig { contextMenuPrompts?: ContextMenuConfig; - modelRoles?: ModelRoles; + modelRoles?: ExperimentalModelRoles; defaultContext?: DefaultContextProvider[]; promptPath?: string; @@ -1171,9 +1186,9 @@ export interface Config { embeddingsProvider?: EmbeddingsProviderDescription | ILLM; /** The model that Continue will use for tab autocompletions. */ tabAutocompleteModel?: - | CustomLLM - | ModelDescription - | (CustomLLM | ModelDescription)[]; + | CustomLLM + | ModelDescription + | (CustomLLM | ModelDescription)[]; /** Options for tab autocomplete */ tabAutocompleteOptions?: Partial; /** UI styles customization */ @@ -1264,9 +1279,9 @@ export type PackageDetailsSuccess = PackageDetails & { export type PackageDocsResult = { packageInfo: ParsedPackageInfo; } & ( - | { error: string; details?: never } - | { details: PackageDetailsSuccess; error?: never } -); + | { error: string; details?: never } + | { details: PackageDetailsSuccess; error?: never } + ); export interface TerminalOptions { reuseTerminal?: boolean; diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index f207f096b..c0d386d07 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -28,7 +28,12 @@ import type { IndexTag, IndexingProgressUpdate, } from "../"; -import { getLastNPathParts, getUriPathBasename } from "../util/uri"; +import { + findUriInDirs, + getLastNPathParts, + getLastNUriRelativePathParts, + getUriPathBasename, +} from "../util/uri"; type SnippetChunk = ChunkWithoutID & { title: string; signature: string }; @@ -347,14 +352,19 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { } } - static async getForId(id: number): Promise { + static async getForId( + id: number, + workspaceDirs: string[], + ): Promise { const db = await SqliteDb.get(); const row = await db.get("SELECT * FROM code_snippets WHERE id = ?", [id]); + const last2Parts = getLastNUriRelativePathParts(workspaceDirs, row.path, 2); + const { relativePathOrBasename } = findUriInDirs(row.path, workspaceDirs); return { name: row.title, - description: getLastNPathParts(row.path, 2), - content: `\`\`\`${getUriPathBasename(row.path)}\n${row.content}\n\`\`\``, + description: last2Parts, + content: `\`\`\`${relativePathOrBasename}\n${row.content}\n\`\`\``, uri: { type: "file", value: row.path, diff --git a/core/indexing/docs/DocsService.skip.ts b/core/indexing/docs/DocsService.skip.ts index 0064f064c..682b76a23 100644 --- a/core/indexing/docs/DocsService.skip.ts +++ b/core/indexing/docs/DocsService.skip.ts @@ -2,7 +2,6 @@ * @jest-environment jsdom */ import { ConfigHandler } from "../../config/ConfigHandler.js"; -import { ControlPlaneClient } from "../../control-plane/client.js"; import { SiteIndexingConfig } from "../../index.js"; import FileSystemIde from "../../util/filesystem.js"; import { editConfigJson } from "../../util/paths.js"; @@ -50,16 +49,7 @@ describe.skip("DocsService Integration Tests", () => { ide, ideSettingsPromise, async () => {}, - new ControlPlaneClient( - Promise.resolve({ - accessToken: "", - account: { - id: "", - label: "", - }, - }), - ideSettingsPromise, - ), + Promise.resolve(undefined), ); docsService = DocsService.createSingleton(configHandler, ide); diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index f0d1e2f3c..4d555f557 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -26,6 +26,8 @@ import { } from "../../util/paths"; import { Telemetry } from "../../util/posthog"; +import { ConfigResult } from "@continuedev/config-yaml"; +import { GlobalContext } from "../../util/GlobalContext"; import { ArticleWithChunks, htmlPageToArticleWithChunks, @@ -40,7 +42,6 @@ import { SiteIndexingResults, } from "./preIndexed"; import preIndexedDocs from "./preIndexedDocs"; -import { ConfigResult } from "@continuedev/config-yaml"; // Purposefully lowercase because lancedb converts export interface LanceDbDocsRow { @@ -156,7 +157,8 @@ export default class DocsService { const currentStatus = this.statuses.get(doc.startUrl); if (currentStatus) { - return currentStatus; + this.handleStatusUpdate(currentStatus); + return; } const sharedStatus = { @@ -210,11 +212,7 @@ export default class DocsService { if (isAborted) { return true; } - // Handle indexing disabled change mid-indexing - if (this.config.disableIndexing) { - this.abort(startUrl); - return true; - } + // Handle embeddings provider change mid-indexing if (this.config.embeddingsProvider.embeddingId !== startedWithEmbedder) { this.abort(startUrl); @@ -276,10 +274,6 @@ export default class DocsService { const oldConfig = this.config; this.config = newConfig; // IMPORTANT - need to set up top, other methods below use this without passing it in - if (this.config.disableIndexing) { - return; - } - // No point in indexing if no docs context provider const hasDocsContextProvider = this.hasDocsContextProvider(); if (!hasDocsContextProvider) { @@ -365,13 +359,16 @@ export default class DocsService { async indexAndAdd( siteIndexingConfig: SiteIndexingConfig, - reIndex: boolean = false, + forceReindex: boolean = false, ): Promise { - if (this.config.disableIndexing) { - console.warn("Attempting to add/index docs when indexing is disabled"); + const { startUrl, useLocalCrawling, maxDepth } = siteIndexingConfig; + + // First, if indexing is already in process, don't attempt + // This queue is necessary because indexAndAdd is invoked circularly by config edits + // TODO shouldn't really be a gap between adding and checking in queue but probably fine + if (this.docsIndexingQueue.has(startUrl)) { return; } - const { startUrl, useLocalCrawling, maxDepth } = siteIndexingConfig; const { isPreindexed, provider } = await this.getEmbeddingsProvider(startUrl); @@ -379,13 +376,10 @@ export default class DocsService { console.warn("Attempted to indexAndAdd pre-indexed doc"); return; } - - // Queue - indexAndAdd is invoked circularly by config edits. This prevents duplicate runs - if (this.docsIndexingQueue.has(startUrl)) { - return; - } - const startedWithEmbedder = provider.embeddingId; + + // Check if doc has been successfully indexed with the given embedder + // Note at this point we know it's not a pre-indexed doc const indexExists = await this.hasMetadata(startUrl); // Build status update - most of it is fixed values @@ -396,32 +390,82 @@ export default class DocsService { type: "docs", id: siteIndexingConfig.startUrl, embeddingsProviderId: provider.embeddingId, - isReindexing: reIndex && indexExists, + isReindexing: forceReindex && indexExists, title: siteIndexingConfig.title, debugInfo: `max depth: ${siteIndexingConfig.maxDepth}`, icon: siteIndexingConfig.faviconUrl, url: siteIndexingConfig.startUrl, }; - // Clear current indexes if reIndexing - if (indexExists) { - if (reIndex) { - await this.deleteIndexes(startUrl); - } else { + // If not force-reindexing and has failed with same config, don't reattempt + if (!forceReindex) { + const globalContext = new GlobalContext(); + const failedDocs = globalContext.get("failedDocs") ?? []; + const hasFailed = failedDocs.find((d) => + this.siteIndexingConfigsAreEqual(siteIndexingConfig, d), + ); + if (hasFailed) { + console.log( + `Not reattempting to index ${siteIndexingConfig.startUrl}, has already failed with same config`, + ); this.handleStatusUpdate({ ...fixedStatus, + description: "Failed", + status: "failed", progress: 1, - description: "Complete", - status: "complete", - debugInfo: "Already indexed", }); return; } } + if (indexExists && !forceReindex) { + this.handleStatusUpdate({ + ...fixedStatus, + progress: 1, + description: "Complete", + status: "complete", + debugInfo: "Already indexed", + }); + return; + } + + // Do a test run on the embedder + // This particular failure will not mark as a failed config in global context + // Since SiteIndexingConfig is likely to be valid + try { + await provider.embed(["continue-test-run"]); + } catch (e) { + console.error("Failed to test embeddings connection", e); + return; + } + + const markFailedInGlobalContext = () => { + const globalContext = new GlobalContext(); + const failedDocs = globalContext.get("failedDocs") ?? []; + const newFailedDocs = failedDocs.filter( + (d) => !this.siteIndexingConfigsAreEqual(siteIndexingConfig, d), + ); + newFailedDocs.push(siteIndexingConfig); + globalContext.update("failedDocs", newFailedDocs); + }; + + const removeFromFailedGlobalContext = () => { + const globalContext = new GlobalContext(); + const failedDocs = globalContext.get("failedDocs") ?? []; + const newFailedDocs = failedDocs.filter( + (d) => !this.siteIndexingConfigsAreEqual(siteIndexingConfig, d), + ); + globalContext.update("failedDocs", newFailedDocs); + }; + try { this.docsIndexingQueue.add(startUrl); + // Clear current indexes if reIndexing + if (indexExists && forceReindex) { + await this.deleteIndexes(startUrl); + } + this.addToConfig(siteIndexingConfig); this.handleStatusUpdate({ @@ -523,9 +567,10 @@ export default class DocsService { }); try { - const subpathEmbeddings = await provider.embed( - article.chunks.map((c) => c.content), - ); + const subpathEmbeddings = + article.chunks.length > 0 + ? await provider.embed(article.chunks.map((c) => c.content)) + : []; chunks.push(...article.chunks); embeddings.push(...subpathEmbeddings); const toWait = 100 * this.docsIndexingQueue.size + 50; @@ -551,7 +596,7 @@ export default class DocsService { }); void this.ide.showToast("info", `Failed to index ${startUrl}`); - this.docsIndexingQueue.delete(startUrl); + markFailedInGlobalContext(); return; } @@ -569,7 +614,7 @@ export default class DocsService { }); // Delete indexed docs if re-indexing - if (reIndex && indexExists) { + if (forceReindex && indexExists) { console.log("Deleting old embeddings"); await this.deleteIndexes(startUrl); } @@ -593,11 +638,6 @@ export default class DocsService { favicon, }); - this.docsIndexingQueue.delete(startUrl); - - if (this.shouldCancel(startUrl, startedWithEmbedder)) { - return; - } this.handleStatusUpdate({ ...fixedStatus, description: "Complete", @@ -610,23 +650,29 @@ export default class DocsService { this.messenger?.send("refreshSubmenuItems", { providers: ["docs"], }); + + removeFromFailedGlobalContext(); } catch (e) { - let description = `Error getting docs from: ${siteIndexingConfig.startUrl}`; + console.error( + `Error indexing docs at: ${siteIndexingConfig.startUrl}`, + e, + ); + let description = `Error indexing docs at: ${siteIndexingConfig.startUrl}`; if (e instanceof Error) { if ( e.message.includes("github.com") && e.message.includes("rate limit") ) { - description = "Github rate limit exceeded"; + description = "Github rate limit exceeded"; // This text is used verbatim elsewhere } } - console.error("Error indexing docs", e); this.handleStatusUpdate({ ...fixedStatus, description, status: "failed", progress: 1, }); + markFailedInGlobalContext(); } finally { this.docsIndexingQueue.delete(startUrl); } @@ -871,7 +917,7 @@ export default class DocsService { // Anything found in old config, new config, AND sqlite that doesn't match should be reindexed // TODO if only favicon and title change, only update, don't embed // Otherwise anything found in new config that isn't in sqlite should be added/indexed - const newDocs: SiteIndexingConfig[] = []; + const addedDocs: SiteIndexingConfig[] = []; const changedDocs: SiteIndexingConfig[] = []; for (const doc of newConfigDocs) { const currentIndexedDoc = currentStartUrls.includes(doc.startUrl); @@ -908,22 +954,16 @@ export default class DocsService { } } } else { - const currentStatus = this.statuses.get(doc.startUrl); - if (currentStatus?.status !== "failed") { - newDocs.push(doc); - } + addedDocs.push(doc); + void Telemetry.capture("add_docs_config", { url: doc.startUrl }); } } await Promise.allSettled([ ...changedDocs.map((doc) => this.indexAndAdd(doc, true)), - ...newDocs.map((doc) => this.indexAndAdd(doc)), + ...addedDocs.map((doc) => this.indexAndAdd(doc)), ]); - for (const doc of newDocs) { - void Telemetry.capture("add_docs_config", { url: doc.startUrl }); - } - for (const doc of deletedDocs) { await this.deleteIndexes(doc.startUrl); } diff --git a/core/indexing/docs/preIndexedDocs.ts b/core/indexing/docs/preIndexedDocs.ts index 1e2a8dbc0..4b0c12fee 100644 --- a/core/indexing/docs/preIndexedDocs.ts +++ b/core/indexing/docs/preIndexedDocs.ts @@ -353,6 +353,11 @@ const preIndexedDocs: Record< startUrl: "https://docs.asksage.ai/", rootUrl: "https://docs.asksage.ai/", }, + "https://angular.dev/": { + title: "Angular", + startUrl: "https://angular.dev/", + rootUrl: "https://angular.dev/", + }, }; export default preIndexedDocs; diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index 8232f8288..6b9884c21 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -1,4 +1,9 @@ -import { ModelCapability, TemplateType } from "../index.js"; +import { + ChatMessage, + ModelCapability, + ModelDescription, + TemplateType, +} from "../index.js"; import { anthropicTemplateMessages, @@ -52,6 +57,7 @@ const PROVIDER_HANDLES_TEMPLATING: string[] = [ "sambanova", "vertexai", "watsonx", + "nebius", ]; const PROVIDER_SUPPORTS_IMAGES: string[] = [ @@ -68,6 +74,7 @@ const PROVIDER_SUPPORTS_IMAGES: string[] = [ "vertexai", "azure", "scaleway", + "nebius", ]; const MODEL_SUPPORTS_IMAGES: string[] = [ @@ -87,12 +94,15 @@ const MODEL_SUPPORTS_IMAGES: string[] = [ "llama3.2", ]; -function modelSupportsTools(modelName: string, provider: string) { - const providerSupport = PROVIDER_TOOL_SUPPORT[provider]; +function modelSupportsTools(modelDescription: ModelDescription) { + if (modelDescription.capabilities?.tools !== undefined) { + return modelDescription.capabilities.tools; + } + const providerSupport = PROVIDER_TOOL_SUPPORT[modelDescription.provider]; if (!providerSupport) { return false; } - return providerSupport(modelName) ?? false; + return providerSupport(modelDescription.model) ?? false; } function modelSupportsImages( @@ -257,7 +267,10 @@ function autodetectTemplateFunction( const templateType = explicitTemplate ?? autodetectTemplateType(model); if (templateType) { - const mapping: Record = { + const mapping: Record< + TemplateType, + null | ((msg: ChatMessage[]) => string) + > = { llama2: llama2TemplateMessages, alpaca: templateAlpacaMessages, phi2: phi2TemplateMessages, diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts index 4d948e7d0..fa6cdd558 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -1,4 +1,9 @@ -import { ChatHistoryItem, ChatMessage, MessagePart } from "../"; +import { + ChatHistoryItem, + ChatMessage, + MessagePart, + ModelDescription, +} from "../"; import { normalizeToMessageParts } from "../util/messageContent"; import { modelSupportsTools } from "./autodetect"; @@ -67,15 +72,18 @@ const TOOL_USE_RULES = `When using tools, follow the following guidelines: - Avoid calling tools unless they are absolutely necessary. For example, if you are asked a simple programming question you do not need web search. As another example, if the user asks you to explain something about code, do not create a new file.`; function constructSystemPrompt( - model: string, - provider: string, + modelDescription: ModelDescription, useTools: boolean, ): string | null { let systemMessage = ""; - if (CUSTOM_SYS_MSG_MODEL_FAMILIES.some((family) => model.includes(family))) { + if ( + CUSTOM_SYS_MSG_MODEL_FAMILIES.some((family) => + modelDescription.model.includes(family), + ) + ) { systemMessage = SYSTEM_MESSAGE; } - if (useTools && modelSupportsTools(model, provider)) { + if (useTools && modelSupportsTools(modelDescription)) { if (systemMessage) { systemMessage += "\n\n"; } @@ -89,8 +97,7 @@ const CANCELED_TOOL_CALL_MESSAGE = export function constructMessages( history: ChatHistoryItem[], - model: string, - provider: string, + modelDescription: ModelDescription, useTools: boolean, ): ChatMessage[] { const filteredHistory = history.filter( @@ -98,7 +105,7 @@ export function constructMessages( ); const msgs: ChatMessage[] = []; - const systemMessage = constructSystemPrompt(model, provider, useTools); + const systemMessage = constructSystemPrompt(modelDescription, useTools); if (systemMessage) { msgs.push({ role: "system", diff --git a/core/llm/index.ts b/core/llm/index.ts index da1825407..7e3c37fc2 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -56,6 +56,7 @@ import { toCompleteBody, toFimBody, } from "./openaiTypeConverters.js"; +import { ModelRole } from "@continuedev/config-yaml"; export abstract class BaseLLM implements ILLM { static providerName: string; @@ -121,6 +122,7 @@ export abstract class BaseLLM implements ILLM { apiBase?: string; cacheBehavior?: CacheBehavior; capabilities?: ModelCapability; + roles?: ModelRole[]; deployment?: string; apiVersion?: string; @@ -191,7 +193,8 @@ export abstract class BaseLLM implements ILLM { options.model, this.providerName, options.template, - ); + ) ?? + undefined; this.writeLog = options.writeLog; this.llmRequestHook = options.llmRequestHook; this.apiKey = options.apiKey; @@ -208,6 +211,7 @@ export abstract class BaseLLM implements ILLM { } this.accountId = options.accountId; this.capabilities = options.capabilities; + this.roles = options.roles; this.deployment = options.deployment; this.apiVersion = options.apiVersion; @@ -957,7 +961,9 @@ export abstract class BaseLLM implements ILLM { this.providerName, autodetectTemplateType(this.model), ); - return templateMessages(rendered); + if (templateMessages) { + return templateMessages(rendered); + } } return rendered; } diff --git a/core/llm/llm.test.ts b/core/llm/llm.test.ts index 53729022a..9912b862e 100644 --- a/core/llm/llm.test.ts +++ b/core/llm/llm.test.ts @@ -2,12 +2,14 @@ import * as dotenv from "dotenv"; import { AssistantChatMessage, CompletionOptions } from ".."; -import { BaseLLM } from "."; import Anthropic from "./llms/Anthropic"; +import Azure from "./llms/Azure"; import Gemini from "./llms/Gemini"; import Mistral from "./llms/Mistral"; import OpenAI from "./llms/OpenAI"; +import { BaseLLM } from "."; + dotenv.config(); const COMPLETION_OPTIONS: Partial = { @@ -222,4 +224,25 @@ describe("LLM", () => { }), { testFim: true, skip: false }, ); + testLLM( + new Azure({ + apiKey: process.env.AZURE_OPENAI_API_KEY, + model: "gpt-4o", + apiVersion: "2024-05-01-preview", + apiBase: "https://continue-azure-openai-instance.openai.azure.com", + deployment: "azure-openai-deployment", + apiType: "azure-openai", + }), + { testFim: false, skip: false, timeout: 20000 }, + ); + testLLM( + new Azure({ + apiKey: process.env.AZURE_FOUNDRY_API_KEY, + model: "codestral-latest", + apiBase: + "https://codestral-2501-continue-testing.eastus.models.ai.azure.com", + apiType: "azure-foundry", + }), + { testFim: false, skip: false, timeout: 20000 }, + ); }); diff --git a/core/llm/llms/Azure.ts b/core/llm/llms/Azure.ts index b2beae921..bd27daeb1 100644 --- a/core/llm/llms/Azure.ts +++ b/core/llm/llms/Azure.ts @@ -14,7 +14,7 @@ class Azure extends OpenAI { static defaultOptions: Partial = { apiVersion: "2024-02-15-preview", - apiType: "azure", + apiType: "azure-openai", }; constructor(options: LLMOptions) { diff --git a/core/llm/llms/FreeTrial.ts b/core/llm/llms/FreeTrial.ts index c092a1ecb..ab69aff70 100644 --- a/core/llm/llms/FreeTrial.ts +++ b/core/llm/llms/FreeTrial.ts @@ -215,7 +215,7 @@ class FreeTrial extends BaseLLM { "llama3.1-70b", "gpt-4o", "gpt-3.5-turbo", - "claude-3-haiku-20240307", + "claude-3-5-haiku-latest", "gemini-1.5-pro-latest", ]; } diff --git a/core/llm/llms/Gemini.ts b/core/llm/llms/Gemini.ts index 4c0fb189b..ee24cc3e9 100644 --- a/core/llm/llms/Gemini.ts +++ b/core/llm/llms/Gemini.ts @@ -1,4 +1,3 @@ -import { r } from "tar"; import { AssistantChatMessage, ChatMessage, @@ -7,6 +6,7 @@ import { MessagePart, ToolCallDelta, } from "../../index.js"; +import { findLast } from "../../util/findLast.js"; import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; @@ -17,7 +17,6 @@ import { GeminiGenerationConfig, GeminiToolFunctionDeclaration, } from "./gemini-types.js"; -import { findLast } from "../../util/findLast.js"; class Gemini extends BaseLLM { static providerName = "gemini"; @@ -253,7 +252,7 @@ class Gemini extends BaseLLM { } // Helper function to recursively clean JSON Schema objects const cleanJsonSchema = (schema: any): any => { - if (!schema || typeof schema !== 'object') return schema; + if (!schema || typeof schema !== "object") return schema; if (Array.isArray(schema)) { return schema.map(cleanJsonSchema); @@ -273,7 +272,7 @@ class Gemini extends BaseLLM { ...acc, [key]: cleanJsonSchema(value), }), - {} + {}, ); } @@ -349,8 +348,8 @@ class Gemini extends BaseLLM { // Process all parts first to maintain order const processedParts: Array<{ - type: 'content' | 'tool' | 'toolCall', - data: any + type: "content" | "tool" | "toolCall"; + data: any; }> = []; for (const part of content.parts) { @@ -366,7 +365,7 @@ class Gemini extends BaseLLM { } else if ("functionCall" in part) { // Queue function call processedParts.push({ - type: 'toolCall', + type: "toolCall", data: { type: "function", id: "", // Not supported by gemini @@ -377,17 +376,17 @@ class Gemini extends BaseLLM { ? part.functionCall.args : JSON.stringify(part.functionCall.args), }, - } + }, }); } else if ("functionResponse" in part) { // Queue function response processedParts.push({ - type: 'tool', + type: "tool", data: { role: "tool", content: part.functionResponse.response.output as string, toolCallId: part.functionResponse.name, - } + }, }); } else { console.warn("Unsupported gemini part type received", part); @@ -404,13 +403,13 @@ class Gemini extends BaseLLM { // Then process tool calls and responses in order for (const part of processedParts) { - if (part.type === 'toolCall') { + if (part.type === "toolCall") { yield { role: "assistant", content: "", toolCalls: [part.data], }; - } else if (part.type === 'tool') { + } else if (part.type === "tool") { yield part.data; } } diff --git a/core/llm/llms/Nebius.ts b/core/llm/llms/Nebius.ts index dc97f94d0..e346e4ca8 100644 --- a/core/llm/llms/Nebius.ts +++ b/core/llm/llms/Nebius.ts @@ -10,6 +10,10 @@ class Nebius extends OpenAI { }; private static MODEL_IDS: { [name: string]: string } = { + "deepseek/deepseek_v3": "deepseek-ai/DeepSeek-V3", + "deepseek/deepseek-r1": "deepseek-ai/DeepSeek-R1", + "qwen2.5-coder-32b": "Qwen/Qwen2.5-Coder-32B-Instruct-fast", + "Qwen/QwQ-32B-Preview": "Qwen/QwQ-32B-Preview", "llama3.1-70b-nemotron": "nvidia/Llama-3.1-Nemotron-70B-Instruct-HF-fast", "llama3.1-8b": "meta-llama/Meta-Llama-3.1-70B-Instruct-fast", "llama3.1-70b": "meta-llama/Meta-Llama-3.1-70B-Instruct-fast", diff --git a/core/llm/llms/Novita.ts b/core/llm/llms/Novita.ts index 2f5c61b55..55b944829 100644 --- a/core/llm/llms/Novita.ts +++ b/core/llm/llms/Novita.ts @@ -9,6 +9,8 @@ class Novita extends OpenAI { }; private static MODEL_IDS: { [name: string]: string } = { + "deepseek-r1": "deepseek/deepseek-r1", + "deepseek_v3": "deepseek/deepseek_v3", "llama3-8b": "meta-llama/llama-3-8b-instruct", "llama3-70b": "meta-llama/llama-3-70b-instruct", "llama3.1-8b": "meta-llama/llama-3.1-8b-instruct", diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index e0acc961e..92f0aca08 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -49,7 +49,7 @@ const CHAT_ONLY_MODELS = [ "gpt-4o-mini", "o1-preview", "o1-mini", - "o3-mini" + "o3-mini", ]; const formatMessageForO1 = (messages: ChatCompletionMessageParam[]) => { @@ -206,18 +206,25 @@ class OpenAI extends BaseLLM { protected _getEndpoint( endpoint: "chat/completions" | "completions" | "models", ) { - if (this.apiType === "azure") { - return new URL( - `openai/deployments/${this.deployment}/${endpoint}?api-version=${this.apiVersion}`, - this.apiBase, - ); - } if (!this.apiBase) { throw new Error( "No API base URL provided. Please set the 'apiBase' option in config.json", ); } + if (this.apiType?.includes("azure")) { + // Default is `azure-openai`, but previously was `azure` + const isAzureOpenAI = + this.apiType === "azure-openai" || this.apiType === "azure"; + + const path = isAzureOpenAI + ? `openai/deployments/${this.deployment}/${endpoint}` + : endpoint; + + const version = this.apiVersion ? `?api-version=${this.apiVersion}` : ""; + return new URL(`${path}${version}`, this.apiBase); + } + return new URL(endpoint, this.apiBase); } @@ -267,7 +274,7 @@ class OpenAI extends BaseLLM { body.max_completion_tokens = undefined; } - if (body.tools?.length) { + if (body.tools?.length && !body.model?.startsWith("o3")) { // To ensure schema adherence: https://platform.openai.com/docs/guides/function-calling#parallel-function-calling-and-structured-outputs // In practice, setting this to true and asking for multiple tool calls // leads to "arguments" being something like '{"file": "test.ts"}{"file": "test.js"}' diff --git a/core/llm/openaiTypeConverters.ts b/core/llm/openaiTypeConverters.ts index 4ed8be1c4..8e0acef56 100644 --- a/core/llm/openaiTypeConverters.ts +++ b/core/llm/openaiTypeConverters.ts @@ -57,30 +57,34 @@ export function toChatMessage( } return msg; } else { + if (typeof message.content === "string") { + return { + role: "user", + content: message.content ?? " ", // LM Studio (and other providers) don't accept empty content + }; + } + + // If no multi-media is in the message, just send as text + // for compatibility with OpenAI-"compatible" servers + // that don't support multi-media format return { role: "user", - content: - typeof message.content === "string" - ? message.content || " " // LM Studio (and other providers) don't accept empty content - : // If no multi-media is in the message, just send as text - // for compatibility with OpenAI-"compatible" servers - // that don't support multi-media format - message.content.some((item) => item.type !== "text") - ? message.content - .map((item) => (item as TextMessagePart).text) - .join("") || " " - : message.content.map((part) => { - if (part.type === "imageUrl") { - return { - type: "image_url" as const, - image_url: { - url: part.imageUrl.url, - detail: "auto" as const, - }, - }; - } - return part; - }), + content: !message.content.some((item) => item.type !== "text") + ? message.content + .map((item) => (item as TextMessagePart).text) + .join("") || " " + : message.content.map((part) => { + if (part.type === "imageUrl") { + return { + type: "image_url" as const, + image_url: { + url: part.imageUrl.url, + detail: "auto" as const, + }, + }; + } + return part; + }), }; } } diff --git a/core/llm/templates/chat.test.ts b/core/llm/templates/chat.test.ts index fbe84c40f..0bbe087ad 100644 --- a/core/llm/templates/chat.test.ts +++ b/core/llm/templates/chat.test.ts @@ -175,7 +175,7 @@ describe.skip("Chat Templates", () => { ]; const prompt = deepseekTemplateMessages(messages); const expectedPrompt = - "You are an AI programming assistant, utilizing the DeepSeek Coder model, developed by DeepSeek Company, and you only answer questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will refuse to answer.\n### Instruction:\nWhat is polymorphism in OOP?\n### Response:\nExplanation of polymorphism.<|EOT|>\n"; + "You are an AI programming assistant, utilizing the DeepSeek Coder model, developed by DeepSeek Company, and your role is to assist with questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will not answer.\n### Instruction:\nWhat is polymorphism in OOP?\n### Response:\nExplanation of polymorphism.<|EOT|>\n"; expect(prompt).toBe(expectedPrompt); }); }); diff --git a/core/llm/templates/chat.ts b/core/llm/templates/chat.ts index a4b999b05..b205f3d3c 100644 --- a/core/llm/templates/chat.ts +++ b/core/llm/templates/chat.ts @@ -156,7 +156,7 @@ function deepseekTemplateMessages(msgs: ChatMessage[]): string { let prompt = ""; let system: string | null = null; prompt += - "You are an AI programming assistant, utilizing the DeepSeek Coder model, developed by DeepSeek Company, and you only answer questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will refuse to answer.\n"; + "You are an AI programming assistant, utilizing the DeepSeek Coder model, developed by DeepSeek Company, and your role is to assist with questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will not answer.\n"; if (msgs[0].role === "system") { system = renderChatMessage(msgs.shift()!); } diff --git a/core/llm/templates/edit.ts b/core/llm/templates/edit.ts index e6ad4d6b6..aa8433fc4 100644 --- a/core/llm/templates/edit.ts +++ b/core/llm/templates/edit.ts @@ -129,7 +129,7 @@ Sure! Here's the code you requested: `; const deepseekEditPrompt = `### System Prompt -You are an AI programming assistant, utilizing the DeepSeek Coder model, developed by DeepSeek Company, and you only answer questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will refuse to answer. +You are an AI programming assistant, utilizing the DeepSeek Coder model, developed by DeepSeek Company, and your role is to assist with questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will not answer. ### Instruction: Rewrite the code to satisfy this request: "{{{userInput}}}" diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index dd8f72fb0..e1e030467 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -2,6 +2,11 @@ export const PROVIDER_TOOL_SUPPORT: Record< string, (model: string) => boolean | undefined > = { + "continue-proxy": (model) => { + return ["claude-3-5", "claude-3.5", "gpt-4", "o3", "gemini"].some((part) => + model.toLowerCase().startsWith(part), + ); + }, anthropic: (model) => { if ( ["claude-3-5", "claude-3.5"].some((part) => @@ -13,7 +18,10 @@ export const PROVIDER_TOOL_SUPPORT: Record< }, openai: (model) => { // https://platform.openai.com/docs/guides/function-calling#models-supporting-function-calling - if (model.toLowerCase().startsWith("gpt-4")) { + if ( + model.toLowerCase().startsWith("gpt-4") || + model.toLowerCase().startsWith("o3") + ) { return true; } }, diff --git a/core/package-lock.json b/core/package-lock.json index 7edab380e..b6285e5e2 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -13,11 +13,11 @@ "@aws-sdk/client-sagemaker-runtime": "^3.621.0", "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.23", + "@continuedev/config-yaml": "^1.0.31", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", "@continuedev/openai-adapters": "^1.0.10", - "@modelcontextprotocol/sdk": "^1.0.0", + "@modelcontextprotocol/sdk": "^1.5.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", "@typescript-eslint/eslint-plugin": "^7.8.0", @@ -3038,9 +3038,9 @@ } }, "node_modules/@continuedev/config-yaml": { - "version": "1.0.23", - "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.23.tgz", - "integrity": "sha512-F2Hwc85iCwAHJuwJALOsmZIBeHdF+87mS0YT7dlC6QiE+zAhZKUHcLQ/nTt9bJuhyVyufpb9LApkp40UdGsaWw==", + "version": "1.0.31", + "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.31.tgz", + "integrity": "sha512-HNj+z7UTTARgsJTI0A1buM09fS4HoWVnn6Hbl6kJ2tZmOOm1OgogbcKP68AzHb4fy5H18MWnKS7XuseZpHFzHQ==", "dependencies": { "@continuedev/config-types": "^1.0.14", "yaml": "^2.6.1", @@ -4218,13 +4218,34 @@ ] }, "node_modules/@modelcontextprotocol/sdk": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.0.3.tgz", - "integrity": "sha512-2as3cX/VJ0YBHGmdv3GFyTpoM8q2gqE98zh3Vf1NwnsSY0h3mvoO07MUzfygCKkWsFjcZm4otIiqD6Xh7kiSBQ==", + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.5.0.tgz", + "integrity": "sha512-IJ+5iVVs8FCumIHxWqpwgkwOzyhtHVKy45s6Ug7Dv0MfRpaYisH8QQ87rIWeWdOzlk8sfhitZ7HCyQZk7d6b8w==", "dependencies": { "content-type": "^1.0.5", + "eventsource": "^3.0.2", "raw-body": "^3.0.0", - "zod": "^3.23.8" + "zod": "^3.23.8", + "zod-to-json-schema": "^3.24.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@modelcontextprotocol/sdk/node_modules/zod": { + "version": "3.24.1", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.24.1.tgz", + "integrity": "sha512-muH7gBL9sI1nciMZV67X5fTKKBLtwpZ5VBp1vsOQzj1MhrBZ4wlVCm3gedKZWLp0Oyel8sIGfeiz54Su+OVT+A==", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema": { + "version": "3.24.1", + "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.24.1.tgz", + "integrity": "sha512-3h08nf3Vw3Wl3PK+q3ow/lIil81IT2Oa7YpQyUUDsEWbXveMesdfK1xBd2RhCkynwZndAxixji/7SYJJowr62w==", + "peerDependencies": { + "zod": "^3.24.1" } }, "node_modules/@mozilla/readability": { @@ -8313,6 +8334,25 @@ "node": ">=0.8.x" } }, + "node_modules/eventsource": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.5.tgz", + "integrity": "sha512-LT/5J605bx5SNyE+ITBDiM3FxffBiq9un7Vx0EwMDM3vg8sWKx/tO2zC+LMqZ+smAM0F2hblaDZUVZF0te2pSw==", + "dependencies": { + "eventsource-parser": "^3.0.0" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/eventsource-parser": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.0.0.tgz", + "integrity": "sha512-T1C0XCUimhxVQzW4zFipdx0SficT651NnkR0ZSH3yQwh+mFMdLfgjABVi4YtMTtaL4s168593DaoaRLMqryavA==", + "engines": { + "node": ">=18.0.0" + } + }, "node_modules/execa": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", @@ -15520,9 +15560,10 @@ } }, "node_modules/undici": { - "version": "6.21.0", - "resolved": "https://registry.npmjs.org/undici/-/undici-6.21.0.tgz", - "integrity": "sha512-BUgJXc752Kou3oOIuU1i+yZZypyZRqNPW0vqoMPl8VaoalSfeR0D8/t4iAS3yirs79SSMTxTag+ZC86uswv+Cw==", + "version": "6.21.1", + "resolved": "https://registry.npmjs.org/undici/-/undici-6.21.1.tgz", + "integrity": "sha512-q/1rj5D0/zayJB2FraXdaWxbhWiNKDvu8naDT2dl1yTlvJp4BLtOcp2a5BvgGNQpYYJzau7tf1WgKv3b+7mqpQ==", + "license": "MIT", "engines": { "node": ">=18.17" } diff --git a/core/package.json b/core/package.json index 111fbe902..37a5b8a3e 100644 --- a/core/package.json +++ b/core/package.json @@ -46,11 +46,11 @@ "@aws-sdk/client-sagemaker-runtime": "^3.621.0", "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.23", + "@continuedev/config-yaml": "^1.0.31", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", "@continuedev/openai-adapters": "^1.0.10", - "@modelcontextprotocol/sdk": "^1.0.0", + "@modelcontextprotocol/sdk": "^1.5.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", "@typescript-eslint/eslint-plugin": "^7.8.0", diff --git a/core/promptFiles/v1/slashCommandFromPromptFile.ts b/core/promptFiles/v1/slashCommandFromPromptFile.ts index d89ee1082..b0dc0f881 100644 --- a/core/promptFiles/v1/slashCommandFromPromptFile.ts +++ b/core/promptFiles/v1/slashCommandFromPromptFile.ts @@ -25,15 +25,20 @@ async function renderPromptV1( ) { const helpers = getContextProviderHelpers(context); - // A few context providers that don't need to be in config.json to work in .prompt files - const diff = await context.ide.getDiff(true); - const currentFile = await context.ide.getCurrentFile(); const inputData: Record = { - diff: diff.join("\n"), input: userInput, }; - if (currentFile) { - inputData.currentFile = currentFile.path; + + // A few context providers that don't need to be in config.json to work in .prompt files + if (helpers?.find((helper) => helper[0] === "diff")) { + const diff = await context.ide.getDiff(true); + inputData.diff = diff.join("\n"); + } + if (helpers?.find((helper) => helper[0] === "currentFile")) { + const currentFile = await context.ide.getCurrentFile(); + if (currentFile) { + inputData.currentFile = currentFile.path; + } } return renderTemplatedString( diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 64bc5f5d4..96eebce84 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -14,11 +14,11 @@ import type { ContextSubmenuItem, DiffLine, DocsIndexingDetails, + ExperimentalModelRoles, FileSymbolMap, IdeSettings, LLMFullCompletionOptions, ModelDescription, - ModelRoles, PromptLog, RangeInFile, SerializedContinueConfig, @@ -28,12 +28,7 @@ import type { ToolCall, } from "../"; -export type OnboardingModes = - | "Local" - | "Best" - | "Custom" - | "Quickstart" - | "LocalAfterFreeTrial"; +export type OnboardingModes = "Local" | "Best" | "Custom" | "Quickstart"; export interface ListHistoryOptions { offset?: number; @@ -57,7 +52,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { "config/addModel": [ { model: SerializedContinueConfig["models"][number]; - role?: keyof ModelRoles; + role?: keyof ExperimentalModelRoles; }, void, ]; @@ -67,13 +62,13 @@ export type ToCoreFromIdeOrWebviewProtocol = { undefined, { result: ConfigResult; - profileId: string; + profileId: string | null; }, ]; "config/deleteModel": [{ title: string }, void]; "config/addContextProvider": [ContextProviderWithParams, void]; "config/reload": [undefined, ConfigResult]; - "config/listProfiles": [undefined, ProfileDescription[]]; + "config/listProfiles": [undefined, ProfileDescription[] | null]; "config/openProfile": [{ profileId: string | undefined }, void]; "config/updateSharedConfig": [SharedConfigSchema, void]; "context/getContextItems": [ @@ -189,14 +184,12 @@ export type ToCoreFromIdeOrWebviewProtocol = { "docs/getDetails": [{ startUrl: string }, DocsIndexingDetails]; addAutocompleteModel: [{ model: ModelDescription }, void]; - "profiles/switch": [{ id: string }, undefined]; - - "auth/getAuthUrl": [undefined, { url: string }]; + "auth/getAuthUrl": [{ useOnboarding: boolean }, { url: string }]; "tools/call": [ { toolCall: ToolCall; selectedModelTitle: string }, { contextItems: ContextItem[] }, ]; "clipboardCache/add": [{ content: string }, void]; - "controlPlane/openUrl": [{ path: string }, void]; + "controlPlane/openUrl": [{ path: string; orgSlug: string | undefined }, void]; "controlPlane/listOrganizations": [undefined, OrganizationDescription[]]; }; diff --git a/core/protocol/coreWebview.ts b/core/protocol/coreWebview.ts index 1622b4be5..67b5919a4 100644 --- a/core/protocol/coreWebview.ts +++ b/core/protocol/coreWebview.ts @@ -4,8 +4,12 @@ import { ToCoreFromIdeOrWebviewProtocol } from "./core.js"; import { ToWebviewFromIdeOrCoreProtocol } from "./webview.js"; export type ToCoreFromWebviewProtocol = ToCoreFromIdeOrWebviewProtocol & { - didChangeSelectedProfile: [{ id: string }, void]; + didChangeSelectedProfile: [{ id: string | null }, void]; + didChangeSelectedOrg: [{ id: string | null }, void]; }; export type ToWebviewFromCoreProtocol = ToWebviewFromIdeOrCoreProtocol & { - didChangeAvailableProfiles: [{ profiles: ProfileDescription[] }, void]; + didChangeAvailableProfiles: [ + { profiles: ProfileDescription[]; selectedProfileId: string | null }, + void, + ]; }; diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 9cc19504d..3598e06ea 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -79,10 +79,6 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { navigateTo: [{ path: string; toggle?: boolean }, void]; addModel: [undefined, void]; - /** - * @deprecated Use navigateTo with a path instead. - */ - viewHistory: [undefined, void]; focusContinueSessionId: [{ sessionId: string | undefined }, void]; newSession: [undefined, void]; setTheme: [{ theme: any }, void]; diff --git a/core/protocol/messenger/index.ts b/core/protocol/messenger/index.ts index 8b7245224..fb2528ae2 100644 --- a/core/protocol/messenger/index.ts +++ b/core/protocol/messenger/index.ts @@ -21,7 +21,7 @@ export interface IMessenger< ToProtocol extends IProtocol, FromProtocol extends IProtocol, > { - onError(handler: (error: Error) => void): void; + onError(handler: (message: Message, error: Error) => void): void; send( messageType: T, data: FromProtocol[T][0], @@ -64,9 +64,9 @@ export class InProcessMessenger< (message: Message) => any >(); - protected _onErrorHandlers: ((error: Error) => void)[] = []; + protected _onErrorHandlers: ((message: Message, error: Error) => void)[] = []; - onError(handler: (error: Error) => void) { + onError(handler: (message: Message, error: Error) => void) { this._onErrorHandlers.push(handler); } diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index edf079157..f0c66f465 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -57,8 +57,8 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = // "completeOnboarding", "addAutocompleteModel", - "profiles/switch", "didChangeSelectedProfile", + "didChangeSelectedOrg", "tools/call", "controlPlane/openUrl", "controlPlane/listOrganizations", @@ -81,7 +81,5 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = "setTTSActive", "getWebviewHistoryLength", "getCurrentSessionId", - "signInToControlPlane", - "openDialogMessage", "docs/suggestions", ]; diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index 822d9b532..90df4bd0f 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -12,7 +12,7 @@ export type ToWebviewFromIdeOrCoreProtocol = { configUpdate: [ { result: ConfigResult; - profileId: string; + profileId: string | null; }, void, ]; @@ -37,7 +37,6 @@ export type ToWebviewFromIdeOrCoreProtocol = { setTTSActive: [boolean, void]; getWebviewHistoryLength: [undefined, number]; getCurrentSessionId: [undefined, string]; - signInToControlPlane: [undefined, void]; - openDialogMessage: ["account", void]; "docs/suggestions": [PackageDocsResult[], void]; + "jetbrains/setColors": [Record, void]; }; diff --git a/core/test/fixtures.ts b/core/test/fixtures.ts index 4f8601303..ae54b03db 100644 --- a/core/test/fixtures.ts +++ b/core/test/fixtures.ts @@ -18,7 +18,7 @@ export const testConfigHandler = new ConfigHandler( testIde, ideSettingsPromise, async (text) => {}, - testControlPlaneClient, + Promise.resolve(undefined), ); export const testLLM = new Mock({ diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts index 706fa57d9..f3b565285 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -1,4 +1,4 @@ -import { ContextItem, ToolExtras } from ".."; +import { ContextItem, Tool, ToolExtras } from ".."; import { MCPManagerSingleton } from "../context/mcp"; import { BuiltInToolNames } from "./builtIn"; @@ -86,13 +86,18 @@ async function callToolFromUri( throw new Error(`Failed to call tool: ${toolName}`); } - return (response.content as any).map((item: any) => { + return (response.content as any).map((item: any): ContextItem => { if (item.type !== "text") { throw new Error( `Continue received item of type "${item.type}" from MCP tool, but currently only supports "text".`, ); } - return { name: toolName, description: toolName, content: item.text }; + return { + name: extras.tool.displayTitle, + description: "Tool output", + content: item.text, + icon: extras.tool.faviconUrl, + }; }); default: @@ -101,10 +106,12 @@ async function callToolFromUri( } export async function callTool( - uri: string, + tool: Tool, args: any, extras: ToolExtras, ): Promise { + const uri = tool.uri ?? tool.function.name; + switch (uri) { case BuiltInToolNames.ReadFile: return await readFileImpl(args, extras); diff --git a/core/tools/implementations/readCurrentlyOpenFile.ts b/core/tools/implementations/readCurrentlyOpenFile.ts index d0db3b60c..a55aee2bd 100644 --- a/core/tools/implementations/readCurrentlyOpenFile.ts +++ b/core/tools/implementations/readCurrentlyOpenFile.ts @@ -1,4 +1,4 @@ -import { getUriPathBasename } from "../../util/uri"; +import { getUriDescription } from "../../util/uri"; import { ToolImpl } from "."; @@ -9,13 +9,16 @@ export const readCurrentlyOpenFileImpl: ToolImpl = async (args, extras) => { return []; } - const basename = getUriPathBasename(result.path); + const { relativePathOrBasename, last2Parts, baseName } = getUriDescription( + result.path, + await extras.ide.getWorkspaceDirs(), + ); return [ { - name: "Current file", - description: basename, - content: `\`\`\`${basename}\n${result.contents}\n\`\`\``, + name: `Current file: ${baseName}`, + description: last2Parts, + content: `\`\`\`${relativePathOrBasename}\n${result.contents}\n\`\`\``, uri: { type: "file", value: result.path, diff --git a/core/tools/implementations/viewRepoMap.ts b/core/tools/implementations/viewRepoMap.ts index 69f624feb..9d7c44809 100644 --- a/core/tools/implementations/viewRepoMap.ts +++ b/core/tools/implementations/viewRepoMap.ts @@ -5,7 +5,7 @@ import { ToolImpl } from "."; export const viewRepoMapImpl: ToolImpl = async (args, extras) => { const repoMap = await generateRepoMap(extras.llm, extras.ide, { outputRelativeUriPaths: true, - includeSignatures: false, + includeSignatures: true, }); return [ { diff --git a/core/util/GlobalContext.ts b/core/util/GlobalContext.ts index 90b403d41..34c3d8ddf 100644 --- a/core/util/GlobalContext.ts +++ b/core/util/GlobalContext.ts @@ -7,11 +7,18 @@ import { } from "../config/sharedConfig"; import { getGlobalContextFilePath } from "./paths"; +import { SiteIndexingConfig } from ".."; export type GlobalContextType = { indexingPaused: boolean; selectedTabAutocompleteModel: string; - lastSelectedProfileForWorkspace: { [workspaceIdentifier: string]: string }; + lastSelectedProfileForWorkspace: { + [workspaceIdentifier: string]: string | null; + }; + lastSelectedOrgIdForWorkspace: { + [workspaceIdentifier: string]: string | null; + }; + /** * This is needed to handle the case where a JetBrains user has created * docs embeddings using one provider, and then updates to a new provider. @@ -23,6 +30,7 @@ export type GlobalContextType = { showConfigUpdateToast: boolean; isSupportedLanceDbCpuTarget: boolean; sharedConfig: SharedConfigSchema; + failedDocs: SiteIndexingConfig[]; }; /** diff --git a/core/util/ideUtils.ts b/core/util/ideUtils.ts index 9ed4a47fc..352aad6ca 100644 --- a/core/util/ideUtils.ts +++ b/core/util/ideUtils.ts @@ -34,10 +34,11 @@ export async function resolveRelativePathInDir( If no meaninful path match just concatenates to first dir's uri */ export async function inferResolvedUriFromRelativePath( - relativePath: string, + _relativePath: string, ide: IDE, dirCandidates?: string[], ): Promise { + const relativePath = _relativePath.trim().replaceAll("\\", "/"); const dirs = dirCandidates ?? (await ide.getWorkspaceDirs()); if (dirs.length === 0) { @@ -51,7 +52,7 @@ export async function inferResolvedUriFromRelativePath( suffixes.push(segments.slice(i).join("/")); } - // For each suffix, try to find a unique matching directory + // For each suffix, try to find a unique matching dir/file for (const suffix of suffixes) { const uris = dirs.map((dir) => ({ dir, @@ -78,6 +79,13 @@ export async function inferResolvedUriFromRelativePath( } } + // Sometimes the model will decide to only output the base name or small number of path parts + // in which case we shouldn't create a new file if it matches the current file + const activeFile = await ide.getCurrentFile(); + if (activeFile && activeFile.path.endsWith(relativePath)) { + return activeFile.path; + } + // If no unique match found, use the first directory return joinPathsToUri(dirs[0], relativePath); } diff --git a/core/util/index.test.ts b/core/util/index.test.ts index 74ee3ccc8..fc48a49b2 100644 --- a/core/util/index.test.ts +++ b/core/util/index.test.ts @@ -207,7 +207,7 @@ World it("should handle strings with only whitespace", () => { const result = dedent` - + `; expect(result).toBe(""); }); @@ -249,9 +249,9 @@ World it("should handle a string with only one non-empty line", () => { const result = dedent` - + Hello World! - + `; expect(result).toBe("Hello World!"); }); @@ -373,11 +373,16 @@ describe("getMarkdownLanguageTagForFile", () => { expect(getMarkdownLanguageTagForFile("test.py")).toBe("python"); expect(getMarkdownLanguageTagForFile("test.tsx")).toBe("tsx"); expect(getMarkdownLanguageTagForFile("test.java")).toBe("java"); + expect(getMarkdownLanguageTagForFile("test.class")).toBe("java"); expect(getMarkdownLanguageTagForFile("test.md")).toBe("markdown"); expect(getMarkdownLanguageTagForFile("test.sh")).toBe("shell"); expect(getMarkdownLanguageTagForFile("test.sql")).toBe("sql"); }); + it("should sanitize ranges from the extension", () => { + expect(getMarkdownLanguageTagForFile("test.java (1-5)")).toBe("java"); + }); + it("should return the extension if not in the known list", () => { expect(getMarkdownLanguageTagForFile("file.unknownext")).toBe("unknownext"); }); diff --git a/core/util/index.ts b/core/util/index.ts index 04dc6d567..4cb0f4920 100644 --- a/core/util/index.ts +++ b/core/util/index.ts @@ -74,6 +74,7 @@ export function getMarkdownLanguageTagForFile(filepath: string): string { tsx: "tsx", ts: "typescript", java: "java", + class:"java", //.class files decompile to Java go: "go", rb: "ruby", rs: "rust", @@ -96,17 +97,28 @@ export function getMarkdownLanguageTagForFile(filepath: string): string { ps1: "powershell", }; - const ext = filepath.split(".").pop(); + const ext = sanitizeExtension(filepath.split(".").pop()); return ext ? (extToLangMap[ext] ?? ext) : ""; } + +function sanitizeExtension(ext?: string): string|undefined { + if (ext) { + //ignore ranges in extension eg. "java (11-23)" + const match = ext.match(/^(\S+)\s*(\(.*\))?$/); + if (match) { + ext = match[1]; + } + } + return ext; +} + export function copyOf(obj: any): any { if (obj === null || obj === undefined) { return obj; } return JSON.parse(JSON.stringify(obj)); } -``; export function deduplicateArray( array: T[], diff --git a/core/util/ollamaHelper.ts b/core/util/ollamaHelper.ts index 1e9c52490..a00e869dd 100644 --- a/core/util/ollamaHelper.ts +++ b/core/util/ollamaHelper.ts @@ -11,7 +11,7 @@ export async function isOllamaInstalled(): Promise { }); } -export async function startLocalOllama(ide: IDE): Promise { +export async function startLocalOllama(ide: IDE): Promise { let startCommand: string | undefined; switch (process.platform) { @@ -20,16 +20,16 @@ export async function startLocalOllama(ide: IDE): Promise { break; case "win32"://Windows - startCommand = `& "ollama app.exe"\n`; + startCommand = "& \"ollama app.exe\"\n"; break; default: //Linux... - const start_script_path = path.resolve(__dirname, './start_ollama.sh'); + const start_script_path = path.resolve(__dirname, "./start_ollama.sh"); if (await ide.fileExists(`file:/${start_script_path}`)) { startCommand = `set -e && chmod +x ${start_script_path} && ${start_script_path}\n`; console.log(`Ollama Linux startup script at : ${start_script_path}`); } else { - ide.showToast("error", `Cannot start Ollama: could not find ${start_script_path}!`) + return ide.showToast("error", `Cannot start Ollama: could not find ${start_script_path}!`) } } if (startCommand) { diff --git a/core/util/parameters.ts b/core/util/parameters.ts index 648253712..05ab61e06 100644 --- a/core/util/parameters.ts +++ b/core/util/parameters.ts @@ -18,6 +18,10 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { useImports: true, transform: true, showWhateverWeHaveAtXMs: 300, + experimental_includeClipboard: true, + experimental_includeRecentlyVisitedRanges: true, + experimental_includeRecentlyEditedRanges: true, + experimental_includeDiff: true, }; export const COUNT_COMPLETION_REJECTED_AFTER = 10_000; diff --git a/core/util/paths.ts b/core/util/paths.ts index 1198dec49..a8861befa 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -377,6 +377,10 @@ export function getEsbuildBinaryPath(): string { return path.join(getContinueUtilsPath(), "esbuild"); } +export function getStagingEnvironmentDotFilePath(): string { + return path.join(getContinueGlobalPath(), ".staging"); +} + export function setupInitialDotContinueDirectory() { const devDataTypes = [ "chat", diff --git a/core/util/uri.ts b/core/util/uri.ts index a1bcd7745..13d7956ac 100644 --- a/core/util/uri.ts +++ b/core/util/uri.ts @@ -177,3 +177,19 @@ export function getLastNPathParts(filepath: string, n: number): string { } return filepath.split(/[\\/]/).slice(-n).join("/"); } + +export function getUriDescription(uri: string, dirUriCandidates: string[]) { + const { relativePathOrBasename, foundInDir } = findUriInDirs( + uri, + dirUriCandidates, + ); + const baseName = getUriPathBasename(uri); + const last2Parts = getLastNUriRelativePathParts(dirUriCandidates, uri, 2); + return { + uri, + relativePathOrBasename, + foundInDir, + last2Parts, + baseName, + }; +} diff --git a/docs/docs/actions/context-selection.md b/docs/docs/actions/context-selection.md index a63eeda38..4e154dcd3 100644 --- a/docs/docs/actions/context-selection.md +++ b/docs/docs/actions/context-selection.md @@ -7,7 +7,7 @@ sidebar_position: 3 ## Slash commands -Slash commands can be combined with additional instructions, including [context providers](chat/context-selection.md) or [highlighted code](chat/context-selection.md). +Slash commands can be combined with additional instructions, including [context providers](../customize/context-providers.mdx) or [highlighted code](../edit/context-selection#highlighted-code). For example, with the “/edit” slash command you should describe the edit that you want the LLM to perform. diff --git a/docs/docs/actions/how-it-works.md b/docs/docs/actions/how-it-works.mdx similarity index 84% rename from docs/docs/actions/how-it-works.md rename to docs/docs/actions/how-it-works.mdx index 57afa90ea..90bd4bb20 100644 --- a/docs/docs/actions/how-it-works.md +++ b/docs/docs/actions/how-it-works.mdx @@ -7,6 +7,6 @@ sidebar_position: 4 While many Actions are based on templated prompts and can be customized with .prompt files, there are a number that execute more complex code under the hood. -Actions that generate inline diffs, like “/edit”, “/comment”, or right click actions, use the same prompt and response processing logic as [Edit](edit/how-it-works.md). +Actions that generate inline diffs, like “/edit”, “/comment”, or right click actions, use the same prompt and response processing logic as [Edit](../edit/how-it-works.md). -To learn how other slash commands work, see the full reference [here](../customize/slash-commands.md). +To learn how other slash commands work, see the full reference [here](../customize/slash-commands.mdx). diff --git a/docs/docs/actions/how-to-customize.md b/docs/docs/actions/how-to-customize.md index 0541bf464..9153a38b0 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](../reference.md) 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](../json-reference.md) and add them to the `slashCommands` array. ## Custom slash commands @@ -18,11 +18,6 @@ There are two ways to add custom slash commands: ### Custom Slash Commands with `config.ts` - - - 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`. To do this, push a new `SlashCommand` object to the `slashCommands` list. This object contains "name", the name that you will type to invoke the slash command, "description", the description seen in the dropdown menu, and "run". The `run` function is any async generator that should yield strings as you want them to be streamed to the UI. As an argument to the function, you have access to a `ContinueSDK` object with utilities such as access to certain information/actions within the IDE, the current language model, and a few other utilities. For example, here is a slash command that generates a commit message: @@ -51,9 +46,6 @@ export function modifyConfig(config: Config): Config { } ``` - - - ## Other custom actions Currently the other action triggers are not open for configuration, but we plan to allow this via .prompt files in the future. diff --git a/docs/docs/actions/how-to-use-it.md b/docs/docs/actions/how-to-use-it.md index 5be83b2e7..018a7c941 100644 --- a/docs/docs/actions/how-to-use-it.md +++ b/docs/docs/actions/how-to-use-it.md @@ -18,7 +18,7 @@ The most common way to invoke an action is with a slash command. These are short ![slash-commands](/img/slash-commands.png) -A few of the most useful slash commands are available by default, like “/edit”, “/comment”, and “/share”, but Continue has a large built-in library of other options. To enable these, learn more [here](../customize/slash-commands.md). +A few of the most useful slash commands are available by default, like “/edit”, “/comment”, and “/share”, but Continue has a large built-in library of other options. To enable these, learn more [here](../customize/slash-commands.mdx). ### Prompt files @@ -36,7 +36,7 @@ Below is a quick example of setting up a prompt file to write unit tests using J 2. Add a file called `test.prompt` to this folder. The name of this file will be the name of the slash command you will use to generate your prompt. 3. Write the following contents to `test.prompt` and save. -``` +```.prompt {{{ input }}} Write unit tests for the above selected code, following each of these instructions: diff --git a/docs/docs/autocomplete/how-it-works.md b/docs/docs/autocomplete/how-it-works.md index 9d87819b3..c97b71c03 100644 --- a/docs/docs/autocomplete/how-it-works.md +++ b/docs/docs/autocomplete/how-it-works.md @@ -16,7 +16,7 @@ In order to display suggestions quickly, without sending too many requests, we d ## Context -As explained on the [context selection](context-selection.md) page, Continue uses a number of retrieval methods to find relevant snippets from your codebase to include in the prompt. +As explained on the [context selection](./context-selection.md) page, Continue uses a number of retrieval methods to find relevant snippets from your codebase to include in the prompt. ## Filtering @@ -28,4 +28,4 @@ Language models aren't perfect, but can be made much closer by adjusting their o We will also occasionally entirely filter out responses if they are bad. This is often due to extreme repetition. -You can learn more about how it works in the [Autocomplete deep dive](../customize/deep-dives/autocomplete.md). +You can learn more about how it works in the [Autocomplete deep dive](../customize/deep-dives/autocomplete.mdx). diff --git a/docs/docs/autocomplete/how-to-customize.md b/docs/docs/autocomplete/how-to-customize.md index ccd1dca9d..abf4c5b11 100644 --- a/docs/docs/autocomplete/how-to-customize.md +++ b/docs/docs/autocomplete/how-to-customize.md @@ -5,18 +5,20 @@ keywords: [customize] sidebar_position: 5 --- -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: +Continue offers a handful of parameters in [`config.json`](../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": { - "maxPromptTokens": 400, - "prefixPercentage": 0.5, - "multilineCompletions": "always" - } +{ + "tabAutocompleteOptions": { + "maxPromptTokens": 400, + "prefixPercentage": 0.5, + "multilineCompletions": "always" + } +} ``` - `maxPromptTokens`: Sets the maximum number of tokens for the prompt, balancing context and speed. - `prefixPercentage`: Defines the proportion of the prompt dedicated to the code before the cursor. - `multilineCompletions`: Controls whether suggestions can span multiple lines ("always", "never", or "auto"). -For a comprehensive guide on all configuration options and their impacts, see the [Autocomplete deep dive](../customize/deep-dives/autocomplete.md). +For a comprehensive guide on all configuration options and their impacts, see the [Autocomplete deep dive](../customize/deep-dives/autocomplete.mdx). diff --git a/docs/docs/autocomplete/model-setup.md b/docs/docs/autocomplete/model-setup.md deleted file mode 100644 index 7d8c98944..000000000 --- a/docs/docs/autocomplete/model-setup.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -title: Model setup -description: Autocomplete \-model setup -keywords: [model, autocomplete] -sidebar_position: 2 ---- - -:::info -This page recommends models and providers for Autocomplete. Read more about how to set up your `config.json` [here](../reference.md). -::: - -## Best overall experience - -For the best Autocomplete experience, we recommend using Codestral through the [Mistral API](https://console.mistral.ai/). This model offers high-quality completions with an excellent understanding of code context: - -```json title="config.json"" -{ - "tabAutocompleteModel": { - "title": "Codestral", - "provider": "mistral", - "model": "codestral-latest", - "apiKey": "YOUR_API_KEY" - } -} -``` - -:::tip[Codestral API Key] -The API keys for Codestral and the general Mistral APIs are different. If you are using Codestral, you probably want a Codestral API key, but if you are sharing the key as a team or otherwise want to use `api.mistral.ai`, then make sure to set `"apiBase": "https://api.mistral.ai/v1"` in your `tabAutocompleteModel`. -::: - -## Local, offline / self-hosted experience - -For those preferring local execution or self-hosting,`Qwen2.5-Coder 1.5B` offers a good balance of performance and quality for most users (e.g. using [Ollama](../customize/model-providers/top-level/ollama.md) or [LM Studio](../customize/model-providers/more/lmstudio.md)). - -```json title="config.json"" -{ - "tabAutocompleteModel": { - "title": "Qwen2.5-Coder 1.5B", - "model": "qwen2.5-coder:1.5b-base", - "provider": "ollama" - } -} -``` - -Have more compute? Use `qwen2.5-coder:7b-base` for potentially higher-quality suggestions. - -:::note - -For LM Studio users, navigate to the "My Models" section, find your desired model, and copy the path (e.g., `Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF/qwen2.5-coder-1.5b-instruct-q4_k_m.gguf`). Use this path as the `model` value in your configuration. - -::: -### Using a remote instance - -When using a remote instance you need to set the `"apiBase"` value in the configuration: - -```json title="config.json"" -{ - "tabAutocompleteModel": { - "title": "Qwen2.5-Coder 1.5B", - "model": "qwen2.5-coder:1.5b-base", - "provider": "ollama" - "apiBase": "http://:11434" - } -} -``` -## Other experiences - -There are many more models and providers you can use with Autocomplete. Check them out [here](../customize/model-types/autocomplete.md). You can also see more examples of Autocomplete configuration [here](../customize/deep-dives/autocomplete.md) diff --git a/docs/docs/autocomplete/model-setup.mdx b/docs/docs/autocomplete/model-setup.mdx new file mode 100644 index 000000000..8d37d39be --- /dev/null +++ b/docs/docs/autocomplete/model-setup.mdx @@ -0,0 +1,115 @@ +--- +title: Model setup +description: Autocomplete \-model setup +keywords: [model, autocomplete] +sidebar_position: 2 +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +:::info +This page recommends models and providers for Autocomplete. Read more about how to set up your `config.yaml` [here](../reference.md). +::: + +## Best overall experience + +For the best Autocomplete experience, we recommend using Codestral through the [Mistral API](https://console.mistral.ai/). This model offers high-quality completions with an excellent understanding of code context: + + + + ```yaml title="config.yaml" + models: + - name: Codestral + provider: mistral + model: codestral-latest + apiKey: + roles: + - autocomplete + ``` + + + ```json title="config.json" + { + "tabAutocompleteModel": { + "title": "Codestral", + "provider": "mistral", + "model": "codestral-latest", + "apiKey": "" + } + } + ``` + + + +:::tip[Codestral API Key] +The API keys for Codestral and the general Mistral APIs are different. If you are using Codestral, you probably want a Codestral API key, but if you are sharing the key as a team or otherwise want to use `api.mistral.ai`, then make sure to set `"apiBase": "https://api.mistral.ai/v1"` in your `tabAutocompleteModel`. +::: + +## Local, offline / self-hosted experience + +For those preferring local execution or self-hosting,`Qwen2.5-Coder 1.5B` offers a good balance of performance and quality for most users (e.g. using [Ollama](../customize/model-providers/top-level/ollama.mdx) or [LM Studio](../customize/model-providers/more/lmstudio.mdx)). + + + + ```yaml title="config.yaml" + models: + - name: Qwen2.5-Coder 1.5B + model: qwen2.5-coder:1.5b-base + provider: ollama + roles: + - autocomplete + ``` + + + ```json title="config.json" + { + "tabAutocompleteModel": { + "title": "Qwen2.5-Coder 1.5B", + "model": "qwen2.5-coder:1.5b-base", + "provider": "ollama" + } + } + ``` + + + +Have more compute? Use `qwen2.5-coder:7b-base` for potentially higher-quality suggestions. + +:::note +For LM Studio users, navigate to the "My Models" section, find your desired model, and copy the path (e.g., `Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF/qwen2.5-coder-1.5b-instruct-q4_k_m.gguf`). Use this path as the `model` value in your configuration. +::: + +### Using a remote instance + +When using a remote instance you need to set the `"apiBase"` value in the configuration: + + + + ```yaml title="config.yaml" + models: + - name: Qwen2.5-Coder 1.5B + model: qwen2.5-coder:1.5b-base + provider: ollama + apiBase: http://:11434 + roles: + - autocomplete + ``` + + + ```json title="config.json" + { + "tabAutocompleteModel": { + "title": "Qwen2.5-Coder 1.5B", + "model": "qwen2.5-coder:1.5b-base", + "provider": "ollama", + "apiBase": "http://:11434" + } + } + ``` + + + +## Other experiences + +There are many more models and providers you can use with Autocomplete. Check them out [here](../customize/model-types/autocomplete.md). You can also see more examples of Autocomplete configuration [here](../customize/deep-dives/autocomplete.mdx) diff --git a/docs/docs/chat/context-selection.md b/docs/docs/chat/context-selection.md index e4c35ddc5..65b76c72a 100644 --- a/docs/docs/chat/context-selection.md +++ b/docs/docs/chat/context-selection.md @@ -19,28 +19,28 @@ You can include the currently open file as context by pressing opt + ## Specific file -You can include a specific file in your current workspace as context by typing [`@Files`](../customize/context-providers.md#file) and selecting the file. +You can include a specific file in your current workspace as context by typing [`@Files`](../customize/context-providers.mdx#file) and selecting the file. ## Specific folder -You can include a folder in your current workspace as context by typing [`@Folder`](../customize/context-providers.md#folder) and selecting the directory. It [works like `@Codebase`](../customize/deep-dives/codebase.md) but only includes the files in the selected folder. +You can include a folder in your current workspace as context by typing [`@Folder`](../customize/context-providers.mdx#folder) and selecting the directory. It [works like `@Codebase`](../customize/deep-dives/codebase.mdx) but only includes the files in the selected folder. ## Codebase search -You can automatically include relevant files from your codebase as context by typing [`@Codebase`](../customize/context-providers.md#codebase). You can learn about how @Codebase works [here](../customize/deep-dives/codebase.md). +You can automatically include relevant files from your codebase as context by typing [`@Codebase`](../customize/context-providers.mdx#codebase). You can learn about how @Codebase works [here](../customize/deep-dives/codebase.mdx). ## Documentation site -You can include a documentation site as context by typing [`@Docs`](../customize/context-providers.md#docs) and selecting the documentation site. You can learn about how @Docs works [here](../customize/deep-dives/docs.md). +You can include a documentation site as context by typing [`@Docs`](../customize/context-providers.mdx#docs) and selecting the documentation site. You can learn about how @Docs works [here](../customize/deep-dives/docs.mdx). ## Terminal contents -You can include the contents of the terminal in your IDE as context by typing [`@Terminal`](../customize/context-providers.md#terminal). +You can include the contents of the terminal in your IDE as context by typing [`@Terminal`](../customize/context-providers.mdx#terminal). ## Git diff -You can include all of the changes you've made to your current branch by typing [`@Git Diff`](../customize/context-providers.md#git-diff). +You can include all of the changes you've made to your current branch by typing [`@Git Diff`](../customize/context-providers.mdx#git-diff). ## Other context -You can see a full list of built-in context providers [here](../customize/context-providers.md) and how to create your own custom context provider [here](../customize/tutorials/build-your-own-context-provider.md). +You can see a full list of built-in context providers [here](../customize/context-providers.mdx) and how to create your own custom context provider [here](../customize/tutorials/build-your-own-context-provider.md). diff --git a/docs/docs/chat/how-it-works.md b/docs/docs/chat/how-it-works.md index 84c81582e..92b6e75f9 100644 --- a/docs/docs/chat/how-it-works.md +++ b/docs/docs/chat/how-it-works.md @@ -9,6 +9,6 @@ Using any selected code sections, all context that you have selected with @, and The model response is then streamed directly back to the sidebar. Each code section included in the response will be placed into its own code block, which gives you buttons to either “Apply to current file”, “Insert at cursor”, or “Copy” for each section. When you press cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains) at the end of a session, all context is cleared and a new session is started, so that you can begin a new task. -If you would like to view the exact prompt that is sent to the model during Chat, you can [view this in the prompt logs](troubleshooting.md#llm-prompt-logs). +If you would like to view the exact prompt that is sent to the model during Chat, you can [view this in the prompt logs](troubleshooting.mdx#llm-prompt-logs). -You can learn more about how `@Codebase` works [here](../customize/deep-dives/codebase.md) and `@Docs` [here](../customize/deep-dives/docs.md). +You can learn more about how `@Codebase` works [here](../customize/deep-dives/codebase.mdx) and `@Docs` [here](../customize/deep-dives/docs.mdx). diff --git a/docs/docs/chat/how-to-customize.md b/docs/docs/chat/how-to-customize.md index ee26a6a84..3fcb7376f 100644 --- a/docs/docs/chat/how-to-customize.md +++ b/docs/docs/chat/how-to-customize.md @@ -8,8 +8,8 @@ sidebar_position: 5 There are a number of different ways to customize Chat - You can add a [`.continuerules`](../customize/deep-dives/rules.md) file to the root of your project to customize the system prompt -- You can configure [`@Codebase`](../customize/deep-dives/codebase.md) -- You can create your own [custom code RAG](../customize/tutorials/custom-code-rag.md) -- You can configure [`@Docs`](../customize/deep-dives/docs.md) +- You can configure [`@Codebase`](../customize/deep-dives/codebase.mdx) +- You can create your own [custom code RAG](../customize/tutorials/custom-code-rag.mdx) +- You can configure [`@Docs`](../customize/deep-dives/docs.mdx) - You can [build your own context provider](../customize/tutorials/build-your-own-context-provider.md) -- You can configure and create custom [tools](../customize/tools.md) +- You can configure and create custom [tools](../customize/tools.mdx) diff --git a/docs/docs/chat/model-setup.mdx b/docs/docs/chat/model-setup.mdx index 327f780d0..52dac63a2 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](../reference.md). +This page recommends models and providers for Chat. Read more about how to set up your config [here](../reference.md). ::: ## Best overall experience @@ -18,116 +18,226 @@ For the best overall Chat experience, you will want to use a 400B+ parameter mod ### Claude Sonnet 3.5 from Anthropic -Our current top recommendation is Claude Sonnet 3.5 from [Anthropic](../customize/model-providers/top-level/anthropic.md). +Our current top recommendation is Claude Sonnet 3.5 from [Anthropic](../customize/model-providers/top-level/anthropic.mdx). -```json title="config.json" - "models": [ - { - "title": "Claude 3.5 Sonnet", - "provider": "anthropic", - "model": "claude-3-5-sonnet-latest", - "apiKey": "[ANTHROPIC_API_KEY]" - } - ] -``` + + + ```yaml title="Package or config.yaml" + models: + - name: Claude 3.5 Sonnet + provider: anthropic + model: claude-3-5-sonnet-latest + apiKey: + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Claude 3.5 Sonnet", + "provider": "anthropic", + "model": "claude-3-5-sonnet-latest", + "apiKey": "" + } + ] + } + ``` + + ### Llama 3.1 405B from Meta -If you prefer to use an open-weight model, then Llama 3.1 405B from Meta is your best option right now. You will need to decide if you use it through a SaaS model provider (e.g. [Together](../customize/model-providers/more/together.md) or [Groq](../customize/model-providers/more/groq.md)) or self-host it (e.g. using [vLLM](../customize/model-providers//more/vllm.md) or [Ollama](../customize/model-providers/top-level/ollama.md)). +If you prefer to use an open-weight model, then Llama 3.1 405B from Meta is your best option right now. You will need to decide if you use it through a SaaS model provider (e.g. [Together](../customize/model-providers/more/together.mdx) or [Groq](../customize/model-providers/more/groq.mdx)) or self-host it (e.g. using [vLLM](../customize/model-providers//more/vllm.mdx) or [Ollama](../customize/model-providers/top-level/ollama.mdx)). - - - ```json title="config.json" - "models": [ - { - "title": "Llama 3.1 405B", - "provider": "together", - "model": "llama3.1-405b", - "apiKey": "[TOGETHER_API_KEY]" - } - ] + + + + + ```yaml title="Package or config.yaml" + models: + - name: "Llama 3.1 405B" + provider: "together" + model: "llama3.1-405b" + apiKey: ``` - - - ```json title="config.json" - "models": [ - { - "title": "Llama 3.1 405B", - "provider": "groq", - "model": "llama3.1-405b", - "apiKey": "[GROQ_API_KEY]" - } - ] + + + ```yaml title="Package or config.yaml" + models: + - name: "Llama 3.1 405B" + provider: "groq" + model: "llama3.1-405b" + apiKey: ``` - - - ```json title="config.json" - "models": [ - { - "title": "Llama 3.1 405B", - "provider": "vllm", - "model": "llama3.1-405b" - } - ] + + + ```yaml title="Package or config.yaml" + models: + - name: "Llama 3.1 405B" + provider: "vllm" + model: "llama3.1-405b" ``` - - - ```json title="config.json" - "models": [ - { - "title": "Llama 3.1 405B", - "provider": "ollama", - "model": "llama3.1:405b" - } - ] + + + ```yaml title="Package or config.yaml" + models: + - name: "Llama 3.1 405B" + provider: "ollama" + model: "llama3.1:405b" ``` - + + + + + + + ```json title="config.json" + { + "models": [ + { + "title": "Llama 3.1 405B", + "provider": "together", + "model": "llama3.1-405b", + "apiKey": "" + } + ] + } + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Llama 3.1 405B", + "provider": "groq", + "model": "llama3.1-405b", + "apiKey": "" + } + ] + } + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Llama 3.1 405B", + "provider": "vllm", + "model": "llama3.1-405b" + } + ] + } + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Llama 3.1 405B", + "provider": "ollama", + "model": "llama3.1:405b" + } + ] + } + ``` + + + ### GPT-4o from OpenAI -If you prefer to use a model from [OpenAI](../customize/model-providers/top-level/openai.md), then we recommend GPT-4o. +If you prefer to use a model from [OpenAI](../customize/model-providers/top-level/openai.mdx), then we recommend GPT-4o. -```json title="config.json" - "models": [ - { - "title": "GPT-4o", - "provider": "openai", - "model": "", - "apiKey": "[OPENAI_API_KEY]" - } - ] -``` + + + ```yaml title="Package or config.yaml" + models: + - name: GPT-4o + provider: openai + model: '' + apiKey: + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "GPT-4o", + "provider": "openai", + "model": "", + "apiKey": "" + } + ] + } + ``` + + ### Grok-2 from xAI -If you prefer to use a model from [xAI](../customize/model-providers/top-level/xAI.md), then we recommend Grok-2. +If you prefer to use a model from [xAI](../customize/model-providers/top-level/xAI.mdx), then we recommend Grok-2. -```json title="config.json" - "models": [ - { - "title": "Grok-2", - "provider": "xAI", - "model": "grok-2-latest", - "apiKey": "[XAI_API_KEY]" - } - ] -``` + + + ```yaml title="Package or config.yaml" + models: + - name: Grok-2 + provider: xAI + model: grok-2-latest + apiKey: + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Grok-2", + "provider": "xAI", + "model": "grok-2-latest", + "apiKey": "" + } + ] + } + ``` + + ### Gemini 1.5 Pro from Google -If you prefer to use a model from [Google](../customize/model-providers/top-level/gemini.md), then we recommend Gemini 1.5 Pro. +If you prefer to use a model from [Google](../customize/model-providers/top-level/gemini.mdx), then we recommend Gemini 1.5 Pro. -```json title="config.json" - "models": [ - { - "title": "Gemini 1.5 Pro", - "provider": "gemini", - "model": "gemini-1.5-pro-latest", - "apiKey": "[GEMINI_API_KEY]" - } - ] -``` + + + ```yaml title="Package or config.yaml" + models: + - name: Gemini 1.5 Pro + provider: gemini + model: gemini-1.5-pro-latest + apiKey: + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Gemini 1.5 Pro", + "provider": "gemini", + "model": "gemini-1.5-pro-latest", + "apiKey": "" + } + ] + } + ``` + + ## Local, offline experience @@ -135,65 +245,117 @@ For the best local, offline Chat experience, you will want to use a model that i ### Llama 3.1 8B -If your local machine can run an 8B parameter model, then we recommend running Llama 3.1 8B on your machine (e.g. using [Ollama](../customize/model-providers/top-level/ollama.md) or [LM Studio](../customize/model-providers/more/lmstudio.md)). +If your local machine can run an 8B parameter model, then we recommend running Llama 3.1 8B on your machine (e.g. using [Ollama](../customize/model-providers/top-level/ollama.mdx) or [LM Studio](../customize/model-providers/more/lmstudio.mdx)). - - - ```json title="config.json" - "models": [ - { - "title": "Llama 3.1 8B", - "provider": "ollama", - "model": "llama3.1:8b", - "apiBase": "http://localhost:11434" - } - ] - ``` - - - ```json title="config.json" - "models": [ - { - "title": "Llama 3.1 8B", - "provider": "lmstudio", - "model": "llama3.1-8b" - } - ] - ``` - + + + + + ```yaml title="Package or config.yaml" + models: + - name: Llama 3.1 8B + provider: ollama + model: llama3.1:8b + ``` + + + ```yaml title="Package or config.yaml" + models: + - name: Llama 3.1 8B + provider: lmstudio + model: llama3.1:8b + ``` + + + + + + + ```json title="config.json" + { + "models": [ + { + "title": "Llama 3.1 8B", + "provider": "ollama", + "model": "llama3.1:8b" + } + ] + } + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Llama 3.1 8B", + "provider": "lmstudio", + "model": "llama3.1-8b" + } + ] + } + ``` + + + ### DeepSeek Coder 2 16B -If your local machine can run a 16B parameter model, then we recommend running DeepSeek Coder 2 16B (e.g. using [Ollama](../customize/model-providers/top-level/ollama.md) or [LM Studio](../customize/model-providers/more/lmstudio.md)). +If your local machine can run a 16B parameter model, then we recommend running DeepSeek Coder 2 16B (e.g. using [Ollama](../customize/model-providers/top-level/ollama.mdx) or [LM Studio](../customize/model-providers/more/lmstudio.mdx)). - - - ```json title="config.json" - "models": [ - { - "title": "DeepSeek Coder 2 16B", - "provider": "ollama", - "model": "deepseek-coder-v2:16b", - "apiBase": "http://localhost:11434" - } - ] + + + + + ```yaml title="Package or config.yaml" + models: + - name: DeepSeek Coder 2 16B + provider: ollama + model: deepseek-coder-v2:16b ``` - - - - - ```json title="config.json" - "models": [ - { - "title": "DeepSeek Coder 2 16B", - "provider": "lmstudio", - "model": "deepseek-coder-v2:16b" - } - ] + + + ```yaml title="Package or config.yaml" + models: + - name: DeepSeek Coder 2 16B + provider: lmstudio + model: deepseek-coder-v2:16b ``` - - + + + + + + + ```json title="config.json" + { + "models": [ + { + "title": "DeepSeek Coder 2 16B", + "provider": "ollama", + "model": "deepseek-coder-v2:16b", + "apiBase": "http://localhost:11434" + } + ] + } + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "DeepSeek Coder 2 16B", + "provider": "lmstudio", + "model": "deepseek-coder-v2:16b" + } + ] + } + ``` + + + ## Other experiences diff --git a/docs/docs/customize/context-providers.md b/docs/docs/customize/context-providers.md deleted file mode 100644 index d49b38c93..000000000 --- a/docs/docs/customize/context-providers.md +++ /dev/null @@ -1,676 +0,0 @@ ---- -title: Context providers -description: Type '@' to select content to the LLM as context -keywords: [context, "@", provider, LLM] ---- - -Context Providers allow you to type '@' and see a dropdown of content that can all be fed to the LLM as context. Every context provider is a plugin, which means if you want to reference some source of information that you don't see here, you can request (or build!) a new context provider. - -As an example, say you are working on solving a new GitHub Issue. You type '@Issue' and select the one you are working on. Continue can now see the issue title and contents. You also know that the issue is related to the files 'readme.md' and 'helloNested.py', so you type '@readme' and '@hello' to find and select them. Now these 3 "Context Items" are displayed inline with the rest of your input. - -![Context Items](/img/context-provider-example.png) - -## Built-in Context Providers - -To use any of the built-in context providers, open `config.json` and add it to the `contextProviders` list. - -### `@File` - -Reference any file in your current workspace. - -```json title="config.json" -{ - "contextProviders": [ - { - "name": "file" - } - ] -} -``` - -### `@Code` - -Reference specific functions or classes from throughout your project. - -```json title="config.json" -{ - "contextProviders": [ - { - "name": "code" - } - ] -} -``` - -### `@Git Diff` - -Reference all of the changes you've made to your current branch. This is useful if you want to summarize what you've done or ask for a general review of your work before committing. - -```json title="config.json" -{ - "contextProviders": [ - { - "name": "diff" - } - ] -} -``` - -### `@Current File` - -Reference the currently open file. - -```json title="config.json" -{ - "contextProviders": [ - { - "name": "currentFile" - } - ] -} -``` - -### `@Terminal` - -Reference the last command you ran in your IDE's terminal and its output. - -```json title="config.json" -{ - "contextProviders": [ - { - "name": "terminal" - } - ] -} -``` - -### `@Docs` - -Reference the contents from any documentation site. - -```json title="config.json" -{ - "contextProviders": [ - { - "name": "docs" - } - ] -} -``` - -Note that this will only enable the `@Docs` context provider. - -To use it, you need to add a documentation site to your `config.json`. See the [docs](../customize/deep-dives/docs.md) page for more information. - -### `@Open` - -Reference the contents of all of your open files. Set `onlyPinned` to `true` to only reference pinned files. - -```json title="config.json" -{ - "contextProviders": [ - { - "name": "open", - "params": { - "onlyPinned": true - } - } - ] -} -``` - -### `@Web` - -Reference relevant pages from across the web, automatically determined from your input. - -Optionally, set "n" to limit the number of results returned (default 6). - -```json title="config.json" -{ - "contextProviders": [ - { - "name": "web", - "params": { - "n": 5 - } - } - ] -} -``` - -### `@Codebase` - -Reference the most relevant snippets from your codebase. - -```json title="config.json" -{ - "contextProviders": [ - { - "name": "codebase" - } - ] -} -``` - -Read more about indexing and retrieval [here](../customize/deep-dives/codebase.md). - -### `@Folder` - -Uses the same retrieval mechanism as `@Codebase`, but only on a single folder. - -```json title="config.json" -{ - "contextProviders": [ - { - "name": "folder" - } - ] -} -``` - -### `@Search` - -Reference the results of codebase search, just like the results you would get from VS Code search. - -```json title="config.json" -{ - "contextProviders": [ - { - "name": "search" - } - ] -} -``` - -This context provider is powered by [ripgrep](https://github.com/BurntSushi/ripgrep). - -### `@Url` - -Reference the markdown converted contents of a given URL. - -```json title="config.json" -{ - "contextProviders": [ - { - "name": "url" - } - ] -} -``` - -### `@Clipboard` - -Reference recent clipboard items - -```json title="config.json" -{ - "contextProviders": [ - { - "name": "clipboard" - } - ] -} -``` - -### `@Tree` - -Reference the structure of your current workspace. - -```json title="config.json" -{ - "contextProviders": [ - { - "name": "tree" - } - ] -} -``` - -### `@Problems` - -Get Problems from the current file. - -```json title="config.json" -{ - "contextProviders": [ - { - "name": "problems" - } - ] -} -``` - -### `@Debugger` - -Reference the contents of the local variables in the debugger. Currently only available in VS Code. - -```json title="config.json" -{ - "contextProviders": [ - { - "name": "debugger", - "params": { - "stackDepth": 3 - } - } - ] -} -``` - -Uses the top _n_ levels (defaulting to 3) of the call stack for that thread. - -### `@Repository Map` - -Reference the outline of your codebase. By default, signatures are included along with file in the repo map. - -`includeSignatures` params can be set to false to exclude signatures. This could be necessary for large codebases and/or to reduce context size significantly. Signatures will not be included if indexing is disabled. - -```json title="config.json" -{ - "contextProviders": [ - { - "name": "repo-map", - "params": { - "includeSignatures": false // default true - } - } - ] -} -``` - -Provides a list of files and the call signatures of top-level classes, functions, and methods in those files. This helps the model better understand how a particular piece of code relates to the rest of the codebase. - -In the submenu that appears, you can select either `Entire codebase`, or specify a subfolder to generate the repostiory map from. - -This context provider is inpsired by [Aider's repository map](https://aider.chat/2023/10/22/repomap.html). - -### `@Operating System` - -Reference the architecture and platform of your current operating system. - -```json title="config.json" -{ - "contextProviders": [ - { - "name": "os" - } - ] -} -``` - -### Model Context Protocol - -The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports any MCP server with the MCP context provider. Read their [quickstart](https://modelcontextprotocol.io/quickstart) to learn how to set up a local server and then configure your `config.json` like this: - -```json -{ - "experimental": { - "modelContextProtocolServers": [ - { - "transport": { - "type": "stdio", - "command": "uvx", - "args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"] - } - } - ] - } -} -``` - -You'll then be able to type "@" and see "MCP" in the context providers dropdown. - -### Prompt Files - -See [Prompt Files](/customize/deep-dives/prompt-files). Prompt files are not added directly to the config file; prompt files are parsed and injected into the config automatically, to be used like other context providers. - -### `@Issue` - -Reference the conversation in a GitHub issue. - -```json title="config.json" -{ - "contextProviders": [ - { - "name": "issue", - "params": { - "repos": [ - { - "owner": "continuedev", - "repo": "continue" - } - ], - "githubToken": "ghp_xxx" - } - } - ] -} -``` - -Make sure to include your own [GitHub personal access token](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#creating-a-fine-grained-personal-access-token) to avoid being rate-limited. - -### `@Database` - -Reference table schemas from Sqlite, Postgres, MSSQL, and MySQL databases. - -```json title="config.json" -{ - "contextProviders": [ - { - "name": "database", - "params": { - "connections": [ - { - "name": "examplePostgres", - "connection_type": "postgres", - "connection": { - "user": "username", - "host": "localhost", - "database": "exampleDB", - "password": "yourPassword", - "port": 5432 - } - }, - { - "name": "exampleMssql", - "connection_type": "mssql", - "connection": { - "user": "username", - "server": "localhost", - "database": "exampleDB", - "password": "yourPassword" - } - }, - { - "name": "exampleSqlite", - "connection_type": "sqlite", - "connection": { - "filename": "/path/to/your/sqlite/database.db" - } - } - ] - } - } - ] -} -``` - -Each connection should include a unique name, the `connection_type`, and the necessary connection parameters specific to each database type. - -Available connection types: - -- `postgres` -- `mysql` -- `sqlite` - -### `@Postgres` - -Reference the schema of a table, and some sample rows - -```json title="config.json" -{ - "contextProviders": [ - { - "name": "postgres", - "params": { - "host": "localhost", - "port": 5436, - "user": "myuser", - "password": "catsarecool", - "database": "animals", - "schema": "public", - "sampleRows": 3 - } - } - ] -} -``` - -The only required settings are those for creating the database connection: `host`, `port`, `user`, `password`, and `database`. - -By default, the `schema` filter is set to `public`, and the `sampleRows` is set to 3. You may unset the schema if you want to include tables from all schemas. - -[Here is a short demo.](https://github.com/continuedev/continue/pull/859) - -### `@Google` - -Reference the results of a Google search. - -```json title="config.json" -{ - "contextProviders": [ - { - "name": "google", - "params": { - "serperApiKey": "" - } - } - ] -} -``` - -For example, type "@Google python tutorial" if you want to search and discuss ways of learning Python. - -Note: You can get an API key for free at [serper.dev](https://serper.dev). - -### `@Gitlab Merge Request` - -Reference an open MR for this branch on GitLab. - -```json title="config.json" -{ - "contextProviders": [ - { - "name": "gitlab-mr", - "params": { - "token": "..." - } - } - ] -} -``` - -You will need to create a [personal access token](https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html) with the `read_api` scope. - -#### Using Self-Hosted GitLab - -You can specify the domain to communicate with by setting the `domain` parameter in your configurtion. By default this is set to `gitlab.com`. - -```json title="config.json" -{ - "contextProviders": [ - { - "name": "gitlab-mr", - "params": { - "token": "...", - "domain": "gitlab.example.com" - } - } - ] -} -``` - -#### Filtering Comments - -If you select some code to be edited, you can have the context provider filter out comments for other files. To enable this feature, set `filterComments` to `true`. - -### `@Jira` - -Reference the conversation in a Jira issue. - -```json title="config.json" -{ - "contextProviders": [ - { - "name": "jira", - "params": { - "domain": "company.atlassian.net", - "token": "ATATT..." - } - } - ] -} -``` - -Make sure to include your own [Atlassian API Token](https://id.atlassian.com/manage-profile/security/api-tokens), or use your `email` and `token`, with token set to your password for basic authentication. If you use your own Atlassian API Token, don't configure your email. - -#### Jira Datacenter Support - -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. - -```json title="config.json" -{ - "contextProviders": [ - { - "name": "jira", - "params": { - "apiVersion": "2" - } - } - ] -} -``` - -#### Issue Query - -By default, the following query will be used to find issues: - -```jql -assignee = currentUser() AND resolution = Unresolved order by updated DESC -``` - -You can override this query by setting the `issueQuery` parameter. - -### `@Discord` - -Reference the messages in a Discord channel. - -```json title="config.json" -{ - "contextProviders": [ - { - "name": "discord", - "params": { - "discordKey": "bot token", - "guildId": "1234567890", - "channels": [ - { - "id": "123456", - "name": "example-channel" - }, - { - "id": "678901", - "name": "example-channel-2" - } - ] - } - } - ] -} -``` - -Make sure to include your own [Bot Token](https://discord.com/developers/applications), and join it to your related server . If you want more granular control over which channels are searched, you can specify a list of channel IDs to search in. If you don't want to specify any channels, just include the guild id(Server ID) and all channels will be included. The provider only reads text channels. - -### `@HTTP` - -The HttpContextProvider makes a POST request to the url passed in the configuration. The server must return 200 OK with a ContextItem object or an array of ContextItems. - -```json title="config.json" -{ - "contextProviders": [ - { - "name": "http", - "params": { - "url": "https://api.example.com/v1/users" - } - } - ] -} -``` - -The receiving URL should expect to receive the following parameters: - -```js title="POST parameters" -{ - query: string, - fullInput: string -} -``` - -The response 200 OK should be a JSON object with the following structure: - -```json title="Response" -[ - { - "name": "", - "description": "", - "content": "" - } -] - -// OR -{ - "name": "", - "description": "", - "content": "" -} -``` - -### `@Commits` - -Reference specific git commit metadata and diff or all of the recent commits. - -```json title="config.json" -{ - "contextProviders": [ - { - "name": "commit", - "params": { - "Depth": 50, - "LastXCommitsDepth": 10 - } - } - ] -} -``` - -The depth is how many commits will be loaded into the submenu, defaults to 50. -The LastXCommitsDepth is how many recent commits will be included, defaults to 10. - -### `@Clipboard` - -Reference recent clipboard items - -```json title="config.json" -{ - "contextProviders": [ - { - "name": "clipboard" - } - ] -} -``` - -### `@Greptile` - -Query a [Greptile](https://www.greptile.com/) index of the current repo/branch. - -```json title="config.json" -{ - "contextProviders": [ - { - "name": "greptile", - "params": { - "GreptileToken": "...", - "GithubToken": "..." - } - } - ] -} -``` - -### Requesting Context Providers - -Not seeing what you want? Create an issue [here](https://github.com/continuedev/continue/issues/new?assignees=TyDunn&labels=enhancement&projects=&template=feature-request-%F0%9F%92%AA.md&title=) to request a new Context Provider. diff --git a/docs/docs/customize/context-providers.mdx b/docs/docs/customize/context-providers.mdx new file mode 100644 index 000000000..fe64a473f --- /dev/null +++ b/docs/docs/customize/context-providers.mdx @@ -0,0 +1,1050 @@ +--- +title: Context providers +description: Type '@' to select content to the LLM as context +keywords: [context, "@", provider, LLM] +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +Context Providers allow you to type '@' and see a dropdown of content that can all be fed to the LLM as context. Every context provider is a plugin, which means if you want to reference some source of information that you don't see here, you can request (or build!) a new context provider. + +As an example, say you are working on solving a new GitHub Issue. You type '@Issue' and select the one you are working on. Continue can now see the issue title and contents. You also know that the issue is related to the files 'readme.md' and 'helloNested.py', so you type '@readme' and '@hello' to find and select them. Now these 3 "Context Items" are displayed inline with the rest of your input. + +![Context Items](/img/context-provider-example.png) + +## Built-in Context Providers + +You can add any built-in context-providers in your config file as shown below: + +### `@File` + +Reference any file in your current workspace. + + + + ```yaml title="Package or config.yaml" + context: + - provider: file + ``` + + + ```json title="config.json" + { + "contextProviders": [ + { + "name": "file" + } + ] + } + ``` + + + +### `@Code` + +Reference specific functions or classes from throughout your project. + + + + ```yaml title="Package or config.yaml" + context: + - provider: code + ``` + + + ```json title="config.json" + { + "contextProviders": [ + { + "name": "code" + } + ] + } + ``` + + + +### `@Git Diff` + +Reference all of the changes you've made to your current branch. This is useful if you want to summarize what you've done or ask for a general review of your work before committing. + + + + ```yaml title="Package or config.yaml" + context: + - provider: diff + ``` + + + ```json title="config.json" + { + "contextProviders": [ + { + "name": "diff" + } + ] + } + ``` + + + +### `@Current File` + +Reference the currently open file. + + + + ```yaml title="Package or config.yaml" + context: + - provider: currentFile + ``` + + + ```json title="config.json" + { + "contextProviders": [ + { + "name": "currentFile" + } + ] + } + ``` + + + +### `@Terminal` + +Reference the last command you ran in your IDE's terminal and its output. + + + + ```yaml title="Package or config.yaml" + context: + - provider: terminal + ``` + + + ```json title="config.json" + { + "contextProviders": [ + { + "name": "terminal" + } + ] + } + ``` + + + +### `@Docs` + +Reference the contents from any documentation site. + + + + ```yaml title="Package or config.yaml" + context: + - provider: docs + ``` + + + ```json title="config.json" + { + "contextProviders": [ + { + "name": "docs" + } + ] + } + ``` + + + +Note that this will only enable the `@Docs` context provider. + +To use it, you need to add a documentation site to your config file. See the [docs](../customize/deep-dives/docs.mdx) page for more information. + +### `@Open` + +Reference the contents of all of your open files. Set `onlyPinned` to `true` to only reference pinned files. + + + + ```yaml title="Package or config.yaml" + context: + - provider: open + params: + onlyPinned: true + ``` + + + ```json title="config.json" + { + "contextProviders": [ + { + "name": "open", + "params": { + "onlyPinned": true + } + } + ] + } + ``` + + + +### `@Web` + +Reference relevant pages from across the web, automatically determined from your input. + +Optionally, set `n` to limit the number of results returned (default 6). + + + + ```yaml title="Package or config.yaml" + context: + - provider: web + params: + n: 5 + ``` + + + ```json title="config.json" + { + "contextProviders": [ + { + "name": "web", + "params": { + "n": 5 + } + } + ] + } + ``` + + + +### `@Codebase` + +Reference the most relevant snippets from your codebase. + + + + ```yaml title="Package or config.yaml" + context: + - provider: codebase + ``` + + + ```json title="config.json" + { + "contextProviders": [ + { + "name": "codebase" + } + ] + } + ``` + + + +Read more about indexing and retrieval [here](../customize/deep-dives/codebase.mdx). + +### `@Folder` + +Uses the same retrieval mechanism as `@Codebase`, but only on a single folder. + + + + ```yaml title="Package or config.yaml" + context: + - provider: folder + ``` + + + ```json title="config.json" + { + "contextProviders": [ + { + "name": "folder" + } + ] + } + ``` + + + +### `@Search` + +Reference the results of codebase search, just like the results you would get from VS Code search. + + + + ```yaml title="Package or config.yaml" + context: + - provider: search + ``` + + + ```json title="config.json" + { + "contextProviders": [ + { + "name": "search" + } + ] + } + ``` + + + +This context provider is powered by [ripgrep](https://github.com/BurntSushi/ripgrep). + +### `@Url` + +Reference the markdown converted contents of a given URL. + + + + ```yaml title="Package or config.yaml" + context: + - provider: url + ``` + + + ```json title="config.json" + { + "contextProviders": [ + { + "name": "url" + } + ] + } + ``` + + + +### `@Clipboard` + +Reference recent clipboard items + + + + ```yaml title="Package or config.yaml" + context: + - provider: clipboard + ``` + + + ```json title="config.json" + { + "contextProviders": [ + { + "name": "clipboard" + } + ] + } + ``` + + + +### `@Tree` + +Reference the structure of your current workspace. + + + + ```yaml title="Package or config.yaml" + context: + - provider: tree + ``` + + + ```json title="config.json" + { + "contextProviders": [ + { + "name": "tree" + } + ] + } + ``` + + + +### `@Problems` + +Get Problems from the current file. + + + + ```yaml title="Package or config.yaml" + context: + - provider: problems + ``` + + + ```json title="config.json" + { + "contextProviders": [ + { + "name": "problems" + } + ] + } + ``` + + + +### `@Debugger` + +Reference the contents of the local variables in the debugger. Currently only available in VS Code. + + + + ```yaml title="Package or config.yaml" + context: + - provider: debugger + params: + stackDepth: 3 + ``` + + + ```json title="config.json" + { + "contextProviders": [ + { + "name": "debugger", + "params": { + "stackDepth": 3 + } + } + ] + } + ``` + + + +Uses the top _n_ levels (defaulting to 3) of the call stack for that thread. + +### `@Repository Map` + +Reference the outline of your codebase. By default, signatures are included along with file in the repo map. + +`includeSignatures` params can be set to false to exclude signatures. This could be necessary for large codebases and/or to reduce context size significantly. Signatures will not be included if indexing is disabled. + + + + ```yaml title="Package or config.yaml" + context: + - provider: repo-map + params: + includeSignatures: false # default true + ``` + + + ```json title="config.json" + { + "contextProviders": [ + { + "name": "repo-map", + "params": { + "includeSignatures": false // default true + } + } + ] + } + ``` + + + +Provides a list of files and the call signatures of top-level classes, functions, and methods in those files. This helps the model better understand how a particular piece of code relates to the rest of the codebase. + +In the submenu that appears, you can select either `Entire codebase`, or specify a subfolder to generate the repostiory map from. + +This context provider is inpsired by [Aider's repository map](https://aider.chat/2023/10/22/repomap.html). + +### `@Operating System` + +Reference the architecture and platform of your current operating system. + + + + ```yaml title="Package or config.yaml" + context: + - provider: os + ``` + + + ```json title="config.json" + { + "contextProviders": [ + { + "name": "os" + } + ] + } + ``` + + + +### Model Context Protocol + +The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports any MCP server with the MCP context provider. Read their [quickstart](https://modelcontextprotocol.io/quickstart) to learn how to set up a local server and then set up your configuration like this: + + + + ```yaml title="Package or config.yaml" + mcpServers: + - name: My MCP Server + command: uvx + args: + - mcp-server-sqlite + - --db-path + - /Users/NAME/test.db + ``` + + + ```json title="config.json" + { + "experimental": { + "modelContextProtocolServers": [ + { + "transport": { + "type": "stdio", + "command": "uvx", + "args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"] + } + } + ] + } + } + ``` + + + +You'll then be able to type "@" and see "MCP" in the context providers dropdown. + +### Prompt Files + +See [Prompt Files](./deep-dives/prompt-files.md). Prompt files are not added directly to the config file; prompt files are parsed and injected into the config automatically, to be used like other context providers. + +### `@Issue` + +Reference the conversation in a GitHub issue. + + + + ```yaml title="Package or config.yaml" + context: + - provider: issue + params: + repos: + - owner: continuedev + repo: continue + githubToken: ghp_xxx + ``` + + + ```json title="config.json" + { + "contextProviders": [ + { + "name": "issue", + "params": { + "repos": [ + { + "owner": "continuedev", + "repo": "continue" + } + ], + "githubToken": "ghp_xxx" + } + } + ] + } + ``` + + + +Make sure to include your own [GitHub personal access token](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#creating-a-fine-grained-personal-access-token) to avoid being rate-limited. + +### `@Database` + +Reference table schemas from Sqlite, Postgres, MSSQL, and MySQL databases. + + + + ```yaml title="Package or config.yaml" + context: + - provider: database + params: + connections: + - name: examplePostgres + connection_type: postgres + connection: + user: username + host: localhost + database: exampleDB + password: yourPassword + port: 5432 + - name: exampleMssql + connection_type: mssql + connection: + user: username + server: localhost + database: exampleDB + password: yourPassword + - name: exampleSqlite + connection_type: sqlite + connection: + filename: /path/to/your/sqlite/database.db + ``` + + + ```json title="config.json" + { + "contextProviders": [ + { + "name": "database", + "params": { + "connections": [ + { + "name": "examplePostgres", + "connection_type": "postgres", + "connection": { + "user": "username", + "host": "localhost", + "database": "exampleDB", + "password": "yourPassword", + "port": 5432 + } + }, + { + "name": "exampleMssql", + "connection_type": "mssql", + "connection": { + "user": "username", + "server": "localhost", + "database": "exampleDB", + "password": "yourPassword" + } + }, + { + "name": "exampleSqlite", + "connection_type": "sqlite", + "connection": { + "filename": "/path/to/your/sqlite/database.db" + } + } + ] + } + } + ] + } + ``` + + + +Each connection should include a unique name, the `connection_type`, and the necessary connection parameters specific to each database type. + +Available connection types: + +- `postgres` +- `mysql` +- `sqlite` + +### `@Postgres` + +Reference the schema of a table, and some sample rows + + + + ```yaml title="Package or config.yaml" + context: + - provider: postgres + params: + host: localhost + port: 5436 + user: myuser + password: catsarecool + database: animals + schema: public + sampleRows: 3 + ``` + + + ```json title="config.json" + { + "contextProviders": [ + { + "name": "postgres", + "params": { + "host": "localhost", + "port": 5436, + "user": "myuser", + "password": "catsarecool", + "database": "animals", + "schema": "public", + "sampleRows": 3 + } + } + ] + } + ``` + + + +The only required settings are those for creating the database connection: `host`, `port`, `user`, `password`, and `database`. + +By default, the `schema` filter is set to `public`, and the `sampleRows` is set to 3. You may unset the schema if you want to include tables from all schemas. + +[Here is a short demo.](https://github.com/continuedev/continue/pull/859) + +### `@Google` + +Reference the results of a Google search. + + + + ```yaml title="Package or config.yaml" + context: + - provider: google + params: + serperApiKey: + ``` + + + ```json title="config.json" + { + "contextProviders": [ + { + "name": "google", + "params": { + "serperApiKey": "" + } + } + ] + } + ``` + + + +For example, type "@Google python tutorial" if you want to search and discuss ways of learning Python. + +Note: You can get an API key for free at [serper.dev](https://serper.dev). + +### `@Gitlab Merge Request` + +Reference an open MR for this branch on GitLab. + + + + ```yaml title="Package or config.yaml" + context: + - provider: gitlab-mr + params: + token: "..." + ``` + + + ```json title="config.json" + { + "contextProviders": [ + { + "name": "gitlab-mr", + "params": { + "token": "..." + } + } + ] + } + ``` + + + +You will need to create a [personal access token](https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html) with the `read_api` scope. + +#### Using Self-Hosted GitLab + +You can specify the domain to communicate with by setting the `domain` parameter in your configurtion. By default this is set to `gitlab.com`. + + + + ```yaml title="Package or config.yaml" + context: + - provider: gitlab-mr + params: + token: "..." + domain: "gitlab.example.com" + ``` + + + ```json title="config.json" + { + "contextProviders": [ + { + "name": "gitlab-mr", + "params": { + "token": "...", + "domain": "gitlab.example.com" + } + } + ] + } + ``` + + + +#### Filtering Comments + +If you select some code to be edited, you can have the context provider filter out comments for other files. To enable this feature, set `filterComments` to `true`. + +### `@Jira` + +Reference the conversation in a Jira issue. + + + + ```yaml title="Package or config.yaml" + context: + - provider: jira + params: + domain: company.atlassian.net + token: ATATT... + ``` + + + ```json title="config.json" + { + "contextProviders": [ + { + "name": "jira", + "params": { + "domain": "company.atlassian.net", + "token": "ATATT..." + } + } + ] + } + ``` + + + +Make sure to include your own [Atlassian API Token](https://id.atlassian.com/manage-profile/security/api-tokens), or use your `email` and `token`, with token set to your password for basic authentication. If you use your own Atlassian API Token, don't configure your email. + +#### Jira Datacenter Support + +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. + + + + ```yaml title="Package or config.yaml" + context: + - provider: jira + params: + apiVersion: "2" + ``` + + + ```json title="config.json" + { + "contextProviders": [ + { + "name": "jira", + "params": { + "apiVersion": "2" + } + } + ] + } + ``` + + + +#### Issue Query + +By default, the following query will be used to find issues: + +```jql +assignee = currentUser() AND resolution = Unresolved order by updated DESC +``` + +You can override this query by setting the `issueQuery` parameter. + +### `@Discord` + +Reference the messages in a Discord channel. + + + + ```yaml title="Package or config.yaml" + context: + - provider: discord + params: + discordKey: "bot token" + guildId: "1234567890" + channels: + - id: "123456" + name: "example-channel" + - id: "678901" + name: "example-channel-2" + ``` + + + ```json title="config.json" + { + "contextProviders": [ + { + "name": "discord", + "params": { + "discordKey": "bot token", + "guildId": "1234567890", + "channels": [ + { + "id": "123456", + "name": "example-channel" + }, + { + "id": "678901", + "name": "example-channel-2" + } + ] + } + } + ] + } + ``` + + + +Make sure to include your own [Bot Token](https://discord.com/developers/applications), and join it to your related server . If you want more granular control over which channels are searched, you can specify a list of channel IDs to search in. If you don't want to specify any channels, just include the guild id(Server ID) and all channels will be included. The provider only reads text channels. + +### `@HTTP` + +The HttpContextProvider makes a POST request to the url passed in the configuration. The server must return 200 OK with a ContextItem object or an array of ContextItems. + + + + ```yaml title="Package or config.yaml" + context: + - provider: http + params: + url: "https://api.example.com/v1/users" + ``` + + + ```json title="config.json" + { + "contextProviders": [ + { + "name": "http", + "params": { + "url": "https://api.example.com/v1/users" + } + } + ] + } + ``` + + + +The receiving URL should expect to receive the following parameters: + +```js title="POST parameters" +{ + query: string, + fullInput: string +} +``` + +The response 200 OK should be a JSON object with the following structure: + +```json title="Response" +[ + { + "name": "", + "description": "", + "content": "" + } +] + +// OR +{ + "name": "", + "description": "", + "content": "" +} +``` + +### `@Commits` + +Reference specific git commit metadata and diff or all of the recent commits. + + + + ```yaml title="Package or config.yaml" + context: + - provider: commit + params: + Depth: 50 + LastXCommitsDepth: 10 + ``` + + + ```json title="config.json" + { + "contextProviders": [ + { + "name": "commit", + "params": { + "Depth": 50, + "LastXCommitsDepth": 10 + } + } + ] + } + ``` + + + +The depth is how many commits will be loaded into the submenu, defaults to 50. +The LastXCommitsDepth is how many recent commits will be included, defaults to 10. + +### `@Greptile` + +Query a [Greptile](https://www.greptile.com/) index of the current repo/branch. + + + + ```yaml title="Package or config.yaml" + context: + - provider: greptile + params: + greptileToken: "..." + githubToken: "..." + ``` + + + ```json title="config.json" + { + "contextProviders": [ + { + "name": "greptile", + "params": { + "GreptileToken": "...", + "GithubToken": "..." + } + } + ] + } + ``` + + + +### Requesting Context Providers + +Not seeing what you want? Create an issue [here](https://github.com/continuedev/continue/issues/new?assignees=TyDunn&labels=enhancement&projects=&template=feature-request-%F0%9F%92%AA.md&title=) to request a new Context Provider. diff --git a/docs/docs/customize/deep-dives/autocomplete.md b/docs/docs/customize/deep-dives/autocomplete.mdx similarity index 79% rename from docs/docs/customize/deep-dives/autocomplete.md rename to docs/docs/customize/deep-dives/autocomplete.mdx index 8d90f2145..6713e4653 100644 --- a/docs/docs/customize/deep-dives/autocomplete.md +++ b/docs/docs/customize/deep-dives/autocomplete.mdx @@ -3,20 +3,38 @@ title: Autocomplete keywords: [autocomplete] --- +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + ### Setting up with Codestral (recommended) -If you want to have the best autocomplete experience, we recommend using Codestral, which is available through the [Mistral API](https://console.mistral.ai/). To do this, obtain an API key and add it to your `config.json`: +If you want to have the best autocomplete experience, we recommend using Codestral, which is available through the [Mistral API](https://console.mistral.ai/). To do this, obtain an API key and add it to your config: -```json -{ - "tabAutocompleteModel": { - "title": "Codestral", - "provider": "mistral", - "model": "codestral-latest", - "apiKey": "YOUR_API_KEY" + + + ```yaml title="config.yaml" + models: + - name: Codestral + provider: mistral + model: codestral-latest + apiKey: + roles: + - autocomplete + ``` + + + ```json title="config.json" + { + "tabAutocompleteModel": { + "title": "Codestral", + "provider": "mistral", + "model": "codestral-latest", + "apiKey": "" + } } -} -``` + ``` + + ### Setting up with Ollama (default) @@ -32,17 +50,31 @@ Once it has been downloaded, you should begin to see completions in VS Code. All of the configuration options available for chat models are available to use for tab-autocomplete. For example, if you wanted to use a remote Ollama instance you would edit your `config.json` like this (note that it is not inside the models array): -```json title="config.json" -{ + + + ```yaml title="config.yaml" + models: + - name: Tab Autocomplete Model + provider: ollama + model: qwen2.5-coder:1.5b-base + apiBase: https:// + roles: + - autocomplete + ``` + + + ```json title="config.json" + { "tabAutocompleteModel": { - "title": "Tab Autocomplete Model", - "provider": "ollama", - "model": "qwen2.5-coder:1.5b-base", - "apiBase": "https://" - }, - ... -} -``` + "title": "Tab Autocomplete Model", + "provider": "ollama", + "model": "qwen2.5-coder:1.5b-base", + "apiBase": "https://" + } + } + ``` + + If you aren't yet familiar with the available options, you can find the full reference [here](./configuration.md). @@ -70,21 +102,36 @@ This object allows you to customize the behavior of tab-autocomplete. The availa ### Full example -```json title="config.json" -{ - "tabAutocompleteModel": { - "title": "Tab Autocomplete Model", - "provider": "ollama", - "model": "qwen2.5-coder:1.5b-base", - "apiBase": "https://" - }, - "tabAutocompleteOptions": { - "debounceDelay": 500, - "maxPromptTokens": 1500, - "disableInFiles": ["*.md"] + + + ```yaml title="config.yaml" + models: + - name: Tab Autocomplete Model + provider: ollama + model: qwen2.5-coder:1.5b-base + apiBase: https:// + roles: + - autocomplete + ``` + + + ```json title="config.json" + { + "tabAutocompleteModel": { + "title": "Tab Autocomplete Model", + "provider": "ollama", + "model": "qwen2.5-coder:1.5b-base", + "apiBase": "https://" + }, + "tabAutocompleteOptions": { + "debounceDelay": 500, + "maxPromptTokens": 1500, + "disableInFiles": ["*.md"] + } } -} -``` + ``` + + ## FAQs diff --git a/docs/docs/customize/deep-dives/codebase.md b/docs/docs/customize/deep-dives/codebase.mdx similarity index 78% rename from docs/docs/customize/deep-dives/codebase.md rename to docs/docs/customize/deep-dives/codebase.mdx index 4da920943..acf19c4fc 100644 --- a/docs/docs/customize/deep-dives/codebase.md +++ b/docs/docs/customize/deep-dives/codebase.mdx @@ -3,12 +3,15 @@ description: Talk to your codebase keywords: [talk, embeddings, reranker, codebase, experimental] --- +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + # @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 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, `transformers.js` cannot be used in JetBrains IDEs. However, you can select a differet embeddings model from [the list here](../model-types/embeddings.mdx). ::: 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. @@ -38,22 +41,36 @@ 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, docs, and folder context providers: +There are a few options that let you configure the behavior of the `@codebase` context provider, which are the same for the `@folder` context provider: -```json title="config.json" -{ - "contextProviders": [ - { - "name": "codebase", - "params": { - "nRetrieve": 25, - "nFinal": 5, - "useReranking": true + + + ```yaml title="Package or config.yaml" + context: + - provider: codebase + params: + nRetrieve: 25, + nFinal: 5, + useReranking: true + ``` + + + ```json title="config.json" + { + "contextProviders": [ + { + "name": "codebase", + "params": { + "nRetrieve": 25, + "nFinal": 5, + "useReranking": true + } } - } - ] -} -``` + ] + } + ``` + + ### `nRetrieve` @@ -79,4 +96,4 @@ If you need to force a refresh of the index, reload the VS Code window with + + ```yaml title="config.yaml" + context: + - provider: docs + ``` + + + ```json title="config.json" + { + "contextProviders": [ + { + "name": "docs" + } + ] + } + ``` + + ## How It Works @@ -76,17 +89,29 @@ Documentation sources may be suggested based on package files in your repo. This For bulk documentation site adds or edits, we recommend editing your global configuration file directly. Documentation sites are stored in an array within `docs` in your global configuration, as follows: -```json title="config.json" -{ - "docs": [ - { - "title": "Nest.js", - "startUrl": "https://docs.nestjs.com/", - "faviconUrl": "https://docs.nestjs.com/favicon.ico" - } - ] -} -``` + + + ```yaml title="config.yaml" + docs: + - title: Nest.js + startUrl: https://docs.nestjs.com/ + faviconUrl: https://docs.nestjs.com/favicon.ico + ``` + + + ```json title="config.json" + { + "docs": [ + { + "title": "Nest.js", + "startUrl": "https://docs.nestjs.com/", + "faviconUrl": "https://docs.nestjs.com/favicon.ico" + } + ] + } + ``` + + See [the config reference](../../reference) for all documentation site configuration options. @@ -96,43 +121,69 @@ Indexing will re-sync upon saving the configuration file. ### Using Your Embeddings Provider -If you have set up an [embeddings provider](../model-types/embeddings.md), @docs will use your embeddings provider. Switching embeddings providers will trigger a re-index of all documentation sites in your configuration. +If you have set up an [embeddings provider](../model-types/embeddings.mdx), @docs will use your embeddings provider. Switching embeddings providers will trigger a re-index of all documentation sites in your configuration. ### Reranking As with [@Codebase context provider configuration](./codebase#configuration), you can adjust the reranking behavior of the `@Docs` context provider with the `nRetrieve`, `nFinal`, and `useReranking`. -```json title="config.json" -{ - "contextProviders": [ - { - "name": "docs", - "params": { - "nRetrieve": 25, // The number of docs to retreive from the embeddings query - "nFinal": 5, // The number of docs chunks to return IF reranking - "useReranking": true // use reranking if a reranker is configured (defaults to true) + + + ```yaml title="config.yaml" + context: + - provider: docs + params: + nRetrieve: 25 # The number of docs to retreive from the embeddings query + nFinal: 5 # The number of docs chunks to return IF reranking + useReranking: true # use reranking if a reranker is configured (defaults to true) + ``` + + + ```json title="config.json" + { + "contextProviders": [ + { + "name": "docs", + "params": { + "nRetrieve": 25, // The number of docs to retreive from the embeddings query + "nFinal": 5, // The number of docs chunks to return IF reranking + "useReranking": true // use reranking if a reranker is configured (defaults to true) + } } - } - ] -} -``` + ] + } + ``` + + ### Github The Github API rate limits public requests to 60 per hour. If you want to reliably index Github repos, you can add a github token to your config file: -```json title="config.json" -{ - "contextProviders": [ - { - "name": "docs", - "params": { - "githubToken": "github_..." + + + ```yaml title="config.yaml" + context: + - provider: docs + params: + githubToken: + ``` + + + ```json title="config.json" + { + "contextProviders": [ + { + "name": "docs", + "params": { + "githubToken": "github_..." + } } - } - ] -} -``` + ] + } + ``` + + ### Local Crawling @@ -140,18 +191,31 @@ By default, Continue crawls documentation sites using a specialized crawling ser If your documentation is private, you can skip the default crawler and use a local crawler instead by setting `useLocalCrawling` to `true`. -```json title="config.json" -{ - "docs": [ - { - "title": "My Private Docs", - "startUrl": "http://10.2.1.2/docs", - "faviconUrl": "http://10.2.1.2/docs/assets/favicon.ico", - "useLocalCrawling": true - } - ] -} -``` + + + ```yaml title="config.yaml" + docs: + - title: My Private Docs + startUrl: http://10.2.1.2/docs + faviconUrl: http://10.2.1.2/docs/assets/favicon.ico, + useLocalCrawling: true + ``` + + + ```json title="config.json" + { + "docs": [ + { + "title": "My Private Docs", + "startUrl": "http://10.2.1.2/docs", + "faviconUrl": "http://10.2.1.2/docs/assets/favicon.ico", + "useLocalCrawling": true + } + ] + } + ``` + + The default local crawler is a lightweight tool that cannot render sites that are dynamically generated using JavaScript. If your sites need to be rendered, you can enable the experimental `Use Chromium for Docs Crawling` feature from your [User Settings Page](../settings.md) This will download and install Chromium to `~/.continue/.utils`, and use it as the local crawler. @@ -182,41 +246,78 @@ You can also use the following IDE command to force a re-index of all docs: `Con The following configuration example works out of the box for VS Code. This uses the built-in embeddings provider with no reranking. Pre-indexed docs will be accessible. -```json title="config.json" - "contextProviders": [ - { - "name": "docs", - } - ], - "docs": [ - { - "title": "Nest.js", - "startUrl": "https://docs.nestjs.com/", - }, - ], -``` + + + ```yaml title="config.yaml" + context: + - provider: docs + + docs: + - title: Nest.js + startUrl: https://docs.nestjs.com/ + ``` + + + ```json title="config.json" + { + "contextProviders": [ + { + "name": "docs", + } + ], + "docs": [ + { + "title": "Nest.js", + "startUrl": "https://docs.nestjs.com/", + }, + ] + } + ``` + + ### Jetbrains minimal setup -Here is the equivalent minimal example for Jetbrains, which requires setting up an [embeddings provider](../model-types/embeddings.md). Pre-indexed docs will _not_ be accessible. +Here is the equivalent minimal example for Jetbrains, which requires setting up an [embeddings provider](../model-types/embeddings.mdx). Pre-indexed docs will _not_ be accessible. -```json title="config.json" - "contextProviders": [ - { - "name": "docs", + + + ```yaml title="config.yaml" + models: + - name: LMStudio embedder + provider: lmstudio + model: nomic-ai/nomic-embed-text-v1.5-GGUF + roles: + - embed + context: + - provider: docs + docs: + - title: Nest.js + startUrl: https://docs.nestjs.com/ + ``` + + + ```json title="config.json" + { + "contextProviders": [ + { + "name": "docs", + } + ], + "docs": [ + { + "title": "Nest.js", + "startUrl": "https://docs.nestjs.com/", + }, + ], + "embeddingsProvider": { + "provider": "lmstudio", + "model": "nomic-ai/nomic-embed-text-v1.5-GGUF" } - ], - "docs": [ - { - "title": "Nest.js", - "startUrl": "https://docs.nestjs.com/", - }, - ], - "embeddingsProvider": { - "provider": "lmstudio", - "model": "nomic-ai/nomic-embed-text-v1.5-GGUF" - }, -``` + } + ``` + + ### Full-power setup (VS Code or Jetbrains) @@ -227,44 +328,79 @@ The following configuration example includes: - A reranker model available, with reranking parameters customized - A Github token to enable Github crawling -```json title="config.json" -{ - "contextProviders": [ - { - "name": "docs", - "params": { - "githubToken": "github_...", - "nRetrieve": 25, - "nFinal": 5, - "useReranking": true + + + ```yaml title="config.yaml" + models: + - name: LMStudio Nomic Text + provider: lmstudio + model: nomic-ai/nomic-embed-text-v1.5-GGUF + roles: + - embed + - name: Voyage Rerank-2 + provider: voyage + apiKey: + model: rerank-2 + roles: + - rerank + context: + - provider: docs + params: + githubToken: + nRetrieve: 25 + nFinal: 5 + useReranking: true + docs: + - title: Nest.js + startUrl: https://docs.nestjs.com/ + - title: My Private Docs + startUrl: http://10.2.1.2/docs + faviconUrl: http://10.2.1.2/docs/assets/favicon.ico + maxDepth: 4 + useLocalCrawling: true + ``` + + + ```json title="config.json" + { + "contextProviders": [ + { + "name": "docs", + "params": { + "githubToken": "github_...", + "nRetrieve": 25, + "nFinal": 5, + "useReranking": true + } + } + ], + "docs": [ + { + "title": "Nest.js", + "startUrl": "https://docs.nestjs.com/" + }, + { + "title": "My Private Docs", + "startUrl": "http://10.2.1.2/docs", + "faviconUrl": "http://10.2.1.2/docs/assets/favicon.ico", + "maxDepth": 4, + "useLocalCrawling": true + } + ], + "reranker": { + "name": "voyage", + "params": { + "model": "rerank-2", + "apiKey": "" } - } - ], - "docs": [ - { - "title": "Nest.js", - "startUrl": "https://docs.nestjs.com/" }, - { - "title": "My Private Docs", - "startUrl": "http://10.2.1.2/docs", - "faviconUrl": "http://10.2.1.2/docs/assets/favicon.ico", - "maxDepth": 4, - "useLocalCrawling": true + "embeddingsProvider": { + "provider": "lmstudio", + "model": "nomic-ai/nomic-embed-text-v1.5-GGUF" } - ], - "reranker": { - "name": "voyage", - "params": { - "model": "rerank-2", - "apiKey": "" - } - }, - "embeddingsProvider": { - "provider": "lmstudio", - "model": "nomic-ai/nomic-embed-text-v1.5-GGUF" } -} -``` + ``` + + This could also involve enabling Chromium as a backup for local documentation the [User Settings Page](../settings.md). diff --git a/docs/docs/customize/deep-dives/prompt-files.md b/docs/docs/customize/deep-dives/prompt-files.md index 7269a459a..bd4c05db6 100644 --- a/docs/docs/customize/deep-dives/prompt-files.md +++ b/docs/docs/customize/deep-dives/prompt-files.md @@ -16,7 +16,7 @@ Below is a quick example of setting up a prompt file to de 2. Add a file called `rails.prompt` to this folder. 3. Write the following contents to `rails.prompt` and save. -``` +```.prompt name: Rails Project description: Information about this project --- @@ -47,7 +47,7 @@ If you don't need any of these parameters, you can leave out the preamble and do ### Context -Many [context provider](../context-providers.md) can be referenced by typing "@" followed by the name of the context provider. The currently supported list is: +Many [context provider](../context-providers.mdx) can be referenced by typing "@" followed by the name of the context provider. The currently supported list is: - `@terminal` - The contents of the terminal - `@currentFile` - The currently active file diff --git a/docs/docs/customize/deep-dives/rules.md b/docs/docs/customize/deep-dives/rules.md index f53135b50..ae8347f29 100644 --- a/docs/docs/customize/deep-dives/rules.md +++ b/docs/docs/customize/deep-dives/rules.md @@ -12,7 +12,7 @@ You can create a project-specific system message by adding a `.continuerules` fi - If you want concise answers: ```title=.continuerules -Please provide concise answers. Do explain obvious concepts. You can assume that I am knowledgable about most programming topics. +Please provide concise answers. Don't explain obvious concepts. You can assume that I am knowledgable about most programming topics. ``` - If you want to ensure certain practices are followed, for example in React: diff --git a/docs/docs/customize/model-providers/moonshot.md b/docs/docs/customize/model-providers/moonshot.md deleted file mode 100644 index 64017d1bd..000000000 --- a/docs/docs/customize/model-providers/moonshot.md +++ /dev/null @@ -1,60 +0,0 @@ -# Moonshot - -[Moonshot AI](https://platform.moonshot.cn/) provides high-quality large language model services with competitive pricing and excellent performance. - -## Configuration - -To use Moonshot AI models, you need to: - -1. Get an API key from [Moonshot AI Platform](https://platform.moonshot.cn/) -2. Add the following configuration to your `config.json`: - -```json -{ - "models": [ - { - "title": "Moonshot", - "provider": "moonshot", - "model": "moonshot-v1-8k", - "apiKey": "YOUR_API_KEY" - } - ] -} -``` - -## Available Models - -Moonshot AI currently provides the following models: - -- `moonshot-v1-8k`: Base model with 8K context window -- `moonshot-v1-32k`: Base model with 32K context window -- `moonshot-v1-128k`: Base model with 128K context window - -## Configuration Options - -| Option | Description | Default | -|--------|-------------|---------| -| `apiKey` | Moonshot API key | Required | -| `apiBase` | API base URL | `https://api.moonshot.cn/v1/` | -| `model` | Model name to use | `moonshot-v1-8k` | - -## Example - -Here's a complete configuration example: - -```json -{ - "models": [ - { - "title": "Moonshot-8K", - "provider": "moonshot", - "model": "moonshot-v1-8k", - "apiKey": "YOUR_API_KEY", - "completionOptions": { - "temperature": 0.7, - "topP": 0.95, - "maxTokens": 2048 - } - } - ] -} diff --git a/docs/docs/customize/model-providers/more/SambaNova.md b/docs/docs/customize/model-providers/more/SambaNova.md deleted file mode 100644 index f35c56dd5..000000000 --- a/docs/docs/customize/model-providers/more/SambaNova.md +++ /dev/null @@ -1,18 +0,0 @@ -# SambaNova Cloud - -The SambaNova Cloud is a cloud platform for running large AI models with the world record Llama 3.1 70B/405B performance. You can follow the instructions in [this blog post](https://sambanova.ai/blog/accelerating-coding-with-sambanova-cloud?ref=blog.continue.dev) to configure your setup. - -```json title="config.json" -{ - "models": [ - { - "title": "SambaNova Llama 3.1 405B", - "provider": "sambanova", - "model": "llama3.1-405b", - "apiKey": "YOUR_API_KEY" - } - ] -} -``` - -[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/SambaNova.ts) diff --git a/docs/docs/customize/model-providers/more/SambaNova.mdx b/docs/docs/customize/model-providers/more/SambaNova.mdx new file mode 100644 index 000000000..86c2e9e0b --- /dev/null +++ b/docs/docs/customize/model-providers/more/SambaNova.mdx @@ -0,0 +1,34 @@ +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +# SambaNova Cloud + +The SambaNova Cloud is a cloud platform for running large AI models with the world record Llama 3.1 70B/405B performance. You can follow the instructions in [this blog post](https://sambanova.ai/blog/accelerating-coding-with-sambanova-cloud?ref=blog.continue.dev) to configure your setup. + + + + ```yaml title="Package or config.yaml" + models: + - name: SambaNova Llama 3.1 405B + provider: sambanova + model: llama3.1-405b + apiKey: + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "SambaNova Llama 3.1 405B", + "provider": "sambanova", + "model": "llama3.1-405b", + "apiKey": "" + } + ] + } + ``` + + + +[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/SambaNova.ts) diff --git a/docs/docs/customize/model-providers/more/asksage.md b/docs/docs/customize/model-providers/more/asksage.md deleted file mode 100644 index 204d29421..000000000 --- a/docs/docs/customize/model-providers/more/asksage.md +++ /dev/null @@ -1,75 +0,0 @@ -# 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. - -## Ask Sage Documentation -Ask Sage documentation is not available with Continue.Dev, so if you have any questions or need help with Ask Sage type `@ask` and select the `Ask Sage` option in the chat. Then procced to ask your question about Ask Sage. - -## Current Models From Ask Sage Supported - -The current Models available provided by Ask Sage are: - -| Index | Model | Added | Status | -|-------|------------------------|-------|--------| -| 1 | GPT-4 Gov | Yes | ✅ | -| 2 | GPT-4o Gov | Yes | ✅ | -| 3 | GPT-4o-mini Gov | Yes | ✅ | -| 4 | GPT-3.5-Turbo Gov | Yes | ✅ | -| 5 | GPT-4o | Yes | ✅ | -| 6 | GPT-4o-mini | Yes | ✅ | -| 7 | GPT-4 | Yes | ✅ | -| 8 | GPT-4-32K | Yes | ✅ | -| 9 | GPT-o1 | Yes | ✅ | -| 10 | GPT-o1-mini | Yes | ✅ | -| 10 | GPT-o3-mini | Yes | ✅ | -| 11 | GPT-3.5-turbo | Yes | ✅ | -| 12 | Calude 3.5 Sonnet Gov | Yes | ✅ | -| 13 | Calude 3 Opus | Yes | ✅ | -| 14 | Calude 3 Sonet | Yes | ✅ | -| 15 | Calude 3.5 Sonnet | Yes | ✅ | -| 16 | Grok (xAI) | Yes | ✅ | -| 17 | Groq Llama 3.3 | Yes | ✅ | -| 18 | Groq 70B | Yes | ✅ | -| 19 | Gemini Pro | Yes | ✅ | -| 20 | llama 3 | Yes | ✅ | -| 21 | Mistral Large | Yes | ✅ | - diff --git a/docs/docs/customize/model-providers/more/asksage.mdx b/docs/docs/customize/model-providers/more/asksage.mdx new file mode 100644 index 000000000..f6966a517 --- /dev/null +++ b/docs/docs/customize/model-providers/more/asksage.mdx @@ -0,0 +1,91 @@ +# Ask Sage + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +:::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, you can use the following + + + + ```yaml title="Package or config.yaml" + models: + - name: GPT-4 gov + provider: askSage + model: gpt4-gov + apiBase: https://api.asksage.ai/server/ + apiKey: + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "GPT-4 gov", + "provider": "askSage", + "model": "gpt4-gov", + "apiBase": "https://api.asksage.ai/server/", + "apiKey": "" + } + ] + } + ``` + + + +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. + +## Ask Sage Documentation + +Ask Sage documentation is not available with Continue.Dev, so if you have any questions or need help with Ask Sage type `@ask` and select the `Ask Sage` option in the chat. Then procced to ask your question about Ask Sage. + +## Current Models From Ask Sage Supported + +The current Models available provided by Ask Sage are: + +| Index | Model | Added | +| ----- | --------------------- | ----- | +| 1 | GPT-4 Gov | ✅ | +| 2 | GPT-4o Gov | ✅ | +| 3 | GPT-4o-mini Gov | ✅ | +| 4 | GPT-3.5-Turbo Gov | ✅ | +| 5 | GPT-4o | ✅ | +| 6 | GPT-4o-mini | ✅ | +| 7 | GPT-4 | ✅ | +| 8 | GPT-4-32K | ✅ | +| 9 | GPT-o1 | ✅ | +| 10 | GPT-o1-mini | ✅ | +| 10 | GPT-o3-mini | ✅ | +| 11 | GPT-3.5-turbo | ✅ | +| 12 | Claude 3.5 Sonnet Gov | ✅ | +| 13 | Claude 3 Opus | ✅ | +| 14 | Claude 3 Sonet | ✅ | +| 15 | Claude 3.5 Sonnet | ✅ | +| 16 | Grok (xAI) | ✅ | +| 17 | Groq Llama 3.3 | ✅ | +| 18 | Groq 70B | ✅ | +| 19 | Gemini Pro | ✅ | +| 20 | llama 3 | ✅ | +| 21 | Mistral Large | ✅ | diff --git a/docs/docs/customize/model-providers/more/cerebras.md b/docs/docs/customize/model-providers/more/cerebras.md deleted file mode 100644 index d9cbd31dc..000000000 --- a/docs/docs/customize/model-providers/more/cerebras.md +++ /dev/null @@ -1,20 +0,0 @@ -# Cerebras Inference - -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. -3. Update your Continue config file: - -```json title="config.json" -{ - "models": [ - { - "title": "Cerebras Llama 3.1 70B", - "provider": "cerebras", - "model": "llama3.1-70b", - "apiKey": "YOUR_API_KEY" - } - ] -} -``` diff --git a/docs/docs/customize/model-providers/more/cerebras.mdx b/docs/docs/customize/model-providers/more/cerebras.mdx new file mode 100644 index 000000000..a0ffabc8b --- /dev/null +++ b/docs/docs/customize/model-providers/more/cerebras.mdx @@ -0,0 +1,36 @@ +# Cerebras Inference + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +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. +3. Update your Continue config file: + + + + ```yaml title="Package or config.yaml" + models: + - name: Cerebras Llama 3.1 70B + provider: cerebras + model: llama3.1-70b + apiKey: + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Cerebras Llama 3.1 70B", + "provider": "cerebras", + "model": "llama3.1-70b", + "apiKey": "" + } + ] + } + ``` + + diff --git a/docs/docs/customize/model-providers/more/cloudflare.md b/docs/docs/customize/model-providers/more/cloudflare.md deleted file mode 100644 index 5281cba79..000000000 --- a/docs/docs/customize/model-providers/more/cloudflare.md +++ /dev/null @@ -1,46 +0,0 @@ -# Cloudflare Workers AI - -Cloudflare Workers AI can be used for both chat and tab autocompletion in Continue. To setup Cloudflare Workers AI, add the following to your `config.json` file: - -```json title="config.json" -{ - "models": [ - { - "accountId": "YOUR CLOUDFLARE ACCOUNT ID", - "apiKey": "YOUR CLOUDFLARE API KEY", - "contextLength": 2400, - "completionOptions": { - "maxTokens": 500 - }, - "model": "@cf/meta/llama-3-8b-instruct", // This can be the name of any model supported by Workers AI - "provider": "cloudflare", - "title": "Llama 3 8B" - }, - { - "accountId": "YOUR CLOUDFLARE ACCOUNT ID", - "apiKey": "YOUR CLOUDFLARE API KEY", - "contextLength": 2400, - "completionOptions": { - "maxTokens": 500 - }, - "model": "@hf/thebloke/deepseek-coder-6.7b-instruct-awq", - "provider": "cloudflare", - "title": "DeepSeek Coder 6.7b Instruct" - } - ... - "tabAutocompleteModel": { - "accountId": "YOUR CLOUDFLARE ACCOUNT ID", - "apiKey": "YOUR CLOUDFLARE API KEY", - "model": "@hf/thebloke/deepseek-coder-6.7b-base-awq", - "provider": "cloudflare", - "title": "DeepSeek 7b" - }, - ] -} -``` - -Visit the [Cloudflare dashboard](https://dash.cloudflare.com/) to [create an API key](https://developers.cloudflare.com/fundamentals/api/get-started/create-token/). - -Review [available models](https://developers.cloudflare.com/workers-ai/models/) on Workers AI - -[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Cloudflare.ts) diff --git a/docs/docs/customize/model-providers/more/cloudflare.mdx b/docs/docs/customize/model-providers/more/cloudflare.mdx new file mode 100644 index 000000000..fa95f4930 --- /dev/null +++ b/docs/docs/customize/model-providers/more/cloudflare.mdx @@ -0,0 +1,84 @@ +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +# Cloudflare Workers AI + +Cloudflare Workers AI can be used for both chat and tab autocompletion in Continue. Here is an example of Cloudflare Workers AI configuration: + + + + ```yaml title="config.yaml" + models: + - name: Llama 3 8B + provider: cloudflare + accountId: YOUR CLOUDFLARE ACCOUNT ID + apiKey: + model: "@cf/meta/llama-3-8b-instruct" + contextLength: 2400 + defaultCompletionOptions: + maxTokens: 500 + roles: + - chat + - name: DeepSeek Coder 6.7b Instruct + provider: cloudflare + accountId: YOUR CLOUDFLARE ACCOUNT ID + apiKey: + model: "@hf/thebloke/deepseek-coder-6.7b-instruct-awq" + contextLength: 2400 + defaultCompletionOptions: + maxTokens: 500 + roles: + - chat + - name: DeepSeek 7b + provider: cloudflare + accountId: YOUR CLOUDFLARE ACCOUNT ID + apiKey: + model: "@hf/thebloke/deepseek-coder-6.7b-base-awq" + roles: + - autocomplete + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Llama 3 8B", + "provider": "cloudflare", + "accountId": "YOUR CLOUDFLARE ACCOUNT ID", + "apiKey": "YOUR CLOUDFLARE API KEY", + "contextLength": 2400, + "completionOptions": { + "maxTokens": 500 + }, + "model": "@cf/meta/llama-3-8b-instruct" + }, + { + "title": "DeepSeek Coder 6.7b Instruct", + "provider": "cloudflare", + "accountId": "YOUR CLOUDFLARE ACCOUNT ID", + "apiKey": "YOUR CLOUDFLARE API KEY", + "contextLength": 2400, + "completionOptions": { + "maxTokens": 500 + }, + "model": "@hf/thebloke/deepseek-coder-6.7b-instruct-awq" + } + ], + "tabAutocompleteModel": { + "title": "DeepSeek 7b", + "provider": "cloudflare", + "accountId": "YOUR CLOUDFLARE ACCOUNT ID", + "apiKey": "YOUR CLOUDFLARE API KEY", + "model": "@hf/thebloke/deepseek-coder-6.7b-base-awq" + } + } + ``` + + + +Visit the [Cloudflare dashboard](https://dash.cloudflare.com/) to [create an API key](https://developers.cloudflare.com/fundamentals/api/get-started/create-token/). + +Review [available models](https://developers.cloudflare.com/workers-ai/models/) on Workers AI + +[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Cloudflare.ts) diff --git a/docs/docs/customize/model-providers/more/cohere.md b/docs/docs/customize/model-providers/more/cohere.md deleted file mode 100644 index 8a1f069a6..000000000 --- a/docs/docs/customize/model-providers/more/cohere.md +++ /dev/null @@ -1,56 +0,0 @@ -# Cohere - -Before using Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key. - -## Chat model - -We recommend configuring **Command-R Plus** as your chat model. - -```json title="config.json" -{ - "models": [ - { - "title": "Cohere", - "provider": "cohere", - "model": "command-r-plus", - "apiKey": "YOUR_API_KEY" - } - ] -} -``` - -## Autocomplete model - -Cohere 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 **embed-english-v3.0** as your embeddings model. - -```json title="config.json" -{ - "embeddingsProvider": { - "provider": "cohere", - "model": "embed-english-v3.0", - "apiKey": "" - } -} -``` - -## Reranking model - -We recommend configuring **rerank-english-v3.0** as your reranking model. - -```json title="config.json" -{ - "reranker": { - "name": "cohere", - "params": { - "model": "rerank-english-v3.0", - "apiKey": "" - } - } -} -``` diff --git a/docs/docs/customize/model-providers/more/cohere.mdx b/docs/docs/customize/model-providers/more/cohere.mdx new file mode 100644 index 000000000..dd7de0321 --- /dev/null +++ b/docs/docs/customize/model-providers/more/cohere.mdx @@ -0,0 +1,102 @@ +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +# Cohere + +Before using Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key. + +## Chat model + +We recommend configuring **Command-R Plus** as your chat model. + + + + ```yaml title="Package or config.yaml" + models: + - name: Cohere + provider: cohere + model: command-r-plus + apiKey: + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Cohere", + "provider": "cohere", + "model": "command-r-plus", + "apiKey": "" + } + ] + } + ``` + + + +## Autocomplete model + +Cohere 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 **embed-english-v3.0** as your embeddings model. + + + + ```yaml title="config.yaml" + models: + - name: Cohere Embed + provider: cohere + model: embed-english-v3.0 + apiKey: + roles: + - embed + ``` + + + ```json title="config.json" + { + "embeddingsProvider": { + "provider": "cohere", + "model": "embed-english-v3.0", + "apiKey": "" + } + } + ``` + + + +## Reranking model + +We recommend configuring **rerank-english-v3.0** as your reranking model. + + + + ```yaml title="config.yaml" + models: + - name: Cohere Reranker + provider: cohere + model: rerank-english-v3.0 + apiKey: + roles: + - rerank + ``` + + + ```json title="config.json" + { + "reranker": { + "name": "cohere", + "params": { + "model": "rerank-english-v3.0", + "apiKey": "" + } + } + } + ``` + + diff --git a/docs/docs/customize/model-providers/more/deepinfra.md b/docs/docs/customize/model-providers/more/deepinfra.md deleted file mode 100644 index f79824cce..000000000 --- a/docs/docs/customize/model-providers/more/deepinfra.md +++ /dev/null @@ -1,18 +0,0 @@ -# DeepInfra - -[DeepInfra](https://deepinfra.com) provides inference for open-source models at very low cost. To get started with DeepInfra, obtain your API key [here](https://deepinfra.com/dash). Then, find the model you want to use [here](https://deepinfra.com/models?type=text-generation) and copy the name of the model. Continue can then be configured to use the `DeepInfra` LLM class, like the example here: - -```json title="config.json" -{ - "models": [ - { - "provider": "deepinfra", - "title": "DeepInfra", - "model": "mistralai/Mixtral-8x7B-Instruct-v0.1", - "apiKey": "" - } - ] -} -``` - -[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/DeepInfra.ts) diff --git a/docs/docs/customize/model-providers/more/deepinfra.mdx b/docs/docs/customize/model-providers/more/deepinfra.mdx new file mode 100644 index 000000000..de3e09e23 --- /dev/null +++ b/docs/docs/customize/model-providers/more/deepinfra.mdx @@ -0,0 +1,34 @@ +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +# DeepInfra + +[DeepInfra](https://deepinfra.com) provides inference for open-source models at very low cost. To get started with DeepInfra, obtain your API key [here](https://deepinfra.com/dash). Then, find the model you want to use [here](https://deepinfra.com/models?type=text-generation) and copy the name of the model. Continue can then be configured to use the `DeepInfra` LLM class, like the example here: + + + + ```yaml title="config.yaml" + models: + - name: DeepInfra + provider: deepinfra + model: mistralai/Mixtral-8x7B-Instruct-v0.1 + apiKey: + ``` + + + ```json title="config.json" + { + "models": [ + { + "provider": "deepinfra", + "title": "DeepInfra", + "model": "mistralai/Mixtral-8x7B-Instruct-v0.1", + "apiKey": "" + } + ] + } + ``` + + + +[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/DeepInfra.ts) diff --git a/docs/docs/customize/model-providers/more/flowise.md b/docs/docs/customize/model-providers/more/flowise.md deleted file mode 100644 index f860d966b..000000000 --- a/docs/docs/customize/model-providers/more/flowise.md +++ /dev/null @@ -1,18 +0,0 @@ -# Flowise - -[Flowise](https://flowiseai.com/) is a low-code/no-code drag & drop tool with the aim to make it easy for people to visualize and build LLM apps. Continue can then be configured to use the `Flowise` LLM class, like the example here: - -```json title="config.json" -{ - "models": [ - { - "provider": "flowise", - "title": "Flowise", - "model": "", - "apiBase": "" - } - ] -} -``` - -[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Flowise.ts) diff --git a/docs/docs/customize/model-providers/more/flowise.mdx b/docs/docs/customize/model-providers/more/flowise.mdx new file mode 100644 index 000000000..546e6a716 --- /dev/null +++ b/docs/docs/customize/model-providers/more/flowise.mdx @@ -0,0 +1,34 @@ +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +# Flowise + +[Flowise](https://flowiseai.com/) is a low-code/no-code drag & drop tool with the aim to make it easy for people to visualize and build LLM apps. Continue can then be configured to use the `Flowise` LLM class, like the example here: + + + + ```yaml title="Package or config.yaml" + models: + - name: Flowise + provider: flowise + model: + apiBase: + ``` + + + ```json title="config.json" + { + "models": [ + { + "provider": "flowise", + "title": "Flowise", + "model": "", + "apiBase": "" + } + ] + } + ``` + + + +[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Flowise.ts) diff --git a/docs/docs/customize/model-providers/more/free-trial.md b/docs/docs/customize/model-providers/more/free-trial.mdx similarity index 90% rename from docs/docs/customize/model-providers/more/free-trial.md rename to docs/docs/customize/model-providers/more/free-trial.mdx index a51d2e61c..28d831738 100644 --- a/docs/docs/customize/model-providers/more/free-trial.md +++ b/docs/docs/customize/model-providers/more/free-trial.mdx @@ -3,12 +3,15 @@ title: Free Trial slug: ../free-trial --- +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + The `"free-trial"` provider lets new users quickly try out the best experience in Continue using our API keys through a secure proxy server. To prevent abuse, we will ask you to sign in with GitHub, which you can read more about below. While the Continue extension is always free to use, we cannot support infinite free LLM usage for all of our users. You will eventually need to either: -1. Select an open-source model to use for free [locally](../top-level/ollama.md), or -2. Add your own API key for [Anthropic](../top-level/anthropic.md) or [another LLM provider](/customize/model-providers) +1. Select an open-source model to use for free [locally](../top-level/ollama.mdx), or +2. Add your own API key for [Anthropic](../top-level/anthropic.mdx) or [another LLM provider](/customize/model-providers) ## FAQ about the trial diff --git a/docs/docs/customize/model-providers/more/function-network.md b/docs/docs/customize/model-providers/more/function-network.md deleted file mode 100644 index c48e899d8..000000000 --- a/docs/docs/customize/model-providers/more/function-network.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -title: Function Network -slug: ../function-network ---- -# Function Network - -> Private, Affordable User-Owned AI - -:::info - -To get an API key, login to the Function Network Developer Platform. If you don't have an account, you can create one [here](https://www.function.network/join-waitlist). - -::: - -## Chat model - -Function Network supports a number of models for chat. We recommend using LLama 3.1 70b or Qwen2.5-Coder-32B-Instruct. - -```json title="config.json" -{ - "models": [ - { - "title": "Llama 3.1 70b", - "provider": "function-network", - "model": "meta/llama-3.1-70b-instruct", - "apiKey": "YOUR_API_KEY" - } - ] -} -``` - -[Click here](https://docs.function.network/models-supported/chat-and-code-completion) to see a list of chat model providers. - -## Autocomplete model - -Function Network supports a number of models for autocomplete. We recommend using Llama 3.1 8b or Qwen2.5-Coder-1.5B. - -```json title="config.json" -{ - "tabAutocompleteModel": { - "title": "Deepseek Coder 6.7b", - "provider": "function-network", - "model": "thebloke/deepseek-coder-6.7b-base-awq", - "apiKey": "YOUR_API_KEY" - } -} -``` - -## Embeddings model - -Function Network supports a number of models for embeddings. We recommend using baai/bge-base-en-v1.5. - -```json title="config.json" -{ - "embeddingsProvider": { - "provider": "function-network", - "model": "baai/bge-base-en-v1.5", - "apiKey": "YOUR_API_KEY" - } -} -``` - -[Click here](https://docs.function.network/models-supported/embeddings) to see a list of embeddings model providers. - -## Reranking model - -Function Network currently does not offer any reranking models. diff --git a/docs/docs/customize/model-providers/more/function-network.mdx b/docs/docs/customize/model-providers/more/function-network.mdx new file mode 100644 index 000000000..d734fde08 --- /dev/null +++ b/docs/docs/customize/model-providers/more/function-network.mdx @@ -0,0 +1,116 @@ +--- +title: Function Network +slug: ../function-network +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +# Function Network + +> Private, Affordable User-Owned AI + +:::info + +To get an API key, login to the Function Network Developer Platform. If you don't have an account, you can create one [here](https://www.function.network/join-waitlist). + +::: + +## Chat model + +Function Network supports a number of models for chat. We recommend using LLama 3.1 70b or Qwen2.5-Coder-32B-Instruct. + + + + ```yaml title="Package or config.yaml" + models: + - name: Llama 3.1 70b + provider: function-network + model: meta/llama-3.1-70b-instruct + apiKey: + roles: + - chat + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Llama 3.1 70b", + "provider": "function-network", + "model": "meta/llama-3.1-70b-instruct", + "apiKey": "" + } + ] + } + ``` + + + +[Click here](https://docs.function.network/models-supported/chat-and-code-completion) to see a list of chat model providers. + +## Autocomplete model + +Function Network supports a number of models for autocomplete. We recommend using Llama 3.1 8b or Qwen2.5-Coder-1.5B. + + + + ```yaml title="Package or config.yaml" + models: + - name: Deepseek Coder 6.7b + provider: function-network + model: thebloke/deepseek-coder-6.7b-base-awq + apiKey: + roles: + - autocomplete + ``` + + + ```json title="config.json" + { + "tabAutocompleteModel": { + "title": "Deepseek Coder 6.7b", + "provider": "function-network", + "model": "thebloke/deepseek-coder-6.7b-base-awq", + "apiKey": "" + } + } + ``` + + + +## Embeddings model + +Function Network supports a number of models for embeddings. We recommend using baai/bge-base-en-v1.5. + + + + ```yaml title="config.yaml" + models: + - name: BGE Base En + provider: function-network + model: baai/bge-base-en-v1.5 + apiKey: + roles: + - embed + ``` + + + ```json title="config.json" + { + "embeddingsProvider": { + "provider": "function-network", + "model": "baai/bge-base-en-v1.5", + "apiKey": "" + } + } + ``` + + + +[Click here](https://docs.function.network/models-supported/embeddings) to see a list of embeddings model providers. + +## Reranking model + +Function Network currently does not offer any reranking models. diff --git a/docs/docs/customize/model-providers/more/groq.md b/docs/docs/customize/model-providers/more/groq.md deleted file mode 100644 index 54e678abc..000000000 --- a/docs/docs/customize/model-providers/more/groq.md +++ /dev/null @@ -1,19 +0,0 @@ -# Groq - -Groq provides the fastest available inference for open-source language models, including the entire Llama 3.1 family. - -1. Obtain an API key [here](https://console.groq.com/keys) -2. Update your Continue config file like this: - -```json title="config.json" -{ - "models": [ - { - "title": "Llama 3.1 405b", - "provider": "groq", - "model": "llama3.1-405b", - "apiKey": "" - } - ] -} -``` diff --git a/docs/docs/customize/model-providers/more/groq.mdx b/docs/docs/customize/model-providers/more/groq.mdx new file mode 100644 index 000000000..45cfd0a8a --- /dev/null +++ b/docs/docs/customize/model-providers/more/groq.mdx @@ -0,0 +1,41 @@ +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +# Groq + +:::info +Check if your chosen model is still supported by referring to the [model documentation](https://console.groq.com/docs/models). If a model has been deprecated, you may encounter a 404 error when attempting to use it. +::: + +Groq provides the fastest available inference for open-source language models, including the entire Llama 3.1 family. + +1. Obtain an API key [here](https://console.groq.com/keys) +2. Update your Continue config file like this: + + + + ```yaml title="Package or config.yaml" + models: + - name: Llama 3.3 70b Versatile + provider: groq + model: llama-3.3-70b-versatile + apiKey: + roles: + - chat + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Llama 3.3 70b Versatile", + "provider": "groq", + "model": "llama-3.3-70b-versatile", + "apiKey": "" + } + ] + } + ``` + + diff --git a/docs/docs/customize/model-providers/more/huggingfaceinferenceapi.md b/docs/docs/customize/model-providers/more/huggingfaceinferenceapi.md deleted file mode 100644 index a2122fc4d..000000000 --- a/docs/docs/customize/model-providers/more/huggingfaceinferenceapi.md +++ /dev/null @@ -1,19 +0,0 @@ -# HuggingFace Inference Endpoints - -Hugging Face Inference Endpoints are an easy way to setup instances of open-source language models on any cloud. Sign up for an account and add billing [here](https://huggingface.co/settings/billing), access the Inference Endpoints [here](https://ui.endpoints.huggingface.co), click on “New endpoint”, and fill out the form (e.g. select a model like [WizardCoder-Python-34B-V1.0](https://huggingface.co/WizardLM/WizardCoder-Python-34B-V1.0)), and then deploy your model by clicking “Create Endpoint”. Change `~/.continue/config.json` to look like this: - -```json title="config.json" -{ - "models": [ - { - "title": "Hugging Face Inference API", - "provider": "huggingface-inference-api", - "model": "MODEL_NAME", - "apiKey": "YOUR_HF_TOKEN", - "apiBase": "INFERENCE_API_ENDPOINT_URL" - } - ] -} -``` - -[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/HuggingFaceInferenceAPI.ts) diff --git a/docs/docs/customize/model-providers/more/huggingfaceinferenceapi.mdx b/docs/docs/customize/model-providers/more/huggingfaceinferenceapi.mdx new file mode 100644 index 000000000..91f37051a --- /dev/null +++ b/docs/docs/customize/model-providers/more/huggingfaceinferenceapi.mdx @@ -0,0 +1,36 @@ +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +# HuggingFace Inference Endpoints + +Hugging Face Inference Endpoints are an easy way to setup instances of open-source language models on any cloud. Sign up for an account and add billing [here](https://huggingface.co/settings/billing), access the Inference Endpoints [here](https://ui.endpoints.huggingface.co), click on “New endpoint”, and fill out the form (e.g. select a model like [WizardCoder-Python-34B-V1.0](https://huggingface.co/WizardLM/WizardCoder-Python-34B-V1.0)), and then deploy your model by clicking “Create Endpoint”. Change `~/.continue/config.json` to look like this: + + + + ```yaml title="config.yaml" + models: + - name: Hugging Face Inference API + provider: huggingface-inference-api + model: MODEL_NAME + apiKey: + apiBase: + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Hugging Face Inference API", + "provider": "huggingface-inference-api", + "model": "MODEL_NAME", + "apiKey": "", + "apiBase": "" + } + ] + } + ``` + + + +[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/HuggingFaceInferenceAPI.ts) diff --git a/docs/docs/customize/model-providers/more/ipex_llm.md b/docs/docs/customize/model-providers/more/ipex_llm.mdx similarity index 54% rename from docs/docs/customize/model-providers/more/ipex_llm.md rename to docs/docs/customize/model-providers/more/ipex_llm.mdx index 47bb18b2a..02d20f89b 100644 --- a/docs/docs/customize/model-providers/more/ipex_llm.md +++ b/docs/docs/customize/model-providers/more/ipex_llm.mdx @@ -1,3 +1,6 @@ +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + # IPEX-LLM :::info @@ -6,35 +9,58 @@ IPEX-LLM supports accelerated Ollama backend to be hosted on Intel GPU. Refer to [this guide](https://ipex-llm.readthedocs.io/en/latest/doc/LLM/Quickstart/ollama_quickstart.html) from IPEX-LLM official documentation about how to install and run Ollama serve accelerated by IPEX-LLM on Intel GPU. You can then configure Continue to use the IPEX-LLM accelerated `"ollama"` provider as follows: -```json title="config.json" -{ - "models": [ - { - "title": "IPEX-LLM", - "provider": "ollama", - "model": "AUTODETECT" - } - ] -} -``` + + + ```yaml title="Package or config.yaml" + models: + - name: IPEX-LLM + provider: ollama + model: AUTODETECT + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "IPEX-LLM", + "provider": "ollama", + "model": "AUTODETECT" + } + ] + } + ``` + + If you would like to reach the Ollama service from another machine, make sure you set or export the environment variable `OLLAMA_HOST=0.0.0.0` before executing the command `ollama serve`. Then, in the Continue configuration, set `'apiBase'` to correspond with the IP address / port of the remote machine. That is, Continue can be configured to be: -```json title="config.json" -{ - "models": [ - { - "title": "IPEX-LLM", - "provider": "ollama", - "model": "AUTODETECT", - "apiBase": "http://your-ollama-service-ip:11434" - } - ] -} -``` + + + ```yaml title="Package or config.yaml" + models: + - name: IPEX-LLM + provider: ollama + model: AUTODETECT + apiBase: http://your-ollama-service-ip:11434 + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "IPEX-LLM", + "provider": "ollama", + "model": "AUTODETECT", + "apiBase": "http://your-ollama-service-ip:11434" + } + ] + } + ``` + + :::tip - If you would like to preload the model before your first conversation with that model in Continue, you could refer to [here](https://ipex-llm.readthedocs.io/en/latest/doc/LLM/Quickstart/continue_quickstart.html#pull-and-prepare-the-model) for more information. - ::: diff --git a/docs/docs/customize/model-providers/more/kindo.md b/docs/docs/customize/model-providers/more/kindo.md deleted file mode 100644 index 9e205c66e..000000000 --- a/docs/docs/customize/model-providers/more/kindo.md +++ /dev/null @@ -1,38 +0,0 @@ -# Kindo - -Kindo offers centralized control over your organization's AI operations, ensuring data protection and compliance with internal policies while supporting various commercial and open-source models. To get started, sign up [here](https://app.kindo.ai/), create an API key in [Settings > API > API Keys](https://app.kindo.ai/settings/api), and choose a model from the list of supported models in the "Available Models" tab or copy and paste the config in [Plugins > Your Configuration](https://app.kindo.ai/plugins). - -## Config Example - -```json title="config.json" -{ - "models": [ - { - "title": "Claude 3.5 Sonnet", - "provider": "kindo", - "model": "claude-3-5-sonnet", - "apiKey": "" - } - ] -} -``` - -## Tab Autocomplete Config Example - -```json title="config.json" -{ - "tabAutocompleteModel": [ - { - "title": "WhiteRabbitNeo", - "provider": "kindo", - "model": "/models/WhiteRabbitNeo-33B-DeepSeekCoder", - "apiKey": "", - "template": "none" - } - ] -} -``` - -## Security - -To update your organization's model access, adjust the controls in [security settings](https://app.kindo.ai/security-settings). diff --git a/docs/docs/customize/model-providers/more/kindo.mdx b/docs/docs/customize/model-providers/more/kindo.mdx new file mode 100644 index 000000000..e788b7e39 --- /dev/null +++ b/docs/docs/customize/model-providers/more/kindo.mdx @@ -0,0 +1,69 @@ +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +# Kindo + +Kindo offers centralized control over your organization's AI operations, ensuring data protection and compliance with internal policies while supporting various commercial and open-source models. To get started, sign up [here](https://app.kindo.ai/), create an API key in [Settings > API > API Keys](https://app.kindo.ai/settings/api), and choose a model from the list of supported models in the "Available Models" tab or copy and paste the config in [Plugins > Your Configuration](https://app.kindo.ai/plugins). + +## Config Example + + + + ```yaml title="Package or config.yaml" + models: + - name: Claude 3.5 Sonnet + provider: kindo + model: claude-3-5-sonnet + apiKey: + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Claude 3.5 Sonnet", + "provider": "kindo", + "model": "claude-3-5-sonnet", + "apiKey": "" + } + ] + } + ``` + + + +## Tab Autocomplete Config Example + + + + ```yaml title="Package or config.yaml" + models: + - name: WhiteRabbitNeo + provider: kindo + model: /models/WhiteRabbitNeo-33B-DeepSeekCoder + apiKey: + roles: + - autocomplete + ``` + + + ```json title="config.json" + { + "tabAutocompleteModel": [ + { + "title": "WhiteRabbitNeo", + "provider": "kindo", + "model": "/models/WhiteRabbitNeo-33B-DeepSeekCoder", + "apiKey": "", + "template": "none" + } + ] + } + ``` + + + +## Security + +To update your organization's model access, adjust the controls in [security settings](https://app.kindo.ai/security-settings). diff --git a/docs/docs/customize/model-providers/more/llamacpp.md b/docs/docs/customize/model-providers/more/llamacpp.md deleted file mode 100644 index 7dbdd47ca..000000000 --- a/docs/docs/customize/model-providers/more/llamacpp.md +++ /dev/null @@ -1,24 +0,0 @@ -# LlamaCpp - -Run the llama.cpp server binary to start the API server. If running on a remote server, be sure to set host to 0.0.0.0: - -```shell -.\server.exe -c 4096 --host 0.0.0.0 -t 16 --mlock -m models\meta\llama\codellama-7b-instruct.Q8_0.gguf -``` - -After it's up and running, change `~/.continue/config.json` to look like this: - -```json title="config.json" -{ - "models": [ - { - "title": "Llama CPP", - "provider": "llama.cpp", - "model": "MODEL_NAME", - "apiBase": "http://localhost:8080" - } - ] -} -``` - -[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/LlamaCpp.ts) diff --git a/docs/docs/customize/model-providers/more/llamacpp.mdx b/docs/docs/customize/model-providers/more/llamacpp.mdx new file mode 100644 index 000000000..291ed0a5a --- /dev/null +++ b/docs/docs/customize/model-providers/more/llamacpp.mdx @@ -0,0 +1,40 @@ +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +# LlamaCpp + +Run the llama.cpp server binary to start the API server. If running on a remote server, be sure to set host to 0.0.0.0: + +```bash +.\server.exe -c 4096 --host 0.0.0.0 -t 16 --mlock -m models\meta\llama\codellama-7b-instruct.Q8_0.gguf +``` + +After it's up and running, change `~/.continue/config.json` to look like this: + + + + ```yaml title="Package or config.yaml" + models: + - name: Llama CPP + provider: llama.cpp + model: MODEL_NAME + apiBase: http://localhost:8080 + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Llama CPP", + "provider": "llama.cpp", + "model": "MODEL_NAME", + "apiBase": "http://localhost:8080" + } + ] + } + ``` + + + +[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/LlamaCpp.ts) diff --git a/docs/docs/customize/model-providers/more/llamafile.md b/docs/docs/customize/model-providers/more/llamafile.md deleted file mode 100644 index 71f4f7f07..000000000 --- a/docs/docs/customize/model-providers/more/llamafile.md +++ /dev/null @@ -1,17 +0,0 @@ -# Llamafile - -A [llamafile](https://github.com/Mozilla-Ocho/llamafile#readme) is a self-contained binary that can run an open-source LLM. You can configure this provider in your config.json as follows: - -```json title="config.json" -{ - "models": [ - { - "title": "Llamafile", - "provider": "llamafile", - "model": "mistral-7b" - } - ] -} -``` - -[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Llamafile.ts) diff --git a/docs/docs/customize/model-providers/more/llamafile.mdx b/docs/docs/customize/model-providers/more/llamafile.mdx new file mode 100644 index 000000000..e674d2f83 --- /dev/null +++ b/docs/docs/customize/model-providers/more/llamafile.mdx @@ -0,0 +1,32 @@ +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +# Llamafile + +A [llamafile](https://github.com/Mozilla-Ocho/llamafile#readme) is a self-contained binary that can run an open-source LLM. You can configure this provider in your config.json as follows: + + + + ```yaml title="config.yaml" + models: + - name: Llamafile + provider: llamafile + model: mistral-7b + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Llamafile", + "provider": "llamafile", + "model": "mistral-7b" + } + ] + } + ``` + + + +[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Llamafile.ts) diff --git a/docs/docs/customize/model-providers/more/lmstudio.md b/docs/docs/customize/model-providers/more/lmstudio.md deleted file mode 100644 index a901f811a..000000000 --- a/docs/docs/customize/model-providers/more/lmstudio.md +++ /dev/null @@ -1,45 +0,0 @@ -# LM Studio - -[LM Studio](https://lmstudio.ai) is an application for Mac, Windows, and Linux that makes it easy to locally run open-source models and comes with a great UI. To get started with LM Studio, download from the website, use the UI to download a model, and then start the local inference server. Continue can then be configured to use the `LMStudio` LLM class: - -```json title="config.json" -{ - "models": [ - { - "title": "LM Studio", - "provider": "lmstudio", - "model": "llama2-7b" - } - ] -} -``` - -### Embeddings model - -LMStudio supports embeddings endpoints, and comes with the `nomic-ai/nomic-embed-text-v1.5-GGUF` model (as of Nov 2024, check your models) - -```json title="config.json" -{ - "embeddingsProvider": { - "provider": "lmstudio", - "model": "nomic-ai/nomic-embed-text-v1.5-GGUF" - } -} -``` - -## Setting up a remote instance - -To configure a remote instance of LM Studio, add the `"apiBase"` property to your model in config.json: - -```json title="config.json" -{ - "title": "LM Studio", - "model": "codestral", - "provider": "lmstudio", - "apiBase": "http://x.x.x.x:1234/v1/" -} -``` - -This `apiBase` will now be used instead of the default `http://localhost:1234/v1`. - -[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/LMStudio.ts) diff --git a/docs/docs/customize/model-providers/more/lmstudio.mdx b/docs/docs/customize/model-providers/more/lmstudio.mdx new file mode 100644 index 000000000..784c321cc --- /dev/null +++ b/docs/docs/customize/model-providers/more/lmstudio.mdx @@ -0,0 +1,88 @@ +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +# LM Studio + +[LM Studio](https://lmstudio.ai) is an application for Mac, Windows, and Linux that makes it easy to locally run open-source models and comes with a great UI. To get started with LM Studio, download from the website, use the UI to download a model, and then start the local inference server. Continue can then be configured to use the `LMStudio` LLM class: + + + + ```yaml title="Package or config.yaml" + models: + - name: LM Studio + provider: lmstudio + model: llama2-7b + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "LM Studio", + "provider": "lmstudio", + "model": "llama2-7b" + } + ] + } + ``` + + + +### Embeddings model + +LMStudio supports embeddings endpoints, and comes with the `nomic-ai/nomic-embed-text-v1.5-GGUF` model (as of Nov 2024, check your models) + + + + ```yaml title="Package or config.yaml" + models: + - name: Nomic Embed Text + provider: lmstudio + model: nomic-ai/nomic-embed-text-v1.5-GGUF + roles: + - embed + ``` + + + ```json title="config.json" + { + "embeddingsProvider": { + "provider": "lmstudio", + "model": "nomic-ai/nomic-embed-text-v1.5-GGUF" + } + } + ``` + + + +## Setting up a remote instance + +To configure a remote instance of LM Studio, add the `"apiBase"` property to your model in config.json: + + + + ```yaml title="Package or config.yaml" + models: + - name: Nomic Embed Text + provider: lmstudio + model: nomic-ai/nomic-embed-text-v1.5-GGUF + roles: + - embed + ``` + + + ```json title="config.json" + { + "embeddingsProvider": { + "provider": "lmstudio", + "model": "nomic-ai/nomic-embed-text-v1.5-GGUF" + } + } + ``` + + + +This `apiBase` will now be used instead of the default `http://localhost:1234/v1`. + +[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/LMStudio.ts) diff --git a/docs/docs/customize/model-providers/more/moonshot.mdx b/docs/docs/customize/model-providers/more/moonshot.mdx new file mode 100644 index 000000000..9fc429f6d --- /dev/null +++ b/docs/docs/customize/model-providers/more/moonshot.mdx @@ -0,0 +1,94 @@ +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +# Moonshot + +[Moonshot AI](https://platform.moonshot.cn/) provides high-quality large language model services with competitive pricing and excellent performance. + +## Configuration + +To use Moonshot AI models, you need to: + +1. Get an API key from [Moonshot AI Platform](https://platform.moonshot.cn/) +2. Add the following configuration: + + + + ```yaml title="Package or config.yaml" + models: + - name: Moonshot + provider: moonshot + model: moonshot-v1-8k + apiKey: + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Moonshot", + "provider": "moonshot", + "model": "moonshot-v1-8k", + "apiKey": "" + } + ] + } + ``` + + + +## Available Models + +Moonshot AI currently provides the following models: + +- `moonshot-v1-8k`: Base model with 8K context window +- `moonshot-v1-32k`: Base model with 32K context window +- `moonshot-v1-128k`: Base model with 128K context window + +## Configuration Options + +| Option | Description | Default | +| --------- | ----------------- | ----------------------------- | +| `apiKey` | Moonshot API key | Required | +| `apiBase` | API base URL | `https://api.moonshot.cn/v1/` | +| `model` | Model name to use | `moonshot-v1-8k` | + +## Example + +Here's a complete configuration example: + + + + ```yaml title="Package or config.yaml" + models: + - name: Moonshot-8K + provider: moonshot + model: moonshot-v1-8k + apiKey: + defaultCompletionOptions: + temperature: 0.7 + topP: 0.95 + maxTokens: 2048 + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Moonshot-8K", + "provider": "moonshot", + "model": "moonshot-v1-8k", + "apiKey": "", + "completionOptions": { + "temperature": 0.7, + "topP": 0.95, + "maxTokens": 2048 + } + } + ] + } + ``` + + diff --git a/docs/docs/customize/model-providers/more/msty.md b/docs/docs/customize/model-providers/more/msty.mdx similarity index 66% rename from docs/docs/customize/model-providers/more/msty.md rename to docs/docs/customize/model-providers/more/msty.mdx index 1fda1d88b..e08d2ffff 100644 --- a/docs/docs/customize/model-providers/more/msty.md +++ b/docs/docs/customize/model-providers/more/msty.mdx @@ -1,19 +1,33 @@ +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + # Msty [Msty](https://msty.app/) is an application for Windows, Mac, and Linux that makes it really easy to run online as well as local open-source models, including Llama-2, DeepSeek Coder, etc. No need to fidget with your terminal, run a command, or anything. Just download the app from the website, click a button, and you are up and running. Continue can then be configured to use the `Msty` LLM class: -```json title="config.json" -{ - "models": [ - { - "title": "Msty", - "provider": "msty", - "model": "deepseek-coder:6.7b", - "completionOptions": {} - } - ] -} -``` + + + ```yaml title="Package or config.yaml" + models: + - name: Msty + provider: msty + model: deepseek-coder:6.7b + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Msty", + "provider": "msty", + "model": "deepseek-coder:6.7b", + } + ] + } + ``` + + ## Completion Options @@ -30,21 +44,36 @@ In addition to the model type, you can also configure some of the parameters tha If you need to send custom headers for authentication, you may use the `requestOptions.headers` property like this: -```json title="config.json" -{ - "models": [ - { - "title": "Msty", - "provider": "msty", - "model": "deepseek-coder:6.7b", - "requestOptions": { - "headers": { - "Authorization": "Bearer xxx" + + + ```yaml title="Package or config.yaml" + models: + - name: Msty + provider: msty + model: deepseek-coder:6.7b + requestOptions: + headers: + Authorization: Bearer xxx + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Msty", + "provider": "msty", + "model": "deepseek-coder:6.7b", + "requestOptions": { + "headers": { + "Authorization": "Bearer xxx" + } } } - } - ] -} -``` + ] + } + ``` + + [View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Msty.ts) diff --git a/docs/docs/customize/model-providers/more/nebius.md b/docs/docs/customize/model-providers/more/nebius.md deleted file mode 100644 index d4cfa344b..000000000 --- a/docs/docs/customize/model-providers/more/nebius.md +++ /dev/null @@ -1,36 +0,0 @@ -# Nebius AI Studio - -You can get an API key from the [Nebius AI Studio API keys page](https://studio.nebius.ai/settings/api-keys) - -## Availible models - -Available models can be found on the [Nebius AI Studio models page](https://studio.nebius.ai/models/text2text) - -## Chat model - -```json title="config.json" -{ - "models": [ - { - "title": "Llama 3.1 405b", - "provider": "nebius", - "model": "llama3.1-405b", - "apiKey": "[API_KEY]" - } - ] -} -``` - -## Embeddings model - -Available models can be found on the [Nebius AI Studio embeddings page](https://studio.nebius.ai/models/embedding) - -```json title="config.json" -{ - "embeddingsProvider": { - "provider": "nebius", - "model": "BAAI/bge-en-icl", - "apiKey": "[API_KEY]" - } -} -``` diff --git a/docs/docs/customize/model-providers/more/nebius.mdx b/docs/docs/customize/model-providers/more/nebius.mdx new file mode 100644 index 000000000..72af4334d --- /dev/null +++ b/docs/docs/customize/model-providers/more/nebius.mdx @@ -0,0 +1,67 @@ +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +# Nebius AI Studio + +You can get an API key from the [Nebius AI Studio API keys page](https://studio.nebius.ai/settings/api-keys) + +## Availible models + +Available models can be found on the [Nebius AI Studio models page](https://studio.nebius.ai/models/text2text) + +## Chat model + + + + ```yaml title="Package or config.yaml" + models: + - name: Llama 3.1 405b + provider: nebius + model: llama3.1-405b + apiKey: + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Llama 3.1 405b", + "provider": "nebius", + "model": "llama3.1-405b", + "apiKey": "" + } + ] + } + ``` + + + +## Embeddings model + +Available models can be found on the [Nebius AI Studio embeddings page](https://studio.nebius.ai/models/embedding) + + + + ```yaml title="config.yaml" + models: + - name: BAAI Embedder + provider: nebius + model: BAAI/bge-en-icl + apiKey: + roles: + - embed + ``` + + + ```json title="config.json" + { + "embeddingsProvider": { + "provider": "nebius", + "model": "BAAI/bge-en-icl", + "apiKey": "" + } + } + ``` + + diff --git a/docs/docs/customize/model-providers/more/novita.md b/docs/docs/customize/model-providers/more/novita.mdx similarity index 64% rename from docs/docs/customize/model-providers/more/novita.md rename to docs/docs/customize/model-providers/more/novita.mdx index 02f7cefb5..bf6e99421 100644 --- a/docs/docs/customize/model-providers/more/novita.md +++ b/docs/docs/customize/model-providers/more/novita.mdx @@ -1,18 +1,34 @@ +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + # Novita [Novita AI](https://novita.ai?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link) offers an affordable, reliable, and simple inference platform with scalable [LLM API](https://novita.ai/docs/model-api/reference/introduction.html), empowering developers to build AI applications. Try the [Novita AI Llama 3 API Demo](https://novita.ai/model-api/product/llm-api/playground/meta-llama-llama-3.1-70b-instruct?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link) today!. You can sign up [here](https://novita.ai/user/login?&redirect=/&utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link), copy your API key on the [Key Management](https://novita.ai/settings/key-management?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link), and then hit the play button on any model from the [Novita AI Models list](https://novita.ai/llm-api?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link). Change `~/.continue/config.json` to look like this: -```json title="config.json" -{ - "models": [ - { - "title": "Llama 3.1 8B", - "provider": "novita", - "model": "meta-llama/llama-3.1-8b-instruct", - "apiKey": "YOUR_API_KEY" - } - ] -} -``` + + + ```yaml title="Package or config.yaml" + models: + - name: Llama 3.1 8B + provider: novita + model: meta-llama/llama-3.1-8b-instruct + apiKey: + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Llama 3.1 8B", + "provider": "novita", + "model": "meta-llama/llama-3.1-8b-instruct", + "apiKey": "" + } + ] + } + ``` + + [View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Novita.ts) diff --git a/docs/docs/customize/model-providers/more/nvidia.md b/docs/docs/customize/model-providers/more/nvidia.md deleted file mode 100644 index 049ff7754..000000000 --- a/docs/docs/customize/model-providers/more/nvidia.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -title: NVIDIA ---- - -:::info - -[View the docs](https://docs.nvidia.com/nim/large-language-models/latest/getting-started.html#option-1-from-api-catalog) to learn how to get an API key. - -::: - -## Chat model - -We recommend configuring **Nemotron-4-340B-Instruct** as your chat model. - -```json title="config.json" -{ - "models": [ - { - "title": "Nemotron-4-340B-Instruct", - "provider": "nvidia", - "model": "nvidia-nemotron-4-340b-instruct", - "apiKey": "[API_KEY]" - } - ] -} -``` - -## Autocomplete model - -NVIDIA 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 **NVIDIA Retrieval QA Mistral 7B** as your embeddings model. - -```json title="config.json" -{ - "embeddingsProvider": { - "provider": "nvidia", - "model": "nvidia/nv-embedqa-mistral-7b-v2", - "apiKey": "[API_KEY]" - } -} -``` - -## Reranking model - -NVIDIA 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/nvidia.mdx b/docs/docs/customize/model-providers/more/nvidia.mdx new file mode 100644 index 000000000..bc395cf0d --- /dev/null +++ b/docs/docs/customize/model-providers/more/nvidia.mdx @@ -0,0 +1,81 @@ +--- +title: NVIDIA +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +:::info +[View the docs](https://docs.nvidia.com/nim/large-language-models/latest/getting-started.html#option-1-from-api-catalog) to learn how to get an API key. +::: + +## Chat model + +We recommend configuring **Nemotron-4-340B-Instruct** as your chat model. + + + + ```yaml title="config.yaml" + models: + - name: Nemotron-4-340B-Instruct + provider: nvidia + model: nvidia-nemotron-4-340b-instruct + apiKey: + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Nemotron-4-340B-Instruct", + "provider": "nvidia", + "model": "nvidia-nemotron-4-340b-instruct", + "apiKey": "" + } + ] + } + ``` + + + +## Autocomplete model + +NVIDIA 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 **NVIDIA Retrieval QA Mistral 7B** as your embeddings model. + + + + ```yaml title="config.yaml" + models: + - name: Nvidia Embedder + provider: nvidia + model: nvidia/nv-embedqa-mistral-7b-v2 + apiKey: + roles: + - embed + ``` + + + ```json title="config.json" + { + "embeddingsProvider": { + "provider": "nvidia", + "model": "nvidia/nv-embedqa-mistral-7b-v2", + "apiKey": "" + } + } + ``` + + + +## Reranking model + +NVIDIA currently does not offer any reranking models. + +[Click here](../../model-types/reranking.mdx) to see a list of reranking model providers. diff --git a/docs/docs/customize/model-providers/more/openrouter.md b/docs/docs/customize/model-providers/more/openrouter.md deleted file mode 100644 index d08f754f5..000000000 --- a/docs/docs/customize/model-providers/more/openrouter.md +++ /dev/null @@ -1,40 +0,0 @@ -# OpenRouter - -OpenRouter is a unified interface for commercial and open-source models, giving you access to the best models at the best prices. You can sign up [here](https://openrouter.ai/signup), create your API key on the [keys page](https://openrouter.ai/keys), and then choose a model from the [list of supported models](https://openrouter.ai/models). - -Change `~/.continue/config.json` to look like the following. - -```json title="config.json" -{ - "models": [ - { - "title": "OpenRouter LLaMA 70 8B", - "provider": "openrouter", - "model": "meta-llama/llama-3-70b-instruct", - "apiBase": "https://openrouter.ai/api/v1", - "apiKey": "..." - } - ] -} -``` - -To utilize features such as provider preferences or model routing configuration, include these parameters inside the `models[].requestsOptions.extraBodyProperties` field of your plugin config. - -For example, to prevent extra long prompts from being compressed, you can explicitly turn off the feature like so: - -```json title="config.json" -{ - "models": [ - { - ... - "requestOptions": { - "extraBodyProperties": { - "transforms": [] - } - } - } - ] -} -``` - -Learn more about available settings [here](https://openrouter.ai/docs). diff --git a/docs/docs/customize/model-providers/more/openrouter.mdx b/docs/docs/customize/model-providers/more/openrouter.mdx new file mode 100644 index 000000000..637366d6e --- /dev/null +++ b/docs/docs/customize/model-providers/more/openrouter.mdx @@ -0,0 +1,74 @@ +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +# OpenRouter + +OpenRouter is a unified interface for commercial and open-source models, giving you access to the best models at the best prices. You can sign up [here](https://openrouter.ai/signup), create your API key on the [keys page](https://openrouter.ai/keys), and then choose a model from the [list of supported models](https://openrouter.ai/models). + +Change `~/.continue/config.json` to look like the following. + + + + ```yaml title="Package or config.yaml" + models: + - name: OpenRouter LLaMA 70 8B + provider: openrouter + model: meta-llama/llama-3-70b-instruct + apiBase: https://openrouter.ai/api/v1 + apiKey: + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "OpenRouter LLaMA 70 8B", + "provider": "openrouter", + "model": "meta-llama/llama-3-70b-instruct", + "apiBase": "https://openrouter.ai/api/v1", + "apiKey": "" + } + ] + } + ``` + + + +To utilize features such as provider preferences or model routing configuration, include these parameters inside the `models[].requestsOptions.extraBodyProperties` field of your plugin config. + +For example, to prevent extra long prompts from being compressed, you can explicitly turn off the feature like so: + + + + ```yaml title="Package or config.yaml" + models: + - name: Example Model + provider: exampleProvider + model: example-model + requestOptions: + extraBodyProperties: + transforms: [] + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Example Model", + "provider": "exampleProvider", + "model": "example-model", + "requestOptions": { + "extraBodyProperties": { + "transforms": [] + } + } + } + ] + } + ``` + + + +Learn more about available settings [here](https://openrouter.ai/docs). diff --git a/docs/docs/customize/model-providers/more/replicatellm.md b/docs/docs/customize/model-providers/more/replicatellm.mdx similarity index 50% rename from docs/docs/customize/model-providers/more/replicatellm.md rename to docs/docs/customize/model-providers/more/replicatellm.mdx index 065825729..958fc347a 100644 --- a/docs/docs/customize/model-providers/more/replicatellm.md +++ b/docs/docs/customize/model-providers/more/replicatellm.mdx @@ -1,19 +1,35 @@ +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + # ReplicateLLM Replicate is a great option for newly released language models or models that you've deployed through their platform. Sign up for an account [here](https://replicate.ai/), copy your API key, and then select any model from the [Replicate Streaming List](https://replicate.com/collections/streaming-language-models). Change `~/.continue/config.json` to look like this: -```json title="config.json" -{ - "models": [ - { - "title": "Replicate CodeLLama", - "provider": "replicate", - "model": "codellama-13b", - "apiKey": "YOUR_API_KEY" - } - ] -} -``` + + + ```yaml title="Package or config.yaml" + models: + - name: Replicate CodeLLama + provider: replicate + model: codellama-13b + apiKey: + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Replicate CodeLLama", + "provider": "replicate", + "model": "codellama-13b", + "apiKey": "" + } + ] + } + ``` + + If you don't specify the `model` parameter, it will default to `replicate/llama-2-70b-chat:58d078176e02c219e11eb4da5a02a7830a283b14cf8f94537af893ccff5ee781`. diff --git a/docs/docs/customize/model-providers/more/sagemaker.md b/docs/docs/customize/model-providers/more/sagemaker.md deleted file mode 100644 index 0c9eba812..000000000 --- a/docs/docs/customize/model-providers/more/sagemaker.md +++ /dev/null @@ -1,34 +0,0 @@ -# AWS SageMaker - -SageMaker can be used for both chat and embedding models. Chat models are supported for endpoints deployed with [LMI](https://docs.djl.ai/docs/serving/serving/docs/lmi/index.html), and embedding models are supported for endpoints deployed with [HuggingFace TEI](https://huggingface.co/blog/sagemaker-huggingface-embedding) - -To setup SageMaker as a chat model provider, add the following to your `config.json` file: - -```json title="config.json" -{ - "models": [ - { - "title": "deepseek-6.7b-instruct", - "provider": "sagemaker", - "model": "lmi-model-deepseek-coder-xxxxxxx", - "region": "us-west-2" - } - ], - "embeddingsProvider": { - "provider": "sagemaker", - "model": "mxbai-embed-large-v1-endpoint" - }, -} -``` - -The value in model should be the SageMaker endpoint name you deployed. - -Authentication will be through temporary or long-term credentials in -~/.aws/credentials under a profile called "sagemaker". - -```title="~/.aws/credentials -[sagemaker] -aws_access_key_id = abcdefg -aws_secret_access_key = hijklmno -aws_session_token = pqrstuvwxyz # Optional: means short term creds. -``` diff --git a/docs/docs/customize/model-providers/more/sagemaker.mdx b/docs/docs/customize/model-providers/more/sagemaker.mdx new file mode 100644 index 000000000..33aa6e253 --- /dev/null +++ b/docs/docs/customize/model-providers/more/sagemaker.mdx @@ -0,0 +1,57 @@ +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +# AWS SageMaker + +SageMaker can be used for both chat and embedding models. Chat models are supported for endpoints deployed with [LMI](https://docs.djl.ai/docs/serving/serving/docs/lmi/index.html), and embedding models are supported for endpoints deployed with [HuggingFace TEI](https://huggingface.co/blog/sagemaker-huggingface-embedding) + +Here is an example Sagemaker configuration setup: + + + + ```yaml title="config.yaml" + models: + - name: deepseek-6.7b-instruct + provider: sagemaker + model: lmi-model-deepseek-coder-xxxxxxx + region: us-west-2 + roles: + - chat + - name: mxbai-embed + provider: sagemaker + model: mxbai-embed-large-v1-endpoint + roles: + - embed + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "deepseek-6.7b-instruct", + "provider": "sagemaker", + "model": "lmi-model-deepseek-coder-xxxxxxx", + "region": "us-west-2" + } + ], + "embeddingsProvider": { + "provider": "sagemaker", + "model": "mxbai-embed-large-v1-endpoint" + } + } + ``` + + + +The value in model should be the SageMaker endpoint name you deployed. + +Authentication will be through temporary or long-term credentials in +~/.aws/credentials under a profile called "sagemaker". + +```title="~/.aws/credentials +[sagemaker] +aws_access_key_id = abcdefg +aws_secret_access_key = hijklmno +aws_session_token = pqrstuvwxyz # Optional: means short term creds. +``` diff --git a/docs/docs/customize/model-providers/more/scaleway.md b/docs/docs/customize/model-providers/more/scaleway.md deleted file mode 100644 index 411e95f3a..000000000 --- a/docs/docs/customize/model-providers/more/scaleway.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -title: Scaleway ---- - -:::info - -Scaleway Generative APIs give you instant access to leading AI models hosted in European data centers, ideal for developers requiring low latency, full data privacy, and compliance with EU AI Act. -You can generate your API key in [Scaleway's console](https://console.scaleway.com/generative-api/models). -Read the [quickstart documentation here](https://www.scaleway.com/en/docs/ai-data/generative-apis/quickstart/). - -::: - -## Chat model - -We recommend configuring **Qwen2.5-Coder-32B-Instruct** as your chat model. -[Click here](https://www.scaleway.com/en/docs/ai-data/generative-apis/reference-content/supported-models/) to see the list of available chat models. - -```json title="config.json" -{ - "models": [ - { - "title": "Qwen2.5-Coder-32B-Instruct", - "provider": "scaleway", - "model": "qwen2.5-coder-32b-instruct", - "apiKey": "[API_KEY]" - } - ] -} -``` - -## Autocomplete model - -Scaleway 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 **BGE-Multilingual-Gemma2** as your embeddings model. - -```json title="config.json" -{ - "embeddingsProvider": { - "provider": "scaleway", - "model": "bge-multilingual-gemma2", - "apiKey": "[API_KEY]" - } -} -``` \ No newline at end of file diff --git a/docs/docs/customize/model-providers/more/scaleway.mdx b/docs/docs/customize/model-providers/more/scaleway.mdx new file mode 100644 index 000000000..462c362b5 --- /dev/null +++ b/docs/docs/customize/model-providers/more/scaleway.mdx @@ -0,0 +1,78 @@ +--- +title: Scaleway +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +:::info +Scaleway Generative APIs give you instant access to leading AI models hosted in European data centers, ideal for developers requiring low latency, full data privacy, and compliance with EU AI Act. +You can generate your API key in [Scaleway's console](https://console.scaleway.com/generative-api/models). +Read the [quickstart documentation here](https://www.scaleway.com/en/docs/ai-data/generative-apis/quickstart/). +::: + +## Chat model + +We recommend configuring **Qwen2.5-Coder-32B-Instruct** as your chat model. +[Click here](https://www.scaleway.com/en/docs/ai-data/generative-apis/reference-content/supported-models/) to see the list of available chat models. + + + + ```yaml title="Package or config.yaml" + models: + - name: Qwen2.5-Coder-32B-Instruct + provider: scaleway + model: qwen2.5-coder-32b-instruct + apiKey: + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Qwen2.5-Coder-32B-Instruct", + "provider": "scaleway", + "model": "qwen2.5-coder-32b-instruct", + "apiKey": "" + } + ] + } + ``` + + + +## Autocomplete model + +Scaleway 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 **BGE-Multilingual-Gemma2** as your embeddings model. + + + + ```yaml title="config.yaml" + models: + - name: BGE Multilingual Gemma2 + provider: scaleway + model: bge-multilingual-gemma2 + apiKey: + roles: + - embed + ``` + + + ```json title="config.json" + { + "embeddingsProvider": { + "provider": "scaleway", + "model": "bge-multilingual-gemma2", + "apiKey": "" + } + } + ``` + + diff --git a/docs/docs/customize/model-providers/more/siliconflow.md b/docs/docs/customize/model-providers/more/siliconflow.md deleted file mode 100644 index c27fbbdaf..000000000 --- a/docs/docs/customize/model-providers/more/siliconflow.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -title: SiliconFlow ---- - -:::info - -You can get an API key from the [Silicon Cloud](https://cloud.siliconflow.cn/account/ak). - -::: - -## Chat model - -We recommend configuring **Qwen/Qwen2.5-Coder-32B-Instruct** as your chat model. - -```json title="config.json" -{ - "models": [ - { - "title": "Qwen", - "provider": "siliconflow", - "model": "Qwen/Qwen2.5-Coder-32B-Instruct", - "apiKey": "[API_KEY]" - } - ] -} -``` - -## Autocomplete model - -We recommend configuring **Qwen/Qwen2.5-Coder-7B-Instruct** as your autocomplete model. - -```json title="config.json" -{ - "tabAutocompleteModel": { - "title": "Qwen", - "provider": "siliconflow", - "model": "Qwen/Qwen2.5-Coder-7B-Instruct", - "apiKey": "[API_KEY]" - } -} -``` - -## Embeddings model - -SiliconFlow provide some embeddings models, [Click here](https://siliconflow.cn/models) to see a list of embeddings models. - -## Reranking model - -SiliconFlow provide some reranking models, [Click here](https://siliconflow.cn/models) to see a list of reranking models. diff --git a/docs/docs/customize/model-providers/more/siliconflow.mdx b/docs/docs/customize/model-providers/more/siliconflow.mdx new file mode 100644 index 000000000..a496d3757 --- /dev/null +++ b/docs/docs/customize/model-providers/more/siliconflow.mdx @@ -0,0 +1,88 @@ +--- +title: SiliconFlow +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +:::info +You can get an API key from the [Silicon Cloud](https://cloud.siliconflow.cn/account/ak). +::: + +## Chat model + +We recommend configuring **Qwen/Qwen2.5-Coder-32B-Instruct** as your chat model. + + + + ```yaml title="config.yaml" + models: + - name: Qwen + provider: siliconflow + model: Qwen/Qwen2.5-Coder-32B-Instruct + apiKey: + roles: + - chat + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Qwen", + "provider": "siliconflow", + "model": "Qwen/Qwen2.5-Coder-32B-Instruct", + "apiKey": "" + } + ] + } + ``` + + + +## Autocomplete model + +We recommend configuring **Qwen/Qwen2.5-Coder-7B-Instruct** as your autocomplete model. + + + + ```yaml title="config.yaml" + models: + - name: Qwen + provider: siliconflow + model: Qwen/Qwen2.5-Coder-32B-Instruct + apiKey: + roles: + - autocomplete + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Qwen", + "provider": "siliconflow", + "model": "Qwen/Qwen2.5-Coder-32B-Instruct", + "apiKey": "" + } + ] + "tabAutocompleteModel": { + "title": "Qwen", + "provider": "siliconflow", + "model": "Qwen/Qwen2.5-Coder-7B-Instruct", + "apiKey": "" + } + } + ``` + + + +## Embeddings model + +SiliconFlow provide some embeddings models, [Click here](https://siliconflow.cn/models) to see a list of embeddings models. + +## Reranking model + +SiliconFlow provide some reranking models, [Click here](https://siliconflow.cn/models) to see a list of reranking models. diff --git a/docs/docs/customize/model-providers/more/textgenwebui.md b/docs/docs/customize/model-providers/more/textgenwebui.md deleted file mode 100644 index 723079735..000000000 --- a/docs/docs/customize/model-providers/more/textgenwebui.md +++ /dev/null @@ -1,16 +0,0 @@ -# TextGenWebUI - -TextGenWebUI is a comprehensive, open-source language model UI and local server. You can set it up with an OpenAI-compatible server plugin, and then configure it in your `config.json` like this: - -```json title="config.json" -{ - "models": [ - { - "title": "Text Generation WebUI", - "provider": "text-gen-webui", - "apiBase": "http://localhost:5000/v1", - "model": "MODEL_NAME" - } - ] -} -``` diff --git a/docs/docs/customize/model-providers/more/textgenwebui.mdx b/docs/docs/customize/model-providers/more/textgenwebui.mdx new file mode 100644 index 000000000..0bfcbb442 --- /dev/null +++ b/docs/docs/customize/model-providers/more/textgenwebui.mdx @@ -0,0 +1,32 @@ +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +# TextGenWebUI + +TextGenWebUI is a comprehensive, open-source language model UI and local server. You can set it up with an OpenAI-compatible server plugin, and then configure it like this: + + + + ```yaml title="Package or config.yaml" + models: + - name: Text Generation WebUI + provider: text-gen-webui + apiBase: http://localhost:5000/v1 + model: MODEL_NAME + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Text Generation WebUI", + "provider": "text-gen-webui", + "apiBase": "http://localhost:5000/v1", + "model": "MODEL_NAME" + } + ] + } + ``` + + diff --git a/docs/docs/customize/model-providers/more/together.md b/docs/docs/customize/model-providers/more/together.md deleted file mode 100644 index e5ed9abd0..000000000 --- a/docs/docs/customize/model-providers/more/together.md +++ /dev/null @@ -1,18 +0,0 @@ -# Together - -The Together API is a cloud platform for running large AI models. You can sign up [here](https://api.together.xyz/signup), copy your API key on the initial welcome screen, and then hit the play button on any model from the [Together Models list](https://docs.together.ai/docs/serverless-models). Change `~/.continue/config.json` to look like this: - -```json title="config.json" -{ - "models": [ - { - "title": "Together Qwen2.5 Coder", - "provider": "together", - "model": "Qwen/Qwen2.5-Coder-32B-Instruct", - "apiKey": "YOUR_API_KEY" - } - ] -} -``` - -[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Together.ts) diff --git a/docs/docs/customize/model-providers/more/together.mdx b/docs/docs/customize/model-providers/more/together.mdx new file mode 100644 index 000000000..8af923471 --- /dev/null +++ b/docs/docs/customize/model-providers/more/together.mdx @@ -0,0 +1,34 @@ +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +# Together + +The Together API is a cloud platform for running large AI models. You can sign up [here](https://api.together.xyz/signup), copy your API key on the initial welcome screen, and then hit the play button on any model from the [Together Models list](https://docs.together.ai/docs/serverless-models). Change `~/.continue/config.json` to look like this: + + + + ```yaml title="Package or config.yaml" + models: + - name: Together Qwen2.5 Coder + provider: together + model: Qwen/Qwen2.5-Coder-32B-Instruct + apiKey: + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Together Qwen2.5 Coder", + "provider": "together", + "model": "Qwen/Qwen2.5-Coder-32B-Instruct", + "apiKey": "" + } + ] + } + ``` + + + +[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Together.ts) diff --git a/docs/docs/customize/model-providers/more/vllm.md b/docs/docs/customize/model-providers/more/vllm.md deleted file mode 100644 index fe6932cc5..000000000 --- a/docs/docs/customize/model-providers/more/vllm.md +++ /dev/null @@ -1,59 +0,0 @@ -# vLLM - -vLLM is an open-source library for fast LLM inference which typically is used to serve multiple users at the same. It can also be used to run a large model on multiple GPU:s (e.g. when it doesn´t fit in a single GPU). Run their OpenAI-compatible server using `vllm serve`. See their [server documentation](https://docs.vllm.ai/en/latest/serving/openai_compatible_server.html) and the [engine arguments documentation](https://docs.vllm.ai/en/latest/usage/engine_args.html). - -```shell -vllm serve meta-llama/Meta-Llama-3.1-8B-Instruct -``` -## Chat model - -We recommend configuring **Llama3.1 8B** as your chat model. - -```json title="config.json" -{ - "models": [ - { - "title": "Llama3.1 8B Instruct", - "provider": "vllm", - "model": "meta-llama/Meta-Llama-3.1-8B-Instruct", - "apiBase": "http:///v1" - } - ] -} -``` - -## Autocomplete model - -We recommend configuring **Qwen2.5-Coder 1.5B** as your autocomplete model. - -```json title="config.json" -{ - "tabAutocompleteModel": { - "title": "Qwen2.5-Coder 1.5B", - "provider": "vllm", - "model": "Qwen/Qwen2.5-Coder-1.5B" - "apiBase": "http:///v1" - } -} -``` - -## Embeddings model - -We recommend configuring **Nomic Embed Text** as your embeddings model. - -```json title="config.json" -{ - "embeddingsProvider": { - "provider": "vllm", - "model": "nomic-ai/nomic-embed-text-v1" - "apiBase": "http:///v1" - } -} -``` - -## Reranking model - -[Click here](../../model-types/reranking.md) to see a list of reranking model providers. - - -The continue implementation uses [OpenAI](../top-level/openai.md) under the hood. [View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Vllm.ts) diff --git a/docs/docs/customize/model-providers/more/vllm.mdx b/docs/docs/customize/model-providers/more/vllm.mdx new file mode 100644 index 000000000..1c49ef620 --- /dev/null +++ b/docs/docs/customize/model-providers/more/vllm.mdx @@ -0,0 +1,105 @@ +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +# vLLM + +vLLM is an open-source library for fast LLM inference which typically is used to serve multiple users at the same. It can also be used to run a large model on multiple GPU:s (e.g. when it doesn´t fit in a single GPU). Run their OpenAI-compatible server using `vllm serve`. See their [server documentation](https://docs.vllm.ai/en/latest/serving/openai_compatible_server.html) and the [engine arguments documentation](https://docs.vllm.ai/en/latest/usage/engine_args.html). + +```shell +vllm serve meta-llama/Meta-Llama-3.1-8B-Instruct +``` + +## Chat model + +We recommend configuring **Llama3.1 8B** as your chat model. + + + + ```yaml title="config.yaml" + models: + - name: Llama3.1 8B Instruct + provider: vllm + model: meta-llama/Meta-Llama-3.1-8B-Instruct + apiBase: http:///v1 + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Llama3.1 8B Instruct", + "provider": "vllm", + "model": "meta-llama/Meta-Llama-3.1-8B-Instruct", + "apiBase": "http:///v1" + } + ] + } + ``` + + + +## Autocomplete model + +We recommend configuring **Qwen2.5-Coder 1.5B** as your autocomplete model. + + + + ```yaml title="Package or config.yaml" + models: + - name: Qwen2.5-Coder 1.5B + provider: vllm + model: Qwen/Qwen2.5-Coder-1.5B + apiBase: http:///v1 + roles: + - autocomplete + ``` + + + ```json title="config.json" + { + "tabAutocompleteModel": { + "title": "Qwen2.5-Coder 1.5B", + "provider": "vllm", + "model": "Qwen/Qwen2.5-Coder-1.5B", + "apiBase": "http:///v1" + } + } + ``` + + + +## Embeddings model + +We recommend configuring **Nomic Embed Text** as your embeddings model. + + + + ```yaml title="Package or config.yaml" + models: + - name: VLLM Nomad Embed Text + provider: vllm + model: nomic-ai/nomic-embed-text-v1 + apiBase: http:///v1 + roles: + - embed + ``` + + + ```json title="config.json" + { + "embeddingsProvider": { + "provider": "vllm", + "model": "nomic-ai/nomic-embed-text-v1", + "apiBase": "http:///v1" + } + } + ``` + + + +## Reranking model + +[Click here](../../model-types/reranking.mdx) to see a list of reranking model providers. + +The continue implementation uses [OpenAI](../top-level/openai.mdx) under the hood. [View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Vllm.ts) diff --git a/docs/docs/customize/model-providers/more/watsonx.md b/docs/docs/customize/model-providers/more/watsonx.md deleted file mode 100644 index eeeb6073f..000000000 --- a/docs/docs/customize/model-providers/more/watsonx.md +++ /dev/null @@ -1,146 +0,0 @@ -# IBM watsonx - -watsonx, 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. - -## Setup - -Accessing watsonx models can be done either through watsonx SaaS on IBM Cloud or using a dedicated watsonx.ai Software instance. - -### watsonx.ai SaaS - IBM Cloud - -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 [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 **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 **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 **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. - -```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", - "projectId": "PROJECT_ID", - "apiKey": "API_KEY/ZENAPI_KEY/USERNAME:PASSWORD", - "apiVersion": "2024-03-14" - } - ] -} -``` - -`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 - -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": "ibm/granite-20b-code-instruct", - "title": "Granite Code 20b", - "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", - "template": "granite", - "contextLength": 8000, - "completionOptions": { - "temperature": 0.1, - "topP": 0.3, - "topK": 20, - "maxTokens": 2000, - "frequencyPenalty": 1.1, - "stop": [ - "Question:", - "\n\n\n" - ] - } - } - ] -} -``` - -## Tab Auto Complete Model - -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/more/watsonx.mdx b/docs/docs/customize/model-providers/more/watsonx.mdx new file mode 100644 index 000000000..e18b3e285 --- /dev/null +++ b/docs/docs/customize/model-providers/more/watsonx.mdx @@ -0,0 +1,242 @@ +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +# IBM watsonx + +watsonx, 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. + +## Setup + +Accessing watsonx models can be done either through watsonx SaaS on IBM Cloud or using a dedicated watsonx.ai Software instance. + +### watsonx.ai SaaS - IBM Cloud + +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 [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 **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 **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 **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: + + + + ```yaml title="Package or config.yaml" + models: + - name: watsonx - Model Name + provider: watsonx + model: model ID + apiBase: https://us-south.ml.cloud.ibm.com + projectId: PROJECT_ID + apiKey: API_KEY/ZENAPI_KEY/USERNAME:PASSWORD + apiVersion: 2024-03-14 + ``` + + + ```json title="config.json" + { + "models": [ + { + "model": "model ID", + "title": "watsonx - Model Name", + "provider": "watsonx", + "apiBase": "https://us-south.ml.cloud.ibm.com", + "projectId": "PROJECT_ID", + "apiKey": "API_KEY/ZENAPI_KEY/USERNAME:PASSWORD", + "apiVersion": "2024-03-14" + } + ] + } + ``` + + + +`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. + + + + ```yaml title="Package or config.yaml" + models: + - name: watsonx - Model Name + provider: watsonx + model: model ID + 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 + ``` + + + ```json title="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 + +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: + + + + ```yaml title="config.yaml" + models: + - name: Granite Code 20b + provider: watsonx + model: ibm/granite-20b-code-instruct + 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 + defaultCompletionOptions: + temperature: 0.1 + topP: 0.3 + topK: 20 + maxTokens: 2000 + frequencyPenalty: 1.1 + stop: + - Question: + - "\n\n\n" + ``` + + + ```json title="config.json" + { + "models": [ + { + "model": "ibm/granite-20b-code-instruct", + "title": "Granite Code 20b", + "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", + "template": "granite", + "contextLength": 8000, + "completionOptions": { + "temperature": 0.1, + "topP": 0.3, + "topK": 20, + "maxTokens": 2000, + "frequencyPenalty": 1.1, + "stop": ["Question:", "\n\n\n"] + } + } + ] + } + ``` + + + +## Tab Auto Complete Model + +Granite models are recommended for tab auto complete. The configuration is similar to that of the chat models: + + + + ```yaml title="Package or config.yaml" + models: + - name: Granite Code 8b + provider: watsonx + model: ibm/granite-8b-code-instruct + 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 + roles: + - autocomplete + ``` + + + ```json title="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). + + + + ```yaml title="config.yaml" + models: + - name: Watsonx Embedder + provider: watsonx + model: ibm/slate-30m-english-rtrvr-v2 + apiBase: https://us-south.ml.cloud.ibm.com + projectId: PROJECT_ID + apiKey: API_KEY/ZENAPI_KEY/USERNAME:PASSWORD + apiVersion: 2024-03-14 + roles: + - embed + ``` + + + ```json title="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/anthropic.md b/docs/docs/customize/model-providers/top-level/anthropic.md deleted file mode 100644 index 9333a8e84..000000000 --- a/docs/docs/customize/model-providers/top-level/anthropic.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -title: Anthropic -slug: ../anthropic ---- - -:::info - -You can get an API key from the [Anthropic console](https://console.anthropic.com/account/keys). - -::: - -## 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", - "model": "claude-3-5-sonnet-latest", - "apiKey": "[API_KEY]" - } - ] -} -``` - -## Autocomplete model - -Anthropic currently does not offer any autocomplete models. - -[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers. - -## Embeddings model - -Anthropic currently does not offer any embeddings models. - -[Click here](../../model-types/embeddings.md) to see a list of embeddings model providers. - -## Reranking model - -Anthropic currently does not offer any reranking models. - -[Click here](../../model-types/reranking.md) to see a list of reranking model providers. - -## Prompt caching - -Anthropic 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: - -```json -{ - "models": [ - { - // Enable prompt caching - "cacheBehavior": { - "cacheSystemMessage": true, - "cacheConversation": true - }, - "title": "Anthropic", - "provider": "anthropic", - "model": "claude-3-5-sonnet-latest", - "apiKey": "[API_KEY]" - } - ] -} -``` diff --git a/docs/docs/customize/model-providers/top-level/anthropic.mdx b/docs/docs/customize/model-providers/top-level/anthropic.mdx new file mode 100644 index 000000000..7844cf49c --- /dev/null +++ b/docs/docs/customize/model-providers/top-level/anthropic.mdx @@ -0,0 +1,100 @@ +--- +title: Anthropic +slug: ../anthropic +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +:::info +You can get an API key from the [Anthropic console](https://console.anthropic.com/account/keys). +::: + +## Chat model + +We recommend configuring **Claude 3.5 Sonnet** as your chat model. + + + + ```yaml title="config.yaml" + models: + - name: Claude 3.5 Sonnet + provider: anthropic + model: claude-3-5-sonnet-latest + apiKey: + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Claude 3.5 Sonnet", + "provider": "anthropic", + "model": "claude-3-5-sonnet-latest", + "apiKey": "" + } + ] + } + ``` + + + +## Autocomplete model + +Anthropic currently does not offer any autocomplete models. + +[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers. + +## Embeddings model + +Anthropic currently does not offer any embeddings models. + +[Click here](../../model-types/embeddings.mdx) to see a list of embeddings model providers. + +## Reranking model + +Anthropic currently does not offer any reranking models. + +[Click here](../../model-types/reranking.mdx) to see a list of reranking model providers. + +## Prompt caching + +Anthropic 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: + + + + ```yaml title="Package or config.yaml" + models: + - name: Anthropic + provider: anthropic + model: claude-3-5-sonnet-latest + apiKey: + roles: + - chat + cacheBehavior: + cacheSystemMessage: true + cacheConversation: true + ``` + + + ```json title="config.json" + { + "models": [ + { + "cacheBehavior": { + "cacheSystemMessage": true, + "cacheConversation": true + }, + "title": "Anthropic", + "provider": "anthropic", + "model": "claude-3-5-sonnet-latest", + "apiKey": "" + } + ] + } + ``` + + diff --git a/docs/docs/customize/model-providers/top-level/azure.md b/docs/docs/customize/model-providers/top-level/azure.md deleted file mode 100644 index 45b49f734..000000000 --- a/docs/docs/customize/model-providers/top-level/azure.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -title: Azure AI Foundry -slug: ../azure ---- - -Azure AI Foundry is a cloud-based service that provides access to models from OpenAI, Mistral AI, and others, integrated with the security and enterprise features of the Microsoft Azure platform. To get started, create an Azure AI Foundry resource in the [Azure portal](https://portal.azure.com). - -:::info - -For details on OpenAI model setup, see [Azure OpenAI Service configuration](#general-model-configuration). - -::: - -## Chat model - -We recommend configuring **GPT-4o** as your chat model. - -```json title="config.json" -"models": [{ - "title": "GPT-4o", - "provider": "azure", - "model": "gpt-4o", - "apiBase": "", - "deployment": "", - "apiKey": "" // If you use subscription key, try using Azure gateway to rename it apiKey -}] -``` - -## Autocomplete model - -We recommend configuring **Codestral** as your autocomplete model. - -```json title="config.json" -{ - "tabAutocompleteModel": { - "title": "Codestral", - "provider": "mistral", - "model": "codestral-latest" - } -} -``` - -## Embeddings model - -We recommend configuring **text-embedding-3-large** as your embeddings model. - -```json title="config.json" -"embeddingsProvider": { - "provider": "openai", - "model": "text-embedding-3-large", - "apiBase": "", - "deployment": "", - "apiType": "azure", - "apiKey": "" -} -``` - -## Reranking model - -Azure OpenAI currently does not offer any reranking models. - -[Click here](../../model-types/reranking.md) to see a list of reranking models. - -## Privacy - -If you'd like to use OpenAI models but are concerned about privacy, you can use the Azure OpenAI service, which is GDPR and HIPAA compliant. - -:::info[Getting access] -You need to apply for access to the Azure OpenAI service. Response times are typically within a few days. - -**[Click here to apply for access to the Azure OpenAI service](https://azure.microsoft.com/en-us/products/ai-services/openai-service)** -::: - -## Azure OpenAI Service configuration - -Azure OpenAI Service requires a handful of additional parameters to be configured, such as a deployment name and API base URL. - -To find this information in _Azure AI Foundry_, first select the model that you would like to connect. Then visit _Endpoint_ > _Target URI_. - -For example, a Target URI of `https://just-an-example.openai.azure.com/openai/deployments/gpt-4o-july/chat/completions?api-version=2023-03-15-preview` would map to the following: - -```json -{ - "title": "GPT-4o Azure", - "model": "gpt-4o", - "provider": "openai", - "apiBase": "https://just-an-example.openai.azure.com", - "deployment": "gpt-4o-july", - "apiVersion": "2023-03-15-preview", - "apiKey": "" -} -``` diff --git a/docs/docs/customize/model-providers/top-level/azure.mdx b/docs/docs/customize/model-providers/top-level/azure.mdx new file mode 100644 index 000000000..a4f1a3f93 --- /dev/null +++ b/docs/docs/customize/model-providers/top-level/azure.mdx @@ -0,0 +1,165 @@ +--- +title: Azure AI Foundry +slug: ../azure +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +Azure AI Foundry is a cloud-based service that provides access to models from OpenAI, Mistral AI, and others, integrated with the security and enterprise features of the Microsoft Azure platform. To get started, create an Azure AI Foundry resource in the [Azure portal](https://portal.azure.com). + +:::info + +For details on OpenAI model setup, see [Azure OpenAI Service configuration](#azure-openai-service-configuration). + +::: + +## Chat model + +We recommend configuring **GPT-4o** as your chat model. + + + + ```yaml title="config.yaml" + models: + - name: GPT-4o + provider: azure + model: gpt-4o + apiBase: + deployment: + apiKey: # If you use subscription key, try using Azure gateway to rename it apiKey + env: + apiType: azure-foundry # Or "azure-openai" if using OpenAI models + ``` + + + ```json title="config.json" + { + "models": [{ + "title": "GPT-4o", + "provider": "azure", + "model": "gpt-4o", + "apiBase": "", + "deployment": "", + "apiKey": "", // If you use subscription key, try using Azure gateway to rename it apiKey + "apiType": "azure-foundry" // Or "azure-openai" if using OpenAI models + }] + } + ``` + + + +## Autocomplete model + +We recommend configuring **Codestral** as your autocomplete model. + + + + ```yaml title="Package or config.yaml" + models: + - name: Codestral + provider: mistral + model: codestral-latest + roles: + - autocomplete + ``` + + + ```json title="config.json" + { + "tabAutocompleteModel": { + "title": "Codestral", + "provider": "mistral", + "model": "codestral-latest" + } + } + ``` + + + +## Embeddings model + +We recommend configuring **text-embedding-3-large** as your embeddings model. + + + + ```yaml title="Package or config.yaml" + models: + - name: Text Embedding-3 Large + provider: azure + model: text-embedding-3-large + apiBase: + deployment: + apiKey: + env: + apiType: azure + ``` + + + ```json title="config.json" + { + "embeddingsProvider": { + "provider": "azure", + "model": "text-embedding-3-large", + "apiBase": "", + "deployment": "", + "apiKey": "", + "apiType": "azure-foundry" // Or "azure-openai" if using OpenAI models + } + } + ``` + + + +## Reranking model + +Azure OpenAI currently does not offer any reranking models. + +[Click here](../../model-types/reranking.mdx) to see a list of reranking models. + +## Privacy + +If you'd like to use OpenAI models but are concerned about privacy, you can use the Azure OpenAI service, which is GDPR and HIPAA compliant. + +:::info[Getting access] +[Click here](https://azure.microsoft.com/en-us/products/ai-services/openai-service) to apply for access to the Azure OpenAI service. Response times are typically within a few days. +::: + +## Azure OpenAI Service configuration + +Azure OpenAI Service requires a handful of additional parameters to be configured, such as a deployment name and API base URL. + +To find this information in _Azure AI Foundry_, first select the model that you would like to connect. Then visit _Endpoint_ > _Target URI_. + +For example, a Target URI of `https://just-an-example.openai.azure.com/openai/deployments/gpt-4o-july/chat/completions?api-version=2023-03-15-preview` would map to the following: + + + + ```yaml title="Package or config.yaml" + models: + - name: GPT-4o Azure + model: gpt-4o + provider: openai + apiBase: https://just-an-example.openai.azure.com + deployment: gpt-4o-july + apiVersion: 2023-03-15-preview + apiKey: + env: + apiType: azure-openai + ``` + + + ```json title="config.json" + { + "title": "GPT-4o Azure", + "model": "gpt-4o", + "provider": "openai", + "apiBase": "https://just-an-example.openai.azure.com", + "deployment": "gpt-4o-july", + "apiVersion": "2023-03-15-preview", + "apiKey": "", + "apiType": "azure-openai" + } + ``` + + diff --git a/docs/docs/customize/model-providers/top-level/bedrock.md b/docs/docs/customize/model-providers/top-level/bedrock.md deleted file mode 100644 index c2fab040a..000000000 --- a/docs/docs/customize/model-providers/top-level/bedrock.md +++ /dev/null @@ -1,118 +0,0 @@ ---- -title: Amazon Bedrock -slug: ../bedrock ---- - -Amazon Bedrock is a fully managed service on AWS that provides access to foundation models from various AI companies through a single API. - -## Chat model - -We recommend configuring **Claude 3.5 Sonnet** as your chat model. - -```json title="config.json" -{ - "models": [ - { - "title": "Claude 3.5 Sonnet", - "provider": "bedrock", - "model": "anthropic.claude-3-5-sonnet-20240620-v1:0", - "region": "us-east-1", - "profile": "bedrock" - } - ] -} -``` -> If you run into the following error when connecting to the new Claude 3.5 Sonnet 2 models from AWS - `400 Invocation of model ID anthropic.claude-3-5-sonnet-20241022-v2:0 with on-demand throughput isn’t supported. Retry your request with the ID or ARN of an inference profile that contains this model.` - -> You can fix this using the following config.json -```json title="config.json" -{ - "models": [ - { - "title": "Claude 3.5 Sonnet", - "provider": "bedrock", - "model": "us.anthropic.claude-3-5-sonnet-20241022-v2:0", - "region": "us-east-1", - "profile": "bedrock" - } - ] -} -``` - -## Autocomplete model - -Bedrock currently does not offer any autocomplete models. However, [Codestral from Mistral](https://mistral.ai/news/codestral-2501/) and [Point from Poolisde](https://aws.amazon.com/bedrock/poolside/) will be supported in the near future. - -In the meantime, you can view a list of autocomplete model providers [here](../../model-types/autocomplete.md). - -## Embeddings model - -We recommend configuring [`amazon.titan-embed-text-v2:0`](https://docs.aws.amazon.com/bedrock/latest/devguide/models.html#amazon.titan-embed-text-v2-0) as your embeddings model. - -```json title="~/.continue/config.json" -{ - "embeddingsProvider": { - "title": "Embeddings Model", - "provider": "bedrock", - "model": "amazon.titan-embed-text-v2:0", - "region": "us-west-2" - } -} -``` - -## Reranking model - -We recommend configuring `cohere.rerank-v3-5:0` as your reranking model, you may also use `amazon.rerank-v1:0`. - -```json title="~/.continue/config.json" -{ - "reranker": { - "name": "bedrock", - "params": { - "model": "cohere.rerank-v3-5:0", - "region": "us-west-2" - } - } -} -``` - -## Authentication - -Authentication will be through temporary or long-term credentials in -`~/.aws/credentials` under a configured profile (e.g. "bedrock"). - -```title="~/.aws/credentials -[bedrock] -aws_access_key_id = abcdefg -aws_secret_access_key = hijklmno -aws_session_token = pqrstuvwxyz # Optional: means short term creds. -``` - -## Custom Imported Models - -To setup Bedrock using custom imported models, add the following to your `config.json` file: - -```json title="config.json" -{ - "models": [ - { - "title": "AWS Bedrock deepseek-coder-6.7b-instruct", - "provider": "bedrockimport", - "model": "deepseek-coder-6.7b-instruct", - "modelArn": "arn:aws:bedrock:us-west-2:XXXXX:imported-model/XXXXXX", - "region": "us-west-2", - "profile": "bedrock" - } - ] -} -``` - -Authentication will be through temporary or long-term credentials in -~/.aws/credentials under a configured profile (e.g. "bedrock"). - -```title="~/.aws/credentials -[bedrock] -aws_access_key_id = abcdefg -aws_secret_access_key = hijklmno -aws_session_token = pqrstuvwxyz # Optional: means short term creds. -``` diff --git a/docs/docs/customize/model-providers/top-level/bedrock.mdx b/docs/docs/customize/model-providers/top-level/bedrock.mdx new file mode 100644 index 000000000..f472d42a5 --- /dev/null +++ b/docs/docs/customize/model-providers/top-level/bedrock.mdx @@ -0,0 +1,200 @@ +--- +title: Amazon Bedrock +slug: ../bedrock +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +Amazon Bedrock is a fully managed service on AWS that provides access to foundation models from various AI companies through a single API. + +## Chat model + +We recommend configuring **Claude 3.5 Sonnet** as your chat model. + + + + ```yaml title="config.yaml" + models: + - name: Claude 3.5 Sonnet + provider: bedrock + model: anthropic.claude-3-5-sonnet-20240620-v1:0 + region: us-east-1 + profile: bedrock + roles: + - chat + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Claude 3.5 Sonnet", + "provider": "bedrock", + "model": "anthropic.claude-3-5-sonnet-20240620-v1:0", + "region": "us-east-1", + "profile": "bedrock" + } + ] + } + ``` + + + +> If you run into the following error when connecting to the new Claude 3.5 Sonnet 2 models from AWS - `400 Invocation of model ID anthropic.claude-3-5-sonnet-20241022-v2:0 with on-demand throughput isn't supported. Retry your request with the ID or ARN of an inference profile that contains this model.` + +> You can fix this using the following config: + + + + ```yaml title="config.yaml" + models: + - name: Claude 3.5 Sonnet + provider: bedrock + model: us.anthropic.claude-3-5-sonnet-20241022-v2:0 + region: us-east-1 + profile: bedrock + roles: + - chat + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Claude 3.5 Sonnet", + "provider": "bedrock", + "model": "us.anthropic.claude-3-5-sonnet-20241022-v2:0", + "region": "us-east-1", + "profile": "bedrock" + } + ] + } + ``` + + + +## Autocomplete model + +Bedrock currently does not offer any autocomplete models. However, [Codestral from Mistral](https://mistral.ai/news/codestral-2501/) and [Point from Poolisde](https://aws.amazon.com/bedrock/poolside/) will be supported in the near future. + +In the meantime, you can view a list of autocomplete model providers [here](../../model-types/autocomplete.md). + +## Embeddings model + +We recommend configuring [`amazon.titan-embed-text-v2:0`](https://docs.aws.amazon.com/bedrock/latest/devguide/models.html#amazon.titan-embed-text-v2-0) as your embeddings model. + + + + ```yaml title="config.yaml" + models: + - name: Embeddings Model + provider: bedrock + model: amazon.titan-embed-text-v2:0 + region: us-west-2 + roles: + - embed + ``` + + + ```json title="config.json" + { + "embeddingsProvider": { + "title": "Embeddings Model", + "provider": "bedrock", + "model": "amazon.titan-embed-text-v2:0", + "region": "us-west-2" + } + } + ``` + + + +## Reranking model + +We recommend configuring `cohere.rerank-v3-5:0` as your reranking model, you may also use `amazon.rerank-v1:0`. + + + + ```yaml title="config.yaml" + models: + - name: Bedrock Reranker + provider: bedrock + model: cohere.rerank-v3-5:0 + region: us-west-2 + roles: + - rerank + ``` + + + ```json title="config.json" + { + "reranker": { + "name": "bedrock", + "params": { + "model": "cohere.rerank-v3-5:0", + "region": "us-west-2" + } + } + } + ``` + + + +## Authentication + +Authentication will be through temporary or long-term credentials in +`~/.aws/credentials` under a configured profile (e.g. "bedrock"). + +```title="~/.aws/credentials +[bedrock] +aws_access_key_id = abcdefg +aws_secret_access_key = hijklmno +aws_session_token = pqrstuvwxyz # Optional: means short term creds. +``` + +## Custom Imported Models + +To setup Bedrock using custom imported models, add the following to your config file: + + + + ```yaml title="config.yaml" + models: + - name: AWS Bedrock deepseek-coder-6.7b-instruct + provider: bedrockimport + model: deepseek-coder-6.7b-instruct + modelArn: arn:aws:bedrock:us-west-2:XXXXX:imported-model/XXXXXX + region: us-west-2 + profile: bedrock + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "AWS Bedrock deepseek-coder-6.7b-instruct", + "provider": "bedrockimport", + "model": "deepseek-coder-6.7b-instruct", + "modelArn": "arn:aws:bedrock:us-west-2:XXXXX:imported-model/XXXXXX", + "region": "us-west-2", + "profile": "bedrock" + } + ] + } + ``` + + + +Authentication will be through temporary or long-term credentials in +~/.aws/credentials under a configured profile (e.g. "bedrock"). + +```title="~/.aws/credentials +[bedrock] +aws_access_key_id = abcdefg +aws_secret_access_key = hijklmno +aws_session_token = pqrstuvwxyz # Optional: means short term creds. +``` diff --git a/docs/docs/customize/model-providers/top-level/deepseek.md b/docs/docs/customize/model-providers/top-level/deepseek.md deleted file mode 100644 index 1ea875785..000000000 --- a/docs/docs/customize/model-providers/top-level/deepseek.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -title: DeepSeek -slug: ../deepseek ---- - -:::info - -You can get an API key from the [DeepSeek console](https://www.deepseek.com/). - -::: - -## Chat model - -We recommend configuring **DeepSeek Chat** as your chat model. - -```json title="config.json" -{ - "models": [ - { - "title": "DeepSeek Chat", - "provider": "deepseek", - "model": "deepseek-chat", - "apiKey": "[API_KEY]" - } - ] -} -``` - -## Autocomplete model - -We recommend configuring **DeepSeek Coder** as your autocomplete model. - -```json title="config.json" -{ - "tabAutocompleteModel": { - "title": "DeepSeek Coder", - "provider": "deepseek", - "model": "deepseek-coder" - } -} -``` - -## Embeddings model - -DeepSeek currently does not offer any embeddings models. - -[Click here](../../model-types/embeddings.md) to see a list of embeddings model providers. - -## Reranking model - -DeepSeek 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/top-level/deepseek.mdx b/docs/docs/customize/model-providers/top-level/deepseek.mdx new file mode 100644 index 000000000..0d15bb5f4 --- /dev/null +++ b/docs/docs/customize/model-providers/top-level/deepseek.mdx @@ -0,0 +1,83 @@ +--- +title: DeepSeek +slug: ../deepseek +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +:::info +You can get an API key from the [DeepSeek console](https://www.deepseek.com/). +::: + +## Chat model + +We recommend configuring **DeepSeek Chat** as your chat model. + + + + ```yaml title="config.yaml" + models: + - name: DeepSeek Chat + provider: deepseek + model: deepseek-chat + apiKey: + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "DeepSeek Chat", + "provider": "deepseek", + "model": "deepseek-chat", + "apiKey": "" + } + ] + } + ``` + + + +## Autocomplete model + +We recommend configuring **DeepSeek Coder** as your autocomplete model. + + + + ```yaml title="config.yaml" + models: + - name: DeepSeek Coder + provider: deepseek + model: deepseek-coder + apiKey: + roles: + - autocomplete + ``` + + + ```json title="config.json" + { + "tabAutocompleteModel": { + "title": "DeepSeek Coder", + "provider": "deepseek", + "model": "deepseek-coder", + "apiKey": "" + } + } + ``` + + + +## Embeddings model + +DeepSeek currently does not offer any embeddings models. + +[Click here](../../model-types/embeddings.mdx) to see a list of embeddings model providers. + +## Reranking model + +DeepSeek currently does not offer any reranking models. + +[Click here](../../model-types/reranking.mdx) to see a list of reranking model providers. diff --git a/docs/docs/customize/model-providers/top-level/gemini.md b/docs/docs/customize/model-providers/top-level/gemini.md deleted file mode 100644 index eff3e91ac..000000000 --- a/docs/docs/customize/model-providers/top-level/gemini.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -title: Gemini -slug: ../gemini ---- - -:::info - -You can get an API key from the [Google AI Studio](https://aistudio.google.com/). - -::: - -## Chat model - -We recommend configuring **Gemini 1.5 Pro** as your chat model. - -```json title="config.json" -{ - "models": [ - { - "title": "Gemini 1.5 Pro", - "provider": "gemini", - "model": "gemini-1.5-pro-latest", - "apiKey": "[API_KEY]" - } - ] -} -``` - -## Autocomplete model - -Gemini 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": "gemini", - "model": "models/text-embedding-004", - "apiKey": "[API_KEY]" - } -} -``` - -## Reranking model - -Gemini 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/top-level/gemini.mdx b/docs/docs/customize/model-providers/top-level/gemini.mdx new file mode 100644 index 000000000..6911a14a0 --- /dev/null +++ b/docs/docs/customize/model-providers/top-level/gemini.mdx @@ -0,0 +1,82 @@ +--- +title: Gemini +slug: ../gemini +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +:::info +You can get an API key from the [Google AI Studio](https://aistudio.google.com/). +::: + +## Chat model + +We recommend configuring **Gemini 1.5 Pro** as your chat model. + + + + ```yaml title="config.yaml" + models: + - name: Gemini 1.5 Pro + provider: gemini + model: gemini-1.5-pro-latest + apiKey: + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Gemini 1.5 Pro", + "provider": "gemini", + "model": "gemini-1.5-pro-latest", + "apiKey": "" + } + ] + } + ``` + + + +## Autocomplete model + +Gemini 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. + + + + ```yaml title="config.yaml" + models: + - name: Gemini Embeddings + provider: gemini + model: models/text-embedding-004 + apiKey: + roles: + - embed + ``` + + + ```json title="config.json" + { + "embeddingsProvider": { + "provider": "gemini", + "model": "models/text-embedding-004", + "apiKey": "" + } + } + ``` + + + +## Reranking model + +Gemini currently does not offer any reranking models. + +[Click here](../../model-types/reranking.mdx) to see a list of reranking model providers. diff --git a/docs/docs/customize/model-providers/top-level/mistral.md b/docs/docs/customize/model-providers/top-level/mistral.md deleted file mode 100644 index 2c1eb81e1..000000000 --- a/docs/docs/customize/model-providers/top-level/mistral.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: Mistral -slug: ../mistral ---- - -:::info - -You can get an API key from the [Mistral Dashboard](https://console.mistral.ai). Note that the API key for Codestral (codestral.mistral.ai) is different from for all other models (api.mistral.ai). If you are using a Codestral API key, you should set the `apiBase` to `https://codestral.mistral.ai/v1`. Otherwise, we will default to using `https://api.mistral.ai/v1`. - -::: - -## Chat model - -We recommend configuring **Mistral Large** as your chat model. - -```json title="config.json" -{ - "models": [ - { - "title": "Mistral Large", - "provider": "mistral", - "model": "mistral-large-latest", - "apiKey": "[API_KEY]" - } - ] -} -``` - -## Autocomplete model - -We recommend configuring **Codestral** as your autocomplete model. - -```json title="config.json" -{ - "tabAutocompleteModel": { - "title": "Codestral", - "provider": "mistral", - "model": "codestral-latest" - // "apiBase": "https://codestral.mistral.ai/v1" // Do this if you are using a Codestral API key - } -} -``` - -## Embeddings model - -We recommend configuring **Mistral Embed** as your embeddings model. - -```json title="config.json" -{ - "embeddingsProvider": { - "provider": "mistral", - "model": "mistral-embed", - "apiKey": "[API_KEY]", - "apiBase": "https://api.mistral.ai/v1" - } -} -``` - -## Reranking model - -Mistral 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/top-level/mistral.mdx b/docs/docs/customize/model-providers/top-level/mistral.mdx new file mode 100644 index 000000000..dd584394d --- /dev/null +++ b/docs/docs/customize/model-providers/top-level/mistral.mdx @@ -0,0 +1,110 @@ +--- +title: Mistral +slug: ../mistral +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +:::info +You can get an API key from the [Mistral Dashboard](https://console.mistral.ai). Note that the API key for Codestral (codestral.mistral.ai) is different from for all other models (api.mistral.ai). If you are using a Codestral API key, you should set the `apiBase` to `https://codestral.mistral.ai/v1`. Otherwise, we will default to using `https://api.mistral.ai/v1`. +::: + +## Chat model + +We recommend configuring **Mistral Large** as your chat model. + + + + ```yaml title="config.yaml" + models: + - name: Mistral Large + provider: mistral + model: mistral-large-latest + apiKey: + roles: + - chat + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Mistral Large", + "provider": "mistral", + "model": "mistral-large-latest", + "apiKey": "" + } + ] + } + ``` + + + +## Autocomplete model + +We recommend configuring **Codestral** as your autocomplete model. + + + + ```yaml title="config.yaml" + models: + - name: Codestral + provider: mistral + model: codestral-latest + # apiBase: https://codestral.mistral.ai/v1 # Do this if you are using a Codestral API key + roles: + - autocomplete + ``` + + + ```json title="config.json" + { + "tabAutocompleteModel": { + "title": "Codestral", + "provider": "mistral", + "model": "codestral-latest" + // "apiBase": "https://codestral.mistral.ai/v1" // Do this if you are using a Codestral API key + } + } + ``` + + + +## Embeddings model + +We recommend configuring **Mistral Embed** as your embeddings model. + + + + ```yaml title="config.yaml" + models: + - name: Mistral Embed + provider: mistral + model: mistral-embed + apiKey: + apiBase: https://api.mistral.ai/v1 + roles: + - embed + ``` + + + ```json title="config.json" + { + "embeddingsProvider": { + "provider": "mistral", + "model": "mistral-embed", + "apiKey": "", + "apiBase": "https://api.mistral.ai/v1" + } + } + ``` + + + +## Reranking model + +Mistral currently does not offer any reranking models. + +[Click here](../../model-types/reranking.mdx) to see a list of reranking model providers. diff --git a/docs/docs/customize/model-providers/top-level/ollama.md b/docs/docs/customize/model-providers/top-level/ollama.md deleted file mode 100644 index 611c3dad8..000000000 --- a/docs/docs/customize/model-providers/top-level/ollama.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -title: Ollama -slug: ../ollama ---- - -Ollama is an open-source tool that allows to run large language models (LLMs) locally on their own computers. To use Ollama, you can install it [here](https://ollama.ai/download) and download the model you want to run with the `ollama run` command. - -## Chat model - -We recommend configuring **Llama3.1 8B** as your chat model. - -```json title="config.json" -{ - "models": [ - { - "title": "Llama3.1 8B", - "provider": "ollama", - "model": "llama3.1:8b" - } - ] -} -``` - -## Autocomplete model - -We recommend configuring **Qwen2.5-Coder 1.5B** as your autocomplete model. - -```json title="config.json" -{ - "tabAutocompleteModel": { - "title": "Qwen2.5-Coder 1.5B", - "provider": "ollama", - "model": "qwen2.5-coder:1.5b-base" - } -} -``` - -## Embeddings model - -We recommend configuring **Nomic Embed Text** as your embeddings model. - -```json title="config.json" -{ - "embeddingsProvider": { - "provider": "ollama", - "model": "nomic-embed-text" - } -} -``` - -## Reranking model - -Ollama currently does not offer any reranking models. - -[Click here](../../model-types/reranking.md) to see a list of reranking model providers. - -## Using a remote instance - -To configure a remote instance of Ollama, add the `"apiBase"` property to your model in config.json: - -```json title="config.json" -{ - "models": [ - { - "title": "Llama3.1 8B", - "provider": "ollama", - "model": "llama3.1:8b", - "apiBase": "http://:11434" - } - ] -} -``` diff --git a/docs/docs/customize/model-providers/top-level/ollama.mdx b/docs/docs/customize/model-providers/top-level/ollama.mdx new file mode 100644 index 000000000..f2a80386e --- /dev/null +++ b/docs/docs/customize/model-providers/top-level/ollama.mdx @@ -0,0 +1,128 @@ +--- +title: Ollama +slug: ../ollama +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +Ollama is an open-source tool that allows to run large language models (LLMs) locally on their own computers. To use Ollama, you can install it [here](https://ollama.ai/download) and download the model you want to run with the `ollama run` command. + +## Chat model + +We recommend configuring **Llama3.1 8B** as your chat model. + + + + ```yaml title="Package or config.yaml" + models: + - name: Llama3.1 8B + provider: ollama + model: llama3.1:8b + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Llama3.1 8B", + "provider": "ollama", + "model": "llama3.1:8b" + } + ] + } + ``` + + + +## Autocomplete model + +We recommend configuring **Qwen2.5-Coder 1.5B** as your autocomplete model. + + + + ```yaml title="Package or config.yaml" + models: + - name: Qwen2.5-Coder 1.5B + provider: ollama + model: qwen2.5-coder:1.5b-base + roles: + - autocomplete + ``` + + + ```json title="config.json" + { + "tabAutocompleteModel": { + "title": "Qwen2.5-Coder 1.5B", + "provider": "ollama", + "model": "qwen2.5-coder:1.5b-base" + } + } + ``` + + + +## Embeddings model + +We recommend configuring **Nomic Embed Text** as your embeddings model. + + + + ```yaml title="Package or config.yaml" + models: + - name: Nomic Embed Text + provider: ollama + model: nomic-embed-text + roles: + - embed + ``` + + + ```json title="config.json" + { + "embeddingsProvider": { + "provider": "ollama", + "model": "nomic-embed-text" + } + } + ``` + + + +## Reranking model + +Ollama currently does not offer any reranking models. + +[Click here](../../model-types/reranking.mdx) to see a list of reranking model providers. + +## Using a remote instance + +To configure a remote instance of Ollama, add the `"apiBase"` property to your model in config.json: + + + + ```yaml title="Package or config.yaml" + models: + - name: Llama3.1 8B + provider: ollama + model: llama3.1:8b + apiBase: http://:11434 + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Llama3.1 8B", + "provider": "ollama", + "model": "llama3.1:8b", + "apiBase": "http://:11434" + } + ] + } + ``` + + diff --git a/docs/docs/customize/model-providers/top-level/openai.md b/docs/docs/customize/model-providers/top-level/openai.md deleted file mode 100644 index 6b31b0b22..000000000 --- a/docs/docs/customize/model-providers/top-level/openai.md +++ /dev/null @@ -1,93 +0,0 @@ ---- -title: OpenAI -slug: ../openai ---- - -:::info - -You can get an API key from the [OpenAI console](https://platform.openai.com/account/api-keys) - -::: - -## Chat model - -We recommend configuring **GPT-4o** as your chat model. - -```json title="config.json" -{ - "models": [ - { - "title": "GPT-4o", - "provider": "openai", - "model": "gpt-4o", - "apiKey": "[API_KEY]" - } - ] -} -``` - -## Autocomplete model - -OpenAI 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-3-large** as your embeddings model. - -```json title="config.json" -{ - "embeddingsProvider": { - "provider": "openai", - "model": "text-embedding-3-large", - "apiKey": "[API_KEY]" - } -} -``` - -## Reranking model - -OpenAI currently does not offer any reranking models. - -[Click here](../../model-types/reranking.md) to see a list of reranking model providers. - -## OpenAI compatible servers / APIs - -OpenAI compatible servers - -- [KoboldCpp](https://github.com/lostruins/koboldcpp) -- [text-gen-webui](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/openai#setup--installation) -- [FastChat](https://github.com/lm-sys/FastChat/blob/main/docs/openai_api.md) -- [LocalAI](https://localai.io/basics/getting_started/) -- [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 - -- [Anyscale Endpoints](https://github.com/continuedev/deploy-os-code-llm#others) -- [Anyscale Private Endpoints](https://github.com/continuedev/deploy-os-code-llm#anyscale-private-endpoints) - -If you are using an OpenAI compatible server / API, you can change the `apiBase` like this: - -```json title="config.json" -{ - "models": [ - { - "title": "OpenAI-compatible server / API", - "provider": "openai", - "model": "MODEL_NAME", - "apiKey": "EMPTY", - "apiBase": "http://localhost:8000/v1" - } - ] -} -``` - -To force usage of `chat/completions` instead of `completions` endpoint you can set - -```json -"useLegacyCompletionsEndpoint": false -``` diff --git a/docs/docs/customize/model-providers/top-level/openai.mdx b/docs/docs/customize/model-providers/top-level/openai.mdx new file mode 100644 index 000000000..71a117850 --- /dev/null +++ b/docs/docs/customize/model-providers/top-level/openai.mdx @@ -0,0 +1,160 @@ +--- +title: OpenAI +slug: ../openai +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +:::info +You can get an API key from the [OpenAI console](https://platform.openai.com/account/api-keys) +::: + +## Chat model + +We recommend configuring **GPT-4o** as your chat model. + + + + ```yaml title="config.yaml" + models: + - name: GPT-4o + provider: openai + model: gpt-4o + apiKey: + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "GPT-4o", + "provider": "openai", + "model": "gpt-4o", + "apiKey": "" + } + ] + } + ``` + + + +## Autocomplete model + +OpenAI 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-3-large** as your embeddings model. + + + + ```yaml title="config.yaml" + models: + - name: OpenAI Embeddings + provider: openai + model: text-embedding-3-large + apiKey: + roles: + - embed + ``` + + + ```json title="config.json" + { + "embeddingsProvider": { + "provider": "openai", + "model": "text-embedding-3-large", + "apiKey": "" + } + } + ``` + + + +## Reranking model + +OpenAI currently does not offer any reranking models. + +[Click here](../../model-types/reranking.mdx) to see a list of reranking model providers. + +## OpenAI compatible servers / APIs + +OpenAI compatible servers + +- [KoboldCpp](https://github.com/lostruins/koboldcpp) +- [text-gen-webui](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/openai#setup--installation) +- [FastChat](https://github.com/lm-sys/FastChat/blob/main/docs/openai_api.md) +- [LocalAI](https://localai.io/basics/getting_started/) +- [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 + +- [Anyscale Endpoints](https://github.com/continuedev/deploy-os-code-llm#others) +- [Anyscale Private Endpoints](https://github.com/continuedev/deploy-os-code-llm#anyscale-private-endpoints) + +If you are using an OpenAI compatible server / API, you can change the `apiBase` like this: + + + + ```yaml title="config.yaml" + models: + - name: OpenAI-compatible server / API + provider: openai + model: MODEL_NAME + apiBase: http://localhost:8000/v1 + apiKey: + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "OpenAI-compatible server / API", + "provider": "openai", + "model": "MODEL_NAME", + "apiKey": "", + "apiBase": "http://localhost:8000/v1" + } + ] + } + ``` + + + +To force usage of `chat/completions` instead of `completions` endpoint you can set: + + + + ```yaml title="config.yaml" + models: + - name: OpenAI-compatible server / API + provider: openai + model: MODEL_NAME + apiBase: http://localhost:8000/v1 + useLegacyCompletionsEndpoint: true + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "OpenAI-compatible server / API", + "provider": "openai", + "model": "MODEL_NAME", + "apiBase": "http://localhost:8000/v1", + "useLegacyCompletionsEndpoint": true + } + ] + } + ``` + + diff --git a/docs/docs/customize/model-providers/top-level/vertexai.md b/docs/docs/customize/model-providers/top-level/vertexai.md deleted file mode 100644 index 50958cae0..000000000 --- a/docs/docs/customize/model-providers/top-level/vertexai.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -title: Vertex AI -slug: ../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": "vertexai", - "model": "claude-3-5-sonnet-20240620", - "projectId": "[PROJECT_ID]", - "region": "us-east5" - } - ] -} -``` - -## Autocomplete model - -We recommend configuring **Codestral** or **code-gecko** as your autocomplete model. - -```json title="config.json" -{ - "tabAutocompleteModel": { - "title": "Codestral (Vertex AI)", - "provider": "vertexai", - "model": "codestral", - "projectId": "[PROJECT_ID]", - "region": "us-central1" - } -} -``` - -## Embeddings model - -We recommend configuring **text-embedding-004** as your embeddings model. - -```json title="config.json" -{ - "embeddingsProvider": { - "provider": "vertexai", - "model": "text-embedding-004", - "projectId": "[PROJECT_ID]", - "region": "us-central1" - } -} -``` - -## Reranking model - -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/top-level/vertexai.mdx b/docs/docs/customize/model-providers/top-level/vertexai.mdx new file mode 100644 index 000000000..514b67cb4 --- /dev/null +++ b/docs/docs/customize/model-providers/top-level/vertexai.mdx @@ -0,0 +1,112 @@ +--- +title: Vertex AI +slug: ../vertexai +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +:::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. + + + + ```yaml title="Package or config.yaml" + models: + - name: Claude 3.5 Sonnet + provider: vertexai + model: claude-3-5-sonnet-20240620 + projectId: + region: us-east5 + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Claude 3.5 Sonnet", + "provider": "vertexai", + "model": "claude-3-5-sonnet-20240620", + "projectId": "[PROJECT_ID]", + "region": "us-east5" + } + ] + } + ``` + + + +## Autocomplete model + +We recommend configuring **Codestral** or **code-gecko** as your autocomplete model. + + + + ```yaml title="config.yaml" + models: + - name: Codestral (Vertex AI) + provider: vertexai + model: codestral + projectId: + region: us-central1 + roles: + - autocomplete + ``` + + + ```json title="config.json" + { + "tabAutocompleteModel": { + "title": "Codestral (Vertex AI)", + "provider": "vertexai", + "model": "codestral", + "projectId": "[PROJECT_ID]", + "region": "us-central1" + } + } + ``` + + + +## Embeddings model + +We recommend configuring **text-embedding-004** as your embeddings model. + + + + ```yaml title="config.yaml" + models: + - name: Text Embedding-004 + provider: vertexai + model: text-embedding-004 + projectId: + region: us-central1 + roles: + - embed + ``` + + + ```json title="config.json" + { + "embeddingsProvider": { + "provider": "vertexai", + "model": "text-embedding-004", + "projectId": "[PROJECT_ID]", + "region": "us-central1" + } + } + ``` + + + +## Reranking model + +Vertex AI currently does not offer any reranking models. + +[Click here](../../model-types/reranking.mdx) to see a list of reranking model providers. diff --git a/docs/docs/customize/model-providers/top-level/xAI.md b/docs/docs/customize/model-providers/top-level/xAI.md deleted file mode 100644 index 550cc0641..000000000 --- a/docs/docs/customize/model-providers/top-level/xAI.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -title: xAI -slug: ../xai ---- - -:::info - -You can get an API key from the [xAI console](https://console.x.ai/) - -::: - -## Chat model - -We recommend configuring **grok-2-latest** as your chat model. For information on other available models, visit [xAI Documentation](https://docs.x.ai/docs/models). - -```json title="config.json" -{ - "models": [ - { - "title": "Grok 2", - "provider": "xAI", - "model": "grok-2-latest", - "apiKey": "[API_KEY]" - } - ] -} -``` - -## Autocomplete model - -xAI currently does not offer any autocomplete models. - -[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers. - -## Embeddings model - -xAI currently does not offer any embeddings models. - -[Click here](../../model-types/embeddings.md) to see a list of embeddings model providers. - -## Reranking model - -xAI currently does not offer any reranking models. - -[Click here](../../model-types/reranking.md) to see a list of reranking model providers. - -## Legacy Completions - -To force usage of `chat/completions` instead of `completions` endpoint you can set - -```json -"useLegacyCompletionsEndpoint": false -``` diff --git a/docs/docs/customize/model-providers/top-level/xAI.mdx b/docs/docs/customize/model-providers/top-level/xAI.mdx new file mode 100644 index 000000000..6fb459736 --- /dev/null +++ b/docs/docs/customize/model-providers/top-level/xAI.mdx @@ -0,0 +1,59 @@ +--- +title: xAI +slug: ../xai +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +:::info +You can get an API key from the [xAI console](https://console.x.ai/) +::: + +## Chat model + +We recommend configuring **grok-2-latest** as your chat model. For information on other available models, visit [xAI Documentation](https://docs.x.ai/docs/models). + + + + ```yaml title="config.yaml" + models: + - name: Grok 2 + provider: xAI + model: grok-2-latest + apiKey: + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Grok 2", + "provider": "xAI", + "model": "grok-2-latest", + "apiKey": "" + } + ] + } + ``` + + + +## Autocomplete model + +xAI currently does not offer any autocomplete models. + +[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers. + +## Embeddings model + +xAI currently does not offer any embeddings models. + +[Click here](../../model-types/embeddings.mdx) to see a list of embeddings model providers. + +## Reranking model + +xAI currently does not offer any reranking models. + +[Click here](../../model-types/reranking.mdx) 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 d85920605..4b14775d1 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 [Vertex AI](../model-providers/top-level/vertexai.md#autocomplete-model). +If you have the ability to use any model, we recommend `Codestral` with [Mistral](../model-providers/top-level/mistral.mdx#autocomplete-model) or [Vertex AI](../model-providers/top-level/vertexai.mdx#autocomplete-model). -If you want to run a model locally, we recommend `Qwen2.5-Coder 1.5B` with [Ollama](../model-providers/top-level/ollama.md#autocomplete-model). +If you want to run a model locally, we recommend `Qwen2.5-Coder 1.5B` with [Ollama](../model-providers/top-level/ollama.mdx#autocomplete-model). diff --git a/docs/docs/customize/model-types/chat.md b/docs/docs/customize/model-types/chat.md index d94f2ce2d..bde3d5557 100644 --- a/docs/docs/customize/model-types/chat.md +++ b/docs/docs/customize/model-types/chat.md @@ -9,11 +9,11 @@ A "chat model" is an LLM that is trained to respond in a conversational format. ## Recommended Chat models -If you have the ability to use any model, we recommend [Claude 3.5 Sonnet](../model-providers/top-level/anthropic.md). +If you have the ability to use any model, we recommend [Claude 3.5 Sonnet](../model-providers/top-level/anthropic.mdx). Otherwise, some of the next best options are: -- [GPT-4o](../model-providers/top-level/openai.md) -- [Grok-2](../model-providers/top-level/xAI.md) -- [Gemini 1.5 Pro](../model-providers/top-level/gemini.md) -- [Llama3.1 405B](../tutorials/llama3.1.md) +- [GPT-4o](../model-providers/top-level/openai.mdx) +- [Grok-2](../model-providers/top-level/xAI.mdx) +- [Gemini 1.5 Pro](../model-providers/top-level/gemini.mdx) +- [Llama3.1 405B](../tutorials/llama3.1.mdx) diff --git a/docs/docs/customize/model-types/embeddings.md b/docs/docs/customize/model-types/embeddings.md deleted file mode 100644 index 137f6c260..000000000 --- a/docs/docs/customize/model-types/embeddings.md +++ /dev/null @@ -1,103 +0,0 @@ ---- -title: Embeddings model -description: Embeddings model -keywords: [embedding] -sidebar_position: 3 ---- - -An "embeddings model" is trained to convert a piece of text into a vector, which can later be rapidly compared to other vectors to determine similarity between the pieces of text. Embeddings models are typically much smaller than LLMs, and will be extremely fast and cheap in comparison. - -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. -::: - -:::info[Free Trial] -The free trial supports embeddings (provider: `free-trial`) -::: - -## Recommended embedding models - -If you have the ability to use any model, we recommend `voyage-code-3`, which is listed below along with the rest of the options for embeddings models. - -If you want to generate embeddings locally, we recommend using `nomic-embed-text` with [Ollama](../model-providers/top-level/ollama.md#embeddings-model). - -### Voyage AI - -After obtaining an API key from [here](https://www.voyageai.com/), you can configure like this: - -```json title="config.json" -{ - "embeddingsProvider": { - "provider": "voyage", - "model": "voyage-code-3", - "apiKey": "" - } -} -``` - -### Ollama - -See [here](../model-providers/top-level/ollama.md#embeddings-model) for instructions on how to use Ollama for embeddings. - -### 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. - -```json title="config.json" -{ - "embeddingsProvider": { - "provider": "transformers.js" - } -} -``` - -### Text Embeddings Inference - -[Hugging Face Text Embeddings Inference](https://huggingface.co/docs/text-embeddings-inference/en/index) enables you to host your own embeddings endpoint. You can configure embeddings to use your endpoint as follows: - -```json title="config.json" -{ - "embeddingsProvider": { - "provider": "huggingface-tei", - "apiBase": "http://localhost:8080" - } -} -``` - -### OpenAI - -See [here](../model-providers/top-level/openai.md#embeddings-model) for instructions on how to use OpenAI for embeddings. - -### Cohere - -See [here](../model-providers/more/cohere.md#embeddings-model) for instructions on how to use Cohere for embeddings. - -### Gemini - -See [here](../model-providers/top-level/gemini.md#embeddings-model) for instructions on how to use Gemini for embeddings. - -### Vertex - -See [here](../model-providers/top-level/vertexai.md#embeddings-model) for instructions on how to use Vertex for embeddings. - -### Mistral - -See [here](../model-providers/top-level/mistral.md#embeddings-model) for instructions on how to use Mistral for embeddings. - -### NVIDIA - -See [here](../model-providers/more/nvidia.md#embeddings-model) for instructions on how to use NVIDIA for embeddings. - -### Bedrock - -See [here](../model-providers/top-level/bedrock.md#embeddings-model) for instructions on how to use Bedrock for embeddings. - -### WatsonX - -See [here](../model-providers/more/watsonx.md#embeddings-model) for instructions on how to use WatsonX for embeddings. - -### LMStudio - -See [here](../model-providers/more/lmstudio.md#embeddings-model) for instructions on how to use LMStudio for embeddings. diff --git a/docs/docs/customize/model-types/embeddings.mdx b/docs/docs/customize/model-types/embeddings.mdx new file mode 100644 index 000000000..ee22f7301 --- /dev/null +++ b/docs/docs/customize/model-types/embeddings.mdx @@ -0,0 +1,147 @@ +--- +title: Embeddings model +description: Embeddings model +keywords: [embedding] +sidebar_position: 3 +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +An "embeddings model" is trained to convert a piece of text into a vector, which can later be rapidly compared to other vectors to determine similarity between the pieces of text. Embeddings models are typically much smaller than LLMs, and will be extremely fast and cheap in comparison. + +In Continue, embeddings are generated during indexing and then used by [@Codebase](../deep-dives/codebase.mdx) 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. +::: + +:::info[Free Trial] +The free trial supports embeddings (provider: `free-trial`) +::: + +## Recommended embedding models + +If you have the ability to use any model, we recommend `voyage-code-3`, which is listed below along with the rest of the options for embeddings models. + +If you want to generate embeddings locally, we recommend using `nomic-embed-text` with [Ollama](../model-providers/top-level/ollama.mdx#embeddings-model). + +### Voyage AI + +After obtaining an API key from [here](https://www.voyageai.com/), you can configure like this: + + + + ```yaml title="Package or config.yaml" + models: + - name: Voyage Code 3 + provider: voyage + model: voyage-code-3 + apiKey: + roles: + - embed + ``` + + + ```json title="config.json" + { + "embeddingsProvider": { + "provider": "voyage", + "model": "voyage-code-3", + "apiKey": "" + } + } + ``` + + + +### Ollama + +See [here](../model-providers/top-level/ollama.mdx#embeddings-model) for instructions on how to use Ollama for embeddings. + +### 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. + + + + ```yaml title="Package or config.yaml" + models: + - name: default-transformers + provider: transformers.js + roles: + - embed + ``` + + + ```json title="config.json" + { + "embeddingsProvider": { + "provider": "transformers.js" + } + } + ``` + + + +### Text Embeddings Inference + +[Hugging Face Text Embeddings Inference](https://huggingface.co/docs/text-embeddings-inference/en/index) enables you to host your own embeddings endpoint. You can configure embeddings to use your endpoint as follows: + + + + ```yaml title="Package or config.yaml" + models: + - name: Huggingface TEI Embedder + provider: huggingface-tei + apiBase: http://localhost:8080 + roles: [embed] + ``` + + + ```json title="config.json" + { + "embeddingsProvider": { + "provider": "huggingface-tei", + "apiBase": "http://localhost:8080" + } + } + ``` + + + +### OpenAI + +See [here](../model-providers/top-level/openai.mdx#embeddings-model) for instructions on how to use OpenAI for embeddings. + +### Cohere + +See [here](../model-providers/more/cohere.mdx#embeddings-model) for instructions on how to use Cohere for embeddings. + +### Gemini + +See [here](../model-providers/top-level/gemini.mdx#embeddings-model) for instructions on how to use Gemini for embeddings. + +### Vertex + +See [here](../model-providers/top-level/vertexai.mdx#embeddings-model) for instructions on how to use Vertex for embeddings. + +### Mistral + +See [here](../model-providers/top-level/mistral.mdx#embeddings-model) for instructions on how to use Mistral for embeddings. + +### NVIDIA + +See [here](../model-providers/more/nvidia.mdx#embeddings-model) for instructions on how to use NVIDIA for embeddings. + +### Bedrock + +See [here](../model-providers/top-level/bedrock.mdx#embeddings-model) for instructions on how to use Bedrock for embeddings. + +### WatsonX + +See [here](../model-providers/more/watsonx.mdx#embeddings-model) for instructions on how to use WatsonX for embeddings. + +### LMStudio + +See [here](../model-providers/more/lmstudio.mdx#embeddings-model) for instructions on how to use LMStudio for embeddings. diff --git a/docs/docs/customize/model-types/reranking.md b/docs/docs/customize/model-types/reranking.md deleted file mode 100644 index a87918cb2..000000000 --- a/docs/docs/customize/model-types/reranking.md +++ /dev/null @@ -1,93 +0,0 @@ ---- -title: Reranking model -description: Reranking model -keywords: [rerank] -sidebar_position: 4 ---- - -A "reranking model" is trained to take two pieces of text (often a user question and a document) and return a relevancy score between 0 and 1, estimating how useful the document will be in answering the question. Rerankers are typically much smaller than LLMs, and will be extremely fast and cheap in comparison. - -In Continue, reranking is used by [@Codebase](../deep-dives/codebase.md) in order to select the most relevant code snippets after vector search. - -## Recommended reranking models - -If you have the ability to use any model, we recommend `rerank-2` by Voyage AI, which is listed below along with the rest of the options for rerankers. - -### Voyage AI - -Voyage AI offers the best reranking model for code with their `rerank-2` model. After obtaining an API key from [here](https://www.voyageai.com/), you can configure like this: - -```json title="config.json" -{ - "reranker": { - "name": "voyage", - "params": { - "model": "rerank-2", - "apiKey": "" - } - } -} -``` - -### Cohere - -See Cohere's documentation for rerankers [here](https://docs.cohere.com/docs/rerank-2). - -```json title="config.json" -{ - "reranker": { - "name": "cohere", - "params": { - "model": "rerank-english-v3.0", - "apiKey": "" - } - } -} -``` - -### LLM - -If you only have access to a single LLM, then you can use it as a reranker. This is discouraged unless truly necessary, because it will be much more expensive and still less accurate than any of the above models trained specifically for the task. Note that this will not work if you are using a local model, for example with Ollama, because too many parallel requests need to be made. - -```json title="config.json" -{ - "reranker": { - "name": "llm", - "params": { - "modelTitle": "My Model Title" - } - } -} -``` - -The `"modelTitle"` field must match one of the models in your "models" array in config.json. - -### Text Embeddings Inference - -[Hugging Face Text Embeddings Inference](https://huggingface.co/docs/text-embeddings-inference/en/index) enables you to host your own [reranker endpoint](https://huggingface.github.io/text-embeddings-inference/#/Text%20Embeddings%20Inference/rerank). You can configure your reranker as follows: - -```json title="config.json" -{ - "reranker": { - "name": "huggingface-tei", - "params": { - "apiBase": "http://localhost:8080", - "apiKey": "", - "truncate": true, - "truncation_direction": "Right" - } - } -} -``` - -### Free Trial (Voyage AI) - -Continue offers a free trial of Voyage AI's reranking model. - -```json title="config.json" -{ - "reranker": { - "name": "free-trial" - } -} -``` diff --git a/docs/docs/customize/model-types/reranking.mdx b/docs/docs/customize/model-types/reranking.mdx new file mode 100644 index 000000000..098dd94bc --- /dev/null +++ b/docs/docs/customize/model-types/reranking.mdx @@ -0,0 +1,166 @@ +--- +title: Reranking model +description: Reranking model +keywords: [rerank] +sidebar_position: 4 +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +A "reranking model" is trained to take two pieces of text (often a user question and a document) and return a relevancy score between 0 and 1, estimating how useful the document will be in answering the question. Rerankers are typically much smaller than LLMs, and will be extremely fast and cheap in comparison. + +In Continue, reranking is used by [@Codebase](../deep-dives/codebase.mdx) in order to select the most relevant code snippets after vector search. + +## Recommended reranking models + +If you have the ability to use any model, we recommend `rerank-2` by Voyage AI, which is listed below along with the rest of the options for rerankers. + +### Voyage AI + +Voyage AI offers the best reranking model for code with their `rerank-2` model. After obtaining an API key from [here](https://www.voyageai.com/), you can configure like this: + + + + ```yaml title="config.yaml" + models: + - name: My Voyage Reranker + provider: voyage + apiKey: + model: rerank-2 + roles: + - rerank + ``` + + + ```json title="config.json" + { + "reranker": { + "name": "voyage", + "params": { + "model": "rerank-2", + "apiKey": "" + } + } + } + ``` + + + +### Cohere + +See Cohere's documentation for rerankers [here](https://docs.cohere.com/docs/rerank-2). + + + + ```yaml title="config.yaml" + models: + - name: Cohere Reranker + provider: cohere + model: rerank-english-v3.0 + apiKey: + roles: + - rerank + ``` + + + ```json title="config.json" + { + "reranker": { + "name": "cohere", + "params": { + "model": "rerank-english-v3.0", + "apiKey": "" + } + } + } + ``` + + + +### LLM + +If you only have access to a single LLM, then you can use it as a reranker. This is discouraged unless truly necessary, because it will be much more expensive and still less accurate than any of the above models trained specifically for the task. Note that this will not work if you are using a local model, for example with Ollama, because too many parallel requests need to be made. + + + + ```yaml title="config.yaml" + models: + - name: LLM Reranker + provider: openai + model: gpt-4o + roles: + - rerank + ``` + + + ```json title="config.json" + { + "reranker": { + "name": "llm", + "params": { + "modelTitle": "My Model Title" + } + } + } + ``` + + + +The `"modelTitle"` field must match one of the models in your "models" array in config.json. + +### Text Embeddings Inference + +[Hugging Face Text Embeddings Inference](https://huggingface.co/docs/text-embeddings-inference/en/index) enables you to host your own [reranker endpoint](https://huggingface.github.io/text-embeddings-inference/#/Text%20Embeddings%20Inference/rerank). You can configure your reranker as follows: + + + + ```yaml title="Package or config.yaml" + models: + - name: Huggingface-tei Reranker + provider: huggingface-tei + apiBase: http://localhost:8080 + apiKey: + roles: + - rerank + ``` + + + ```json title="config.json" + { + "reranker": { + "name": "huggingface-tei", + "params": { + "apiBase": "http://localhost:8080", + "apiKey": "" + } + } + } + ``` + + + +### Free Trial (Voyage AI) + +Continue offers a free trial of Voyage AI's reranking model. + + + + ```yaml title="config.yaml" + models: + - name: Free Trial Reranker + provider: free-trial + roles: + - rerank + ``` + + + ```json title="config.json" + { + "reranker": { + "name": "free-trial" + } + } + ``` + + diff --git a/docs/docs/customize/overview.md b/docs/docs/customize/overview.md index 80c18846a..1a52712b9 100644 --- a/docs/docs/customize/overview.md +++ b/docs/docs/customize/overview.md @@ -6,22 +6,22 @@ keywords: [customize, configure, config] Continue can be deeply customized. For example you might: -- **Change your Model Provider**. Continue allows you to choose your favorite or even add multiple model providers. This allows you to use different models for different tasks, or to try another model if you're not happy with the results from your current model. Continue supports all of the popular model providers, including OpenAI, Anthropic, Microsoft/Azure, Mistral, and more. You can even self host your own model provider if you'd like. Learn more about [model providers](/customize/model-providers). -- **Select different model providers for each Compose feature**. Different Continue features can use different model providers. We call these _model types_. For example, you can use a different model provider for chat than you do for autocomplete. Learn more about [model types](/customize/model-types) . +- **Change your Model Provider**. Continue allows you to choose your favorite or even add multiple model providers. This allows you to use different models for different tasks, or to try another model if you're not happy with the results from your current model. Continue supports all of the popular model providers, including OpenAI, Anthropic, Microsoft/Azure, Mistral, and more. You can even self host your own model provider if you'd like. Learn more about [model providers](../customize/model-providers/). +- **Select different model providers for each Compose feature**. Different Continue features can use different model providers. We call these _model types_. For example, you can use a different model provider for chat than you do for autocomplete. Learn more about [model types](../customize/model-types/) . - **Add a Context Provider**. Context providers allow you to add information to your prompts, giving your LLM additional context to work with. Context providers allow you to reference snippets from your codebase, or lookup relevant documentation, or use a search engine to find information and much more. Learn more about [context providers](/customize/context-providers). - **Create a Slash Command**. Slash commands allow you to easily add custom functionality to Continue. You can use a slash command that allows you to generate a shell command from natural language, or perhaps generate a commit message, or create your own custom command to do whatever you want. Learn more about [slash commands](/customize/slash-commands). - **Call external tools and functions**. Unchain your LLM with the power of _Tools_. You can call any external tool or function from your prompts. Currently only available with Anthropic. Learn more about [Tools](/customize/tools). -Whatever you choose, you'll probably start by editing `config.json`. +Whatever you choose, you'll probably start by editing `config.yaml`. ## Editing config.json -Most custom configuration is done by editing `config.json`. This file is a JSON file that allows you to customize Continue to your liking. It is found at: +Most custom configuration is done by editing `config.yaml` (or the older `config.json`). This is a YAML file that allows you to customize Continue to your liking. It is found at: -- MacOS and Linux: `~/.continue/config.json` -- Windows: `%USERPROFILE%\.continue\config.json` +- MacOS and Linux: `~/.continue/config.yaml` +- Windows: `%USERPROFILE%\.continue\config.yaml` -You can easily access `config.json` from the Continue Chat sidebar. Open the sidebar by pressing cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains) and click the "gear" icon in header to open the Settings page. Then click the button labeled `Open [your config profile]`. +You can easily access config file from the Continue Chat sidebar. Open the sidebar by pressing cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains) and click the "gear" icon in header to open the Settings page. Then click the button labeled `Open config file`. ![configure-continue](/img/configure-continue.png) @@ -29,13 +29,13 @@ When editing this file, you can see the available options suggested as you type, :::info -`config.json` is created the first time you use Continue. If you'd like to reset your configuration to the default, you can delete this file and Continue will automatically recreate it with the default settings. +A configuration file is created the first time you use Continue. If you'd like to reset your configuration to the default, you can delete this file and Continue will automatically recreate it with the default settings. ::: :::info -When you save `config.json`, Continue will automatically refresh to take into account your changes. +When you save a configuration file from the IDE, Continue will automatically refresh to take into account your changes. ::: @@ -45,6 +45,6 @@ If you'd like to scope certain settings to a particular workspace, you can add a ## 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). +`config.yaml` or `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). diff --git a/docs/docs/customize/slash-commands.md b/docs/docs/customize/slash-commands.mdx similarity index 76% rename from docs/docs/customize/slash-commands.md rename to docs/docs/customize/slash-commands.mdx index bc3bac24a..710d5fd69 100644 --- a/docs/docs/customize/slash-commands.md +++ b/docs/docs/customize/slash-commands.mdx @@ -4,6 +4,13 @@ description: Shortcuts that can be activated by prefacing your input with '/' keywords: [slash command, custom commands, step] --- +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +:::info +Slash commands can currently only be added using [`config.json`](../json-reference.md). The [`YAML Config Format`](../reference.md) is the new and preferred format. We recommend looking into [Prompt Files](../customize/deep-dives/prompt-files.md) to achieve similar functionality. +::: + Slash commands 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. ![slash-commands](/img/slash-commands.png) @@ -109,23 +116,39 @@ The onboard slash command helps to familiarize yourself with a new project by an ### Model Context Protocol -The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports MCP "prompts" by creating slash commands. Read their [quickstart](https://modelcontextprotocol.io/quickstart) to learn how to set up a local server and then configure your `config.json` like this: +The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports MCP "prompts" by creating slash commands. Read their [quickstart](https://modelcontextprotocol.io/quickstart) to learn how to set up a local server and then set up your configuration like this: -```json -{ - "experimental": { - "modelContextProtocolServers": [ - { - "transport": { - "type": "stdio", - "command": "uvx", - "args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"] + + + ```yaml title="Package or config.yaml" + mcpServers: + - name: My MCP Server + command: uvx + args: + - mcp-server-sqlite + - --db-path + - /Users/NAME/test.db + ``` + + + ```json title="config.json" + { + "experimental": { + "modelContextProtocolServers": [ + { + "transport": { + "type": "stdio", + "command": "uvx", + "args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"] + } } - } - ] + ] + } } -} -``` + ``` + + ### Build your own Slash Command -You can build your own slash command by following [this tutorial](/customize/tutorials/build-your-own-slash-command). \ No newline at end of file + +You can build your own slash command by following [this tutorial](/customize/tutorials/build-your-own-slash-command). diff --git a/docs/docs/customize/tools.md b/docs/docs/customize/tools.mdx similarity index 51% rename from docs/docs/customize/tools.md rename to docs/docs/customize/tools.mdx index 020c38459..2f06f5081 100644 --- a/docs/docs/customize/tools.md +++ b/docs/docs/customize/tools.mdx @@ -4,10 +4,13 @@ description: Tool use and customization keywords: [tool, use, function calling, claude, automatic] --- +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + Tools allow Continue to take action in your IDE and beyond (when you give permission). Currently, they are only supported for the following providers: -- [Anthropic](./model-providers/top-level/anthropic.md) - see recommended models [here](https://docs.anthropic.com/en/docs/build-with-claude/tool-use#choosing-a-model). -- [Ollama](./model-providers/top-level/ollama.md) - see recommended models [here](https://ollama.com/search?c=tools). +- [Anthropic](./model-providers/top-level/anthropic.mdx) - see recommended models [here](https://docs.anthropic.com/en/docs/build-with-claude/tool-use#choosing-a-model). +- [Ollama](./model-providers/top-level/ollama.mdx) - see recommended models [here](https://ollama.com/search?c=tools). To use tools, click on the icon in the input toolbar like below. @@ -21,20 +24,35 @@ To let you balance speed and safety, each tool can be set to 1 of 3 modes: ### Custom tools -Currently custom tools can be configured using the [Model Context Protocol](https://modelcontextprotocol.io/introduction), a standard proposed by Anthropic to unify prompts, context, and tool use. Read their [quickstart](https://modelcontextprotocol.io/quickstart) to learn how to set up a local server and then configure your `config.json` like this: +Currently custom tools can be configured using the [Model Context Protocol](https://modelcontextprotocol.io/introduction), a standard proposed by Anthropic to unify prompts, context, and tool use. Read their [quickstart](https://modelcontextprotocol.io/quickstart) to learn how to set up a local server and then configure your [config](../customize/deep-dives/configuration.md) like this: -```json title="~/.continue/config.json" -{ - "experimental": { - "modelContextProtocolServers": [ - { - "transport": { - "type": "stdio", - "command": "uvx", - "args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"] + + + ```yaml title="Package or config.yaml" + mcpServers: + - name: My MCP Server + command: uvx + args: + - mcp-server-sqlite + - --db-path + - /Users/NAME/test.db + ``` + + + ```json title="config.json" + { + "experimental": { + "modelContextProtocolServers": [ + { + "transport": { + "type": "stdio", + "command": "uvx", + "args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"] + } } - } - ] + ] + } } -} -``` + ``` + + diff --git a/docs/docs/customize/tutorials/build-your-own-context-provider.md b/docs/docs/customize/tutorials/build-your-own-context-provider.md index 3d37790cd..33ba4441a 100644 --- a/docs/docs/customize/tutorials/build-your-own-context-provider.md +++ b/docs/docs/customize/tutorials/build-your-own-context-provider.md @@ -2,6 +2,10 @@ title: Build your own context provider --- +:::info +Custom context providers are added through `~/config.ts`. The [`YAML Config Format`](../../reference.md) is the new and preferred config format. We recommend looking into [Prompt Files](../deep-dives/prompt-files.md) and [MCP Servers](../context-providers.mdx#modelcontextprotocol) to achieve similar functionality. +::: + ## Introductory Example To write your own context provider, you just have to implement the `CustomContextProvider` @@ -69,7 +73,7 @@ export function modifyConfig(config: Config): Config { } ``` -No modification in `config.json` is necessary. +This is automatically appended to your configuration. ## Custom Context Providers with Submenu or Query @@ -107,17 +111,19 @@ const ReadMeContextProvider: CustomContextProvider = { const { ide } = args; // Filter all workspace files for READMEs - const workspaceDirs = await ide.getWorkspaceDirs() + const workspaceDirs = await ide.getWorkspaceDirs(); const allFiles = await Promise.all( - workspaceDirs.map(dir => ide.subprocess(`find ${dir} -name "README.md"`)), + workspaceDirs.map((dir) => + ide.subprocess(`find ${dir} -name "README.md"`), + ), ); // 'readmes' now contains an array of file paths for each README.md file found in the workspace, // excluding those in 'node_modules' const readmes = allFiles - .flatMap(mds => mds[0].split("\n")) - .filter(file => file.trim() !== '' && !file.includes("/node_modules/")) + .flatMap((mds) => mds[0].split("\n")) + .filter((file) => file.trim() !== "" && !file.includes("/node_modules/")); // Return the items that will be shown in the dropdown return readmes.map((filepath) => { @@ -182,7 +188,7 @@ Continue will use [esbuild](https://esbuild.github.io/) to bundle your `config.t If you'd like to write a context provider in a language other than TypeScript, you can use the "http" context provider to call a server that hosts your own code. Add the context provider to `config.json` like this: -```json +```json title="config.json" { "name": "http", "params": { diff --git a/docs/docs/customize/tutorials/build-your-own-slash-command.md b/docs/docs/customize/tutorials/build-your-own-slash-command.md index dc450cdd4..27b0517b3 100644 --- a/docs/docs/customize/tutorials/build-your-own-slash-command.md +++ b/docs/docs/customize/tutorials/build-your-own-slash-command.md @@ -2,6 +2,10 @@ title: Build your own slash command --- +:::info +Slash commands can currently only be added using [`config.json`](../../json-reference.md) or `config.ts`. The [`YAML Config Format`](../../reference.md) is the new and preferred format. We recommend looking into [Prompt Files](../deep-dives/prompt-files.md) to achieve similar functionality. +::: + There are two ways to add custom slash commands: 1. With natural language prompts - this is simpler and only requires writing a string or string template. @@ -18,11 +22,15 @@ You can add custom slash commands by adding to the `customCommands` property in Custom commands are great when you are frequently reusing a prompt. For example, if you've crafted a great prompt and frequently ask the LLM to check for mistakes in your code, you could add a command like this: ```json title="config.json" -customCommands=[{ - "name": "check", - "description": "Check for mistakes in my code", - "prompt": "{{{ input }}}\n\nPlease read the highlighted code and check for any mistakes. You should look for the following, and be extremely vigilant:\n- Syntax errors\n- Logic errors\n- Security vulnerabilities\n- Performance issues\n- Anything else that looks wrong\n\nOnce you find an error, please explain it as clearly as possible, but without using extra words. For example, instead of saying 'I think there is a syntax error on line 5', you should say 'Syntax error on line 5'. Give your answer as one bullet point per mistake found." -}] +{ + "customCommands": [ + { + "name": "check", + "description": "Check for mistakes in my code", + "prompt": "{{{ input }}}\n\nPlease read the highlighted code and check for any mistakes. You should look for the following, and be extremely vigilant:\n- Syntax errors\n- Logic errors\n- Security vulnerabilities\n- Performance issues\n- Anything else that looks wrong\n\nOnce you find an error, please explain it as clearly as possible, but without using extra words. For example, instead of saying 'I think there is a syntax error on line 5', you should say 'Syntax error on line 5'. Give your answer as one bullet point per mistake found." + } + ] +} ``` #### Templating diff --git a/docs/docs/customize/tutorials/custom-code-rag.md b/docs/docs/customize/tutorials/custom-code-rag.mdx similarity index 86% rename from docs/docs/customize/tutorials/custom-code-rag.md rename to docs/docs/customize/tutorials/custom-code-rag.mdx index b6f1cc251..f5e43dc8e 100644 --- a/docs/docs/customize/tutorials/custom-code-rag.md +++ b/docs/docs/customize/tutorials/custom-code-rag.mdx @@ -1,6 +1,9 @@ +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + # Custom code RAG -While Continue comes with [@Codebase](../deep-dives/codebase.md) out of the box, you might wish to set up your own vector database and build a custom retrieval-augmented generation (RAG) system. This can allow you to access code that is not available locally, to index code a single time across all users, or to include custom logic. In this guide, we'll walk you through the steps it takes to build this. +While Continue comes with [@Codebase](../deep-dives/codebase.mdx) out of the box, you might wish to set up your own vector database and build a custom retrieval-augmented generation (RAG) system. This can allow you to access code that is not available locally, to index code a single time across all users, or to include custom logic. In this guide, we'll walk you through the steps it takes to build this. ## Step 1: Choose an embeddings model @@ -122,19 +125,38 @@ async def create_item(item: ContextProviderInput): return context_items ``` -After you've set up your server, you can configure Continue to use it by adding the "http" context provider to your `contextProviders` array in `config.json`: +After you've set up your server, you can configure Continue to use it by adding the "http" context provider to your `contextProviders` array in your configuration: -```json title="config.json" -{ - "name": "http", - "params": { - "url": "https://myserver.com/retrieve", - "title": "http", - "description": "Custom HTTP Context Provider", - "displayTitle": "My Custom Context" + + + ```yaml title="config.yaml" + context: + - provider: http + params: + url: https://myserver.com/retrieve + name: http + description: Custom HTTP Context Provider + displayTitle: My Custom Context + ``` + + + ```json title="config.json" + { + "contextProviders": [ + { + "name": "http", + "params": { + "url": "https://myserver.com/retrieve", + "title": "http", + "description": "Custom HTTP Context Provider", + "displayTitle": "My Custom Context" + } + } + ] } -} -``` + ``` + + ## Step 7 (Bonus): Set up reranking diff --git a/docs/docs/customize/tutorials/how-to-self-host-a-model.md b/docs/docs/customize/tutorials/how-to-self-host-a-model.md deleted file mode 100644 index 4f97824d1..000000000 --- a/docs/docs/customize/tutorials/how-to-self-host-a-model.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -title: How to self-host a model ---- - -You can deploy a model in your [AWS](https://github.com/continuedev/deploy-os-code-llm#aws), [GCP](https://github.com/continuedev/deploy-os-code-llm#gcp), [Azure](https://github.com/continuedev/deploy-os-code-llm#azure), [Lambda](https://lambdalabs.com/), or [other clouds](https://github.com/continuedev/deploy-os-code-llm#others-2) using: - -- [HuggingFace TGI](https://github.com/continuedev/deploy-os-code-llm#tgi) -- [vLLM](https://github.com/continuedev/deploy-os-code-llm#vllm) -- [SkyPilot](https://github.com/continuedev/deploy-os-code-llm#skypilot) -- [Anyscale Private Endpoints](https://github.com/continuedev/deploy-os-code-llm#anyscale-private-endpoints) (OpenAI compatible API) -- [Lambda](https://github.com/continuedev/deploy-os-code-llm#lambda) - -## Self-hosting an open-source model - -For many cases, either Continue will have a built-in provider or the API you use will be OpenAI-compatible, in which case you can use the "openai" provider and change the "baseUrl" to point to the server. - -However, if neither of these are the case, you will need to wire up a new LLM object. - -## Authentication - -Basic authentication can be done with any provider using the `apiKey` field: - -```json title="config.json" -{ - "models": [ - { - "title": "Ollama", - "provider": "ollama", - "model": "llama2-7b", - "apiKey": "xxx" - } - ] -} -``` - -This translates to the header `"Authorization": "Bearer xxx"`. - -If you need to send custom headers for authentication, you may use the `requestOptions.headers` property like in this example with Ollama: - -```json title="config.json" -{ - "models": [ - { - "title": "Ollama", - "provider": "ollama", - "model": "llama2-7b", - "requestOptions": { - "headers": { - "X-Auth-Token": "xxx" - } - } - } - ] -} -``` - -Similarly if your model requires a Certificate for authentication, you may use the `requestOptions.clientCertificate` property like in the example below: - -```json title="config.json" -{ - "models": [ - { - "title": "Ollama", - "provider": "ollama", - "model": "llama2-7b", - "requestOptions": { - "clientCertificate": { - "cert": "C:\tempollama.pem", - "key": "C:\tempollama.key", - "passphrase": "c0nt!nu3" - } - } - } - ] -} -``` diff --git a/docs/docs/customize/tutorials/how-to-self-host-a-model.mdx b/docs/docs/customize/tutorials/how-to-self-host-a-model.mdx new file mode 100644 index 000000000..abd726aba --- /dev/null +++ b/docs/docs/customize/tutorials/how-to-self-host-a-model.mdx @@ -0,0 +1,124 @@ +--- +title: How to self-host a model +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +You can deploy a model in your [AWS](https://github.com/continuedev/deploy-os-code-llm#aws), [GCP](https://github.com/continuedev/deploy-os-code-llm#gcp), [Azure](https://github.com/continuedev/deploy-os-code-llm#azure), [Lambda](https://lambdalabs.com/), or [other clouds](https://github.com/continuedev/deploy-os-code-llm#others-2) using: + +- [HuggingFace TGI](https://github.com/continuedev/deploy-os-code-llm#tgi) +- [vLLM](https://github.com/continuedev/deploy-os-code-llm#vllm) +- [SkyPilot](https://github.com/continuedev/deploy-os-code-llm#skypilot) +- [Anyscale Private Endpoints](https://github.com/continuedev/deploy-os-code-llm#anyscale-private-endpoints) (OpenAI compatible API) +- [Lambda](https://github.com/continuedev/deploy-os-code-llm#lambda) + +## Self-hosting an open-source model + +For many cases, either Continue will have a built-in provider or the API you use will be OpenAI-compatible, in which case you can use the "openai" provider and change the "baseUrl" to point to the server. + +However, if neither of these are the case, you will need to wire up a new LLM object. + +## Authentication + +Basic authentication can be done with any provider using the `apiKey` field: + + + + ```yaml title="Package or config.yaml" + models: + - name: Ollama + provider: ollama + model: llama2-7b + apiKey: + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Ollama", + "provider": "ollama", + "model": "llama2-7b", + "apiKey": "" + } + ] + } + ``` + + + +This translates to the header `"Authorization": "Bearer xxx"`. + +If you need to send custom headers for authentication, you may use the `requestOptions.headers` property like in this example with Ollama: + + + + ```yaml title="Package or config.yaml" + models: + - name: Ollama + provider: ollama + model: llama2-7b + requestOptions: + headers: + X-Auth-Token: xxx + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Ollama", + "provider": "ollama", + "model": "llama2-7b", + "requestOptions": { + "headers": { + "X-Auth-Token": "xxx" + } + } + } + ] + } + ``` + + + +Similarly if your model requires a Certificate for authentication, you may use the `requestOptions.clientCertificate` property like in the example below: + + + + ```yaml title="config.yaml" + models: + - name: Ollama + provider: ollama + model: llama2-7b + requestOptions: + clientCertificate: + cert: C:\tempollama.pem + key: C:\tempollama.key + passphrase: c0nt!nu3 + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Ollama", + "provider": "ollama", + "model": "llama2-7b", + "requestOptions": { + "clientCertificate": { + "cert": "C:\\tempollama.pem", + "key": "C:\\tempollama.key", + "passphrase": "c0nt!nu3" + } + } + } + ] + } + ``` + + diff --git a/docs/docs/customize/tutorials/llama3.1.md b/docs/docs/customize/tutorials/llama3.1.md deleted file mode 100644 index e2ac72986..000000000 --- a/docs/docs/customize/tutorials/llama3.1.md +++ /dev/null @@ -1,134 +0,0 @@ ---- -title: Using Llama 3.1 with Continue -description: How to use Llama 3.1 with Continue -keywords: [llama, meta, togetherai, novita, ollama, replicate] ---- - -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). - -Below we share some of the easiest ways to get up and running, depending on your use-case. - -## Ollama - -Ollama is the fastest way to get up and running with local language models. We recommend trying Llama 3.1 8b, which is impressive for its size and will perform well on most hardware. - -1. Download Ollama [here](https://ollama.ai/) (it should walk you through the rest of these steps) -2. Open a terminal and run `ollama run llama3.1:8b` -3. Change your Continue config file like this: - -```json title="config.json" -{ - "models": [ - { - "title": "Llama 3.1 8b", - "provider": "ollama", - "model": "llama3.1-8b" - } - ] -} -``` - -## Groq - -Groq provides the fastest available inference for open-source language models, including the entire Llama 3.1 family. - -1. Obtain an API key [here](https://console.groq.com/keys) -2. Update your Continue config file like this: - -```json title="config.json" -{ - "models": [ - { - "title": "Llama 3.1 405b", - "provider": "groq", - "model": "llama3.1-405b", - "apiKey": "" - } - ] -} -``` - -## Together AI - -Together AI provides fast and reliable inference of open-source models. You'll be able to run the 405b model with good speed. - -1. Create an account [here](https://api.together.xyz/signup) -2. Copy your API key that appears on the welcome screen -3. Update your Continue config file like this: - -```json title="config.json" -{ - "models": [ - { - "title": "Llama 3.1 405b", - "provider": "together", - "model": "llama3.1-405b", - "apiKey": "" - } - ] -} -``` - -## Replicate - -Replicate makes it easy to host and run open-source AI with an API. - -1. Get your Replicate API key [here](https://replicate.ai/) -2. Change your Continue config file like this: - -```json title="config.json" -{ - "models": [ - { - "title": "Llama 3.1 405b", - "provider": "replicate", - "model": "llama3.1-405b", - "apiKey": "" - } - ] -} -``` - -## SambaNova - -SambaNova Cloud provides world record Llama3.1 70B/405B serving. - -1. Create an account [here](https://cloud.sambanova.ai/) -2. Copy your API key -3. Update your Continue config file like this: - -```json title="~/.continue/config.json" -{ - "models": [ - { - "title": "SambaNova Llama 3.1 405B", - "provider": "sambanova", - "model": "llama3.1-405b", - "apiKey": "YOUR_API_KEY" - } - ] -} -``` - -## Cerebras Inference - -Cerebras Inference uses specialized silicon to provides fast inference for the Llama3.1 8B/70B. - -1. Create an account in the portal [here](https://cloud.cerebras.ai/). -2. Create and copy the API key for use in Continue. -3. Update your Continue config file: - -```json title="config.json" -{ - "models": [ - { - "title": "Cerebras Llama 3.1 70B", - "provider": "cerebras", - "model": "llama3.1-70b", - "apiKey": "YOUR_API_KEY" - } - ] -} -``` diff --git a/docs/docs/customize/tutorials/llama3.1.mdx b/docs/docs/customize/tutorials/llama3.1.mdx new file mode 100644 index 000000000..294fc4e8b --- /dev/null +++ b/docs/docs/customize/tutorials/llama3.1.mdx @@ -0,0 +1,218 @@ +--- +title: Using Llama 3.1 with Continue +description: How to use Llama 3.1 with Continue +keywords: [llama, meta, togetherai, ollama, replicate] +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +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). + +Below we share some of the easiest ways to get up and running, depending on your use-case. + +## Ollama + +Ollama is the fastest way to get up and running with local language models. We recommend trying Llama 3.1 8b, which is impressive for its size and will perform well on most hardware. + +1. Download Ollama [here](https://ollama.ai/) (it should walk you through the rest of these steps) +2. Open a terminal and run `ollama run llama3.1:8b` +3. Change your Continue config file like this: + + + + ```yaml title="Package or config.yaml" + models: + - name: Llama 3.1 8b + provider: ollama + model: llama3.1-8b + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Llama 3.1 8b", + "provider": "ollama", + "model": "llama3.1-8b" + } + ] + } + ``` + + + +## Groq + +:::info +Check if your chosen model is still supported by referring to the [model documentation](https://console.groq.com/docs/models). If a model has been deprecated, you may encounter a 404 error when attempting to use it. +::: + +Groq provides the fastest available inference for open-source language models, including the entire Llama 3.1 family. + +1. Obtain an API key [here](https://console.groq.com/keys) +2. Update your Continue config file like this: + + + + ```yaml title="config.yaml" + models: + - name: Llama 3.3 70b Versatile + provider: groq + model: llama-3.3-70b-versatile + apiKey: + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Llama 3.3 70b Versatile", + "provider": "groq", + "model": "llama-3.3-70b-versatile", + "apiKey": "" + } + ] + } + ``` + + + +## Together AI + +Together AI provides fast and reliable inference of open-source models. You'll be able to run the 405b model with good speed. + +1. Create an account [here](https://api.together.xyz/signup) +2. Copy your API key that appears on the welcome screen +3. Update your Continue config file like this: + + + + ```yaml title="Package or config.yaml" + models: + - name: Llama 3.1 405b + provider: together + model: llama3.1-405b + apiKey: + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Llama 3.1 405b", + "provider": "together", + "model": "llama3.1-405b", + "apiKey": "" + } + ] + } + ``` + + + +## Replicate + +Replicate makes it easy to host and run open-source AI with an API. + +1. Get your Replicate API key [here](https://replicate.ai/) +2. Change your Continue config file like this: + + + + ```yaml title="Package or config.yaml" + models: + - name: Llama 3.1 405b + provider: replicate + model: llama3.1-405b + apiKey: + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Llama 3.1 405b", + "provider": "replicate", + "model": "llama3.1-405b", + "apiKey": "" + } + ] + } + ``` + + + +## SambaNova + +SambaNova Cloud provides world record Llama3.1 70B/405B serving. + +1. Create an account [here](https://cloud.sambanova.ai/) +2. Copy your API key +3. Update your Continue config file like this: + + + + ```yaml title="config.yaml" + models: + - name: SambaNova Llama 3.1 405B + provider: sambanova + model: llama3.1-405b + apiKey: + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "SambaNova Llama 3.1 405B", + "provider": "sambanova", + "model": "llama3.1-405b", + "apiKey": "" + } + ] + } + ``` + + + +## Cerebras Inference + +Cerebras Inference uses specialized silicon to provides fast inference for the Llama3.1 8B/70B. + +1. Create an account in the portal [here](https://cloud.cerebras.ai/). +2. Create and copy the API key for use in Continue. +3. Update your Continue config file: + + + + ```yaml title="Package or config.yaml" + models: + - name: Cerebras Llama 3.1 70B + provider: cerebras + model: llama3.1-70b + apiKey: + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Cerebras Llama 3.1 70B", + "provider": "cerebras", + "model": "llama3.1-70b", + "apiKey": "" + } + ] + } + ``` + + diff --git a/docs/docs/customize/tutorials/running-continue-without-internet.md b/docs/docs/customize/tutorials/running-continue-without-internet.md index 277272767..e3de1e79e 100644 --- a/docs/docs/customize/tutorials/running-continue-without-internet.md +++ b/docs/docs/customize/tutorials/running-continue-without-internet.md @@ -9,4 +9,4 @@ Continue can be run even on an air-gapped computer if you use a local model. Onl 1. Download the latest .vsix file from the [Open VSX Registry](https://open-vsx.org/extension/Continue/continue) and [install it to VS Code](https://code.visualstudio.com/docs/editor/extension-marketplace#_install-from-a-vsix). 2. Open the [User Settings Page](../settings.md) and turn off "Allow Anonymous Telemetry". This will stop Continue from attempting requests to PostHog for [anonymous telemetry](../../telemetry.md). 3. Also in `config.json`, set the default model to a local model. You can available options [here](../model-providers/). -4. Restart VS Code to ensure that the changes to `config.json` take effect. +4. Restart VS Code to ensure that the changes to `config.json` or `config.yaml` take effect. diff --git a/docs/docs/customize/tutorials/set-up-codestral.md b/docs/docs/customize/tutorials/set-up-codestral.mdx similarity index 50% rename from docs/docs/customize/tutorials/set-up-codestral.md rename to docs/docs/customize/tutorials/set-up-codestral.mdx index c48fea653..97ec3c981 100644 --- a/docs/docs/customize/tutorials/set-up-codestral.md +++ b/docs/docs/customize/tutorials/set-up-codestral.mdx @@ -4,6 +4,9 @@ description: How to set up Codestral keywords: [codestral, mistral, model setup] --- +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + ![mistral x continue](../../../static/img/mistral-x-continue.png) **Here is a step-by-step guide on how to set up Codestral with Continue using the Mistral AI API:** @@ -14,28 +17,45 @@ keywords: [codestral, mistral, model setup] 3. Log in and create an API key on Mistral AI's La Plateforme [here](https://console.mistral.ai/codestral). Make sure you get an API key from the "Codestral" page. -4. To use Codestral as your model for both `autocomplete` and `chat`, replace `[API_KEY]` with your Mistral API key below and add it to your `config.json` file: +4. To use Codestral as your model for both `autocomplete` and `chat`, insert your Mistral API key below and add it to your configuration file: -```json title="config.json" -{ - "models": [ + + + ```yaml title="config.yaml" + models: + - name: Codestral + provider: mistral + model: codestral-latest + apiKey: + apiBase: https://codestral.mistral.ai/v1 + roles: + - chat + - autocomplete + ``` + + + ```json title="config.json" { - "title": "Codestral", - "provider": "mistral", - "model": "codestral-latest", - "apiKey": "[API_KEY]", - "apiBase": "https://codestral.mistral.ai/v1" + "models": [ + { + "title": "Codestral", + "provider": "mistral", + "model": "codestral-latest", + "apiKey": "", + "apiBase": "https://codestral.mistral.ai/v1" + } + ], + "tabAutocompleteModel": { + "title": "Codestral", + "provider": "mistral", + "model": "codestral-latest", + "apiKey": "", + "apiBase": "https://codestral.mistral.ai/v1" + } } - ], - "tabAutocompleteModel": { - "title": "Codestral", - "provider": "mistral", - "model": "codestral-latest", - "apiKey": "[API_KEY]", - "apiBase": "https://codestral.mistral.ai/v1" - } -} -``` + ``` + + 5. If you run into any issues or have any questions, please join our Discord and post in the `#help` channel [here](https://discord.gg/EfJEfdFnDQ) diff --git a/docs/docs/edit/how-it-works.md b/docs/docs/edit/how-it-works.md index 19f107782..453d1e98f 100644 --- a/docs/docs/edit/how-it-works.md +++ b/docs/docs/edit/how-it-works.md @@ -11,4 +11,4 @@ The model response is then streamed directly back to the highlighted range in yo If you accept the diff, we remove the previously highlighted lines, and if you reject the diff, we remove the proposed changes. -If you would like to view the exact prompt that is sent to the model during an edit, you can [view this in the prompt logs](troubleshooting.md#check-the-logs). +If you would like to view the exact prompt that is sent to the model during an edit, you can [view this in the prompt logs](../troubleshooting.mdx#check-the-logs). diff --git a/docs/docs/edit/how-to-customize.md b/docs/docs/edit/how-to-customize.md deleted file mode 100644 index aa9d464c7..000000000 --- a/docs/docs/edit/how-to-customize.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -title: How to customize -sidebar_position: 5 -description: How to customize Edit -keywords: [edit, cmd i, works] ---- - -You can configure a particular model to be used for Edit using the `inlineEdit` property. - -```json title="config.json" -"experimental": { - "modelRoles": { - "inlineEdit": "MODEL_TITLE", - } -} -``` \ No newline at end of file diff --git a/docs/docs/edit/how-to-customize.mdx b/docs/docs/edit/how-to-customize.mdx new file mode 100644 index 000000000..ef8e44a54 --- /dev/null +++ b/docs/docs/edit/how-to-customize.mdx @@ -0,0 +1,44 @@ +--- +title: How to customize +sidebar_position: 5 +description: How to customize Edit +keywords: [edit, cmd i, works] +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +You can configure a particular model to be used for Edit: + + + + Use model roles. + ```yaml title="Package or config.yaml" + models: + - name: Claude 3.5 Sonnet + provider: anthropic + model: claude-3-5-sonnet-latest + apiKey: + roles: + - edit + ``` + + + Set the `experimental.modelRoles.inlineEdit` property in `config.json`. + ```json title="config.json" + { + "models": { + "name": "Claude 3.5 Sonnet", + "provider": "anthropic", + "model": "claude-3-5-sonnet-latest", + "apiKey": "" + }, + "experimental": { + "modelRoles": { + "inlineEdit": "Claude 3.5 Sonnet", + } + } + } + ``` + + diff --git a/docs/docs/edit/model-setup.md b/docs/docs/edit/model-setup.md index ded10c2a4..ad884b334 100644 --- a/docs/docs/edit/model-setup.md +++ b/docs/docs/edit/model-setup.md @@ -5,6 +5,6 @@ description: How to set up an Edit model 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. +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`](../reference.md). +You can configure a different model to be used for edits by updating your [configuration](../reference.md). diff --git a/docs/docs/getting-started/install.md b/docs/docs/getting-started/install.md index 3729edbfd..f144a37a1 100644 --- a/docs/docs/getting-started/install.md +++ b/docs/docs/getting-started/install.md @@ -13,7 +13,7 @@ keywords: [install, installation, getting started, vs code, jetbrains] ![move-to-right-sidebar](/img/move-to-right-sidebar.gif) :::info[Troubleshooting] -If you have any problems, see the [troubleshooting guide](troubleshooting.md) or ask for help in [our Discord](https://discord.gg/NWtdYexhMs) +If you have any problems, see the [troubleshooting guide](../troubleshooting.mdx) or ask for help in [our Discord](https://discord.gg/NWtdYexhMs) ::: ## JetBrains @@ -25,5 +25,5 @@ If you have any problems, see the [troubleshooting guide](troubleshooting.md) or ![jetbrains-getting-started.png](/img/jetbrains-getting-started.png) :::info[Troubleshooting] -If you have any problems, see the [troubleshooting guide](troubleshooting.md) or ask for help in [our Discord](https://discord.com/invite/EfJEfdFnDQ) +If you have any problems, see the [troubleshooting guide](../troubleshooting.mdx) or ask for help in [our Discord](https://discord.com/invite/EfJEfdFnDQ) ::: diff --git a/docs/docs/introduction.md b/docs/docs/introduction.md index 64f83436d..cfa1301cd 100644 --- a/docs/docs/introduction.md +++ b/docs/docs/introduction.md @@ -19,7 +19,7 @@ keywords: **Continue is the leading open-source AI code assistant inside of [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension)** -- [Chat](chat/how-to-use-it.md) to understand and iterate on code in the sidebar -- [Autocomplete](autocomplete/how-to-use-it.md) to receive inline code suggestions as you type -- [Edit](edit/how-to-use-it.md) to modify code without leaving your current file -- [Actions](actions/how-to-use-it.md) to establish shortcuts for common use cases +- [Chat](chat/how-to-use-it) to understand and iterate on code in the sidebar +- [Autocomplete](autocomplete/how-to-use-it) to receive inline code suggestions as you type +- [Edit](edit/how-to-use-it) to modify code without leaving your current file +- [Actions](actions/how-to-use-it) to establish shortcuts for common use cases diff --git a/docs/docs/json-reference.md b/docs/docs/json-reference.md new file mode 100644 index 000000000..470d59921 --- /dev/null +++ b/docs/docs/json-reference.md @@ -0,0 +1,438 @@ +--- +title: config.json Reference +description: Reference for the Continue _config.json_ configuration file +keywords: [config, config_schema.json, json] +--- + +:::info +`config.json` is the original Continue configuration format. The newer and preferred format is [`YAML Config`](./reference). See the [migration guide](./yaml-migration). +::: + +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), [Edit](./edit/how-to-use-it), and [Actions](./actions/how-to-use-it). +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`, `xAI`, etc., see IntelliJ suggestions. +- `model` (**required**): The name of the model, used for prompt template auto-detection. Use `AUTODETECT` special name to get all available models. +- `apiKey`: API key required by providers like OpenAI, Anthropic, Cohere, and xAI. +- `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": "" + } + ] +} +``` + +### `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`). +- `maxPromptTokens`: Maximum number of tokens for the prompt (default: `1024`). +- `debounceDelay`: Delay (in ms) before triggering autocomplete (default: `350`). +- `maxSuffixPercentage`: Maximum percentage of prompt for suffix (default: `0.2`). +- `prefixPercentage`: Percentage of input for prefix (default: `0.3`). +- `template`: Template string for autocomplete, using Mustache templating. You can use the `{{{ prefix }}}`, `{{{ suffix }}}`, `{{{ filename }}}`, `{{{ reponame }}}`, and `{{{ language }}}` variables. +- `onlyMyCode`: If `true`, only includes code within the repository (default: `true`). + +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). +- `useMmap`: For Ollama, this parameter allows the model to be mapped into memory. If disabled can enhance response time on low end devices but will slow down the stream. + +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`, `bedrock` +- `params`: + - `model`: Model name + - `apiKey`: Api key + - `region`: Region (for Bedrock only) + +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" + } + ] +} +``` + +### `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", "http", "commit", and "review". +- `description`: Brief description of the command. +- `step`: 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": "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. +- `codeWrap`: If `true`, enables text wrapping in code blocks. + +Example: + +```json title="config.json" +{ + "ui": { + "codeBlockToolbarPosition": "bottom", + "fontSize": 14, + "displayRawMarkdown": false, + "showChatScrollbar": false, + "codeWrap": 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. + +### `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. +- `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. +- `modelContextProtocolServers`: See [Model Context Protocol](/customize/context-providers#model-context-protocol) + +Example + +```json title="config.json" +{ + "experimental": { + "modelRoles": { + "inlineEdit": "Edit Model" + }, + "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." + }, + "modelContextProtocolServers": [ + { + "transport": { + "type": "stdio", + "command": "uvx", + "args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"] + } + } + ] + } +} +``` diff --git a/docs/docs/reference.md b/docs/docs/reference.md index a14da2944..03707c4e4 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -4,6 +4,10 @@ description: Reference for the Continue _config.json_ configuration file keywords: [config, config_schema.json, json] --- +:::info +We recently introduced a new configuration format, `config.yaml`, to replace `config.json`. See the `config.yaml` reference and migration guide [here](./yaml-reference.md). +::: + 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** @@ -32,6 +36,7 @@ Each model has specific configuration options tailored to its provider and funct - `engine`: Engine for Azure OpenAI requests. - `capabilities`: Override auto-detected capabilities: - `uploadImage`: Boolean indicating if the model supports image uploads. + - `tools`: Boolean indicating if the model supports tool use. _(AWS Only)_ diff --git a/docs/docs/telemetry.md b/docs/docs/telemetry.md index 3d59ebf74..e086d409d 100644 --- a/docs/docs/telemetry.md +++ b/docs/docs/telemetry.md @@ -28,4 +28,4 @@ The following usage information is collected and reported: You can disable anonymous telemetry by visiting the [User Settings Page](./customize/settings.md) and toggling "Allow Anonymous Telemetry" off. -Alternatively in VS Code, you can disable telemetry through your VS Code settings by unchecking the "Continue: Telemetry Enabled" box (this will override the Settings Page settings). +Alternatively in VS Code, you can disable telemetry through your VS Code settings by unchecking the "Continue: Telemetry Enabled" box (this will override the Settings Page settings). VS Code settings can be accessed with `File` > `Preferences` > `Settings` (or use the keyboard shortcut ctrl + , on Windows/Linux or cmd + , on macOS). diff --git a/docs/docs/troubleshooting.md b/docs/docs/troubleshooting.mdx similarity index 85% rename from docs/docs/troubleshooting.md rename to docs/docs/troubleshooting.mdx index d4bbe69db..ae54ee8ac 100644 --- a/docs/docs/troubleshooting.md +++ b/docs/docs/troubleshooting.mdx @@ -4,6 +4,9 @@ description: Troubleshooting while waiting for help during beta / alpha testing keywords: [reload, delete, manually, logs, server, console] --- +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + The Continue VS Code extension is currently in beta, and the JetBrains extension is in Alpha. If you are having trouble, please follow the steps below. 1. [Check the logs](#check-the-logs) @@ -24,7 +27,9 @@ To solve many problems, the first step is reading the logs to find the relevant In order to view debug logs, which contain extra information, click the dropdown at the top that says "Default levels" and select "Verbose". ::: -1. cmd + shift + P for MacOS or ctrl + shift + P for Windows +1. cmd + shift + P for MacOS or ctrl + + shift + + P for Windows 2. Search for and then select "Developer: Toggle Developer Tools" 3. This will open the [Chrome DevTools window](https://developer.chrome.com/docs/devtools/) 4. Select the `Console` tab @@ -83,22 +88,34 @@ If your keyboard shortcuts are not resolving, you may have other commands that a #### Configure Certificates -If you're seeing a `fetch failed` error and your network requires custom certificates, you will need to configure them in `config.json`. In each of the objects in the `"models"` array, add `requestOptions.caBundlePath` like this: +If you're seeing a `fetch failed` error and your network requires custom certificates, you will need to configure them in your config file. In each of the objects in the `"models"` array, add `requestOptions.caBundlePath` like this: -```json -{ - "models": [ - { - "title": "My Model", + + + ```yaml title="config.yaml" + models: + - name: My Model ... - "requestOptions": { - "caBundlePath": "/path/to/cert.pem" + requestOptions: + caBundlePath: /path/to/cert.pem + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "My Model", + ... + "requestOptions": { + "caBundlePath": "/path/to/cert.pem" + } } - } - ], - ... -} -``` + ], + } + ``` + + You may also set `requestOptions.caBundlePath` to an array of paths to multiple certificates. @@ -118,6 +135,12 @@ By default the Continue window is on the left side of VS Code, but it can be dra If you have entered a valid API key and model, but are still getting a 404 error from OpenAI, this may be because you need to add credits to your billing account. You can do so from the [billing console](https://platform.openai.com/settings/organization/billing/overview). If you just want to check that this is in fact the cause of the error, you can try adding $1 to your account and checking whether the error persists. +### I'm getting a 404 error from OpenRouter + +If you have entered a valid API key and model, but are still getting a 404 error from OpenRouter, this may be because models that do not support function calling will return an error to Continue when a request is sent. +Example error: +`HTTP 404 Not Found from https://openrouter.ai/api/v1/chat/completions` + ### Indexing issues If you are having persistent errors with indexing, our recommendation is to rebuild your index from scratch. Note that for large codebases this may take some time. diff --git a/docs/docs/yaml-migration.md b/docs/docs/yaml-migration.md index 04f1b4e15..cc603ce1c 100644 --- a/docs/docs/yaml-migration.md +++ b/docs/docs/yaml-migration.md @@ -11,8 +11,8 @@ Continue's YAML configuration format provides more readable, maintainable, consi See also - [Intro to YAML](https://yaml.org/) -- [JSON Continue Config Reference](/reference) -- [YAML Continue Config Reference](/yaml-reference) +- [JSON Continue Config Reference](/json-reference) +- [YAML Continue Config Reference](/reference) ## Create YAML file @@ -37,23 +37,22 @@ Add all model configurations in `config.json`, including models in `models`, `ta - `inlineEdit` -> e.g. `roles: [chat, edit]` - `applyCodeBlock` -> e.g. `roles: [chat, apply]` -Model-level `requestOptions` remain, with minor changes. See [YAML Continue Config Reference](/yaml-reference#requestoptions) +Model-level `requestOptions` remain, with minor changes. See [YAML Continue Config Reference](/reference#requestoptions) -Model-level `completionOptions` are replaced by `defaultCompletionOptions`, with minor changes. See [YAML Continue Config Reference](/yaml-reference#completionoptions) +Model-level `completionOptions` are replaced by `defaultCompletionOptions`, with minor changes. See [YAML Continue Config Reference](/reference#completionoptions) - **Before** -```json title="config.json" +```json title="config.json"" { "models": [ { "title": "GPT-4", "provider": "openai", "model": "gpt-4", - "apiKey": "YOUR_API_KEY", + "apiKey": "", "completionOptions": { "temperature": 0.5, "maxTokens": 2000 @@ -82,7 +81,7 @@ Model-level `completionOptions` are replaced by `defaultCompletionOptions`, with "embeddingsProvider": { "provider": "openai", "model": "text-embedding-ada-002", - "apiKey": "", + "apiKey": "", "maxChunkSize": 256, "maxBatchSize": 5 }, @@ -90,7 +89,7 @@ Model-level `completionOptions` are replaced by `defaultCompletionOptions`, with "name": "voyage", "params": { "model": "rerank-2", - "apiKey": "" + "apiKey": "" } } } @@ -103,7 +102,7 @@ models: - name: GPT-4 provider: openai model: gpt-4 - apiKey: + apiKey: defaultCompletionOptions: temperature: 0.5 maxTokens: 2000 @@ -113,8 +112,7 @@ models: - name: My Voyage Reranker provider: voyage - apiKey: - roles: + apiKey: - rerank - name: My Starcoder @@ -125,7 +123,7 @@ models: - name: My Ada Embedder provider: openai - apiKey: + apiKey: roles: - embed @@ -139,7 +137,7 @@ models: apiBase: http://3.3.3.3/v1 requestOptions: headers: - X-Auth-Token: + X-Auth-Token: roles: - chat - apply @@ -156,7 +154,7 @@ The JSON `contextProviders` field is replaced by the YAML `context` array. **Before** -```json title="config.json" +```json title="config.json"" { "contextProviders": [ { @@ -188,7 +186,7 @@ context: nRetrieve: 30 nFinal: 3 - - params: diff + - provider: diff ``` ### System Message @@ -197,7 +195,7 @@ The `systemMessage` property has been replaced with a `rules` property that take **Before** -```json title="config.json" +```json title="config.json"" { "systemMessage": "Always give concise responses" } @@ -216,7 +214,7 @@ Rather than with `customCommands`, you can now use the `prompts` field to define **Before** -```json title="config.json" +```json title="config.json"" { "customCommands": [ { @@ -251,7 +249,7 @@ Documentation is largely the same, but the `title` property has been replaced wi **Before** -```json title="config.json" +```json title="config.json"" { "docs": [ { @@ -279,8 +277,6 @@ docs: ### MCP Servers - - **Properties:** - `name` (**required**): The name of the MCP server. @@ -290,7 +286,7 @@ docs: **Before** -```json title="config.json" +```json title="config.json"" { "experimental": { "modelContextProtocolServers": [ @@ -345,10 +341,13 @@ The following top-level fields from `config.json` still work when using `config. - `template` - `onlyMyCode` - `analytics` + +The following top-level fields from `config.json` have been deprecated. Most UI-related and user-specific options will move into a settings page in the UI + - `customCommands` - `experimental` - `userToken` ## New Configuration options -The YAML configuration format offers new configuration options not available in the JSON format. See the [YAML Config Reference](/yaml-reference) for more information. +The YAML configuration format offers new configuration options not available in the JSON format. See the [YAML Config Reference](./reference) for more information. diff --git a/docs/docs/yaml-reference.md b/docs/docs/yaml-reference.md index e504c95fd..d4ae3acac 100644 --- a/docs/docs/yaml-reference.md +++ b/docs/docs/yaml-reference.md @@ -4,7 +4,7 @@ description: Reference for the Continue configuration YAML file keywords: [config, yaml, configuration, customize, customization] --- -# Config YAML Reference +# confg.yaml Reference @@ -13,7 +13,7 @@ Continue can be configured using a YAML file `config.yaml` which for local confi Below are details for each property that can be set in `config.yaml`. :::info -Config YAML does not work alongside `config.json` - it replaces it. View the **[Migration Guide](/yaml-migration)**. `config.yaml` currently only works in VS Code pre-release. +Config YAML replaces `config.json`. View the **[Migration Guide](/yaml-migration)**. `config.yaml` currently only works in VS Code pre-release. ::: **All properties at all levels are optional unless explicitly marked as required.** @@ -23,6 +23,7 @@ Config YAML does not work alongside `config.json` - it replaces it. View the **[ The top-level properties in the `config.yaml` configuration file are: - [`name`](#name) (**required**) + - [`version`](#version) (**required**) - [`models`](#models) - [`context`](#context) @@ -115,7 +116,7 @@ models: The `context` section defines context providers, which supply additional information or context to the language models. Each context provider can be configured with specific parameters. -More information about usage/params for each context provider can be found [here](/customize/context-providers) +More information about usage/params for each context provider can be found [here](/customize/context-providers.mdx) **Properties:** @@ -179,9 +180,9 @@ List of documentation sites to index. - `name` (**required**): Name of the documentation site, displayed in dropdowns, etc. - `startUrl` (**required**): Start page for crawling - usually root or intro page for docs +- `maxDepth`: Maximum link depth for crawling. Default `4` - `favicon`: URL for site favicon (default is `/favicon.ico` from `startUrl`). -- `maxDepth`: M -- `useLocalCrawling`: Force use of local crawling +- `useLocalCrawling`: Skip the default crawler and only crawl using a local crawler. Example @@ -208,7 +209,7 @@ The `tools` section specifies external tools or APIs that can be used within you ```yaml title="config.yaml" tools: - url: https://api.exampletool.com/tool1 - apiKey: YOUR_API_KEY + apiKey: ``` --- --> @@ -252,7 +253,6 @@ The `data` section specifies data providers used in your configuration. Data pro data: - provider: embeddings ``` - --- --> --- @@ -307,6 +307,7 @@ context: - provider: docs params: startUrl: https://docs.example.com/introduction + rootUrl: https://docs.example.com maxDepth: 3 mcpServers: @@ -318,3 +319,28 @@ mcpServers: env: PORT: "3000" ``` + +### Fully deprecated settings + +Some deprecated `config.json` settings are no longer stored in config and have been moved to be editable through the [User Settings Page](./customize/settings.md). If found in `config.json`, they will be migrated to the [User Settings Page](./customize/settings.md) and removed from `config.json`. + +- `allowAnonymousTelemetry`: This value will be migrated to the safest merged value (`false` if either are `false`). +- `promptPath`: This value will override during migration. +- `disableIndexing`: This value will be migrated to the safest merged value (`true` if either are `true`). +- `disableSessionTitles`/`ui.getChatTitles`: This value will be migrated to the safest merged value (`true` if either are `true`). `getChatTitles` takes precedence if set to false +- `tabAutocompleteOptions` + - `useCache`: This value will override during migration. + - `disableInFiles`: This value will be migrated to the safest merged value (arrays of file matches merged/deduplicated) + - `multilineCompletions`: This value will override during migration. +- `experimental` + - `useChromiumForDocsCrawling`: This value will override during migration. + - `readResponseTTS`: This value will override during migration. +- `ui` - all will override during migration + + - `codeBlockToolbarPosition` + - `fontSize` + - `codeWrap` + - `displayRawMarkdown` + - `showChatScrollbar` + + See [User Settings Page](./customize/settings.md) for more information about each option. diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-customize.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-customize.md index 2ffc4d0f2..aeadb68f8 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-customize.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-customize.md @@ -7,7 +7,7 @@ sidebar_position: 5 ## 内置的斜杠命令 -Continue 有一个大的内置斜杠命令库,但是当你首次安装时,我们只显示最常用的一些,比如 "/edit", "/comment" 和 "/share" 。为了添加更多的 action ,你可以打开 [config.json](../reference.md) 并添加它们到 `slashCommands` 列表中。 +Continue 有一个大的内置斜杠命令库,但是当你首次安装时,我们只显示最常用的一些,比如 "/edit", "/comment" 和 "/share" 。为了添加更多的 action ,你可以打开 [config.json](../json-reference.md) 并添加它们到 `slashCommands` 列表中。 ## 定制斜杠命令 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/how-to-customize.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/how-to-customize.md index 143645591..14a062a50 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/how-to-customize.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/how-to-customize.md @@ -5,7 +5,7 @@ keywords: [定制] sidebar_position: 5 --- -Continue 在 [`config.json`](../reference.md) 提供少量的参数,对于你的特定需求和硬件能力,可以调整找到建议质量和系统性能之间的最佳平衡: +Continue 在 [`config.json`](../json-reference.md) 提供少量的参数,对于你的特定需求和硬件能力,可以调整找到建议质量和系统性能之间的最佳平衡: ```json title="config.json" "tabAutocompleteOptions": { diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/model-setup.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/model-setup.md index 01747b24c..a7d9c3173 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/model-setup.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/model-setup.md @@ -9,7 +9,7 @@ sidebar_position: 2 为了最好的自动补全体验,我们推荐通过 [Mistral API](https://console.mistral.ai/) 使用 Codestral 。这个模型提供高质量的补全,使用极好的代码上下文理解: -```json title="config.json"" +```json title="config.json" { "tabAutocompleteModel": { "title": "Codestral", @@ -28,7 +28,7 @@ Codestral 的 API key 和通常的 Mistral API 是不同的。如果你使用 Co 对于倾向于本地执行或自托管的, `StarCoder2-3b` 提供了一个对于大多数用户性能和质量的平衡: -```json title="config.json"" +```json title="config.json" { "tabAutocompleteModel": { "title": "StarCoder2-3b", diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/context-selection.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/context-selection.md index a52a5a3d7..301de5524 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/context-selection.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/context-selection.md @@ -19,28 +19,28 @@ sidebar_position: 3 ## 指定文件 -你可以通过输入 [`@Files`](../customize/context-providers.md#file) 并选择文件,包含当前工作区中的指定文件作为上下文。 +你可以通过输入 [`@Files`](../customize/context-providers.mdx#file) 并选择文件,包含当前工作区中的指定文件作为上下文。 ## 指定目录 -你可以通过输入 [`@Folder`](../customize/context-providers.md#folder) 并选择目录,包含当前工作区中指定目录作为上下文。它像 [`@Codebase`](../customize/deep-dives/codebase.md) 一样工作,但是只包含指定目录中的文件。 +你可以通过输入 [`@Folder`](../customize/context-providers.mdx#folder) 并选择目录,包含当前工作区中指定目录作为上下文。它像 [`@Codebase`](../customize/deep-dives/codebase.md) 一样工作,但是只包含指定目录中的文件。 ## 整个代码库 -你可以通过输入 [`@Codebase`](../customize/context-providers.md#codebase) 包含整个代码库作为上下文。你可以 [在这里](../customize/deep-dives/codebase.md) 了解 `@Codebase` 是如何工作的。 +你可以通过输入 [`@Codebase`](../customize/context-providers.mdx#codebase) 包含整个代码库作为上下文。你可以 [在这里](../customize/deep-dives/codebase.md) 了解 `@Codebase` 是如何工作的。 ## 文档网址 -你可以通过输入 [`@Docs`](../customize/context-providers.md#docs) 并选择文档网址,包含文档网址作文上下文。你可以 [在这里](../customize/deep-dives/docs.md) 了解 `@Docs` 是如何工作的。 +你可以通过输入 [`@Docs`](../customize/context-providers.mdx#docs) 并选择文档网址,包含文档网址作文上下文。你可以 [在这里](../customize/deep-dives/docs.md) 了解 `@Docs` 是如何工作的。 ## 终端内容 -你可以通过输入 [`@Terminal`](../customize/context-providers.md#terminal) ,包含 IDE 中终端的内容作为上下文。 +你可以通过输入 [`@Terminal`](../customize/context-providers.mdx#terminal) ,包含 IDE 中终端的内容作为上下文。 ## Git diff -你可以通过输入 [`@Git Diff`](../customize/context-providers.md#git-diff) ,包含当前分支中你做的所有变更作为上下文。 +你可以通过输入 [`@Git Diff`](../customize/context-providers.mdx#git-diff) ,包含当前分支中你做的所有变更作为上下文。 ## 其他上下文 -你可以 [在这里](../customize/context-providers.md) 看到完整的内置上下文提供者列表,以及 [在这里](../customize/tutorials/build-your-own-context-provider.md) 看到如何创建你自己定制的上下文提供者。 +你可以 [在这里](../customize/context-providers.mdx) 看到完整的内置上下文提供者列表,以及 [在这里](../customize/tutorials/build-your-own-context-provider.md) 看到如何创建你自己定制的上下文提供者。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/model-setup.mdx b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/model-setup.mdx index cbbef8761..b6360c8d3 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/model-setup.mdx +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/model-setup.mdx @@ -9,7 +9,7 @@ import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; :::info -这个页面推荐聊天的模型和提供者。在 [这里](../reference.md) 了解更多关于如何设置你的 `config.json` 。 +这个页面推荐聊天的模型和提供者。在 [这里](../json-reference.md) 了解更多关于如何设置你的 `config.json` 。 ::: ## 最好的总体体验 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/autocomplete.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/autocomplete.md index 985a66809..e6774dfe5 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/autocomplete.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/autocomplete.md @@ -44,7 +44,7 @@ ollama run starcoder2:3b } ``` -如果你对可用选项不熟悉,你可以在 [这里](../../reference.md) 查找完整的参考。 +如果你对可用选项不熟悉,你可以在 [这里](../../json-reference.md) 查找完整的参考。 ## 配置选项 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/codebase.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/codebase.md index eb55aa668..969e394a0 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/codebase.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/codebase.md @@ -73,4 +73,4 @@ Continue 遵守 `.gitignore` 文件,为了确定哪些文件不需要索引。 ## 仓库 map -Claude 3, Llama 3.1, Gemini 1.5 和 GPT-4o 家族的模型在代码库检索时会自动地使用 [仓库 map](../context-providers.md#repository-map) ,允许模型理解你的代码库的结构,并使用它回答问题。当前,仓库 map 仅包含代码库中的文件路径。 +Claude 3, Llama 3.1, Gemini 1.5 和 GPT-4o 家族的模型在代码库检索时会自动地使用 [仓库 map](../context-providers.mdx#repository-map) ,允许模型理解你的代码库的结构,并使用它回答问题。当前,仓库 map 仅包含代码库中的文件路径。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/prompt-files.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/prompt-files.md index bbcd0d36b..b419231fe 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/prompt-files.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/prompt-files.md @@ -79,7 +79,7 @@ Write unit tests for the above selected code, following each of these instructio ### 上下文提供者 -任何你添加到配置中的 [上下文提供者](../context-providers.md) ,可以使用上下文提供者的名称引用。接收输入的上下文提供者也支持。 +任何你添加到配置中的 [上下文提供者](../context-providers.mdx) ,可以使用上下文提供者的名称引用。接收输入的上下文提供者也支持。 - `{{{ terminal }}}` - 终端的内容 - `{{{ url "https://github.com/continuedev/continue" }}}` - URL 的内容 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/xai.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/xai.md index fbdfa83ad..c920114b0 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/xai.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/xai.md @@ -46,8 +46,16 @@ xAI currently does not offer any reranking models. ## Legacy Completions -To force usage of `chat/completions` instead of `completions` endpoint you can set +To force usage of `chat/completions` instead of `completions` endpoint you can set `useLegacyCompletionsEndpoint` to `true`: -```json -"useLegacyCompletionsEndpoint": false +```json title="config.json" + "models": [ + { + "title": "Grok Beta", + "provider": "xAI", + "model": "grok-beta", + "apiKey": "[API_KEY]", + "useLegacyCompletionsEndpoint": false + } + ] ``` diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/overview.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/overview.md index 1c5d041e2..0d94978c1 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/overview.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/overview.md @@ -8,13 +8,13 @@ Continue 可以深度定制。这个主要通过编辑位于 `~/.continue/config ## 开始 -要打开 `config.json` ,在 Continue 聊天侧边栏的右下角点击 "齿轮" 图标。当编辑这个文件时,你可以使用 IntelliSense ,随着你的输入来查看有效的选项,或者你可以查看 [完整参考](../reference.md) 。 +要打开 `config.json` ,在 Continue 聊天侧边栏的右下角点击 "齿轮" 图标。当编辑这个文件时,你可以使用 IntelliSense ,随着你的输入来查看有效的选项,或者你可以查看 [完整参考](../json-reference.md) 。 当你保存 `config.json` 时, Continue 会自动地刷新,应用你的变更。 ## 每个工作区的配置 -如果你想要限制指定的配置到一个特定的工作区,你可以添加一个 `.continuerc.json` 到你的项目根目录。它有和 `config.json` 相同的 [定义](../reference.md) ,会自动地应用到本地 `config.json` 之上。 +如果你想要限制指定的配置到一个特定的工作区,你可以添加一个 `.continuerc.json` 到你的项目根目录。它有和 `config.json` 相同的 [定义](../json-reference.md) ,会自动地应用到本地 `config.json` 之上。 ## 可编程的配置 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/build-your-own-context-provider.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/build-your-own-context-provider.md index 735f405de..abe3612ce 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/build-your-own-context-provider.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/build-your-own-context-provider.md @@ -68,7 +68,7 @@ export function modifyConfig(config: Config): Config { } ``` -不需要对 `config.json` 做修改。 +不需要对 `config.json` 做修改。 ## 定制有 submenu 或 query 的上下文提供者 @@ -174,7 +174,7 @@ Continue 将使用 [esbuild](https://esbuild.github.io/) 打包你的 `config.ts 如果你想要用除了 TypeScript 的其他语言编写上下文提供者,你可以使用 "http" 上下文提供者,来调用一个托管你自己代码的服务器。添加上下文提供者到 `config.json` ,像这样: -```json +```json title="config.json" { "name": "http", "params": { diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/llama3.1.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/llama3.1.md index e02ba6741..877864a15 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/llama3.1.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/llama3.1.md @@ -99,7 +99,7 @@ SambaNova Cloud 提供 Llama3.1 70B/405B 服务的世界记录。 2. 复制你的 API key 3. 更新你的 Continue 配置文件像这样: -```json title="~/.continue/config.json" +```json title="config.json" { "models": [ { diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/edit/model-setup.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/edit/model-setup.md index 07a0a6c65..f0db33bbc 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/edit/model-setup.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/edit/model-setup.md @@ -7,4 +7,4 @@ keywords: [编辑, cmd l, 模型] 默认情况下,编辑使用 [与聊天相同的模型](../chat/model-setup.mdx) ,所以对于代码编辑,我们推荐相同的 400B+ 参数模型或者领先的模型之一。 -你可以通过更新你的 [`config.json`](../reference.md) 为编辑配置一个不同的模型。 +你可以通过更新你的 [`config.json`](../json-reference.md) 为编辑配置一个不同的模型。 diff --git a/docs/sidebars.js b/docs/sidebars.js index 380377f8a..bb7f80604 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -138,6 +138,11 @@ const sidebars = { label: "Reference", href: "/reference", }, + { + type: "link", + label: "JSON Reference", + href: "/json-reference", + }, "customize/changelog", // { // type: "link", diff --git a/docs/src/theme/Root.js b/docs/src/theme/Root.js new file mode 100644 index 000000000..88a8947e4 --- /dev/null +++ b/docs/src/theme/Root.js @@ -0,0 +1,21 @@ +import React from "react"; + +function TabsSetDefaultValue() { + React.useEffect(() => { + // Only set if it's not already set + if (!localStorage.getItem("docusaurus.tab.config-example")) { + localStorage.setItem("docusaurus.tab.config-example", "json"); + } + }, []); + + return null; +} + +export default function Root({ children }) { + return ( + <> + + {children} + + ); +} diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index 7028aa723..b8b36867e 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.87 +pluginVersion=0.0.91 # 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/actions/ContinuePluginActions.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt index b93d294e1..3c6b27f05 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt @@ -113,7 +113,8 @@ class NewContinueSessionAction : AnAction() { class ViewHistoryAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { val continuePluginService = getContinuePluginService(e.project) ?: return - continuePluginService.sendToWebview("viewHistory", null) + val params = mapOf("path" to "/history", "toggle" to true) + continuePluginService.sendToWebview("navigateTo", params) } } @@ -133,11 +134,4 @@ class OpenMorePageAction : AnAction() { val params = mapOf("path" to "/more", "toggle" to true) continuePluginService.sendToWebview("navigateTo", params) } -} - -class OpenAccountDialogAction : AnAction() { - override fun actionPerformed(e: AnActionEvent) { - val continuePluginService = getContinuePluginService(e.project) ?: return - continuePluginService.sendToWebview("openDialogMessage", "account") - } } \ No newline at end of file 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 72819421a..b65266016 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 @@ -37,6 +37,7 @@ import com.intellij.openapi.vfs.newvfs.BulkFileListener import com.intellij.openapi.vfs.newvfs.events.VFileEvent import com.intellij.openapi.vfs.newvfs.events.VFileDeleteEvent import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent +import com.intellij.ide.ui.LafManagerListener fun showTutorial(project: Project) { val tutorialFileName = getTutorialFileName() @@ -47,7 +48,15 @@ fun showTutorial(project: Project) { throw IOException("Resource not found: $tutorialFileName") } var content = StreamUtil.readText(`is`, StandardCharsets.UTF_8) + + // All jetbrains will use J instead of L + content = content.replace("[Cmd + L]", "[Cmd + J]") + content = content.replace("[Cmd + Shift + L]", "[Cmd + Shift + J]") + if (!System.getProperty("os.name").lowercase().contains("mac")) { + content = content.replace("[Cmd + J]", "[Ctrl + J]") + content = content.replace("[Cmd + Shift + J]", "[Ctrl + Shift + J]") + content = content.replace("[Cmd + I]", "[Ctrl + I]") content = content.replace("⌘", "⌃") } val filepath = Paths.get(getContinueGlobalPath(), tutorialFileName).toString() @@ -174,7 +183,7 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware { val changedURIs = events.filterIsInstance() .mapNotNull { event -> event.file.toUriOrNull() } - // Send "files/changed" message if there are any content changes + // Notify core of content changes if (changedURIs.isNotEmpty()) { val data = mapOf("files" to changedURIs) continuePluginService.coreMessenger?.request("files/changed", data, null) { _ -> } @@ -182,6 +191,15 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware { } }) + // Listen for theme changes + connection.subscribe(LafManagerListener.TOPIC, LafManagerListener { + val colors = GetTheme().getTheme(); + continuePluginService.sendToWebview( + "jetbrains/setColors", + colors + ) + }) + // Listen for clicking settings button to start the auth flow val authService = service() val initialSessionInfo = authService.loadControlPlaneSessionInfo() @@ -196,7 +214,7 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware { connection.subscribe(AuthListener.TOPIC, object : AuthListener { override fun startAuthFlow() { - authService.startAuthFlow(project) + authService.startAuthFlow(project, false) } override fun handleUpdatedSessionInfo(sessionInfo: ControlPlaneSessionInfo?) { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthDialog.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthDialog.kt index b8a862fad..b9faf65d7 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthDialog.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthDialog.kt @@ -7,7 +7,8 @@ import javax.swing.JComponent import javax.swing.JPanel import java.awt.BorderLayout -class ContinueAuthDialog(private val onTokenEntered: (String) -> Unit) : DialogWrapper(true) { +class ContinueAuthDialog(private val useOnboarding: Boolean, private val onTokenEntered: (String) -> Unit) : + DialogWrapper(true) { private val tokenField = JBTextField() init { @@ -17,7 +18,9 @@ class ContinueAuthDialog(private val onTokenEntered: (String) -> Unit) : DialogW override fun createCenterPanel(): JComponent { val panel = JPanel(BorderLayout()) - panel.add(JBLabel("Please enter your Continue authentication token:"), BorderLayout.NORTH) + val message = + if (useOnboarding) "After onboarding you will be shown an authentication token. Please enter it here:" else "Please enter your Continue authentication token:" + panel.add(JBLabel(message), BorderLayout.NORTH) panel.add(tokenField, BorderLayout.CENTER) return panel } 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 d23308cf1..23b6b66bd 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 @@ -33,8 +33,18 @@ class ContinueAuthService { private const val REFRESH_TOKEN_KEY = "ContinueRefreshToken" private const val ACCOUNT_ID_KEY = "ContinueAccountId" private const val ACCOUNT_LABEL_KEY = "ContinueAccountLabel" - private const val CONTROL_PLANE_URL = "https://control-plane-api-service-i3dqylpbqa-uc.a.run.app" -// private const val CONTROL_PLANE_URL = "http://localhost:3001" + } + + private fun getControlPlaneUrl(): String { + val env = service().continueState.continueTestEnvironment; + when (env) { + "none" -> return "https://control-plane-api-service-i3dqylpbqa-uc.a.run.app" + "local" -> return "http://localhost:3001" + "production" -> return "https://api.continue.dev" + "test" -> return "https://api-test.continue.dev" + } + + return "https://control-plane-api-service-i3dqylpbqa-uc.a.run.app" } init { @@ -44,13 +54,13 @@ class ContinueAuthService { } } - fun startAuthFlow(project: Project) { + fun startAuthFlow(project: Project, useOnboarding: Boolean) { // Open login page - openSignInPage(project) + openSignInPage(project, useOnboarding) // Open a dialog where the user should paste their sign-in token ApplicationManager.getApplication().invokeLater { - val dialog = ContinueAuthDialog() { token -> + val dialog = ContinueAuthDialog(useOnboarding) { token -> // Store the token updateRefreshToken(token) } @@ -78,10 +88,12 @@ class ContinueAuthService { val lastName = user?.get("lastName") as? String val label = "$firstName $lastName" val id = user?.get("id") as? String + val email = user?.get("email") as? String // Persist the session info setRefreshToken(refreshToken!!) - val sessionInfo = ControlPlaneSessionInfo(accessToken!!, ControlPlaneSessionInfo.Account(id!!, label)) + val sessionInfo = + ControlPlaneSessionInfo(accessToken!!, ControlPlaneSessionInfo.Account(email!!, label)) setControlPlaneSessionInfo(sessionInfo) // Notify listeners @@ -111,7 +123,7 @@ class ContinueAuthService { private suspend fun refreshToken(refreshToken: String) = withContext(Dispatchers.IO) { val client = OkHttpClient() - val url = URL(CONTROL_PLANE_URL).toURI().resolve("/auth/refresh").toURL() + val url = URL(getControlPlaneUrl()).toURI().resolve("/auth/refresh").toURL() val jsonBody = mapOf("refreshToken" to refreshToken) val jsonString = Gson().toJson(jsonBody) val requestBody = jsonString.toRequestBody("application/json".toMediaType()) @@ -132,9 +144,13 @@ class ContinueAuthService { } - private fun openSignInPage(project: Project) { + private fun openSignInPage(project: Project, useOnboarding: Boolean) { val coreMessenger = project.service().coreMessenger - coreMessenger?.request("auth/getAuthUrl", null, null) { response -> + coreMessenger?.request( + "auth/getAuthUrl", mapOf( + "useOnboarding" to useOnboarding + ), null + ) { response -> val authUrl = ((response as? Map<*, *>)?.get("content") as? Map<*, *>)?.get("url") as? String if (authUrl != null) { // Open the auth URL in the browser @@ -208,7 +224,7 @@ class ContinueAuthService { val accountId = getAccountId() val accountLabel = getAccountLabel() - return if (accessToken != null && accountId != null && accountLabel != null) { + return if ((accessToken != null && accessToken != "") && accountId != null && accountLabel != null) { ControlPlaneSessionInfo( accessToken = accessToken, account = ControlPlaneSessionInfo.Account( diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteEditorListener.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteEditorListener.kt index f4ef8128b..19b0dfa3a 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteEditorListener.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteEditorListener.kt @@ -3,6 +3,7 @@ package com.github.continuedev.continueintellijextension.autocomplete import com.intellij.openapi.application.invokeLater import com.intellij.openapi.components.service import com.intellij.openapi.editor.Editor +import com.intellij.openapi.editor.EditorKind import com.intellij.openapi.editor.event.* import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.FileEditorManagerEvent @@ -11,6 +12,10 @@ import com.intellij.openapi.util.TextRange class AutocompleteCaretListener : CaretListener { override fun caretPositionChanged(event: CaretEvent) { + if(event.editor.editorKind != EditorKind.MAIN_EDITOR) { + return + } + val caret = event.caret ?: return val offset = caret.offset val editor = caret.editor diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt index 873add597..c6e5684e3 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt @@ -41,6 +41,18 @@ class MessageTypes { "logoutOfControlPlane", "getTerminalContents", "showToast", + "openUrl", + + // These only come from the GUI for now but should be here to prevent confusion + "toggleDevTools", + "showTutorial", + + // These are jetbrains only and only come from the GUI for now + // But again including for consistency + "copyText", + "jetbrains/isOSREnabled", + "jetbrains/getColors", + "jetbrains/onLoad" ) // Note: If updating these values, make a corresponding update in @@ -58,8 +70,6 @@ class MessageTypes { "setTTSActive", "getWebviewHistoryLength", "getCurrentSessionId", - "signInToControlPlane", - "openDialogMessage", "docs/suggestions", ) @@ -111,11 +121,12 @@ class MessageTypes { "indexing/setPaused", "docs/getSuggestedDocs", "docs/initStatuses", + "docs/getDetails", // "completeOnboarding", "addAutocompleteModel", - "profiles/switch", "didChangeSelectedProfile", + "didChangeSelectedOrg", "tools/call", "controlPlane/openUrl", "controlPlane/listOrganizations" diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GetTheme.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GetTheme.kt index 7eb4ab700..6aecca81b 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GetTheme.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GetTheme.kt @@ -1,15 +1,12 @@ package com.github.continuedev.continueintellijextension.`continue` -import com.intellij.codeInsight.template.impl.TemplateColors -import com.intellij.openapi.editor.DefaultLanguageHighlighterColors import com.intellij.openapi.editor.colors.EditorColors import com.intellij.openapi.editor.colors.EditorColorsManager -import com.intellij.openapi.editor.colors.EditorColorsScheme -import com.intellij.openapi.editor.colors.TextAttributesKey import java.awt.Color import kotlin.math.max import kotlin.math.min - +import com.intellij.ui.JBColor +import com.intellij.ui.ColorUtil class GetTheme { fun getSecondaryDark(): Color { @@ -42,53 +39,60 @@ class GetTheme { } fun getTheme(): Map { + fun toHex(color: Color): String { + return String.format("#%02x%02x%02x", color.red, color.green, color.blue) + } try { - val globalScheme = EditorColorsManager.getInstance().globalScheme - val defaultBackground = globalScheme.defaultBackground - val defaultForeground = globalScheme.defaultForeground - val highlight = globalScheme.getColor(EditorColors.MODIFIED_TAB_ICON_COLOR) ?: defaultForeground - val defaultBackgroundHex = - String.format("#%02x%02x%02x", defaultBackground.red, defaultBackground.green, defaultBackground.blue) - val defaultForegroundHex = - String.format("#%02x%02x%02x", defaultForeground.red, defaultForeground.green, defaultForeground.blue) - val highlightHex = String.format("#%02x%02x%02x", highlight.red, highlight.green, highlight.blue) + val background = JBColor.background() + val foreground = JBColor.foreground() - val grayscale = - (defaultBackground.red * 0.3 + defaultBackground.green * 0.59 + defaultBackground.blue * 0.11).toInt() + val buttonBackground = JBColor.namedColor("Button.background", Color(230, 230, 230)) + val buttonForeground = JBColor.namedColor("Button.foreground", Color(0, 0, 0)) - val adjustedRed: Int - val adjustedGreen: Int - val adjustedBlue: Int + val badgeBackground = JBColor.namedColor("Badge.background", Color(150, 150, 150)) + val badgeForeground = JBColor.namedColor("Badge.foreground", Color(0, 0, 0)) - val tint: Int = 20 - if (grayscale > 128) { // if closer to white - adjustedRed = max(0, defaultBackground.red - tint) - adjustedGreen = max(0, defaultBackground.green - tint) - adjustedBlue = max(0, defaultBackground.blue - tint) - } else { // if closer to black - adjustedRed = min(255, defaultBackground.red + tint) - adjustedGreen = min(255, defaultBackground.green + tint) - adjustedBlue = min(255, defaultBackground.blue + tint) - } + val inputBackground = JBColor.namedColor("TextField.background", Color(255, 255, 255)) - val secondaryDarkHex = String.format("#%02x%02x%02x", adjustedRed, adjustedGreen, adjustedBlue) + val border = JBColor.border() + val focusBorder = JBColor.namedColor("Focus.borderColor", Color(100, 100, 255)) + val editorScheme = EditorColorsManager.getInstance().globalScheme - return mapOf( - "--vscode-editor-foreground" to defaultForegroundHex, - "--vscode-sideBar-background" to defaultBackgroundHex, - "--vscode-input-background" to secondaryDarkHex, - "--vscode-editor-background" to defaultBackgroundHex, - "--vscode-button-background" to defaultBackgroundHex, - "--vscode-list-activeSelectionBackground" to defaultBackgroundHex, - "--vscode-focusBorder" to highlightHex, - "--vscode-quickInputList-focusForeground" to defaultForegroundHex, - "--vscode-quickInput-background" to secondaryDarkHex, - "--vscode-input-border" to "#80808080", - "--vscode-badge-background" to highlightHex, - "--vscode-badge-foreground" to defaultForegroundHex, - "--vscode-sideBar-border" to "#80808080" + val editorBackground = editorScheme.defaultBackground + val editorForeground = editorScheme.defaultForeground + + val actionHoverBackground = JBColor.namedColor("ActionButton.hoverBackground", Color(220, 220, 220)) + + val findMatchBackground = editorScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES)?.backgroundColor ?: Color(255, 221, 0) + + val theme = mapOf( + "--vscode-editor-foreground" to toHex(editorForeground), + "--vscode-editor-background" to toHex(editorBackground), + + "--vscode-button-background" to toHex(buttonBackground), + "--vscode-button-foreground" to toHex(buttonForeground), + + "--vscode-list-activeSelectionBackground" to toHex(actionHoverBackground) + "50", + + "--vscode-quickInputList-focusForeground" to toHex(foreground), + "--vscode-quickInput-background" to toHex(inputBackground), + + "--vscode-badge-background" to toHex(badgeBackground), + "--vscode-badge-foreground" to toHex(badgeForeground), + + "--vscode-input-background" to toHex(inputBackground), + "--vscode-input-border" to toHex(border), + "--vscode-sideBar-background" to toHex(background), + "--vscode-sideBar-border" to toHex(border), + "--vscode-focusBorder" to toHex(focusBorder), + + "--vscode-commandCenter-activeBorder" to toHex(focusBorder), + "--vscode-commandCenter-inactiveBorder" to toHex(border), + + "--vscode-editor-findMatchHighlightBackground" to toHex(findMatchBackground) + "40" ) + return theme } catch (error: Error) { return mapOf() } 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 efffc54ee..9b8f558c2 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 @@ -43,27 +43,12 @@ class IdeProtocolClient( ) } - private fun send(messageType: String, data: Any?, messageId: String? = null) { - val id = messageId ?: uuid() - continuePluginService.sendToWebview(messageType, data, id) - } - fun handleMessage(msg: String, respond: (Any?) -> Unit) { coroutineScope.launch(Dispatchers.IO) { val message = Gson().fromJson(msg, Message::class.java) val messageType = message.messageType val dataElement = message.data - // A couple oddball messages respond directly to GUI, expect a different message format - // e.g. jetbrains/isOSREnabled - fun respondToWebview(content: Any) { - respond(mutableMapOf( - "done" to true, - "status" to "success", - "content" to content - )) - } - try { when (messageType) { "toggleDevTools" -> { @@ -77,12 +62,12 @@ class IdeProtocolClient( "jetbrains/isOSREnabled" -> { val isOSREnabled = ServiceManager.getService(ContinueExtensionSettings::class.java).continueState.enableOSR - respondToWebview(isOSREnabled) + respond(isOSREnabled) } "jetbrains/getColors" -> { val colors = GetTheme().getTheme(); - respondToWebview(colors) + respond(colors) } "jetbrains/onLoad" -> { @@ -92,7 +77,7 @@ class IdeProtocolClient( "vscMachineId" to getMachineUniqueID(), "vscMediaUrl" to "http://continue", ) - respondToWebview(jsonData) + respond(jsonData) } "getIdeSettings" -> { @@ -111,7 +96,7 @@ class IdeProtocolClient( val sessionInfo = authService.loadControlPlaneSessionInfo() respond(sessionInfo) } else { - authService.startAuthFlow(project) + authService.startAuthFlow(project, params.useOnboarding) respond(null) } } @@ -121,6 +106,10 @@ class IdeProtocolClient( authService.signOut() ApplicationManager.getApplication().messageBus.syncPublisher(AuthListener.TOPIC) .handleUpdatedSessionInfo(null) + + // Tell the webview that session info changed + continuePluginService.sendToWebview("didChangeControlPlaneSessionInfo", null, uuid()) + respond(null) } @@ -593,11 +582,11 @@ class IdeProtocolClient( fun sendAcceptRejectDiff(accepted: Boolean, stepIndex: Int) { - send("acceptRejectDiff", AcceptRejectDiff(accepted, stepIndex), uuid()) + continuePluginService.sendToWebview("acceptRejectDiff", AcceptRejectDiff(accepted, stepIndex), uuid()) } fun deleteAtIndex(index: Int) { - send("deleteAtIndex", DeleteAtIndex(index), uuid()) + continuePluginService.sendToWebview("deleteAtIndex", DeleteAtIndex(index), uuid()) } private fun getModelByRole( diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt index f871fc69e..87b0d6970 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt @@ -6,6 +6,7 @@ import com.github.continuedev.continueintellijextension.utils.OS import com.github.continuedev.continueintellijextension.utils.getMachineUniqueID import com.github.continuedev.continueintellijextension.utils.getOS import com.github.continuedev.continueintellijextension.utils.toUriOrNull +import com.google.gson.Gson import com.intellij.codeInsight.daemon.impl.HighlightInfo import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.util.ExecUtil @@ -31,6 +32,10 @@ import com.intellij.psi.PsiDocumentManager import com.intellij.testFramework.LightVirtualFile import com.intellij.util.containers.toArray import kotlinx.coroutines.* +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.RequestBody.Companion.toRequestBody import java.awt.Desktop import java.awt.Toolkit import java.awt.datatransfer.DataFlavor @@ -39,6 +44,7 @@ import java.io.File import java.io.FileInputStream import java.io.InputStreamReader import java.net.URI +import java.net.URL import java.nio.charset.Charset import java.nio.file.Paths @@ -85,14 +91,50 @@ class IntelliJIDE( ) } + suspend fun enableHubContinueDev(): Boolean { + try { + val client = OkHttpClient() + val url = URL("https://api.continue.dev/features/hub") + + val request = Request.Builder() + .url(url) + .get() + .header("Content-Type", "application/json") + .build() + + val response = client.newCall(request).execute() + + val responseBody = response.body?.string() + val gson = Gson() + val responseMap = gson.fromJson(responseBody, Map::class.java) + + if (responseMap["enabled"] == true) { + return true + } + } catch (e: Exception) { + return false + } + return false + } + override suspend fun getIdeSettings(): IdeSettings { val settings = service() + + var continueTestEnvironment = settings.continueState.continueTestEnvironment + if (continueTestEnvironment != "production") { + val enableHub = enableHubContinueDev() + if (enableHub) { + continueTestEnvironment = "production" + } + } + return IdeSettings( remoteConfigServerUrl = settings.continueState.remoteConfigServerUrl, remoteConfigSyncPeriod = settings.continueState.remoteConfigSyncPeriod, userToken = settings.continueState.userToken ?: "", enableControlServerBeta = settings.continueState.enableContinueTeamsBeta, + continueTestEnvironment = continueTestEnvironment, pauseCodebaseIndexOnStart = false, // TODO: Needs to be implemented ) } 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 9f314ede6..8fcaf590a 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 @@ -29,7 +29,6 @@ import java.awt.geom.AffineTransform import java.awt.geom.Path2D import java.awt.geom.RoundRectangle2D import javax.swing.* -import javax.swing.border.EmptyBorder import javax.swing.event.DocumentEvent import javax.swing.event.DocumentListener import javax.swing.event.ListDataListener @@ -73,8 +72,8 @@ fun makePanel( onReject: () -> Unit ): JPanel { val topPanel = - ShadowPanel(MigLayout("wrap 1, insets 2 ${leftInset} 2 2, gap 0!")).apply { - background = JBColor(0x20888888.toInt(), 0x20888888.toInt()) + ShadowPanel(MigLayout("wrap 1, insets 2 $leftInset 2 2, gap 0!")).apply { + background = JBColor(0x20888888, 0x20888888) isOpaque = false } @@ -374,7 +373,7 @@ class CustomPanel( val closeIcon = IconLoader.getIcon("/icons/close.svg", javaClass) return JLabel(closeIcon).apply { background = Color(0, 0, 0, 0) - border = EmptyBorder(2, 6, 2, 0) + border = JBUI.Borders.empty(2, 6, 2, 0) toolTipText = "`esc` to cancel" isOpaque = false addMouseListener( @@ -406,7 +405,7 @@ class CustomPanel( background = defaultBackground foreground = Color(128, 128, 128, 200) font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 12) - border = EmptyBorder(8, 8, 8, 8) + border = JBUI.Borders.empty(8) isOpaque = false isEditable = false cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) @@ -423,7 +422,7 @@ class CustomPanel( val component = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus) if (component is JLabel) { - component.border = EmptyBorder(4, 6, 4, 6) + component.border = JBUI.Borders.empty(4, 6) } return component } @@ -451,9 +450,9 @@ class CustomPanel( val rightButton = CustomButton("⏎ Enter") { onEnter() } .apply { - background = JBColor(0x999998.toInt(), 0x999998.toInt()) - foreground = JBColor(0xF5F5F5.toInt(), 0xF5F5F5.toInt()) - border = EmptyBorder(2, 6, 2, 6) + background = globalScheme.defaultForeground + foreground = globalScheme.defaultBackground + border = JBUI.Borders.empty(2, 6) } val rightPanel = JPanel(MigLayout("insets 0, fillx")).apply { @@ -461,7 +460,7 @@ class CustomPanel( add(rightButton, "align right") } - border = EmptyBorder(0, 0, 16, 12) + border = JBUI.Borders.empty(0, 0, 16, 12) isOpaque = false add(dropdown, "align left") @@ -477,7 +476,7 @@ class CustomPanel( val progressBar = JProgressBar().apply { isIndeterminate = true } add(progressBar, BorderLayout.CENTER) - border = BorderFactory.createEmptyBorder(0, 0, 16, 12) + border = JBUI.Borders.empty(0, 0, 16, 12) } private val subPanelC: JPanel = @@ -486,21 +485,19 @@ class CustomPanel( JLabel("Type to re-prompt").apply { foreground = Color(156, 163, 175) // text-gray-400 font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11) - border = EmptyBorder(0, 4, 0, 0) + border = JBUI.Borders.emptyLeft(4) } val leftButton = CustomButton("Reject All (${getMetaKeyLabel()}${getShiftKeyLabel()}⌫)") { onReject() } .apply { - background = JBColor(0x30FF0000.toInt(), 0x30FF0000.toInt()) - foreground = JBColor(0xF5F5F5.toInt(), 0xF5F5F5.toInt()) + background = JBColor(0x30FF0000, 0x30FF0000) } val rightButton = CustomButton("Accept All (${getMetaKeyLabel()}${getShiftKeyLabel()}⏎)") { onAccept() } .apply { - background = JBColor(0x3000FF00.toInt(), 0x3000FF00.toInt()) - foreground = JBColor(0xF5F5F5.toInt(), 0xF5F5F5.toInt()) + background = JBColor(0x3000FF00, 0x3000FF00) } val rightPanel = @@ -508,12 +505,12 @@ class CustomPanel( isOpaque = false add(leftButton, "align right") add(rightButton, "align right") - border = EmptyBorder(0, 0, 0, 0) + border = JBUI.Borders.empty() } add(leftLabel, "align left") add(rightPanel, "align right") - border = BorderFactory.createEmptyBorder(0, 0, 16, 12) + border = JBUI.Borders.empty(0, 0, 16, 12) isOpaque = false } @@ -625,7 +622,7 @@ class CustomButton(text: String, onClick: () -> Unit) : JLabel(text, CENTER) { }) font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11) - border = EmptyBorder(2, 6, 2, 6) + border = JBUI.Borders.empty(2, 6) } override fun paintComponent(g: Graphics) { @@ -694,7 +691,7 @@ class TransparentArrowButtonUI : BasicComboBoxUI() { } override fun getInsets(): Insets { - return JBUI.insets(0, 6, 0, 0) + return JBUI.insetsLeft(6) } override fun installUI(c: JComponent?) { 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 6f311c29b..e121e5687 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 @@ -13,8 +13,8 @@ import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.ui.JBColor import com.intellij.util.application +import com.intellij.util.ui.JBUI import java.awt.* -import javax.swing.BorderFactory import javax.swing.JButton import javax.swing.JTextArea import kotlin.math.min @@ -25,8 +25,8 @@ class VerticalDiffBlock( var startLine: Int, private val onAcceptReject: (VerticalDiffBlock, Boolean) -> Unit ) { - val deletedLines: MutableList = mutableListOf(); - val addedLines: MutableList = mutableListOf(); + val deletedLines: MutableList = mutableListOf() + val addedLines: MutableList = mutableListOf() private val acceptButton: JButton private val rejectButton: JButton private var deletionInlay: Disposable? = null @@ -155,10 +155,10 @@ class VerticalDiffBlock( val rejectBtn = createButton( "${getAltKeyLabel()}${getShiftKeyLabel()}N", - JBColor(0x99FF0000.toInt(), 0x99FF0000.toInt()) + JBColor(0x77FF0000, 0x77FF0000) ).apply { addActionListener { - handleReject(); + handleReject() onAcceptReject(this@VerticalDiffBlock, false) } @@ -168,10 +168,10 @@ class VerticalDiffBlock( createButton( "${getAltKeyLabel()}${ getShiftKeyLabel() - }Y", JBColor(0x7700BB00.toInt(), 0x7700BB00.toInt()) + }Y", JBColor(0x7700BB00, 0x7700BB00) ).apply { addActionListener { - handleAccept(); + handleAccept() onAcceptReject(this@VerticalDiffBlock, true) } } @@ -215,9 +215,9 @@ class VerticalDiffBlock( private fun createDeletionTextArea(text: String) = JTextArea(text).apply { isEditable = false - background = JBColor(0x30FF0000.toInt(), 0x30FF0000.toInt()) + background = JBColor(0x30FF0000, 0x30FF0000) foreground = JBColor.GRAY - border = BorderFactory.createEmptyBorder() + border = JBUI.Borders.empty() lineWrap = false wrapStyleWord = false font = editor.colorsScheme.getFont(EditorFontType.PLAIN) @@ -250,7 +250,7 @@ class VerticalDiffBlock( font = Font("Arial", Font.BOLD, 9) isContentAreaFilled = false isOpaque = false - border = BorderFactory.createEmptyBorder(4, 2, 4, 2) + border = JBUI.Borders.empty(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/protocol/ide.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt index 4aa433f52..5ce49e80a 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt @@ -2,7 +2,7 @@ package com.github.continuedev.continueintellijextension.protocol import com.github.continuedev.continueintellijextension.* -data class GetControlPlaneSessionInfoParams(val silent: Boolean) +data class GetControlPlaneSessionInfoParams(val silent: Boolean, val useOnboarding: Boolean) data class WriteFileParams( val path: String, diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt index ce548e5f5..9e3d00d23 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt @@ -2,6 +2,7 @@ package com.github.continuedev.continueintellijextension.services import com.github.continuedev.continueintellijextension.constants.getConfigJsPath import com.github.continuedev.continueintellijextension.constants.getConfigJsonPath +import com.intellij.execution.target.value.constant import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.* @@ -33,6 +34,7 @@ class ContinueSettingsComponent : DumbAware { val enableOSR: JCheckBox = JCheckBox("Enable Off-Screen Rendering") val displayEditorTooltip: JCheckBox = JCheckBox("Display Editor Tooltip") val showIDECompletionSideBySide: JCheckBox = JCheckBox("Show IDE completions side-by-side") + val enableContinueHub: JCheckBox = JCheckBox("Enable Continue Hub") init { val constraints = GridBagConstraints() @@ -66,6 +68,8 @@ class ContinueSettingsComponent : DumbAware { constraints.gridy++ panel.add(showIDECompletionSideBySide, constraints) constraints.gridy++ + panel.add(enableContinueHub, constraints) + constraints.gridy++ // Add a "filler" component that takes up all remaining vertical space constraints.weighty = 1.0 @@ -98,6 +102,7 @@ open class ContinueExtensionSettings : PersistentStateComponent - - - - - diff --git a/extensions/intellij/src/main/resources/continue_tutorial.java b/extensions/intellij/src/main/resources/continue_tutorial.java index 41ac854c0..e566b14ce 100644 --- a/extensions/intellij/src/main/resources/continue_tutorial.java +++ b/extensions/intellij/src/main/resources/continue_tutorial.java @@ -1,17 +1,24 @@ -/* _________ _____ _____ - __ ____/______ _______ __ /____(_)_______ ____ _______ - _ / _ __ \__ __ \_ __/__ / __ __ \_ / / /_ _ \ - / /___ / /_/ /_ / / // /_ _ / _ / / // /_/ / / __/ - \____/ \____/ /_/ /_/ \__/ /_/ /_/ /_/ \__,_/ \___/ +// _________ _____ _____ +// __ ____/______ _______ __ /____(_)_______ ____ _______ +// _ / _ __ \__ __ \_ __/__ / __ __ \_ / / /_ _ \ +// / /___ / /_/ /_ / / // /_ _ / _ / / // /_/ / / __/ +// \____/ \____/ /_/ /_/ \__/ /_/ /_/ /_/ \__,_/ \___/ +// +// Chat, Edit, and Autocomplete tutorial +// - Chat, Edit, and Autocomplete tutorial -*/ +// ———————————————————————————————————————————————— Setup ————————————————————————————————————————————————- +// First, open the Continue sidebar by pressing [Cmd + L] or clicking the Continue icon. -/* ————————————————————————————————————————————————— Chat ————————————————————————————————————————————————— */ +// See an example at https://docs.continue.dev/getting-started/install + +// Follow the instructions in the sidebar to set up a Chat/Edit modela and an Autocomplete model. + +// ————————————————————————————————————————————————— Chat ————————————————————————————————————————————————— // Highlight the code below -// Press [Cmd/Ctrl + J] to add to Chat +// Press [Cmd + L] 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++) { @@ -26,10 +33,13 @@ public static int[] sortingAlgorithm(int[] x) { return x; } -/* ————————————————————————————————————————————————— Edit ————————————————————————————————————————————————— */ +// [Cmd + L] always starts a new chat. Now, try the same thing using [Cmd + Shift + L]. +// This will add the code into the current chat + +// ————————————————————————————————————————————————— Edit ————————————————————————————————————————————————— // Highlight the code below -// Press [Cmd/Ctrl + I] to Edit +// Press [Cmd + 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++) { @@ -44,12 +54,15 @@ public static int[] sortingAlgorithm2(int[] x) { return x; } -/* ————————————————————————————————————————————— Autocomplete —————————————————————————————————————————————— */ +// ————————————————————————————————————————————— Autocomplete —————————————————————————————————————————————— -// Place cursor after `sortingAlgorithm...` below and press [Enter] +// Place cursor after `sortingAlgorithm:` below and press [Enter] // Press [Tab] to accept the Autocomplete suggestion -// Basic assertion for sortingAlgorithm... +// Basic assertion for sortingAlgorithm: -/* —————————————————— Learn more at https://docs.continue.dev/getting-started/overview ——————————————————— */ + +// —————————————————————————————————————————————- Learn More -—————————————————————————————————————————————— + +// Visit the Continue Docs 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 16a297c16..4670772df 100644 --- a/extensions/intellij/src/main/resources/continue_tutorial.py +++ b/extensions/intellij/src/main/resources/continue_tutorial.py @@ -7,11 +7,18 @@ Chat, Edit, and Autocomplete tutorial """ +# ———————————————————————————————————————————————— Setup ————————————————————————————————————————————————- -# ————————————————————————————————————————————————— Chat ————————————————————————————————————————————————— # +# First, open the Continue sidebar by pressing [Cmd + L] or clicking the Continue icon. + +# See an example at https://docs.continue.dev/getting-started/install + +# Follow the instructions in the sidebar to set up a Chat/Edit modela and an Autocomplete model. + +# ————————————————————————————————————————————————— Chat ————————————————————————————————————————————————— ## Highlight the code below -## Press [Cmd/Ctrl + J] to add to Chat +## Press [Cmd + L] to add to Chat ## Try asking Continue "what sorting algorithm is this?" def sorting_algorithm(x): for i in range(len(x)): @@ -20,11 +27,13 @@ def sorting_algorithm(x): x[j], x[j + 1] = x[j + 1], x[j] return x +# [Cmd + L] always starts a new chat. Now, try the same thing using [Cmd + Shift + L]. +# This will add the code into the current chat -# ————————————————————————————————————————————————— Edit ————————————————————————————————————————————————— # +# ————————————————————————————————————————————————— Edit ————————————————————————————————————————————————— ## Highlight the code below -## Press [Cmd/Ctrl + I] to Edit +## Press [Cmd + I] to Edit ## Try asking Continue to "make this more readable" def sorting_algorithm(x): for i in range(len(x)): @@ -33,12 +42,16 @@ def sorting_algorithm(x): x[j], x[j + 1] = x[j + 1], x[j] return x -# ————————————————————————————————————————————— Autocomplete —————————————————————————————————————————————— # +# ————————————————————————————————————————————— Autocomplete —————————————————————————————————————————————— -## Place cursor after `sorting_algorithm...` below and press [Enter] +## Place cursor after `sorting_algorithm:` below and press [Enter] ## Press [Tab] to accept the Autocomplete suggestion -# Basic assertion for sorting_algorithm... +# Basic assertion for sorting_algorithm: -# —————————————————— Learn more at https://docs.continue.dev/getting-started/overview ——————————————————— # + + +# —————————————————————————————————————————————- Learn More -—————————————————————————————————————————————— + +# Visit the Continue Docs 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 index 301fc248c..4cde323ca 100644 --- a/extensions/intellij/src/main/resources/continue_tutorial.ts +++ b/extensions/intellij/src/main/resources/continue_tutorial.ts @@ -1,17 +1,24 @@ -/* _________ _____ _____ - __ ____/______ _______ __ /____(_)_______ ____ _______ - _ / _ __ \__ __ \_ __/__ / __ __ \_ / / /_ _ \ - / /___ / /_/ /_ / / // /_ _ / _ / / // /_/ / / __/ - \____/ \____/ /_/ /_/ \__/ /_/ /_/ /_/ \__,_/ \___/ +// _________ _____ _____ +// __ ____/______ _______ __ /____(_)_______ ____ _______ +// _ / _ __ \__ __ \_ __/__ / __ __ \_ / / /_ _ \ +// / /___ / /_/ /_ / / // /_ _ / _ / / // /_/ / / __/ +// \____/ \____/ /_/ /_/ \__/ /_/ /_/ /_/ \__,_/ \___/ +// +// Chat, Edit, and Autocomplete tutorial +// - Chat, Edit, and Autocomplete tutorial -*/ +// ———————————————————————————————————————————————— Setup ————————————————————————————————————————————————- +// First, open the Continue sidebar by pressing [Cmd + L] or clicking the Continue icon. -/* ————————————————————————————————————————————————— Chat ————————————————————————————————————————————————— */ +// See an example at https://docs.continue.dev/getting-started/install + +// Follow the instructions in the sidebar to set up a Chat/Edit modela and an Autocomplete model. + +// ————————————————————————————————————————————————— Chat ————————————————————————————————————————————————— // Highlight the code below -// Press [Cmd/Ctrl + J] to add to Chat +// Press [Cmd + L] 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++) { @@ -26,10 +33,13 @@ function sortingAlgorithm(x: number[]): number[] { return x; } -/* ————————————————————————————————————————————————— Edit ————————————————————————————————————————————————— */ +// [Cmd + L] always starts a new chat. Now, try the same thing using [Cmd + Shift + L]. +// This will add the code into the current chat + +// ————————————————————————————————————————————————— Edit ————————————————————————————————————————————————— // Highlight the code below -// Press [Cmd/Ctrl + I] to Edit +// Press [Cmd + I] to Edit // Try asking Continue to "make this more readable" function sortingAlgorithm2(x: number[]): number[] { for (let i = 0; i < x.length; i++) { @@ -44,12 +54,13 @@ function sortingAlgorithm2(x: number[]): number[] { return x; } -/* ————————————————————————————————————————————— Autocomplete —————————————————————————————————————————————— */ +// ————————————————————————————————————————————— Autocomplete —————————————————————————————————————————————— -// Place cursor after `sortingAlgorithm...` below and press [Enter] +// Place cursor after `sortingAlgorithm:` below and press [Enter] // Press [Tab] to accept the Autocomplete suggestion -// Basic assertion for sortingAlgorithm... +// Basic assertion for sortingAlgorithm: +// —————————————————————————————————————————————- Learn More -—————————————————————————————————————————————— -/* —————————————————— Learn more at https://docs.continue.dev/getting-started/overview ——————————————————— */ +// Visit the Continue Docs at https://docs.continue.dev/getting-started/overview diff --git a/extensions/vscode/.gitignore b/extensions/vscode/.gitignore index 05afd11d4..29ad0b023 100644 --- a/extensions/vscode/.gitignore +++ b/extensions/vscode/.gitignore @@ -11,7 +11,6 @@ bin assets gui/** -!gui/onigasm.wasm .devcontainer .github diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 2b12cf21e..259d3e7c8 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -440,6 +440,10 @@ "uploadImage": { "type": "boolean", "description": "Indicates whether the model can upload images." + }, + "tools": { + "type": "boolean", + "description": "Indicates whether the model can use tools" } } } @@ -936,7 +940,8 @@ "gemini-1.5-flash-latest", "gemini-1.5-flash", "gemini-1.5-flash-8b", - "gemini-2.0-flash-exp" + "gemini-2.0-flash-exp", + "gemini-2.0-flash" ] } } @@ -998,6 +1003,8 @@ "anyOf": [ { "enum": [ + "deepseek-r1", + "deepseek_v3", "llama3-8b", "llama3-70b", "llama3.1-8b", @@ -1680,33 +1687,6 @@ } ] }, - "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", diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 816822f52..57f283f76 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.259", + "version": "0.9.268", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.259", + "version": "0.9.268", "license": "Apache-2.0", "dependencies": { "@continuedev/fetch": "^1.0.3", @@ -22,7 +22,7 @@ "dbinfoz": "^0.14.0", "diff": "^7.0.0", "downshift": "^7.6.0", - "esbuild": "^0.17.19", + "esbuild": "0.17.19", "express": "^4.18.2", "fkill": "^8.1.0", "follow-redirects": "^1.15.4", @@ -50,7 +50,7 @@ "socket.io-client": "^4.7.2", "strip-ansi": "^7.1.0", "svg-builder": "^2.0.0", - "systeminformation": "^5.22.10", + "systeminformation": "^5.23.7", "tailwindcss": "^3.3.2", "undici": "^6.2.0", "uuid": "^9.0.1", @@ -106,11 +106,11 @@ "@aws-sdk/client-sagemaker-runtime": "^3.621.0", "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.23", + "@continuedev/config-yaml": "^1.0.31", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", "@continuedev/openai-adapters": "^1.0.10", - "@modelcontextprotocol/sdk": "^1.0.0", + "@modelcontextprotocol/sdk": "^1.5.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", "@typescript-eslint/eslint-plugin": "^7.8.0", @@ -5735,9 +5735,10 @@ "integrity": "sha512-dX7e/LHVJ6W3DE1MHWi9S1EYzDESENfLrYohG2G++ovZrYOkm4Knwa0mc1cn84xJOR4KEU0WSchhLbd0UklbHw==" }, "node_modules/express": { - "version": "4.21.1", - "resolved": "https://registry.npmjs.org/express/-/express-4.21.1.tgz", - "integrity": "sha512-YSFlK1Ee0/GC8QaO91tHcDxJiE/X4FbpAyQWkxAvG6AXCuR65YzK8ua6D9hvi/TzUfZMpc+BwuM1IPw8fmQBiQ==", + "version": "4.21.2", + "resolved": "https://registry.npmjs.org/express/-/express-4.21.2.tgz", + "integrity": "sha512-28HqgMZAmih1Czt9ny7qr6ek2qddF4FclbMzwhCREB6OFfH+rXAnuNCwo1/wFvrtbgsQDb4kSbX9de9lFbrXnA==", + "license": "MIT", "dependencies": { "accepts": "~1.3.8", "array-flatten": "1.1.1", @@ -5758,7 +5759,7 @@ "methods": "~1.1.2", "on-finished": "2.4.1", "parseurl": "~1.3.3", - "path-to-regexp": "0.1.10", + "path-to-regexp": "0.1.12", "proxy-addr": "~2.0.7", "qs": "6.13.0", "range-parser": "~1.2.1", @@ -5773,6 +5774,10 @@ }, "engines": { "node": ">= 0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, "node_modules/express/node_modules/debug": { @@ -9098,15 +9103,16 @@ } }, "node_modules/nanoid": { - "version": "3.3.7", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.7.tgz", - "integrity": "sha512-eSRppjcPIatRIMC1U6UngP8XFcz8MQWGQdt1MTBQ7NaAmvXDfvNxbvWV3x2y6CdEUciCSsDHDQZbhYaB8QEo2g==", + "version": "3.3.8", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.8.tgz", + "integrity": "sha512-WNLf5Sd8oZxOm+TzppcYk8gVOgP+l58xNy58D0nbUnOxOWRWvlcCV4kUF7ltmI6PsrLl/BgKEyS4mqsGChFN0w==", "funding": [ { "type": "github", "url": "https://github.com/sponsors/ai" } ], + "license": "MIT", "bin": { "nanoid": "bin/nanoid.cjs" }, @@ -10059,9 +10065,10 @@ } }, "node_modules/path-to-regexp": { - "version": "0.1.10", - "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.10.tgz", - "integrity": "sha512-7lf7qcQidTku0Gu3YDPc8DJ1q7OOucfa/BSsIwjuh56VU7katFvuM8hULfkwB3Fns/rsVF7PwPKVw1sl5KQS9w==" + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.12.tgz", + "integrity": "sha512-RA1GjUVMnvYFxuqovrEqZoxxW5NUZqbwKtYz/Tt7nXerk0LbLblQmrsgdeOxV5SFHf0UDggjS/bSeOZwt1pmEQ==", + "license": "MIT" }, "node_modules/path-type": { "version": "4.0.0", @@ -12168,9 +12175,10 @@ } }, "node_modules/systeminformation": { - "version": "5.23.5", - "resolved": "https://registry.npmjs.org/systeminformation/-/systeminformation-5.23.5.tgz", - "integrity": "sha512-PEpJwhRYxZgBCAlWZhWIgfMTjXLqfcaZ1pJsJn9snWNfBW/Z1YQg1mbIUSWrEV3ErAHF7l/OoVLQeaZDlPzkpA==", + "version": "5.25.11", + "resolved": "https://registry.npmjs.org/systeminformation/-/systeminformation-5.25.11.tgz", + "integrity": "sha512-jI01fn/t47rrLTQB0FTlMCC+5dYx8o0RRF+R4BPiUNsvg5OdY0s9DKMFmJGrx5SwMZQ4cag0Gl6v8oycso9b/g==", + "license": "MIT", "os": [ "darwin", "linux", @@ -12911,9 +12919,10 @@ "dev": true }, "node_modules/undici": { - "version": "6.20.1", - "resolved": "https://registry.npmjs.org/undici/-/undici-6.20.1.tgz", - "integrity": "sha512-AjQF1QsmqfJys+LXfGTNum+qw4S88CojRInG/6t31W/1fk6G59s92bnAvGz5Cmur+kQv2SURXEvvudLmbrE8QA==", + "version": "6.21.1", + "resolved": "https://registry.npmjs.org/undici/-/undici-6.21.1.tgz", + "integrity": "sha512-q/1rj5D0/zayJB2FraXdaWxbhWiNKDvu8naDT2dl1yTlvJp4BLtOcp2a5BvgGNQpYYJzau7tf1WgKv3b+7mqpQ==", + "license": "MIT", "engines": { "node": ">=18.17" } @@ -13309,10 +13318,11 @@ } }, "node_modules/vite": { - "version": "4.5.5", - "resolved": "https://registry.npmjs.org/vite/-/vite-4.5.5.tgz", - "integrity": "sha512-ifW3Lb2sMdX+WU91s3R0FyQlAyLxOzCSCP37ujw0+r5POeHPwe6udWVIElKQq8gk3t7b8rkmvqC6IHBpCff4GQ==", + "version": "4.5.9", + "resolved": "https://registry.npmjs.org/vite/-/vite-4.5.9.tgz", + "integrity": "sha512-qK9W4xjgD3gXbC0NmdNFFnVFLMWSNiR3swj957yutwzzN16xF/E7nmtAyp1rT9hviDroQANjE4HK3H4WqWdFtw==", "dev": true, + "license": "MIT", "dependencies": { "esbuild": "^0.18.10", "postcss": "^8.4.27", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index c688eda3f..a25aecbd5 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.259", + "version": "0.9.269", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" @@ -94,7 +94,7 @@ "continue.enableContinueForTeams": { "type": "boolean", "default": false, - "markdownDescription": "Enable Continue for teams beta features. To sign in, click the person icon in the bottom right of the sidebar." + "markdownDescription": "Enable Continue for teams beta features. To sign in, click the gear icon to go to the settings page, and click Sign In." }, "continue.enableContinueHub": { "type": "boolean", @@ -213,14 +213,14 @@ { "command": "continue.toggleFullScreen", "category": "Continue", - "title": "Toggle Full Screen", + "title": "Open in new window", "icon": "$(link-external)", "group": "Continue" }, { "command": "continue.openConfigPage", "category": "Continue", - "title": "Open Continue Config", + "title": "Open Settings", "icon": "$(gear)", "group": "Continue" }, @@ -328,20 +328,6 @@ "category": "Continue", "title": "Focus Continue Chat", "group": "Continue" - }, - { - "command": "continue.signInToControlPlane", - "title": "Sign In", - "category": "Continue", - "group": "Continue", - "icon": "$(account)" - }, - { - "command": "continue.openAccountDialog", - "title": "Account", - "category": "Continue", - "group": "Continue", - "icon": "$(account)" } ], "keybindings": [ @@ -531,16 +517,6 @@ "group": "navigation@4", "when": "view == continue.continueGUIView" }, - { - "command": "continue.signInToControlPlane", - "group": "navigation@5", - "when": "(view == continue.continueGUIView) && (config.continue.enableContinueForTeams || config.continue.enableContinueHub) && !continue.isSignedInToControlPlane" - }, - { - "command": "continue.openAccountDialog", - "group": "navigation@5", - "when": "(view == continue.continueGUIView) && (config.continue.enableContinueForTeams || config.continue.enableContinueHub) && continue.isSignedInToControlPlane" - }, { "command": "continue.openMorePage", "group": "navigation@6", @@ -580,7 +556,8 @@ { "type": "webview", "id": "continue.continueGUIView", - "name": "", + "name": "Continue", + "icon": "media/sidebar-icon.png", "visibility": "visible" } ] @@ -623,7 +600,7 @@ "e2e:build": "npm --prefix ../../gui run build && npm run package", "e2e:create-storage": "mkdir -p ./e2e/storage", "e2e:get-chromedriver": "extest get-chromedriver --storage ./e2e/storage", - "e2e:get-vscode": "extest get-vscode --storage ./e2e/storage", + "e2e:get-vscode": "CODE_VERSION=\"1.95.0\" extest get-vscode --storage ./e2e/storage", "e2e:sign-vscode": "codesign --entitlements entitlements.plist --deep --force -s - './e2e/storage/Visual Studio Code.app'", "e2e:copy-vsix": "chmod +x ./e2e/get-latest-vsix.sh && bash ./e2e/get-latest-vsix.sh", "e2e:install-vsix": "extest install-vsix -f ./e2e/vsix/continue.vsix --extensions_dir ./e2e/.test-extensions --storage ./e2e/storage", @@ -682,7 +659,7 @@ "dbinfoz": "^0.14.0", "diff": "^7.0.0", "downshift": "^7.6.0", - "esbuild": "^0.17.19", + "esbuild": "0.17.19", "express": "^4.18.2", "fkill": "^8.1.0", "follow-redirects": "^1.15.4", @@ -710,7 +687,7 @@ "socket.io-client": "^4.7.2", "strip-ansi": "^7.1.0", "svg-builder": "^2.0.0", - "systeminformation": "^5.22.10", + "systeminformation": "^5.23.7", "tailwindcss": "^3.3.2", "undici": "^6.2.0", "uuid": "^9.0.1", diff --git a/extensions/vscode/scripts/prepackage.js b/extensions/vscode/scripts/prepackage.js index 4f3650ff0..aeab677ca 100644 --- a/extensions/vscode/scripts/prepackage.js +++ b/extensions/vscode/scripts/prepackage.js @@ -1,12 +1,15 @@ const fs = require("fs"); -const ncp = require("ncp").ncp; const path = require("path"); + +const ncp = require("ncp").ncp; const { rimrafSync } = require("rimraf"); + const { validateFilesPresent, execCmdSync, autodetectPlatformAndArch, } = require("../../../scripts/util/index"); + const { copyConfigSchema } = require("./utils"); // Clear folders that will be packaged to ensure clean slate @@ -46,6 +49,17 @@ console.log("[info] Using target: ", target); const exe = os === "win32" ? ".exe" : ""; +const isInGitHubAction = !!process.env.GITHUB_ACTIONS; + +const isArmTarget = + target === "darwin-arm64" || + target === "linux-arm64" || + target === "win32-arm64"; + +const isWinTarget = target?.startsWith("win"); +const isLinuxTarget = target?.startsWith("linux"); +const isMacTarget = target?.startsWith("darwin"); + (async () => { console.log("[info] Packaging extension for target ", target); @@ -66,7 +80,7 @@ const exe = os === "win32" ? ".exe" : ""; execCmdSync("npm install"); console.log("[info] npm install in gui completed"); - if (ghAction()) { + if (isInGitHubAction) { execCmdSync("npm run build"); } @@ -106,12 +120,6 @@ const exe = os === "win32" ? ".exe" : ""; fs.copyFileSync("tmp_index.html", indexHtmlPath); fs.unlinkSync("tmp_index.html"); - // Copy over other misc. files - fs.copyFileSync( - "../extensions/vscode/gui/onigasm.wasm", - path.join(intellijExtensionWebviewPath, "onigasm.wasm"), - ); - console.log("[info] Copied gui build to JetBrains extension"); // Then copy over the dist folder to the VSCode extension // @@ -222,7 +230,7 @@ const exe = os === "win32" ? ".exe" : ""; "../../../core/llm/llamaTokenizerWorkerPool.mjs", "../../../core/llm/llamaTokenizer.mjs", "../../../core/llm/tiktokenWorkerPool.mjs", - "../../../core/util/start_ollama.sh" + "../../../core/util/start_ollama.sh", ]; for (const f of filesToCopy) { @@ -262,22 +270,6 @@ const exe = os === "win32" ? ".exe" : ""; ); }); - function ghAction() { - return !!process.env.GITHUB_ACTIONS; - } - - function isArm() { - return ( - target === "darwin-arm64" || - target === "linux-arm64" || - target === "win32-arm64" - ); - } - - function isWin() { - return target?.startsWith("win"); - } - async function installNodeModuleInTempDirAndCopyToCurrent( packageName, toCopy, @@ -341,42 +333,40 @@ const exe = os === "win32" ? ".exe" : ""; } // GitHub Actions doesn't support ARM, so we need to download pre-saved binaries - if (ghAction() && isArm()) { - // sqlite3 - if (!isWin()) { - // Neither lancedb nor sqlite3 have pre-built windows arm64 binaries + // 02/07/25 - the above comment is out of date, there is now support for ARM runners on GitHub Actions + if (isInGitHubAction && isArmTarget) { + // lancedb binary + const packageToInstall = { + "darwin-arm64": "@lancedb/vectordb-darwin-arm64", + "linux-arm64": "@lancedb/vectordb-linux-arm64-gnu", + "win32-arm64": "@lancedb/vectordb-win32-arm64-msvc", + }[target]; + console.log( + "[info] Downloading pre-built lancedb binary: " + packageToInstall, + ); - // lancedb binary - const packageToInstall = { - "darwin-arm64": "@lancedb/vectordb-darwin-arm64", - "linux-arm64": "@lancedb/vectordb-linux-arm64-gnu", - }[target]; - console.log( - "[info] Downloading pre-built lancedb binary: " + packageToInstall, - ); + await installNodeModuleInTempDirAndCopyToCurrent( + packageToInstall, + "@lancedb", + ); - await installNodeModuleInTempDirAndCopyToCurrent( - packageToInstall, - "@lancedb", - ); - - // Replace the installed with pre-built - console.log("[info] Downloading pre-built sqlite3 binary"); - rimrafSync("../../core/node_modules/sqlite3/build"); - const downloadUrl = { - "darwin-arm64": - "https://github.com/TryGhost/node-sqlite3/releases/download/v5.1.7/sqlite3-v5.1.7-napi-v6-darwin-arm64.tar.gz", - "linux-arm64": - "https://github.com/TryGhost/node-sqlite3/releases/download/v5.1.7/sqlite3-v5.1.7-napi-v3-linux-arm64.tar.gz", - }[target]; - execCmdSync( - `curl -L -o ../../core/node_modules/sqlite3/build.tar.gz ${downloadUrl}`, - ); - execCmdSync( - "cd ../../core/node_modules/sqlite3 && tar -xvzf build.tar.gz", - ); - fs.unlinkSync("../../core/node_modules/sqlite3/build.tar.gz"); - } + // Replace the installed with pre-built + console.log("[info] Downloading pre-built sqlite3 binary"); + rimrafSync("../../core/node_modules/sqlite3/build"); + const downloadUrl = { + "darwin-arm64": + "https://github.com/TryGhost/node-sqlite3/releases/download/v5.1.7/sqlite3-v5.1.7-napi-v6-darwin-arm64.tar.gz", + "linux-arm64": + "https://github.com/TryGhost/node-sqlite3/releases/download/v5.1.7/sqlite3-v5.1.7-napi-v3-linux-arm64.tar.gz", + // node-sqlite3 doesn't have a pre-built binary for win32-arm64 + "win32-arm64": + "https://continue-server-binaries.s3.us-west-1.amazonaws.com/win32-arm64/node_sqlite3.tar.gz", + }[target]; + execCmdSync( + `curl -L -o ../../core/node_modules/sqlite3/build.tar.gz ${downloadUrl}`, + ); + execCmdSync("cd ../../core/node_modules/sqlite3 && tar -xvzf build.tar.gz"); + fs.unlinkSync("../../core/node_modules/sqlite3/build.tar.gz"); // Download and unzip esbuild console.log("[info] Downloading pre-built esbuild binary"); @@ -483,9 +473,9 @@ const exe = os === "win32" ? ".exe" : ""; // onnx runtime bindngs `bin/napi-v3/${os}/${arch}/onnxruntime_binding.node`, `bin/napi-v3/${os}/${arch}/${ - os === "darwin" + isMacTarget ? "libonnxruntime.1.14.0.dylib" - : os === "linux" + : isLinuxTarget ? "libonnxruntime.so.1.14.0" : "onnxruntime.dll" }`, @@ -528,11 +518,7 @@ const exe = os === "win32" ? ".exe" : ""; ? "win32-x64/esbuild.exe" : `${target}/bin/esbuild` }`, - `out/node_modules/@lancedb/vectordb-${ - os === "win32" - ? "win32-x64-msvc" - : `${target}${os === "linux" ? "-gnu" : ""}` - }/index.node`, + `out/node_modules/@lancedb/vectordb-${target}${isWinTarget ? "-msvc" : ""}${isLinuxTarget ? "-gnu" : ""}/index.node`, `out/node_modules/esbuild/lib/main.js`, `out/node_modules/esbuild/bin/esbuild`, ]); diff --git a/extensions/vscode/scripts/utils.js b/extensions/vscode/scripts/utils.js index 4f9ce187c..2254bb1f3 100644 --- a/extensions/vscode/scripts/utils.js +++ b/extensions/vscode/scripts/utils.js @@ -18,8 +18,10 @@ function copyConfigSchema() { enum: ["merge", "overwrite"], default: "merge", title: "Merge behavior", - markdownDescription: "If set to 'merge', .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.", - "x-intellij-html-description": "

If set to merge, .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.

" + markdownDescription: + "If set to 'merge', .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.", + "x-intellij-html-description": + "

If set to merge, .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.

", }; fs.writeFileSync("continue_rc_schema.json", JSON.stringify(schema, null, 2)); @@ -123,12 +125,6 @@ async function buildGui(isGhAction) { fs.copyFileSync("tmp_index.html", indexHtmlPath); fs.unlinkSync("tmp_index.html"); - // Copy over other misc. files - fs.copyFileSync( - "../extensions/vscode/gui/onigasm.wasm", - path.join(intellijExtensionWebviewPath, "onigasm.wasm"), - ); - console.log("[info] Copied gui build to JetBrains extension"); // Then copy over the dist folder to the VSCode extension // @@ -539,5 +535,5 @@ module.exports = { downloadSqliteBinary, downloadRipgrepBinary, copyTokenizers, - copyScripts + copyScripts, }; diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index 7f9f561f6..f4323a18c 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -2,7 +2,7 @@ import * as child_process from "node:child_process"; import { exec } from "node:child_process"; import { Range } from "core"; -import { EXTENSION_NAME } from "core/control-plane/env"; +import { enableHubContinueDev, EXTENSION_NAME } from "core/control-plane/env"; import { GetGhTokenArgs } from "core/protocol/ide"; import { editConfigJson, getConfigJsonPath } from "core/util/paths"; import * as vscode from "vscode"; @@ -33,6 +33,7 @@ import { SecretStorage } from "./stubs/SecretStorage"; class VsCodeIde implements IDE { ideUtils: VsCodeIdeUtils; secretStorage: SecretStorage; + private lastFileSaveTimestamp: number = Date.now(); constructor( private readonly vscodeWebviewProtocolPromise: Promise, @@ -42,6 +43,14 @@ class VsCodeIde implements IDE { this.secretStorage = new SecretStorage(context); } + public updateLastFileSaveTimestamp(): void { + this.lastFileSaveTimestamp = Date.now(); + } + + public getLastFileSaveTimestamp(): number { + return this.lastFileSaveTimestamp; + } + async readSecrets(keys: string[]): Promise> { const secretValuePromises = keys.map((key) => this.secretStorage.get(key)); const secretValues = await Promise.all(secretValuePromises); @@ -619,7 +628,7 @@ class VsCodeIde implements IDE { return vscode.workspace.fs.readDirectory(vscode.Uri.parse(dir)) as any; } - getIdeSettingsSync(): IdeSettings { + private getIdeSettingsSync(): IdeSettings { const settings = vscode.workspace.getConfiguration(EXTENSION_NAME); const remoteConfigServerUrl = settings.get( "remoteConfigServerUrl", @@ -652,7 +661,17 @@ class VsCodeIde implements IDE { } async getIdeSettings(): Promise { - return this.getIdeSettingsSync(); + const ideSettings = this.getIdeSettingsSync(); + + // Feature flag for when hub is enabled + if (ideSettings.continueTestEnvironment !== "production") { + const enableHub = await enableHubContinueDev(); + if (enableHub) { + ideSettings.continueTestEnvironment = "production"; + } + } + + return ideSettings; } } diff --git a/extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts b/extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts index 2dba327ef..a20e88ac3 100644 --- a/extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts +++ b/extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts @@ -16,10 +16,10 @@ export class RecentlyVisitedRangesService { Array >; // Default value, we override in initWithPostHog - private numSurroundingLines = 5; + private numSurroundingLines = 20; private maxRecentFiles = 3; private maxSnippetsPerFile = 3; - private isEnabled = false; + private isEnabled = true; constructor(private readonly ide: IDE) { this.cache = new LRUCache< @@ -38,12 +38,11 @@ export class RecentlyVisitedRangesService { PosthogFeatureFlag.RecentlyVisitedRangesNumSurroundingLines, ); - if (!recentlyVisitedRangesNumSurroundingLines) { - return; + if (recentlyVisitedRangesNumSurroundingLines) { + this.isEnabled = true; + this.numSurroundingLines = recentlyVisitedRangesNumSurroundingLines; } - this.isEnabled = true; - this.numSurroundingLines = recentlyVisitedRangesNumSurroundingLines; vscode.window.onDidChangeTextEditorSelection( this.cacheCurrentSelectionContext, ); @@ -114,7 +113,10 @@ export class RecentlyVisitedRangesService { } return allSnippets - .filter((s) => !currentFilepath || s.filepath !== currentFilepath) + .filter((s) => !currentFilepath || (s.filepath !== currentFilepath && + // Exclude Continue's own output as it makes it super-hard for users to test the autocomplete feature + // while looking at the prompts in the Continue's output + !s.filepath.startsWith("output:extension-output-Continue.continue"))) .sort((a, b) => b.timestamp - a.timestamp) .map(({ timestamp, ...snippet }) => snippet); } diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index c10d4d5f1..fb174b53c 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -41,14 +41,13 @@ interface VsCodeCompletionInput { } export class ContinueCompletionProvider - implements vscode.InlineCompletionItemProvider -{ + implements vscode.InlineCompletionItemProvider { private onError(e: any) { - const options = ["Documentation"]; + let options = ["Documentation"]; if (e.message.includes("Ollama may not be installed")) { options.push("Download Ollama"); } else if (e.message.includes("Ollama may not be running")) { - options.unshift("Start Ollama"); // We want "Start" to be the default choice + options = ["Start Ollama"]; // We want "Start" to be the only choice } if (e.message.includes("Please sign in with GitHub")) { @@ -70,7 +69,7 @@ export class ContinueCompletionProvider ); } else if (val === "Download Ollama") { vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai/download")); - } else if (val == "Start Ollama") { + } else if (val === "Start Ollama") { startLocalOllama(this.ide); } }); @@ -304,7 +303,7 @@ export class ContinueCompletionProvider } else { // If the first part of the diff isn't an insertion, then the model is // probably rewriting other parts of the line - return undefined; + // return undefined; - Let's assume it's simply an insertion } } } else { diff --git a/extensions/vscode/src/autocomplete/lsp.ts b/extensions/vscode/src/autocomplete/lsp.ts index 6d3b27543..5a56925cc 100644 --- a/extensions/vscode/src/autocomplete/lsp.ts +++ b/extensions/vscode/src/autocomplete/lsp.ts @@ -33,7 +33,7 @@ function gotoInputKey(input: GotoInput) { return `${input.name}${input.uri.toString()}${input.line}${input.character}`; } -const MAX_CACHE_SIZE = 50; +const MAX_CACHE_SIZE = 500; const gotoCache = new Map(); export async function executeGotoProvider( @@ -151,28 +151,32 @@ async function crawlTypes( identifierNodes.forEach((node) => searchedLabels.add(node.text)); // Use LSP to get the definitions of those types - const definitions = await Promise.all( - identifierNodes.map(async (node) => { - const [typeDef] = await executeGotoProvider({ - uri: vscode.Uri.parse(rif.filepath), - // TODO: tree-sitter is zero-indexed, but there seems to be an off-by-one - // error at least with the .ts parser sometimes - line: - rif.range.start.line + - Math.min(node.startPosition.row, astLineCount - 1), - character: rif.range.start.character + node.startPosition.column, - name: "vscode.executeDefinitionProvider", - }); + const definitions = []; - if (!typeDef) { - return undefined; - } - return { - ...typeDef, - contents: await ide.readRangeInFile(typeDef.filepath, typeDef.range), - }; - }), - ); + for (const node of identifierNodes) { + const [typeDef] = await executeGotoProvider({ + uri: vscode.Uri.parse(rif.filepath), + // TODO: tree-sitter is zero-indexed, but there seems to be an off-by-one + // error at least with the .ts parser sometimes + line: + rif.range.start.line + + Math.min(node.startPosition.row, astLineCount - 1), + character: rif.range.start.character + node.startPosition.column, + name: "vscode.executeDefinitionProvider", + }); + + if (!typeDef) { + definitions.push(undefined); + continue; + } + + const contents = await ide.readRangeInFile(typeDef.filepath, typeDef.range); + + definitions.push({ + ...typeDef, + contents, + }); + } // TODO: Filter out if not in our code? diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index da5e7db94..d99bbd5ae 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -31,8 +31,10 @@ import EditDecorationManager from "./quickEdit/EditDecorationManager"; import { QuickEdit, QuickEditShowParams } from "./quickEdit/QuickEditQuickPick"; import { Battery } from "./util/battery"; import { VsCodeIde } from "./VsCodeIde"; +import { getMetaKeyLabel } from "./util/util"; import type { VsCodeWebviewProtocol } from "./webviewProtocol"; +import { startLocalOllama } from "core/util/ollamaHelper"; let fullScreenPanel: vscode.WebviewPanel | undefined; @@ -708,7 +710,7 @@ const getCommandsMap: ( sidebar.webviewProtocol?.request("newSession", undefined); }, "continue.viewHistory": () => { - sidebar.webviewProtocol?.request("viewHistory", undefined); + vscode.commands.executeCommand("continue.navigateTo", "/history", true); }, "continue.focusContinueSessionId": async ( sessionId: string | undefined, @@ -776,6 +778,7 @@ const getCommandsMap: ( sessionId, ); } + panel.reveal(); sessionLoader.dispose(); }); @@ -902,15 +905,19 @@ const getCommandsMap: ( ? StatusBarStatus.Enabled : StatusBarStatus.Disabled; } + quickPick.items = [ { label: "$(question) Open help center", }, { - label: "$(comment) Open chat (Cmd+L)", + label: "$(comment) Open chat", + description: getMetaKeyLabel() + " + L", }, { - label: "$(screen-full) Open full screen chat (Cmd+K Cmd+M)", + label: "$(screen-full) Open full screen chat", + description: + getMetaKeyLabel() + " + K, " + getMetaKeyLabel() + " + M", }, { label: quickPickStatusText(targetStatus), @@ -992,11 +999,8 @@ const getCommandsMap: ( sidebar.webviewProtocol?.request("navigateTo", { path, toggle }); focusGUI(); }, - "continue.signInToControlPlane": () => { - sidebar.webviewProtocol?.request("signInToControlPlane", undefined); - }, - "continue.openAccountDialog": () => { - sidebar.webviewProtocol?.request("openDialogMessage", "account"); + "continue.startLocalOllama": () => { + startLocalOllama(ide); }, }; }; @@ -1052,7 +1056,7 @@ export function registerAllCommands( core: Core, editDecorationManager: EditDecorationManager, ) { - registerCopyBufferSpy(context, core); + // registerCopyBufferSpy(context, core); for (const [command, callback] of Object.entries( getCommandsMap( diff --git a/extensions/vscode/src/diff/vertical/manager.ts b/extensions/vscode/src/diff/vertical/manager.ts index 1e1b41a17..a62406b00 100644 --- a/extensions/vscode/src/diff/vertical/manager.ts +++ b/extensions/vscode/src/diff/vertical/manager.ts @@ -1,4 +1,4 @@ -import { DiffLine } from "core"; +import { ChatMessage, DiffLine } from "core"; import { ConfigHandler } from "core/config/ConfigHandler"; import { streamDiffLines } from "core/edit/streamDiffLines"; import { pruneLinesFromBottom, pruneLinesFromTop } from "core/llm/countTokens"; @@ -272,6 +272,7 @@ export class VerticalDiffManager { onlyOneInsertion?: boolean, quickEdit?: string, range?: vscode.Range, + newCode?: string, ): Promise { vscode.commands.executeCommand("setContext", "continue.diffVisible", true); @@ -386,6 +387,18 @@ export class VerticalDiffManager { llm.model, ); + let overridePrompt: ChatMessage[] | undefined; + if (llm.promptTemplates?.apply) { + const rendered = llm.renderPromptTemplate(llm.promptTemplates.apply, [], { + original_code: rangeContent, + new_code: newCode ?? "", + }); + overridePrompt = + typeof rendered === "string" + ? [{ role: "user", content: rendered }] + : rendered; + } + if (editor.selection) { // Unselect the range editor.selection = new vscode.Selection( @@ -413,7 +426,8 @@ export class VerticalDiffManager { llm, input, getMarkdownLanguageTagForFile(fileUri), - onlyOneInsertion, + !!onlyOneInsertion, + overridePrompt, ); for await (const line of stream) { diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index be58bb375..f8b8ca130 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -168,12 +168,6 @@ export class VsCodeExtension { } else if (newConfig) { setupStatusBar(undefined, undefined, false); - const result = await this.configHandler.getSerializedConfig(); - this.sidebar.webviewProtocol?.request("configUpdate", { - result, - profileId: this.configHandler.currentProfile.profileDescription.id, - }); - this.tabAutocompleteModel.clearLlm(); registerAllCodeLensProviders( @@ -182,8 +176,6 @@ export class VsCodeExtension { newConfig, ); } - - this.sidebar.webviewProtocol?.request("configError", errors); }, ); @@ -275,6 +267,7 @@ export class VsCodeExtension { }); vscode.workspace.onDidSaveTextDocument(async (event) => { + this.ide.updateLastFileSaveTimestamp(); this.core.invoke("files/changed", { uris: [event.uri.toString()], }); @@ -354,8 +347,7 @@ export class VsCodeExtension { // Register a content provider for the readonly virtual documents const documentContentProvider = new (class - implements vscode.TextDocumentContentProvider - { + implements vscode.TextDocumentContentProvider { // emitter and its event onDidChangeEmitter = new vscode.EventEmitter(); onDidChange = this.onDidChangeEmitter.event; @@ -380,7 +372,7 @@ export class VsCodeExtension { .get("enableContinueHub"); vscode.workspace.onDidChangeConfiguration(async (event) => { if (event.affectsConfiguration(EXTENSION_NAME)) { - const settings = this.ide.getIdeSettingsSync(); + const settings = await this.ide.getIdeSettings(); const webviewProtocol = await this.webviewProtocolPromise; void webviewProtocol.request("didChangeIdeSettings", { settings, diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 6bce4818a..aac537d93 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -230,6 +230,7 @@ export class VsCodeMessenger { undefined, undefined, rangeToApplyTo, + data.text, ); } }); diff --git a/extensions/vscode/src/util/ideUtils.ts b/extensions/vscode/src/util/ideUtils.ts index f576d6d1e..9642af68e 100644 --- a/extensions/vscode/src/util/ideUtils.ts +++ b/extensions/vscode/src/util/ideUtils.ts @@ -394,6 +394,27 @@ export class VsCodeIdeUtils { } } + private _getRepositories(): Repository[] | undefined { + const extension = + vscode.extensions.getExtension("vscode.git"); + if ( + typeof extension === "undefined" || + !extension.isActive || + typeof vscode.workspace.workspaceFolders === "undefined" + ) { + return undefined; + } + + try { + const git = extension.exports.getAPI(1); + return git.repositories; + } catch (e) { + this._repoWasNone = true; + console.warn("Git not found: ", e); + return undefined; + } + } + private _repoWasNone: boolean = false; private repoCache: Map = new Map(); private static secondsToWaitForGitToLoad = @@ -475,20 +496,28 @@ export class VsCodeIdeUtils { async getDiff(includeUnstaged: boolean): Promise { const diffs: string[] = []; - for (const dir of this.getWorkspaceDirectories()) { - const repo = await this.getRepo(dir); - if (!repo) { - continue; + const repos = this._getRepositories(); + + try { + if (repos) { + for (const repo of repos) { + + const staged = await repo.diff(true); + + diffs.push(staged); + if (includeUnstaged) { + const unstaged = await repo.diff(false); + diffs.push(unstaged); + } + } } - const staged = await repo.diff(true); - diffs.push(staged); - if (includeUnstaged) { - const unstaged = await repo.diff(false); - diffs.push(unstaged); - } + return diffs.flatMap((diff) => this.splitDiff(diff)); + + } catch (e) { + console.error(e); + return []; } - return diffs.flatMap((diff) => this.splitDiff(diff)); } } diff --git a/extensions/vscode/src/util/tutorial.ts b/extensions/vscode/src/util/tutorial.ts index 45a86a675..6557b5790 100644 --- a/extensions/vscode/src/util/tutorial.ts +++ b/extensions/vscode/src/util/tutorial.ts @@ -16,7 +16,12 @@ export async function showTutorial(ide: IDE) { // Ensure keyboard shortcuts match OS if (process.platform !== "darwin") { let tutorialContent = await ide.readFile(tutorialUri.toString()); - tutorialContent = tutorialContent.replace("⌘", "^").replace("Cmd", "Ctrl"); + tutorialContent = tutorialContent + .replaceAll("[Cmd + L]", "[Ctrl + L]") + .replaceAll("[Cmd + Shift + L]", "[Ctrl + Shift + L]") + .replaceAll("[Cmd + I]", "[Ctrl + I]") + .replaceAll("⌘", "^"); + await ide.writeFile(tutorialUri.toString(), tutorialContent); } diff --git a/extensions/vscode/src/util/util.ts b/extensions/vscode/src/util/util.ts index 6691a66d2..916d7b3bc 100644 --- a/extensions/vscode/src/util/util.ts +++ b/extensions/vscode/src/util/util.ts @@ -99,9 +99,9 @@ export function getMetaKeyLabel() { return "⌘"; case "linux": case "windows": - return "^"; + return "Ctrl"; default: - return "^"; + return "Ctrl"; } } diff --git a/extensions/vscode/src/webviewProtocol.ts b/extensions/vscode/src/webviewProtocol.ts index 2129c0ce3..14854f1c3 100644 --- a/extensions/vscode/src/webviewProtocol.ts +++ b/extensions/vscode/src/webviewProtocol.ts @@ -10,7 +10,8 @@ import { IMessenger } from "../../../core/protocol/messenger"; import { showFreeTrialLoginMessage } from "./util/messages"; export class VsCodeWebviewProtocol - implements IMessenger { + implements IMessenger +{ listeners = new Map< keyof FromWebviewProtocol, ((message: Message) => any)[] @@ -85,6 +86,30 @@ export class VsCodeWebviewProtocol respond({ done: true, content: response, status: "success" }); } } catch (e: any) { + let message = e.message; + //Intercept Ollama errors for special handling + if (message.includes("Ollama may not")) { + const options = []; + if (message.includes("be installed")) { + options.push("Download Ollama"); + } else if (message.includes("be running")) { + options.push("Start Ollama"); + } + if (options.length > 0) { + // Respond without an error, so the UI doesn't show the error component + respond({ done: true, status: "error" }); + // Show native vscode error message instead, with options to download/start Ollama + vscode.window.showErrorMessage(e.message, ...options).then(async (val) => { + if (val === "Download Ollama") { + vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai/download")); + } else if (val === "Start Ollama") { + vscode.commands.executeCommand("continue.startLocalOllama"); + } + }); + return; + } + } + respond({ done: true, error: e.message, status: "error" }); const stringified = JSON.stringify({ msg }, null, 2); @@ -99,7 +124,6 @@ export class VsCodeWebviewProtocol return; } - let message = e.message; if (e.cause) { if (e.cause.name === "ConnectTimeoutError") { message = `Connection timed out. If you expect it to take a long time to connect, you can increase the timeout in config.json by setting "requestOptions": { "timeout": 10000 }. You can find the full config reference here: https://docs.continue.dev/reference/config`; @@ -114,8 +138,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."; @@ -152,8 +175,7 @@ export class VsCodeWebviewProtocol this._webviewListener = this._webview.onDidReceiveMessage(handleMessage); } - constructor(private readonly reloadConfig: () => void) { - } + constructor(private readonly reloadConfig: () => void) {} invoke( messageType: T, @@ -163,7 +185,7 @@ export class VsCodeWebviewProtocol throw new Error("Method not implemented."); } - onError(handler: (error: Error) => void): void { + onError(handler: (message: Message, error: Error) => void): void { throw new Error("Method not implemented."); } diff --git a/gui/package-lock.json b/gui/package-lock.json index cca979250..acdad5284 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -7,7 +7,7 @@ "name": "gui", "license": "Apache-2.0", "dependencies": { - "@continuedev/config-yaml": "^1.0.23", + "@continuedev/config-yaml": "^1.0.31", "@headlessui/react": "^1.7.17", "@heroicons/react": "^2.0.18", "@reduxjs/toolkit": "^2.3.0", @@ -32,7 +32,6 @@ "lodash": "^4.17.21", "minisearch": "^7.0.2", "mustache": "^4.2.0", - "onigasm": "^2.2.5", "posthog-js": "^1.130.1", "prismjs": "^1.29.0", "react": "^18.2.0", @@ -51,7 +50,7 @@ "redux-persist-transform-filter": "^0.0.22", "redux-thunk": "^3.1.0", "rehype-highlight": "^7.0.0", - "rehype-katex": "^7.0.0", + "rehype-katex": "^7.0.1", "rehype-wrap-all": "^1.1.0", "remark-math": "^6.0.0", "reselect": "^5.1.1", @@ -108,11 +107,11 @@ "@aws-sdk/client-sagemaker-runtime": "^3.621.0", "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.23", + "@continuedev/config-yaml": "^1.0.31", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", "@continuedev/openai-adapters": "^1.0.10", - "@modelcontextprotocol/sdk": "^1.0.0", + "@modelcontextprotocol/sdk": "^1.5.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", "@typescript-eslint/eslint-plugin": "^7.8.0", @@ -556,9 +555,9 @@ } }, "node_modules/@continuedev/config-yaml": { - "version": "1.0.23", - "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.23.tgz", - "integrity": "sha512-F2Hwc85iCwAHJuwJALOsmZIBeHdF+87mS0YT7dlC6QiE+zAhZKUHcLQ/nTt9bJuhyVyufpb9LApkp40UdGsaWw==", + "version": "1.0.31", + "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.31.tgz", + "integrity": "sha512-HNj+z7UTTARgsJTI0A1buM09fS4HoWVnn6Hbl6kJ2tZmOOm1OgogbcKP68AzHb4fy5H18MWnKS7XuseZpHFzHQ==", "dependencies": { "@continuedev/config-types": "^1.0.14", "yaml": "^2.6.1", @@ -3871,10 +3870,11 @@ } }, "node_modules/bin-version/node_modules/cross-spawn": { - "version": "7.0.3", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", - "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", "dev": true, + "license": "MIT", "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", @@ -5756,10 +5756,11 @@ } }, "node_modules/foreground-child/node_modules/cross-spawn": { - "version": "7.0.3", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", - "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", "dev": true, + "license": "MIT", "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", @@ -7595,13 +7596,14 @@ } }, "node_modules/katex": { - "version": "0.16.11", - "resolved": "https://registry.npmjs.org/katex/-/katex-0.16.11.tgz", - "integrity": "sha512-RQrI8rlHY92OLf3rho/Ts8i/XvjgguEjOkO1BEXcU3N8BqPpSzBNwV/G0Ukr+P/l3ivvJUE/Fa/CwbS6HesGNQ==", + "version": "0.16.21", + "resolved": "https://registry.npmjs.org/katex/-/katex-0.16.21.tgz", + "integrity": "sha512-XvqR7FgOHtWupfMiigNzmh+MgUVmDGU2kXZm899ZkPfcuoPuFxyHmXsgATDpFZDAXCI8tvinaVcDo8PIIJSo4A==", "funding": [ "https://opencollective.com/katex", "https://github.com/sponsors/katex" ], + "license": "MIT", "dependencies": { "commander": "^8.3.0" }, @@ -8610,9 +8612,9 @@ } }, "node_modules/nanoid": { - "version": "3.3.7", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.7.tgz", - "integrity": "sha512-eSRppjcPIatRIMC1U6UngP8XFcz8MQWGQdt1MTBQ7NaAmvXDfvNxbvWV3x2y6CdEUciCSsDHDQZbhYaB8QEo2g==", + "version": "3.3.8", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.8.tgz", + "integrity": "sha512-WNLf5Sd8oZxOm+TzppcYk8gVOgP+l58xNy58D0nbUnOxOWRWvlcCV4kUF7ltmI6PsrLl/BgKEyS4mqsGChFN0w==", "dev": true, "funding": [ { @@ -8620,6 +8622,7 @@ "url": "https://github.com/sponsors/ai" } ], + "license": "MIT", "bin": { "nanoid": "bin/nanoid.cjs" }, @@ -8831,27 +8834,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/onigasm": { - "version": "2.2.5", - "resolved": "https://registry.npmjs.org/onigasm/-/onigasm-2.2.5.tgz", - "integrity": "sha512-F+th54mPc0l1lp1ZcFMyL/jTs2Tlq4SqIHKIXGZOR/VkHkF9A7Fr5rRr5+ZG/lWeRsyrClLYRq7s/yFQ/XhWCA==", - "dependencies": { - "lru-cache": "^5.1.1" - } - }, - "node_modules/onigasm/node_modules/lru-cache": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", - "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", - "dependencies": { - "yallist": "^3.0.2" - } - }, - "node_modules/onigasm/node_modules/yallist": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", - "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==" - }, "node_modules/optionator": { "version": "0.9.4", "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", @@ -12198,10 +12180,11 @@ } }, "node_modules/vite": { - "version": "4.5.5", - "resolved": "https://registry.npmjs.org/vite/-/vite-4.5.5.tgz", - "integrity": "sha512-ifW3Lb2sMdX+WU91s3R0FyQlAyLxOzCSCP37ujw0+r5POeHPwe6udWVIElKQq8gk3t7b8rkmvqC6IHBpCff4GQ==", + "version": "4.5.9", + "resolved": "https://registry.npmjs.org/vite/-/vite-4.5.9.tgz", + "integrity": "sha512-qK9W4xjgD3gXbC0NmdNFFnVFLMWSNiR3swj957yutwzzN16xF/E7nmtAyp1rT9hviDroQANjE4HK3H4WqWdFtw==", "dev": true, + "license": "MIT", "dependencies": { "esbuild": "^0.18.10", "postcss": "^8.4.27", @@ -12699,10 +12682,11 @@ } }, "node_modules/vite-node/node_modules/vite": { - "version": "5.4.9", - "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.9.tgz", - "integrity": "sha512-20OVpJHh0PAM0oSOELa5GaZNWeDjcAvQjGXy2Uyr+Tp+/D2/Hdz6NLgpJLsarPTA2QJ6v8mX2P1ZfbsSKvdMkg==", + "version": "5.4.14", + "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.14.tgz", + "integrity": "sha512-EK5cY7Q1D8JNhSaPKVK4pwBFvaTmZxEnoKXLG/U9gmdDcihQGNzFlgIvaxezFR4glP1LsuiedwMBqCXH3wZccA==", "dev": true, + "license": "MIT", "dependencies": { "esbuild": "^0.21.3", "postcss": "^8.4.43", @@ -13274,10 +13258,11 @@ } }, "node_modules/vitest/node_modules/vite": { - "version": "5.4.9", - "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.9.tgz", - "integrity": "sha512-20OVpJHh0PAM0oSOELa5GaZNWeDjcAvQjGXy2Uyr+Tp+/D2/Hdz6NLgpJLsarPTA2QJ6v8mX2P1ZfbsSKvdMkg==", + "version": "5.4.14", + "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.14.tgz", + "integrity": "sha512-EK5cY7Q1D8JNhSaPKVK4pwBFvaTmZxEnoKXLG/U9gmdDcihQGNzFlgIvaxezFR4glP1LsuiedwMBqCXH3wZccA==", "dev": true, + "license": "MIT", "dependencies": { "esbuild": "^0.21.3", "postcss": "^8.4.43", @@ -13748,9 +13733,9 @@ } }, "node_modules/zod": { - "version": "3.24.1", - "resolved": "https://registry.npmjs.org/zod/-/zod-3.24.1.tgz", - "integrity": "sha512-muH7gBL9sI1nciMZV67X5fTKKBLtwpZ5VBp1vsOQzj1MhrBZ4wlVCm3gedKZWLp0Oyel8sIGfeiz54Su+OVT+A==", + "version": "3.24.2", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.24.2.tgz", + "integrity": "sha512-lY7CDW43ECgW9u1TcT3IoXHflywfVqDYze4waEz812jR/bZ8FHDsl7pFQoSZTz5N+2NqRXs8GBwnAwo3ZNxqhQ==", "funding": { "url": "https://github.com/sponsors/colinhacks" } diff --git a/gui/package.json b/gui/package.json index 4500287fa..456c519fd 100644 --- a/gui/package.json +++ b/gui/package.json @@ -15,7 +15,7 @@ "test:watch": "vitest" }, "dependencies": { - "@continuedev/config-yaml": "^1.0.23", + "@continuedev/config-yaml": "^1.0.31", "@headlessui/react": "^1.7.17", "@heroicons/react": "^2.0.18", "@reduxjs/toolkit": "^2.3.0", @@ -40,7 +40,6 @@ "lodash": "^4.17.21", "minisearch": "^7.0.2", "mustache": "^4.2.0", - "onigasm": "^2.2.5", "posthog-js": "^1.130.1", "prismjs": "^1.29.0", "react": "^18.2.0", @@ -59,7 +58,7 @@ "redux-persist-transform-filter": "^0.0.22", "redux-thunk": "^3.1.0", "rehype-highlight": "^7.0.0", - "rehype-katex": "^7.0.0", + "rehype-katex": "^7.0.1", "rehype-wrap-all": "^1.1.0", "remark-math": "^6.0.0", "reselect": "^5.1.1", diff --git a/gui/public/logos/novita.png b/gui/public/logos/novita.png index b744cd35c..30ccb507e 100644 Binary files a/gui/public/logos/novita.png and b/gui/public/logos/novita.png differ diff --git a/gui/public/logos/siliconflow.png b/gui/public/logos/siliconflow.png new file mode 100644 index 000000000..f32fc6ebf Binary files /dev/null and b/gui/public/logos/siliconflow.png differ diff --git a/gui/src/components/AccountDialog.tsx b/gui/src/components/AccountDialog.tsx deleted file mode 100644 index 2b8e17ae4..000000000 --- a/gui/src/components/AccountDialog.tsx +++ /dev/null @@ -1,156 +0,0 @@ -import { Listbox, Transition } from "@headlessui/react"; -import { ChevronUpDownIcon } from "@heroicons/react/24/outline"; -import { Fragment, useContext } from "react"; -import { useDispatch } from "react-redux"; -import styled from "styled-components"; -import { - Button, - SecondaryButton, - vscInputBackground, - vscListActiveBackground, - vscListActiveForeground, -} from "."; -import { useAuth } from "../context/Auth"; -import { IdeMessengerContext } from "../context/IdeMessenger"; -import { setSelectedProfileId } from "../redux/slices/sessionSlice"; -import { setDialogMessage, setShowDialog } from "../redux/slices/uiSlice"; - -const StyledListboxOption = styled(Listbox.Option)<{ selected: boolean }>` - background-color: ${({ selected }) => - selected ? vscListActiveBackground : vscInputBackground}; - cursor: pointer; - padding: 6px 8px; - - &:hover { - background-color: ${vscListActiveBackground}; - color: ${vscListActiveForeground}; - } -`; - -export default function AccountDialog() { - const ideMessenger = useContext(IdeMessengerContext); - const { - session, - logout, - login, - profiles, - selectedProfile, - controlServerBetaEnabled, - } = useAuth(); - - // These shouldn't usually show but just to be safe - if (!session?.account?.id) { - return ( -
-

Account

- - Signed out - - -
- ); - } - - if (!controlServerBetaEnabled) { - return ( -
-

Account

-

- Continue For Teams is not enabled. You can enable it in your IDE - settings. -

-

Using local config.

-
- ); - } - - const dispatch = useDispatch(); - - const changeProfileId = (id: string) => { - ideMessenger.post("didChangeSelectedProfile", { id }); - dispatch(setSelectedProfileId(id)); - }; - - return ( -
-
-

Account

- - {session.account.label === "" ? ( - "Signed in" - ) : ( - <> - Signed in as{" "} - {session.account.label} - - )} - -
- -
- Current workspace - - - {({ open }) => ( -
- - {selectedProfile?.title} -
-
-
- - - - {profiles.map((option, idx) => ( - - - {option.title} - - - ))} - {profiles.length === 0 && ( -
- No workspaces found -
- )} -
-
-
- )} -
-
- -
- - Sign out - - -
-
- ); -} diff --git a/gui/src/components/CodeToEditCard/AddFileCombobox.tsx b/gui/src/components/CodeToEditCard/AddFileCombobox.tsx index abd7da72f..07ab68a2c 100644 --- a/gui/src/components/CodeToEditCard/AddFileCombobox.tsx +++ b/gui/src/components/CodeToEditCard/AddFileCombobox.tsx @@ -84,7 +84,7 @@ export default function AddFileCombobox({ className={({ active }) => `relative flex w-full cursor-pointer px-2 py-1 text-left text-xs ${ active - ? "bg-vsc-list-active-background text-vsc-list-active-foreground" + ? "bg-list-active text-list-active-foreground" : "" }` } @@ -112,7 +112,7 @@ export default function AddFileCombobox({ )) ) : ( -
+
No results
)} diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index 747c2ddab..b54db7549 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -2,27 +2,28 @@ import { useEffect, useMemo } from "react"; import { Outlet, useLocation, useNavigate } from "react-router-dom"; import styled from "styled-components"; import { CustomScrollbarDiv, defaultBorderRadius } from "."; +import { AuthProvider } from "../context/Auth"; import { useWebviewListener } from "../hooks/useWebviewListener"; import { useAppDispatch, useAppSelector } from "../redux/hooks"; -import { setEditStatus, focusEdit } from "../redux/slices/editModeState"; -import { setDialogMessage, setShowDialog } from "../redux/slices/uiSlice"; +import { focusEdit, setEditStatus } from "../redux/slices/editModeState"; import { addCodeToEdit, - updateApplyState, - setMode, newSession, + selectIsInEditMode, + setMode, + updateApplyState, } from "../redux/slices/sessionSlice"; +import { setShowDialog } from "../redux/slices/uiSlice"; +import { exitEditMode } from "../redux/thunks"; +import { loadLastSession, saveCurrentSession } from "../redux/thunks/session"; import { getFontSize, isMetaEquivalentKeyPressed } from "../util"; +import { incrementFreeTrialCount } from "../util/freeTrial"; import { ROUTES } from "../util/navigation"; import TextDialog from "./dialogs"; import Footer from "./Footer"; import { isNewUserOnboarding, useOnboardingCard } from "./OnboardingCard"; +import OSRContextMenu from "./OSRContextMenu"; import PostHogPageView from "./PosthogPageView"; -import AccountDialog from "./AccountDialog"; -import { AuthProvider } from "../context/Auth"; -import { exitEditMode } from "../redux/thunks"; -import { loadLastSession, saveCurrentSession } from "../redux/thunks/session"; -import { incrementFreeTrialCount } from "../util/freeTrial"; const LayoutTopDiv = styled(CustomScrollbarDiv)` height: 100%; @@ -62,6 +63,7 @@ const Layout = () => { await dispatch( saveCurrentSession({ openNewSession: true, + generateTitle: true, }), ); dispatch(exitEditMode()); @@ -85,6 +87,7 @@ const Layout = () => { await dispatch( saveCurrentSession({ openNewSession: true, + generateTitle: true, }), ); dispatch(exitEditMode()); @@ -93,17 +96,6 @@ const Layout = () => { location.pathname === ROUTES.HOME, ); - useWebviewListener( - "openDialogMessage", - async (message) => { - if (message === "account") { - dispatch(setShowDialog(true)); - dispatch(setDialogMessage()); - } - }, - [], - ); - useWebviewListener( "addModel", async () => { @@ -112,19 +104,6 @@ const Layout = () => { [navigate], ); - useWebviewListener( - "viewHistory", - async () => { - // Toggle the history page / main page - if (location.pathname === "/history") { - navigate("/"); - } else { - navigate("/history"); - } - }, - [location, navigate], - ); - useWebviewListener( "navigateTo", async (data) => { @@ -181,6 +160,8 @@ const Layout = () => { await dispatch( saveCurrentSession({ openNewSession: false, + // Because this causes a lag before Edit mode is focused. TODO just have that happen in background + generateTitle: false, }), ); dispatch(newSession()); @@ -196,6 +177,7 @@ const Layout = () => { await dispatch( saveCurrentSession({ openNewSession: true, + generateTitle: true, }), ); dispatch(focusEdit()); @@ -220,7 +202,11 @@ const Layout = () => { [], ); + const isInEditMode = useAppSelector(selectIsInEditMode); useWebviewListener("exitEditMode", async () => { + if (!isInEditMode) { + return; + } dispatch( loadLastSession({ saveCurrentSession: false, @@ -261,6 +247,7 @@ const Layout = () => { return ( +
{ + const ideMessenger = useContext(IdeMessengerContext); + const isOSREnabled = useIsOSREnabled(); + const platform = useRef(getPlatform()); + + const [position, setPosition] = useState(null); + const [canCopy, setCanCopy] = useState(false); + const [canCut, setCanCut] = useState(false); + const [canPaste, setCanPaste] = useState(false); + + const menuRef = React.useRef(null); + const selectedTextRef = useRef(null); + const selectedRangeRef = useRef(null); + + function onMenuItemClick( + event: React.MouseEvent, + ) { + event.preventDefault(); + + // restore selection + if (selectedRangeRef.current) { + const selection = window.getSelection(); + selection?.removeAllRanges(); + selection?.addRange(selectedRangeRef.current); + } + + // Hide menu + setPosition(null); + } + + useEffect(() => { + function leaveWindowHandler() { + setPosition(null); + } + function contextMenuHandler(event: MouseEvent) { + event.preventDefault(); + } + function clickHandler(event: MouseEvent) { + // If clicked outside of menu, close menu + if (!menuRef.current?.contains(event.target as Node)) { + setPosition(null); + } + + if (event.button === 2) { + // Prevent default context menu + event.preventDefault(); + + selectedRangeRef.current = null; + selectedTextRef.current = null; + + const selection = window.getSelection(); + let isClickWithinSelection = false; + if (selection && selection.rangeCount > 0) { + const range = selection.getRangeAt(0); + const selectedText = range.toString(); + selectedRangeRef.current = range.cloneRange(); + + if (selectedText.length > 0) { + if (selectedText) { + selectedTextRef.current = selectedText; + const rects = range.getClientRects(); + for (let i = 0; i < rects.length; i++) { + const rect = rects[i]; + if ( + event.clientX >= rect.left && + event.clientX <= rect.right && + event.clientY >= rect.top && + event.clientY <= rect.bottom + ) { + isClickWithinSelection = true; + break; + } + } + } + } + } + + // Check if right clicked on editable content (allows paste/cut) + let isEditable = false; + if ( + event.target && + "isContentEditable" in event.target && + typeof event.target.isContentEditable === "boolean" + ) { + isEditable = event.target.isContentEditable; + } + + setCanCopy(!!selectedTextRef.current && isClickWithinSelection); + setCanCut( + !!(isEditable && selectedTextRef.current && isClickWithinSelection), + ); + + // TODO only can paste if there is text in clipboard? + setCanPaste(isEditable); + // navigator.clipboard.readText().then((text) => { + // setCanPaste(text || null); + // }); + + // Open towards inside of window from click + const toRight = event.clientX > window.innerWidth / 2; + const toBottom = event.clientY > window.innerHeight / 2; + if (toRight) { + if (toBottom) { + setPosition({ + bottom: window.innerHeight - event.clientY, + right: window.innerWidth - event.clientX, + }); + } else { + setPosition({ + top: event.clientY, + right: window.innerWidth - event.clientX, + }); + } + } else { + if (toBottom) { + setPosition({ + bottom: window.innerHeight - event.clientY, + left: event.clientX, + }); + } else { + setPosition({ + top: event.clientY, + left: event.clientX, + }); + } + } + } + } + + setPosition(null); + if (isOSREnabled && platform.current !== "mac") { + document.addEventListener("mousedown", clickHandler); + document.addEventListener("mouseleave", leaveWindowHandler); + document.addEventListener("contextmenu", contextMenuHandler); + } + + return () => { + document.removeEventListener("mousedown", clickHandler); + document.removeEventListener("mouseleave", leaveWindowHandler); + document.removeEventListener("contextmenu", contextMenuHandler); + }; + }, [isOSREnabled]); + + if (platform.current === "mac" || !isOSREnabled || !position) { + return null; + } + return ( +
+ {canCopy && ( +
{ + onMenuItemClick(e); + document.execCommand("copy"); + }} + > + Copy +
+ )} + {canCut && ( +
{ + onMenuItemClick(e); + document.execCommand("cut"); + }} + > + Cut +
+ )} + {/* PASTING is currently broken, can't get the clipboard text */} + {/* {canPaste && ( +
{ + onMenuItemClick(e); + const clipboardText = await navigator.clipboard.readText(); + // const out = await navigator.clipboard.read(); + if (clipboardText) { + selectedRangeRef.current?.deleteContents(); + selectedRangeRef.current?.insertNode( + document.createTextNode(clipboardText), + ); + } + }} + > + Paste +
+ )} */} +
{ + onMenuItemClick(e); + ideMessenger.post("toggleDevTools", undefined); + }} + > + Open Dev Tools +
+
+ ); +}; + +export default OSRContextMenu; diff --git a/gui/src/components/OnboardingCard/OnboardingCard.tsx b/gui/src/components/OnboardingCard/OnboardingCard.tsx index eebbfb2bc..f48e2939d 100644 --- a/gui/src/components/OnboardingCard/OnboardingCard.tsx +++ b/gui/src/components/OnboardingCard/OnboardingCard.tsx @@ -5,6 +5,7 @@ import styled from "styled-components"; import { CloseButton, defaultBorderRadius, vscInputBackground } from "../"; import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; import { useOnboardingCard } from "./hooks/useOnboardingCard"; +import { useAppSelector } from "../../redux/hooks"; const StyledCard = styled.div` margin: auto; @@ -26,6 +27,7 @@ interface OnboardingCardProps { export function OnboardingCard({ isDialog }: OnboardingCardProps) { const onboardingCard = useOnboardingCard(); + const config = useAppSelector((store) => store.config.config); function renderTabContent() { switch (onboardingCard.activeTab) { @@ -53,7 +55,7 @@ export function OnboardingCard({ isDialog }: OnboardingCardProps) { activeTab={onboardingCard.activeTab || "Best"} onTabClick={onboardingCard.setActiveTab} /> - {!isDialog && ( + {!isDialog && !!config.models.length && ( onboardingCard.close()}> diff --git a/gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx b/gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx index 86e7cd693..389ed72dd 100644 --- a/gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx +++ b/gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx @@ -1,13 +1,12 @@ import { CubeIcon } from "@heroicons/react/24/outline"; -import { DEFAULT_CHAT_MODEL_CONFIG } from "core/config/default"; import { FormEventHandler, useContext, useState } from "react"; import { useDispatch } from "react-redux"; import { Button, Input, InputSubtext, lightGray } from "../.."; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { models } from "../../../pages/AddNewModel/configs/models"; import { providers } from "../../../pages/AddNewModel/configs/providers"; -import AddModelButtonSubtext from "../../AddModelButtonSubtext"; import { setDefaultModel } from "../../../redux/slices/configSlice"; +import AddModelButtonSubtext from "../../AddModelButtonSubtext"; const { anthropic, mistral } = providers; const chatProvider = anthropic!; @@ -15,7 +14,7 @@ const autocompleteProvider = mistral!; const { claude35Sonnet: chatModel, - claude3Haiku: repoMapModel, + claude35Haiku: repoMapModel, codestral: autocompleteModel, } = models; @@ -57,9 +56,6 @@ function BestExperienceConfigForm({ apiKey: autocompleteApiKey, }; - ideMessenger.post("config/deleteModel", { - title: DEFAULT_CHAT_MODEL_CONFIG.title, - }); ideMessenger.post("config/addModel", { model: chatModelConfig }); ideMessenger.post("config/addModel", { model: repoMapConfig, diff --git a/gui/src/components/OnboardingCard/components/OllamaCompletedStep.tsx b/gui/src/components/OnboardingCard/components/OllamaCompletedStep.tsx index 1b2cbea0a..d7a396804 100644 --- a/gui/src/components/OnboardingCard/components/OllamaCompletedStep.tsx +++ b/gui/src/components/OnboardingCard/components/OllamaCompletedStep.tsx @@ -7,7 +7,7 @@ interface OllamaCompletedStepProps { function OllamaCompletedStep({ text }: OllamaCompletedStepProps) { return (
-

{text}

+

{text}

); diff --git a/gui/src/components/OnboardingCard/components/OllamaModelDownload.tsx b/gui/src/components/OnboardingCard/components/OllamaModelDownload.tsx index 7a4eede07..6a7075fac 100644 --- a/gui/src/components/OnboardingCard/components/OllamaModelDownload.tsx +++ b/gui/src/components/OnboardingCard/components/OllamaModelDownload.tsx @@ -27,13 +27,13 @@ function OllamaModelDownload({ return (
-

{title}

+

{title}

{hasDownloaded ? ( ) : ( <> -

{command}

+

{command}

diff --git a/gui/src/components/OnboardingCard/components/OllamaStatus.tsx b/gui/src/components/OnboardingCard/components/OllamaStatus.tsx index 15132518e..515958503 100644 --- a/gui/src/components/OnboardingCard/components/OllamaStatus.tsx +++ b/gui/src/components/OnboardingCard/components/OllamaStatus.tsx @@ -2,7 +2,7 @@ import { ArrowPathIcon, ArrowTopRightOnSquareIcon, } from "@heroicons/react/24/outline"; -import { useState, useContext } from "react"; +import { useState, useContext, useEffect } from "react"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { providers } from "../../../pages/AddNewModel/configs/providers"; import { StyledActionButton } from "../.."; @@ -19,10 +19,15 @@ export function OllamaStatus({ isOllamaConnected }: OllamaStatusProps) { const ideMessenger = useContext(IdeMessengerContext); const [status, setStatus] = useState( - isOllamaConnected - ? OllamaConnectionStatuses.Connected - : OllamaConnectionStatuses.WaitingToDownload, + OllamaConnectionStatuses.WaitingToDownload, ); + useEffect(() => { + if (isOllamaConnected) { + setStatus(OllamaConnectionStatuses.Connected); + } else if (status !== OllamaConnectionStatuses.Downloading) { + setStatus(OllamaConnectionStatuses.WaitingToDownload); + } + }, [status, isOllamaConnected]); function onClickDownload() { ideMessenger.post("openUrl", downloadUrl); @@ -33,14 +38,14 @@ export function OllamaStatus({ isOllamaConnected }: OllamaStatusProps) { case OllamaConnectionStatuses.WaitingToDownload: return ( -

{downloadUrl}

+

{downloadUrl}

); case OllamaConnectionStatuses.Downloading: return (
-

+

Checking for connection to Ollama at http://localhost:11434

diff --git a/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx b/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx index ede9295b3..a48845c44 100644 --- a/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx +++ b/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx @@ -8,6 +8,7 @@ import { TabTitle } from "../components/OnboardingCardTabs"; import { useOnboardingCard } from "../hooks"; import OnboardingLocalTab from "../tabs/OnboardingLocalTab"; import MainTab from "./tabs/main"; +import { useAppSelector } from "../../../redux/hooks"; const StyledCard = styled.div` margin: auto; @@ -29,6 +30,7 @@ interface OnboardingCardProps { export function PlatformOnboardingCard({ isDialog }: OnboardingCardProps) { const onboardingCard = useOnboardingCard(); + const config = useAppSelector((store) => store.config.config); if (getLocalStorage("onboardingStatus") === undefined) { setLocalStorage("onboardingStatus", "Started"); @@ -38,7 +40,7 @@ export function PlatformOnboardingCard({ isDialog }: OnboardingCardProps) { return ( - {!isDialog && ( + {!isDialog && !!config.models.length && ( onboardingCard.close()}> @@ -51,7 +53,7 @@ export function PlatformOnboardingCard({ isDialog }: OnboardingCardProps) { isDialog={isDialog} /> ) : ( -
+
By choosing this option, Continue will be configured by a local{" "} config.yaml file. If you're just looking to use diff --git a/gui/src/components/OnboardingCard/platform/tabs/main.tsx b/gui/src/components/OnboardingCard/platform/tabs/main.tsx index 94e3c0de0..51a40e46d 100644 --- a/gui/src/components/OnboardingCard/platform/tabs/main.tsx +++ b/gui/src/components/OnboardingCard/platform/tabs/main.tsx @@ -1,11 +1,11 @@ import { ChevronRightIcon } from "@heroicons/react/24/outline"; +import { useContext } from "react"; import { Button, ButtonSubtext } from "../../.."; import { useAuth } from "../../../../context/Auth"; +import { IdeMessengerContext } from "../../../../context/IdeMessenger"; +import { hasPassedFTL } from "../../../../util/freeTrial"; import ContinueLogo from "../../../gui/ContinueLogo"; import { useOnboardingCard } from "../../hooks"; -import { hasPassedFTL } from "../../../../util/freeTrial"; -import { useContext } from "react"; -import { IdeMessengerContext } from "../../../../context/IdeMessenger"; export default function MainTab({ onRemainLocal, @@ -29,6 +29,7 @@ export default function MainTab({ function openPastFreeTrialOnboarding() { ideMessenger.post("controlPlane/openUrl", { path: "setup-models", + orgSlug: auth.selectedOrganization?.slug, }); onboardingCard.close(isDialog); } diff --git a/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx b/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx index 76ba5bf5c..81b0a7a6b 100644 --- a/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx +++ b/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx @@ -1,14 +1,14 @@ import { LOCAL_ONBOARDING_CHAT_MODEL, LOCAL_ONBOARDING_CHAT_TITLE, + LOCAL_ONBOARDING_EMBEDDINGS_MODEL, LOCAL_ONBOARDING_FIM_MODEL, - ONBOARDING_LOCAL_MODEL_TITLE, + LOCAL_ONBOARDING_PROVIDER_TITLE, } from "core/config/onboarding"; import { useContext, useEffect, useState } from "react"; import { useDispatch } from "react-redux"; import { Button } from "../.."; import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import { hasPassedFTL } from "../../../util/freeTrial"; import AddModelButtonSubtext from "../../AddModelButtonSubtext"; import OllamaModelDownload from "../components/OllamaModelDownload"; import { OllamaStatus } from "../components/OllamaStatus"; @@ -25,10 +25,7 @@ interface OnboardingLocalTabProps { function OnboardingLocalTab({ isDialog }: OnboardingLocalTabProps) { const dispatch = useDispatch(); const ideMessenger = useContext(IdeMessengerContext); - const { submitOnboarding } = useSubmitOnboarding( - hasPassedFTL() ? "LocalAfterFreeTrial" : "Local", - isDialog, - ); + const { submitOnboarding } = useSubmitOnboarding("Local", isDialog); const [hasLoadedChatModel, setHasLoadedChatModel] = useState(false); const [downloadedOllamaModels, setDownloadedOllamaModels] = useState< string[] @@ -37,17 +34,28 @@ function OnboardingLocalTab({ isDialog }: OnboardingLocalTabProps) { const [isOllamaConnected, setIsOllamaConnected] = useState(false); const hasDownloadedChatModel = Array.isArray(downloadedOllamaModels) - ? downloadedOllamaModels.some((ollamaModel) => - ollamaModel.startsWith(LOCAL_ONBOARDING_CHAT_MODEL), + ? downloadedOllamaModels.some( + (ollamaModel) => ollamaModel === LOCAL_ONBOARDING_CHAT_MODEL, ) : false; const hasDownloadedAutocompleteModel = Array.isArray(downloadedOllamaModels) - ? downloadedOllamaModels.some((ollamaModel) => - ollamaModel.startsWith(LOCAL_ONBOARDING_CHAT_MODEL), + ? downloadedOllamaModels.some( + (ollamaModel) => ollamaModel === LOCAL_ONBOARDING_FIM_MODEL, ) : false; + const hasDownloadedEmbeddingsModel = Array.isArray(downloadedOllamaModels) + ? downloadedOllamaModels.some( + (ollamaModel) => ollamaModel === LOCAL_ONBOARDING_EMBEDDINGS_MODEL, + ) + : false; + + const allDownloaded = + hasDownloadedAutocompleteModel && + hasDownloadedChatModel && + hasDownloadedEmbeddingsModel; + /** * The first time we detect that a chat model has been loaded, * we send an empty request to load it @@ -57,7 +65,7 @@ function OnboardingLocalTab({ isDialog }: OnboardingLocalTabProps) { ideMessenger.post("llm/complete", { completionOptions: {}, prompt: "", - title: ONBOARDING_LOCAL_MODEL_TITLE, + title: LOCAL_ONBOARDING_PROVIDER_TITLE, }); setHasLoadedChatModel(true); @@ -68,18 +76,11 @@ function OnboardingLocalTab({ isDialog }: OnboardingLocalTabProps) { const fetchDownloadedModels = async () => { try { const result = await ideMessenger.request("llm/listModels", { - title: ONBOARDING_LOCAL_MODEL_TITLE, + title: LOCAL_ONBOARDING_PROVIDER_TITLE, }); if (result.status === "success") { - // TODO - temporary fix, see notes - // https://github.com/continuedev/continue/pull/3059 - if (Array.isArray(result.content)) { - setDownloadedOllamaModels(result.content); - setIsOllamaConnected(true); - } else { - setDownloadedOllamaModels([]); - setIsOllamaConnected(false); - } + setDownloadedOllamaModels(result.content ?? []); + setIsOllamaConnected(!!result.content); } else { throw new Error("Failed to fetch models"); } @@ -100,9 +101,9 @@ function OnboardingLocalTab({ isDialog }: OnboardingLocalTabProps) { }, []); return ( -
+
-

Install Ollama

+

Install Ollama

@@ -118,6 +119,12 @@ function OnboardingLocalTab({ isDialog }: OnboardingLocalTabProps) { hasDownloaded={hasDownloadedAutocompleteModel} /> + +
diff --git a/gui/src/components/PageHeader.tsx b/gui/src/components/PageHeader.tsx index 04317c947..22755926e 100644 --- a/gui/src/components/PageHeader.tsx +++ b/gui/src/components/PageHeader.tsx @@ -12,7 +12,7 @@ export default function PageHeader({ rightContent, }: PageHeaderProps) { return ( -
+
{title && (
` - background-color: ${({ selected }) => - selected ? vscListActiveBackground : vscInputBackground}; - cursor: pointer; - padding: 6px 8px; - - &:hover { - background-color: ${vscListActiveBackground}; - color: ${vscListActiveForeground}; - } -`; - -function ListBoxOption({ - option, - idx, - showDelete, - selected, -}: { - option: ProfileDescription; - idx: number; - showDelete?: boolean; - selected: boolean; -}) { - const [hovered, setHovered] = useState(false); - - return ( - { - setHovered(true); - }} - onMouseLeave={() => { - setHovered(false); - }} - > -
- {option.title} -
-
- ); -} - -function ProfileSwitcher() { - const ideMessenger = useContext(IdeMessengerContext); - const { session, logout, login } = useAuth(); - const [profiles, setProfiles] = useState([]); - - const dispatch = useDispatch(); - const lastControlServerBetaEnabledStatus = useAppSelector( - (state) => state.misc.lastControlServerBetaEnabledStatus, - ); - - const selectedProfileId = useAppSelector( - (store) => store.session.selectedProfileId, - ); - - const [controlServerBetaEnabled, setControlServerBetaEnabled] = - useState(false); - - useEffect(() => { - ideMessenger.ide.getIdeSettings().then(({ enableControlServerBeta }) => { - setControlServerBetaEnabled(enableControlServerBeta); - dispatch(setLastControlServerBetaEnabledStatus(enableControlServerBeta)); - - const shouldShowPopup = - !lastControlServerBetaEnabledStatus && enableControlServerBeta; - }); - }, []); - - useWebviewListener( - "didChangeIdeSettings", - async (msg) => { - const { settings } = msg; - setControlServerBetaEnabled(settings.enableControlServerBeta); - dispatch( - setLastControlServerBetaEnabledStatus(settings.enableControlServerBeta), - ); - }, - [], - ); - - useEffect(() => { - ideMessenger - .request("config/listProfiles", undefined) - .then( - (result) => result.status === "success" && setProfiles(result.content), - ); - }, []); - - useWebviewListener( - "didChangeAvailableProfiles", - async (data) => { - setProfiles(data.profiles); - }, - [], - ); - - const topDiv = document.getElementById("profile-select-top-div"); - - function selectedProfile() { - return profiles.find((p) => p.id === selectedProfileId); - } - - return ( - <> - {controlServerBetaEnabled && session?.account?.id && ( - { - ideMessenger.post("didChangeSelectedProfile", { id }); - }} - > -
- - {selectedProfile()?.title} -
-
-
- {topDiv && - ReactDOM.createPortal( - - - {profiles.map((option, idx) => ( - 1} - /> - ))} -
- {profiles.length === 0 ? ( - No workspaces found - ) : ( - "Select workspace" - )} -
-
-
, - topDiv, - )} -
-
- )} - - {controlServerBetaEnabled && - (session?.account ? ( - - - - ) : ( - - - - ))} - - ); -} - -export default ProfileSwitcher; diff --git a/gui/src/components/dialogs/AboutAssistantDialog.tsx b/gui/src/components/dialogs/AboutAssistantDialog.tsx deleted file mode 100644 index 6f1734a92..000000000 --- a/gui/src/components/dialogs/AboutAssistantDialog.tsx +++ /dev/null @@ -1,80 +0,0 @@ -import { useAppSelector } from "../../redux/hooks"; -import { RootState } from "../../redux/store"; - -export default function AboutAssistantDialog() { - const configJson = useAppSelector((store: RootState) => store.config.config); - - const selectedProfileId = useAppSelector( - (store) => store.session.selectedProfileId, - ); - - return ( -
-

About {selectedProfileId} assistant

- {configJson.models?.length > 0 && ( -
- Chat models -
    - {configJson.models.map((model, index) => ( -
  • {model.title}
  • - ))} -
-
- )} - - {configJson.embeddingsProvider && ( -
- Embedding model -

{configJson.embeddingsProvider}

-
- )} - - {configJson.reranker?.name && ( -
- Rerank model -

{configJson.reranker.name}

-
- )} - - {configJson.systemMessage && ( -
- Rules -

{configJson.systemMessage}

-
- )} - - {configJson.contextProviders?.length ? ( -
- Context -
    - {configJson.contextProviders.map((provider, index) => ( -
  • {provider.title}
  • - ))} -
-
- ) : null} - - {configJson.tools.length > 0 && ( -
- Tools -
    - {configJson.tools.map((tool, index) => ( -
  • {tool.displayTitle}
  • - ))} -
-
- )} - - {configJson.docs?.length ? ( -
- Docs -
    - {configJson.docs.map((doc, index) => ( -
  • {doc.title}
  • - ))} -
-
- ) : null} -
- ); -} diff --git a/gui/src/components/dialogs/AddDocsDialog.tsx b/gui/src/components/dialogs/AddDocsDialog.tsx index 8439a70fa..df75e6203 100644 --- a/gui/src/components/dialogs/AddDocsDialog.tsx +++ b/gui/src/components/dialogs/AddDocsDialog.tsx @@ -184,7 +184,7 @@ function AddDocsDialog() { {!!sortedDocsSuggestions.length && (

Suggestions

)} -
+
{sortedDocsSuggestions.map((docsResult) => { const { error, details } = docsResult; const { language, name, version } = docsResult.packageInfo; @@ -202,14 +202,14 @@ function AddDocsDialog() {
This may not be a docs page
) : ( - + )}
@@ -224,7 +224,7 @@ function AddDocsDialog() {
{error || !details?.docsLink ? ( - + No docs link found ) : ( @@ -251,7 +251,7 @@ function AddDocsDialog() { >

{`Version: ${version}`}

@@ -271,7 +271,7 @@ function AddDocsDialog() {
The title that will be displayed to users in the `@docs` @@ -297,7 +297,7 @@ function AddDocsDialog() {
The starting location to begin crawling the documentation diff --git a/gui/src/components/dialogs/FreeTrialOverDialog.tsx b/gui/src/components/dialogs/FreeTrialOverDialog.tsx index d8666b1b2..107e351ce 100644 --- a/gui/src/components/dialogs/FreeTrialOverDialog.tsx +++ b/gui/src/components/dialogs/FreeTrialOverDialog.tsx @@ -1,15 +1,15 @@ -import { useDispatch } from "react-redux"; -import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; -import { useAppSelector } from "../../redux/hooks"; import { useEffect } from "react"; -import { selectUsePlatform } from "../../redux/selectors"; -import { PlatformOnboardingCard } from "../OnboardingCard/platform/PlatformOnboardingCard"; +import { useDispatch } from "react-redux"; +import { useAppSelector } from "../../redux/hooks"; +import { selectUseHub } from "../../redux/selectors"; +import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; import { OnboardingCard } from "../OnboardingCard"; +import { PlatformOnboardingCard } from "../OnboardingCard/platform/PlatformOnboardingCard"; function FreeTrialOverDialog() { const dispatch = useDispatch(); const history = useAppSelector((store) => store.session.history); - const usePlatform = useAppSelector(selectUsePlatform); + const usePlatform = useAppSelector(selectUseHub); useEffect(() => { if (history.length === 0) { diff --git a/gui/src/components/find/FindWidget.tsx b/gui/src/components/find/FindWidget.tsx index 9bf965d0f..7f6874aeb 100644 --- a/gui/src/components/find/FindWidget.tsx +++ b/gui/src/components/find/FindWidget.tsx @@ -43,7 +43,7 @@ const HighlightOverlay = (props: HighlightOverlayProps) => { const { isCurrent, top, left, width, height } = props; return (
7) { - document.body.style.setProperty(colorVar, value.slice(0, 7)); - } - } -} +export const vscCommandCenterActiveBorder = `var(${VSC_COMMAND_CENTER_ACTIVE_BORDER_VAR}, #1bbe84)`; +export const vscCommandCenterInactiveBorder = `var(${VSC_COMMAND_CENTER_INACTIVE_BORDER_VAR}, #1bbe84)`; +export const vscFindMatchSelected = `var(${VSC_FIND_MATCH_SELECTED_VAR}, rgba(255, 223, 0))`; export function parseHexColor(hexColor: string): { r: number; @@ -134,7 +110,7 @@ export function parseColorForHex(colorVar: string): string { } export const Button = styled.button` - padding: 10px 12px; + padding: 6px 12px; margin: 8px 0; border-radius: ${defaultBorderRadius}; @@ -154,21 +130,14 @@ export const Button = styled.button` } `; -type NumberInputProps = { - value: number; - onChange: (value: number) => void; - max?: number; - min?: number; -}; - export const SecondaryButton = styled.button` - padding: 10px 12px; + padding: 6px 12px; margin: 8px 0; border-radius: ${defaultBorderRadius}; - border: 1px solid ${vscForeground}; + border: 1px solid ${vscInputBorder}; color: ${vscForeground}; - background-color: inherit; + background-color: ${vscInputBackground}; &:disabled { color: gray; diff --git a/gui/src/components/indexing/DocsDetailsDialog.tsx b/gui/src/components/indexing/DocsDetailsDialog.tsx index 7b824291a..f8d0a54e9 100644 --- a/gui/src/components/indexing/DocsDetailsDialog.tsx +++ b/gui/src/components/indexing/DocsDetailsDialog.tsx @@ -127,25 +127,36 @@ function DocsDetailsDialog({ startUrl }: DocsDetailsDialogProps) { - - {chunk.filepath} - - - {chunk.content} - ); })} + {/* Rending tooltips here because div can't be child of tbody apparently */} + {data.chunks.map((chunk, i) => { + const contentToolTipId = `docs-content-peek-${i}`; + const urlToolTipId = `docs-url-peek-${i}`; + return ( + <> + + {chunk.filepath} + + + {chunk.content} + + + ); + })}
)}
diff --git a/gui/src/components/indexing/DocsIndexingStatus.tsx b/gui/src/components/indexing/DocsIndexingStatus.tsx index fe64ae2dc..224d96265 100644 --- a/gui/src/components/indexing/DocsIndexingStatus.tsx +++ b/gui/src/components/indexing/DocsIndexingStatus.tsx @@ -91,7 +91,6 @@ function DocsIndexingStatus({ docConfig }: IndexingStatusViewerProps) { return (
- {/* {`${status.type} - ${status.id} - ${status.status} - ${status.progress} - ${status.description} - ${status.icon}`} */}
diff --git a/gui/src/components/indexing/DocsIndexingStatuses.tsx b/gui/src/components/indexing/DocsIndexingStatuses.tsx index db312aef9..f1e261dfb 100644 --- a/gui/src/components/indexing/DocsIndexingStatuses.tsx +++ b/gui/src/components/indexing/DocsIndexingStatuses.tsx @@ -7,11 +7,15 @@ import { useAppSelector } from "../../redux/hooks"; import { useContext, useMemo } from "react"; import { ExclamationTriangleIcon } from "@heroicons/react/24/outline"; import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { IndexingStatus } from "core"; function DocsIndexingStatuses() { const dispatch = useDispatch(); const config = useAppSelector((store) => store.config.config); const ideMessenger = useContext(IdeMessengerContext); + const indexingStatuses = useAppSelector( + (store) => store.indexing.indexing.statuses, + ); const hasDocsProvider = useMemo(() => { return !!config.contextProviders?.some( @@ -19,15 +23,31 @@ function DocsIndexingStatuses() { ); }, [config]); - const configDocs = useMemo(() => { - return config.docs ?? []; - }, [config]); + // TODO - this might significantly impact performance during indexing + const sortedConfigDocs = useMemo(() => { + const sorter = (status: IndexingStatus["status"]) => { + // TODO - further sorting? + if (status === "indexing" || status === "paused") return 0; + if (status === "failed") return 1; + if (status === "aborted" || status === "pending") return 2; + return 3; + }; + + const docs = [...(config.docs ?? [])]; + docs.sort((a, b) => + sorter(indexingStatuses[b.startUrl]?.status ?? "pending") > + sorter(indexingStatuses[a.startUrl]?.status ?? "pending") + ? -1 + : 1, + ); + return docs; + }, [config, indexingStatuses]); return (

@docs indexes

- {configDocs.length ? ( + {sortedConfigDocs.length ? ( { @@ -41,7 +61,7 @@ function DocsIndexingStatuses() {
{hasDocsProvider ? ( - configDocs.length ? ( + sortedConfigDocs.length ? ( "Manage your documentation sources" ) : ( "No docs yet" @@ -72,7 +92,7 @@ function DocsIndexingStatuses() {
- {configDocs.length === 0 && ( + {sortedConfigDocs.length === 0 && ( { @@ -84,7 +104,7 @@ function DocsIndexingStatuses() { )}
- {configDocs.map((doc) => { + {sortedConfigDocs.map((doc) => { return ; })}
diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index 93b437fdc..a6b92ab90 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -91,9 +91,9 @@ function InputToolbar(props: InputToolbarProps) { const hasCodeToEdit = useAppSelector(selectHasCodeToEdit); const isEditModeAndNoCodeToEdit = isInEditMode && !hasCodeToEdit; const isEnterDisabled = props.disabled || isEditModeAndNoCodeToEdit; - const shouldRenderToolsButton = + const toolsSupported = defaultModel && - modelSupportsTools(defaultModel.model, defaultModel.provider) && + modelSupportsTools(defaultModel) && !props.toolbarOptions?.hideTools; const supportsImages = @@ -158,14 +158,14 @@ function InputToolbar(props: InputToolbarProps) { )} - {shouldRenderToolsButton && } +
{!props.toolbarOptions?.hideUseCodebase && !isInEditMode && (
- {availableTools.map((tool) => ( + {availableTools.map((tool: any) => ( + {props.tool.faviconUrl && ( + {props.tool.displayTitle} + )} {props.tool.displayTitle}{" "} {/* ` +const InputBoxDiv = styled.div<{}>` resize: none; padding-bottom: 4px; font-family: inherit; @@ -90,8 +85,13 @@ const InputBoxDiv = styled.div<{ border?: string }>` width: 100%; background-color: ${vscInputBackground}; color: ${vscForeground}; - border: ${(props) => - props.border ? props.border : `0.5px solid ${vscInputBorder}`}; + + border: 1px solid ${vscCommandCenterInactiveBorder}; + transition: border-color 0.15s ease-in-out; + &:focus-within { + border: 1px solid ${vscCommandCenterActiveBorder}; + } + outline: none; font-size: ${getFontSize()}px; @@ -173,7 +173,6 @@ interface TipTapEditorProps { ) => void; editorState?: JSONContent; toolbarOptions?: ToolbarOptions; - border?: string; placeholder?: string; historyKey: string; inputId: string; @@ -730,6 +729,7 @@ function TipTapEditor(props: TipTapEditorProps) { await dispatch( saveCurrentSession({ openNewSession: false, + generateTitle: true, }), ); } @@ -763,6 +763,7 @@ function TipTapEditor(props: TipTapEditorProps) { await dispatch( saveCurrentSession({ openNewSession: true, + generateTitle: true, }), ); setTimeout(() => { @@ -925,7 +926,6 @@ function TipTapEditor(props: TipTapEditorProps) { return ( void; } -const TutorialCardDiv = styled.div` - border: 1px solid ${lightGray}; - border-radius: ${defaultBorderRadius}; - background-color: ${vscBackground}; - padding: 1rem 2.5rem 1rem 2rem; - margin: 1rem; - max-width: 28rem; - position: relative; -`; - -const CloseButton = styled.button` - border: none; - background-color: ${vscBackground}; - color: ${lightGray}; - position: absolute; - top: 0.4rem; - right: 0.5rem; - padding: 0.25rem; - display: flex; - align-items: center; - justify-content: center; - cursor: pointer; -`; - export function TutorialCard({ onClose }: TutorialCardProps) { const ideMessenger = useContext(IdeMessengerContext); + const jetbrains = isJetBrains(); return ( - - - - +
+
+

+
+ +
+
    - {!isJetBrains() && ( + {!jetbrains && (
  • @@ -67,27 +52,36 @@ export function TutorialCard({ onClose }: TutorialCardProps) {
  • )}
  • - +
    + +
    - Highlight code and press {getMetaKeyLabel()} + I to - quickly make natural language edits + Highlight code and press {getMetaKeyLabel()} +{" "} + I to quickly make natural language edits
  • - +
    + +
    - Highlight code and press {getMetaKeyLabel()} + L to - add it to the chat window + Highlight code and press {getMetaKeyLabel()} +{" "} + {jetbrains ? "J" : "L"} to add it to the chat window
  • - +
    + +
    - Click the gear icon in the bottom right to configure Continue + Click the gear icon at the top of the chat window to configure + Continue
  • - +
    + +
- +
); } diff --git a/gui/src/components/mainInput/handleMetaKeyIssues.ts b/gui/src/components/mainInput/handleMetaKeyIssues.ts index 14bf3f792..1adf5593a 100644 --- a/gui/src/components/mainInput/handleMetaKeyIssues.ts +++ b/gui/src/components/mainInput/handleMetaKeyIssues.ts @@ -3,7 +3,6 @@ import { KeyboardEvent } from "react"; import { getPlatform, isWebEnvironment } from "../../util"; const isWebEnv = isWebEnvironment(); -const platform = getPlatform(); /** * This handles various keypress issues when OSR is enabled @@ -14,6 +13,7 @@ export const handleJetBrainsOSRMetaKeyIssues = ( ) => { const selection = window.getSelection(); const alter = e.shiftKey ? "extend" : "move"; + const platform = getPlatform(); const handlers: Record void> = { Backspace: () => handleJetBrainsMetaBackspace(editor), @@ -108,6 +108,7 @@ export const handleJetBrainsMetaBackspace = (editor: Editor) => { } // For Linux/Windows, only delete the word to the left of the cursor + const platform = getPlatform(); if (platform !== "mac") { deleteSingleWord(editor); break; diff --git a/gui/src/components/markdown/StepContainerPreActionButtons.tsx b/gui/src/components/markdown/StepContainerPreActionButtons.tsx index 641e17c13..5cb33d939 100644 --- a/gui/src/components/markdown/StepContainerPreActionButtons.tsx +++ b/gui/src/components/markdown/StepContainerPreActionButtons.tsx @@ -84,7 +84,7 @@ export default function StepContainerPreActionButtons({ tabIndex={-1} onMouseEnter={() => setHovering(true)} onMouseLeave={() => setHovering(false)} - className="bg-vsc-editor-background border-vsc-input-border relative rounded-md border-[1px] border-solid" + className="bg-vsc-editor-background border-vsc-input-border relative my-2.5 rounded-md border-[1px] border-solid" >
{children}
{hovering && !isStreaming && ( diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index 45faf550a..99e449cc7 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx @@ -99,16 +99,6 @@ export default function StepContainerPreToolbar( ideMessenger.ide, ); - // Sometimes the model will decide to only output the base name - // in which case we shouldn't create a new file if it matches the current file - const exists = await ideMessenger.ide.fileExists(fileUri); - if (!exists) { - const activeFile = await ideMessenger.ide.getCurrentFile(); - if (activeFile && activeFile.path.endsWith(props.relativeFilepath)) { - fileUri = activeFile.path; - } - } - ideMessenger.post("applyToFile", { streamId: streamIdRef.current, filepath: fileUri, diff --git a/gui/src/components/modelSelection/ModelSelect.tsx b/gui/src/components/modelSelection/ModelSelect.tsx index 68f5ea996..92a37928f 100644 --- a/gui/src/components/modelSelection/ModelSelect.tsx +++ b/gui/src/components/modelSelection/ModelSelect.tsx @@ -10,6 +10,7 @@ import { useContext, useEffect, useRef, useState } from "react"; import { useDispatch } from "react-redux"; import styled from "styled-components"; import { defaultBorderRadius, lightGray, vscInputBackground } from ".."; +import { useAuth } from "../../context/Auth"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import AddModelForm from "../../forms/AddModelForm"; import { useAppSelector } from "../../redux/hooks"; @@ -219,9 +220,7 @@ function ModelSelect() { const buttonRef = useRef(null); const [options, setOptions] = useState([]); const [sortedOptions, setSortedOptions] = useState([]); - const selectedProfileId = useAppSelector( - (store) => store.session.selectedProfileId, - ); + const { selectedProfile } = useAuth(); // Sort so that options without an API key are at the end useEffect(() => { @@ -235,13 +234,15 @@ function ModelSelect() { useEffect(() => { setOptions( - allModels.map((model) => { - return { - value: model.title, - title: modelSelectTitle(model), - apiKey: model.apiKey, - }; - }), + allModels + .filter((m) => !m.roles || m.roles.includes("chat")) + .map((model) => { + return { + value: model.title, + title: modelSelectTitle(model), + apiKey: model.apiKey, + }; + }), ); }, [allModels]); @@ -349,7 +350,7 @@ function ModelSelect() {
- {selectedProfileId === "local" && ( + {selectedProfile?.id === "local" && ( <> ; } else if (assistant.iconUrl) { - return ; + return ; } else { return ; } diff --git a/gui/src/components/modelSelection/platform/AssistantSelect.tsx b/gui/src/components/modelSelection/platform/AssistantSelect.tsx index f1216ac3f..629f0fe14 100644 --- a/gui/src/components/modelSelection/platform/AssistantSelect.tsx +++ b/gui/src/components/modelSelection/platform/AssistantSelect.tsx @@ -1,26 +1,36 @@ import { Popover } from "@headlessui/react"; -import { ChevronDownIcon } from "@heroicons/react/24/outline"; -import { useEffect, useRef } from "react"; +import { ChevronDownIcon, PlusIcon } from "@heroicons/react/24/outline"; +import { ProfileDescription } from "core/config/ConfigHandler"; +import { useContext, useEffect, useRef } from "react"; import { useAuth } from "../../../context/Auth"; +import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { useAppDispatch } from "../../../redux/hooks"; -import { cycleProfile } from "../../../redux/thunks/cycleProfile"; -import { - getFontSize, - isLocalProfile, - isMetaEquivalentKeyPressed, -} from "../../../util"; +import { cycleProfile } from "../../../redux/thunks/profileAndOrg"; +import { getFontSize, isMetaEquivalentKeyPressed } from "../../../util"; import PopoverTransition from "../../mainInput/InputToolbar/PopoverTransition"; -import { AssistantSelectOptions } from "./AssistantSelectOptions"; import AssistantIcon from "./AssistantIcon"; +import { AssistantSelectOptions } from "./AssistantSelectOptions"; import { getProfileDisplayText } from "./utils"; +function AssistantSelectButton(props: { selectedProfile: ProfileDescription }) { + return ( +
+
+ +
+ + {getProfileDisplayText(props.selectedProfile)} + +
+ ); +} + export default function AssistantSelect() { const dispatch = useAppDispatch(); const buttonRef = useRef(null); - const { selectedProfile } = useAuth(); - - const isLocalProfileSelected = - selectedProfile && isLocalProfile(selectedProfile); + const { selectedProfile, selectedOrganization, profiles } = useAuth(); + const ideMessenger = useContext(IdeMessengerContext); useEffect(() => { let lastToggleTime = 0; @@ -48,7 +58,20 @@ export default function AssistantSelect() { }, []); if (!selectedProfile) { - return null; + return ( +
{ + ideMessenger.request("controlPlane/openUrl", { + path: "/new?type=assistant", + orgSlug: selectedOrganization?.slug, + }); + }} + className="text-lightgray hover:bg mb-1 mr-3 flex cursor-pointer items-center gap-1" + style={{ fontSize: `${getFontSize() - 2}px` }} + > + Create your first assistant +
+ ); } return ( @@ -57,21 +80,10 @@ export default function AssistantSelect() { -
-
- -
- - {getProfileDisplayText(selectedProfile)} - -
+
diff --git a/gui/src/components/modelSelection/platform/AssistantSelectOptions.tsx b/gui/src/components/modelSelection/platform/AssistantSelectOptions.tsx index b2604501c..aef66670a 100644 --- a/gui/src/components/modelSelection/platform/AssistantSelectOptions.tsx +++ b/gui/src/components/modelSelection/platform/AssistantSelectOptions.tsx @@ -1,24 +1,25 @@ -import { PlusIcon } from "@heroicons/react/24/outline"; +import { BuildingOfficeIcon, PlusIcon } from "@heroicons/react/24/outline"; +import { ProfileDescription } from "core/config/ConfigHandler"; import { useContext } from "react"; +import { useNavigate } from "react-router-dom"; import { lightGray } from "../.."; import { useAuth } from "../../../context/Auth"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { useAppDispatch } from "../../../redux/hooks"; -import { setDialogMessage, setShowDialog } from "../../../redux/slices/uiSlice"; -import { setProfileId } from "../../../redux/thunks/setProfileId"; +import { selectProfileThunk } from "../../../redux/thunks/profileAndOrg"; import { getFontSize, getMetaKeyLabel, isLocalProfile } from "../../../util"; -import AboutAssistantDialog from "../../dialogs/AboutAssistantDialog"; +import { ROUTES } from "../../../util/navigation"; +import AssistantIcon from "./AssistantIcon"; import { Divider, Option, OptionDiv } from "./shared"; import { getProfileDisplayText } from "./utils"; -import AssistantIcon from "./AssistantIcon"; -import { useNavigate } from "react-router-dom"; -import { ROUTES } from "../../../util/navigation"; interface AssistantSelectOptionsProps { onClose: () => void; } -export function AssistantSelectOptions(props: AssistantSelectOptionsProps) { +export function AssistantSelectOptions({ + onClose, +}: AssistantSelectOptionsProps) { const ideMessenger = useContext(IdeMessengerContext); const { profiles, selectedProfile, selectedOrganization } = useAuth(); const dispatch = useAppDispatch(); @@ -26,83 +27,61 @@ export function AssistantSelectOptions(props: AssistantSelectOptionsProps) { function onNewAssistant() { ideMessenger.post("controlPlane/openUrl", { - path: "platform/new", + path: "new", + orgSlug: selectedOrganization?.slug, }); + onClose(); } - function handleOptionLink(e: React.MouseEvent, profileId: string) { - e.stopPropagation(); - e.preventDefault(); - ideMessenger.post("config/openProfile", { profileId }); - } - - function handleConfigure(e: React.MouseEvent, option: any) { - e.stopPropagation(); - e.preventDefault(); - - if (option.id === "local") { - ideMessenger.post("config/openProfile", { profileId: option.id }); - } else { - props.onClose(); - dispatch(setDialogMessage()); - dispatch(setShowDialog(true)); - } + function handleConfigure(profile: ProfileDescription) { + ideMessenger.post("config/openProfile", { profileId: profile.id }); + onClose(); } function handleClickError(profileId: string) { ideMessenger.post("config/openProfile", { profileId }); + onClose(); + } + + if (!profiles) { + return null; } return (
-
navigate(ROUTES.CONFIG)} - > - {selectedOrganization?.name || "Personal"} Assistants -
-
- {profiles.map((profile, idx) => ( -
); diff --git a/gui/src/components/modelSelection/platform/shared.tsx b/gui/src/components/modelSelection/platform/shared.tsx index bb94188a9..627d39133 100644 --- a/gui/src/components/modelSelection/platform/shared.tsx +++ b/gui/src/components/modelSelection/platform/shared.tsx @@ -54,8 +54,7 @@ interface ModelOptionProps { disabled: boolean; selected: boolean; showConfigure: boolean; - onLink?: (e: any) => void; - onConfigure: (e: any) => void; + onOpenConfig: () => void; onClick: () => void; errors?: ConfigValidationError[]; onClickError?: (e: any) => void; @@ -85,16 +84,15 @@ const StyledExclamationTriangleIcon = styled(IconBase).attrs({ })``; export function Option({ - onConfigure, children, idx, disabled, onClick, showConfigure, - onLink, selected, errors, onClickError, + onOpenConfig, }: ModelOptionProps) { const [hovered, setHovered] = useState(false); @@ -119,16 +117,27 @@ export function Option({
{children}
- {!errors?.length && showConfigure && ( - - )} - {!errors?.length && onLink && ( - - )} - {errors?.length ? ( + {!errors?.length ? ( + showConfigure ? ( + { + e.stopPropagation(); + e.preventDefault(); + onOpenConfig(); + }} + /> + ) : ( + { + e.stopPropagation(); + e.preventDefault(); + onOpenConfig(); + }} + /> + ) + ) : ( <> - ) : null} + )}
diff --git a/gui/src/context/Auth.tsx b/gui/src/context/Auth.tsx index 5154c67ae..03856874a 100644 --- a/gui/src/context/Auth.tsx +++ b/gui/src/context/Auth.tsx @@ -10,29 +10,26 @@ import React, { useMemo, useState, } from "react"; -import { useDispatch } from "react-redux"; -import AccountDialog from "../components/AccountDialog"; import ConfirmationDialog from "../components/dialogs/ConfirmationDialog"; import { useWebviewListener } from "../hooks/useWebviewListener"; -import { useAppSelector } from "../redux/hooks"; +import { useAppDispatch, useAppSelector } from "../redux/hooks"; import { setLastControlServerBetaEnabledStatus } from "../redux/slices/miscSlice"; -import { - selectAvailableProfiles, - setAvailableProfiles, -} from "../redux/slices/sessionSlice"; import { setDialogMessage, setShowDialog } from "../redux/slices/uiSlice"; -import { getLocalStorage, setLocalStorage } from "../util/localStorage"; +import { + updateOrgsThunk, + updateProfilesThunk, +} from "../redux/thunks/profileAndOrg"; import { IdeMessengerContext } from "./IdeMessenger"; interface AuthContextType { session: ControlPlaneSessionInfo | undefined; logout: () => void; login: (useOnboarding: boolean) => Promise; - selectedProfile: ProfileDescription | undefined; - profiles: ProfileDescription[]; + selectedProfile: ProfileDescription | null; + profiles: ProfileDescription[] | null; controlServerBetaEnabled: boolean; organizations: OrganizationDescription[]; - selectedOrganization: OrganizationDescription | undefined; + selectedOrganization: OrganizationDescription | null; } const AuthContext = createContext(undefined); @@ -40,34 +37,31 @@ const AuthContext = createContext(undefined); export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children, }) => { + const dispatch = useAppDispatch(); + const ideMessenger = useContext(IdeMessengerContext); + + // Session const [session, setSession] = useState( undefined, ); - const [organizations, setOrganizations] = useState( - [], - ); - - const ideMessenger = useContext(IdeMessengerContext); - - const selectedOrganizationId = useAppSelector( + // Orgs + const orgs = useAppSelector((store) => store.session.organizations); + const selectedOrgId = useAppSelector( (store) => store.session.selectedOrganizationId, ); - const selectedOrganization = useMemo(() => { - return organizations.find((p) => p.id === selectedOrganizationId); - }, [organizations, selectedOrganizationId]); + if (!selectedOrgId) { + return null; + } + return orgs.find((p) => p.id === selectedOrgId) ?? null; + }, [orgs, selectedOrgId]); - const profiles = useAppSelector(selectAvailableProfiles); - - const selectedProfileId = useAppSelector( - (store) => store.session.selectedProfileId, + // Profiles + const profiles = useAppSelector((store) => store.session.availableProfiles); + const selectedProfile = useAppSelector( + (store) => store.session.selectedProfile, ); - const selectedProfile = useMemo(() => { - return profiles.find((p) => p.id === selectedProfileId); - }, [profiles, selectedProfileId]); - - const dispatch = useDispatch(); const login: AuthContextType["login"] = (useOnboarding: boolean) => { return new Promise((resolve) => { @@ -85,23 +79,6 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ const session = result.content; setSession(session); - // If this is the first time the user has logged in, explain how profiles work - if (!getLocalStorage("shownProfilesIntroduction")) { - dispatch(setShowDialog(true)); - dispatch( - setDialogMessage( - {}} - />, - ), - ); - setLocalStorage("shownProfilesIntroduction", true); - } - resolve(true); }); }); @@ -118,8 +95,8 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ ideMessenger.post("logoutOfControlPlane", undefined); }} onCancel={() => { - dispatch(setDialogMessage()); - dispatch(setShowDialog(true)); + dispatch(setDialogMessage(undefined)); + dispatch(setShowDialog(false)); }} />, ), @@ -128,10 +105,10 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ useWebviewListener("didChangeControlPlaneSessionInfo", async (data) => { setSession(data.sessionInfo); - }); - - useWebviewListener("signInToControlPlane", async () => { - login(false); + // On logout, clear the list of orgs + if (!data.sessionInfo) { + dispatch(updateOrgsThunk([])); + } }); useEffect(() => { @@ -152,10 +129,10 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ ideMessenger.ide .getIdeSettings() .then(({ enableControlServerBeta, continueTestEnvironment }) => { - const enabled = - enableControlServerBeta || continueTestEnvironment !== "none"; - setControlServerBetaEnabled(enabled); - dispatch(setLastControlServerBetaEnabledStatus(enabled)); + setControlServerBetaEnabled(enableControlServerBeta); + dispatch( + setLastControlServerBetaEnabledStatus(enableControlServerBeta), + ); }); }, []); @@ -165,11 +142,11 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ .request("controlPlane/listOrganizations", undefined) .then((result) => { if (result.status === "success") { - setOrganizations(result.content); + dispatch(updateOrgsThunk(result.content)); + } else { + dispatch(updateOrgsThunk([])); } }); - } else { - setOrganizations([]); } }, [session]); @@ -186,19 +163,29 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ ); useEffect(() => { - ideMessenger - .request("config/listProfiles", undefined) - .then( - (result) => - result.status === "success" && - dispatch(setAvailableProfiles(result.content)), - ); + ideMessenger.request("config/listProfiles", undefined).then((result) => { + if (result.status === "success") { + console.log("PROFILES: ", result.content); + dispatch( + updateProfilesThunk({ + profiles: result.content, + selectedProfileId: null, + }), + ); + } + }); }, []); useWebviewListener( "didChangeAvailableProfiles", async (data) => { - dispatch(setAvailableProfiles(data.profiles)); + console.log("AVAILABLE: ", data.profiles, data.selectedProfileId); + dispatch( + updateProfilesThunk({ + profiles: data.profiles, + selectedProfileId: data.selectedProfileId, + }), + ); }, [], ); @@ -212,7 +199,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ selectedProfile, profiles, selectedOrganization, - organizations, + organizations: orgs, controlServerBetaEnabled, }} > diff --git a/gui/src/context/SubmenuContextProviders.tsx b/gui/src/context/SubmenuContextProviders.tsx index 5b6e58fa4..dc69c68d1 100644 --- a/gui/src/context/SubmenuContextProviders.tsx +++ b/gui/src/context/SubmenuContextProviders.tsx @@ -3,18 +3,24 @@ import { ContextProviderName, ContextSubmenuItemWithProvider, } from "core"; -import { createContext } from "react"; import { deduplicateArray } from "core/util"; -import MiniSearch, { SearchResult } from "minisearch"; -import { useCallback, useContext, useEffect, useRef, useState } from "react"; -import { IdeMessengerContext } from "./IdeMessenger"; -import { selectSubmenuContextProviders } from "../redux/selectors"; -import { useWebviewListener } from "../hooks/useWebviewListener"; -import { useAppSelector } from "../redux/hooks"; import { getShortestUniqueRelativeUriPaths, getUriPathBasename, } from "core/util/uri"; +import MiniSearch, { SearchResult } from "minisearch"; +import { + createContext, + useCallback, + useContext, + useEffect, + useRef, + useState, +} from "react"; +import { useWebviewListener } from "../hooks/useWebviewListener"; +import { useAppSelector } from "../redux/hooks"; +import { selectSubmenuContextProviders } from "../redux/selectors"; +import { IdeMessengerContext } from "./IdeMessenger"; const MINISEARCH_OPTIONS = { prefix: true, @@ -246,9 +252,7 @@ export const SubmenuContextProvidersProvider = ({ abortControllers.get(description.title)?.abort(); abortControllers.set(description.title, controller); providersLoading.add(description.title); - console.log( - `Refreshing items for ${description.title} submenu provider`, - ); + const result = await ideMessenger.request( "context/loadSubmenuItems", { @@ -296,7 +300,7 @@ export const SubmenuContextProvidersProvider = ({ setFallbackResults((prev) => ({ ...prev, file: deduplicateArray( - [...lastOpenFilesRef.current, ...(prev.file ?? [])], + [...lastOpenFilesRef.current, ...itemsWithProvider], (a, b) => a.id === b.id, ), })); diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 5ea5c2975..714f4ed75 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -11,9 +11,9 @@ import { updateDocsSuggestions } from "../redux/slices/miscSlice"; import { addContextItemsAtIndex, setInactive, - setSelectedProfileId, } from "../redux/slices/sessionSlice"; import { setTTSActive } from "../redux/slices/uiSlice"; +import { selectProfileThunk } from "../redux/thunks/profileAndOrg"; import { refreshSessionMetadata } from "../redux/thunks/session"; import { streamResponseThunk } from "../redux/thunks/streamResponse"; import { updateFileSymbolsFromHistory } from "../redux/thunks/updateFileSymbols"; @@ -36,7 +36,7 @@ function useSetup() { initial: boolean, result: { result: ConfigResult; - profileId: string; + profileId: string | null; }, ) => { const { result: configResult, profileId } = result; @@ -44,17 +44,9 @@ function useSetup() { return; } hasLoadedConfig.current = true; - // window.postMessage( - // { - // messageType: "refreshSubmenuItems", - // data: { - // providers: "all", - // }, - // }, - // "*", - // ); dispatch(setConfigResult(configResult)); - dispatch(setSelectedProfileId(profileId)); + console.log("selecting 1", profileId); + dispatch(selectProfileThunk(profileId)); // Perform any actions needed with the config if (configResult.config?.ui?.fontSize) { @@ -103,6 +95,7 @@ function useSetup() { useWebviewListener( "configUpdate", async (update) => { + console.log("CONFIG UPDATE: ", update); if (!update) { return; } @@ -124,7 +117,25 @@ function useSetup() { // Override persisted state dispatch(setInactive()); - if (isJetBrains()) { + const jetbrains = isJetBrains(); + for (const colorVar of VSC_THEME_COLOR_VARS) { + if (jetbrains) { + const cached = localStorage.getItem(colorVar); + if (cached) { + document.body.style.setProperty(colorVar, cached); + } + } + + // Remove alpha channel from colors + const value = getComputedStyle(document.documentElement).getPropertyValue( + colorVar, + ); + if (colorVar.startsWith("#") && value.length > 7) { + document.body.style.setProperty(colorVar, value.slice(0, 7)); + } + } + + if (jetbrains) { // Save theme colors to local storage for immediate loading in JetBrains ideMessenger.request("jetbrains/getColors", undefined).then((result) => { if (result.status === "success") { @@ -160,6 +171,17 @@ function useSetup() { } }, []); + useWebviewListener( + "jetbrains/setColors", + async (data) => { + Object.entries(data).forEach(([key, value]) => { + document.body.style.setProperty(key, value); + document.documentElement.style.setProperty(key, value); + }); + }, + [], + ); + useWebviewListener("docs/suggestions", async (data) => { dispatch(updateDocsSuggestions(data)); }); diff --git a/gui/src/index.css b/gui/src/index.css index d51fbf004..b151f3743 100644 --- a/gui/src/index.css +++ b/gui/src/index.css @@ -3,14 +3,7 @@ @tailwind utilities; :root { - --secondary-dark: rgb(37, 37, 38); - --vsc-background: rgb(30, 30, 30); - --button-color: rgb(113, 28, 59); - --button-color-hover: rgba(113, 28, 59, 0.667); - --def-border-radius: 5px; - --vscode-editor-background: rgb(30, 30, 30); - --vscode-editor-foreground: rgb(197, 200, 198); - --vscode-textBlockQuote-background: rgba(255, 255, 255, 1); + --example-var: rgb(30, 30, 30); } html, diff --git a/gui/src/pages/AddNewModel/AddNewModel.tsx b/gui/src/pages/AddNewModel/AddNewModel.tsx index d74cbf25c..f5caa2419 100644 --- a/gui/src/pages/AddNewModel/AddNewModel.tsx +++ b/gui/src/pages/AddNewModel/AddNewModel.tsx @@ -13,10 +13,10 @@ import ModelCard from "../../components/modelSelection/ModelCard"; import Toggle from "../../components/modelSelection/Toggle"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useNavigationListener } from "../../hooks/useNavigationListener"; +import { setDefaultModel } from "../../redux/slices/configSlice"; import { ModelPackage, models } from "./configs/models"; import { providers } from "./configs/providers"; import { CustomModelButton } from "./ConfigureProvider"; -import { setDefaultModel } from "../../redux/slices/configSlice"; const IntroDiv = styled.div` padding: 8px 12px; @@ -39,7 +39,7 @@ const GridDiv = styled.div` */ const modelsByProvider: Record = { "Open AI": [models.gpt4turbo, models.gpt4o, models.gpt35turbo], - Anthropic: [models.claude3Opus, models.claude3Sonnet, models.claude3Haiku], + Anthropic: [models.claude3Opus, models.claude3Sonnet, models.claude35Haiku], Mistral: [ models.codestral, models.mistral7b, @@ -49,7 +49,11 @@ const modelsByProvider: Record = { models.mistralLarge, ], Cohere: [models.commandR, models.commandRPlus], - DeepSeek: [models.deepseekCoderApi, models.deepseekChatApi, models.deepseekReasonerApi], + DeepSeek: [ + models.deepseekCoderApi, + models.deepseekChatApi, + models.deepseekReasonerApi, + ], Gemini: [models.geminiPro, models.gemini15Pro, models.gemini15Flash], "Open Source": [models.llama3Chat, models.mistralOs, models.deepseek], }; diff --git a/gui/src/pages/AddNewModel/configs/models.ts b/gui/src/pages/AddNewModel/configs/models.ts index 3bd4c262d..72303ce17 100644 --- a/gui/src/pages/AddNewModel/configs/models.ts +++ b/gui/src/pages/AddNewModel/configs/models.ts @@ -37,6 +37,56 @@ export interface ModelPackage { } export const models: { [key: string]: ModelPackage } = { + deepseekV3Chat: { + title: "deepseek v3", + description: "A model from deekseek for chat", + refUrl: "", + params: { + title: "deepseek_v3", + model: "deepseek/deepseek_v3", + contextLength: 2048, + }, + icon: "deepseek.png", + dimensions: [ + { + name: "Parameter Count", + description: "The number of parameters in the model", + options: { + r1: { + model: "deepseek/deepseek_v3", + title: "deepseek_v3", + }, + }, + }, + ], + providerOptions: ["novita", "nebius"], + isOpenSource: true, + }, + deepseekR1Chat: { + title: "deepseek r1", + description: "A model from deekseek for chat", + refUrl: "", + params: { + title: "deepseek-r1", + model: "deepseek/deepseek-r1", + contextLength: 2048, + }, + icon: "deepseek.png", + dimensions: [ + { + name: "Parameter Count", + description: "The number of parameters in the model", + options: { + r1: { + model: "deepseek/deepseek-r1", + title: "deepseek-r1", + }, + }, + }, + ], + providerOptions: ["novita", "nebius"], + isOpenSource: true, + }, llama318BChat: { title: "Llama 3.1 8B", description: "A model from Meta, fine-tuned for chat", @@ -55,13 +105,11 @@ export const models: { [key: string]: ModelPackage } = { "8b": { model: "meta-llama/llama-3.1-8b-instruct", title: "Llama3.1-8b", - } + }, }, }, ], - providerOptions: [ - "novita" - ], + providerOptions: ["novita"], isOpenSource: true, }, mistralChat: { @@ -86,9 +134,7 @@ export const models: { [key: string]: ModelPackage } = { }, ], icon: "mistral.png", - providerOptions: [ - "novita", - ], + providerOptions: ["novita"], isOpenSource: true, }, llama31Chat: { @@ -453,7 +499,7 @@ export const models: { [key: string]: ModelPackage } = { contextLength: 8192, }, icon: "meta.png", - providerOptions: ["groq", "scaleway"], + providerOptions: ["groq", "scaleway", "nebius"], isOpenSource: false, }, llama3170bChat: { @@ -466,7 +512,7 @@ export const models: { [key: string]: ModelPackage } = { contextLength: 8192, }, icon: "meta.png", - providerOptions: ["groq", "scaleway"], + providerOptions: ["groq", "scaleway", "nebius"], isOpenSource: false, }, llama31405bChat: { @@ -479,7 +525,7 @@ export const models: { [key: string]: ModelPackage } = { contextLength: 8192, }, icon: "meta.png", - providerOptions: ["groq"], + providerOptions: ["groq", "nebius"], isOpenSource: false, }, llama3170bNemotron: { @@ -505,7 +551,7 @@ export const models: { [key: string]: ModelPackage } = { contextLength: 8192, }, icon: "meta.png", - providerOptions: ["ollama", "groq", "llama.cpp", "sambanova"], + providerOptions: ["ollama", "groq", "llama.cpp", "sambanova", "nebius"], isOpenSource: false, }, llama323bChat: { @@ -941,14 +987,14 @@ export const models: { [key: string]: ModelPackage } = { icon: "anthropic.png", isOpenSource: false, }, - claude3Haiku: { - title: "Claude 3 Haiku", + claude35Haiku: { + title: "Claude 3.5 Haiku", description: - "The third most capable model in the Claude 3 series: fastest and most compact model for near-instant responsiveness", + "The fastest model in the Claude 3.5 series: a compact model for near-instant responsiveness", params: { - model: "claude-3-haiku-20240307", + model: "claude-3-5-haiku-latest", contextLength: 200_000, - title: "Claude 3 Haiku", + title: "Claude 3.5 Haiku", apiKey: "", }, providerOptions: ["anthropic", "free-trial"], @@ -1325,10 +1371,10 @@ export const models: { [key: string]: ModelPackage } = { params: { title: "Qwen 2.5 Coder 32b", model: "qwen2.5-coder-32b", - contextLength: 128_000, + contextLength: 32_000, }, icon: "qwen.png", - providerOptions: ["scaleway"], + providerOptions: ["scaleway", "nebius"], isOpenSource: true, }, grokBeta: { diff --git a/gui/src/pages/AddNewModel/configs/providers.ts b/gui/src/pages/AddNewModel/configs/providers.ts index bf6fe735d..31c0bb2f6 100644 --- a/gui/src/pages/AddNewModel/configs/providers.ts +++ b/gui/src/pages/AddNewModel/configs/providers.ts @@ -111,7 +111,7 @@ export const providers: Partial> = { models.claude35Sonnet, models.claude3Opus, models.claude3Sonnet, - models.claude3Haiku, + models.claude35Haiku, ], apiKeyUrl: "https://console.anthropic.com/account/keys", }, @@ -370,7 +370,11 @@ Select the \`GPT-4o\` model below to complete your provider configuration, but n required: true, }, ], - packages: [models.deepseekCoderApi, models.deepseekChatApi, models.deepseekReasonerApi], + packages: [ + models.deepseekCoderApi, + models.deepseekChatApi, + models.deepseekReasonerApi, + ], apiKeyUrl: "https://platform.deepseek.com/api_keys", }, together: { @@ -427,7 +431,12 @@ Select the \`GPT-4o\` model below to complete your provider configuration, but n }, ...completionParamsInputsConfigs, ], - packages: [models.llama318BChat, models.mistralChat].map((p) => { + packages: [ + models.llama318BChat, + models.mistralChat, + models.deepseekR1Chat, + models.deepseekV3Chat, + ].map((p) => { p.params.contextLength = 4096; return p; }), @@ -680,7 +689,7 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo { ...models.claude35Sonnet, title: "Claude 3.5 Sonnet (trial)" }, { ...models.gpt4o, title: "GPT-4o (trial)" }, { ...models.gpt35turbo, title: "GPT-3.5-Turbo (trial)" }, - { ...models.claude3Haiku, title: "Claude 3 Haiku (trial)" }, + { ...models.claude35Haiku, title: "Claude 3.5 Haiku (trial)" }, models.mixtralTrial, { ...models.gemini15Pro, title: "Gemini 1.5 Pro (trial)" }, { @@ -785,7 +794,7 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo askSage: { title: "Ask Sage", provider: "askSage", - icon: "ask-Sage.png", + icon: "ask-sage.png", description: "The Ask Sage API provides seamless access to LLMs including OpenAI, Anthropic, Meta, Mistral, and more.", longDescription: `To get access to the Ask Sage API, obtain your API key from the [Ask Sage platform](https://chat.asksage.ai/) for all other models.`, @@ -858,6 +867,10 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo icon: "nebius.png", tags: [ModelProviderTags.RequiresApiKey, ModelProviderTags.OpenSource], packages: [ + models.deepseekR1Chat, + models.deepseekV3Chat, + models.QwenQwQ_32b_preview, + models.Qwen25Coder_32b, models.llama318bChat, models.llama3170bChat, models.llama31405bChat, diff --git a/gui/src/pages/More/More.tsx b/gui/src/pages/More/More.tsx index 360a5951f..b9bc3f4d3 100644 --- a/gui/src/pages/More/More.tsx +++ b/gui/src/pages/More/More.tsx @@ -5,16 +5,16 @@ import { } from "@heroicons/react/24/outline"; import { useContext } from "react"; import { useNavigate } from "react-router-dom"; -import KeyboardShortcuts from "./KeyboardShortcuts"; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { useNavigationListener } from "../../hooks/useNavigationListener"; -import { setOnboardingCard } from "../../redux/slices/uiSlice"; -import MoreHelpRow from "./MoreHelpRow"; -import IndexingProgress from "./IndexingProgress"; import DocsIndexingStatuses from "../../components/indexing/DocsIndexingStatuses"; import PageHeader from "../../components/PageHeader"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { useNavigationListener } from "../../hooks/useNavigationListener"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; +import { setOnboardingCard } from "../../redux/slices/uiSlice"; import { saveCurrentSession } from "../../redux/thunks/session"; +import IndexingProgress from "./IndexingProgress"; +import KeyboardShortcuts from "./KeyboardShortcuts"; +import MoreHelpRow from "./MoreHelpRow"; function MorePage() { useNavigationListener(); @@ -100,6 +100,7 @@ function MorePage() { await dispatch( saveCurrentSession({ openNewSession: true, + generateTitle: true, }), ); dispatch(setOnboardingCard({ show: true, activeTab: "Best" })); diff --git a/gui/src/pages/config/ScopeSelect.tsx b/gui/src/pages/config/ScopeSelect.tsx index 773ad180f..c67f68241 100644 --- a/gui/src/pages/config/ScopeSelect.tsx +++ b/gui/src/pages/config/ScopeSelect.tsx @@ -1,79 +1,82 @@ -// gui/src/pages/config/ScopeSelect.tsx - import { Listbox } from "@headlessui/react"; import { - ChevronDownIcon, + BuildingOfficeIcon, + ChevronUpDownIcon, UserCircleIcon, - CubeIcon, } from "@heroicons/react/24/outline"; -import { useState } from "react"; import { useAuth } from "../../context/Auth"; -import { useDispatch } from "react-redux"; -import { setSelectedOrganizationId } from "../../redux/slices/sessionSlice"; +import { useAppDispatch, useAppSelector } from "../../redux/hooks"; +import { selectOrgThunk } from "../../redux/thunks/profileAndOrg"; export function ScopeSelect() { const { organizations, selectedOrganization } = useAuth(); - const [value, setValue] = useState( - selectedOrganization?.id || "personal", + const selectedOrgId = useAppSelector( + (state) => state.session.selectedOrganizationId, ); - const dispatch = useDispatch(); + const dispatch = useAppDispatch(); - const handleChange = (newValue: string) => { - setValue(newValue); - dispatch( - setSelectedOrganizationId(newValue === "personal" ? null : newValue), - ); + const handleChange = (newValue: string | null) => { + dispatch(selectOrgThunk(newValue)); + }; + + const CurScopeEntityFallBackIcon = selectedOrgId + ? BuildingOfficeIcon + : UserCircleIcon; + + const selectedDisplay = selectedOrganization ?? { + name: "Personal", + iconUrl: null, }; - const selectedDisplay = - value === "personal" - ? { name: "Personal", iconUrl: null } - : organizations.find((org) => org.id === value); return ( - +
- +
{selectedDisplay?.iconUrl ? ( ) : ( - + )} {selectedDisplay?.name || "Select Organization"}
-
- -
- Organizations -
- {organizations.map((org) => ( - -
- {org.iconUrl ? ( - - ) : ( - - )} - {org.name} + + {organizations.length > 0 && ( + <> +
+ Organizations
- - ))} + {organizations.map((org) => ( + +
+ {org.iconUrl ? ( + + ) : ( + + )} + {org.name} +
+
+ ))} -
+
+ + )}
diff --git a/gui/src/pages/config/UserSettings.tsx b/gui/src/pages/config/UserSettings.tsx new file mode 100644 index 000000000..6912cd031 --- /dev/null +++ b/gui/src/pages/config/UserSettings.tsx @@ -0,0 +1,322 @@ +import { useContext, useEffect, useState } from "react"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { useAppDispatch, useAppSelector } from "../../redux/hooks"; + +import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline"; +import { + SharedConfigSchema, + modifyContinueConfigWithSharedConfig, +} from "core/config/sharedConfig"; +import { Input } from "../../components"; +import NumberInput from "../../components/gui/NumberInput"; +import { Select } from "../../components/gui/Select"; +import ToggleSwitch from "../../components/gui/Switch"; +import { updateConfig } from "../../redux/slices/configSlice"; +import { getFontSize } from "../../util"; + +function UserSettingsUI() { + const dispatch = useAppDispatch(); + const ideMessenger = useContext(IdeMessengerContext); + + const config = useAppSelector((state) => state.config.config); + + function handleUpdate(sharedConfig: Partial) { + dispatch( + updateConfig(modifyContinueConfigWithSharedConfig(config, sharedConfig)), + ); + ideMessenger.post("config/updateSharedConfig", sharedConfig); + } + + // TODO defaults are in multiple places, should be consolidated and probably not explicit here + const codeWrap = config.ui?.codeWrap ?? false; + const showChatScrollbar = config.ui?.showChatScrollbar ?? false; + const displayRawMarkdown = config.ui?.displayRawMarkdown ?? false; + const disableSessionTitles = config.disableSessionTitles ?? false; + const readResponseTTS = config.experimental?.readResponseTTS ?? false; + + const allowAnonymousTelemetry = config.allowAnonymousTelemetry ?? true; + const disableIndexing = config.disableIndexing ?? false; + + const useAutocompleteCache = config.tabAutocompleteOptions?.useCache ?? false; + const useChromiumForDocsCrawling = + config.experimental?.useChromiumForDocsCrawling ?? false; + const codeBlockToolbarPosition = config.ui?.codeBlockToolbarPosition ?? "top"; + const useAutocompleteMultilineCompletions = + config.tabAutocompleteOptions?.multilineCompletions ?? "auto"; + const fontSize = getFontSize(); + + // Disable autocomplete + const disableAutocompleteInFiles = ( + config.tabAutocompleteOptions?.disableInFiles ?? [] + ).join(", "); + const [formDisableAutocomplete, setFormDisableAutocomplete] = useState( + disableAutocompleteInFiles, + ); + const cancelChangeDisableAutocomplete = () => { + setFormDisableAutocomplete(disableAutocompleteInFiles); + }; + const handleDisableAutocompleteSubmit = () => { + handleUpdate({ + disableAutocompleteInFiles: formDisableAutocomplete + .split(",") + .map((val) => val.trim()) + .filter((val) => !!val), + }); + }; + + useEffect(() => { + // Necessary so that reformatted/trimmed values don't cause dirty state + setFormDisableAutocomplete(disableAutocompleteInFiles); + }, [disableAutocompleteInFiles]); + + // Workspace prompts + const promptPath = config.experimental?.promptPath || ""; + const [formPromptPath, setFormPromptPath] = useState(promptPath); + const cancelChangePromptPath = () => { + setFormPromptPath(promptPath); + }; + const handleSubmitPromptPath = () => { + handleUpdate({ + promptPath: formPromptPath || "", + }); + }; + + useEffect(() => { + // Necessary so that reformatted/trimmed values don't cause dirty state + setFormPromptPath(promptPath); + }, [promptPath]); + + return ( +
+
+

User settings

+
+ +
+ + handleUpdate({ + codeWrap: !codeWrap, + }) + } + text="Wrap Codeblocks" + /> + + handleUpdate({ + displayRawMarkdown: !displayRawMarkdown, + }) + } + text="Display Raw Markdown" + /> + + handleUpdate({ + allowAnonymousTelemetry: !allowAnonymousTelemetry, + }) + } + text="Allow Anonymous Telemetry" + /> + + handleUpdate({ + disableIndexing: !disableIndexing, + }) + } + text="Disable Indexing" + /> + + + handleUpdate({ + disableSessionTitles: !disableSessionTitles, + }) + } + text="Disable Session Titles" + /> + + handleUpdate({ + readResponseTTS: !readResponseTTS, + }) + } + text="Response Text to Speech" + /> + + + handleUpdate({ + showChatScrollbar: !showChatScrollbar, + }) + } + text="Show Chat Scrollbar" + /> + + + handleUpdate({ + useAutocompleteCache: !useAutocompleteCache, + }) + } + text="Use Autocomplete Cache" + /> + + + handleUpdate({ + useChromiumForDocsCrawling: !useChromiumForDocsCrawling, + }) + } + text="Use Chromium for Docs Crawling" + /> + + + + + + + +
{ + e.preventDefault(); + handleSubmitPromptPath(); + }} + > +
+ Workspace prompts path +
+ { + setFormPromptPath(e.target.value); + }} + /> +
+ {formPromptPath !== promptPath ? ( + <> +
+ +
+
+ +
+ + ) : ( +
+ +
+ )} +
+
+
+
+
{ + e.preventDefault(); + handleDisableAutocompleteSubmit(); + }} + > +
+ Disable autocomplete in files +
+ { + setFormDisableAutocomplete(e.target.value); + }} + /> +
+ {formDisableAutocomplete !== disableAutocompleteInFiles ? ( + <> +
+ +
+
+ +
+ + ) : ( +
+ +
+ )} +
+
+
+ + Comma-separated list of path matchers + +
+
+
+ ); +} + +export default UserSettingsUI; diff --git a/gui/src/pages/config/index.tsx b/gui/src/pages/config/index.tsx index 5f9cf3d09..56fe464f7 100644 --- a/gui/src/pages/config/index.tsx +++ b/gui/src/pages/config/index.tsx @@ -1,23 +1,16 @@ -import { useContext, useEffect, useState } from "react"; +import { Listbox, Transition } from "@headlessui/react"; +import { ChevronUpDownIcon, PlusCircleIcon } from "@heroicons/react/24/outline"; +import { Fragment, useContext, useEffect, useState } from "react"; import { useNavigate } from "react-router-dom"; +import { SecondaryButton } from "../../components"; import PageHeader from "../../components/PageHeader"; +import { useAuth } from "../../context/Auth"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useNavigationListener } from "../../hooks/useNavigationListener"; -import { useAppDispatch, useAppSelector } from "../../redux/hooks"; - -import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline"; -import { - SharedConfigSchema, - modifyContinueConfigWithSharedConfig, -} from "core/config/sharedConfig"; -import { Input, SecondaryButton } from "../../components"; -import NumberInput from "../../components/gui/NumberInput"; -import { Select } from "../../components/gui/Select"; -import ToggleSwitch from "../../components/gui/Switch"; -import { useAuth } from "../../context/Auth"; -import { updateConfig } from "../../redux/slices/configSlice"; -import { getFontSize } from "../../util"; +import { useAppDispatch } from "../../redux/hooks"; +import { selectProfileThunk } from "../../redux/thunks/profileAndOrg"; import { ScopeSelect } from "./ScopeSelect"; +import UserSettingsUI from "./UserSettings"; function ConfigPage() { useNavigationListener(); @@ -25,82 +18,28 @@ function ConfigPage() { const navigate = useNavigate(); const ideMessenger = useContext(IdeMessengerContext); - const { selectedProfile, selectedOrganization, session } = useAuth(); - const config = useAppSelector((state) => state.config.config); + const { + session, + logout, + login, + profiles, + selectedProfile, + controlServerBetaEnabled, + selectedOrganization, + } = useAuth(); - function handleUpdate(sharedConfig: Partial) { - dispatch( - updateConfig(modifyContinueConfigWithSharedConfig(config, sharedConfig)), - ); - ideMessenger.post("config/updateSharedConfig", sharedConfig); - } - - const codeWrap = config.ui?.codeWrap ?? false; - const showChatScrollbar = config.ui?.showChatScrollbar ?? false; - const displayRawMarkdown = config.ui?.displayRawMarkdown ?? false; - const disableSessionTitles = config.disableSessionTitles ?? false; - const readResponseTTS = config.experimental?.readResponseTTS ?? false; - - const allowAnonymousTelemetry = config.allowAnonymousTelemetry ?? true; - const disableIndexing = config.disableIndexing ?? false; - - const useAutocompleteCache = config.tabAutocompleteOptions?.useCache ?? false; - const useChromiumForDocsCrawling = - config.experimental?.useChromiumForDocsCrawling ?? false; - const codeBlockToolbarPosition = config.ui?.codeBlockToolbarPosition ?? "top"; - const useAutocompleteMultilineCompletions = - config.tabAutocompleteOptions?.multilineCompletions ?? "auto"; - const fontSize = getFontSize(); + const changeProfileId = (id: string) => { + console.log("selecting 2", id); + dispatch(selectProfileThunk(id)); + }; const [hubEnabled, setHubEnabled] = useState(false); - useEffect(() => { ideMessenger.ide.getIdeSettings().then(({ continueTestEnvironment }) => { setHubEnabled(continueTestEnvironment === "production"); }); }, [ideMessenger]); - // Disable autocomplete - const disableAutocompleteInFiles = ( - config.tabAutocompleteOptions?.disableInFiles ?? [] - ).join(", "); - const [formDisableAutocomplete, setFormDisableAutocomplete] = useState( - disableAutocompleteInFiles, - ); - const cancelChangeDisableAutocomplete = () => { - setFormDisableAutocomplete(disableAutocompleteInFiles); - }; - const handleDisableAutocompleteSubmit = () => { - handleUpdate({ - disableAutocompleteInFiles: formDisableAutocomplete - .split(",") - .map((val) => val.trim()) - .filter((val) => !!val), - }); - }; - - useEffect(() => { - // Necessary so that reformatted/trimmed values don't cause dirty state - setFormDisableAutocomplete(disableAutocompleteInFiles); - }, [disableAutocompleteInFiles]); - - // Workspace prompts - const promptPath = config.experimental?.promptPath || ""; - const [formPromptPath, setFormPromptPath] = useState(promptPath); - const cancelChangePromptPath = () => { - setFormPromptPath(promptPath); - }; - const handleSubmitPromptPath = () => { - handleUpdate({ - promptPath: formPromptPath || "", - }); - }; - - useEffect(() => { - // Necessary so that reformatted/trimmed values don't cause dirty state - setFormPromptPath(promptPath); - }, [promptPath]); - function handleOpenConfig() { if (!selectedProfile) { return; @@ -110,295 +49,139 @@ function ConfigPage() { }); } - if (!selectedProfile) { - return ( -
- navigate("/")} title="Chat" /> -
-
-

Continue Config

-
-

No config profile selected

-
-
- ); - } + // NOTE Hub takes priority over Continue for Teams + // Since teams will be moving to hub, not vice versa return (
navigate("/")} title="Chat" />
- {hubEnabled && !!session && ( -
-
-

Account

- {selectedOrganization?.name && ( - - You are currently signed in to{" "} - - {selectedOrganization?.name} +
+
+

Account

+ {!session ? ( +
+ You are not signed in. + login(false)}> + Sign in + +
+ ) : ( +
+ {hubEnabled ? ( + // Hub: show org selector +
+ {`Organization`} + +
+ ) : ( + // Continue for teams: show org text +
You are using Continue for Teams
+ )} +
+ + {session.account.label === "" + ? "Signed in" + : `Signed in as ${session.account.label}`} - - )} + {`Sign out`} +
+
+ )} +
+
+ +
+
+

Configuration

+ {profiles ? ( + <> + + {({ open }) => ( +
+ + + {selectedProfile?.title ?? "No Assistant Selected"} + +
+
+
+ + + + {profiles.map((option, idx) => ( + + + {option.title} + + + ))} + {hubEnabled && ( + { + ideMessenger.post("controlPlane/openUrl", { + path: "new", + orgSlug: selectedOrganization?.slug, + }); + }} + > + + + Create new Assistant + + + )} + + +
+ )} +
+ {selectedProfile && ( + + {selectedProfile.id === "local" + ? "Open Config File" + : hubEnabled + ? "Open Assistant" + : "Open Workspace"} + + )} + + ) : ( +
Loading...
+ )} +
+
+ {!controlServerBetaEnabled || hubEnabled ? ( +
+
+
- -
- )} - -
-

Configuration

- - - Open configuration file - -
- -
-
-

User settings

-
- -
- - handleUpdate({ - codeWrap: !codeWrap, - }) - } - text="Wrap Codeblocks" - /> - - handleUpdate({ - displayRawMarkdown: !displayRawMarkdown, - }) - } - text="Display Raw Markdown" - /> - - handleUpdate({ - allowAnonymousTelemetry: !allowAnonymousTelemetry, - }) - } - text="Allow Anonymous Telemetry" - /> - - handleUpdate({ - disableIndexing: !disableIndexing, - }) - } - text="Disable Indexing" - /> - - - handleUpdate({ - disableSessionTitles: !disableSessionTitles, - }) - } - text="Disable Session Titles" - /> - - handleUpdate({ - readResponseTTS: !readResponseTTS, - }) - } - text="Response Text to Speech" - /> - - - handleUpdate({ - showChatScrollbar: !showChatScrollbar, - }) - } - text="Show Chat Scrollbar" - /> - - - handleUpdate({ - useAutocompleteCache: !useAutocompleteCache, - }) - } - text="Use Autocomplete Cache" - /> - - - handleUpdate({ - useChromiumForDocsCrawling: !useChromiumForDocsCrawling, - }) - } - text="Use Chromium for Docs Crawling" - /> - - - - - - - - -
{ - e.preventDefault(); - handleSubmitPromptPath(); - }} - > -
- Workspace prompts path -
- { - setFormPromptPath(e.target.value); - }} - /> -
- {formPromptPath !== promptPath ? ( - <> -
- -
-
- -
- - ) : ( -
- -
- )} -
-
-
-
-
{ - e.preventDefault(); - handleDisableAutocompleteSubmit(); - }} - > -
- Disable autocomplete in files -
- { - setFormDisableAutocomplete(e.target.value); - }} - /> -
- {formDisableAutocomplete !== disableAutocompleteInFiles ? ( - <> -
- -
-
- -
- - ) : ( -
- -
- )} -
-
-
- - Comma-separated list of path matchers - -
-
-
+ ) : null}
); diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index c91781417..55027c041 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -21,6 +21,7 @@ import { } from "../../components"; import CodeToEditCard from "../../components/CodeToEditCard"; import FeedbackDialog from "../../components/dialogs/FeedbackDialog"; +import FreeTrialOverDialog from "../../components/dialogs/FreeTrialOverDialog"; import { useFindWidget } from "../../components/find/FindWidget"; import TimelineItem from "../../components/gui/TimelineItem"; import ChatIndexingPeeks from "../../components/indexing/ChatIndexingPeeks"; @@ -28,6 +29,7 @@ import ContinueInputBox from "../../components/mainInput/ContinueInputBox"; import { NewSessionButton } from "../../components/mainInput/NewSessionButton"; import resolveEditorContent from "../../components/mainInput/resolveInput"; import { TutorialCard } from "../../components/mainInput/TutorialCard"; +import AssistantSelect from "../../components/modelSelection/platform/AssistantSelect"; import { OnboardingCard, useOnboardingCard, @@ -40,7 +42,7 @@ import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useTutorialCard } from "../../hooks/useTutorialCard"; import { useWebviewListener } from "../../hooks/useWebviewListener"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; -import { selectUsePlatform } from "../../redux/selectors"; +import { selectUseHub } from "../../redux/selectors"; import { selectCurrentToolCall } from "../../redux/selectors/selectCurrentToolCall"; import { selectDefaultModel } from "../../redux/slices/configSlice"; import { submitEdit } from "../../redux/slices/editModeState"; @@ -76,8 +78,6 @@ import ConfigErrorIndicator from "./ConfigError"; import { ToolCallDiv } from "./ToolCallDiv"; import { ToolCallButtons } from "./ToolCallDiv/ToolCallButtonsDiv"; import ToolOutput from "./ToolCallDiv/ToolOutput"; -import FreeTrialOverDialog from "../../components/dialogs/FreeTrialOverDialog"; -import AssistantSelect from "../../components/modelSelection/platform/AssistantSelect"; const StopButton = styled.div` background-color: ${vscBackground}; @@ -222,7 +222,7 @@ export function Chat() { selectIsSingleRangeEditOrInsertion, ); const lastSessionId = useAppSelector((state) => state.session.lastSessionId); - const usePlatform = useAppSelector(selectUsePlatform); + const useHub = useAppSelector(selectUseHub); useEffect(() => { // Cmd + Backspace to delete current step @@ -365,9 +365,11 @@ export function Chat() { useAutoScroll(stepsDivRef, history); + const showPageHeader = isInEditMode || useHub; + return ( <> - {(isInEditMode || usePlatform) && ( + {showPageHeader && ( } + rightContent={useHub && } /> )} @@ -388,7 +390,7 @@ export function Chat() { 0 ? "flex-1" : ""}`} + className={`overflow-y-scroll ${showPageHeader ? "" : "pt-[8px]"} ${showScrollbar ? "thin-scrollbar" : "no-scrollbar"} ${history.length > 0 ? "flex-1" : ""}`} > {highlights} {history.map((item, index: number) => ( @@ -565,7 +567,7 @@ export function Chat() { <> {onboardingCard.show && (
- {usePlatform ? ( + {useHub ? ( ) : ( diff --git a/gui/src/pages/gui/StreamError.tsx b/gui/src/pages/gui/StreamError.tsx index ca3bc04bc..2a8465c30 100644 --- a/gui/src/pages/gui/StreamError.tsx +++ b/gui/src/pages/gui/StreamError.tsx @@ -51,7 +51,8 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => { typeof error["message"] === "string" ) { message = error["message"]; - const status = message?.split(" ")[0]; + const parts = message?.split(" ") ?? []; + const status = parts[0] === "HTTP" ? parts[1] : parts[0]; if (status) { const code = Number(status); if (!Number.isNaN(statusCode)) { diff --git a/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx b/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx index 41ce2498e..503f54cb4 100644 --- a/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx @@ -46,6 +46,10 @@ export function ThreadDiv(props: ThreadDivProps) { return rendered; } + const tool = availableTools.find( + (tool) => props.toolCall.function?.name === tool.function.name, + ); + return ( @@ -60,13 +64,10 @@ export function ThreadDiv(props: ThreadDivProps) { > {props.icon}
- Continue wants to{" "} - {renderWouldLikeToMessage( - availableTools.find( - (tool) => props.toolCall.function?.name === tool.function.name, - ), - props.toolCallState, + {tool?.faviconUrl && ( + )} + Continue wants to {renderWouldLikeToMessage(tool, props.toolCallState)} {props.children} diff --git a/gui/src/redux/selectors/index.ts b/gui/src/redux/selectors/index.ts index 737e865d3..2097dbce8 100644 --- a/gui/src/redux/selectors/index.ts +++ b/gui/src/redux/selectors/index.ts @@ -43,7 +43,7 @@ export const selectUseActiveFile = createSelector( (defaultContext) => defaultContext?.includes("activeFile" as any), ); -export const selectUsePlatform = createSelector( +export const selectUseHub = createSelector( [(state: RootState) => state.config.config.usePlatform], (usePlatform) => usePlatform, ); diff --git a/gui/src/redux/slices/configSlice.ts b/gui/src/redux/slices/configSlice.ts index e8939e81d..604f583e4 100644 --- a/gui/src/redux/slices/configSlice.ts +++ b/gui/src/redux/slices/configSlice.ts @@ -26,7 +26,7 @@ const initialState: ConfigState = { contextProviders: [], models: [], tools: [], - usePlatform: false, + usePlatform: true, }, }; diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index fa6cfb03c..dd8f0b5bb 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -22,6 +22,7 @@ import { ToolCallState, } from "core"; import { ProfileDescription } from "core/config/ConfigHandler"; +import { OrganizationDescription } from "core/config/ProfileLifecycleManager"; import { NEW_SESSION_TITLE } from "core/util/constants"; import { incrementalParseJson } from "core/util/incrementalParseJson"; import { renderChatMessage } from "core/util/messageContent"; @@ -30,7 +31,6 @@ import { v4 as uuidv4 } from "uuid"; import { RootState } from "../store"; import { streamResponseThunk } from "../thunks/streamResponse"; import { findCurrentToolCall } from "../util"; -import { OrganizationDescription } from "core/config/ProfileLifecycleManager"; // We need this to handle reorderings (e.g. a mid-array deletion) of the messages array. // The proper fix is adding a UUID to all chat messages, but this is the temp workaround. @@ -45,10 +45,11 @@ type SessionState = { isStreaming: boolean; title: string; id: string; - selectedProfileId: string; - availableProfiles: ProfileDescription[]; + /** null indicates loading state */ + availableProfiles: ProfileDescription[] | null; + selectedProfile: ProfileDescription | null; + organizations: OrganizationDescription[]; selectedOrganizationId: string | null; - availableOrganizations: OrganizationDescription[]; streamAborter: AbortController; codeToEdit: CodeToEdit[]; curCheckpointIndex: number; @@ -88,23 +89,10 @@ const initialState: SessionState = { isStreaming: false, title: NEW_SESSION_TITLE, id: uuidv4(), - selectedProfileId: "local", - availableProfiles: [ - { - id: "local", - title: "Local", - errors: undefined, - profileType: "local", - fullSlug: { - ownerSlug: "", - packageSlug: "", - versionSlug: "", - }, - iconUrl: "", - }, - ], + selectedProfile: null, + availableProfiles: null, + organizations: [], selectedOrganizationId: "", - availableOrganizations: [], curCheckpointIndex: 0, streamAborter: new AbortController(), codeToEdit: [], @@ -191,13 +179,13 @@ export const sessionSlice = createSlice({ { payload, }: PayloadAction<{ - index?: number; + index: number; editorState: JSONContent; }>, ) => { const { index, editorState } = payload; - if (typeof index === "number" && index < state.history.length) { + if (state.history.length && index < state.history.length) { // Resubmission - update input message, truncate history after resubmit with new empty response message if (index % 2 === 1) { console.warn( @@ -208,6 +196,7 @@ export const sessionSlice = createSlice({ historyItem.message.content = ""; // IMPORTANT - this is quickly updated by resolveEditorContent based on editor state prior to streaming historyItem.editorState = payload.editorState; + historyItem.contextItems = []; state.history = state.history.slice(0, index + 1).concat({ message: { @@ -260,7 +249,7 @@ export const sessionSlice = createSlice({ }>, ) => { const { index, updates } = payload; - if (!state.history[index]) { + if (index !== 0 && !state.history[index]) { console.error( `attempting to update history item at nonexistent index ${index}`, updates, @@ -544,49 +533,34 @@ export const sessionSlice = createSlice({ state.history[state.history.length - 1].contextItems = contextItems; }, - setSelectedProfileId: (state, { payload }: PayloadAction) => { - return { - ...state, - selectedProfileId: payload, - }; + // Important: these reducers don't handle selected profile/organization fallback logic + // That is done in thunks + setSelectedProfile: ( + state, + { payload }: PayloadAction, + ) => { + state.selectedProfile = payload; }, setAvailableProfiles: ( state, - { payload }: PayloadAction, + { payload }: PayloadAction, ) => { - return { - ...state, - availableProfiles: payload, - selectedProfileId: payload.find( - (profile) => profile.id === state.selectedProfileId, - ) - ? state.selectedProfileId - : payload[0]?.id, - }; + state.availableProfiles = payload; + }, + setOrganizations: ( + state, + { payload }: PayloadAction, + ) => { + state.organizations = payload; }, setSelectedOrganizationId: ( state, { payload }: PayloadAction, ) => { - return { - ...state, - selectedOrganizationId: payload, - }; - }, - setAvailableOrganizations: ( - state, - { payload }: PayloadAction, - ) => { - return { - ...state, - availableOrganizations: payload, - selectedOrganizationId: payload.find( - (org) => org.id === state.selectedOrganizationId, - ) - ? state.selectedOrganizationId - : payload[0]?.id, - }; + state.selectedOrganizationId = payload; }, + /////////////// + updateCurCheckpoint: ( state, { payload }: PayloadAction<{ filepath: string; content: string }>, @@ -712,12 +686,6 @@ export const sessionSlice = createSlice({ selectHasCodeToEdit: (state) => { return state.codeToEdit.length > 0; }, - selectAvailableProfiles: (state) => { - return state.availableProfiles; - }, - selectAvailableOrganizations: (state) => { - return state.availableOrganizations; - }, }, extraReducers: (builder) => { addPassthroughCases(builder, [streamResponseThunk]); @@ -768,8 +736,6 @@ export const { updateHistoryItemAtIndex, clearLastEmptyResponse, setMainEditorContentTrigger, - setSelectedProfileId, - setSelectedOrganizationId, deleteMessage, setIsGatheringContext, updateCurCheckpoint, @@ -782,8 +748,6 @@ export const { removeCodeToEdit, setCalling, cancelToolCall, - setAvailableProfiles, - setAvailableOrganizations, acceptToolCall, setToolGenerated, setToolCallOutput, @@ -793,6 +757,11 @@ export const { updateSessionMetadata, deleteSessionMetadata, setNewestCodeblocksForInput, + + setAvailableProfiles, + setSelectedProfile, + setOrganizations, + setSelectedOrganizationId, } = sessionSlice.actions; export const { @@ -800,8 +769,6 @@ export const { selectIsInEditMode, selectIsSingleRangeEditOrInsertion, selectHasCodeToEdit, - selectAvailableProfiles, - selectAvailableOrganizations, } = sessionSlice.selectors; export default sessionSlice.reducer; diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index d716a6446..8cfb8f937 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -1,5 +1,4 @@ import { combineReducers, configureStore } from "@reduxjs/toolkit"; -import miscReducer from "./slices/miscSlice"; import { createMigrate, MigrationManifest, @@ -10,9 +9,10 @@ import { createFilter } from "redux-persist-transform-filter"; import autoMergeLevel2 from "redux-persist/lib/stateReconciler/autoMergeLevel2"; import storage from "redux-persist/lib/storage"; import { IdeMessenger, IIdeMessenger } from "../context/IdeMessenger"; -import editModeStateReducer from "./slices/editModeState"; import configReducer from "./slices/configSlice"; +import editModeStateReducer from "./slices/editModeState"; import indexingReducer from "./slices/indexingSlice"; +import miscReducer from "./slices/miscSlice"; import sessionReducer from "./slices/sessionSlice"; import uiReducer from "./slices/uiSlice"; @@ -35,7 +35,7 @@ const saveSubsetFilters = [ "history", "sessionId", "selectedOrganizationId", - "selectedProfileId", + "selectedProfile", ]), // Don't persist any of the edit state for now createFilter("editModeState", []), diff --git a/gui/src/redux/thunks/callTool.ts b/gui/src/redux/thunks/callTool.ts index a59a1d119..0bd367587 100644 --- a/gui/src/redux/thunks/callTool.ts +++ b/gui/src/redux/thunks/callTool.ts @@ -1,4 +1,4 @@ -import { createAsyncThunk } from "@reduxjs/toolkit"; +import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; import { acceptToolCall, @@ -23,8 +23,7 @@ export const callTool = createAsyncThunk( } if (!state.config.defaultModelTitle) { - console.error("Cannot call tools, no model selected"); - return; + throw new Error("No model selected"); } dispatch(setCalling()); @@ -40,12 +39,17 @@ export const callTool = createAsyncThunk( dispatch(acceptToolCall()); // Send to the LLM to continue the conversation - dispatch( + const response = await dispatch( streamResponseAfterToolCall({ toolCallId: toolCallState.toolCall.id, toolOutput: contextItems, }), ); + unwrapResult(response); + } else { + throw new Error( + `Failed to call tool ${toolCallState.toolCall.function.name}: ${result.error}`, + ); } }, ); diff --git a/gui/src/redux/thunks/cycleProfile.ts b/gui/src/redux/thunks/cycleProfile.ts deleted file mode 100644 index 0ee548c31..000000000 --- a/gui/src/redux/thunks/cycleProfile.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { createAsyncThunk } from "@reduxjs/toolkit"; -import { ThunkApiType } from "../store"; -import { setProfileId } from "./setProfileId"; - -export const cycleProfile = createAsyncThunk( - "profile/cycle", - async (_, { dispatch, getState, extra }) => { - const state = getState(); - const profileIds = state.session.availableProfiles.map( - (profile) => profile.id, - ); - const curIndex = profileIds.indexOf(state.session.selectedProfileId); - const nextIndex = (curIndex + 1) % profileIds.length; - const nextId = profileIds[nextIndex]; - dispatch(setProfileId(nextId)); - - extra.ideMessenger.post("didChangeSelectedProfile", { - id: nextId, - }); - }, -); diff --git a/gui/src/redux/thunks/gatherContext.ts b/gui/src/redux/thunks/gatherContext.ts index 0883ec3eb..6b1f11db4 100644 --- a/gui/src/redux/thunks/gatherContext.ts +++ b/gui/src/redux/thunks/gatherContext.ts @@ -6,10 +6,10 @@ import { MessageContent, RangeInFile, } from "core"; +import * as URI from "uri-js"; import resolveEditorContent from "../../components/mainInput/resolveInput"; -import { ThunkApiType } from "../store"; import { selectDefaultModel } from "../slices/configSlice"; -import { findUriInDirs, getUriPathBasename } from "core/util/uri"; +import { ThunkApiType } from "../store"; export const gatherContext = createAsyncThunk< { @@ -34,7 +34,7 @@ export const gatherContext = createAsyncThunk< const defaultContextProviders = state.config.config.experimental?.defaultContext ?? []; - if (!state.config.defaultModelTitle) { + if (!defaultModel) { console.error( "gatherContext thunk: Cannot gather context, no model selected", ); @@ -49,46 +49,52 @@ export const gatherContext = createAsyncThunk< ideMessenger: extra.ideMessenger, defaultContextProviders, dispatch, - selectedModelTitle: state.config.defaultModelTitle, + selectedModelTitle: defaultModel.title, }); // Automatically use currently open file if (!modifiers.noContext) { const usingFreeTrial = defaultModel?.provider === "free-trial"; - const currentFile = await extra.ideMessenger.ide.getCurrentFile(); - if (currentFile) { - let currentFileContents = currentFile.contents; - if (usingFreeTrial) { - currentFileContents = currentFile.contents - .split("\n") - .slice(0, 1000) - .join("\n"); - } - if ( - !selectedContextItems.find( - (item) => item.uri?.value === currentFile.path, - ) - ) { + const currentFileResponse = await extra.ideMessenger.request( + "context/getContextItems", + { + name: "currentFile", + query: "non-mention-usage", + fullInput: "", + selectedCode: [], + selectedModelTitle: defaultModel.title, + }, + ); + if (currentFileResponse.status === "success") { + const items = currentFileResponse.content; + if (items.length > 0) { + const currentFile = items[0]; + const uri = currentFile.uri?.value; + // don't add the file if it's already in the context items - selectedContextItems.unshift({ - content: `The following file is currently open. Don't reference it if it's not relevant to the user's message.\n\n\`\`\`${ - findUriInDirs( - currentFile.path, - await extra.ideMessenger.ide.getWorkspaceDirs(), - ).relativePathOrBasename - }\n${currentFileContents}\n\`\`\``, - name: `Active file: ${getUriPathBasename(currentFile.path)}`, - description: currentFile.path, - id: { - itemId: currentFile.path, + if ( + uri && + !selectedContextItems.find( + (item) => item.uri?.value && URI.equal(item.uri.value, uri), + ) + ) { + // Limit to 1000 lines if using free trial + if (usingFreeTrial) { + currentFile.content = currentFile.content + .split("\n") + .slice(0, 1000) + .join("\n"); + if (!currentFile.content.endsWith("```")) { + currentFile.content += "\n```"; + } + } + currentFile.id = { providerTitle: "file", - }, - uri: { - type: "file", - value: currentFile.path, - }, - }); + itemId: uri, + }; + selectedContextItems.unshift(currentFile); + } } } } diff --git a/gui/src/redux/thunks/profileAndOrg.ts b/gui/src/redux/thunks/profileAndOrg.ts new file mode 100644 index 000000000..6632b77ab --- /dev/null +++ b/gui/src/redux/thunks/profileAndOrg.ts @@ -0,0 +1,150 @@ +import { createAsyncThunk } from "@reduxjs/toolkit"; +import { ProfileDescription } from "core/config/ConfigHandler"; +import { OrganizationDescription } from "core/config/ProfileLifecycleManager"; +import { + setAvailableProfiles, + setOrganizations, + setSelectedOrganizationId, + setSelectedProfile, +} from "../slices/sessionSlice"; +import { ThunkApiType } from "../store"; + +export const selectProfileThunk = createAsyncThunk< + void, + string | null, + ThunkApiType +>("profiles/select", async (id, { dispatch, extra, getState }) => { + const state = getState(); + + if (state.session.availableProfiles === null) { + // Currently in loading state + return; + } + + const initialId = state.session.selectedProfile?.id; + + let newId = id; + + console.log( + "Running Thunk: ", + initialId, + newId, + state.session.availableProfiles, + ); + // If no profiles, force clear + if (state.session.availableProfiles.length === 0) { + newId = null; + } else { + // If new id doesn't match an existing profile, clear it + if (newId) { + if (!state.session.availableProfiles.find((p) => p.id === newId)) { + newId = null; + } + } + if (!newId) { + // At this point if null ID and there ARE profiles, + // Fallback to a profile, prioritizing the first in the list + newId = state.session.availableProfiles[0].id; + } + } + + // Only update if there's a change + console.log( + "update selected profile?", + newId, + initialId, + state.session.availableProfiles, + ); + if ((newId ?? null) !== (initialId ?? null)) { + dispatch( + setSelectedProfile( + state.session.availableProfiles.find((p) => p.id === newId) ?? null, + ), + ); + extra.ideMessenger.post("didChangeSelectedProfile", { + id: newId, + }); + } +}); + +export const cycleProfile = createAsyncThunk( + "profiles/cycle", + async (_, { dispatch, getState }) => { + const state = getState(); + + if (state.session.availableProfiles === null) { + return; + } + + const profileIds = state.session.availableProfiles.map( + (profile) => profile.id, + ); + // In case of no profiles just does nothing + if (profileIds.length === 0) { + return; + } + let nextId = profileIds[0]; + if (state.session.selectedProfile) { + const curIndex = profileIds.indexOf(state.session.selectedProfile?.id); + const nextIndex = (curIndex + 1) % profileIds.length; + nextId = profileIds[nextIndex]; + } + await dispatch(selectProfileThunk(nextId)); + }, +); + +export const updateProfilesThunk = createAsyncThunk< + void, + { profiles: ProfileDescription[] | null; selectedProfileId: string | null }, + ThunkApiType +>("profiles/update", async (data, { dispatch, extra, getState }) => { + const { profiles, selectedProfileId } = data; + + dispatch(setAvailableProfiles(profiles)); + + // This will trigger reselection if needed + console.log("selecting 3", selectedProfileId); + dispatch(selectProfileThunk(selectedProfileId)); +}); + +export const selectOrgThunk = createAsyncThunk< + void, + string | null, + ThunkApiType +>("session/selectOrg", async (id, { dispatch, extra, getState }) => { + const state = getState(); + const initialId = state.session.selectedOrganizationId; + let newId = id; + + // If no orgs, force clear + if (state.session.organizations.length === 0) { + newId = null; + } else if (newId) { + // If new id doesn't match an existing org, clear it + if (!state.session.organizations.find((o) => o.id === newId)) { + newId = null; + } + } + // Unlike profiles, don't fallback to the first org, + // Fallback to Personal (org = null) + + if (initialId !== newId) { + dispatch(setAvailableProfiles(null)); + dispatch(setSelectedOrganizationId(newId)); + extra.ideMessenger.post("didChangeSelectedOrg", { + id: newId, + }); + } +}); + +export const updateOrgsThunk = createAsyncThunk< + void, + OrganizationDescription[], + ThunkApiType +>("session/updateOrgs", async (orgs, { dispatch, getState }) => { + const state = getState(); + dispatch(setOrganizations(orgs)); + + // This will trigger reselection if needed + dispatch(selectOrgThunk(state.session.selectedOrganizationId)); +}); diff --git a/gui/src/redux/thunks/session.ts b/gui/src/redux/thunks/session.ts index c311df194..be43f725e 100644 --- a/gui/src/redux/thunks/session.ts +++ b/gui/src/redux/thunks/session.ts @@ -1,15 +1,15 @@ -import { createAsyncThunk, Dispatch, unwrapResult } from "@reduxjs/toolkit"; +import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; import { ChatMessage, Session, SessionMetadata } from "core"; import { NEW_SESSION_TITLE } from "core/util/constants"; import { renderChatMessage } from "core/util/messageContent"; -import { ThunkApiType } from "../store"; +import { IIdeMessenger } from "../../context/IdeMessenger"; import { deleteSessionMetadata, newSession, setAllSessionMetadata, updateSessionMetadata, } from "../slices/sessionSlice"; -import { IIdeMessenger } from "../../context/IdeMessenger"; +import { ThunkApiType } from "../store"; const MAX_TITLE_LENGTH = 100; @@ -97,6 +97,7 @@ export const loadSession = createAsyncThunk< const result = await dispatch( saveCurrentSession({ openNewSession: false, + generateTitle: true, }), ); unwrapResult(result); @@ -147,11 +148,11 @@ function getChatTitleFromMessage(message: ChatMessage) { export const saveCurrentSession = createAsyncThunk< void, - { openNewSession: boolean }, + { openNewSession: boolean; generateTitle: boolean }, ThunkApiType >( "session/saveCurrent", - async ({ openNewSession }, { dispatch, extra, getState }) => { + async ({ openNewSession, generateTitle }, { dispatch, extra, getState }) => { const state = getState(); if (state.session.history.length === 0) { return; @@ -173,7 +174,7 @@ export const saveCurrentSession = createAsyncThunk< ?.filter((h) => h.message.role === "assistant")[0] ?.message?.content?.toString(); - if (assistantResponse) { + if (assistantResponse && generateTitle) { try { const result = await extra.ideMessenger.request( "chatDescriber/describe", diff --git a/gui/src/redux/thunks/setProfileId.ts b/gui/src/redux/thunks/setProfileId.ts deleted file mode 100644 index 6ec1020ce..000000000 --- a/gui/src/redux/thunks/setProfileId.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { createAsyncThunk } from "@reduxjs/toolkit"; -import { setSelectedProfileId } from "../slices/sessionSlice"; -import { ThunkApiType } from "../store"; - -export const setProfileId = createAsyncThunk( - "profile/setId", - async (id, { dispatch, extra }) => { - dispatch(setSelectedProfileId(id)); - extra.ideMessenger.post("didChangeSelectedProfile", { - id, - }); - }, -); diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index 9a19a471c..1bd82a030 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -1,4 +1,4 @@ -import { createAsyncThunk } from "@reduxjs/toolkit"; +import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; import { ChatMessage, PromptLog } from "core"; import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; import { selectDefaultModel } from "../slices/configSlice"; @@ -27,8 +27,7 @@ export const streamNormalInput = createAsyncThunk< throw new Error("Default model not defined"); } - const includeTools = - useTools && modelSupportsTools(defaultModel.model, defaultModel.provider); + const includeTools = useTools && modelSupportsTools(defaultModel); // Send request const gen = extra.ideMessenger.llmStreamChat( @@ -70,7 +69,8 @@ export const streamNormalInput = createAsyncThunk< toolSettings[toolCallState.toolCall.function.name] === "allowedWithoutPermission" ) { - await dispatch(callTool()); + const response = await dispatch(callTool()); + unwrapResult(response); } } }); diff --git a/gui/src/redux/thunks/streamResponse.ts b/gui/src/redux/thunks/streamResponse.ts index 1c191b662..16043daee 100644 --- a/gui/src/redux/thunks/streamResponse.ts +++ b/gui/src/redux/thunks/streamResponse.ts @@ -74,13 +74,15 @@ export const streamResponseThunk = createAsyncThunk< const useTools = state.ui.useTools; const defaultModel = selectDefaultModel(state); const slashCommands = state.config.config.slashCommands || []; - const inputIndex = index ?? state.session.history.length; + const inputIndex = index ?? state.session.history.length; // Either given index or concat to end if (!defaultModel) { throw new Error("No chat model selected"); } - dispatch(submitEditorAndInitAtIndex({ index, editorState })); + dispatch( + submitEditorAndInitAtIndex({ index: inputIndex, editorState }), + ); resetStateForNewMessage(); const result = await dispatch( @@ -120,8 +122,7 @@ export const streamResponseThunk = createAsyncThunk< const updatedHistory = getState().session.history; const messages = constructMessages( [...updatedHistory], - defaultModel.model, - defaultModel.provider, + defaultModel, useTools, ); diff --git a/gui/src/redux/thunks/streamResponseAfterToolCall.ts b/gui/src/redux/thunks/streamResponseAfterToolCall.ts index 396ab6075..3d41c664f 100644 --- a/gui/src/redux/thunks/streamResponseAfterToolCall.ts +++ b/gui/src/redux/thunks/streamResponseAfterToolCall.ts @@ -31,8 +31,7 @@ export const streamResponseAfterToolCall = createAsyncThunk< const defaultModel = selectDefaultModel(state); if (!defaultModel) { - console.error("No default model found"); - return; + throw new Error("No model selected"); } resetStateForNewMessage(); @@ -64,11 +63,11 @@ export const streamResponseAfterToolCall = createAsyncThunk< const updatedHistory = getState().session.history; const messages = constructMessages( [...updatedHistory], - defaultModel.model, - defaultModel.provider, + defaultModel, useTools, ); - unwrapResult(await dispatch(streamNormalInput(messages))); + const output = await dispatch(streamNormalInput(messages)); + unwrapResult(output); }), ); }, diff --git a/gui/src/redux/thunks/streamThunkWrapper.tsx b/gui/src/redux/thunks/streamThunkWrapper.tsx index cd9f10f6d..7bd5a82f9 100644 --- a/gui/src/redux/thunks/streamThunkWrapper.tsx +++ b/gui/src/redux/thunks/streamThunkWrapper.tsx @@ -1,9 +1,9 @@ import { createAsyncThunk } from "@reduxjs/toolkit"; +import StreamErrorDialog from "../../pages/gui/StreamError"; import { clearLastEmptyResponse, setInactive } from "../slices/sessionSlice"; +import { setDialogMessage, setShowDialog } from "../slices/uiSlice"; import { ThunkApiType } from "../store"; import { saveCurrentSession } from "./session"; -import { setDialogMessage, setShowDialog } from "../slices/uiSlice"; -import StreamErrorDialog from "../../pages/gui/StreamError"; export const streamThunkWrapper = createAsyncThunk< void, @@ -23,6 +23,7 @@ export const streamThunkWrapper = createAsyncThunk< await dispatch( saveCurrentSession({ openNewSession: false, + generateTitle: true, }), ); } diff --git a/gui/tailwind.config.cjs b/gui/tailwind.config.cjs index c837eea75..3441bfdee 100644 --- a/gui/tailwind.config.cjs +++ b/gui/tailwind.config.cjs @@ -26,36 +26,20 @@ module.exports = { }, colors: { lightgray: "#999998", - "vsc-background": "rgb(var(--vsc-background) / )", - "secondary-dark": "rgb(var(--secondary-dark) / )", "vsc-input-background": "var(--vscode-input-background, rgb(45 45 45))", - "vsc-quick-input-background": - "var(--vscode-quickInput-background, var(--vscode-input-background, rgb(45 45 45)))", "vsc-background": "var(--vscode-sideBar-background, rgb(30 30 30))", "vsc-foreground": "var(--vscode-editor-foreground, #fff)", - "vsc-button-background": "var(--vscode-button-background, #1bbe84)", - "vsc-button-foreground": "var(--vscode-button-foreground, #ffffff)", "vsc-editor-background": "var(--vscode-editor-background, var(--vscode-sideBar-background, rgb(30 30 30)))", - "vsc-list-active-background": - "var(--vscode-list-activeSelectionBackground, #1bbe84)", - "vsc-focus-border": "var(--vscode-focus-border, #1bbe84)", - "vsc-list-active-foreground": - "var(--vscode-quickInputList-focusForeground, var(--vscode-editor-foreground))", "vsc-input-border": "var(--vscode-input-border, #999998)", - "vsc-input-border-focus": "var(--vscode-focusBorder, #999998)", - "vsc-badge-background": "var(--vscode-badge-background, #1bbe84)", - "vsc-badge-foreground": "var(--vscode-badge-foreground, #fff)", - "vsc-sidebar-border": "var(--vscode-sideBar-border, transparent)", - "vsc-find-match": - "var(--vscode-editor-findMatchBackground, rgba(255, 255, 0, 0.6))", - "vsc-find-match-selected": - "var(--vscode-editor-findMatchHighlightBackground, rgba(255, 223, 0, 0.8))", - "vsc-foreground-muted": "var(--vscode-foreground-muted, #999)", - "vsc-description-foreground": - "var(--vscode-descriptionForeground, #999)", - "vsc-input-placeholder-foreground": - "var(--vscode-input-placeholderForeground, #999)", + + // Starting to make things less vsc-specific + // TODO make it all non-IDE-specific naming + "find-match-selected": + "var(--vscode-editor-findMatchHighlightBackground, rgba(255, 223, 0))", + "list-active": "var(--vscode-list-activeSelectionBackground, #1bbe84)", + "list-active-foreground": + "var(--vscode-quickInputList-focusForeground, var(--vscode-editor-foreground))", }, }, }, diff --git a/gui/vite.config.ts b/gui/vite.config.ts index d4c4ba7d7..6c5cd6d75 100644 --- a/gui/vite.config.ts +++ b/gui/vite.config.ts @@ -16,6 +16,14 @@ export default defineConfig({ }, }, }, + server: { + cors: { + origin: "*", + methods: ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"], + allowedHeaders: ["*", "Content-Type", "Authorization"], + credentials: true, + }, + }, test: { globals: true, environment: "jsdom", diff --git a/manual-testing-sandbox/AdvancedPage.tsx b/manual-testing-sandbox/AdvancedPage.tsx index 5b5ccbde6..9f7d321ec 100644 --- a/manual-testing-sandbox/AdvancedPage.tsx +++ b/manual-testing-sandbox/AdvancedPage.tsx @@ -30,6 +30,7 @@ const AdvancedPage = () => {

Counter: {counter}

+