diff --git a/.changes/extensions/intellij/0.0.92.md b/.changes/extensions/intellij/0.0.92.md new file mode 100644 index 000000000..2d3774eec --- /dev/null +++ b/.changes/extensions/intellij/0.0.92.md @@ -0,0 +1,5 @@ +## 0.0.92 - 2025-02-26 +### Fixed +* Off-screen rendering to solve white flash on load and lack of changing cursor type +* OSR-related fixes for non-Mac users +* Fixes for inline edit in JetBrains diff --git a/.changes/extensions/intellij/1.0.0.md b/.changes/extensions/intellij/1.0.0.md new file mode 100644 index 000000000..43ea4a0ed --- /dev/null +++ b/.changes/extensions/intellij/1.0.0.md @@ -0,0 +1,7 @@ +## 1.0.0 - 2025-02-26 +### Added +* Introduces hub.continue.dev +* Improved theme matching +### Fixed +* Fixes interference between SonarQube and Continue autocomplete +* Numerous reliability improvements diff --git a/.changes/extensions/vscode/1.0.0.md b/.changes/extensions/vscode/1.0.0.md new file mode 100644 index 000000000..cea7899ff --- /dev/null +++ b/.changes/extensions/vscode/1.0.0.md @@ -0,0 +1,6 @@ +## 1.0.0 - 2025-02-26 +### Added +* Introduces hub.continue.dev +* Improved apply quality +### Fixed +* Numerous reliability improvements diff --git a/.changes/unreleased/Fixed-20241007-183820.yaml b/.changes/unreleased/Fixed-20241007-183820.yaml deleted file mode 100644 index f756e6f90..000000000 --- a/.changes/unreleased/Fixed-20241007-183820.yaml +++ /dev/null @@ -1,5 +0,0 @@ -project: extensions/intellij -kind: Fixed -body: Off-screen rendering to solve white flash on load and lack of changing cursor - type -time: 2024-10-07T18:38:20.733658-07:00 diff --git a/.changes/unreleased/Fixed-20241108-114322.yaml b/.changes/unreleased/Fixed-20241108-114322.yaml deleted file mode 100644 index e896eac4d..000000000 --- a/.changes/unreleased/Fixed-20241108-114322.yaml +++ /dev/null @@ -1,4 +0,0 @@ -project: extensions/intellij -kind: Fixed -body: OSR-related fixes for non-Mac users -time: 2024-11-08T11:43:22.623155-08:00 diff --git a/.changes/unreleased/Fixed-20241108-114707.yaml b/.changes/unreleased/Fixed-20241108-114707.yaml deleted file mode 100644 index 95c70c844..000000000 --- a/.changes/unreleased/Fixed-20241108-114707.yaml +++ /dev/null @@ -1,4 +0,0 @@ -project: extensions/intellij -kind: Fixed -body: Fixes for inline edit in JetBrains -time: 2024-11-08T11:47:07.953304-08:00 diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index c6e087b38..4a0595a38 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -27,8 +27,7 @@ body: - **Continue version**: v0.9.4 - **IDE version**: VSCode 1.85.1 - Model: Claude Sonnet 3.5 - - config.yaml: `models: ...` - - OR config.json: `{ "models": ... }` + - Assistant configuration value: | - OS: - Continue version: @@ -38,6 +37,7 @@ body: ```yaml ``` + OR link to assistant in Continue hub: render: Markdown validations: required: false diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index ffc4a967f..bf2fa74a6 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -31,7 +31,7 @@ jobs: - id: check working-directory: . run: | - if [[ "${{ github.event.release.tag_name }}" == v0.0.*-jetbrains ]]; then + if [[ "${{ github.event.release.tag_name }}" == v1.0.*-jetbrains ]]; then echo "should_run=true" >> $GITHUB_OUTPUT else echo "should_run=false" >> $GITHUB_OUTPUT diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index 46209d364..29965a305 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -20,7 +20,7 @@ jobs: - id: check working-directory: . run: | - if [[ "${{ github.event.release.tag_name }}" == v0.8.*-vscode ]]; then + if [[ "${{ github.event.release.tag_name }}" == v1.0.*-vscode ]]; then echo "should_run=true" >> $GITHUB_OUTPUT else echo "should_run=false" >> $GITHUB_OUTPUT diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index 7c005de7b..5fe472a10 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -4,10 +4,12 @@ on: pull_request: branches: - main + - staging push: branches: - main + - staging jobs: install-root: @@ -273,7 +275,7 @@ jobs: cd core npm test env: - IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork }} + IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true && github.actor == 'dependabot[bot]' }} OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} @@ -407,6 +409,14 @@ jobs: path: extensions/vscode/node_modules key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }} + # We don't want to cache the Continue extension, so it is deleted at the end of the job + - uses: actions/cache@v4 + id: test-extensions-cache + with: + path: extensions/vscode/e2e/.test-extensions + # package.json used as the key because that's where the download script is defined + key: vscode-test-extensions-${{ hashFiles('extensions/vscode/package.json') }} + - name: Download build artifact uses: actions/download-artifact@v4 with: @@ -434,7 +444,7 @@ jobs: chmod 600 ~/.ssh/id_rsa ssh-keyscan -H "$SSH_HOST" >> ~/.ssh/known_hosts echo -e "Host ssh-test-container\n\tHostName $SSH_HOST\n\tUser ec2-user\n\tIdentityFile ~/.ssh/id_rsa" >> ~/.ssh/config - if: ${{ github.event.pull_request.head.repo.fork == false }} + if: ${{ github.event.pull_request.head.repo.fork == false && github.actor != 'dependabot[bot]' }} - name: Set up Xvfb run: | @@ -444,10 +454,15 @@ jobs: - name: Run e2e tests run: | cd extensions/vscode - IGNORE_SSH_TESTS="${{ github.event.pull_request.head.repo.fork }}" TEST_FILE="${{ matrix.test_file }}" npm run ${{ matrix.command }} + IGNORE_SSH_TESTS="${{ github.event.pull_request.head.repo.fork == false && github.actor != 'dependabot[bot]' }}" TEST_FILE="${{ matrix.test_file }}" npm run ${{ matrix.command }} env: DISPLAY: :99 + - name: Delete continue from test extensions + run: | + cd extensions/vscode + rm -rf e2e/.test-extensions/continue* + - name: Upload e2e test screenshots if: failure() uses: actions/upload-artifact@v4 diff --git a/.github/workflows/preview.yaml b/.github/workflows/preview.yaml index abf58e6e8..7408cf76f 100644 --- a/.github/workflows/preview.yaml +++ b/.github/workflows/preview.yaml @@ -20,7 +20,7 @@ jobs: - id: check working-directory: . run: | - if [[ "${{ github.event.release.tag_name }}" == v0.9.*-vscode ]]; then + if [[ "${{ github.event.release.tag_name }}" == v1.1.*-vscode ]]; then echo "should_run=true" >> $GITHUB_OUTPUT else echo "should_run=false" >> $GITHUB_OUTPUT @@ -217,8 +217,8 @@ jobs: git config --local user.email "action@github.com" git config --local user.name "GitHub Action" - - name: Pull latest changes - run: git pull origin main + - name: Pull latest changes from release + run: git fetch origin ${{ github.ref }} && git checkout ${{ github.ref }} # 1. Download the artifacts - uses: actions/download-artifact@v4 diff --git a/.github/workflows/stale-issue-helper.yaml b/.github/workflows/stale-issue-helper.yaml new file mode 100644 index 000000000..067f4c60f --- /dev/null +++ b/.github/workflows/stale-issue-helper.yaml @@ -0,0 +1,25 @@ +name: "Label / close stale issues" +on: + schedule: + - cron: "30 1 * * *" + +jobs: + stale: + permissions: + issues: write + pull-requests: write + runs-on: ubuntu-latest + steps: + - uses: actions/stale@v9 + with: + close-issue-message: "This issue was closed because it wasn't updated for 10 days after being marked stale. If it's still important, please reopen + comment and we'll gladly take another look!" + stale-issue-message: "This issue hasn't been updated in 90 days and will be closed after an additional 10 days without activity. If it's still important, please leave a comment and share any new information that would help us address the issue." + days-before-stale: 90 + days-before-close: 10 + days-before-pr-stale: -1 + days-before-pr-close: -1 + operations-per-run: 1000 + stale-issue-label: "stale" + stale-pr-label: "stale" + exempt-issue-labels: "needs-triage,no-stale,high,highest" + exempt-pr-labels: "no-stale" diff --git a/.vscode/launch.json b/.vscode/launch.json index 7a5161729..294429bcb 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -138,6 +138,25 @@ "env": { "NODE_OPTIONS": "--experimental-vm-modules" } + }, + { + "name": "[config-yaml] Jest Test Debugger, Current Open File", + "type": "node", + "request": "launch", + "runtimeArgs": [ + "--inspect-brk", + "${workspaceRoot}/packages/config-yaml/node_modules/jest/bin/jest.js", + "--runInBand", + "--config", + "${workspaceRoot}/packages/config-yaml/jest.config.mjs", + "${relativeFile}" + ], + "cwd": "${workspaceRoot}/packages/config-yaml", + "console": "integratedTerminal", + "internalConsoleOptions": "neverOpen", + "env": { + "NODE_OPTIONS": "--experimental-vm-modules" + } } ] } diff --git a/.vscode/settings.json b/.vscode/settings.json index dd446726a..397937afb 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -13,6 +13,9 @@ "args": ["-l"] } }, + "editor.codeActionsOnSave": { + "source.organizeImports": "explicit" + }, "editor.defaultFormatter": "esbenp.prettier-vscode", "search.exclude": { "**/package-lock.json": true, diff --git a/README.md b/README.md index 9751d618d..bdfa8533c 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@
-**[Continue](https://docs.continue.dev) is the leading open-source AI code assistant. You can connect any models and any context to build custom autocomplete and chat experiences inside [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension)** +**[Continue](https://docs.continue.dev) enables to developers to create, share, and use custom AI code assistants with our open-source [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension) extensions and [hub of models, rules, prompts, docs, and other building blocks](https://hub.continue.dev)**
@@ -46,7 +46,7 @@ ## Actions -[Actions](https://continue.dev/docs/actions/how-to-use-it) are shortcuts for common use cases. +[Actions](https://continue.dev/docs/actions/how-to-use-it) are shortcuts for common use cases ![actions](docs/static/img/actions.gif) diff --git a/binary/build.js b/binary/build.js index 609a4b68c..adc461396 100644 --- a/binary/build.js +++ b/binary/build.js @@ -285,7 +285,7 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) { // Informs the `continue-binary` of where to look for node_sqlite3.node // https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found - // fs.writeFileSync(`${targetDir}/package.json`, ""); + fs.writeFileSync(`${targetDir}/package.json`, ""); } // Cleanup - this is needed when running locally diff --git a/binary/core-dev-server.js b/binary/core-dev-server.js new file mode 100644 index 000000000..506c79e68 --- /dev/null +++ b/binary/core-dev-server.js @@ -0,0 +1,6 @@ +const path = require('path'); +process.env.CONTINUE_DEVELOPMENT = true; + +process.env.CONTINUE_GLOBAL_DIR = path.join(process.env.PROJECT_DIR, 'extensions', '.continue-debug'); + +require('./out/index.js'); \ No newline at end of file diff --git a/binary/package-lock.json b/binary/package-lock.json index 367b0eb93..ca7d26b85 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -48,13 +48,13 @@ "@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.28", + "@continuedev/config-yaml": "^1.0.52", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", "@continuedev/openai-adapters": "^1.0.10", "@modelcontextprotocol/sdk": "^1.5.0", "@mozilla/readability": "^0.5.0", - "@octokit/rest": "^20.0.2", + "@octokit/rest": "^20.1.1", "@typescript-eslint/eslint-plugin": "^7.8.0", "@xenova/transformers": "2.14.0", "adf-to-md": "^1.1.0", @@ -107,7 +107,7 @@ "wink-nlp-utils": "^2.1.0", "workerpool": "^9.1.3", "yaml": "^2.4.2", - "zod": "^3.23.8" + "zod": "^3.24.2" }, "devDependencies": { "@babel/preset-env": "^7.24.7", @@ -128,7 +128,7 @@ "@types/uuid": "^9.0.7", "@types/win-ca": "^3.5.4", "cross-env": "^7.0.3", - "esbuild": "0.24.0", + "esbuild": "0.17.19", "eslint": "^8", "jest": "^29.7.0", "jest-environment-jsdom": "^29.7.0", diff --git a/binary/package.json b/binary/package.json index e698b9d2d..426127922 100644 --- a/binary/package.json +++ b/binary/package.json @@ -23,7 +23,6 @@ "scripts": { "test": "jest", "build": "node build.js", - "quick-build": "node quick-build.js --target darwin-arm64", "build:darwin-x64": "node build.js --os darwin-x64" }, "license": "Apache-2.0", diff --git a/binary/prompt-logs.js b/binary/prompt-logs.js new file mode 100644 index 000000000..68ee996f7 --- /dev/null +++ b/binary/prompt-logs.js @@ -0,0 +1,20 @@ +const fs = require('fs'); +const path = require('path'); + +const logDirPath = path.join(__dirname, '..', 'extensions', '.continue-debug', 'logs'); +const logFilePath = path.join(logDirPath, "prompt.log"); + +if (!fs.existsSync(logDirPath)) { + fs.mkdirSync(logDirPath, { recursive: true }); +} + +if (!fs.existsSync(logFilePath)) { + fs.createWriteStream(logFilePath).end(); +} + +console.log("Watching logs at " + logFilePath) + +fs.watch(logFilePath, () => { + // console.clear(); + fs.createReadStream(logFilePath).pipe(process.stdout); +}); \ No newline at end of file diff --git a/binary/quick-build.js b/binary/quick-build.js deleted file mode 100644 index a9a2e57d0..000000000 --- a/binary/quick-build.js +++ /dev/null @@ -1,86 +0,0 @@ -const esbuild = require("esbuild"); -const fs = require("fs"); -const path = require("path"); -const { - execCmdSync, - validateFilesPresent, - autodetectPlatformAndArch, -} = require("../scripts/util"); - -// Paths -const bin = path.join(__dirname, "bin"); -const esbuildOutputFile = "out/index.js"; -let targets = [ - "darwin-x64", - "darwin-arm64", - "linux-x64", - "linux-arm64", - "win32-x64", -]; - -for (let i = 2; i < process.argv.length; i++) { - if (process.argv[i - 1] === "--target") { - targets = [process.argv[i]]; - } -} - -// Cleanup -for (const target of targets) { - const exe = target.startsWith("win") ? ".exe" : ""; - const targetDir = path.join(bin, target); - fs.rmSync(path.join(targetDir, `continue-binary${exe}`), { force: true }); -} - -// Validate files to ensure prerequisites are available -const filesToValidate = [ - "src/index.ts", - "../core/node_modules/jsdom/lib/jsdom/living/xhr/xhr-sync-worker.js", - "../core/llm/tiktokenWorkerPool.mjs", - "../core/llm/llamaTokenizerWorkerPool.mjs", -]; -validateFilesPresent(filesToValidate); - -// Quick Build -(async () => { - console.log("[info] Building with esbuild..."); - await esbuild.build({ - entryPoints: ["src/index.ts"], - bundle: true, - outfile: esbuildOutputFile, - external: [ - "esbuild", - "./xhr-sync-worker.js", - "llamaTokenizerWorkerPool.mjs", - "tiktokenWorkerPool.mjs", - "vscode", - "./index.node", - ], - format: "cjs", - platform: "node", - sourcemap: true, - minify: true, - treeShaking: true, - loader: { ".node": "file" }, - inject: ["./importMetaUrl.js"], - define: { "import.meta.url": "importMetaUrl" }, - }); - - console.log("[info] Building binaries with pkg..."); - for (const target of targets) { - const targetDir = path.join(bin, target); - fs.mkdirSync(targetDir, { recursive: true }); - console.log(`[info] Building ${target}...`); - execCmdSync( - `npx pkg --no-bytecode --public-packages "*" --public pkgJson/${target} --out-path ${targetDir}`, - ); - } - - // Validate only continue-binary files - const pathsToVerify = targets.map((target) => { - const exe = target.startsWith("win") ? ".exe" : ""; - return path.join(bin, target, `continue-binary${exe}`); - }); - validateFilesPresent(pathsToVerify); - - console.log("[info] Quick build completed!"); -})(); diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 32e8a4127..b56d153dc 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -134,6 +134,13 @@ export class CompletionProvider { token: AbortSignal | undefined, ): Promise { try { + // Create abort signal if not given + if (!token) { + const controller = this.loggingService.createAbortController( + input.completionId, + ); + token = controller.signal; + } const startTime = Date.now(); const options = await this._getAutocompleteOptions(); @@ -158,14 +165,6 @@ export class CompletionProvider { return undefined; } - // Create abort signal if not given - if (!token) { - const controller = this.loggingService.createAbortController( - input.completionId, - ); - token = controller.signal; - } - const [snippetPayload, workspaceDirs] = await Promise.all([ getAllSnippets({ helper, diff --git a/core/autocomplete/util/AutocompleteLoggingService.ts b/core/autocomplete/util/AutocompleteLoggingService.ts index 96bf4b4bc..2e4d19844 100644 --- a/core/autocomplete/util/AutocompleteLoggingService.ts +++ b/core/autocomplete/util/AutocompleteLoggingService.ts @@ -1,4 +1,4 @@ -import { logDevData } from "../../util/devdata"; +import { DataLogger } from "../../data/log"; import { COUNT_COMPLETION_REJECTED_AFTER } from "../../util/parameters"; import { Telemetry } from "../../util/posthog"; import { getUriFileExtension } from "../../util/uri"; @@ -96,7 +96,14 @@ export class AutocompleteLoggingService { } private logAutocompleteOutcome(outcome: AutocompleteOutcome) { - logDevData("autocomplete", outcome); + void DataLogger.getInstance().logDevData({ + name: "autocomplete", + data: { + ...outcome, + useFileSuffix: true, // from outdated schema + }, + }); + const { prompt, completion, prefix, suffix, ...restOfOutcome } = outcome; void Telemetry.capture( "autocomplete", diff --git a/core/commands/index.ts b/core/commands/index.ts index f4a0084da..72719d832 100644 --- a/core/commands/index.ts +++ b/core/commands/index.ts @@ -10,7 +10,7 @@ export function slashFromCustomCommand( return { name: customCommand.name, description: customCommand.description ?? "", - run: async function* ({ input, llm, history, ide }) { + run: async function* ({ input, llm, history, ide, completionOptions }) { // Remove slash command prefix from input let userInput = input; if (userInput.startsWith(`/${customCommand.name}`)) { @@ -20,11 +20,16 @@ export function slashFromCustomCommand( } // Render prompt template - const promptUserInput = await renderTemplatedString( - customCommand.prompt, - ide.readFile.bind(ide), - { input: userInput }, - ); + let promptUserInput: string; + if (customCommand.prompt.includes("{{{ input }}}")) { + promptUserInput = await renderTemplatedString( + customCommand.prompt, + ide.readFile.bind(ide), + { input: userInput }, + ); + } else { + promptUserInput = customCommand.prompt + "\n\n" + userInput; + } const messages = [...history]; // Find the last chat message with this slash command and replace it with the user input @@ -67,6 +72,7 @@ export function slashFromCustomCommand( for await (const chunk of llm.streamChat( messages, new AbortController().signal, + completionOptions, )) { yield renderChatMessage(chunk); } diff --git a/core/commands/slash/onboard.ts b/core/commands/slash/onboard.ts index d6fedcafb..b53c8d3a9 100644 --- a/core/commands/slash/onboard.ts +++ b/core/commands/slash/onboard.ts @@ -2,8 +2,7 @@ import ignore from "ignore"; import type { FileType, IDE, SlashCommand } from "../.."; import { - defaultIgnoreDir, - defaultIgnoreFile, + DEFAULT_IGNORE, getGlobalContinueIgArray, gitIgArrayFromFile, } from "../../indexing/ignore"; @@ -58,10 +57,7 @@ const OnboardSlashCommand: SlashCommand = { }; async function getEntriesFilteredByIgnore(dir: string, ide: IDE) { - const ig = ignore() - .add(defaultIgnoreDir) - .add(defaultIgnoreFile) - .add(getGlobalContinueIgArray()); + const ig = ignore().add(DEFAULT_IGNORE).add(getGlobalContinueIgArray()); const entries = await ide.listDir(dir); const ignoreUri = joinPathsToUri(dir, ".gitignore"); diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index 659584056..b9a0f0896 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -1,11 +1,6 @@ import * as fs from "node:fs"; -import { - AssistantUnrolled, - ConfigResult, - FullSlug, -} from "@continuedev/config-yaml"; -import * as YAML from "yaml"; +import { ConfigResult, FullSlug } from "@continuedev/config-yaml"; import { ControlPlaneClient, @@ -36,7 +31,6 @@ import { ProfileDescription, ProfileLifecycleManager, } from "./ProfileLifecycleManager.js"; -import { clientRenderHelper } from "./yaml/clientRender.js"; export type { ProfileDescription }; @@ -50,7 +44,7 @@ export class ConfigHandler { private profiles: ProfileLifecycleManager[] | null = null; // null until profiles are loaded private selectedProfileId: string | null = null; private localProfileManager: ProfileLifecycleManager; - private controlPlaneClient: ControlPlaneClient; + controlPlaneClient: ControlPlaneClient; initializedPromise: Promise; @@ -99,8 +93,8 @@ export class ConfigHandler { */ getAdditionalSubmenuContextProviders(): string[] { return this.additionalContextProviders - .filter(provider => provider.description.type === "submenu") - .map(provider => provider.description.title); + .filter((provider) => provider.description.type === "submenu") + .map((provider) => provider.description.title); } private async init() { @@ -108,7 +102,7 @@ export class ConfigHandler { 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); + console.error("Failed to fetch control plane profiles in init: ", e); await this.updateAvailableProfiles([this.localProfileManager]); } try { @@ -172,37 +166,26 @@ export class ConfigHandler { // 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.controlPlaneClient, - ); - } - 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), - ); + const hubProfiles = assistants.map((assistant) => { + const profileLoader = new PlatformProfileLoader( + { + ...assistant.configResult, + config: assistant.configResult.config, + }, + assistant.ownerSlug, + assistant.packageSlug, + assistant.iconUrl, + assistant.configResult.config?.version ?? "latest", + this.controlPlaneClient, + this.ide, + this.ideSettingsPromise, + this.writeLog, + this.reloadConfig.bind(this), + ); - return new ProfileLifecycleManager(profileLoader, this.ide); - }), - ); + return new ProfileLifecycleManager(profileLoader, this.ide); + }); if (selectedOrgId === null) { // Personal @@ -223,8 +206,16 @@ export class ConfigHandler { // Otherwise, choose the first profile const previouslySelectedProfileId = await this.getPersistedSelectedProfileId(); - const selectedProfileId = - previouslySelectedProfileId ?? profiles[0].profileDescription.id ?? null; + + // Check if the previously selected profile exists in the current profiles + const profileExists = profiles.some( + (profile) => + profile.profileDescription.id === previouslySelectedProfileId, + ); + + const selectedProfileId = profileExists + ? previouslySelectedProfileId + : (profiles[0]?.profileDescription.id ?? null); // Notify listeners const profileDescriptions = profiles.map( @@ -362,8 +353,10 @@ export class ConfigHandler { Promise.resolve(sessionInfo), this.ideSettingsPromise, ); - this.fetchControlPlaneProfiles().catch((e) => { + this.fetchControlPlaneProfiles().catch(async (e) => { console.error("Failed to fetch control plane profiles: ", e); + await this.updateAvailableProfiles([this.localProfileManager]); + await this.reloadConfig(); }); } diff --git a/core/config/default.ts b/core/config/default.ts index 23e709603..8c349a13b 100644 --- a/core/config/default.ts +++ b/core/config/default.ts @@ -82,10 +82,12 @@ export const defaultConfig: SerializedContinueConfig = { models: [], contextProviders: defaultContextProvidersVsCode, slashCommands: defaultSlashCommandsVscode, + data: [], }; export const defaultConfigJetBrains: SerializedContinueConfig = { models: [], contextProviders: defaultContextProvidersJetBrains, slashCommands: defaultSlashCommandsJetBrains, + data: [], }; diff --git a/core/config/load.ts b/core/config/load.ts index c8499dc8b..873577d8c 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -3,6 +3,11 @@ import * as fs from "fs"; import os from "os"; import path from "path"; +import { + ConfigResult, + ConfigValidationError, + ModelRole, +} from "@continuedev/config-yaml"; import { fetchwithRequestOptions } from "@continuedev/fetch"; import * as JSONC from "comment-json"; import * as tar from "tar"; @@ -18,6 +23,7 @@ import { EmbeddingsProviderDescription, IContextProvider, IDE, + IdeInfo, IdeSettings, IdeType, ILLM, @@ -30,14 +36,16 @@ import { import { slashCommandFromDescription, slashFromCustomCommand, -} from "../commands/index.js"; +} from "../commands/index"; import { AllRerankers } from "../context/allRerankers"; import { MCPManagerSingleton } from "../context/mcp"; +import CodebaseContextProvider from "../context/providers/CodebaseContextProvider"; import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider"; import CustomContextProviderClass from "../context/providers/CustomContextProvider"; import FileContextProvider from "../context/providers/FileContextProvider"; import { contextProviderClassFromName } from "../context/providers/index"; import PromptFilesContextProvider from "../context/providers/PromptFilesContextProvider"; +import { useHub } from "../control-plane/env"; import { allEmbeddingsProviders } from "../indexing/allEmbeddingsProviders"; import { BaseLLM } from "../llm"; import { llmFromDescription } from "../llm/llms"; @@ -61,10 +69,8 @@ import { getContinueDotEnv, getEsbuildBinaryPath, } from "../util/paths"; - -import { ConfigResult, ConfigValidationError } from "@continuedev/config-yaml"; -import { useHub } from "../control-plane/env"; import { localPathToUri } from "../util/pathToUri"; + import { defaultContextProvidersJetBrains, defaultContextProvidersVsCode, @@ -72,7 +78,8 @@ import { defaultSlashCommandsVscode, } from "./default"; import { getSystemPromptDotFile } from "./getSystemPromptDotFile"; -import { modifyContinueConfigWithSharedConfig } from "./sharedConfig"; +import { modifyAnyConfigWithSharedConfig } from "./sharedConfig"; +import { getModelByRole, isSupportedLanceDbCpuTargetForLinux } from "./util"; import { validateConfig } from "./validation.js"; export function resolveSerializedConfig( @@ -166,10 +173,9 @@ function loadSerializedConfig( ? [...defaultSlashCommandsVscode] : [...defaultSlashCommandsJetBrains]; - // Temporarily disabling this check until we can verify the commands are accuarate - // if (!isSupportedLanceDbCpuTarget(ide)) { - // config.disableIndexing = true; - // } + if (os.platform() === "linux" && !isSupportedLanceDbCpuTargetForLinux(ide)) { + config.disableIndexing = true; + } return { config, errors, configLoadInterrupted: false }; } @@ -226,18 +232,12 @@ export function isContextProviderWithParams( return (contextProvider as ContextProviderWithParams).name !== undefined; } -const getCodebaseProvider = async (params: any) => { - const { default: CodebaseContextProvider } = await import( - "../context/providers/CodebaseContextProvider" - ); - return new CodebaseContextProvider(params); -}; - /** Only difference between intermediate and final configs is the `models` array */ async function intermediateToFinalConfig( config: Config, ide: IDE, ideSettings: IdeSettings, + ideInfo: IdeInfo, uniqueId: string, writeLog: (log: string) => Promise, workOsAccessToken: string | undefined, @@ -326,7 +326,7 @@ async function intermediateToFinalConfig( ...model.requestOptions, ...config.requestOptions, }; - model.roles = model.roles ?? ["chat"]; // Default to chat role if not specified + model.roles = model.roles ?? ["chat", "apply", "edit", "summarize"]; // Default to chat role if not specified } if (allowFreeTrial) { @@ -398,7 +398,7 @@ async function intermediateToFinalConfig( new FileContextProvider({}), // Add codebase provider if indexing is enabled ...(!config.disableIndexing - ? [await getCodebaseProvider(codebaseContextParams)] + ? [new CodebaseContextProvider(codebaseContextParams)] : []), // Add prompt files provider if enabled ...(loadPromptFiles ? [new PromptFilesContextProvider({})] : []), @@ -436,23 +436,28 @@ async function intermediateToFinalConfig( } // Embeddings Provider - const embeddingsProviderDescription = config.embeddingsProvider as - | EmbeddingsProviderDescription - | undefined; - if (embeddingsProviderDescription?.provider) { - const { provider, ...options } = embeddingsProviderDescription; + function getEmbeddingsILLM( + embedConfig: EmbeddingsProviderDescription | ILLM | undefined, + ): ILLM | null { + if (!embedConfig) { + return null; + } + if ("providerName" in embedConfig) { + return embedConfig; + } + const { provider, ...options } = embedConfig; const embeddingsProviderClass = allEmbeddingsProviders[provider]; if (embeddingsProviderClass) { if ( embeddingsProviderClass.name === "_TransformersJsEmbeddingsProvider" ) { - config.embeddingsProvider = new embeddingsProviderClass(); + return new embeddingsProviderClass(); } else { const llmOptions: LLMOptions = { model: options.model ?? "UNSPECIFIED", ...options, }; - config.embeddingsProvider = new embeddingsProviderClass( + return new embeddingsProviderClass( llmOptions, (url: string | URL, init: any) => fetchwithRequestOptions(url, init, { @@ -461,42 +466,74 @@ async function intermediateToFinalConfig( }), ); } + } else { + errors.push({ + fatal: false, + message: `Embeddings provider ${provider} not found. Using default`, + }); } + return null; } - - if (!config.embeddingsProvider) { - config.embeddingsProvider = new TransformersJsEmbeddingsProvider(); - } + const newEmbedder = getEmbeddingsILLM(config.embeddingsProvider); // Reranker - if (config.reranker && !(config.reranker as ILLM | undefined)?.rerank) { + function getRerankingILLM( + rerankingConfig: ILLM | RerankerDescription | undefined, + ): ILLM | null { + if (!rerankingConfig) { + return null; + } + if ("providerName" in rerankingConfig) { + return rerankingConfig; + } const { name, params } = config.reranker as RerankerDescription; const rerankerClass = AllRerankers[name]; if (name === "llm") { const llm = models.find((model) => model.title === params?.modelTitle); if (!llm) { - console.warn(`Unknown model ${params?.modelTitle}`); + errors.push({ + fatal: false, + message: `Unknown reranking model ${params?.modelTitle}`, + }); + return null; } else { - config.reranker = new LLMReranker(llm); + return new LLMReranker(llm); } } else if (rerankerClass) { const llmOptions: LLMOptions = { model: "rerank-2", ...params, }; - config.reranker = new rerankerClass(llmOptions); + return new rerankerClass(llmOptions); } + return null; } + const newReranker = getRerankingILLM(config.reranker); - let continueConfig: ContinueConfig = { + const continueConfig: ContinueConfig = { ...config, contextProviders, models, - embeddingsProvider: config.embeddingsProvider as any, - tabAutocompleteModels, - reranker: config.reranker as any, tools: allTools, + modelsByRole: { + chat: models, + edit: models, + apply: models, + summarize: models, + autocomplete: [...tabAutocompleteModels], + embed: newEmbedder ? [newEmbedder] : [], + rerank: newReranker ? [newReranker] : [], + }, + selectedModelByRole: { + chat: null, // Not implemented (uses GUI defaultModel) + edit: null, + apply: null, + embed: newEmbedder ?? null, + autocomplete: null, + rerank: newReranker ?? null, + summarize: null, // Not implemented + }, }; // Apply MCP if specified @@ -538,48 +575,112 @@ async function intermediateToFinalConfig( ); } + // Handle experimental modelRole config values for apply and edit + const inlineEditModel = getModelByRole(continueConfig, "inlineEdit")?.title; + if (inlineEditModel) { + const match = continueConfig.models.find( + (m) => m.title === inlineEditModel, + ); + if (match) { + continueConfig.selectedModelByRole.edit = match; + continueConfig.modelsByRole.edit = [match]; // The only option if inlineEdit role is set + } else { + errors.push({ + fatal: false, + message: `experimental.modelRoles.inlineEdit model title ${inlineEditModel} not found in models array`, + }); + } + } + + const applyBlockModel = getModelByRole( + continueConfig, + "applyCodeBlock", + )?.title; + if (applyBlockModel) { + const match = continueConfig.models.find( + (m) => m.title === applyBlockModel, + ); + if (match) { + continueConfig.selectedModelByRole.apply = match; + continueConfig.modelsByRole.apply = [match]; // The only option if applyCodeBlock role is set + } else { + errors.push({ + fatal: false, + message: `experimental.modelRoles.applyCodeBlock model title ${inlineEditModel} not found in models array`, + }); + } + } + + // Add transformers JS to the embed models list if not already added + if ( + ideInfo.ideType === "vscode" && + !continueConfig.modelsByRole.embed.find( + (m) => m.providerName === "transformers.js", + ) + ) { + continueConfig.modelsByRole.embed.push( + new TransformersJsEmbeddingsProvider(), + ); + } + return { config: continueConfig, errors }; } +function llmToSerializedModelDescription(llm: ILLM): ModelDescription { + return { + provider: llm.providerName, + model: llm.model, + title: llm.title ?? llm.model, + apiKey: llm.apiKey, + apiBase: llm.apiBase, + contextLength: llm.contextLength, + template: llm.template, + completionOptions: llm.completionOptions, + systemMessage: llm.systemMessage, + requestOptions: llm.requestOptions, + promptTemplates: llm.promptTemplates as any, + capabilities: llm.capabilities, + roles: llm.roles, + }; +} + async function finalToBrowserConfig( final: ContinueConfig, ide: IDE, ): Promise { return { allowAnonymousTelemetry: final.allowAnonymousTelemetry, - models: final.models.map((m) => ({ - provider: m.providerName, - model: m.model, - title: m.title ?? m.model, - apiKey: m.apiKey, - apiBase: m.apiBase, - contextLength: m.contextLength, - template: m.template, - completionOptions: m.completionOptions, - systemMessage: m.systemMessage, - requestOptions: m.requestOptions, - promptTemplates: m.promptTemplates as any, - capabilities: m.capabilities, - roles: m.roles, - })), + models: final.models.map(llmToSerializedModelDescription), systemMessage: final.systemMessage, completionOptions: final.completionOptions, slashCommands: final.slashCommands?.map((s) => ({ name: s.name, description: s.description, - params: s.params, //PZTODO: is this why params aren't referenced properly by slash commands? + params: s.params, // TODO: is this why params aren't referenced properly by slash commands? })), contextProviders: final.contextProviders?.map((c) => c.description), disableIndexing: final.disableIndexing, disableSessionTitles: final.disableSessionTitles, userToken: final.userToken, - embeddingsProvider: final.embeddingsProvider?.embeddingId, ui: final.ui, experimental: final.experimental, docs: final.docs, tools: final.tools, tabAutocompleteOptions: final.tabAutocompleteOptions, usePlatform: await useHub(ide.getIdeSettings()), + modelsByRole: Object.fromEntries( + Object.entries(final.modelsByRole).map(([k, v]) => [ + k, + v.map(llmToSerializedModelDescription), + ]), + ) as Record, // TODO better types here + selectedModelByRole: Object.fromEntries( + Object.entries(final.selectedModelByRole).map(([k, v]) => [ + k, + v ? llmToSerializedModelDescription(v) : null, + ]), + ) as Record, // TODO better types here + // data not included here because client doesn't need }; } @@ -767,7 +868,7 @@ async function loadContinueConfigFromJson( ide: IDE, workspaceConfigs: ContinueRcJson[], ideSettings: IdeSettings, - ideType: IdeType, + ideInfo: IdeInfo, uniqueId: string, writeLog: (log: string) => Promise, workOsAccessToken: string | undefined, @@ -781,7 +882,7 @@ async function loadContinueConfigFromJson( } = loadSerializedConfig( workspaceConfigs, ideSettings, - ideType, + ideInfo.ideType, overrideConfigJson, ide, ); @@ -798,16 +899,16 @@ async function loadContinueConfigFromJson( // Apply shared config // TODO: override several of these values with user/org shared config const sharedConfig = new GlobalContext().getSharedConfig(); - const withShared = modifyContinueConfigWithSharedConfig( - serialized, - sharedConfig, - ); + const withShared = modifyAnyConfigWithSharedConfig(serialized, sharedConfig); // Convert serialized to intermediate config let intermediate = await serializedToIntermediateConfig(withShared, ide); // Apply config.ts to modify intermediate config - const configJsContents = await buildConfigTsandReadConfigJs(ide, ideType); + const configJsContents = await buildConfigTsandReadConfigJs( + ide, + ideInfo.ideType, + ); if (configJsContents) { try { // Try config.ts first @@ -867,6 +968,7 @@ async function loadContinueConfigFromJson( intermediate, ide, ideSettings, + ideInfo, uniqueId, writeLog, workOsAccessToken, diff --git a/core/config/profile/LocalProfileLoader.ts b/core/config/profile/LocalProfileLoader.ts index 3196faff4..9ccf5c812 100644 --- a/core/config/profile/LocalProfileLoader.ts +++ b/core/config/profile/LocalProfileLoader.ts @@ -38,6 +38,7 @@ export default class LocalProfileLoader implements IProfileLoader { undefined, undefined, undefined, + this.description.id, ); this.description.errors = result.errors; diff --git a/core/config/profile/PlatformProfileLoader.ts b/core/config/profile/PlatformProfileLoader.ts index 04f1d3acf..c0fa4c5cc 100644 --- a/core/config/profile/PlatformProfileLoader.ts +++ b/core/config/profile/PlatformProfileLoader.ts @@ -1,7 +1,8 @@ -import { ConfigResult, AssistantUnrolled } from "@continuedev/config-yaml"; +import { AssistantUnrolled, ConfigResult } from "@continuedev/config-yaml"; import { ControlPlaneClient } from "../../control-plane/client.js"; import { ContinueConfig, IDE, IdeSettings } from "../../index.js"; + import { ProfileDescription } from "../ProfileLifecycleManager.js"; import doLoadConfig from "./doLoadConfig.js"; @@ -42,7 +43,7 @@ export default class PlatformProfileLoader implements IProfileLoader { packageSlug, versionSlug, }, - title: `${ownerSlug}/${packageSlug}@${versionSlug}`, + title: configResult.config?.name ?? `${ownerSlug}/${packageSlug}`, errors: configResult.errors, iconUrl: this.iconUrl, }; @@ -68,6 +69,7 @@ export default class PlatformProfileLoader implements IProfileLoader { ownerSlug: this.ownerSlug, packageSlug: this.packageSlug, }, + this.description.id, ); return { diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index af8c59c97..0ec9b4137 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -4,6 +4,7 @@ import { AssistantUnrolled, ConfigResult, ConfigValidationError, + ModelRole, } from "@continuedev/config-yaml"; import { ContinueConfig, @@ -24,6 +25,7 @@ import { loadContinueConfigFromJson } from "../load"; import { migrateJsonSharedConfig } from "../migrateSharedConfig"; import { loadContinueConfigFromYaml } from "../yaml/loadYaml"; import { PlatformConfigMetadata } from "./PlatformProfileLoader"; +import { rectifySelectedModelsFromGlobalContext } from "../selectedModels"; export default async function doLoadConfig( ide: IDE, @@ -33,7 +35,7 @@ export default async function doLoadConfig( overrideConfigJson: SerializedContinueConfig | undefined, overrideConfigYaml: AssistantUnrolled | undefined, platformConfigMetadata: PlatformConfigMetadata | undefined, - workspaceId?: string, + profileId: string, ): Promise> { const workspaceConfigs = await getWorkspaceConfigs(ide); const ideInfo = await ide.getIdeInfo(); @@ -59,7 +61,7 @@ export default async function doLoadConfig( ide, workspaceConfigs.map((c) => JSON.stringify(c)), ideSettings, - ideInfo.ideType, + ideInfo, uniqueId, writeLog, workOsAccessToken, @@ -75,7 +77,7 @@ export default async function doLoadConfig( ide, workspaceConfigs, ideSettings, - ideInfo.ideType, + ideInfo, uniqueId, writeLog, workOsAccessToken, @@ -86,6 +88,11 @@ export default async function doLoadConfig( configLoadInterrupted = result.configLoadInterrupted; } + // Rectify model selections for each role + if (newConfig) { + newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId); + } + if (configLoadInterrupted || !newConfig) { return { errors, config: newConfig, configLoadInterrupted: true }; } @@ -117,7 +124,7 @@ export default async function doLoadConfig( controlPlaneProxyUrl += "/"; } const controlPlaneProxyInfo = { - workspaceId, + profileId, controlPlaneProxyUrl, workOsAccessToken, }; @@ -147,21 +154,26 @@ async function injectControlPlaneProxyInfo( config: ContinueConfig, info: ControlPlaneProxyInfo, ): Promise { - [...config.models, ...(config.tabAutocompleteModels ?? [])].forEach( - async (model) => { + Object.keys(config.modelsByRole).forEach((key) => { + config.modelsByRole[key as ModelRole].forEach((model) => { if (model.providerName === "continue-proxy") { (model as ContinueProxy).controlPlaneProxyInfo = info; } - }, - ); + }); + }); - if (config.embeddingsProvider?.providerName === "continue-proxy") { - (config.embeddingsProvider as ContinueProxy).controlPlaneProxyInfo = info; - } + Object.keys(config.selectedModelByRole).forEach((key) => { + const model = config.selectedModelByRole[key as ModelRole]; + if (model?.providerName === "continue-proxy") { + (model as ContinueProxy).controlPlaneProxyInfo = info; + } + }); - if (config.reranker?.providerName === "continue-proxy") { - (config.reranker as ContinueProxy).controlPlaneProxyInfo = info; - } + config.models.forEach((model) => { + if (model.providerName === "continue-proxy") { + (model as ContinueProxy).controlPlaneProxyInfo = info; + } + }); return config; } diff --git a/core/config/selectedModels.ts b/core/config/selectedModels.ts new file mode 100644 index 000000000..dd537665d --- /dev/null +++ b/core/config/selectedModels.ts @@ -0,0 +1,67 @@ +import { ModelRole } from "@continuedev/config-yaml"; + +import { ContinueConfig, ILLM } from ".."; +import { + GlobalContext, + GlobalContextModelSelections, +} from "../util/GlobalContext"; + +export function rectifySelectedModelsFromGlobalContext( + continueConfig: ContinueConfig, + profileId: string, +): ContinueConfig { + const configCopy = { ...continueConfig }; + + const globalContext = new GlobalContext(); + const currentSelectedModels = globalContext.get("selectedModelsByProfileId"); + const currentForProfile: GlobalContextModelSelections = + currentSelectedModels?.[profileId] ?? {}; + + let fellBack = false; + + // chat and summarize not implemented yet + // default chat model is stored in GUI still + + const roles: ModelRole[] = [ + "autocomplete", + "apply", + "edit", + "embed", + "rerank", + ]; + for (const role of roles) { + let newModel: ILLM | null = null; + const currentSelection = currentForProfile[role] ?? null; + if (currentSelection) { + const match = continueConfig.modelsByRole[role].find( + (m) => m.title === currentSelection, + ); + if (match) { + newModel = match; + } + } + if (!newModel && continueConfig.modelsByRole[role].length > 0) { + newModel = continueConfig.modelsByRole[role][0]; + } + if (!(currentSelection === (newModel?.title ?? null))) { + fellBack = true; + } + configCopy.selectedModelByRole[role] = newModel; + } + + // In the case shared config wasn't respected, + // Rewrite the shared config + if (fellBack) { + globalContext.update("selectedModelsByProfileId", { + ...currentSelectedModels, + [profileId]: Object.fromEntries( + Object.entries(configCopy.selectedModelByRole).map(([key, value]) => [ + key, + value?.title ?? null, + ]), + ), + }); + } + + return configCopy; +} diff --git a/core/config/sharedConfig.ts b/core/config/sharedConfig.ts index 9f2335243..ce16ea24f 100644 --- a/core/config/sharedConfig.ts +++ b/core/config/sharedConfig.ts @@ -1,13 +1,15 @@ import z from "zod"; + import { BrowserSerializedContinueConfig, - ContinueConfig, Config, + ContinueConfig, SerializedContinueConfig, } from ".."; export const sharedConfigSchema = z .object({ + // boolean fields in config.json allowAnonymousTelemetry: z.boolean(), disableIndexing: z.boolean(), disableSessionTitles: z.boolean(), @@ -18,6 +20,7 @@ export const sharedConfigSchema = z promptPath: z.string(), // `ui` in `ContinueConfig` + showSessionTabs: z.boolean(), codeBlockToolbarPosition: z.enum(["top", "bottom"]), fontSize: z.number(), codeWrap: z.boolean(), @@ -65,7 +68,19 @@ export function salvageSharedConfig(sharedConfig: object): SharedConfigSchema { return salvagedConfig; } -export function modifyContinueConfigWithSharedConfig< +// Apply shared config to all forms of config +// - SerializedContinueConfig (config.json) +// - Config ("intermediate") - passed to config.ts +// - ContinueConfig +// - BrowserSerializedContinueConfig (final converted to be passed to GUI) + +// This modify function is split into two steps +// - rectifySharedModelsFromSharedConfig - includes boolean flags like allowAnonymousTelemetry which +// must be added BEFORE config.ts and remote server config apply for JSON +// for security reasons +// - setSharedModelsFromSharedConfig - exists because of selectedModelsByRole +// Which don't exist on SerializedContinueConfig/Config types, so must be added after the fact +export function modifyAnyConfigWithSharedConfig< T extends | ContinueConfig | BrowserSerializedContinueConfig @@ -92,6 +107,7 @@ export function modifyContinueConfigWithSharedConfig< configCopy.ui = { ...configCopy.ui, }; + if (sharedConfig.codeBlockToolbarPosition !== undefined) { configCopy.ui.codeBlockToolbarPosition = sharedConfig.codeBlockToolbarPosition; @@ -119,6 +135,10 @@ export function modifyContinueConfigWithSharedConfig< configCopy.disableSessionTitles = sharedConfig.disableSessionTitles; } + if (sharedConfig.showSessionTabs !== undefined) { + configCopy.ui.showSessionTabs = sharedConfig.showSessionTabs; + } + configCopy.experimental = { ...configCopy.experimental, }; @@ -135,28 +155,3 @@ export function modifyContinueConfigWithSharedConfig< return configCopy; } - -// continueConfig.tabAutocompleteOptions = { -// ...continueConfig.tabAutocompleteOptions, -// useCache: sharedConfig.useAutocompleteCache, -// disableInFiles: sharedConfig.disableAutocompleteInFiles, -// multilineCompletions: sharedConfig.useAutocompleteMultilineCompletions, -// }; -// continueConfig.ui = { -// ...continueConfig.ui, -// codeBlockToolbarPosition: sharedConfig.codeBlockToolbarPosition, -// fontSize: sharedConfig.fontSize, -// codeWrap: sharedConfig.codeWrap, -// displayRawMarkdown: sharedConfig.displayRawMarkdown, -// showChatScrollbar: sharedConfig.showChatScrollbar, -// }; -// continueConfig.allowAnonymousTelemetry = sharedConfig.allowAnonymousTelemetry; -// continueConfig.disableIndexing = sharedConfig.disableIndexing; -// continueConfig.disableIndexing = sharedConfig.disableIndexing; -// continueConfig.disableSessionTitles = sharedConfig.disableSessionTitles; -// continueConfig.experimental = { -// ...continueConfig.experimental, -// useChromiumForDocsCrawling: sharedConfig.useChromiumForDocsCrawling, -// readResponseTTS: sharedConfig.readResponseTTS, -// promptPath: sharedConfig.promptPath, -// }; diff --git a/core/config/util.ts b/core/config/util.ts index f55848586..8bfe6a84f 100644 --- a/core/config/util.ts +++ b/core/config/util.ts @@ -1,4 +1,4 @@ -import { execSync } from "child_process"; +import fs from "fs"; import os from "os"; import { @@ -121,11 +121,13 @@ export function getModelByRole( * * See here for details: https://github.com/continuedev/continue/issues/940 */ -export function isSupportedLanceDbCpuTarget(ide: IDE) { +export function isSupportedLanceDbCpuTargetForLinux(ide?: IDE) { const CPU_FEATURES_TO_CHECK = ["avx2", "fma"] as const; const globalContext = new GlobalContext(); - const globalContextVal = globalContext.get("isSupportedLanceDbCpuTarget"); + const globalContextVal = globalContext.get( + "isSupportedLanceDbCpuTargetForLinux", + ); // If we've already checked the CPU target, return the cached value if (globalContextVal !== undefined) { @@ -133,51 +135,35 @@ export function isSupportedLanceDbCpuTarget(ide: IDE) { } const arch = os.arch(); - const platform = os.platform(); // This check only applies to x64 //https://github.com/lancedb/lance/issues/2195#issuecomment-2057841311 if (arch !== "x64") { - globalContext.update("isSupportedLanceDbCpuTarget", true); + globalContext.update("isSupportedLanceDbCpuTargetForLinux", true); return true; } try { - const cpuFlags = (() => { - switch (platform) { - case "darwin": - return execSync("sysctl -n machdep.cpu.features") - .toString() - .toLowerCase(); - case "linux": - return execSync("cat /proc/cpuinfo").toString().toLowerCase(); - case "win32": - return execSync("wmic cpu get caption /format:list") - .toString() - .toLowerCase(); - default: - return ""; - } - })(); + const cpuFlags = fs.readFileSync("/proc/cpuinfo", "utf-8").toLowerCase(); - const isSupportedLanceDbCpuTarget = cpuFlags + const isSupportedLanceDbCpuTargetForLinux = cpuFlags ? CPU_FEATURES_TO_CHECK.every((feature) => cpuFlags.includes(feature)) : true; // If it's not a supported CPU target, and it's the first time we are checking, // show a toast to inform the user that we are going to disable indexing. - if (!isSupportedLanceDbCpuTarget) { + if (!isSupportedLanceDbCpuTargetForLinux && ide) { // We offload our async toast to `showUnsupportedCpuToast` to prevent making - // our config loading async upstream of `isSupportedLanceDbCpuTarget` + // our config loading async upstream of `isSupportedLanceDbCpuTargetForLinux` void showUnsupportedCpuToast(ide); } globalContext.update( - "isSupportedLanceDbCpuTarget", - isSupportedLanceDbCpuTarget, + "isSupportedLanceDbCpuTargetForLinux", + isSupportedLanceDbCpuTargetForLinux, ); - return isSupportedLanceDbCpuTarget; + return isSupportedLanceDbCpuTargetForLinux; } catch (error) { // If we can't determine CPU features, default to true return true; @@ -187,11 +173,13 @@ export function isSupportedLanceDbCpuTarget(ide: IDE) { async function showUnsupportedCpuToast(ide: IDE) { const shouldOpenLink = await ide.showToast( "warning", - "Codebase indexing is disabled due to CPU incompatibility", + "Codebase indexing disabled - Your Linux system lacks required CPU features (AVX2, FMA)", "Learn more", ); if (shouldOpenLink) { - void ide.openUrl("https://github.com/continuedev/continue/pull/3551"); + void ide.openUrl( + "https://docs.continue.dev/troubleshooting#i-received-a-codebase-indexing-disabled---your-linux-system-lacks-required-cpu-features-avx2-fma-notification", + ); } } diff --git a/core/config/yaml/clientRender.ts b/core/config/yaml/clientRender.ts deleted file mode 100644 index 14f7e718f..000000000 --- a/core/config/yaml/clientRender.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { - clientRender, - PackageSlug, - PlatformClient, - SecretStore, -} from "@continuedev/config-yaml"; - -import { IDE } from "../.."; -import { ControlPlaneClient } from "../../control-plane/client"; - -export async function clientRenderHelper( - packageSlug: PackageSlug, - unrolledAssistant: string, - ide: IDE, - controlPlaneClient: ControlPlaneClient, -) { - const ideSecretStore: SecretStore = { - get: async function (secretName: string): Promise { - const results = await ide.readSecrets([secretName]); - return results[secretName]; - }, - set: async function ( - secretName: string, - secretValue: string, - ): Promise { - return await ide.writeSecrets({ - [secretName]: secretValue, - }); - }, - }; - - const platformClient: PlatformClient = { - resolveFQSNs: controlPlaneClient.resolveFQSNs.bind(controlPlaneClient), - }; - - 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 a989d2631..fdf73606f 100644 --- a/core/config/yaml/convertFromJson.ts +++ b/core/config/yaml/convertFromJson.ts @@ -15,10 +15,11 @@ export function convertConfigJsonToConfigYaml( name: model.title, // defaultCompletionOptions: model.completionOptions, provider: model.provider, - roles: ["chat"], + roles: ["chat", "edit", "apply", "summarize"], }), ), - // ... tabAutocompleteModels + // TODO + // tabAutocompleteModels // embeddingsModels // rerankModels ], diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index 37abaf83e..b008092e9 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -14,8 +14,8 @@ import { ContinueConfig, IContextProvider, IDE, + IdeInfo, IdeSettings, - IdeType, SlashCommand, } from "../.."; import { slashFromCustomCommand } from "../../commands"; @@ -37,7 +37,7 @@ import { GlobalContext } from "../../util/GlobalContext"; import { getConfigYamlPath } from "../../util/paths"; import { getSystemPromptDotFile } from "../getSystemPromptDotFile"; import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader"; -import { modifyContinueConfigWithSharedConfig } from "../sharedConfig"; +import { modifyAnyConfigWithSharedConfig } from "../sharedConfig"; import { llmsFromModelConfig } from "./models"; @@ -48,7 +48,7 @@ async function loadConfigYaml( ide: IDE, controlPlaneClient: ControlPlaneClient, ): Promise> { - const ideSettings = await ide.getIdeSettings(); + // const ideSettings = await ide.getIdeSettings(); let config = overrideConfigYaml ?? // (ideSettings.continueTestEnvironment === "production" @@ -98,6 +98,7 @@ async function configYamlToContinueConfig( config: AssistantUnrolled, ide: IDE, ideSettings: IdeSettings, + ideInfo: IdeInfo, uniqueId: string, writeLog: (log: string) => Promise, workOsAccessToken: string | undefined, @@ -111,10 +112,8 @@ async function configYamlToContinueConfig( ...(config.prompts?.map(slashFromCustomCommand) ?? []), ], models: [], - tabAutocompleteModels: [], tools: allTools, systemMessage: config.rules?.join("\n"), - embeddingsProvider: new TransformersJsEmbeddingsProvider(), experimental: { modelContextProtocolServers: config.mcpServers?.map((mcpServer) => ({ transport: { @@ -132,59 +131,125 @@ async function configYamlToContinueConfig( faviconUrl: doc.faviconUrl, })), contextProviders: [], + modelsByRole: { + chat: [], + edit: [], + apply: [], + embed: [], + autocomplete: [], + rerank: [], + summarize: [], + }, + selectedModelByRole: { + chat: null, // not currently used - defaultModel on GUI is used + edit: null, // not currently used + apply: null, + embed: null, + autocomplete: null, + rerank: null, + summarize: null, + }, + data: config.data, }; // Models const modelsArrayRoles: ModelRole[] = ["chat", "summarize", "apply", "edit"]; for (const model of config.models ?? []) { - model.roles = model.roles ?? ["chat"]; // Default to chat role if not specified + model.roles = model.roles ?? modelsArrayRoles; // Default to all 4 chat-esque roles if not specified + const llms = await llmsFromModelConfig( + model, + ide, + uniqueId, + ideSettings, + writeLog, + platformConfigMetadata, + continueConfig.systemMessage, + ); + + // if (modelsArrayRoles.some((role) => model.roles?.includes(role))) { - // Main model array - const llms = await llmsFromModelConfig( - model, - ide, - uniqueId, - ideSettings, - writeLog, - platformConfigMetadata, - continueConfig.systemMessage, - ); continueConfig.models.push(...llms); } + if (model.roles?.includes("chat")) { + continueConfig.modelsByRole.chat.push(...llms); + } + + if (model.roles?.includes("summarize")) { + continueConfig.modelsByRole.summarize.push(...llms); + } + + if (model.roles?.includes("apply")) { + continueConfig.modelsByRole.apply.push(...llms); + } + + if (model.roles?.includes("edit")) { + continueConfig.modelsByRole.edit.push(...llms); + } + if (model.roles?.includes("autocomplete")) { - // Autocomplete models array - const llms = await llmsFromModelConfig( - model, - ide, - uniqueId, - ideSettings, - writeLog, - platformConfigMetadata, - continueConfig.systemMessage, - ); - continueConfig.tabAutocompleteModels?.push(...llms); + continueConfig.modelsByRole.autocomplete.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("embed")) { + const { provider, ...options } = model; + const embeddingsProviderClass = allEmbeddingsProviders[provider]; + if (embeddingsProviderClass) { + if ( + embeddingsProviderClass.name === "_TransformersJsEmbeddingsProvider" + ) { + continueConfig.modelsByRole.embed.push(new embeddingsProviderClass()); + } else { + continueConfig.modelsByRole.embed.push( + new embeddingsProviderClass( + options, + (url: string | URL, init: any) => + fetchwithRequestOptions(url, init, { + ...options.requestOptions, + }), + ), + ); + } + } else { + errors.push({ + fatal: false, + message: `Unsupported embeddings model provider found: ${provider}`, + }); + } } - if ( - model.roles?.includes("edit") && - !continueConfig.experimental?.modelRoles?.inlineEdit - ) { - continueConfig.experimental ??= {}; - continueConfig.experimental!.modelRoles ??= {}; - continueConfig.experimental!.modelRoles!.inlineEdit = model.name; + if (model.roles?.includes("rerank")) { + const { provider, ...options } = model; + const rerankerClass = AllRerankers[provider]; + if (rerankerClass) { + continueConfig.modelsByRole.rerank.push( + new rerankerClass(options, (url: string | URL, init: any) => + fetchwithRequestOptions(url, init, { + ...options.requestOptions, + }), + ), + ); + } else { + errors.push({ + fatal: false, + message: `Unsupported reranking model provider found: ${provider}`, + }); + } } } + // Add transformers js to the embed models in vs code if not already added + if ( + ideInfo.ideType === "vscode" && + !continueConfig.modelsByRole.embed.find( + (m) => m.providerName === "transformers.js", + ) + ) { + continueConfig.modelsByRole.embed.push( + new TransformersJsEmbeddingsProvider(), + ); + } + if (allowFreeTrial) { // Obtain auth token (iff free trial being used) const freeTrialModels = continueConfig.models.filter( @@ -203,8 +268,6 @@ async function configYamlToContinueConfig( ); } - // TODO: Split into model roles. - // Context providers const codebaseContextParams: IContextProvider[] = (config.context || []).find((cp) => cp.provider === "codebase")?.params || @@ -243,51 +306,6 @@ async function configYamlToContinueConfig( 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"), - ); - if (embedConfig) { - const { provider, ...options } = embedConfig; - const embeddingsProviderClass = allEmbeddingsProviders[provider]; - if (embeddingsProviderClass) { - if ( - embeddingsProviderClass.name === "_TransformersJsEmbeddingsProvider" - ) { - continueConfig.embeddingsProvider = new embeddingsProviderClass(); - } else { - continueConfig.embeddingsProvider = new embeddingsProviderClass( - options, - (url: string | URL, init: any) => - fetchwithRequestOptions(url, init, { - ...options.requestOptions, - }), - ); - } - } - } - - // Reranker - // IMPORTANT this currently will grab the first model found with a rerank role - const rerankConfig = config.models?.find((model) => - model.roles?.includes("rerank"), - ); - if (rerankConfig) { - const { provider, ...options } = rerankConfig; - const rerankerClass = AllRerankers[provider]; - - if (rerankerClass) { - continueConfig.reranker = new rerankerClass( - options, - (url: string | URL, init: any) => - fetchwithRequestOptions(url, init, { - ...options.requestOptions, - }), - ); - } - } - // Apply MCP if specified const mcpManager = MCPManagerSingleton.getInstance(); await Promise.all( @@ -341,7 +359,7 @@ export async function loadContinueConfigFromYaml( ide: IDE, workspaceConfigs: string[], ideSettings: IdeSettings, - ideType: IdeType, + ideInfo: IdeInfo, uniqueId: string, writeLog: (log: string) => Promise, workOsAccessToken: string | undefined, @@ -351,7 +369,7 @@ export async function loadContinueConfigFromYaml( ): Promise> { const rawYaml = overrideConfigYaml === undefined - ? fs.readFileSync(getConfigYamlPath(ideType), "utf-8") + ? fs.readFileSync(getConfigYamlPath(ideInfo.ideType), "utf-8") : ""; const configYamlResult = await loadConfigYaml( @@ -374,6 +392,7 @@ export async function loadContinueConfigFromYaml( configYamlResult.config, ide, ideSettings, + ideInfo, uniqueId, writeLog, workOsAccessToken, @@ -392,10 +411,13 @@ export async function loadContinueConfigFromYaml( // Apply shared config // TODO: override several of these values with user/org shared config const sharedConfig = new GlobalContext().getSharedConfig(); - const withShared = modifyContinueConfigWithSharedConfig( + const withShared = modifyAnyConfigWithSharedConfig( continueConfig, sharedConfig, ); + if (withShared.allowAnonymousTelemetry === undefined) { + withShared.allowAnonymousTelemetry = true; + } return { config: withShared, diff --git a/core/config/yaml/models.ts b/core/config/yaml/models.ts index e6d0ef00a..c6916b010 100644 --- a/core/config/yaml/models.ts +++ b/core/config/yaml/models.ts @@ -51,6 +51,55 @@ async function modelConfigToBaseLLM( promptTemplates: model.promptTemplates, }; + if (model.embedOptions?.maxBatchSize) { + options.maxEmbeddingBatchSize = model.embedOptions.maxBatchSize; + } + if (model.embedOptions?.maxChunkSize) { + options.maxEmbeddingChunkSize = model.embedOptions.maxChunkSize; + } + + // These are params that are at model config level in JSON + // But we decided to move to nested `env` in YAML + // Since types vary and we don't want to blindly spread env for now, + // Each one is handled individually here + const env = model.env ?? {}; + if ( + "useLegacyCompletionsEndpoint" in env && + typeof env.useLegacyCompletionsEndpoint === "boolean" + ) { + options.useLegacyCompletionsEndpoint = env.useLegacyCompletionsEndpoint; + } + if ("apiType" in env && typeof env.apiType === "string") { + options.apiType = env.apiType; + } + if ("apiVersion" in env && typeof env.apiVersion === "string") { + options.apiVersion = env.apiVersion; + } + if ("deployment" in env && typeof env.deployment === "string") { + options.deployment = env.deployment; + } + if ("deploymentId" in env && typeof env.deploymentId === "string") { + options.deploymentId = env.deploymentId; + } + if ("projectId" in env && typeof env.projectId === "string") { + options.projectId = env.projectId; + } + if ("region" in env && typeof env.region === "string") { + options.region = env.region; + } + if ("profile" in env && typeof env.profile === "string") { + options.profile = env.profile; + } + if ("modelArn" in env && typeof env.modelArn === "string") { + options.modelArn = env.modelArn; + } + if ("aiGatewaySlug" in env && typeof env.aiGatewaySlug === "string") { + options.aiGatewaySlug = env.aiGatewaySlug; + } + if ("accountId" in env && typeof env.accountId === "string") { + options.accountId = env.accountId; + } + const llm = new cls(options); return llm; } diff --git a/core/context/providers/DocsContextProvider.ts b/core/context/providers/DocsContextProvider.ts index cb8e926d5..f4b816f33 100644 --- a/core/context/providers/DocsContextProvider.ts +++ b/core/context/providers/DocsContextProvider.ts @@ -23,7 +23,7 @@ class DocsContextProvider extends BaseContextProvider { // Todo: consider a different renderInline so that when multiple docs are referenced in one message, // Or the doc has an odd name unrelated to the content // The name of the doc itself doesn't skew the embedding results - // renderInlineAs: "", + renderInlineAs: "", }; constructor(options: any) { diff --git a/core/context/providers/GitLabMergeRequestContextProvider.ts b/core/context/providers/GitLabMergeRequestContextProvider.ts index 3e8f77a67..b4d3fe2ed 100644 --- a/core/context/providers/GitLabMergeRequestContextProvider.ts +++ b/core/context/providers/GitLabMergeRequestContextProvider.ts @@ -94,7 +94,7 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider { }); } - private async getRemoteBranchName( + private async getRemoteBranchInfo( extras: ContextProviderExtras, ): Promise { const subprocess = await getSubprocess(extras); @@ -121,9 +121,16 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider { const remoteUrl = await subprocess(`git remote get-url ${branchRemote}`); - const urlMatches = /:(?.*).git/.exec(remoteUrl); + let urlMatches: RegExpExecArray | null; + if (/https?.*/.test(remoteUrl)) { + const pathname = new URL(remoteUrl).pathname; + urlMatches = /\/(?.*?)(?:(?=\.git)|$)/.exec(pathname) + } else { + // ssh + urlMatches = /:(?.*).git/.exec(remoteUrl) + } - const project = urlMatches?.groups?.project ?? null; + const project = urlMatches?.groups?.projectPath ?? null; return { branch: remoteBranch, @@ -135,7 +142,7 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider { query: string, extras: ContextProviderExtras, ): Promise { - const { branch, project } = await this.getRemoteBranchName(extras); + const { branch, project } = await this.getRemoteBranchInfo(extras); const api = await this.getApi(); diff --git a/core/context/providers/_context-providers.test.ts b/core/context/providers/_context-providers.test.ts index e877c10e7..345d21e37 100644 --- a/core/context/providers/_context-providers.test.ts +++ b/core/context/providers/_context-providers.test.ts @@ -42,10 +42,10 @@ async function getContextProviderExtras( fullInput, ide, config, - embeddingsProvider: config.embeddingsProvider, + embeddingsProvider: config.selectedModelByRole.embed, fetch: fetch, llm: config.models[0], - reranker: config.reranker, + reranker: config.selectedModelByRole.rerank, selectedCode: [], }; } diff --git a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts index 0ba94964c..d91931327 100644 --- a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts @@ -7,6 +7,8 @@ import { FullTextSearchCodebaseIndex } from "../../../indexing/FullTextSearchCod import { LanceDbIndex } from "../../../indexing/LanceDbIndex"; import { recentlyEditedFilesCache } from "../recentlyEditedFilesCache"; +const DEFAULT_CHUNK_SIZE = 384; + export interface RetrievalPipelineOptions { llm: ILLM; config: ContinueConfig; @@ -16,13 +18,13 @@ export interface RetrievalPipelineOptions { nFinal: number; tags: BranchAndDir[]; filterDirectory?: string; - includeEmbeddings?: boolean; // Used to handle JB w/o an embeddings model } export interface RetrievalPipelineRunArguments { query: string; tags: BranchAndDir[]; filterDirectory?: string; + includeEmbeddings: boolean; } export interface IRetrievalPipeline { @@ -31,12 +33,21 @@ export interface IRetrievalPipeline { export default class BaseRetrievalPipeline implements IRetrievalPipeline { private ftsIndex = new FullTextSearchCodebaseIndex(); - private lanceDbIndex: LanceDbIndex; + private lanceDbIndex: LanceDbIndex | null = null; constructor(protected readonly options: RetrievalPipelineOptions) { - this.lanceDbIndex = new LanceDbIndex( - options.config.embeddingsProvider, - (uri) => options.ide.readFile(uri), + void this.initLanceDb(); + } + + private async initLanceDb() { + const embedModel = this.options.config.selectedModelByRole.embed; + + if (!embedModel) { + return; + } + + this.lanceDbIndex = await LanceDbIndex.create(embedModel, (uri) => + this.options.ide.readFile(uri), ); } @@ -60,6 +71,11 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline { return trigrams; } + private escapeFtsQueryString(query: string): string { + const escapedDoubleQuotes = query.replace(/"/g, '""'); + return `"${escapedDoubleQuotes}"`; + } + protected async retrieveFts( args: RetrievalPipelineRunArguments, n: number, @@ -69,7 +85,8 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline { return []; } - const tokens = this.getCleanedTrigrams(args.query).join(" OR "); + const tokensRaw = this.getCleanedTrigrams(args.query).join(" OR "); + const tokens = this.escapeFtsQueryString(tokensRaw); return await this.ftsIndex.retrieve({ n, @@ -109,7 +126,8 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline { filepath, contents, maxChunkSize: - this.options.config.embeddingsProvider.maxEmbeddingChunkSize, + this.options.config.selectedModelByRole.embed + ?.maxEmbeddingChunkSize ?? DEFAULT_CHUNK_SIZE, digest: filepath, }); @@ -125,6 +143,13 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline { input: string, n: number, ): Promise { + if (!this.lanceDbIndex) { + console.warn( + "LanceDB index not available, skipping embeddings retrieval", + ); + return []; + } + return this.lanceDbIndex.retrieve( input, n, diff --git a/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts index af72c0639..889005414 100644 --- a/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts @@ -9,7 +9,7 @@ import BaseRetrievalPipeline, { export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline { async run(args: RetrievalPipelineRunArguments): Promise { - const { input, nFinal, filterDirectory, includeEmbeddings } = this.options; + const { input, nFinal, filterDirectory, config } = this.options; // We give 1/4 weight to recently edited files, 1/4 to full text search, // and the remaining 1/2 to embeddings @@ -21,7 +21,7 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline { const ftsChunks = await this.retrieveFts(args, ftsNFinal); - const embeddingsChunks = includeEmbeddings + const embeddingsChunks = !!config.selectedModelByRole.embed ? await this.retrieveEmbeddings(input, embeddingsNFinal) : []; diff --git a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts index 7c7e69860..5fc4f240b 100644 --- a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts @@ -12,13 +12,12 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { private async _retrieveInitial( args: RetrievalPipelineRunArguments, ): Promise { - const { input, nRetrieve, filterDirectory, includeEmbeddings } = - this.options; + const { input, nRetrieve, filterDirectory, config } = this.options; let retrievalResults: Chunk[] = []; const ftsChunks = await this.retrieveFts(args, nRetrieve); - const embeddingsChunks = includeEmbeddings + const embeddingsChunks = !!config.selectedModelByRole.embed ? await this.retrieveEmbeddings(input, nRetrieve) : []; const recentlyEditedFilesChunks = @@ -42,7 +41,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { if (filterDirectory) { // Backup if the individual retrieval methods don't listen retrievalResults = retrievalResults.filter( - (chunk) => !!findUriInDirs(chunk.filepath, [filterDirectory]), + (chunk) => !!findUriInDirs(chunk.filepath, [filterDirectory]).foundInDir, ); } @@ -53,17 +52,18 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { } private async _rerank(input: string, chunks: Chunk[]): Promise { - if (!this.options.config.reranker) { - throw new Error("No reranker provided"); + if (!this.options.config.selectedModelByRole.rerank) { + throw new Error("No reranker set up"); } // remove empty chunks -- some APIs fail on that chunks = chunks.filter((chunk) => chunk.content); - let scores: number[] = await this.options.config.reranker.rerank( - input, - chunks, - ); + let scores: number[] = + await this.options.config.selectedModelByRole.rerank.rerank( + input, + chunks, + ); // Filter out low-scoring results let results = chunks; diff --git a/core/context/retrieval/repoMapRequest.ts b/core/context/retrieval/repoMapRequest.ts index 39223321b..5637019ad 100644 --- a/core/context/retrieval/repoMapRequest.ts +++ b/core/context/retrieval/repoMapRequest.ts @@ -2,7 +2,6 @@ import { Chunk, ContinueConfig, IDE, ILLM } from "../.."; import { getModelByRole } from "../../config/util"; import generateRepoMap from "../../util/generateRepoMap"; import { renderChatMessage } from "../../util/messageContent"; -import { getUriPathBasename } from "../../util/uri"; const SUPPORTED_MODEL_TITLE_FAMILIES = [ "claude-3", @@ -16,7 +15,7 @@ function isSupportedModel( config: ContinueConfig, modelTitle?: string, ): boolean { - if (config.experimental?.modelRoles?.applyCodeBlock) { + if (config.experimental?.modelRoles?.repoMapFileSelection) { return true; } diff --git a/core/context/retrieval/retrieval.ts b/core/context/retrieval/retrieval.ts index 0f0a238eb..3b8e98427 100644 --- a/core/context/retrieval/retrieval.ts +++ b/core/context/retrieval/retrieval.ts @@ -1,5 +1,4 @@ import { BranchAndDir, ContextItem, ContextProviderExtras } from "../../"; -import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider"; import { getUriDescription } from "../../util/uri"; import { INSTRUCTIONS_BASE_ITEM } from "../providers/utils"; @@ -14,26 +13,16 @@ export async function retrieveContextItemsFromEmbeddings( options: any | undefined, filterDirectory: string | undefined, ): Promise { - if (!extras.embeddingsProvider) { - return []; - } - - // transformers.js not supported in JetBrains IDEs right now - - const isJetBrainsAndTransformersJs = - extras.embeddingsProvider.providerName === - TransformersJsEmbeddingsProvider.providerName && - (await extras.ide.getIdeInfo()).ideType === "jetbrains"; - - if (isJetBrainsAndTransformersJs) { - void extras.ide.showToast( - "warning", - "Codebase retrieval is limited when `embeddingsProvider` is empty or set to `transformers.js` in JetBrains. " + - "You can use Ollama to set up local embeddings, use our 'free-trial', " + - "or configure your own. See here to learn more: " + - "https://docs.continue.dev/customize/model-types/embeddings", - ); - } + // Currently you can use codebase without an embeddings provider and it will just skip the embeddings inputs + // if (!extras.embeddingsProvider) { + // void extras.ide.showToast( + // "warning", + // "Set up an embeddings model to use this feature. Visit the docs to learn more: " + + // "https://docs.continue.dev/customize/model-roles/embeddings", + // ); + // return []; + // } + const includeEmbeddings = !!extras.config.selectedModelByRole.embed; // Get tags to retrieve for const workspaceDirs = await extras.ide.getWorkspaceDirs(); @@ -78,7 +67,6 @@ export async function retrieveContextItemsFromEmbeddings( input: extras.fullInput, llm: extras.llm, config: extras.config, - includeEmbeddings: !isJetBrainsAndTransformersJs, }; const pipeline = new pipelineType(pipelineOptions); @@ -86,16 +74,17 @@ export async function retrieveContextItemsFromEmbeddings( tags, filterDirectory, query: extras.fullInput, + includeEmbeddings, }); if (results.length === 0) { if (extras.config.disableIndexing) { - void extras.ide.showToast("warning", "No embeddings results found."); + void extras.ide.showToast("warning", "No results found."); return []; } else { void extras.ide.showToast( "warning", - "No embeddings results found. If you think this is an error, re-index your codebase.", + "No results found. If you think this is an error, re-index your codebase.", ); // TODO - add "re-index" option to warning message which clears and reindexes codebase } diff --git a/core/control-plane/client.ts b/core/control-plane/client.ts index 7d0e03cc8..9dcf40b6d 100644 --- a/core/control-plane/client.ts +++ b/core/control-plane/client.ts @@ -40,7 +40,10 @@ export class ControlPlaneClient { private readonly ideSettingsPromise: Promise, ) {} - async resolveFQSNs(fqsns: FQSN[]): Promise<(SecretResult | undefined)[]> { + async resolveFQSNs( + fqsns: FQSN[], + orgScopeId: string | null, + ): Promise<(SecretResult | undefined)[]> { const userId = await this.userId; if (!userId) { throw new Error("No user id"); @@ -48,7 +51,7 @@ export class ControlPlaneClient { const resp = await this.request("ide/sync-secrets", { method: "POST", - body: JSON.stringify({ fqsns }), + body: JSON.stringify({ fqsns, orgScopeId }), }); return (await resp.json()) as any; } @@ -183,21 +186,4 @@ export class ControlPlaneClient { }); return ((await resp.json()) as any).settings; } - - async syncSecrets(secretNames: string[]): Promise> { - const userId = await this.userId; - if (!userId) { - throw new Error("No user id"); - } - - try { - const resp = await this.request("ide/sync-secrets", { - method: "POST", - body: JSON.stringify({ secretNames }), - }); - return (await resp.json()) as any; - } catch (e) { - return {}; - } - } } diff --git a/core/control-plane/env.ts b/core/control-plane/env.ts index ca8a85a12..288901cab 100644 --- a/core/control-plane/env.ts +++ b/core/control-plane/env.ts @@ -1,4 +1,3 @@ -import fetch from "node-fetch"; import * as fs from "node:fs"; import { IdeSettings } from ".."; import { getStagingEnvironmentDotFilePath } from "../util/paths"; @@ -62,30 +61,31 @@ const LOCAL_ENV: ControlPlaneEnv = { }; 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; + return true; } export async function getControlPlaneEnv( ideSettingsPromise: Promise, ): Promise { const ideSettings = await ideSettingsPromise; - return getControlPlaneEnvSync(ideSettings.continueTestEnvironment); + return getControlPlaneEnvSync( + ideSettings.continueTestEnvironment, + ideSettings.enableControlServerBeta, + ); } export function getControlPlaneEnvSync( ideTestEnvironment: IdeSettings["continueTestEnvironment"], + enableControlServerBeta: IdeSettings["enableControlServerBeta"], ): ControlPlaneEnv { if (fs.existsSync(getStagingEnvironmentDotFilePath())) { return STAGING_ENV; } + if (enableControlServerBeta === true) { + return PRODUCTION_ENV; + } + const env = ideTestEnvironment === "production" ? "hub" @@ -110,5 +110,8 @@ export async function useHub( ideSettingsPromise: Promise, ): Promise { const ideSettings = await ideSettingsPromise; + if (ideSettings.enableControlServerBeta) { + return false; + } return ideSettings.continueTestEnvironment !== "none"; } diff --git a/core/core.ts b/core/core.ts index 8a9df812e..d5b0f6d8e 100644 --- a/core/core.ts +++ b/core/core.ts @@ -1,7 +1,4 @@ -import path from "path"; - import { fetchwithRequestOptions } from "@continuedev/fetch"; -import ignore from "ignore"; import * as URI from "uri-js"; import { v4 as uuidv4 } from "uuid"; @@ -14,28 +11,29 @@ import { setupQuickstartConfig, } from "./config/onboarding"; import { addContextProvider, addModel, deleteModel } from "./config/util"; +import CodebaseContextProvider from "./context/providers/CodebaseContextProvider"; +import CurrentFileContextProvider from "./context/providers/CurrentFileContextProvider"; import { recentlyEditedFilesCache } from "./context/retrieval/recentlyEditedFilesCache"; import { ContinueServerClient } from "./continueServer/stubs/client"; import { getAuthUrlForTokenPage } from "./control-plane/auth/index"; import { getControlPlaneEnv } from "./control-plane/env"; +import { DevDataSqliteDb } from "./data/devdataSqlite"; +import { DataLogger } from "./data/log"; import { streamDiffLines } from "./edit/streamDiffLines"; import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer"; import DocsService from "./indexing/docs/DocsService"; import { getAllSuggestedDocs } from "./indexing/docs/suggestions"; -import { defaultIgnoreFile } from "./indexing/ignore.js"; import Ollama from "./llm/llms/Ollama"; import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile"; import { callTool } from "./tools/callTool"; import { ChatDescriber } from "./util/chatDescriber"; import { clipboardCache } from "./util/clipboardCache"; -import { logDevData } from "./util/devdata"; -import { DevDataSqliteDb } from "./util/devdataSqlite"; import { GlobalContext } from "./util/GlobalContext"; import historyManager from "./util/history"; import { editConfigJson, getConfigJsonPath, - setupInitialDotContinueDirectory, + migrateV1DevDataFiles, } from "./util/paths"; import { localPathToUri } from "./util/pathToUri"; import { Telemetry } from "./util/posthog"; @@ -51,8 +49,7 @@ import { type IndexingProgressUpdate, } from "."; -import CodebaseContextProvider from "./context/providers/CodebaseContextProvider"; -import CurrentFileContextProvider from "./context/providers/CurrentFileContextProvider"; +import { shouldIgnore } from "./indexing/shouldIgnore"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import type { IMessenger, Message } from "./protocol/messenger"; @@ -94,7 +91,7 @@ export class Core { private readonly onWrite: (text: string) => Promise = async () => {}, ) { // Ensure .continue directory is created - setupInitialDotContinueDirectory(); + migrateV1DevDataFiles(); this.codebaseIndexingState = { status: "loading", @@ -102,6 +99,7 @@ export class Core { progress: 0, }; + const ideInfoPromise = messenger.request("getIdeInfo", undefined); const ideSettingsPromise = messenger.request("getIdeSettings", undefined); const sessionInfoPromise = messenger.request("getControlPlaneSessionInfo", { silent: true, @@ -130,7 +128,8 @@ export class Core { }); // update additional submenu context providers registered via VSCode API - const additionalProviders = this.configHandler.getAdditionalSubmenuContextProviders(); + const additionalProviders = + this.configHandler.getAdditionalSubmenuContextProviders(); if (additionalProviders.length > 0) { this.messenger.send("refreshSubmenuItems", { providers: additionalProviders, @@ -146,6 +145,12 @@ export class Core { }), ); + // Dev Data Logger + const dataLogger = DataLogger.getInstance(); + dataLogger.core = this; + dataLogger.ideInfoPromise = ideInfoPromise; + dataLogger.ideSettingsPromise = ideSettingsPromise; + // Codebase Indexer and ContinueServerClient depend on IdeSettings let codebaseIndexerResolve: (_: any) => void | undefined; this.codebaseIndexerPromise = new Promise( @@ -192,12 +197,10 @@ export class Core { const getLlm = async () => { const { config } = await this.configHandler.loadConfig(); - const selected = this.globalContext.get("selectedTabAutocompleteModel"); - return ( - config?.tabAutocompleteModels?.find( - (model) => model.title === selected, - ) ?? config?.tabAutocompleteModels?.[0] - ); + if (!config) { + return undefined; + } + return config.selectedModelByRole.autocomplete ?? undefined; }; this.completionProvider = new CompletionProvider( this.configHandler, @@ -231,11 +234,6 @@ export class Core { } }); - on("update/selectTabAutocompleteModel", async (msg) => { - this.globalContext.update("selectedTabAutocompleteModel", msg.data); - void this.configHandler.reloadConfig(); - }); - // Special on("abort", (msg) => { this.abortedMessageIds.add(msg.messageId); @@ -266,8 +264,8 @@ export class Core { }); // Dev data - on("devdata/log", (msg) => { - logDevData(msg.data.tableName, msg.data.data); + on("devdata/log", async (msg) => { + void DataLogger.getInstance().logDevData(msg.data); }); // Edit config @@ -305,13 +303,28 @@ export class Core { return this.configHandler.listProfiles(); }); + on("config/refreshProfiles", async (msg) => { + await this.configHandler.loadAssistantsForSelectedOrg(); + }); + on("config/addContextProvider", async (msg) => { addContextProvider(msg.data, this.configHandler); }); on("config/updateSharedConfig", async (msg) => { - this.globalContext.updateSharedConfig(msg.data); + const newSharedConfig = this.globalContext.updateSharedConfig(msg.data); await this.configHandler.reloadConfig(); + return newSharedConfig; + }); + + on("config/updateSelectedModel", async (msg) => { + const newSelectedModels = this.globalContext.updateSelectedModel( + msg.data.profileId, + msg.data.role, + msg.data.title, + ); + await this.configHandler.reloadConfig(); + return newSelectedModels; }); on("controlPlane/openUrl", async (msg) => { @@ -391,11 +404,11 @@ export class Core { const items = await provider.getContextItems(query, { config, llm, - embeddingsProvider: config.embeddingsProvider, + embeddingsProvider: config.selectedModelByRole.embed, fullInput, ide, selectedCode, - reranker: config.reranker, + reranker: config.selectedModelByRole.rerank, fetch: (url, init) => fetchwithRequestOptions(url, init, config.requestOptions), }); @@ -416,26 +429,25 @@ export class Core { 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", - ); - } - }); - } + // After removing transformers JS embeddings provider from jetbrains + // Should no longer see this error + // if (e.message.toLowerCase().includes("embeddings provider")) { + // 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-roles/embeddings", + // ); + // } + // }); + // } } if (!knownError) { void this.ide.showToast( @@ -641,6 +653,7 @@ export class Core { params, historyIndex, selectedCode, + completionOptions, } = msg.data; const { config } = await configHandler.loadConfig(); @@ -689,6 +702,7 @@ export class Core { config, fetch: (url, init) => fetchwithRequestOptions(url, init, config.requestOptions), + completionOptions, })) { if (abortedMessageIds.has(msg.messageId)) { abortedMessageIds.delete(msg.messageId); @@ -812,6 +826,10 @@ export class Core { // Codebase indexing on("index/forceReIndex", async ({ data }) => { + const { config } = await this.configHandler.loadConfig(); + if (!config || config.disableIndexing) { + return; // TODO silent in case of commands? + } if (data?.shouldClearIndexes) { const codebaseIndexer = await this.codebaseIndexerPromise; await codebaseIndexer.clearIndexes(); @@ -869,30 +887,51 @@ export class Core { uri.endsWith(".gitignore") ) { // Reindex the workspaces - this.invoke("index/forceReIndex", undefined); + this.invoke("index/forceReIndex", { + shouldClearIndexes: true, + }); } else { - // Reindex the file - await this.refreshCodebaseIndexFiles([uri]); + const { config } = await this.configHandler.loadConfig(); + if (config && !config.disableIndexing) { + // Reindex the file + const ignore = await shouldIgnore(uri, this.ide); + if (!ignore) { + await this.refreshCodebaseIndexFiles([uri]); + } + } } } } }); - on("files/created", async ({ data }) => { - if (data?.uris?.length) { + const refreshIfNotIgnored = async (uris: string[]) => { + const toRefresh: string[] = []; + for (const uri of uris) { + const ignore = await shouldIgnore(uri, ide); + if (!ignore) { + toRefresh.push(uri); + } + } + if (toRefresh.length > 0) { this.messenger.send("refreshSubmenuItems", { providers: ["file"], }); - await this.refreshCodebaseIndexFiles(data.uris); + const { config } = await this.configHandler.loadConfig(); + if (config && !config.disableIndexing) { + await this.refreshCodebaseIndexFiles(toRefresh); + } + } + }; + + on("files/created", async ({ data }) => { + if (data?.uris?.length) { + void refreshIfNotIgnored(data.uris); } }); on("files/deleted", async ({ data }) => { if (data?.uris?.length) { - this.messenger.send("refreshSubmenuItems", { - providers: ["file"], - }); - await this.refreshCodebaseIndexFiles(data.uris); + void refreshIfNotIgnored(data.uris); } }); on("files/opened", async ({ data }) => { @@ -933,15 +972,21 @@ export class Core { }); // - on("didChangeSelectedProfile", (msg) => { - void this.configHandler.setSelectedProfile(msg.data.id); - void this.configHandler.reloadConfig(); + on("didChangeSelectedProfile", async (msg) => { + await this.configHandler.setSelectedProfile(msg.data.id); + await this.configHandler.reloadConfig(); }); - on("didChangeSelectedOrg", (msg) => { - void this.configHandler.setSelectedOrgId(msg.data.id); - void this.configHandler.reloadConfig(); - void this.configHandler.loadAssistantsForSelectedOrg(); + on("didChangeSelectedOrg", async (msg) => { + await this.configHandler.setSelectedOrgId(msg.data.id); + await this.configHandler.loadAssistantsForSelectedOrg(); + if (msg.data.profileId) { + this.invoke("didChangeSelectedProfile", { + id: msg.data.profileId, + }); + } else { + await this.configHandler.reloadConfig(); + } }); on("didChangeControlPlaneSessionInfo", async (msg) => { @@ -958,19 +1003,15 @@ export class Core { }); on("didChangeActiveTextEditor", async ({ data: { filepath } }) => { - const ignoreInstance = ignore().add(defaultIgnoreFile); - let rootDirectory = await this.ide.getWorkspaceDirs(); - const relativeFilePath = path.relative(rootDirectory[0], filepath); try { - if (!ignoreInstance.ignores(relativeFilePath)) { + const ignore = shouldIgnore(filepath, this.ide); + if (!ignore) { recentlyEditedFilesCache.set(filepath, filepath); } } catch (e) { - if (e instanceof RangeError) { - // do nothing, this can happen when editing a file outside the workspace such as `../extensions/.continue-debug/config.json` - } else { - console.debug("unhandled ignores error", relativeFilePath, e); - } + console.error( + `didChangeActiveTextEditor: failed to update recentlyEditedFiles cache for ${filepath}`, + ); } }); @@ -1091,6 +1132,7 @@ export class Core { this.messenger.send("refreshSubmenuItems", { providers: "dependsOnIndexing", }); + this.indexingCancellationController = undefined; } // private diff --git a/core/util/devdataSqlite.ts b/core/data/devdataSqlite.ts similarity index 95% rename from core/util/devdataSqlite.ts rename to core/data/devdataSqlite.ts index bd9e45dca..bf713ca6c 100644 --- a/core/util/devdataSqlite.ts +++ b/core/data/devdataSqlite.ts @@ -5,8 +5,9 @@ import sqlite3 from "sqlite3"; import { DatabaseConnection } from "../indexing/refreshIndex.js"; -import { getDevDataSqlitePath } from "./paths.js"; +import { getDevDataSqlitePath } from "../util/paths.js"; +/* The Dev Data SQLITE table is only used for local tokens generated */ export class DevDataSqliteDb { static db: DatabaseConnection | null = null; diff --git a/core/data/log.ts b/core/data/log.ts new file mode 100644 index 000000000..1b810d851 --- /dev/null +++ b/core/data/log.ts @@ -0,0 +1,226 @@ +import fs from "fs"; +import path from "path"; + +import { + allDevEventNames, + DataLogLevel, + DevDataLogEvent, + devDataVersionedSchemas, +} from "@continuedev/config-yaml"; +import { fetchwithRequestOptions } from "@continuedev/fetch"; +import * as URI from "uri-js"; +import { fileURLToPath } from "url"; +import { AnyZodObject } from "zod"; +import { Core } from "../core.js"; +import { IdeInfo, IdeSettings } from "../index.js"; +import { getDevDataFilePath } from "../util/paths.js"; +import { joinPathsToUri } from "../util/uri.js"; + +const DEFAULT_DEV_DATA_LEVEL: DataLogLevel = "all"; +export const LOCAL_DEV_DATA_VERSION = "0.2.0"; +export class DataLogger { + private static instance: DataLogger | null = null; + core?: Core; + ideSettingsPromise?: Promise; + ideInfoPromise?: Promise; + + private constructor() {} + + public static getInstance(): DataLogger { + if (DataLogger.instance === null) { + DataLogger.instance = new DataLogger(); + } + return DataLogger.instance; + } + + async addBaseValues( + body: Record, + eventName: string, + schema: string, + zodSchema: AnyZodObject, + ): Promise> { + const newBody = { ...body }; + const ideSettings = await this.ideSettingsPromise; + const ideInfo = await this.ideInfoPromise; + + if ("eventName" in zodSchema.shape) { + newBody.eventName = eventName; + } + if ("timestamp" in zodSchema.shape) { + newBody.timestamp = new Date().toISOString(); + } + if ("schema" in zodSchema.shape) { + newBody.schema = schema; + } + if ("userAgent" in zodSchema.shape) { + newBody.userAgent = ideInfo + ? `${ideInfo.name}/${ideInfo.version} (Continue/${ideInfo.extensionVersion})` + : "Unknown/Unknown (Continue/Unknown)"; + } + if ("selectedProfileId" in zodSchema.shape) { + newBody.selectedProfileId = + this.core?.configHandler.currentProfile?.profileDescription.id ?? ""; + } + if ("userId" in zodSchema.shape) { + newBody.userId = ideSettings?.userToken ?? ""; + } + + return newBody; + } + + async logDevData(event: DevDataLogEvent) { + // Local logs (always on for all levels) + try { + const filepath: string = getDevDataFilePath( + event.name, + LOCAL_DEV_DATA_VERSION, + ); + const localSchema = + devDataVersionedSchemas[LOCAL_DEV_DATA_VERSION]["all"][event.name]; + + if (!localSchema) { + throw new Error( + `Schema ${LOCAL_DEV_DATA_VERSION} doesn't exist at level "all"`, + ); + } + + const eventDataWithBaseValues = await this.addBaseValues( + event.data, + event.name, + LOCAL_DEV_DATA_VERSION, + localSchema, + ); + + const parsed = localSchema?.safeParse(eventDataWithBaseValues); + if (parsed?.success) { + fs.writeFileSync(filepath, `${JSON.stringify(parsed.data)}\n`, { + flag: "a", + }); + } + } catch (error) { + console.error("Error logging local dev data:", error); + } + + // Remote logs + const config = (await this.core?.configHandler.loadConfig())?.config; + if (config?.data?.length) { + await Promise.allSettled( + config.data.map(async (dataConfig) => { + try { + // First extract the data schema based on the version and level + const { schema } = dataConfig; + + const level = dataConfig.level ?? DEFAULT_DEV_DATA_LEVEL; + + // Skip event if `events` is specified and does not include the event + const events = dataConfig.events ?? allDevEventNames; + if (!events.includes(event.name)) { + return; + } + + const versionSchemas = devDataVersionedSchemas[schema]; + if (!versionSchemas) { + throw new Error( + `Attempting to log dev data to non-existent version ${schema}`, + ); + } + + const levelSchemas = versionSchemas[level]; + if (!levelSchemas) { + throw new Error( + `Attempting to log dev data at level ${level} for version ${schema} which does not exist`, + ); + } + + const zodSchema = levelSchemas[event.name]; + if (!zodSchema) { + throw new Error( + `Attempting to log dev data for event ${event.name} at level ${level} for version ${schema}: no schema found`, + ); + } + + const eventDataWithBaseValues = await this.addBaseValues( + event.data, + event.name, + schema, + zodSchema, + ); + + const parsed = zodSchema.safeParse(eventDataWithBaseValues); + if (!parsed.success) { + throw new Error( + `Failed to parse event data for event ${event.name} and schema ${schema}\n:${parsed.error.toString()}`, + ); + } + + const uriComponents = URI.parse(dataConfig.destination); + + // Send to remote server + if ( + uriComponents.scheme === "https" || + uriComponents.scheme === "http" + ) { + const headers: Record = { + "Content-Type": "application/json", + }; + if (dataConfig.apiKey) { + headers["Authorization"] = `Bearer ${dataConfig.apiKey}`; + } + + // For events going to Continue, overwrite the access token + if ( + uriComponents.host?.endsWith(".continue.dev") || + uriComponents.host === "continue.dev" + ) { + // + const accessToken = + await this.core?.configHandler.controlPlaneClient.getAccessToken(); + headers["Authorization"] = `Bearer ${accessToken}`; + } + const profileId = + this.core?.configHandler.currentProfile?.profileDescription + .id ?? ""; + const response = await fetchwithRequestOptions( + dataConfig.destination, + { + method: "POST", + headers, + body: JSON.stringify({ + name: event.name, + data: parsed.data, + schema, + level, + profileId, + }), + }, + dataConfig.requestOptions, + ); + if (!response.ok) { + throw new Error( + `Post request failed. ${response.status}: ${response.statusText}`, + ); + } + } else if (uriComponents.scheme === "file") { + // Write to jsonc file for local file URIs + const dirUri = joinPathsToUri(dataConfig.destination, schema); + const dirPath = fileURLToPath(dirUri); + + if (!fs.existsSync(dirPath)) { + fs.mkdirSync(dirPath, { recursive: true }); + } + const filepath = path.join(dirPath, `${event.name}.jsonl`); + const jsonLine = JSON.stringify(event.data); + fs.writeFileSync(filepath, `${jsonLine}\n`, { flag: "a" }); + } else { + throw new Error(`Unsupported URI scheme ${uriComponents.scheme}`); + } + } catch (error) { + console.error( + `Error logging data to ${dataConfig.destination}: ${error instanceof Error ? error.message : error}`, + ); + } + }), + ); + } + } +} diff --git a/core/edit/lazy/applyCodeBlock.ts b/core/edit/lazy/applyCodeBlock.ts index 924d1c282..424d4e831 100644 --- a/core/edit/lazy/applyCodeBlock.ts +++ b/core/edit/lazy/applyCodeBlock.ts @@ -18,7 +18,8 @@ export async function applyCodeBlock( llm: ILLM, fastLlm: ILLM, ): Promise<[boolean, AsyncGenerator]> { - if (canUseInstantApply(filename)) { + // This was buggy, removed for now, maybe forever + if (false && canUseInstantApply(filename)) { const diffLines = await deterministicApplyLazyEdit( oldFile, newFile, diff --git a/core/index.d.ts b/core/index.d.ts index 86310d97d..3691ab283 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1,4 +1,4 @@ -import { ModelRole } from "@continuedev/config-yaml"; +import { DataDestination, ModelRole } from "@continuedev/config-yaml"; import Parser from "web-tree-sitter"; import { GetGhTokenArgs } from "./protocol/ide"; declare global { @@ -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; } @@ -60,7 +60,7 @@ export interface IndexingStatus { progress: number; description: string; status: "indexing" | "complete" | "paused" | "failed" | "aborted" | "pending"; - embeddingsProviderId: string; + embeddingsProviderId?: string; isReindexing?: boolean; debugInfo?: string; title: string; @@ -179,8 +179,8 @@ export type FetchFunction = (url: string | URL, init?: any) => Promise; export interface ContextProviderExtras { config: ContinueConfig; fullInput: string; - embeddingsProvider: ILLM; - reranker: ILLM | undefined; + embeddingsProvider: ILLM | null; + reranker: ILLM | null; llm: ILLM; ide: IDE; selectedCode: RangeInFile[]; @@ -478,9 +478,15 @@ export interface LLMOptions { writeLog?: (str: string) => Promise; llmRequestHook?: (model: string, prompt: string) => any; apiKey?: string; + + // continueProperties apiKeyLocation?: string; - aiGatewaySlug?: string; apiBase?: string; + orgScopeId?: string | null; + + onPremProxyUrl?: string | null; + + aiGatewaySlug?: string; cacheBehavior?: CacheBehavior; capabilities?: ModelCapability; roles?: ModelRole[]; @@ -504,14 +510,16 @@ export interface LLMOptions { profile?: string; modelArn?: string; - // AWS and GCP Options + // AWS and VertexAI Options region?: string; - // GCP and Watsonx Options + // VertexAI and Watsonx Options projectId?: string; // IBM watsonx Options deploymentId?: string; + + env?: Record; } type RequireAtLeastOne = Pick< @@ -667,10 +675,10 @@ export interface IDE { getCurrentFile(): Promise< | undefined | { - isUntitled: boolean; - path: string; - contents: string; - } + isUntitled: boolean; + path: string; + contents: string; + } >; getLastFileSaveTimestamp?(): number; @@ -730,6 +738,7 @@ export interface ContinueSDK { selectedCode: RangeInFile[]; config: ContinueConfig; fetch: FetchFunction; + completionOptions?: LLMFullCompletionOptions; } export interface SlashCommand { @@ -853,11 +862,11 @@ export interface CustomCommand { export interface Prediction { type: "content"; content: - | string - | { - type: "text"; - text: string; - }[]; + | string + | { + type: "text"; + text: string; + }[]; } export interface ToolExtras { @@ -921,8 +930,14 @@ export interface ModelDescription { provider: string; model: string; apiKey?: string; + + // continueProperties apiKeyLocation?: string; apiBase?: string; + orgScopeId?: string | null; + + onPremProxyUrl?: string | null; + contextLength?: number; maxStopWords?: number; template?: TemplateType; @@ -943,15 +958,16 @@ export interface EmbedOptions { apiType?: string; apiVersion?: string; requestOptions?: RequestOptions; - maxChunkSize?: number; - maxBatchSize?: number; + maxEmbeddingChunkSize?: number; + maxEmbeddingBatchSize?: number; + // AWS options profile?: string; - // AWS and GCP Options + // AWS and VertexAI Options region?: string; - // GCP and Watsonx Options + // VertexAI and Watsonx Options projectId?: string; } @@ -1018,6 +1034,7 @@ export interface ContinueUIConfig { displayRawMarkdown?: boolean; showChatScrollbar?: boolean; codeWrap?: boolean; + showSessionTabs?: boolean; } export interface ContextMenuConfig { @@ -1029,9 +1046,9 @@ export interface ContextMenuConfig { } export interface ExperimentalModelRoles { + repoMapFileSelection?: string; inlineEdit?: string; applyCodeBlock?: string; - repoMapFileSelection?: string; } export type EditStatus = @@ -1148,6 +1165,7 @@ export interface SerializedContinueConfig { experimental?: ExperimentalConfig; analytics?: AnalyticsConfig; docs?: SiteIndexingConfig[]; + data?: DataDestination[]; } export type ConfigMergeType = "merge" | "overwrite"; @@ -1187,9 +1205,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 */ @@ -1200,6 +1218,7 @@ export interface Config { experimental?: ExperimentalConfig; /** Analytics configuration */ analytics?: AnalyticsConfig; + data?: DataDestination[]; } // in the actual Continue source code @@ -1214,15 +1233,15 @@ export interface ContinueConfig { disableSessionTitles?: boolean; disableIndexing?: boolean; userToken?: string; - embeddingsProvider: ILLM; - tabAutocompleteModels?: ILLM[]; tabAutocompleteOptions?: Partial; ui?: ContinueUIConfig; - reranker?: ILLM; experimental?: ExperimentalConfig; analytics?: AnalyticsConfig; docs?: SiteIndexingConfig[]; tools: Tool[]; + modelsByRole: Record; + selectedModelByRole: Record; + data?: DataDestination[]; } export interface BrowserSerializedContinueConfig { @@ -1236,15 +1255,15 @@ export interface BrowserSerializedContinueConfig { disableIndexing?: boolean; disableSessionTitles?: boolean; userToken?: string; - embeddingsProvider?: string; ui?: ContinueUIConfig; - reranker?: RerankerDescription; experimental?: ExperimentalConfig; analytics?: AnalyticsConfig; docs?: SiteIndexingConfig[]; tools: Tool[]; usePlatform: boolean; tabAutocompleteOptions?: Partial; + modelsByRole: Record; + selectedModelByRole: Record; } // DOCS SUGGESTIONS AND PACKAGE INFO @@ -1280,9 +1299,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/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index 677cc4305..d59f0ded8 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -5,8 +5,8 @@ import { IContinueServerClient } from "../continueServer/interface.js"; import { IDE, IndexingProgressUpdate, IndexTag } from "../index.js"; import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceInfo.js"; import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js"; - import { findUriInDirs, getUriPathBasename } from "../util/uri.js"; + import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js"; import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js"; import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex.js"; @@ -15,6 +15,7 @@ import { getComputeDeleteAddRemove } from "./refreshIndex.js"; import { CodebaseIndex, IndexResultType, + PathAndCacheKey, RefreshIndexResults, } from "./types.js"; import { walkDirAsync } from "./walkDir.js"; @@ -80,24 +81,66 @@ export class CodebaseIndexer { return []; } - const indexes = [ + const embeddingsModel = config.selectedModelByRole.embed; + if (!embeddingsModel) { + return []; + } + + const indexes: CodebaseIndex[] = [ new ChunkCodebaseIndex( this.ide.readFile.bind(this.ide), this.continueServerClient, - config.embeddingsProvider.maxEmbeddingChunkSize, + embeddingsModel.maxEmbeddingChunkSize, ), // Chunking must come first - new LanceDbIndex( - config.embeddingsProvider, - this.ide.readFile.bind(this.ide), - this.continueServerClient, - ), - new FullTextSearchCodebaseIndex(), - new CodeSnippetsCodebaseIndex(this.ide), ]; + const lanceDbIndex = await LanceDbIndex.create( + embeddingsModel, + this.ide.readFile.bind(this.ide), + this.continueServerClient, + ); + + if (lanceDbIndex) { + indexes.push(lanceDbIndex); + } + + indexes.push( + new FullTextSearchCodebaseIndex(), + new CodeSnippetsCodebaseIndex(this.ide), + ); + return indexes; } + private totalIndexOps(results: RefreshIndexResults): number { + return ( + results.compute.length + + results.del.length + + results.addTag.length + + results.removeTag.length + ); + } + + private singleFileIndexOps( + results: RefreshIndexResults, + lastUpdated: PathAndCacheKey[], + filePath: string, + ): [RefreshIndexResults, PathAndCacheKey[]] { + const filterFn = (item: PathAndCacheKey) => item.path === filePath; + const compute = results.compute.filter(filterFn); + const del = results.del.filter(filterFn); + const addTag = results.addTag.filter(filterFn); + const removeTag = results.removeTag.filter(filterFn); + const newResults = { + compute, + del, + addTag, + removeTag, + }; + const newLastUpdated = lastUpdated.filter(filterFn); + return [newResults, newLastUpdated]; + } + public async refreshFile( file: string, workspaceDirs: string[], @@ -115,26 +158,28 @@ export class CodebaseIndexer { const repoName = await this.ide.getRepoName(foundInDir); const indexesToBuild = await this.getIndexesToBuild(); const stats = await this.ide.getFileStats([file]); + const filePath = Object.keys(stats)[0]; for (const index of indexesToBuild) { const tag = { directory: foundInDir, branch, artifactId: index.artifactId, }; - const [results, lastUpdated, markComplete] = + const [fullResults, fullLastUpdated, markComplete] = await getComputeDeleteAddRemove( tag, { ...stats }, (filepath) => this.ide.readFile(filepath), repoName, ); - // since this is only a single file update / save we do not want to actualy remove anything, we just want to recompute for our single file - results.removeTag = []; - results.addTag = []; - results.del = []; + const [results, lastUpdated] = this.singleFileIndexOps( + fullResults, + fullLastUpdated, + filePath, + ); // Don't update if nothing to update. Some of the indices might do unnecessary setup work - if (results.compute.length === 0) { + if (this.totalIndexOps(results) + lastUpdated.length === 0) { continue; } @@ -415,11 +460,7 @@ export class CodebaseIndexer { (filepath) => this.ide.readFile(filepath), repoName, ); - const totalOps = - results.compute.length + - results.del.length + - results.addTag.length + - results.removeTag.length; + const totalOps = this.totalIndexOps(results); let completedOps = 0; // Don't update if nothing to update. Some of the indices might do unnecessary setup work diff --git a/core/indexing/FullTextSearchCodebaseIndex.ts b/core/indexing/FullTextSearchCodebaseIndex.ts index 7ff54781c..de183e158 100644 --- a/core/indexing/FullTextSearchCodebaseIndex.ts +++ b/core/indexing/FullTextSearchCodebaseIndex.ts @@ -97,13 +97,15 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex { // Delete for (const item of results.del) { + await db.run(` + DELETE FROM fts WHERE rowid IN ( + SELECT id FROM fts_metadata WHERE path = ? AND cacheKey = ? + ) + `,[item.path, item.cacheKey]); await db.run("DELETE FROM fts_metadata WHERE path = ? AND cacheKey = ?", [ item.path, item.cacheKey, ]); - - await db.run("DELETE FROM fts WHERE path = ?", [item.path]); - await markComplete([item], IndexResultType.Delete); } } diff --git a/core/indexing/LanceDbIndex.test.ts b/core/indexing/LanceDbIndex.test.ts index 08c8f9982..ac6ed3591 100644 --- a/core/indexing/LanceDbIndex.test.ts +++ b/core/indexing/LanceDbIndex.test.ts @@ -3,15 +3,15 @@ import lance from "vectordb"; import { testConfigHandler, testIde } from "../test/fixtures"; import { getLanceDbPath } from "../util/paths"; + +import { LanceDbIndex } from "./LanceDbIndex"; +import { DatabaseConnection, SqliteDb } from "./refreshIndex"; import { mockPathAndCacheKey, mockTag, testContinueServerClient, updateIndexAndAwaitGenerator, } from "./test/indexing"; - -import { LanceDbIndex } from "./LanceDbIndex"; -import { DatabaseConnection, SqliteDb } from "./refreshIndex"; import { IndexResultType } from "./types"; jest.useFakeTimers(); @@ -30,12 +30,15 @@ describe.skip("ChunkCodebaseIndex", () => { if (!mockConfig) { throw new Error("Failed to load config"); } + if (!mockConfig.selectedModelByRole.embed) { + throw new Error("No embeddings model selected"); + } - index = new LanceDbIndex( - mockConfig.embeddingsProvider, + index = (await LanceDbIndex.create( + mockConfig.selectedModelByRole.embed, testIde.readFile.bind(testIde), testContinueServerClient, - ); + ))!; sqliteDb = await SqliteDb.get(); lanceDb = await lance.connect(getLanceDbPath()); diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index d11feb1d1..168a4ff07 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -1,30 +1,30 @@ -// NOTE: vectordb requirement must be listed in extensions/vscode to avoid error import { RunResult } from "sqlite3"; import { v4 as uuidv4 } from "uuid"; -import lance, { Table } from "vectordb"; -import { IContinueServerClient } from "../continueServer/interface.js"; +import { isSupportedLanceDbCpuTargetForLinux } from "../config/util"; +import { IContinueServerClient } from "../continueServer/interface"; import { BranchAndDir, Chunk, ILLM, IndexTag, IndexingProgressUpdate, -} from "../index.js"; -import { getLanceDbPath, migrate } from "../util/paths.js"; +} from "../index"; +import { getLanceDbPath, migrate } from "../util/paths"; +import { getUriPathBasename } from "../util/uri"; -import { chunkDocument, shouldChunk } from "./chunk/chunk.js"; -import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex.js"; +import { chunkDocument, shouldChunk } from "./chunk/chunk"; +import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex"; import { CodebaseIndex, IndexResultType, MarkCompleteCallback, PathAndCacheKey, RefreshIndexResults, -} from "./types.js"; -import { getUriPathBasename } from "../util/uri.js"; +} from "./types"; + +import type * as LanceType from "vectordb"; -// LanceDB converts to lowercase, so names must all be lowercase interface LanceDbRow { uuid: string; path: string; @@ -38,16 +38,53 @@ type ItemWithChunks = { item: PathAndCacheKey; chunks: Chunk[] }; type ChunkMap = Map; export class LanceDbIndex implements CodebaseIndex { + private static lance: typeof LanceType | null = null; + relativeExpectedTime: number = 13; get artifactId(): string { - return `vectordb::${this.embeddingsProvider.embeddingId}`; + return `vectordb::${this.embeddingsProvider?.embeddingId}`; } - constructor( + /** + * Factory method for creating LanceDbIndex instances. + * + * We dynamically import LanceDB only when supported to avoid native module loading errors + * on incompatible platforms. LanceDB has CPU-specific native dependencies that can crash + * the application if loaded on unsupported architectures. + * + * See isSupportedLanceDbCpuTargetForLinux() for platform compatibility details. + */ + static async create( + embeddingsProvider: ILLM, + readFile: (filepath: string) => Promise, + continueServerClient?: IContinueServerClient, + ): Promise { + if (!isSupportedLanceDbCpuTargetForLinux()) { + return null; + } + + try { + this.lance = await import("vectordb"); + return new LanceDbIndex( + embeddingsProvider, + readFile, + continueServerClient, + ); + } catch (err) { + console.error("Failed to load LanceDB:", err); + return null; + } + } + + private constructor( private readonly embeddingsProvider: ILLM, private readonly readFile: (filepath: string) => Promise, private readonly continueServerClient?: IContinueServerClient, - ) {} + ) { + if (!LanceDbIndex.lance) { + throw new Error("LanceDB not initialized"); + } + } tableNameForTag(tag: IndexTag) { return tagToString(tag).replace(/[^\w-_.]/g, ""); @@ -97,12 +134,10 @@ export class LanceDbIndex implements CodebaseIndex { ); const embeddings = await this.getEmbeddings(allChunks); - // Remove undefined embeddings and their corresponding chunks for (let i = embeddings.length - 1; i >= 0; i--) { if (embeddings[i] === undefined) { const chunk = allChunks[i]; const chunks = chunkMap.get(chunk.filepath)?.chunks; - if (chunks) { const index = chunks.findIndex((c) => c === chunk); if (index !== -1) { @@ -142,6 +177,9 @@ export class LanceDbIndex implements CodebaseIndex { item: PathAndCacheKey, content: string, ): Promise { + if (!this.embeddingsProvider) { + return []; + } const chunks: Chunk[] = []; const chunkParams = { @@ -163,6 +201,9 @@ export class LanceDbIndex implements CodebaseIndex { } private async getEmbeddings(chunks: Chunk[]): Promise { + if (!this.embeddingsProvider) { + return []; + } try { return await this.embeddingsProvider.embed(chunks.map((c) => c.content)); } catch (err) { @@ -204,6 +245,7 @@ export class LanceDbIndex implements CodebaseIndex { markComplete: MarkCompleteCallback, repoName: string | undefined, ): AsyncGenerator { + const lance = LanceDbIndex.lance!; const sqliteDb = await SqliteDb.get(); await this.createSqliteCacheTable(sqliteDb); @@ -211,15 +253,13 @@ export class LanceDbIndex implements CodebaseIndex { const lanceDb = await lance.connect(getLanceDbPath()); const existingLanceTables = await lanceDb.tableNames(); - let lanceTable: Table | undefined = undefined; + let lanceTable: LanceType.Table | undefined = undefined; let needToCreateLanceTable = !existingLanceTables.includes(lanceTableName); - // Compute const addComputedLanceDbRows = async ( pathAndCacheKeys: PathAndCacheKey[], computedRows: LanceDbRow[], ) => { - // Create table if needed, add computed rows if (lanceTable) { if (computedRows.length > 0) { await lanceTable.add(computedRows); @@ -235,11 +275,9 @@ export class LanceDbIndex implements CodebaseIndex { needToCreateLanceTable = false; } - // Mark item complete await markComplete(pathAndCacheKeys, IndexResultType.Compute); }; - // Check remote cache if (this.continueServerClient?.connected) { try { const keys = results.compute.map(({ cacheKey }) => cacheKey); @@ -249,7 +287,6 @@ export class LanceDbIndex implements CodebaseIndex { repoName, ); for (const [cacheKey, chunks] of Object.entries(resp.files)) { - // Get path for cacheKey const path = results.compute.find( (item) => item.cacheKey === cacheKey, )?.path; @@ -261,7 +298,6 @@ export class LanceDbIndex implements CodebaseIndex { continue; } - // Build LanceDbRow objects const rows: LanceDbRow[] = []; for (const chunk of chunks) { const row = { @@ -288,7 +324,6 @@ export class LanceDbIndex implements CodebaseIndex { await addComputedLanceDbRows([{ cacheKey, path }], rows); } - // Remove items that don't need to be recomputed results.compute = results.compute.filter( (item) => !resp.files[item.cacheKey], ); @@ -310,12 +345,10 @@ export class LanceDbIndex implements CodebaseIndex { await addComputedLanceDbRows(results.compute, dbRows); let accumulatedProgress = 0; - // Add tag - retrieve the computed info from lance sqlite cache for (const { path, cacheKey } of results.addTag) { const stmt = await sqliteDb.prepare( - "SELECT * FROM lance_db_cache WHERE cacheKey = ? AND path = ? AND artifact_id = ?", + "SELECT * FROM lance_db_cache WHERE cacheKey = ? AND artifact_id = ?", cacheKey, - path, this.artifactId, ); const cachedItems = await stmt.all(); @@ -354,7 +387,6 @@ export class LanceDbIndex implements CodebaseIndex { }; } - // Delete or remove tag - remove from lance table) if (!needToCreateLanceTable) { const toDel = [...results.removeTag, ...results.del]; @@ -363,7 +395,6 @@ export class LanceDbIndex implements CodebaseIndex { } for (const { path, cacheKey } of toDel) { - // This is where the aforementioned lowercase conversion problem shows await lanceTable.delete( `cachekey = '${cacheKey}' AND path = '${path}'`, ); @@ -379,7 +410,6 @@ export class LanceDbIndex implements CodebaseIndex { await markComplete(results.removeTag, IndexResultType.RemoveTag); - // Delete - also remove from sqlite cache for (const { path, cacheKey } of results.del) { await sqliteDb.run( "DELETE FROM lance_db_cache WHERE cacheKey = ? AND path = ? AND artifact_id = ?", @@ -409,7 +439,7 @@ export class LanceDbIndex implements CodebaseIndex { n: number, directory: string | undefined, vector: number[], - db: any, /// lancedb.Connection + db: any, ): Promise { const tableName = this.tableNameForTag(tag); const tableNames = await db.tableNames(); @@ -421,7 +451,6 @@ export class LanceDbIndex implements CodebaseIndex { const table = await db.openTable(tableName); let query = table.search(vector); if (directory) { - // seems like lancedb is only post-filtering, so have to return a bunch of results and slice after query = query.where(`path LIKE '${directory}%'`).limit(300); } else { query = query.limit(n); @@ -436,6 +465,10 @@ export class LanceDbIndex implements CodebaseIndex { tags: BranchAndDir[], filterDirectory: string | undefined, ): Promise { + const lance = LanceDbIndex.lance!; + if (!this.embeddingsProvider) { + return []; + } const [vector] = await this.embeddingsProvider.embed([query]); const db = await lance.connect(getLanceDbPath()); diff --git a/core/indexing/allEmbeddingsProviders.ts b/core/indexing/allEmbeddingsProviders.ts index 9efa37f2d..3986fa2c0 100644 --- a/core/indexing/allEmbeddingsProviders.ts +++ b/core/indexing/allEmbeddingsProviders.ts @@ -8,6 +8,7 @@ import Gemini from "../llm/llms/Gemini.js"; import HuggingFaceTEIEmbeddingsProvider from "../llm/llms/HuggingFaceTEI.js"; import LMStudio from "../llm/llms/LMStudio.js"; import Mistral from "../llm/llms/Mistral.js"; +import NCompass from "../llm/llms/NCompass.js"; import Nebius from "../llm/llms/Nebius.js"; import Nvidia from "../llm/llms/Nvidia.js"; import Ollama from "../llm/llms/Ollama.js"; @@ -39,6 +40,7 @@ export const allEmbeddingsProviders: Record< gemini: Gemini, "continue-proxy": ContinueProxy, deepinfra: DeepInfra, + ncompass: NCompass, nvidia: Nvidia, voyage: Voyage, mistral: Mistral, diff --git a/core/indexing/chunk/ChunkCodebaseIndex.ts b/core/indexing/chunk/ChunkCodebaseIndex.ts index 1f6a45258..9b39e506a 100644 --- a/core/indexing/chunk/ChunkCodebaseIndex.ts +++ b/core/indexing/chunk/ChunkCodebaseIndex.ts @@ -80,9 +80,9 @@ export class ChunkCodebaseIndex implements CodebaseIndex { ` INSERT INTO chunk_tags (chunkId, tag) SELECT id, ? FROM chunks - WHERE cacheKey = ? AND path = ? + WHERE cacheKey = ? `, - [tagString, item.cacheKey, item.path], + [tagString, item.cacheKey], ); await markComplete([item], IndexResultType.AddTag); accumulatedProgress += 1 / results.addTag.length / 4; @@ -158,7 +158,8 @@ export class ChunkCodebaseIndex implements CodebaseIndex { id INTEGER PRIMARY KEY AUTOINCREMENT, tag TEXT NOT NULL, chunkId INTEGER NOT NULL, - FOREIGN KEY (chunkId) REFERENCES chunks (id) + FOREIGN KEY (chunkId) REFERENCES chunks (id), + UNIQUE (tag, chunkId) )`); } diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 4d555f557..75f92b145 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -1,6 +1,6 @@ +import { ConfigResult } from "@continuedev/config-yaml"; import { open, type Database } from "sqlite"; import sqlite3 from "sqlite3"; -import lancedb, { Connection } from "vectordb"; import { Chunk, @@ -13,12 +13,16 @@ import { SiteIndexingConfig, } from "../.."; import { ConfigHandler } from "../../config/ConfigHandler"; -import { addContextProvider } from "../../config/util"; +import { + addContextProvider, + isSupportedLanceDbCpuTargetForLinux, +} from "../../config/util"; import DocsContextProvider from "../../context/providers/DocsContextProvider"; import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider"; import { FromCoreProtocol, ToCoreProtocol } from "../../protocol"; import { IMessenger } from "../../protocol/messenger"; import { fetchFavicon, getFaviconBase64 } from "../../util/fetchFavicon"; +import { GlobalContext } from "../../util/GlobalContext"; import { editConfigJson, getDocsSqlitePath, @@ -26,8 +30,6 @@ import { } from "../../util/paths"; import { Telemetry } from "../../util/posthog"; -import { ConfigResult } from "@continuedev/config-yaml"; -import { GlobalContext } from "../../util/GlobalContext"; import { ArticleWithChunks, htmlPageToArticleWithChunks, @@ -43,6 +45,8 @@ import { } from "./preIndexed"; import preIndexedDocs from "./preIndexedDocs"; +import type * as LanceType from "vectordb"; + // Purposefully lowercase because lancedb converts export interface LanceDbDocsRow { title: string; @@ -81,6 +85,7 @@ export type AddParams = { - add/index one */ export default class DocsService { + private static lance: typeof LanceType | null = null; static lanceTableName = "docs"; static sqlitebTableName = "docs"; @@ -112,6 +117,22 @@ export default class DocsService { this.githubToken = token; } + private async initLanceDb() { + if (!isSupportedLanceDbCpuTargetForLinux()) { + return null; + } + + try { + if (!DocsService.lance) { + DocsService.lance = await import("vectordb"); + } + return DocsService.lance; + } catch (err) { + console.error("Failed to load LanceDB:", err); + return null; + } + } + // Singleton pattern: only one service globally private static instance?: DocsService; static createSingleton( @@ -161,16 +182,22 @@ export default class DocsService { return; } - const sharedStatus = { - type: "docs" as IndexingStatus["type"], + const sharedStatus: Omit< + IndexingStatus, + "progress" | "description" | "status" + > = { + type: "docs", id: doc.startUrl, - embeddingsProviderId: this.config.embeddingsProvider.embeddingId, isReindexing: false, title: doc.title, debugInfo: `max depth: ${doc.maxDepth}`, icon: doc.faviconUrl, url: doc.startUrl, }; + if (this.config.selectedModelByRole.embed) { + sharedStatus.embeddingsProviderId = + this.config.selectedModelByRole.embed.embeddingId; + } const indexedStatus: IndexingStatus = metadata.find( (meta) => meta.startUrl === doc.startUrl, ) @@ -214,7 +241,9 @@ export default class DocsService { } // Handle embeddings provider change mid-indexing - if (this.config.embeddingsProvider.embeddingId !== startedWithEmbedder) { + if ( + this.config.selectedModelByRole.embed?.embeddingId !== startedWithEmbedder + ) { this.abort(startUrl); return true; } @@ -234,14 +263,6 @@ export default class DocsService { return true; } - async isUsingUnsupportedPreIndexedEmbeddingsProvider() { - const isPreIndexedDocsProvider = - this.config.embeddingsProvider.embeddingId === - DocsService.preIndexedDocsEmbeddingsProvider.embeddingId; - const canUsePreindexedDocs = await this.canUsePreindexedDocs(); - return isPreIndexedDocsProvider && !canUsePreindexedDocs; - } - // Determines if using preIndexed and returns proper embeddings provider async getEmbeddingsProvider(startUrl: string) { // Conditions for using a pre-indexed doc @@ -262,7 +283,7 @@ export default class DocsService { } } return { - provider: this.config.embeddingsProvider, + provider: this.config.selectedModelByRole.embed, isPreindexed: false, }; } @@ -282,9 +303,7 @@ export default class DocsService { // Skip docs indexing if not supported // No warning message here because would show on ANY config update - const unsupported = - await this.isUsingUnsupportedPreIndexedEmbeddingsProvider(); - if (unsupported) { + if (!this.config.selectedModelByRole.embed) { return; } @@ -323,18 +342,21 @@ export default class DocsService { // Returns true if startUrl has been indexed with current embeddingsProvider async hasMetadata(startUrl: string): Promise { + if (!this.config.selectedModelByRole.embed) { + return false; + } const db = await this.getOrCreateSqliteDb(); const title = await db.get( `SELECT title FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`, startUrl, - this.config.embeddingsProvider.embeddingId, + this.config.selectedModelByRole.embed.embeddingId, ); return !!title; } async listMetadata() { - const embeddingsProvider = this.config.embeddingsProvider; + const embeddingsProvider = this.config.selectedModelByRole.embed; if (!embeddingsProvider) { return []; } @@ -376,6 +398,11 @@ export default class DocsService { console.warn("Attempted to indexAndAdd pre-indexed doc"); return; } + if (!provider) { + console.warn("@docs indexAndAdd: no embeddings provider found"); + return; + } + const startedWithEmbedder = provider.embeddingId; // Check if doc has been successfully indexed with the given embedder @@ -716,21 +743,18 @@ export default class DocsService { startUrl: string, nRetrieve: number, ) { - if (await this.isUsingUnsupportedPreIndexedEmbeddingsProvider()) { - await this.ide.showToast( - "error", - `${DocsService.preIndexedDocsEmbeddingsProvider.embeddingId} is configured as ` + - "the embeddings provider, but it cannot be used with JetBrains. " + // TODO "with this IDE" - "Please select a different embeddings provider to use the '@docs' " + - "context provider.", - ); - - return []; - } - const { isPreindexed, provider } = await this.getEmbeddingsProvider(startUrl); + if (!provider) { + void this.ide.showToast( + "error", + "Set up an embeddings model to use the @docs context provider. See: " + + "https://docs.continue.dev/customize/model-roles/embeddings", + ); + return []; + } + if (isPreindexed) { void Telemetry.capture("docs_pre_indexed_doc_used", { doc: preIndexedDocs[startUrl]!["title"], @@ -761,8 +785,10 @@ export default class DocsService { try { const { isPreindexed, provider } = await this.getEmbeddingsProvider(startUrl); - const preIndexedDoc = preIndexedDocs[startUrl]; - const isPreIndexedDoc = !!preIndexedDoc; + + if (!provider) { + throw new Error("No embeddings model set"); + } const result = await db.get( `SELECT startUrl, title, favicon FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`, @@ -793,7 +819,7 @@ export default class DocsService { config: siteIndexingConfig, indexingStatus: this.statuses.get(startUrl), chunks: rows.map(this.lanceDBRowToChunk), - isPreIndexedDoc, + isPreIndexedDoc: isPreindexed, }; } catch (e) { console.warn("Error getting details", e); @@ -867,7 +893,7 @@ export default class DocsService { } async getFavicon(startUrl: string) { - if (!this.config.embeddingsProvider) { + if (!this.config.selectedModelByRole.embed) { console.warn( "Attempting to get favicon without embeddings provider specified", ); @@ -877,7 +903,7 @@ export default class DocsService { const result = await db.get( `SELECT favicon FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`, startUrl, - this.config.embeddingsProvider.embeddingId, + this.config.selectedModelByRole.embed.embeddingId, ); if (!result) { @@ -941,7 +967,7 @@ export default class DocsService { type: "docs", id: doc.startUrl, embeddingsProviderId: - this.config.embeddingsProvider.embeddingId, + this.config.selectedModelByRole.embed?.embeddingId, isReindexing: false, title: doc.title, debugInfo: "Config sync: not changed", @@ -983,7 +1009,7 @@ export default class DocsService { // Lance DB Initialization private async createLanceDocsTable( - connection: Connection, + connection: LanceType.Connection, initializationVector: number[], tableName: string, ) { @@ -1030,9 +1056,21 @@ export default class DocsService { initializationVector: number[]; startUrl: string; }) { - const conn = await lancedb.connect(getLanceDbPath()); + const lance = await this.initLanceDb(); + if (!lance) { + throw new Error("LanceDB not available on this platform"); + } + + const conn = await lance.connect(getLanceDbPath()); const tableNames = await conn.tableNames(); const { provider } = await this.getEmbeddingsProvider(startUrl); + + if (!provider) { + throw new Error( + "Could not retrieve @docs Lance Table: no embeddings provider specified", + ); + } + const tableNameFromEmbeddingsProvider = await this.getLanceTableName(provider); @@ -1089,13 +1127,19 @@ export default class DocsService { siteIndexingConfig: { title, startUrl }, favicon, }: AddParams) { + if (!this.config.selectedModelByRole.embed) { + console.warn( + `Attempting to add metadata for ${startUrl} without embeddings provider specified`, + ); + return; + } const db = await this.getOrCreateSqliteDb(); await db.run( `INSERT INTO ${DocsService.sqlitebTableName} (title, startUrl, favicon, embeddingsProviderId) VALUES (?, ?, ?, ?)`, title, startUrl, favicon, - this.config.embeddingsProvider.embeddingId, + this.config.selectedModelByRole.embed.embeddingId, ); } @@ -1139,15 +1183,20 @@ export default class DocsService { // Delete methods private async deleteEmbeddingsFromLance(startUrl: string) { + const lance = await this.initLanceDb(); + if (!lance) { + return; + } + for (const tableName of this.lanceTableNamesSet) { - const conn = await lancedb.connect(getLanceDbPath()); + const conn = await lance.connect(getLanceDbPath()); const table = await conn.openTable(tableName); await table.delete(`starturl = '${startUrl}'`); } } private async deleteMetadataFromSqlite(startUrl: string) { - if (!this.config.embeddingsProvider) { + if (!this.config.selectedModelByRole.embed) { console.warn( `Attempting to delete metadata for ${startUrl} without embeddings provider specified`, ); @@ -1158,7 +1207,7 @@ export default class DocsService { await db.run( `DELETE FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`, startUrl, - this.config.embeddingsProvider.embeddingId, + this.config.selectedModelByRole.embed.embeddingId, ); } diff --git a/core/indexing/docs/migrations.ts b/core/indexing/docs/migrations.ts index 38aa987b3..64e313175 100644 --- a/core/indexing/docs/migrations.ts +++ b/core/indexing/docs/migrations.ts @@ -1,5 +1,5 @@ import { type Database } from "sqlite"; -import { Table } from "vectordb"; +import { type Table } from "vectordb"; import { editConfigJson, migrate } from "../../util/paths.js"; diff --git a/core/indexing/ignore.ts b/core/indexing/ignore.ts index 6075bdb26..7f5e8a039 100644 --- a/core/indexing/ignore.ts +++ b/core/indexing/ignore.ts @@ -114,6 +114,10 @@ export const defaultIgnoreDir = ignore().add(DEFAULT_IGNORE_DIRS); export const DEFAULT_IGNORE = DEFAULT_IGNORE_FILETYPES.join("\n") + "\n" + DEFAULT_IGNORE_DIRS.join("\n"); +export const defaultIgnoreFileAndDir = ignore() + .add(defaultIgnoreFile) + .add(defaultIgnoreDir); + export function gitIgArrayFromFile(file: string) { return file .split(/\r?\n/) // Split on new line diff --git a/core/indexing/refreshIndex.ts b/core/indexing/refreshIndex.ts index 34c1ac4a2..ef21149b1 100644 --- a/core/indexing/refreshIndex.ts +++ b/core/indexing/refreshIndex.ts @@ -157,32 +157,64 @@ async function getAddRemoveForTag( const remove: PathAndCacheKey[] = []; const updateLastUpdated: PathAndCacheKey[] = []; - for (const item of saved) { - const { lastUpdated, ...pathAndCacheKey } = item; + // First, group items by path and find latest timestamp for each + const pathGroups = new Map + }>(); - if (files[item.path] === undefined) { - // Was indexed, but no longer exists. Remove - remove.push(pathAndCacheKey); + for (const item of saved) { + const { lastUpdated, path, cacheKey } = item; + + if (!pathGroups.has(path)) { + pathGroups.set(path, { + latest: { lastUpdated, cacheKey }, + allVersions: [{ cacheKey }] + }); + } else { + const group = pathGroups.get(path)!; + group.allVersions.push({ cacheKey }); + if (lastUpdated > group.latest.lastUpdated) { + group.latest = { lastUpdated, cacheKey }; + } + } + } + + // Now process each unique path + for (const [path, group] of pathGroups) { + if (files[path] === undefined) { + // Was indexed, but no longer exists. Remove all versions + for (const version of group.allVersions) { + remove.push({ path, cacheKey: version.cacheKey }); + } } else { // Exists in old and new, so determine whether it was updated - if (lastUpdated < files[item.path].lastModified) { + if (group.latest.lastUpdated < files[path].lastModified) { // Change was made after last update - const newHash = calculateHash(await readFile(pathAndCacheKey.path)); - if (pathAndCacheKey.cacheKey !== newHash) { + const newHash = calculateHash(await readFile(path)); + if (group.latest.cacheKey !== newHash) { updateNewVersion.push({ - path: pathAndCacheKey.path, + path, cacheKey: newHash, }); - updateOldVersion.push(pathAndCacheKey); + for (const version of group.allVersions) { + updateOldVersion.push({ path, cacheKey: version.cacheKey }); + } } else { - updateLastUpdated.push(pathAndCacheKey); + // File contents did not change + updateLastUpdated.push({ path, cacheKey: group.latest.cacheKey }); + for (const version of group.allVersions) { + if (version.cacheKey !== group.latest.cacheKey) { + updateOldVersion.push({ path, cacheKey: version.cacheKey }); + } + } } } else { // Already updated, do nothing } - // Remove so we can check leftovers afterward - delete files[item.path]; + // Remove path, so that only newly created paths remain + delete files[path]; } } diff --git a/core/indexing/shouldIgnore.test.ts b/core/indexing/shouldIgnore.test.ts new file mode 100644 index 000000000..c1935e7d9 --- /dev/null +++ b/core/indexing/shouldIgnore.test.ts @@ -0,0 +1,167 @@ +// Generated by continue + +import { testIde } from "../test/fixtures"; +import { + TEST_DIR, + addToTestDir, + setUpTestDir, + tearDownTestDir, +} from "../test/testDir"; + +import { shouldIgnore } from "./shouldIgnore"; + +// Test for the shouldIgnore function +describe("shouldIgnore", () => { + beforeEach(() => { + setUpTestDir(); + }); + + afterEach(() => { + tearDownTestDir(); + }); + + test("should return true if a file is ignored by .gitignore", async () => { + addToTestDir([ + ["ignored-file.txt", "content"], + [".gitignore", "ignored-file.txt"], + ]); + const result = await shouldIgnore(TEST_DIR + "/ignored-file.txt", testIde, [ + TEST_DIR, + ]); + expect(result).toBe(true); + }); + test("should return true if a folder is ignored by .continueignore", async () => { + addToTestDir([ + ["ignored-folder/file.txt", "content"], + [".continueignore", "ignored-folder/"], + ]); + const result = await shouldIgnore( + TEST_DIR + "/ignored-folder/file.txt", + testIde, + [TEST_DIR], + ); + expect(result).toBe(true); + }); + test("should return false if a file is not ignored", async () => { + addToTestDir([["kept-file.txt", "contents"]]); + const result = await shouldIgnore(TEST_DIR + "/kept-file.txt", testIde, [ + TEST_DIR, + ]); + expect(result).toBe(false); + }); + test("should return true if a file is ignored by .gitignore with spaces in file name", async () => { + addToTestDir([ + ["ignored file.txt", "content"], + [".gitignore", "ignored file.txt"], + ]); + const result = await shouldIgnore(TEST_DIR + "/ignored file.txt", testIde, [ + TEST_DIR, + ]); + expect(result).toBe(true); + }); + + test("should return true if a .continueignore override ignores file", async () => { + addToTestDir([ + ["override-file.txt", "content"], + [".gitignore", "override-file.txt"], + [".continueignore", "!override-file.txt"], + ]); + const result = await shouldIgnore( + TEST_DIR + "/override-file.txt", + testIde, + [TEST_DIR], + ); + expect(result).toBe(false); + }); + + test("should return true for deeply nested file ignored by ignore files at multiple levels", async () => { + addToTestDir([ + ["level1/level2/level3/ignored-file.txt", "content"], + ["level1/.gitignore", "level2/"], + ["level1/level2/.continueignore", "level3/"], + ]); + const result = await shouldIgnore( + TEST_DIR + "/level1/level2/level3/ignored-file.txt", + testIde, + [TEST_DIR], + ); + expect(result).toBe(true); + }); + + test("should return false if a file with spaces is not ignored", async () => { + addToTestDir([["kept file.txt", "contents"]]); + const result = await shouldIgnore(TEST_DIR + "/kept file.txt", testIde, [ + TEST_DIR, + ]); + expect(result).toBe(false); + }); + + test("should handle multiple levels of directories with some files ignored", async () => { + addToTestDir([ + ["nested/dir1/.gitignore", "ignored.txt"], + ["nested/dir1/ignored.txt", "content"], + ["nested/dir2/kept.txt", "content"], + ]); + const ignoredResult = await shouldIgnore( + TEST_DIR + "/nested/dir1/ignored.txt", + testIde, + [TEST_DIR], + ); + expect(ignoredResult).toBe(true); + + const keptResult = await shouldIgnore( + TEST_DIR + "/nested/dir2/kept.txt", + testIde, + [TEST_DIR], + ); + expect(keptResult).toBe(false); + }); + + test("should respect default file and folder ignores top level", async () => { + addToTestDir([ + [".env", "contents"], + ["go.sum", "contents"], + ".idea/", + [".idea/test.xml", "contents"], + ]); + let result = await shouldIgnore(TEST_DIR + "/.env", testIde, [TEST_DIR]); + expect(result).toBe(true); + + result = await shouldIgnore(TEST_DIR + "/go.sum", testIde, [TEST_DIR]); + expect(result).toBe(true); + + result = await shouldIgnore(TEST_DIR + "/.idea", testIde, [TEST_DIR]); + expect(result).toBe(true); + + result = await shouldIgnore(TEST_DIR + "/.idea/test.xml", testIde, [ + TEST_DIR, + ]); + expect(result).toBe(true); + }); + + test("should respect default file and folder ignores at nested level", async () => { + addToTestDir([ + "nested/.idea/test.xml", + ["nested/.env", "contents"], + ["nested/go.sum", "contents"], + ]); + + let result = await shouldIgnore(TEST_DIR + "/nested/.idea", testIde, [ + TEST_DIR, + ]); + expect(result).toBe(true); + + result = await shouldIgnore(TEST_DIR + "/nested/.idea/test.xml", testIde, [ + TEST_DIR, + ]); + expect(result).toBe(true); + + result = await shouldIgnore(TEST_DIR + "/nested/.env", testIde, [TEST_DIR]); + expect(result).toBe(true); + + result = await shouldIgnore(TEST_DIR + "/nested/go.sum", testIde, [ + TEST_DIR, + ]); + expect(result).toBe(true); + }); +}); diff --git a/core/indexing/shouldIgnore.ts b/core/indexing/shouldIgnore.ts new file mode 100644 index 000000000..dd82a0457 --- /dev/null +++ b/core/indexing/shouldIgnore.ts @@ -0,0 +1,73 @@ +import ignore from "ignore"; +import type { FileType, IDE } from "../"; +import { findUriInDirs, getUriPathBasename } from "../util/uri"; +import { defaultIgnoreFileAndDir, getGlobalContinueIgArray } from "./ignore"; +import { getIgnoreContext } from "./walkDir"; + +/* + Process: + 1. Check global/default ignores + 2. Walk UP tree from file, checking ignores at each level + + TODO there might be issues with symlinks here +*/ +export async function shouldIgnore( + fileUri: string, + ide: IDE, + rootDirCandidates?: string[], +): Promise { + const rootDirUris = rootDirCandidates ?? (await ide.getWorkspaceDirs()); + const { foundInDir: rootDir, uri } = findUriInDirs(fileUri, rootDirUris); + + if (!rootDir) { + return true; + } + + const defaultAndGlobalIgnores = ignore() + .add(defaultIgnoreFileAndDir) + .add(getGlobalContinueIgArray()); + + let currentDir = uri; + let directParent = true; + let fileType = 1 as FileType.File as FileType; + while (currentDir !== rootDir) { + // Go to parent dir of file + const splitUri = currentDir.split("/"); + splitUri.pop(); + currentDir = splitUri.join("/"); + + // Get all files in the dir + const dirEntries = await ide.listDir(currentDir); + + // Check if the file is a symbolic link, ignore if so + if (directParent) { + directParent = false; + const baseName = getUriPathBasename(fileUri); + const entry = dirEntries.find(([name, _]) => name === baseName); + if (entry) { + fileType = entry[1]; + if (fileType === (64 as FileType.SymbolicLink)) { + return true; + } + } + } + + const ignoreContext = await getIgnoreContext( + currentDir, + dirEntries, + ide, + defaultAndGlobalIgnores, + ); + + let relativePath = uri.substring(currentDir.length + 1); + if (fileType === (2 as FileType.Directory)) { + relativePath += "/"; + } + + if (ignoreContext.ignores(relativePath)) { + return true; + } + } + + return false; +} diff --git a/core/indexing/walkDir.test.ts b/core/indexing/walkDir.test.ts index 8a9d26e7e..8ded86670 100644 --- a/core/indexing/walkDir.test.ts +++ b/core/indexing/walkDir.test.ts @@ -1,14 +1,14 @@ // Generated by continue -import { testIde } from "../test/fixtures"; -import { - setUpTestDir, - tearDownTestDir, - addToTestDir, - TEST_DIR_PATH, -} from "../test/testDir"; -import { walkDir, walkDirAsync, walkDirs } from "../indexing/walkDir"; import fs from "fs"; import path from "path"; +import { walkDir, walkDirAsync, walkDirs } from "../indexing/walkDir"; +import { testIde } from "../test/fixtures"; +import { + addToTestDir, + setUpTestDir, + tearDownTestDir, + TEST_DIR_PATH, +} from "../test/testDir"; describe("walkDir functions", () => { beforeEach(async () => { @@ -19,6 +19,27 @@ describe("walkDir functions", () => { tearDownTestDir(); }); + // describe.only("test speed", () => { + // it("should walk a simple directory structure", async () => { + // addToTestDir([ + // "src/", + // ["src/file1.ts", "content1"], + // ["src/file2.ts", "content2"], + // "src/nested/", + // ["src/nested/file3.ts", "content3"], + // ]); + + // const dir = await testIde.getWorkspaceDirs(); + + // const start = Date.now(); + // for (let i = 0; i < 10000; i++) { + // await walkDir(dir[0], testIde); + // } + // const passed = Date.now() - start; + // console.log(`Test took ${passed} ms`); + // }); + // }); + describe("walkDir", () => { it("should walk a simple directory structure", async () => { addToTestDir([ @@ -313,6 +334,9 @@ describe("walkDir functions", () => { ["node_modules/package/index.js", "content"], ["dist/bundle.js", "content"], ["coverage/lcov.env", "content"], + ["nested/node_modules/package/index.js", "content"], + ["nested/dist/bundle.js", "content"], + ["nested/coverage/lcov.env", "content"], ]); const files = await walkDir( @@ -327,6 +351,9 @@ describe("walkDir functions", () => { expect(files).not.toContain(".git/config"); expect(files).not.toContain("node_modules/package/index.js"); expect(files).not.toContain("coverage/lcov.info"); + expect(files).not.toContain("nested/node_modules/package/index.js"); + expect(files).not.toContain("nested/dist/bundle.js"); + expect(files).not.toContain("nested/coverage/lcov.env"); }); it("should handle directory-specific ignore patterns correctly", async () => { diff --git a/core/indexing/walkDir.ts b/core/indexing/walkDir.ts index 4e97e01d4..757163d96 100644 --- a/core/indexing/walkDir.ts +++ b/core/indexing/walkDir.ts @@ -2,27 +2,23 @@ import ignore, { Ignore } from "ignore"; import type { FileType, IDE } from ".."; +import { joinPathsToUri } from "../util/uri"; import { - DEFAULT_IGNORE_DIRS, - DEFAULT_IGNORE_FILETYPES, - defaultIgnoreDir, - defaultIgnoreFile, + defaultIgnoreFileAndDir, getGlobalContinueIgArray, gitIgArrayFromFile, } from "./ignore"; -import { joinPathsToUri } from "../util/uri"; export interface WalkerOptions { - ignoreFiles?: string[]; onlyDirs?: boolean; returnRelativeUrisPaths?: boolean; - additionalIgnoreRules?: string[]; } type Entry = [string, FileType]; // helper struct used for the DFS walk type WalkableEntry = { + name: string; relativeUriPath: string; uri: string; type: FileType; @@ -41,143 +37,110 @@ type IgnoreContext = { }; class DFSWalker { - private readonly ignoreFileNames: Set; - constructor( private readonly uri: string, private readonly ide: IDE, private readonly options: WalkerOptions, - ) { - this.ignoreFileNames = new Set(options.ignoreFiles); - } + ) {} // walk is a depth-first search implementation public async *walk(): AsyncGenerator { - const root = this.newRootWalkContext(); - const stack = [root]; - for (let cur = stack.pop(); cur; cur = stack.pop()) { - const walkableEntries = await this.listDirForWalking(cur.walkableEntry); - const ignoreContexts = await this.getIgnoreToApplyInDir( - cur, - walkableEntries, - ); - for (const w of walkableEntries) { - if (!this.shouldInclude(w, ignoreContexts)) { - continue; - } - if (this.entryIsDirectory(w.entry)) { - stack.push({ - walkableEntry: w, - ignoreContexts: ignoreContexts, - }); - if (this.options.onlyDirs) { - // when onlyDirs is enabled the walker will only return directory names - if (this.options.returnRelativeUrisPaths) { - yield w.relativeUriPath; - } else { - yield w.uri; - } - } - } else { - // Note that shouldInclude handles skipping files if options.onlyDirs is true - if (this.options.returnRelativeUrisPaths) { - yield w.relativeUriPath; - } else { - yield w.uri; - } - } - } - } - } + const defaultAndGlobalIgnores = ignore() + .add(defaultIgnoreFileAndDir) + .add(getGlobalContinueIgArray()); - private newRootWalkContext(): WalkContext { - const globalIgnoreFile = getGlobalContinueIgArray(); - return { + const rootContext: WalkContext = { walkableEntry: { + name: "", relativeUriPath: "", uri: this.uri, type: 2 as FileType.Directory, entry: ["", 2 as FileType.Directory], }, - ignoreContexts: [ + ignoreContexts: [], + }; + const stack = [rootContext]; + + for (let cur = stack.pop(); cur; cur = stack.pop()) { + // Only directories will be added to the stack + const entries = await this.ide.listDir(cur.walkableEntry.uri); + + const newIgnore = await getIgnoreContext( + cur.walkableEntry.uri, + entries, + this.ide, + defaultAndGlobalIgnores, + ); + + const ignoreContexts = [ + ...cur.ignoreContexts, { - ignore: ignore() - .add(defaultIgnoreDir) - .add(defaultIgnoreFile) - .add(globalIgnoreFile), - dirname: "", + ignore: newIgnore, + dirname: cur.walkableEntry.relativeUriPath, }, - ], - }; - } + ]; - private async listDirForWalking( - walkableEntry: WalkableEntry, - ): Promise { - const entries = await this.ide.listDir(walkableEntry.uri); - return entries.map((e) => ({ - relativeUriPath: `${walkableEntry.relativeUriPath}${walkableEntry.relativeUriPath ? "/" : ""}${e[0]}`, - uri: joinPathsToUri(walkableEntry.uri, e[0]), - type: e[1], - entry: e, - })); - } + for (const entry of entries) { + if (this.entryIsSymlink(entry)) { + // If called from the root, a symlink either links to a real file in this repository, + // and therefore will be walked OR it links to something outside of the repository and + // we do not want to index it + continue; + } + const walkableEntry = { + name: entry[0], + relativeUriPath: `${cur.walkableEntry.relativeUriPath}${cur.walkableEntry.relativeUriPath ? "/" : ""}${entry[0]}`, + uri: joinPathsToUri(cur.walkableEntry.uri, entry[0]), + type: entry[1], + entry: entry, + }; - private async getIgnoreToApplyInDir( - curDir: WalkContext, - entriesInDir: WalkableEntry[], - ): Promise { - const ignoreFilesInDir = await this.loadIgnoreFiles(entriesInDir); - if (ignoreFilesInDir.length === 0) { - return curDir.ignoreContexts; - } - const patterns = ignoreFilesInDir.map((c) => gitIgArrayFromFile(c)).flat(); - const newIgnoreContext = { - ignore: ignore().add(patterns), - dirname: curDir.walkableEntry.relativeUriPath, - }; - return [...curDir.ignoreContexts, newIgnoreContext]; - } + let relPath = walkableEntry.relativeUriPath; + if (this.entryIsDirectory(entry)) { + relPath = `${relPath}/`; + } else { + if (this.options.onlyDirs) { + continue; + } + } + let shouldInclude = true; + for (const ig of ignoreContexts) { + // remove the directory name and path separator from the match path, unless this an ignore file + // in the root directory + const prefixLength = + ig.dirname.length === 0 ? 0 : ig.dirname.length + 1; + // The ignore library expects a path relative to the ignore file location + const matchPath = relPath.substring(prefixLength); + if (ig.ignore.ignores(matchPath)) { + shouldInclude = false; + } + } + if (!shouldInclude) { + continue; + } - private async loadIgnoreFiles(entries: WalkableEntry[]): Promise { - const ignoreEntries = entries.filter((w) => - this.entryIsIgnoreFile(w.entry), - ); - const promises = ignoreEntries.map(async (w) => { - return await this.ide.readFile(w.uri); - }); - return Promise.all(promises); - } - - private shouldInclude( - walkableEntry: WalkableEntry, - ignoreContexts: IgnoreContext[], - ) { - if (this.entryIsSymlink(walkableEntry.entry)) { - // If called from the root, a symlink either links to a real file in this repository, - // and therefore will be walked OR it links to something outside of the repository and - // we do not want to index it - return false; - } - let relPath = walkableEntry.relativeUriPath; - if (this.entryIsDirectory(walkableEntry.entry)) { - relPath = `${relPath}/`; - } else { - if (this.options.onlyDirs) { - return false; + if (this.entryIsDirectory(entry)) { + stack.push({ + walkableEntry, + ignoreContexts, + }); + if (this.options.onlyDirs) { + // when onlyDirs is enabled the walker will only return directory names + if (this.options.returnRelativeUrisPaths) { + yield walkableEntry.relativeUriPath; + } else { + yield walkableEntry.uri; + } + } + } else { + if (this.options.returnRelativeUrisPaths) { + yield walkableEntry.relativeUriPath; + } else { + yield walkableEntry.uri; + } + } } } - for (const ig of ignoreContexts) { - // remove the directory name and path separator from the match path, unless this an ignore file - // in the root directory - const prefixLength = ig.dirname.length === 0 ? 0 : ig.dirname.length + 1; - // The ignore library expects a path relative to the ignore file location - const matchPath = relPath.substring(prefixLength); - if (ig.ignore.ignores(matchPath)) { - return false; - } - } - return true; } private entryIsDirectory(entry: Entry) { @@ -187,21 +150,9 @@ class DFSWalker { private entryIsSymlink(entry: Entry) { return entry[1] === (64 as FileType.SymbolicLink); } - - private entryIsIgnoreFile(e: Entry): boolean { - if ( - e[1] === (2 as FileType.Directory) || - e[1] === (64 as FileType.SymbolicLink) - ) { - return false; - } - return this.ignoreFileNames.has(e[0]); - } } const defaultOptions: WalkerOptions = { - ignoreFiles: [".gitignore", ".continueignore"], - additionalIgnoreRules: [...DEFAULT_IGNORE_DIRS, ...DEFAULT_IGNORE_FILETYPES], onlyDirs: false, returnRelativeUrisPaths: false, }; @@ -238,3 +189,49 @@ export async function walkDirs( ); return results.flat(); } + +export async function getIgnoreContext( + currentDir: string, + currentDirEntries: Entry[], + ide: IDE, + defaultAndGlobalIgnores: Ignore, +) { + const dirFiles = currentDirEntries + .filter(([_, entryType]) => entryType === (1 as FileType.File)) + .map(([name, _]) => name); + + // Find ignore files and get ignore arrays from their contexts + // These are done separately so that .continueignore can override .gitignore + const gitIgnoreFile = dirFiles.find((name) => name === ".gitignore"); + const continueIgnoreFile = dirFiles.find( + (name) => name === ".continueignore", + ); + + const getGitIgnorePatterns = async () => { + if (gitIgnoreFile) { + const contents = await ide.readFile(`${currentDir}/.gitignore`); + return gitIgArrayFromFile(contents); + } + return []; + }; + const getContinueIgnorePatterns = async () => { + if (continueIgnoreFile) { + const contents = await ide.readFile(`${currentDir}/.continueignore`); + return gitIgArrayFromFile(contents); + } + return []; + }; + + const ignoreArrays = await Promise.all([ + getGitIgnorePatterns(), + getContinueIgnorePatterns(), + ]); + + // Note precedence here! + const ignoreContext = ignore() + .add(ignoreArrays[0]) // gitignore + .add(defaultAndGlobalIgnores) // default file/folder ignores followed by global .continueignore - this is combined for speed + .add(ignoreArrays[1]); // local .continueignore + + return ignoreContext; +} diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index 6b9884c21..4fe864bfc 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -71,6 +71,7 @@ const PROVIDER_SUPPORTS_IMAGES: string[] = [ "sagemaker", "continue-proxy", "openrouter", + "sambanova", "vertexai", "azure", "scaleway", @@ -92,6 +93,7 @@ const MODEL_SUPPORTS_IMAGES: string[] = [ "haiku", "pixtral", "llama3.2", + "llama-3.2", ]; function modelSupportsTools(modelDescription: ModelDescription) { diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts index fa6cdd558..0e4533ceb 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -8,66 +8,6 @@ import { normalizeToMessageParts } from "../util/messageContent"; import { modelSupportsTools } from "./autodetect"; -const CUSTOM_SYS_MSG_MODEL_FAMILIES = ["sonnet"]; - -const SYSTEM_MESSAGE = `When generating new code: - -1. Always produce a single code block. -2. Never separate the code into multiple code blocks. -3. Only include the code that is being added. -4. Replace existing code with a "lazy" comment like this: "// ... existing code ..." -5. The "lazy" comment must always be a valid comment in the current context (e.g. "" for HTML, "// ... existing code ..." for JavaScript, "{/* ... existing code */}" for TSX, etc.) -6. You must always provide 1-2 lines of context above and below a "lazy" comment -7. If the user submits a code block that contains a filename in the language specifier, always include the filename in any code block you generate based on that file. The filename should be on the same line as the language specifier in your code block. - -Example 1: -Input: -\`\`\`test.js -import addition from "addition" - -class Calculator { - constructor() { - this.result = 0; - } - - add(number) { - this.result += number; - return this; - } -} -\`\`\` -User request: Add a subtract method - -Output: -\`\`\`javascript test.js -// ... existing code ... -import subtraction from "subtraction" - -class Calculator { - // ... existing code ... - - subtract(number) { - this.result -= number; - return this; - } -} -\`\`\` - -Example 2: -Input: -\`\`\`javascript test.js (6-9) -function helloWorld() {} -\`\`\` - -Output: -\`\`\`javascript test.js -function helloWorld() { - // New code here -} -\`\`\` - -Always follow these guidelines when generating code responses.`; - 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.`; @@ -75,21 +15,12 @@ function constructSystemPrompt( modelDescription: ModelDescription, useTools: boolean, ): string | null { - let systemMessage = ""; - if ( - CUSTOM_SYS_MSG_MODEL_FAMILIES.some((family) => - modelDescription.model.includes(family), - ) - ) { - systemMessage = SYSTEM_MESSAGE; - } + let systemMessage = + "Always include the language and file name in the info string when you write code blocks, for example '```python file.py'."; if (useTools && modelSupportsTools(modelDescription)) { - if (systemMessage) { - systemMessage += "\n\n"; - } - systemMessage += TOOL_USE_RULES; + systemMessage += "\n\n" + TOOL_USE_RULES; } - return systemMessage || null; + return systemMessage; } const CANCELED_TOOL_CALL_MESSAGE = diff --git a/core/llm/index.ts b/core/llm/index.ts index 7e3c37fc2..ccbad6699 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -1,3 +1,4 @@ +import { ModelRole } from "@continuedev/config-yaml"; import { fetchwithRequestOptions } from "@continuedev/fetch"; import { findLlmInfo } from "@continuedev/llm-info"; import { @@ -7,6 +8,8 @@ import { } from "@continuedev/openai-adapters"; import Handlebars from "handlebars"; +import { DevDataSqliteDb } from "../data/devdataSqlite.js"; +import { DataLogger } from "../data/log.js"; import { CacheBehavior, ChatMessage, @@ -21,8 +24,6 @@ import { RequestOptions, TemplateType, } from "../index.js"; -import { logDevData } from "../util/devdata.js"; -import { DevDataSqliteDb } from "../util/devdataSqlite.js"; import mergeJson from "../util/merge.js"; import { renderChatMessage } from "../util/messageContent.js"; import { isOllamaInstalled } from "../util/ollamaHelper.js"; @@ -56,7 +57,6 @@ import { toCompleteBody, toFimBody, } from "./openaiTypeConverters.js"; -import { ModelRole } from "@continuedev/config-yaml"; export abstract class BaseLLM implements ILLM { static providerName: string; @@ -118,8 +118,14 @@ export abstract class BaseLLM implements ILLM { writeLog?: (str: string) => Promise; llmRequestHook?: (model: string, prompt: string) => any; apiKey?: string; + + // continueProperties apiKeyLocation?: string; apiBase?: string; + orgScopeId?: string | null; + + onPremProxyUrl?: string | null; + cacheBehavior?: CacheBehavior; capabilities?: ModelCapability; roles?: ModelRole[]; @@ -198,9 +204,15 @@ export abstract class BaseLLM implements ILLM { this.writeLog = options.writeLog; this.llmRequestHook = options.llmRequestHook; this.apiKey = options.apiKey; + + // continueProperties this.apiKeyLocation = options.apiKeyLocation; - this.aiGatewaySlug = options.aiGatewaySlug; + this.orgScopeId = options.orgScopeId; this.apiBase = options.apiBase; + + this.onPremProxyUrl = options.onPremProxyUrl; + + this.aiGatewaySlug = options.aiGatewaySlug; this.cacheBehavior = options.cacheBehavior; // watsonx deploymentId @@ -288,7 +300,7 @@ export abstract class BaseLLM implements ILLM { return this.templateMessages(msgs); } - private _compileLogMessage( + private _compilePromptForLog( prompt: string, completionOptions: CompletionOptions, ): string { @@ -343,11 +355,14 @@ export abstract class BaseLLM implements ILLM { generatedTokens, ); - logDevData("tokens_generated", { - model: model, - provider: this.providerName, - promptTokens: promptTokens, - generatedTokens: generatedTokens, + void DataLogger.getInstance().logDevData({ + name: "tokensGenerated", + data: { + model: model, + provider: this.providerName, + promptTokens: promptTokens, + generatedTokens: generatedTokens, + }, }); } @@ -447,7 +462,7 @@ export abstract class BaseLLM implements ILLM { options, ); - return { completionOptions, log, raw }; + return { completionOptions, logEnabled: log, raw }; } private _formatChatMessages(messages: ChatMessage[]): string { @@ -500,12 +515,15 @@ export abstract class BaseLLM implements ILLM { signal: AbortSignal, options: LLMFullCompletionOptions = {}, ): AsyncGenerator { - const { completionOptions, log } = this._parseCompletionOptions(options); + const { completionOptions, logEnabled } = + this._parseCompletionOptions(options); const fimLog = `Prefix: ${prefix}\nSuffix: ${suffix}`; - if (log) { + if (logEnabled) { if (this.writeLog) { - await this.writeLog(this._compileLogMessage(fimLog, completionOptions)); + await this.writeLog( + this._compilePromptForLog(fimLog, completionOptions), + ); } if (this.llmRequestHook) { this.llmRequestHook(completionOptions.model, fimLog); @@ -541,7 +559,7 @@ export abstract class BaseLLM implements ILLM { this._logTokensGenerated(completionOptions.model, fimLog, completion); - if (log && this.writeLog) { + if (logEnabled && this.writeLog) { await this.writeLog(`Completion:\n${completion}\n\n`); } @@ -557,7 +575,7 @@ export abstract class BaseLLM implements ILLM { signal: AbortSignal, options: LLMFullCompletionOptions = {}, ) { - const { completionOptions, log, raw } = + const { completionOptions, logEnabled, raw } = this._parseCompletionOptions(options); let prompt = pruneRawPromptFromTop( @@ -571,9 +589,11 @@ export abstract class BaseLLM implements ILLM { prompt = this._templatePromptLikeMessages(prompt); } - if (log) { + if (logEnabled) { if (this.writeLog) { - await this.writeLog(this._compileLogMessage(prompt, completionOptions)); + await this.writeLog( + this._compilePromptForLog(prompt, completionOptions), + ); } if (this.llmRequestHook) { this.llmRequestHook(completionOptions.model, prompt); @@ -618,7 +638,7 @@ export abstract class BaseLLM implements ILLM { } finally { this._logTokensGenerated(completionOptions.model, prompt, completion); - if (log && this.writeLog) { + if (logEnabled && this.writeLog) { await this.writeLog(`Completion:\n${completion}\n\n`); } } @@ -636,7 +656,7 @@ export abstract class BaseLLM implements ILLM { signal: AbortSignal, options: LLMFullCompletionOptions = {}, ) { - const { completionOptions, log, raw } = + const { completionOptions, logEnabled, raw } = this._parseCompletionOptions(options); let prompt = pruneRawPromptFromTop( @@ -650,9 +670,11 @@ export abstract class BaseLLM implements ILLM { prompt = this._templatePromptLikeMessages(prompt); } - if (log) { + if (logEnabled) { if (this.writeLog) { - await this.writeLog(this._compileLogMessage(prompt, completionOptions)); + await this.writeLog( + this._compilePromptForLog(prompt, completionOptions), + ); } if (this.llmRequestHook) { this.llmRequestHook(completionOptions.model, prompt); @@ -675,7 +697,7 @@ export abstract class BaseLLM implements ILLM { this._logTokensGenerated(completionOptions.model, prompt, completion); - if (log && this.writeLog) { + if (logEnabled && this.writeLog) { await this.writeLog(`Completion:\n${completion}\n\n`); } @@ -719,7 +741,8 @@ export abstract class BaseLLM implements ILLM { signal: AbortSignal, options: LLMFullCompletionOptions = {}, ): AsyncGenerator { - let { completionOptions, log } = this._parseCompletionOptions(options); + let { completionOptions, logEnabled } = + this._parseCompletionOptions(options); completionOptions = this._modifyCompletionOptions(completionOptions); @@ -728,9 +751,11 @@ export abstract class BaseLLM implements ILLM { const prompt = this.templateMessages ? this.templateMessages(messages) : this._formatChatMessages(messages); - if (log) { + if (logEnabled) { if (this.writeLog) { - await this.writeLog(this._compileLogMessage(prompt, completionOptions)); + await this.writeLog( + this._compilePromptForLog(prompt, completionOptions), + ); } if (this.llmRequestHook) { this.llmRequestHook(completionOptions.model, prompt); @@ -797,7 +822,7 @@ export abstract class BaseLLM implements ILLM { this._logTokensGenerated(completionOptions.model, prompt, completion); - if (log && this.writeLog) { + if (logEnabled && this.writeLog) { await this.writeLog(`Completion:\n${completion}\n\n`); } diff --git a/core/llm/llm.test.ts b/core/llm/llm.test.ts index 9912b862e..ff897d5a3 100644 --- a/core/llm/llm.test.ts +++ b/core/llm/llm.test.ts @@ -205,10 +205,11 @@ describe("LLM", () => { }); testLLM( new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "o1-preview" }), - { skip: false, timeout: 20000 }, + { skip: false, timeout: 60000 }, ); testLLM(new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "o1" }), { skip: false, + timeout: 60000, }); testLLM( new Gemini({ diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index df527d579..dcd13d38e 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -145,6 +145,12 @@ class Anthropic extends BaseLLM { signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { + if (!this.apiKey || this.apiKey === "") { + throw new Error( + "Request not sent. You have an Anthropic model configured in your config.json, but the API key is not set.", + ); + } + const shouldCacheSystemMessage = !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage; const systemMessage: string = stripImages( diff --git a/core/llm/llms/Bedrock.test.ts b/core/llm/llms/Bedrock.test.ts new file mode 100644 index 000000000..d39246fa5 --- /dev/null +++ b/core/llm/llms/Bedrock.test.ts @@ -0,0 +1,375 @@ +import { BedrockRuntimeClient } from "@aws-sdk/client-bedrock-runtime"; +import { fromIni } from "@aws-sdk/credential-providers"; +import Bedrock from "./Bedrock.js"; +import { ChatMessage, Chunk, CompletionOptions, UserChatMessage } from "../../index.js"; + +// Mock AWS SDK +jest.mock("@aws-sdk/client-bedrock-runtime", () => ({ + BedrockRuntimeClient: jest.fn().mockImplementation(() => ({ + send: jest.fn(), + middlewareStack: { add: jest.fn() }, + })), + ConverseStreamCommand: jest.fn(), + InvokeModelCommand: jest.fn(), +})); + +// Mock credential provider +jest.mock("@aws-sdk/credential-providers", () => ({ + fromIni: jest.fn().mockImplementation(() => async () => ({ + accessKeyId: "test-access-key", + secretAccessKey: "test-secret-key", + sessionToken: "test-session-token", + })), +})); + +// Extend CompletionOptions for testing +interface TestCompletionOptions extends CompletionOptions { + mockError?: string; + mockToolUse?: boolean; +} + +// Create a test class that overrides the protected methods +class TestBedrock extends Bedrock { + // Make _streamChat public for testing + public async *streamChat( + messages: ChatMessage[], + signal: AbortSignal, + options: TestCompletionOptions + ): AsyncGenerator { + if (options.mockError) { + throw new Error(options.mockError); + } + + if (options.mockToolUse) { + yield { + role: "assistant", + content: "", + toolCalls: [{ + id: "tool-1", + type: "function", + function: { + name: "test_tool", + arguments: '{"arg1":"value1"}' + } + }], + }; + return; + } + + yield { role: "assistant", content: "Hello" }; + yield { role: "assistant", content: " world" }; + } + + // Override embed to avoid making real API calls + async embed(chunks: string[]): Promise { + if (chunks[0] === "error") { + throw new Error("Embedding Error"); + } + return [[0.1, 0.2, 0.3]]; + } + + // Override rerank to avoid making real API calls + async rerank(query: string, chunks: Chunk[]): Promise { + if (!query || !chunks.length) { + throw new Error("Query and chunks must not be empty"); + } + + if (query === "error") { + throw new Error("Reranking Error"); + } + + return chunks.map((_, i) => 0.8 - i * 0.3); + } +} + +describe("Bedrock", () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + describe("constructor", () => { + it("should initialize with default options", () => { + const bedrock = new TestBedrock({ + apiKey: "test-key", + model: "anthropic.claude-3-sonnet-20240229-v1:0", + region: "us-east-1", + }); + + expect(bedrock.region).toBe("us-east-1"); + expect(bedrock.profile).toBe("bedrock"); + expect(bedrock.apiBase).toBe("https://bedrock-runtime.us-east-1.amazonaws.com"); + }); + + it("should use custom options when provided", () => { + const bedrock = new TestBedrock({ + apiKey: "test-key", + model: "anthropic.claude-3-sonnet-20240229-v1:0", + region: "us-west-2", + profile: "custom-profile", + apiBase: "https://custom-endpoint.amazonaws.com/", + }); + + expect(bedrock.region).toBe("us-west-2"); + expect(bedrock.profile).toBe("custom-profile"); + expect(bedrock.apiBase).toBe("https://custom-endpoint.amazonaws.com/"); + }); + }); + + describe("streamChat", () => { + let bedrock: TestBedrock; + const mockAbortSignal = new AbortController().signal; + const defaultOptions: TestCompletionOptions = { + model: "anthropic.claude-3-sonnet-20240229-v1:0", + }; + + beforeEach(() => { + bedrock = new TestBedrock({ + apiKey: "test-key", + model: "anthropic.claude-3-sonnet-20240229-v1:0", + region: "us-east-1", + }); + }); + + it("should handle text streaming correctly", async () => { + const messages: ChatMessage[] = [{ + role: "user", + content: "Hi" + } as UserChatMessage]; + + const results = []; + + for await (const message of bedrock.streamChat(messages, mockAbortSignal, defaultOptions)) { + results.push(message); + } + + expect(results).toEqual([ + { role: "assistant", content: "Hello" }, + { role: "assistant", content: " world" }, + ]); + }); + + it("should handle tool use streaming correctly", async () => { + const messages: ChatMessage[] = [{ + role: "user", + content: "Use a tool" + } as UserChatMessage]; + + const results = []; + const options: TestCompletionOptions = { + ...defaultOptions, + mockToolUse: true + }; + + for await (const message of bedrock.streamChat(messages, mockAbortSignal, options)) { + results.push(message); + } + + expect(results).toEqual([ + { + role: "assistant", + content: "", + toolCalls: [{ + id: "tool-1", + type: "function", + function: { + name: "test_tool", + arguments: '{"arg1":"value1"}' + } + }], + }, + ]); + }); + + it("should handle API errors", async () => { + const messages: ChatMessage[] = [{ + role: "user", + content: "Hi" + } as UserChatMessage]; + + const options: TestCompletionOptions = { + ...defaultOptions, + mockError: "API Error" + }; + + await expect(async () => { + for await (const _ of bedrock.streamChat(messages, mockAbortSignal, options)) { + // consume generator + } + }).rejects.toThrow("API Error"); + }); + }); + + describe("embed", () => { + let bedrock: TestBedrock; + + beforeEach(() => { + bedrock = new TestBedrock({ + apiKey: "test-key", + model: "cohere.embed-english-v3", + region: "us-east-1", + }); + }); + + it("should handle embedding requests correctly", async () => { + const result = await bedrock.embed(["test text"]); + expect(result).toEqual([[0.1, 0.2, 0.3]]); + }); + + it("should handle embedding errors", async () => { + await expect(bedrock.embed(["error"])).rejects.toThrow("Embedding Error"); + }); + }); + + describe("rerank", () => { + let bedrock: TestBedrock; + + beforeEach(() => { + bedrock = new TestBedrock({ + apiKey: "test-key", + model: "cohere.rerank-english-v2.0", + region: "us-east-1", + }); + }); + + it("should handle reranking requests correctly", async () => { + const chunks: Chunk[] = [ + { + content: "doc1", + digest: "digest1", + filepath: "file1", + index: 0, + startLine: 1, + endLine: 1 + }, + { + content: "doc2", + digest: "digest2", + filepath: "file2", + index: 1, + startLine: 1, + endLine: 1 + } + ]; + + const result = await bedrock.rerank("query", chunks); + expect(result).toEqual([0.8, 0.5]); + }); + + it("should handle reranking errors", async () => { + const chunk: Chunk = { + content: "doc1", + digest: "digest1", + filepath: "file1", + index: 0, + startLine: 1, + endLine: 1 + }; + + await expect( + bedrock.rerank("error", [chunk]) + ).rejects.toThrow("Reranking Error"); + }); + + it("should throw error for empty input", async () => { + await expect(bedrock.rerank("", [])).rejects.toThrow("Query and chunks must not be empty"); + }); + }); + + describe("message conversion", () => { + let bedrock: TestBedrock; + + beforeEach(() => { + bedrock = new TestBedrock({ + apiKey: "test-key", + model: "anthropic.claude-3-sonnet-20240229-v1:0", + region: "us-east-1", + }); + }); + + it("should convert text messages correctly", () => { + const message: ChatMessage = { + role: "user", + content: "Hello" + } as UserChatMessage; + const converted = bedrock["_convertMessage"](message); + expect(converted).toEqual({ + role: "user", + content: [{ text: "Hello" }], + }); + }); + + it("should convert tool responses correctly", () => { + const message: ChatMessage = { + role: "tool", + content: "Tool result", + toolCallId: "tool-1", + }; + const converted = bedrock["_convertMessage"](message); + expect(converted).toEqual({ + role: "user", + content: [{ + toolResult: { + toolUseId: "tool-1", + content: [{ text: "Tool result" }], + }, + }], + }); + }); + + it("should convert tool calls correctly", () => { + const message: ChatMessage = { + role: "assistant", + content: "", + toolCalls: [{ + id: "tool-1", + type: "function" as const, + function: { + name: "test_tool", + arguments: '{"arg":"value"}', + }, + }], + }; + const converted = bedrock["_convertMessage"](message); + expect(converted).toEqual({ + role: "assistant", + content: [{ + toolUse: { + toolUseId: "tool-1", + name: "test_tool", + input: { arg: "value" }, + }, + }], + }); + }); + + it("should handle multimodal content correctly", () => { + const message: ChatMessage = { + role: "user", + content: [ + { type: "text", text: "Look at this image:" }, + { + type: "imageUrl", + imageUrl: { + url: "data:image/jpeg;base64,/9j/4AAQSkZJRg==", + }, + }, + ], + } as UserChatMessage; + const converted = bedrock["_convertMessage"](message); + expect(converted).toEqual({ + role: "user", + content: [ + { text: "Look at this image:" }, + { + image: { + format: "jpeg", + source: { + bytes: Buffer.from("/9j/4AAQSkZJRg==", "base64"), + }, + }, + }, + ], + }); + }); + }); +}); diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 17d2911b8..aa15997ad 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -10,16 +10,25 @@ import { Chunk, CompletionOptions, LLMOptions, - MessageContent, } from "../../index.js"; import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; +import { PROVIDER_TOOL_SUPPORT } from "../toolSupport.js"; interface ModelConfig { formatPayload: (text: string) => any; extractEmbeddings: (responseBody: any) => number[][]; } +/** + * Interface for tool use state tracking + */ +interface ToolUseState { + toolUseId: string; + name: string; + input: string; +} + class Bedrock extends BaseLLM { static providerName = "bedrock"; static defaultOptions: Partial = { @@ -29,6 +38,10 @@ class Bedrock extends BaseLLM { profile: "bedrock", }; + private _currentToolResponse: Partial | null = null; + + public requestOptions: { region?: string; credentials?: any; headers?: Record }; + constructor(options: LLMOptions) { super(options); if (!options.apiBase) { @@ -39,6 +52,10 @@ class Bedrock extends BaseLLM { } else { this.profile = "bedrock"; } + this.requestOptions = { + region: options.region, + headers: {}, + }; } protected async *_streamComplete( @@ -58,7 +75,6 @@ class Bedrock extends BaseLLM { options: CompletionOptions, ): AsyncGenerator { const credentials = await this._getCredentials(); - const client = new BedrockRuntimeClient({ region: this.region, endpoint: this.apiBase, @@ -70,9 +86,9 @@ class Bedrock extends BaseLLM { }); let config_headers = - this.requestOptions && this.requestOptions.headers - ? this.requestOptions.headers - : {}; + this.requestOptions && this.requestOptions.headers + ? this.requestOptions.headers + : {}; // AWS SigV4 requires strict canonicalization of headers. // DO NOT USE "_" in your header name. It will return an error like below. // "The request signature we calculated does not match the signature you provided." @@ -90,32 +106,116 @@ class Bedrock extends BaseLLM { }, ); - const input = this._generateConverseInput(messages, options); + const input = this._generateConverseInput(messages, { ...options, stream: true }); const command = new ConverseStreamCommand(input); - const response = await client.send(command, { abortSignal: signal }); - if (response.stream) { + let response; + try { + response = await client.send(command, { abortSignal: signal }); + } catch (error: unknown) { + const message = error instanceof Error ? error.message : "Unknown error"; + throw new Error(`Failed to communicate with Bedrock API: ${message}`); + } + + if (!response?.stream) { + throw new Error("No stream received from Bedrock API"); + } + + try { for await (const chunk of response.stream) { - if (chunk.contentBlockDelta?.delta?.text) { - yield { - role: "assistant", - content: chunk.contentBlockDelta.delta.text, - }; + + console.log(chunk); + + if (chunk.contentBlockDelta?.delta) { + + // Handle text content + if (chunk.contentBlockDelta.delta.text) { + yield { role: "assistant", content: chunk.contentBlockDelta.delta.text }; + continue; + } + + if (chunk.contentBlockDelta.delta.toolUse?.input && this._currentToolResponse) { + // Append the new input to the existing string + if (this._currentToolResponse.input === undefined) { + this._currentToolResponse.input = ""; + } + this._currentToolResponse.input += chunk.contentBlockDelta.delta.toolUse.input; + continue; + } + } + + if (chunk.contentBlockStart?.start) { + const toolUse = chunk.contentBlockStart.start.toolUse; + if (toolUse?.toolUseId && toolUse?.name) { + this._currentToolResponse = { + toolUseId: toolUse.toolUseId, + name: toolUse.name, + input: "" + }; + } + continue; + } + + if (chunk.contentBlockStop) { + if (this._currentToolResponse) { + yield { + role: "assistant", + content: "", + toolCalls: [{ + id: this._currentToolResponse.toolUseId, + type: "function", + function: { + name: this._currentToolResponse.name, + arguments: this._currentToolResponse.input + } + }], + }; + this._currentToolResponse = null; + } + continue; } } + } catch (error: unknown) { + this._currentToolResponse = null; + if (error instanceof Error) { + if ("code" in error) { + // AWS SDK specific errors + throw new Error(`AWS Bedrock stream error (${(error as any).code}): ${error.message}`); + } + throw new Error(`Error processing Bedrock stream: ${error.message}`); + } + throw new Error("Error processing Bedrock stream: Unknown error occurred"); } } + /** + * Generates the input payload for the Bedrock Converse API + * @param messages - Array of chat messages + * @param options - Completion options + * @returns Formatted input payload for the API + */ private _generateConverseInput( messages: ChatMessage[], options: CompletionOptions, ): any { const convertedMessages = this._convertMessages(messages); + const supportsTools = PROVIDER_TOOL_SUPPORT.bedrock?.(options.model || "") ?? false; return { modelId: options.model, messages: convertedMessages, system: this.systemMessage ? [{ text: this.systemMessage }] : undefined, + toolConfig: supportsTools && options.tools ? { + tools: options.tools.map(tool => ({ + toolSpec: { + name: tool.function.name, + description: tool.function.description, + inputSchema: { + json: tool.function.parameters + } + } + })) + } : undefined, inferenceConfig: { maxTokens: options.maxTokens, temperature: options.temperature, @@ -135,35 +235,93 @@ class Bedrock extends BaseLLM { }; } - private _convertMessages(messages: ChatMessage[]): any[] { - return messages - .filter((message) => message.role !== "system") - .map((message) => ({ + private _convertMessage(message: ChatMessage): any { + // Handle system messages explicitly + if (message.role === "system") { + return; + } + + // Tool response handling + if (message.role === "tool") { + return { + role: "user", + content: [ + { + toolResult: { + toolUseId: message.toolCallId, + content: [ + { + text: message.content || "" + } + ] + } + } + ] + }; + } + + // Tool calls handling + if (message.role === "assistant" && message.toolCalls) { + return { + role: "assistant", + content: message.toolCalls.map((toolCall) => ({ + toolUse: { + toolUseId: toolCall.id, + name: toolCall.function?.name, + input: JSON.parse(toolCall.function?.arguments || "{}"), + } + })) + }; + } + + // Standard text message + if (typeof message.content === "string") { + return { role: message.role, - content: this._convertMessageContent(message.content), - })); + content: [{ text: message.content }] + }; + } + + // Improved multimodal content handling + if (Array.isArray(message.content)) { + return { + role: message.role, + content: message.content.map(part => { + if (part.type === "text") { + return { text: part.text }; + } + if (part.type === "imageUrl" && part.imageUrl) { + try { + const [mimeType, base64Data] = part.imageUrl.url.split(","); + const format = mimeType.split("/")[1]?.split(";")[0] || "jpeg"; + return { + image: { + format, + source: { + bytes: Buffer.from(base64Data, "base64") + } + } + }; + } catch (error) { + console.warn(`Failed to process image: ${error}`); + return null; + } + } + return null; + }).filter(Boolean) + }; + } } - private _convertMessageContent(messageContent: MessageContent): any[] { - if (typeof messageContent === "string") { - return [{ text: messageContent }]; - } - return messageContent - .map((part) => { - if (part.type === "text") { - return { text: part.text }; + private _convertMessages(messages: ChatMessage[]): any[] { + return messages + .map((message) => { + try { + return this._convertMessage(message); + } catch (error) { + console.error(`Failed to convert message: ${error}`); + return null; } - if (part.type === "imageUrl" && part.imageUrl) { - return { - image: { - format: "jpeg", - source: { - bytes: Buffer.from(part.imageUrl.url.split(",")[1], "base64"), - }, - }, - }; - } - return null; }) .filter(Boolean); } @@ -229,6 +387,7 @@ class Bedrock extends BaseLLM { return modelConfig.extractEmbeddings(responseBody); } + private _getModelConfig() { const modelConfigs: { [key: string]: ModelConfig } = { cohere: { @@ -301,9 +460,15 @@ class Bedrock extends BaseLLM { return responseBody.results .sort((a: any, b: any) => a.index - b.index) .map((result: any) => result.relevance_score); - } catch (error) { - console.error("Error in BedrockReranker.rerank:", error); - throw error; + } catch (error: unknown) { + if (error instanceof Error) { + if ("code" in error) { + // AWS SDK specific errors + throw new Error(`AWS Bedrock rerank error (${(error as any).code}): ${error.message}`); + } + throw new Error(`Error in BedrockReranker.rerank: ${error.message}`); + } + throw new Error("Error in BedrockReranker.rerank: Unknown error occurred"); } } } diff --git a/core/llm/llms/NCompass.ts b/core/llm/llms/NCompass.ts new file mode 100644 index 000000000..45ee8ca7c --- /dev/null +++ b/core/llm/llms/NCompass.ts @@ -0,0 +1,62 @@ +import { ChatCompletionCreateParams } from "openai/resources/index"; +import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; + +import OpenAI from "./OpenAI.js"; + +class NCompass extends OpenAI { + static providerName = "ncompass"; + static defaultOptions: Partial = { + apiBase: "https://api.ncompass.tech/v1" + }; + static embeddingsApiEndpoint: "https://api.gcp.ncompass.tech/v1/embeddings" + + private static modelConversion: { [key: string]: string } = { + "qwen2.5-coder-7b": "Qwen/Qwen2.5-Coder-7B-Instruct", + "qwen2.5-coder:7b": "Qwen/Qwen2.5-Coder-7B-Instruct", + "qwen2.5-coder-32b": "Qwen/Qwen2.5-Coder-32B-Instruct", + "qwen2.5-coder:32b": "Qwen/Qwen2.5-Coder-32B-Instruct", + }; + protected _convertModelName(model: string): string { + return NCompass.modelConversion[model] ?? model; + } + + protected _convertArgs( + options: CompletionOptions, + messages: ChatMessage[], + ): ChatCompletionCreateParams { + const finalOptions = super._convertArgs(options, messages); + finalOptions.model = this._convertModelName(options.model); + return finalOptions; + } + + protected _getHeaders() { + const headers = super._getHeaders() as { "Content-Type": string; Authorization: string; "api-key": string; Accept?: string }; + headers["Accept"] = "text/event-stream"; + return headers; + } + + protected async _embed(chunks: string[]): Promise { + const resp = await this.fetch(NCompass.embeddingsApiEndpoint, { + method: "POST", + body: JSON.stringify({ + input: chunks, + model: this.model, + ...this.extraBodyProperties(), + }), + headers: { + Authorization: `Bearer ${this.apiKey}`, + "Content-Type": "application/json", + }, + }); + + if (!resp.ok) { + throw new Error(await resp.text()); + } + + const data = (await resp.json()) as any; + return data.data.map((result: { embedding: number[] }) => result.embedding); + } + +} + +export default NCompass; diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index fe1902b89..752034fc6 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -139,12 +139,17 @@ class Ollama extends BaseLLM { if (options.model === "AUTODETECT") { return; } + const headers: Record = { + "Content-Type": "application/json", + }; + + if (this.apiKey) { + headers.Authorization = `Bearer ${this.apiKey}`; + } + this.fetch(this.getEndpoint("api/show"), { method: "POST", - headers: { - Authorization: `Bearer ${this.apiKey}`, - "Content-Type": "application/json", - }, + headers: headers, body: JSON.stringify({ name: this._getModel() }), }) .then(async (response) => { @@ -324,12 +329,16 @@ class Ollama extends BaseLLM { signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { + const headers: Record = { + "Content-Type": "application/json", + }; + + if (this.apiKey) { + headers.Authorization = `Bearer ${this.apiKey}`; + } const response = await this.fetch(this.getEndpoint("api/generate"), { method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${this.apiKey}`, - }, + headers: headers, body: JSON.stringify(this._getGenerateOptions(options, prompt)), signal, }); @@ -385,13 +394,16 @@ class Ollama extends BaseLLM { })); chatOptions.stream = false; // Cannot set stream = true for tools calls } - + const headers: Record = { + "Content-Type": "application/json", + }; + + if (this.apiKey) { + headers.Authorization = `Bearer ${this.apiKey}`; + } const response = await this.fetch(this.getEndpoint("api/chat"), { method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${this.apiKey}`, - }, + headers: headers, body: JSON.stringify(chatOptions), signal, }); @@ -468,12 +480,16 @@ class Ollama extends BaseLLM { signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { + const headers: Record = { + "Content-Type": "application/json", + }; + + if (this.apiKey) { + headers.Authorization = `Bearer ${this.apiKey}`; + } const response = await this.fetch(this.getEndpoint("api/generate"), { method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${this.apiKey}`, - }, + headers: headers, body: JSON.stringify(this._getGenerateOptions(options, prefix, suffix)), signal, }); @@ -505,11 +521,19 @@ class Ollama extends BaseLLM { } async listModels(): Promise { + const headers: Record = { + "Content-Type": "application/json", + }; + + if (this.apiKey) { + headers.Authorization = `Bearer ${this.apiKey}`; + } const response = await this.fetch( // localhost was causing fetch failed in pkg binary only for this Ollama endpoint this.getEndpoint("api/tags"), { method: "GET", + headers: headers, }, ); const data = await response.json(); @@ -523,16 +547,20 @@ class Ollama extends BaseLLM { } protected async _embed(chunks: string[]): Promise { + const headers: Record = { + "Content-Type": "application/json", + }; + + if (this.apiKey) { + headers.Authorization = `Bearer ${this.apiKey}`; + } const resp = await this.fetch(new URL("api/embed", this.apiBase), { method: "POST", body: JSON.stringify({ model: this.model, input: chunks, }), - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${this.apiKey}`, - }, + headers: headers }); if (!resp.ok) { diff --git a/core/llm/llms/SambaNova.ts b/core/llm/llms/SambaNova.ts index 7c1f83c89..4c2599529 100644 --- a/core/llm/llms/SambaNova.ts +++ b/core/llm/llms/SambaNova.ts @@ -9,11 +9,20 @@ class SambaNova extends OpenAI { }; private static MODEL_IDS: { [name: string]: string } = { + "qwen2.5-coder-32b": "Qwen2.5-Coder-32B-Instruct", + "llama3.3-70b": "Meta-Llama-3.3-70B-Instruct", "llama3.1-8b": "Meta-Llama-3.1-8B-Instruct", "llama3.1-70b": "Meta-Llama-3.1-70B-Instruct", "llama3.1-405b": "Meta-Llama-3.1-405B-Instruct", - "llama3.1-1b": "Meta-Llama-3.2-1B-Instruct", - "llama3.1-3b": "Meta-Llama-3.2-3B-Instruct", + "llama3.1-tulu-405b": "Llama-3.1-Tulu-3-405B", + "llama3.2-1b": "Meta-Llama-3.2-1B-Instruct", + "llama3.2-3b": "Meta-Llama-3.2-3B-Instruct", + "llama3.2-11b": "Llama-3.2-11B-Vision-Instruct", + "llama3.2-90b": "Llama-3.2-90B-Vision-Instruct", + "qwen2.5-72b": "Qwen2.5-72B-Instruct", + "qwq-32b": "QwQ-32B-Preview", + "deepseek-r1-distill-llama-70b": "DeepSeek-R1-Distill-Llama-70B", + "deepseek-r1": "DeepSeek-R1", }; protected _convertModelName(model: string) { diff --git a/core/llm/llms/TransformersJsEmbeddingsProvider.ts b/core/llm/llms/TransformersJsEmbeddingsProvider.ts index 206d534d3..d17c9e0f1 100644 --- a/core/llm/llms/TransformersJsEmbeddingsProvider.ts +++ b/core/llm/llms/TransformersJsEmbeddingsProvider.ts @@ -43,6 +43,7 @@ export class TransformersJsEmbeddingsProvider extends BaseLLM { static maxGroupSize: number = 1; static model: string = "all-MiniLM-L6-v2"; static mockVector: number[] = Array.from({ length: 384 }).fill(2) as number[]; + static title: string = "Transformers.js (Built-In)"; static defaultOptions: Partial | undefined = { model: TransformersJsEmbeddingsProvider.model, diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index 20bc8b710..32cda4aec 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -19,6 +19,7 @@ import Cohere from "./Cohere"; import DeepInfra from "./DeepInfra"; import Deepseek from "./Deepseek"; import Fireworks from "./Fireworks"; +import NCompass from "./NCompass"; import Flowise from "./Flowise"; import FreeTrial from "./FreeTrial"; import FunctionNetwork from "./FunctionNetwork"; @@ -81,6 +82,7 @@ export const LLMClasses = [ Flowise, Groq, Fireworks, + NCompass, ContinueProxy, Cloudflare, Deepseek, diff --git a/core/llm/llms/stubs/ContinueProxy.ts b/core/llm/llms/stubs/ContinueProxy.ts index 848b3fff7..00ec93dbc 100644 --- a/core/llm/llms/stubs/ContinueProxy.ts +++ b/core/llm/llms/stubs/ContinueProxy.ts @@ -1,3 +1,5 @@ +import { ContinueProperties } from "@continuedev/config-yaml"; + import { ControlPlaneProxyInfo } from "../../../control-plane/analytics/IAnalyticsProvider.js"; import { Telemetry } from "../../../util/posthog.js"; import OpenAI from "../OpenAI.js"; @@ -7,7 +9,12 @@ import type { Chunk, LLMOptions } from "../../../index.js"; class ContinueProxy extends OpenAI { set controlPlaneProxyInfo(value: ControlPlaneProxyInfo) { this.apiKey = value.workOsAccessToken; - this.apiBase = new URL("openai/v1/", value.controlPlaneProxyUrl).toString(); + if (!this.onPremProxyUrl) { + this.apiBase = new URL( + "openai/v1/", + value.controlPlaneProxyUrl, + ).toString(); + } } // The apiKey and apiBase are set to the values for the proxy, @@ -19,6 +26,11 @@ class ContinueProxy extends OpenAI { super(options); this.actualApiBase = options.apiBase; this.apiKeyLocation = options.apiKeyLocation; + this.orgScopeId = options.orgScopeId; + this.onPremProxyUrl = options.onPremProxyUrl; + if (this.onPremProxyUrl) { + this.apiBase = new URL("openai/v1/", this.onPremProxyUrl).toString(); + } } static providerName = "continue-proxy"; @@ -27,11 +39,13 @@ class ContinueProxy extends OpenAI { }; protected extraBodyProperties(): Record { + const continueProperties: ContinueProperties = { + apiKeyLocation: this.apiKeyLocation, + apiBase: this.actualApiBase, + orgScopeId: this.orgScopeId ?? null, + }; return { - continueProperties: { - apiKeyLocation: this.apiKeyLocation, - apiBase: this.actualApiBase, - }, + continueProperties, }; } diff --git a/core/llm/toolSupport.test.ts b/core/llm/toolSupport.test.ts new file mode 100644 index 000000000..df18dc876 --- /dev/null +++ b/core/llm/toolSupport.test.ts @@ -0,0 +1,203 @@ +// core/llm/toolSupport.test.ts +import { PROVIDER_TOOL_SUPPORT } from "./toolSupport"; + +describe("PROVIDER_TOOL_SUPPORT", () => { + describe("continue-proxy", () => { + const supportsFn = PROVIDER_TOOL_SUPPORT["continue-proxy"]; + + it("should return true for Claude 3.5 models", () => { + expect(supportsFn("claude-3-5-sonnet")).toBe(true); + expect(supportsFn("claude-3.5-sonnet")).toBe(true); + }); + + it("should return true for Claude 3.7 models", () => { + expect(supportsFn("claude-3-7-haiku")).toBe(true); + expect(supportsFn("claude-3.7-sonnet")).toBe(true); + }); + + it("should return true for GPT-4 models", () => { + expect(supportsFn("gpt-4-turbo")).toBe(true); + expect(supportsFn("gpt-4-1106-preview")).toBe(true); + }); + + it("should return true for O3 models", () => { + expect(supportsFn("o3-preview")).toBe(true); + }); + + it("should return true for Gemini models", () => { + expect(supportsFn("gemini-pro")).toBe(true); + expect(supportsFn("gemini-1.5-pro")).toBe(true); + }); + + it("should return false for unsupported models", () => { + expect(supportsFn("gpt-3.5-turbo")).toBe(false); + expect(supportsFn("claude-2")).toBe(false); + expect(supportsFn("llama-3")).toBe(false); + }); + + it("should handle case insensitivity", () => { + expect(supportsFn("CLAUDE-3-5-sonnet")).toBe(true); + expect(supportsFn("GPT-4-turbo")).toBe(true); + expect(supportsFn("GEMINI-pro")).toBe(true); + }); + }); + + describe("anthropic", () => { + const supportsFn = PROVIDER_TOOL_SUPPORT["anthropic"]; + + it("should return true for Claude 3.5 models", () => { + expect(supportsFn("claude-3-5-sonnet")).toBe(true); + expect(supportsFn("claude-3.5-haiku")).toBe(true); + }); + + it("should return true for Claude 3.7 models", () => { + expect(supportsFn("claude-3-7-haiku")).toBe(true); + expect(supportsFn("claude-3.7-sonnet")).toBe(true); + }); + + it("should return undefined for unsupported models", () => { + expect(supportsFn("claude-2")).toBeUndefined(); + expect(supportsFn("claude-instant")).toBeUndefined(); + }); + + it("should handle case insensitivity", () => { + expect(supportsFn("CLAUDE-3-5-sonnet")).toBe(true); + expect(supportsFn("CLAUDE-3.7-haiku")).toBe(true); + }); + }); + + describe("openai", () => { + const supportsFn = PROVIDER_TOOL_SUPPORT["openai"]; + + it("should return true for GPT-4 models", () => { + expect(supportsFn("gpt-4")).toBe(true); + expect(supportsFn("gpt-4-turbo")).toBe(true); + expect(supportsFn("gpt-4-1106-preview")).toBe(true); + }); + + it("should return true for O3 models", () => { + expect(supportsFn("o3")).toBe(true); + expect(supportsFn("o3-preview")).toBe(true); + }); + + it("should return undefined for unsupported models", () => { + expect(supportsFn("gpt-3.5-turbo")).toBeUndefined(); + expect(supportsFn("davinci")).toBeUndefined(); + }); + + it("should handle case insensitivity", () => { + expect(supportsFn("GPT-4-turbo")).toBe(true); + expect(supportsFn("O3-preview")).toBe(true); + }); + }); + + describe("gemini", () => { + const supportsFn = PROVIDER_TOOL_SUPPORT["gemini"]; + + it("should return true for all Gemini models", () => { + expect(supportsFn("gemini-pro")).toBe(true); + expect(supportsFn("gemini-1.5-pro")).toBe(true); + expect(supportsFn("gemini-ultra")).toBe(true); + }); + + it("should return false for non-Gemini models", () => { + expect(supportsFn("gpt-4")).toBe(false); + expect(supportsFn("claude-3")).toBe(false); + }); + + it("should handle case insensitivity", () => { + expect(supportsFn("GEMINI-pro")).toBe(true); + expect(supportsFn("Gemini-1.5-Pro")).toBe(true); + }); + }); + + describe("bedrock", () => { + const supportsFn = PROVIDER_TOOL_SUPPORT["bedrock"]; + + it("should return true for Claude 3.5 Sonnet models", () => { + expect(supportsFn("anthropic.claude-3-5-sonnet-20240620-v1:0")).toBe(true); + expect(supportsFn("anthropic.claude-3.5-sonnet-20240620-v1:0")).toBe(true); + }); + + it("should return true for Claude 3.7 Sonnet models", () => { + expect(supportsFn("anthropic.claude-3-7-sonnet-20240620-v1:0")).toBe(true); + expect(supportsFn("anthropic.claude-3.7-sonnet-20240620-v1:0")).toBe(true); + }); + + it("should return undefined for Claude Haiku and Opus models", () => { + expect(supportsFn("anthropic.claude-3-5-haiku-20240307-v1:0")).toBeUndefined(); + expect(supportsFn("anthropic.claude-3.5-haiku-20240620-v1:0")).toBeUndefined(); + expect(supportsFn("anthropic.claude-3-7-haiku-20240620-v1:0")).toBeUndefined(); + expect(supportsFn("anthropic.claude-3-5-opus-20240620-v1:0")).toBeUndefined(); + expect(supportsFn("anthropic.claude-3.7-opus-20240620-v1:0")).toBeUndefined(); + }); + + it("should return undefined for other unsupported models", () => { + expect(supportsFn("anthropic.claude-instant-v1")).toBeUndefined(); + expect(supportsFn("anthropic.titan-text-express-v1")).toBeUndefined(); + }); + + it("should handle case insensitivity", () => { + expect(supportsFn("ANTHROPIC.CLAUDE-3-5-SONNET-20240620-v1:0")).toBe(true); + expect(supportsFn("ANTHROPIC.CLAUDE-3.7-SONNET-20240620-v1:0")).toBe(true); + }); + }); + + describe("ollama", () => { + const supportsFn = PROVIDER_TOOL_SUPPORT["ollama"]; + + it("should return true for supported models", () => { + expect(supportsFn("llama3.1")).toBe(true); + expect(supportsFn("llama3.2-8b")).toBe(true); + expect(supportsFn("llama3.3-70b")).toBe(true); + expect(supportsFn("qwen2")).toBe(true); + expect(supportsFn("mixtral-8x7b")).toBe(true); + expect(supportsFn("command-r")).toBe(true); + expect(supportsFn("smollm2")).toBe(true); + expect(supportsFn("hermes3")).toBe(true); + expect(supportsFn("athene-v2")).toBe(true); + expect(supportsFn("nemotron-4-340b")).toBe(true); + expect(supportsFn("llama3-groq")).toBe(true); + expect(supportsFn("granite3")).toBe(true); + expect(supportsFn("aya-expanse")).toBe(true); + expect(supportsFn("firefunction-v2")).toBe(true); + expect(supportsFn("mistral-7b")).toBe(true); + }); + + it("should return false for explicitly unsupported models", () => { + expect(supportsFn("vision")).toBe(false); + expect(supportsFn("math")).toBe(false); + expect(supportsFn("guard")).toBe(false); + expect(supportsFn("mistrallite")).toBe(false); + expect(supportsFn("mistral-openorca")).toBe(false); + }); + + it("should return undefined for other models", () => { + expect(supportsFn("llama2")).toBeUndefined(); + expect(supportsFn("phi-2")).toBeUndefined(); + expect(supportsFn("falcon")).toBeUndefined(); + }); + + it("should handle case insensitivity", () => { + expect(supportsFn("LLAMA3.1")).toBe(true); + expect(supportsFn("MIXTRAL-8x7b")).toBe(true); + expect(supportsFn("VISION")).toBe(false); + }); + }); + + describe("edge cases", () => { + it("should handle empty model names", () => { + expect(PROVIDER_TOOL_SUPPORT["continue-proxy"]("")).toBe(false); + expect(PROVIDER_TOOL_SUPPORT["anthropic"]("")).toBeUndefined(); + expect(PROVIDER_TOOL_SUPPORT["openai"]("")).toBeUndefined(); + expect(PROVIDER_TOOL_SUPPORT["gemini"]("")).toBe(false); + expect(PROVIDER_TOOL_SUPPORT["bedrock"]("")).toBeUndefined(); + expect(PROVIDER_TOOL_SUPPORT["ollama"]("")).toBeUndefined(); + }); + + it("should handle non-existent provider", () => { + // @ts-ignore - Testing runtime behavior with invalid provider + expect(PROVIDER_TOOL_SUPPORT["non-existent"]).toBeUndefined(); + }); + }); +}); diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index e1e030467..1e23cbf3e 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -3,13 +3,28 @@ export const PROVIDER_TOOL_SUPPORT: Record< (model: string) => boolean | undefined > = { "continue-proxy": (model) => { - return ["claude-3-5", "claude-3.5", "gpt-4", "o3", "gemini"].some((part) => - model.toLowerCase().startsWith(part), - ); + // see getContinueProxyModelName + const provider = model.split("/")[2]; + const _model = model.split("/")[3]; + if (provider && _model && provider !== "continue-proxy") { + const fn = PROVIDER_TOOL_SUPPORT[provider]; + if (fn) { + return fn(_model); + } + } + return [ + "claude-3-5", + "claude-3.5", + "claude-3-7", + "claude-3.7", + "gpt-4", + "o3", + "gemini", + ].some((part) => model.toLowerCase().startsWith(part)); }, anthropic: (model) => { if ( - ["claude-3-5", "claude-3.5"].some((part) => + ["claude-3-5", "claude-3.5", "claude-3-7", "claude-3.7"].some((part) => model.toLowerCase().startsWith(part), ) ) { @@ -29,6 +44,17 @@ export const PROVIDER_TOOL_SUPPORT: Record< // All gemini models support function calling return model.toLowerCase().includes("gemini"); }, + bedrock: (model) => { + // For Bedrock, only support Claude Sonnet models with versions 3.5/3-5 and 3.7/3-7 + if ( + model.toLowerCase().includes("sonnet") && + ["claude-3-5", "claude-3.5", "claude-3-7", "claude-3.7"].some((part) => + model.toLowerCase().includes(part), + ) + ) { + return true; + } + }, // https://ollama.com/search?c=tools ollama: (model) => { if ( @@ -61,4 +87,12 @@ export const PROVIDER_TOOL_SUPPORT: Record< return true; } }, + sambanova: (model) => { + // https://docs.sambanova.ai/cloud/docs/capabilities/function-calling + if ( + model.toLowerCase().startsWith("meta-llama-3") + ) { + return true; + } + }, }; diff --git a/core/package-lock.json b/core/package-lock.json index b6285e5e2..a15d33faf 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -13,13 +13,13 @@ "@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.31", + "@continuedev/config-yaml": "^1.0.52", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", "@continuedev/openai-adapters": "^1.0.10", "@modelcontextprotocol/sdk": "^1.5.0", "@mozilla/readability": "^0.5.0", - "@octokit/rest": "^20.0.2", + "@octokit/rest": "^20.1.1", "@typescript-eslint/eslint-plugin": "^7.8.0", "@xenova/transformers": "2.14.0", "adf-to-md": "^1.1.0", @@ -72,7 +72,7 @@ "wink-nlp-utils": "^2.1.0", "workerpool": "^9.1.3", "yaml": "^2.4.2", - "zod": "^3.23.8" + "zod": "^3.24.2" }, "devDependencies": { "@babel/preset-env": "^7.24.7", @@ -3038,13 +3038,13 @@ } }, "node_modules/@continuedev/config-yaml": { - "version": "1.0.31", - "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.31.tgz", - "integrity": "sha512-HNj+z7UTTARgsJTI0A1buM09fS4HoWVnn6Hbl6kJ2tZmOOm1OgogbcKP68AzHb4fy5H18MWnKS7XuseZpHFzHQ==", + "version": "1.0.52", + "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.52.tgz", + "integrity": "sha512-x0m4bcQpjHrrv95cq5tsen4Hb6yKCVGn+NeojyzNQYnRD0If/On+ATgX78uXtQtZxsdO4ip73HHCyQlA0O3ZyQ==", "dependencies": { "@continuedev/config-types": "^1.0.14", "yaml": "^2.6.1", - "zod": "^3.23.8" + "zod": "^3.24.2" } }, "node_modules/@continuedev/fetch": { @@ -4232,14 +4232,6 @@ "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", @@ -6171,9 +6163,10 @@ "integrity": "sha512-lHe62zvbTB5eEABUVi/AwVh0ZKY9rMMDhmm+eeyuuUQbQ3+J+fONVQOZyj+DdrvD4BY33uYniyRJ4UJIaSKAfw==" }, "node_modules/axios": { - "version": "1.7.9", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.9.tgz", - "integrity": "sha512-LhLcE7Hbiryz8oMDdDptSrWowmB4Bl6RCt6sIJKpRB4XtVf0iEgewX3au/pJqm+Py1kCASkb/FFKjxQaLtxJvw==", + "version": "1.8.2", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.8.2.tgz", + "integrity": "sha512-ls4GYBm5aig9vWx8AWDSGLpnpDQRtWAfrjU+EuytuODrFBkqesN2RkOQCBzrA1RQNHw1SmRMSDDDSwzNAYQ6Rg==", + "license": "MIT", "dependencies": { "follow-redirects": "^1.15.6", "form-data": "^4.0.0", @@ -6829,6 +6822,14 @@ "devtools-protocol": "*" } }, + "node_modules/chromium-bidi/node_modules/zod": { + "version": "3.23.8", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.23.8.tgz", + "integrity": "sha512-XBx9AXhXktjUqnepgTiE5flcKIYWi/rme0Eaj+5Y0lftuGBq+jyRu/md4WnuxqgP1ubdpNCsYEYPxrzVHD8d6g==", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, "node_modules/ci-info": { "version": "3.9.0", "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.9.0.tgz", @@ -13691,6 +13692,14 @@ "node": ">=10" } }, + "node_modules/puppeteer-chromium-resolver/node_modules/zod": { + "version": "3.23.8", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.23.8.tgz", + "integrity": "sha512-XBx9AXhXktjUqnepgTiE5flcKIYWi/rme0Eaj+5Y0lftuGBq+jyRu/md4WnuxqgP1ubdpNCsYEYPxrzVHD8d6g==", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, "node_modules/puppeteer-core": { "version": "22.15.0", "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-22.15.0.tgz", @@ -16268,9 +16277,9 @@ } }, "node_modules/zod": { - "version": "3.23.8", - "resolved": "https://registry.npmjs.org/zod/-/zod-3.23.8.tgz", - "integrity": "sha512-XBx9AXhXktjUqnepgTiE5flcKIYWi/rme0Eaj+5Y0lftuGBq+jyRu/md4WnuxqgP1ubdpNCsYEYPxrzVHD8d6g==", + "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/core/package.json b/core/package.json index 37a5b8a3e..a88bf0cf1 100644 --- a/core/package.json +++ b/core/package.json @@ -46,13 +46,13 @@ "@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.31", + "@continuedev/config-yaml": "^1.0.52", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", "@continuedev/openai-adapters": "^1.0.10", "@modelcontextprotocol/sdk": "^1.5.0", "@mozilla/readability": "^0.5.0", - "@octokit/rest": "^20.0.2", + "@octokit/rest": "^20.1.1", "@typescript-eslint/eslint-plugin": "^7.8.0", "@xenova/transformers": "2.14.0", "adf-to-md": "^1.1.0", @@ -105,7 +105,7 @@ "wink-nlp-utils": "^2.1.0", "workerpool": "^9.1.3", "yaml": "^2.4.2", - "zod": "^3.23.8" + "zod": "^3.24.2" }, "engine-strict": true, "engines": { diff --git a/core/promptFiles/v1/getContextProviderHelpers.ts b/core/promptFiles/v1/getContextProviderHelpers.ts index e027ffbc5..30b51bf8b 100644 --- a/core/promptFiles/v1/getContextProviderHelpers.ts +++ b/core/promptFiles/v1/getContextProviderHelpers.ts @@ -19,12 +19,12 @@ export function getContextProviderHelpers( async (helperContext: any) => { const items = await provider.getContextItems(helperContext, { config: context.config, - embeddingsProvider: context.config.embeddingsProvider, + embeddingsProvider: context.config.selectedModelByRole.embed, fetch: context.fetch, fullInput: context.input, ide: context.ide, llm: context.llm, - reranker: context.config.reranker, + reranker: context.config.selectedModelByRole.rerank, selectedCode: context.selectedCode, }); diff --git a/core/promptFiles/v2/getPromptFiles.ts b/core/promptFiles/v2/getPromptFiles.ts index d991d140a..7859c7cf7 100644 --- a/core/promptFiles/v2/getPromptFiles.ts +++ b/core/promptFiles/v2/getPromptFiles.ts @@ -16,7 +16,7 @@ export async function getPromptFilesFromDir( return []; } - const uris = await walkDir(dir, ide, { ignoreFiles: [] }); + const uris = await walkDir(dir, ide); const promptFilePaths = uris.filter((p) => p.endsWith(".prompt")); const results = promptFilePaths.map(async (uri) => { const content = await ide.readFile(uri); // make a try catch diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 96eebce84..ac991622a 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -1,10 +1,11 @@ -import { ConfigResult } from "@continuedev/config-yaml"; +import { ConfigResult, ModelRole } from "@continuedev/config-yaml"; import { AutocompleteInput } from "../autocomplete/util/types"; import { ProfileDescription } from "../config/ConfigHandler"; import { OrganizationDescription } from "../config/ProfileLifecycleManager"; import { SharedConfigSchema } from "../config/sharedConfig"; +import { DevDataLogEvent } from "@continuedev/config-yaml"; import type { BrowserSerializedContinueConfig, ChatMessage, @@ -27,6 +28,7 @@ import type { SiteIndexingConfig, ToolCall, } from "../"; +import { GlobalContextModelSelections } from "../util/GlobalContext"; export type OnboardingModes = "Local" | "Best" | "Custom" | "Quickstart"; @@ -36,8 +38,6 @@ export interface ListHistoryOptions { } export type ToCoreFromIdeOrWebviewProtocol = { - "update/selectTabAutocompleteModel": [string, void]; - // Special ping: [string, string]; abort: [undefined, void]; @@ -47,7 +47,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { "history/delete": [{ id: string }, void]; "history/load": [{ id: string }, Session]; "history/save": [Session, void]; - "devdata/log": [{ tableName: string; data: any }, void]; + "devdata/log": [DevDataLogEvent, void]; "config/addOpenAiKey": [string, void]; "config/addModel": [ { @@ -69,8 +69,17 @@ export type ToCoreFromIdeOrWebviewProtocol = { "config/addContextProvider": [ContextProviderWithParams, void]; "config/reload": [undefined, ConfigResult]; "config/listProfiles": [undefined, ProfileDescription[] | null]; + "config/refreshProfiles": [undefined, void]; "config/openProfile": [{ profileId: string | undefined }, void]; - "config/updateSharedConfig": [SharedConfigSchema, void]; + "config/updateSharedConfig": [SharedConfigSchema, SharedConfigSchema]; + "config/updateSelectedModel": [ + { + profileId: string; + role: ModelRole; + title: string | null; + }, + GlobalContextModelSelections, + ]; "context/getContextItems": [ { name: string; @@ -99,6 +108,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { params: any; historyIndex: number; selectedCode: RangeInFile[]; + completionOptions?: LLMFullCompletionOptions; }, AsyncGenerator, ]; diff --git a/core/protocol/coreWebview.ts b/core/protocol/coreWebview.ts index 67b5919a4..5e71e5f11 100644 --- a/core/protocol/coreWebview.ts +++ b/core/protocol/coreWebview.ts @@ -5,7 +5,10 @@ import { ToWebviewFromIdeOrCoreProtocol } from "./webview.js"; export type ToCoreFromWebviewProtocol = ToCoreFromIdeOrWebviewProtocol & { didChangeSelectedProfile: [{ id: string | null }, void]; - didChangeSelectedOrg: [{ id: string | null }, void]; + didChangeSelectedOrg: [ + { id: string | null; profileId?: string | null }, + void, + ]; }; export type ToWebviewFromCoreProtocol = ToWebviewFromIdeOrCoreProtocol & { didChangeAvailableProfiles: [ diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 3598e06ea..a7cd16e5b 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -49,11 +49,11 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { acceptDiff: [{ filepath: string; streamId?: string }, void]; rejectDiff: [{ filepath: string; streamId?: string }, void]; "edit/sendPrompt": [ - { prompt: MessageContent; range: RangeInFileWithContents }, - void, - ]; - "edit/acceptReject": [ - { accept: boolean; onlyFirst: boolean; filepath: string }, + { + prompt: MessageContent; + range: RangeInFileWithContents; + selectedModelTitle: string; + }, void, ]; "edit/exit": [{ shouldFocusEditor: boolean }, void]; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index f0c66f465..ef71c66a1 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -22,8 +22,10 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "config/getSerializedProfileInfo", "config/deleteModel", "config/listProfiles", + "config/refreshProfiles", "config/openProfile", "config/updateSharedConfig", + "config/updateSelectedModel", "context/getContextItems", "context/getSymbolsForFiles", "context/loadSubmenuItems", diff --git a/core/test/testDir.ts b/core/test/testDir.ts index 9b0473b46..0e34f509b 100644 --- a/core/test/testDir.ts +++ b/core/test/testDir.ts @@ -1,7 +1,7 @@ import fs from "fs"; import os from "os"; import path from "path"; -import { localPathToUri, localPathOrUriToPath } from "../util/pathToUri"; +import { localPathOrUriToPath, localPathToUri } from "../util/pathToUri"; // Want this outside of the git repository so we can change branches in tests export const TEST_DIR_PATH = path.join(os.tmpdir(), "testWorkspaceDir"); @@ -26,7 +26,7 @@ export function tearDownTestDir() { "index/index.ts" creates an empty index/index.ts ["index/index.ts", "hello"] creates index/index.ts with contents "hello" */ -export function addToTestDir(pathsOrUris: (string | string[])[]) { +export function addToTestDir(pathsOrUris: (string | [string, string])[]) { // Allow tests to use URIs or local paths const paths = pathsOrUris.map((val) => { if (Array.isArray(val)) { diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts index f3b565285..959752af1 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -1,5 +1,6 @@ import { ContextItem, Tool, ToolExtras } from ".."; import { MCPManagerSingleton } from "../context/mcp"; +import { canParseUrl } from "../util/url"; import { BuiltInToolNames } from "./builtIn"; import { createNewFileImpl } from "./implementations/createNewFile"; @@ -55,9 +56,8 @@ async function callToolFromUri( args: any, extras: ToolExtras, ): Promise { - // @ts-ignore - const canParse = URL.canParse(uri); - if (!canParse) { + const parseable = canParseUrl(uri); + if (!parseable) { throw new Error(`Invalid URI: ${uri}`); } const parsedUri = new URL(uri); diff --git a/core/util/GlobalContext.test.ts b/core/util/GlobalContext.test.ts index 0d6b9d799..b13f3b87b 100644 --- a/core/util/GlobalContext.test.ts +++ b/core/util/GlobalContext.test.ts @@ -29,12 +29,6 @@ describe("GlobalContext", () => { expect(value).toBe(true); }); - it("should update and get a string value correctly", () => { - globalContext.update("selectedTabAutocompleteModel", "test-model"); - const value = globalContext.get("selectedTabAutocompleteModel"); - expect(value).toBe("test-model"); - }); - it("should update and get an object value correctly", () => { const workspaceIdentifier = "workspace-1"; globalContext.update("lastSelectedProfileForWorkspace", { @@ -108,13 +102,9 @@ describe("GlobalContext", () => { it("should update and retrieve multiple values correctly", () => { globalContext.update("indexingPaused", true); - globalContext.update("selectedTabAutocompleteModel", "test-model"); globalContext.update("hasDismissedConfigTsNoticeJetBrains", false); expect(globalContext.get("indexingPaused")).toBe(true); - expect(globalContext.get("selectedTabAutocompleteModel")).toBe( - "test-model", - ); expect(globalContext.get("hasDismissedConfigTsNoticeJetBrains")).toBe( false, ); diff --git a/core/util/GlobalContext.ts b/core/util/GlobalContext.ts index 34c3d8ddf..640bf7a56 100644 --- a/core/util/GlobalContext.ts +++ b/core/util/GlobalContext.ts @@ -1,5 +1,8 @@ import fs from "node:fs"; +import { ModelRole } from "@continuedev/config-yaml"; + +import { SiteIndexingConfig } from ".."; import { salvageSharedConfig, sharedConfigSchema, @@ -7,17 +10,22 @@ import { } from "../config/sharedConfig"; import { getGlobalContextFilePath } from "./paths"; -import { SiteIndexingConfig } from ".."; + +export type GlobalContextModelSelections = Partial< + Record +>; export type GlobalContextType = { indexingPaused: boolean; - selectedTabAutocompleteModel: string; lastSelectedProfileForWorkspace: { [workspaceIdentifier: string]: string | null; }; lastSelectedOrgIdForWorkspace: { [workspaceIdentifier: string]: string | null; }; + selectedModelsByProfileId: { + [profileId: string]: GlobalContextModelSelections; + }; /** * This is needed to handle the case where a JetBrains user has created @@ -28,7 +36,7 @@ export type GlobalContextType = { hasDismissedConfigTsNoticeJetBrains: boolean; hasAlreadyCreatedAPromptFile: boolean; showConfigUpdateToast: boolean; - isSupportedLanceDbCpuTarget: boolean; + isSupportedLanceDbCpuTargetForLinux: boolean; sharedConfig: SharedConfigSchema; failedDocs: SiteIndexingConfig[]; }; @@ -113,4 +121,23 @@ export class GlobalContext { this.update("sharedConfig", updatedSharedConfig); return updatedSharedConfig; } + + updateSelectedModel( + profileId: string, + role: ModelRole, + title: string | null, + ): GlobalContextModelSelections { + const currentSelections = this.get("selectedModelsByProfileId") ?? {}; + const forProfile = currentSelections[profileId] ?? {}; + const newSelections = { + ...forProfile, + [role]: title, + }; + + this.update("selectedModelsByProfileId", { + ...currentSelections, + [profileId]: newSelections, + }); + return newSelections; + } } diff --git a/core/util/devdata.ts b/core/util/devdata.ts deleted file mode 100644 index 3f786fa84..000000000 --- a/core/util/devdata.ts +++ /dev/null @@ -1,9 +0,0 @@ -import fs from "fs"; - -import { getDevDataFilePath } from "./paths.js"; - -export function logDevData(tableName: string, data: any) { - const filepath: string = getDevDataFilePath(tableName); - const jsonLine = JSON.stringify(data); - fs.writeFileSync(filepath, `${jsonLine}\n`, { flag: "a" }); -} diff --git a/core/util/paths.ts b/core/util/paths.ts index a8861befa..31ed8bb02 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -5,6 +5,7 @@ import * as path from "path"; import * as JSONC from "comment-json"; import dotenv from "dotenv"; +import { DevEventName } from "@continuedev/config-yaml"; import { IdeType, SerializedContinueConfig } from "../"; import { defaultConfig, defaultConfigJetBrains } from "../config/default"; import Types from "../config/types"; @@ -202,7 +203,7 @@ export function getContinueRcPath(): string { return continuercPath; } -export function devDataPath(): string { +function getDevDataPath(): string { const sPath = path.join(getContinueGlobalPath(), "dev_data"); if (!fs.existsSync(sPath)) { fs.mkdirSync(sPath); @@ -211,11 +212,18 @@ export function devDataPath(): string { } export function getDevDataSqlitePath(): string { - return path.join(devDataPath(), "devdata.sqlite"); + return path.join(getDevDataPath(), "devdata.sqlite"); } -export function getDevDataFilePath(fileName: string): string { - return path.join(devDataPath(), `${fileName}.jsonl`); +export function getDevDataFilePath( + eventName: DevEventName, + schema: string, +): string { + const versionPath = path.join(getDevDataPath(), schema); + if (!fs.existsSync(versionPath)) { + fs.mkdirSync(versionPath); + } + return path.join(versionPath, `${String(eventName)}.jsonl`); } export function editConfigJson( @@ -360,7 +368,7 @@ export function readAllGlobalPromptFiles( if (stats.isDirectory()) { const nestedPromptFiles = readAllGlobalPromptFiles(filepath); promptFiles.push(...nestedPromptFiles); - } else { + } else if (file.endsWith(".prompt")) { const content = fs.readFileSync(filepath, "utf8"); promptFiles.push({ path: filepath, content }); } @@ -377,23 +385,29 @@ export function getEsbuildBinaryPath(): string { return path.join(getContinueUtilsPath(), "esbuild"); } -export function getStagingEnvironmentDotFilePath(): string { - return path.join(getContinueGlobalPath(), ".staging"); +export function migrateV1DevDataFiles() { + const devDataPath = getDevDataPath(); + function moveToV1FolderIfExists( + oldFileName: string, + newFileName: DevEventName, + ) { + const oldFilePath = path.join(devDataPath, `${oldFileName}.jsonl`); + if (fs.existsSync(oldFilePath)) { + const newFilePath = getDevDataFilePath(newFileName, "0.1.0"); + if (!fs.existsSync(newFilePath)) { + fs.copyFileSync(oldFilePath, newFilePath); + fs.unlinkSync(oldFilePath); + } + } + } + moveToV1FolderIfExists("tokens_generated", "tokensGenerated"); + moveToV1FolderIfExists("chat", "chatFeedback"); + moveToV1FolderIfExists("quickEdit", "quickEdit"); + moveToV1FolderIfExists("autocomplete", "autocomplete"); } -export function setupInitialDotContinueDirectory() { - const devDataTypes = [ - "chat", - "autocomplete", - "quickEdit", - "tokens_generated", - ]; - devDataTypes.forEach((p) => { - const devDataPath = getDevDataFilePath(p); - if (!fs.existsSync(devDataPath)) { - fs.writeFileSync(devDataPath, ""); - } - }); +export function getStagingEnvironmentDotFilePath(): string { + return path.join(getContinueGlobalPath(), ".staging"); } export function getDiffsDirectoryPath(): string { diff --git a/core/util/uri.ts b/core/util/uri.ts index 13d7956ac..e180a0a69 100644 --- a/core/util/uri.ts +++ b/core/util/uri.ts @@ -116,19 +116,23 @@ export function getLastNUriRelativePathParts( } export function joinPathsToUri(uri: string, ...pathSegments: string[]) { - const components = URI.parse(uri); + let baseUri = uri; + if (baseUri.at(-1) !== "/") { + baseUri += "/"; + } const segments = pathSegments.map((segment) => pathToUriPathSegment(segment)); - components.path = `${components.path}/${segments.join("/")}`; - return URI.serialize(components); + return URI.resolve(baseUri, segments.join("/")); } export function joinEncodedUriPathSegmentToUri( uri: string, pathSegment: string, ) { - const components = URI.parse(uri); - components.path = `${components.path}/${pathSegment}`; - return URI.serialize(components); + let baseUri = uri; + if (baseUri.at(-1) !== "/") { + baseUri += "/"; + } + return URI.resolve(baseUri, pathSegment); } export function getShortestUniqueRelativeUriPaths( diff --git a/core/util/url.ts b/core/util/url.ts new file mode 100644 index 000000000..83e0edcba --- /dev/null +++ b/core/util/url.ts @@ -0,0 +1,11 @@ +export function canParseUrl(url: string): boolean { + if ((URL as any)?.canParse) { + return (URL as any).canParse(url); + } + try { + new URL(url); + return true; + } catch (e) { + return false; + } +} diff --git a/docs/docs/actions/context-selection.md b/docs/docs/actions/context-selection.md index 4e154dcd3..90bc7c0d2 100644 --- a/docs/docs/actions/context-selection.md +++ b/docs/docs/actions/context-selection.md @@ -9,10 +9,6 @@ sidebar_position: 3 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. - -Some slash commands will not acknowledge your input; for example, the “/share” slash command just creates a markdown copy of the current conversation, regardless of what else you may request it to do. - ## Quick actions Quick actions are always displayed above a class or function and will edit that class or function, but nothing outside of it. diff --git a/docs/docs/actions/how-it-works.mdx b/docs/docs/actions/how-it-works.mdx index 90bd4bb20..afacc3dbe 100644 --- a/docs/docs/actions/how-it-works.mdx +++ 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). +Right click actions that generate inline diffs, 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.mdx). diff --git a/docs/docs/actions/how-to-customize.md b/docs/docs/actions/how-to-customize.md index 9153a38b0..2f13e4f1a 100644 --- a/docs/docs/actions/how-to-customize.md +++ b/docs/docs/actions/how-to-customize.md @@ -5,49 +5,6 @@ keywords: [customize, actions] sidebar_position: 5 --- -## Built-in slash commands +The easiest way to add actions is by adding [`prompt` blocks](../hub/blocks/block-types.md#prompts) to your assistant, which show up as slash commands in [Chat](../chat/how-it-works.md). -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 - -There are two ways to add custom slash commands: - -1. With `.prompt` files - this is recommended in most cases. See the full reference [here](../customize/deep-dives/prompt-files.md). -2. With `config.ts` - this gives you full programmatic access to the LLM, IDE, and other important entities by writing a JavaScript/TypeScript function - -### 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: - -```typescript title="config.ts" -export function modifyConfig(config: Config): Config { - config.slashCommands?.push({ - name: "commit", - description: "Write a commit message", - run: async function* (sdk) { - // The getDiff function takes a boolean parameter that indicates whether - // to include unstaged changes in the diff or not. - const diff = await sdk.ide.getDiff(false); // Pass false to exclude unstaged changes - for await (const message of sdk.llm.streamComplete( - `${diff}\n\nWrite a commit message for the above changes. Use no more than 20 tokens to give a brief description in the imperative mood (e.g. 'Add feature' not 'Added feature'):`, - new AbortController().signal, - { - maxTokens: 20, - }, - )) { - yield message; - } - }, - }); - return 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. - - +Check out the [slash commands deep dive](../customize/slash-commands.mdx) for more information on extending actions. diff --git a/docs/docs/actions/how-to-use-it.md b/docs/docs/actions/how-to-use-it.md index 018a7c941..d69ec3851 100644 --- a/docs/docs/actions/how-to-use-it.md +++ b/docs/docs/actions/how-to-use-it.md @@ -14,43 +14,23 @@ Actions are shortcuts for common use cases. For example, you might want to revie ### Slash commands -The most common way to invoke an action is with a slash command. These are shortcuts that can be activated by typing '/' in a chat session (press cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains)), and selecting from the dropdown. For example, the built-in '/edit' slash command lets you stream edits directly into your editor. +The most common way to invoke an action is with a slash command. These are shortcuts that can be activated by typing '/' in a chat session (press cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains)), and selecting from the dropdown. ![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.mdx). +In YAML assistants, slash commands are generated from [`prompts` blocks](../hub/blocks/block-types.md#prompts). + +Learn more about slash commands [here](../customize/slash-commands.mdx). + +:::info +Important: For assistants, slash commands only come from `prompts` blocks. When using older `config.json` configuration, other slash commands like `/share` and `/cmd` are included by default. +::: ### Prompt files It is also possible to write your own slash command by defining a “.prompt file.” Prompt files can be as simple as a text file, but also include templating so that you can refer to files, URLs, highlighted code, and more. -The full .prompt file reference can be found [here](../customize/deep-dives/prompt-files.md). - -:::tip[Prompt library] -To assist you in getting started, [we've curated a small library of `.prompt` files](https://github.com/continuedev/prompt-file-examples). We encourage community contributions to this repository, so please consider opening up a pull request with your own prompts! -::: - -Below is a quick example of setting up a prompt file to write unit tests using Jest. - -1. Create a folder called `.prompts/` at the top level of your workspace. -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: -- Use `jest` -- Properly set up and tear down -- Include important edge cases -- The tests should be complete and sophisticated -- Give the tests just as chat output, don't edit any file -- Don't explain how to set up `jest` -``` - -Now to use this prompt, you can highlight code and use cmd/ctrl + L to select it in the Continue sidebar. - -Then, type "/" to see the list of slash commands and choose the one called "test". Press enter and the LLM will respond given the instructions from your prompt file. +Learn more about prompt files [here](../customize/deep-dives/prompt-files.md) ### Other triggers for Actions (VS Code) diff --git a/docs/docs/actions/model-setup.md b/docs/docs/actions/model-setup.md index 7dd9a0213..91912dcbf 100644 --- a/docs/docs/actions/model-setup.md +++ b/docs/docs/actions/model-setup.md @@ -5,4 +5,6 @@ keywords: [model] sidebar_position: 2 --- -By default, Actions uses the same model as [Chat](chat/model-setup.mdx) since we recommend a similar, 400B+ parameter model or one of the frontier models for the complex instructions that will be carried out. +By default, Actions uses the same model as [Chat](chat/model-setup.mdx), since we recommend a similar, 400B+ parameter model or one of the frontier models for the complex instructions that will be carried out. + +You can also set specific models to be used for Edit and Apply actions. See the [Model roles](../customize/model-roles/intro.mdx) page for more details. diff --git a/docs/docs/autocomplete/how-to-customize.md b/docs/docs/autocomplete/how-to-customize.md index abf4c5b11..db77a43f0 100644 --- a/docs/docs/autocomplete/how-to-customize.md +++ b/docs/docs/autocomplete/how-to-customize.md @@ -5,20 +5,6 @@ keywords: [customize] sidebar_position: 5 --- -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" - } -} -``` - -- `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"). +Continue offers a handful of settings to customize autocomplete behavior. For the most part, these options can be found in the [User Settings Page](../customize/settings.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/how-to-use-it.md b/docs/docs/autocomplete/how-to-use-it.md index 5fd127ce5..b9b3c19d2 100644 --- a/docs/docs/autocomplete/how-to-use-it.md +++ b/docs/docs/autocomplete/how-to-use-it.md @@ -2,7 +2,7 @@ title: Autocomplete description: Autocomplete \- how to use it sidebar_label: How to use it -keywords: [how] +keywords: [autocomplete] sidebar_position: 1 --- diff --git a/docs/docs/autocomplete/model-setup.mdx b/docs/docs/autocomplete/model-setup.mdx index 8d37d39be..aa05e3c31 100644 --- a/docs/docs/autocomplete/model-setup.mdx +++ b/docs/docs/autocomplete/model-setup.mdx @@ -5,111 +5,13 @@ keywords: [model, autocomplete] sidebar_position: 2 --- -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; -:::info -This page recommends models and providers for Autocomplete. Read more about how to set up your `config.yaml` [here](../reference.md). -::: +For the best autocomplete experience we recommend Codestral from Mistral. -## Best overall experience +Add Codestral to your assistant from the hub [here](https://hub.continue.dev/mistral/codestral). Visit the [Mistral Platform](https://console.mistral.ai/codestral) to get a Codestral API key. -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: +For a fully local autocomplete experience, we recommend [Qwen 2.5 Coder 1.5B on Ollama](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b). - - - ```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) +For more details about setup and recommended models, visit the [autocomplete deep dive](../customize/deep-dives/autocomplete.mdx). diff --git a/docs/docs/chat/context-selection.md b/docs/docs/chat/context-selection.md index 65b76c72a..ee427cf0a 100644 --- a/docs/docs/chat/context-selection.md +++ b/docs/docs/chat/context-selection.md @@ -43,4 +43,4 @@ You can include all of the changes you've made to your current branch by typing ## Other context -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). +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.mdx). diff --git a/docs/docs/chat/how-to-customize.md b/docs/docs/chat/how-to-customize.md index 3fcb7376f..acb357983 100644 --- a/docs/docs/chat/how-to-customize.md +++ b/docs/docs/chat/how-to-customize.md @@ -5,11 +5,11 @@ keywords: [customize, chat] sidebar_position: 5 --- -There are a number of different ways to customize Chat +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 add a [`rules` block](../hub/blocks/block-types.md#rules) to your assistant to give the model persistent instructions through the system prompt. See the [rules deep dive](../customize/deep-dives/rules.md) for more information. - 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.mdx) +- You can [build your own context provider](../customize/tutorials/build-your-own-context-provider.mdx) +- You can create your own [custom code RAG](../customize/tutorials/custom-code-rag.mdx) diff --git a/docs/docs/chat/model-setup.mdx b/docs/docs/chat/model-setup.mdx index 52dac63a2..8608f5e1d 100644 --- a/docs/docs/chat/model-setup.mdx +++ b/docs/docs/chat/model-setup.mdx @@ -5,359 +5,20 @@ keywords: [model] sidebar_position: 2 --- -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; -:::info -This page recommends models and providers for Chat. Read more about how to set up your config [here](../reference.md). -::: +For the best chat experience we recommend Claude 3.7 Sonnet from Anthropic. -## Best overall experience +Add Claude 3.7 Sonnet to your assistant from the hub [here](https://hub.continue.dev/anthropic/claude-3-7-sonnet). You can get an API key from the [Anthropic console](https://console.anthropic.com/settings/keys). -For the best overall Chat experience, you will want to use a 400B+ parameter model or one of the frontier models. +Other recommended chat models include: -### Claude Sonnet 3.5 from Anthropic +- [GPT-4o from OpenAI](https://hub.continue.dev/openai/gpt-4o) +- [Grok-2 from xAI](https://hub.continue.dev/xai/grok-2) +- [Gemini 2.0 Flash from Google](https://hub.continue.dev/google/gemini-2.0-flash) +- [Llama 3.1 8b from Meta on Ollama](https://hub.continue.dev/ollama/llama3.1-8b) for a fully local experience + {/* HUB_TODO nonexistent blocks */} + {/* - Deepseek Coder 2 from deepseek on [Ollama](https://hub.continue.dev/explore/models) or [LM Studio](https://hub.continue.dev/explore/models) */} -Our current top recommendation is Claude Sonnet 3.5 from [Anthropic](../customize/model-providers/top-level/anthropic.mdx). - - - - ```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.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)). - - - - - - ```yaml title="Package or config.yaml" - models: - - name: "Llama 3.1 405B" - provider: "together" - model: "llama3.1-405b" - apiKey: - ``` - - - ```yaml title="Package or config.yaml" - models: - - name: "Llama 3.1 405B" - provider: "groq" - model: "llama3.1-405b" - apiKey: - ``` - - - ```yaml title="Package or config.yaml" - models: - - name: "Llama 3.1 405B" - provider: "vllm" - 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.mdx), then we recommend GPT-4o. - - - - ```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.mdx), then we recommend Grok-2. - - - - ```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.mdx), then we recommend Gemini 1.5 Pro. - - - - ```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 - -For the best local, offline Chat experience, you will want to use a model that is large but fast enough on your machine. - -### 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.mdx) or [LM Studio](../customize/model-providers/more/lmstudio.mdx)). - - - - - - ```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.mdx) or [LM Studio](../customize/model-providers/more/lmstudio.mdx)). - - - - - - ```yaml title="Package or config.yaml" - models: - - name: DeepSeek Coder 2 16B - provider: ollama - 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 - -There are many more models and providers you can use with Chat beyond those mentioned above. Read more [here](../customize/model-types/chat.md) +For more details about setup and recommended models, see [here](../customize/model-roles/chat.mdx). diff --git a/docs/docs/customize/context-providers.mdx b/docs/docs/customize/context-providers.mdx index fe64a473f..41c6edc57 100644 --- a/docs/docs/customize/context-providers.mdx +++ b/docs/docs/customize/context-providers.mdx @@ -4,8 +4,8 @@ description: Type '@' to select content to the LLM as context keywords: [context, "@", provider, LLM] --- -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; 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. @@ -13,6 +13,10 @@ As an example, say you are working on solving a new GitHub Issue. You type '@Iss ![Context Items](/img/context-provider-example.png) +## Context blocks + +You can add context providers to assistants using [`context` blocks](../hub/blocks/block-types.md#context). Explore available context blocks in [the hub](https://hub.continue.dev/explore/context). + ## Built-in Context Providers You can add any built-in context-providers in your config file as shown below: @@ -23,7 +27,7 @@ Reference any file in your current workspace. - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" context: - provider: file ``` @@ -47,7 +51,7 @@ Reference specific functions or classes from throughout your project. - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" context: - provider: code ``` @@ -71,7 +75,7 @@ Reference all of the changes you've made to your current branch. This is useful - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" context: - provider: diff ``` @@ -95,7 +99,7 @@ Reference the currently open file. - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" context: - provider: currentFile ``` @@ -119,7 +123,7 @@ Reference the last command you ran in your IDE's terminal and its output. - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" context: - provider: terminal ``` @@ -143,7 +147,7 @@ Reference the contents from any documentation site. - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" context: - provider: docs ``` @@ -171,7 +175,7 @@ Reference the contents of all of your open files. Set `onlyPinned` to `true` to - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" context: - provider: open params: @@ -202,7 +206,7 @@ Optionally, set `n` to limit the number of results returned (default 6). - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" context: - provider: web params: @@ -231,7 +235,7 @@ Reference the most relevant snippets from your codebase. - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" context: - provider: codebase ``` @@ -257,7 +261,7 @@ Uses the same retrieval mechanism as `@Codebase`, but only on a single folder. - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" context: - provider: folder ``` @@ -281,7 +285,7 @@ Reference the results of codebase search, just like the results you would get fr - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" context: - provider: search ``` @@ -307,7 +311,7 @@ Reference the markdown converted contents of a given URL. - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" context: - provider: url ``` @@ -331,7 +335,7 @@ Reference recent clipboard items - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" context: - provider: clipboard ``` @@ -355,7 +359,7 @@ Reference the structure of your current workspace. - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" context: - provider: tree ``` @@ -379,7 +383,7 @@ Get Problems from the current file. - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" context: - provider: problems ``` @@ -403,7 +407,7 @@ Reference the contents of the local variables in the debugger. Currently only av - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" context: - provider: debugger params: @@ -436,7 +440,7 @@ Reference the outline of your codebase. By default, signatures are included alon - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" context: - provider: repo-map params: @@ -471,7 +475,7 @@ Reference the architecture and platform of your current operating system. - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" context: - provider: os ``` @@ -495,7 +499,7 @@ The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" mcpServers: - name: My MCP Server command: uvx @@ -536,7 +540,7 @@ Reference the conversation in a GitHub issue. - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" context: - provider: issue params: @@ -576,7 +580,7 @@ Reference table schemas from Sqlite, Postgres, MSSQL, and MySQL databases. - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" context: - provider: database params: @@ -661,7 +665,7 @@ Reference the schema of a table, and some sample rows - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" context: - provider: postgres params: @@ -708,7 +712,7 @@ Reference the results of a Google search. - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" context: - provider: google params: @@ -741,7 +745,7 @@ Reference an open MR for this branch on GitLab. - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" context: - provider: gitlab-mr params: @@ -772,7 +776,7 @@ You can specify the domain to communicate with by setting the `domain` parameter - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" context: - provider: gitlab-mr params: @@ -807,7 +811,7 @@ Reference the conversation in a Jira issue. - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" context: - provider: jira params: @@ -842,7 +846,7 @@ to set the API Version to 2 using the `apiVersion` property. - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" context: - provider: jira params: @@ -881,7 +885,7 @@ Reference the messages in a Discord channel. - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" context: - provider: discord params: @@ -929,7 +933,7 @@ The HttpContextProvider makes a POST request to the url passed in the configurat - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" context: - provider: http params: @@ -986,7 +990,7 @@ Reference specific git commit metadata and diff or all of the recent commits. - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" context: - provider: commit params: @@ -1020,7 +1024,7 @@ Query a [Greptile](https://www.greptile.com/) index of the current repo/branch. - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" context: - provider: greptile params: diff --git a/docs/docs/customize/deep-dives/autocomplete.mdx b/docs/docs/customize/deep-dives/autocomplete.mdx index 6713e4653..c350b4d2c 100644 --- a/docs/docs/customize/deep-dives/autocomplete.mdx +++ b/docs/docs/customize/deep-dives/autocomplete.mdx @@ -3,14 +3,17 @@ title: Autocomplete keywords: [autocomplete] --- -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; ### 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: - + + + [Mistral Codestral model block](https://hub.continue.dev/mistral/codestral) + ```yaml title="config.yaml" models: @@ -36,28 +39,30 @@ If you want to have the best autocomplete experience, we recommend using Codestr +:::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`. +::: + ### Setting up with Ollama (default) If you'd like to run your autocomplete model locally, we recommend using Ollama. To do this, first download the latest version of Ollama from [here](https://ollama.ai). Then, run the following command to download our recommended model: ```bash -ollama run qwen2.5-coder:1.5b-base +ollama run qwen2.5-coder:1.5b ``` -Once it has been downloaded, you should begin to see completions in VS Code. +Then, add the model to your configuration: -### Setting up a custom model - -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): - - + + + [Ollama Qwen 2.5 Coder 1.5B model block](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b) + ```yaml title="config.yaml" models: - - name: Tab Autocomplete Model + - name: Qwen 1.5b Autocomplete Model provider: ollama - model: qwen2.5-coder:1.5b-base - apiBase: https:// + model: qwen2.5-coder:1.5b roles: - autocomplete ``` @@ -66,72 +71,34 @@ All of the configuration options available for chat models are available to use ```json title="config.json" { "tabAutocompleteModel": { - "title": "Tab Autocomplete Model", + "title": "Qwen 1.5b Autocomplete Model", "provider": "ollama", - "model": "qwen2.5-coder:1.5b-base", - "apiBase": "https://" + "model": "qwen2.5-coder:1.5b", } } ``` -If you aren't yet familiar with the available options, you can find the full reference [here](./configuration.md). +Once the model has been downloaded, you should begin to see completions in VS Code. ## Configuration Options -The following can be configured in `config.json`: +### Hub Autocomplete models -### `tabAutocompleteModel` +Explore autocomplete model configurations on [the hub](https://hub.continue.dev/explore/models?roles=autocomplete) -This is just another object like the ones in the `"models"` array of `config.json`. You can choose and configure any model you would like, but we strongly suggest using a small model made for tab-autocomplete, such as `deepseek-1b`, `qwen2.5-coder:1.5b`, or `starcoder2-3b`. +### Autocomplete User Settings -### `tabAutocompleteOptions` +The following settings can be configured for autocompletion in the IDE extension [User Settings Page](../settings.md): -This object allows you to customize the behavior of tab-autocomplete. The available options are shown below, and you can find their default values [here](https://github.com/continuedev/continue/blob/fbeb2e4fe15d4b434a30a136f74b672485c852d9/core/util/parameters.ts). +- `Use autocomplete cache`: If on, caches completions +- `Multiline Autocompletions`: Controls multiline completions for autocomplete. Can be set to `always`, `never`, or `auto`. Defaults to `auto` +- `Disable autocomplete in files`: List of comma-separated glob pattern to disable autocomplete in matching files. E.g., "\_/.md, \*/.txt" -- `disable`: Disable autocomplete (can also be done from IDE settings) (default: `false`) -- `template`: An optional template string to be used for autocomplete. It will be rendered with the Mustache templating language, and is passed the 'prefix' and 'suffix' variables. (String) -- `maxPromptTokens`: The maximum number of prompt tokens to use. A smaller number will yield faster completions, but less context. (Number) (default: `1024`) -- `prefixPercentage`: The percentage of the input that should be dedicated to the prefix. (Number) (default: `0.3`) -- `maxSuffixPercentage`: The maximum percentage of the prompt that can be dedicated to the suffix. (Number) (default: `0.2`) -- `debounceDelay`: The delay in milliseconds before triggering autocomplete after a keystroke. (Number) (default: `350`) -- `multilineCompletions`: Whether to enable multiline completions ("always", "never", or "auto"). Defaults to "auto". (default: `auto`) -- `useCache`: Whether to cache and reuse completions when the prompt is the same as a previous one. May be useful to disable for testing purposes. (default: `true`) -- `disableInFiles`: A list of glob patterns for files in which you want to disable tab autocomplete. (default: `[]`) +### `config.json` Configuration -### Full example - - - - ```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"] - } - } - ``` - - +The `config.json` configuration format (deprecated) offers further configuration options through `tabAutocompleteOptions`. See the [JSON Reference](../../reference.md#tabautocompleteoptions) for more details. ## FAQs @@ -145,7 +112,7 @@ Follow these steps to ensure that everything is set up correctly: 1. Make sure you have the "Enable Tab Autocomplete" setting checked (in VS Code, you can toggle by clicking the "Continue" button in the status bar, and in JetBrains by going to Settings -> Tools -> Continue). 2. Make sure you have downloaded Ollama. -3. Run `ollama run qwen2.5-coder:1.5b-base` to verify that the model is downloaded. +3. Run `ollama run qwen2.5-coder:1.5b` to verify that the model is downloaded. 4. Make sure that any other completion providers are disabled (e.g. Copilot), as they may interfere. 5. Check the output of the logs to find any potential errors: cmd/ctrl + shift + P -> "Toggle Developer Tools" -> "Console" tab in VS Code, ~/.continue/logs/core.log in JetBrains. 6. Check VS Code settings to make sure that `"editor.inlineSuggest.enabled"` is set to `true` (use cmd/ctrl + , then search for this and check the box) diff --git a/docs/docs/customize/deep-dives/codebase.mdx b/docs/docs/customize/deep-dives/codebase.mdx index acf19c4fc..24256672e 100644 --- a/docs/docs/customize/deep-dives/codebase.mdx +++ b/docs/docs/customize/deep-dives/codebase.mdx @@ -3,15 +3,15 @@ description: Talk to your codebase keywords: [talk, embeddings, reranker, codebase, experimental] --- -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; # @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.mdx). +Currently, `transformers.js` cannot be used in JetBrains IDEs. However, you can select a differet embeddings model from [the list here](../model-roles/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. @@ -45,7 +45,7 @@ There are a few options that let you configure the behavior of the `@codebase` c - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" context: - provider: codebase params: diff --git a/docs/docs/customize/deep-dives/configuration.md b/docs/docs/customize/deep-dives/configuration.md index c87ebfb1b..5cd0ebf24 100644 --- a/docs/docs/customize/deep-dives/configuration.md +++ b/docs/docs/customize/deep-dives/configuration.md @@ -18,7 +18,7 @@ To open your configuration file, you can click the "gear" icon in the bottom rig When you save a config file from the IDE, Continue will automatically refresh to take into account your changes. A config file is automatically created the first time you use Continue, and always automatically generated with default values if it doesn't exist. -See the full reference for `config.yaml` [here](../../reference.md). +See the full reference for `config.yaml` [here](../../yaml-reference.md). ## Deprecated configuration methods @@ -26,7 +26,7 @@ See the full reference for `config.yaml` [here](../../reference.md). View the `config.json` migration guide [here](../../yaml-migration.md) ::: -- [`config.json`](../../json-reference.md) - The original configuration format which is stored in a file at the same location as `config.yaml` +- [`config.json`](../../reference.md) - The original configuration format which is stored in a file at the same location as `config.yaml` - [`.continuerc.json`](#continuercjson) - Workspace-level configuration - [`config.ts`](#configts) - Advanced configuration (probably unnecessary) - a TypeScript file in your home directory that can be used to programmatically modify (_merged_) the `config.json` schema: - `~/.continue/config.ts` (MacOS / Linux) diff --git a/docs/docs/customize/deep-dives/development-data.md b/docs/docs/customize/deep-dives/development-data.md new file mode 100644 index 000000000..da9f5136c --- /dev/null +++ b/docs/docs/customize/deep-dives/development-data.md @@ -0,0 +1,21 @@ +--- +title: Development Data +description: Collecting data on how you build software +keywords: [development data, dev data, LLM-aided development] +--- + +# Development Data + +When you use Continue, you automatically collect data on how you build software. By default, this development data is saved to `.continue/dev_data` on your local machine. + +You can read more about how development data is generated as a byproduct of LLM-aided development and why we believe that you should start collecting it now: [It’s time to collect data on how you build software](https://blog.continue.dev/its-time-to-collect-data-on-how-you-build-software) + +## Custom Data Destinations + +You can also configure custom destinations for your data, including remote HTTP endpoints and local file directories. + +For hub assistants, data destinations are configured in `data` blocks. Visit the hub to [explore example data blocks](https://hub.continue.dev/explore/data) or [create your own](https://hub.continue.dev/new?type=block&blockType=data). + +See more details about adding `data` blocks to your configuration files in the [YAML specification](../../yaml-reference.md#data) + +When sending development data to your own HTTP endpoint, it will receive an event JSON blob at the given `schema` version. You can view event names, schema versions, and fields [here in the source code](https://github.com/continuedev/continue/tree/main/packages/config-yaml/src/schemas/data). diff --git a/docs/docs/customize/deep-dives/docs.mdx b/docs/docs/customize/deep-dives/docs.mdx index e48bac259..4a2aac376 100644 --- a/docs/docs/customize/deep-dives/docs.mdx +++ b/docs/docs/customize/deep-dives/docs.mdx @@ -14,8 +14,8 @@ keywords: toc_max_heading_level: 5 --- -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; # @Docs @@ -62,6 +62,10 @@ Pre-indexed docs are only available in VS Code because the VS Code extension shi ## Indexing Your Own Documentation +### Hub `docs` Blocks + +@Docs uses [`docs` blocks](../../hub/blocks/block-types.md#docs) in Assistants from the hub. Visit the hub to [explore `docs` blocks](https://hub.continue.dev/explore/docs) or [create your own](https://hub.continue.dev/new?type=block&blockType=docs). + ### Through the `@Docs` Context Provider To add a single documentation site, we recommend using the **Add Documentation** Form within the GUI. This can be accessed @@ -85,7 +89,7 @@ Documentation sources may be suggested based on package files in your repo. This ![Add documentation form](/img/docs-form.png) -### Through global configuration +### In a configuration file 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: @@ -121,7 +125,7 @@ Indexing will re-sync upon saving the configuration file. ### Using Your Embeddings Provider -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. +If you have set up an [embeddings provider](../model-roles/embeddings.mdx), @docs will use your embeddings provider. Switching embeddings providers will trigger a re-index of all documentation sites in your configuration. ### Reranking @@ -278,7 +282,7 @@ The following configuration example works out of the box for VS Code. This uses ### Jetbrains minimal setup -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. +Here is the equivalent minimal example for Jetbrains, which requires setting up an [embeddings provider](../model-roles/embeddings.mdx). Pre-indexed docs will _not_ be accessible. diff --git a/docs/docs/customize/deep-dives/prompt-files.md b/docs/docs/customize/deep-dives/prompt-files.md index bd4c05db6..f5c834c17 100644 --- a/docs/docs/customize/deep-dives/prompt-files.md +++ b/docs/docs/customize/deep-dives/prompt-files.md @@ -4,13 +4,13 @@ title: Prompt files Prompt files provide a convenient way to standardize common patterns and share a collection of LLM prompts with your team. They make it easy to build and use these prompts. +On the [hub](../../hub/introduction.md), prompt files are stored within [prompt blocks](../../hub/blocks/block-types.md#prompts), which show up as [slash commands](../slash-commands.mdx) in Chat. Visit the hub to [explore prompts](https://hub.continue.dev/explore/prompts) or [create your own](https://hub.continue.dev/new?type=block&blockType=rules). + +Prompt files can also be stored within your project's root directory as `.prompt` files. See below. + ## Quick start - - -Below is a quick example of setting up a prompt file to de +Below is a quick example of setting up a prompt file: 1. Create a folder called `.continue/prompts` at the top level of your workspace (or you can use the button in the UI by typing @, selecting "Prompt Files", and selecting "New Prompt File"). 2. Add a file called `rails.prompt` to this folder. diff --git a/docs/docs/customize/deep-dives/rules.md b/docs/docs/customize/deep-dives/rules.md index ae8347f29..59f816c15 100644 --- a/docs/docs/customize/deep-dives/rules.md +++ b/docs/docs/customize/deep-dives/rules.md @@ -3,11 +3,19 @@ description: Learn how to customize the system prompt with a `.continuerules` fi keywords: [rules, .continuerules, system, prompt, message] --- -# `.continuerules` +# Rules -You can create a project-specific system message by adding a `.continuerules` file to the root of your project. This file is raw text and its contents will be inserted into the system message for all chat requests. Rules are not used for autocomplete. +Rules are used to provide instructions to **chat** models. They are inserted into the system message for all chat requests. Rules are _only_ used during Chat, they are not used for autocomplete or other roles. -## Simple Examples +## Hub `rules` blocks + +Rules can be added to an Assistant on the Continue Hub. Explore available rules [here](https://hub.continue.dev/explore/rules), or [create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub. + +## `.continuerules` + +You can create a project-specific system message by adding a `.continuerules` file to the root of your project. This file is raw text and its full contents will be used as rules. + +### Simple Examples - If you want concise answers: diff --git a/docs/docs/customize/development-data.md b/docs/docs/customize/development-data.md deleted file mode 100644 index 5380eb7e7..000000000 --- a/docs/docs/customize/development-data.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -title: Development data -description: Collecting data on how you build software -keywords: [development data, dev data, LLM-aided development] ---- - -When you use Continue, you automatically collect data on how you build software. By default, this development data is saved to `.continue/dev_data` on your local machine. When combined with the code that you ultimately commit, it can be used to improve the LLM that you or your team use (if you allow). - -You can read more about how development data is generated as a byproduct of LLM-aided development and why we believe that you should start collecting it now: [It’s time to collect data on how you build software](https://blog.continue.dev/its-time-to-collect-data-on-how-you-build-software) diff --git a/docs/docs/customize/model-providers/more/SambaNova.mdx b/docs/docs/customize/model-providers/more/SambaNova.mdx index 86c2e9e0b..3d554006e 100644 --- a/docs/docs/customize/model-providers/more/SambaNova.mdx +++ b/docs/docs/customize/model-providers/more/SambaNova.mdx @@ -1,17 +1,17 @@ -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; # 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. +The SambaNova Cloud is a cloud platform for running large AI models with the world record open source models 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" + ```yaml title="config.yaml" models: - - name: SambaNova Llama 3.1 405B + - name: SambaNova Qwen2.5 coder provider: sambanova - model: llama3.1-405b + model: qwen2.5-coder-32b apiKey: ``` @@ -20,9 +20,9 @@ The SambaNova Cloud is a cloud platform for running large AI models with the wor { "models": [ { - "title": "SambaNova Llama 3.1 405B", + "title": "SambaNova Qwen2.5 coder", "provider": "sambanova", - "model": "llama3.1-405b", + "model": "qwen2.5-coder-32b", "apiKey": "" } ] diff --git a/docs/docs/customize/model-providers/more/asksage.mdx b/docs/docs/customize/model-providers/more/asksage.mdx index f6966a517..675cedc7f 100644 --- a/docs/docs/customize/model-providers/more/asksage.mdx +++ b/docs/docs/customize/model-providers/more/asksage.mdx @@ -1,7 +1,7 @@ # Ask Sage -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; :::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) @@ -13,7 +13,7 @@ To use the Ask Sage models, you can use the following - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: GPT-4 gov provider: askSage diff --git a/docs/docs/customize/model-providers/more/cerebras.mdx b/docs/docs/customize/model-providers/more/cerebras.mdx index a0ffabc8b..838b1d1b9 100644 --- a/docs/docs/customize/model-providers/more/cerebras.mdx +++ b/docs/docs/customize/model-providers/more/cerebras.mdx @@ -1,7 +1,7 @@ # Cerebras Inference -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; Cerebras Inference uses specialized silicon to provides fast inference. @@ -11,7 +11,7 @@ Cerebras Inference uses specialized silicon to provides fast inference. - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Cerebras Llama 3.1 70B provider: cerebras diff --git a/docs/docs/customize/model-providers/more/cloudflare.mdx b/docs/docs/customize/model-providers/more/cloudflare.mdx index fa95f4930..8463d2557 100644 --- a/docs/docs/customize/model-providers/more/cloudflare.mdx +++ b/docs/docs/customize/model-providers/more/cloudflare.mdx @@ -1,5 +1,5 @@ -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; # Cloudflare Workers AI @@ -11,7 +11,6 @@ Cloudflare Workers AI can be used for both chat and tab autocompletion in Contin models: - name: Llama 3 8B provider: cloudflare - accountId: YOUR CLOUDFLARE ACCOUNT ID apiKey: model: "@cf/meta/llama-3-8b-instruct" contextLength: 2400 @@ -19,9 +18,10 @@ Cloudflare Workers AI can be used for both chat and tab autocompletion in Contin maxTokens: 500 roles: - chat + env: + accountId: YOUR CLOUDFLARE ACCOUNT ID - 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 @@ -29,13 +29,16 @@ Cloudflare Workers AI can be used for both chat and tab autocompletion in Contin maxTokens: 500 roles: - chat + env: + accountId: YOUR CLOUDFLARE ACCOUNT ID - name: DeepSeek 7b provider: cloudflare - accountId: YOUR CLOUDFLARE ACCOUNT ID apiKey: model: "@hf/thebloke/deepseek-coder-6.7b-base-awq" roles: - autocomplete + env: + accountId: YOUR CLOUDFLARE ACCOUNT ID ``` diff --git a/docs/docs/customize/model-providers/more/cohere.mdx b/docs/docs/customize/model-providers/more/cohere.mdx index dd7de0321..352908e12 100644 --- a/docs/docs/customize/model-providers/more/cohere.mdx +++ b/docs/docs/customize/model-providers/more/cohere.mdx @@ -1,5 +1,5 @@ -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; # Cohere @@ -11,7 +11,7 @@ We recommend configuring **Command-R Plus** as your chat model. - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Cohere provider: cohere @@ -39,7 +39,7 @@ We recommend configuring **Command-R Plus** as your chat model. Cohere currently does not offer any autocomplete models. -[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers. +[Click here](../../model-roles/autocomplete.md) to see a list of autocomplete model providers. ## Embeddings model diff --git a/docs/docs/customize/model-providers/more/flowise.mdx b/docs/docs/customize/model-providers/more/flowise.mdx index 546e6a716..c0257f851 100644 --- a/docs/docs/customize/model-providers/more/flowise.mdx +++ b/docs/docs/customize/model-providers/more/flowise.mdx @@ -1,5 +1,5 @@ -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; # Flowise @@ -7,7 +7,7 @@ import TabItem from "@theme/TabItem"; - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Flowise provider: flowise diff --git a/docs/docs/customize/model-providers/more/free-trial.mdx b/docs/docs/customize/model-providers/more/free-trial.mdx deleted file mode 100644 index 28d831738..000000000 --- a/docs/docs/customize/model-providers/more/free-trial.mdx +++ /dev/null @@ -1,34 +0,0 @@ ---- -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.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 - -Continue asks free trial users to sign in so that we can prevent abuse of our API endpoints. If you are not using the free trial, we will not ask you to sign in. - -### How do I stop Continue from asking me to sign in? - -Remove all models from the "models" array or "tabAutocompleteModel" with `"provider": "free-trial"`, and we will never request sign in. - -### What information is collected? - -Continue uses your GitHub username and no other information, for the sole purpose of limiting requests. - -### What happens if I don't sign in? - -If you don't sign in, you can still use every feature of Continue, you will just need to provide your own LLM either with an API key or by running a local model. - -### How is telemetry related to sign in? - -It is not. We do not link your GitHub username to telemetry data. diff --git a/docs/docs/customize/model-providers/more/function-network.mdx b/docs/docs/customize/model-providers/more/function-network.mdx index d734fde08..e2089ac1a 100644 --- a/docs/docs/customize/model-providers/more/function-network.mdx +++ b/docs/docs/customize/model-providers/more/function-network.mdx @@ -3,8 +3,8 @@ title: Function Network slug: ../function-network --- -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; # Function Network @@ -22,7 +22,7 @@ Function Network supports a number of models for chat. We recommend using LLama - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Llama 3.1 70b provider: function-network @@ -56,7 +56,7 @@ Function Network supports a number of models for autocomplete. We recommend usin - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Deepseek Coder 6.7b provider: function-network diff --git a/docs/docs/customize/model-providers/more/groq.mdx b/docs/docs/customize/model-providers/more/groq.mdx index 45cfd0a8a..2c33e37f1 100644 --- a/docs/docs/customize/model-providers/more/groq.mdx +++ b/docs/docs/customize/model-providers/more/groq.mdx @@ -1,5 +1,5 @@ -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; # Groq @@ -14,7 +14,7 @@ Groq provides the fastest available inference for open-source language models, i - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Llama 3.3 70b Versatile provider: groq diff --git a/docs/docs/customize/model-providers/more/ipex_llm.mdx b/docs/docs/customize/model-providers/more/ipex_llm.mdx index 02d20f89b..5af95a7cf 100644 --- a/docs/docs/customize/model-providers/more/ipex_llm.mdx +++ b/docs/docs/customize/model-providers/more/ipex_llm.mdx @@ -1,5 +1,5 @@ -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; # IPEX-LLM @@ -11,7 +11,7 @@ IPEX-LLM supports accelerated Ollama backend to be hosted on Intel GPU. Refer to - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: IPEX-LLM provider: ollama @@ -37,7 +37,7 @@ If you would like to reach the Ollama service from another machine, make sure yo - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: IPEX-LLM provider: ollama diff --git a/docs/docs/customize/model-providers/more/kindo.mdx b/docs/docs/customize/model-providers/more/kindo.mdx index e788b7e39..2315fe7a1 100644 --- a/docs/docs/customize/model-providers/more/kindo.mdx +++ b/docs/docs/customize/model-providers/more/kindo.mdx @@ -1,5 +1,5 @@ -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; # Kindo @@ -9,7 +9,7 @@ Kindo offers centralized control over your organization's AI operations, ensurin - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Claude 3.5 Sonnet provider: kindo @@ -37,7 +37,7 @@ Kindo offers centralized control over your organization's AI operations, ensurin - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: WhiteRabbitNeo provider: kindo diff --git a/docs/docs/customize/model-providers/more/llamacpp.mdx b/docs/docs/customize/model-providers/more/llamacpp.mdx index 291ed0a5a..5b210bb6b 100644 --- a/docs/docs/customize/model-providers/more/llamacpp.mdx +++ b/docs/docs/customize/model-providers/more/llamacpp.mdx @@ -1,5 +1,5 @@ -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; # LlamaCpp @@ -13,7 +13,7 @@ After it's up and running, change `~/.continue/config.json` to look like this: - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Llama CPP provider: llama.cpp diff --git a/docs/docs/customize/model-providers/more/lmstudio.mdx b/docs/docs/customize/model-providers/more/lmstudio.mdx index 784c321cc..6dedb0a88 100644 --- a/docs/docs/customize/model-providers/more/lmstudio.mdx +++ b/docs/docs/customize/model-providers/more/lmstudio.mdx @@ -1,5 +1,5 @@ -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; # LM Studio @@ -7,7 +7,7 @@ import TabItem from "@theme/TabItem"; - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: LM Studio provider: lmstudio @@ -35,7 +35,7 @@ LMStudio supports embeddings endpoints, and comes with the `nomic-ai/nomic-embed - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Nomic Embed Text provider: lmstudio @@ -62,7 +62,7 @@ To configure a remote instance of LM Studio, add the `"apiBase"` property to you - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Nomic Embed Text provider: lmstudio diff --git a/docs/docs/customize/model-providers/more/moonshot.mdx b/docs/docs/customize/model-providers/more/moonshot.mdx index 9fc429f6d..0d9f838eb 100644 --- a/docs/docs/customize/model-providers/more/moonshot.mdx +++ b/docs/docs/customize/model-providers/more/moonshot.mdx @@ -1,5 +1,5 @@ -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; # Moonshot @@ -14,7 +14,7 @@ To use Moonshot AI models, you need to: - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Moonshot provider: moonshot @@ -60,7 +60,7 @@ Here's a complete configuration example: - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Moonshot-8K provider: moonshot diff --git a/docs/docs/customize/model-providers/more/msty.mdx b/docs/docs/customize/model-providers/more/msty.mdx index e08d2ffff..d23955fd4 100644 --- a/docs/docs/customize/model-providers/more/msty.mdx +++ b/docs/docs/customize/model-providers/more/msty.mdx @@ -1,5 +1,5 @@ -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; # Msty @@ -7,7 +7,7 @@ import TabItem from "@theme/TabItem"; - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Msty provider: msty @@ -46,7 +46,7 @@ If you need to send custom headers for authentication, you may use the `requestO - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Msty provider: msty diff --git a/docs/docs/customize/model-providers/more/ncompass.mdx b/docs/docs/customize/model-providers/more/ncompass.mdx new file mode 100644 index 000000000..e6f98c296 --- /dev/null +++ b/docs/docs/customize/model-providers/more/ncompass.mdx @@ -0,0 +1,34 @@ +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +# nCompass + +The nCompass Technologies API exposes an extremely fast inference engine for open-source language models. You can sign up [here](https://app.ncompass.tech/api-settings), copy your API key on the initial welcome screen, and then hit the play button on any model from the [nCompass Models list](https://console.ncompass.tech/models). Change `~/.continue/config.json` to look like this: + + + + ```yaml title="Package or config.yaml" + models: + - name: Ncompass Qwen2.5 Coder + provider: ncompass + model: Qwen/Qwen2.5-Coder-32B-Instruct + apiKey: + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Ncompass Qwen2.5 Coder", + "provider": "ncompass", + "model": "Qwen/Qwen2.5-Coder-32B-Instruct", + "apiKey": "" + } + ] + } + ``` + + + +[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/NCompass.ts) diff --git a/docs/docs/customize/model-providers/more/nebius.mdx b/docs/docs/customize/model-providers/more/nebius.mdx index 72af4334d..12a660ead 100644 --- a/docs/docs/customize/model-providers/more/nebius.mdx +++ b/docs/docs/customize/model-providers/more/nebius.mdx @@ -1,5 +1,5 @@ -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; # Nebius AI Studio @@ -13,7 +13,7 @@ Available models can be found on the [Nebius AI Studio models page](https://stud - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Llama 3.1 405b provider: nebius diff --git a/docs/docs/customize/model-providers/more/novita.mdx b/docs/docs/customize/model-providers/more/novita.mdx index bf6e99421..ca2f603b0 100644 --- a/docs/docs/customize/model-providers/more/novita.mdx +++ b/docs/docs/customize/model-providers/more/novita.mdx @@ -1,5 +1,5 @@ -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; # Novita @@ -7,7 +7,7 @@ import TabItem from "@theme/TabItem"; - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Llama 3.1 8B provider: novita diff --git a/docs/docs/customize/model-providers/more/nvidia.mdx b/docs/docs/customize/model-providers/more/nvidia.mdx index bc395cf0d..27fdc9041 100644 --- a/docs/docs/customize/model-providers/more/nvidia.mdx +++ b/docs/docs/customize/model-providers/more/nvidia.mdx @@ -2,8 +2,8 @@ title: NVIDIA --- -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; :::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. @@ -43,7 +43,7 @@ We recommend configuring **Nemotron-4-340B-Instruct** as your chat model. NVIDIA currently does not offer any autocomplete models. -[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers. +[Click here](../../model-roles/autocomplete.md) to see a list of autocomplete model providers. ## Embeddings model @@ -78,4 +78,4 @@ We recommend configuring **NVIDIA Retrieval QA Mistral 7B** as your embeddings m NVIDIA currently does not offer any reranking models. -[Click here](../../model-types/reranking.mdx) to see a list of reranking model providers. +[Click here](../../model-roles/reranking.mdx) to see a list of reranking model providers. diff --git a/docs/docs/customize/model-providers/more/openrouter.mdx b/docs/docs/customize/model-providers/more/openrouter.mdx index 637366d6e..cc7902a65 100644 --- a/docs/docs/customize/model-providers/more/openrouter.mdx +++ b/docs/docs/customize/model-providers/more/openrouter.mdx @@ -1,5 +1,5 @@ -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; # OpenRouter @@ -9,7 +9,7 @@ Change `~/.continue/config.json` to look like the following. - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: OpenRouter LLaMA 70 8B provider: openrouter @@ -41,7 +41,7 @@ For example, to prevent extra long prompts from being compressed, you can explic - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Example Model provider: exampleProvider diff --git a/docs/docs/customize/model-providers/more/replicatellm.mdx b/docs/docs/customize/model-providers/more/replicatellm.mdx index 958fc347a..c7a58e076 100644 --- a/docs/docs/customize/model-providers/more/replicatellm.mdx +++ b/docs/docs/customize/model-providers/more/replicatellm.mdx @@ -1,5 +1,5 @@ -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; # ReplicateLLM @@ -7,7 +7,7 @@ Replicate is a great option for newly released language models or models that yo - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Replicate CodeLLama provider: replicate diff --git a/docs/docs/customize/model-providers/more/scaleway.mdx b/docs/docs/customize/model-providers/more/scaleway.mdx index 462c362b5..299c6cc19 100644 --- a/docs/docs/customize/model-providers/more/scaleway.mdx +++ b/docs/docs/customize/model-providers/more/scaleway.mdx @@ -2,8 +2,8 @@ title: Scaleway --- -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; :::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. @@ -18,7 +18,7 @@ We recommend configuring **Qwen2.5-Coder-32B-Instruct** as your chat model. - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Qwen2.5-Coder-32B-Instruct provider: scaleway @@ -46,7 +46,7 @@ We recommend configuring **Qwen2.5-Coder-32B-Instruct** as your chat model. Scaleway currently does not offer any autocomplete models. -[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers. +[Click here](../../model-roles/autocomplete.md) to see a list of autocomplete model providers. ## Embeddings model diff --git a/docs/docs/customize/model-providers/more/textgenwebui.mdx b/docs/docs/customize/model-providers/more/textgenwebui.mdx index 0bfcbb442..2f41c4ab9 100644 --- a/docs/docs/customize/model-providers/more/textgenwebui.mdx +++ b/docs/docs/customize/model-providers/more/textgenwebui.mdx @@ -1,5 +1,5 @@ -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; # TextGenWebUI @@ -7,7 +7,7 @@ TextGenWebUI is a comprehensive, open-source language model UI and local server. - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Text Generation WebUI provider: text-gen-webui diff --git a/docs/docs/customize/model-providers/more/together.mdx b/docs/docs/customize/model-providers/more/together.mdx index 8af923471..7b2f3b829 100644 --- a/docs/docs/customize/model-providers/more/together.mdx +++ b/docs/docs/customize/model-providers/more/together.mdx @@ -1,5 +1,5 @@ -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; # Together @@ -7,7 +7,7 @@ The Together API is a cloud platform for running large AI models. You can sign u - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Together Qwen2.5 Coder provider: together diff --git a/docs/docs/customize/model-providers/more/vllm.mdx b/docs/docs/customize/model-providers/more/vllm.mdx index 1c49ef620..58431ec7d 100644 --- a/docs/docs/customize/model-providers/more/vllm.mdx +++ b/docs/docs/customize/model-providers/more/vllm.mdx @@ -1,5 +1,5 @@ -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; # vLLM @@ -45,7 +45,7 @@ We recommend configuring **Qwen2.5-Coder 1.5B** as your autocomplete model. - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Qwen2.5-Coder 1.5B provider: vllm @@ -75,7 +75,7 @@ We recommend configuring **Nomic Embed Text** as your embeddings model. - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: VLLM Nomad Embed Text provider: vllm @@ -100,6 +100,6 @@ We recommend configuring **Nomic Embed Text** as your embeddings model. ## Reranking model -[Click here](../../model-types/reranking.mdx) to see a list of reranking model providers. +[Click here](../../model-roles/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.mdx b/docs/docs/customize/model-providers/more/watsonx.mdx index e18b3e285..0854e0cd6 100644 --- a/docs/docs/customize/model-providers/more/watsonx.mdx +++ b/docs/docs/customize/model-providers/more/watsonx.mdx @@ -1,5 +1,5 @@ -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; # IBM watsonx @@ -45,15 +45,16 @@ Add the following configuration: - ```yaml title="Package or config.yaml" + ```yaml title="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 + env: + projectId: PROJECT_ID + apiVersion: 2024-03-14 ``` @@ -81,15 +82,16 @@ If you are using a custom deployment endpoint, set `deploymentID` to the model's - ```yaml title="Package or config.yaml" + ```yaml title="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 + env: + apiVersion: 2024-03-14 + deploymentId: DEPLOYMENT_ID ``` @@ -124,9 +126,7 @@ You can also configure generation parameters, such as temperature, topP, topK, f 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: @@ -138,6 +138,10 @@ You can also configure generation parameters, such as temperature, topP, topK, f stop: - Question: - "\n\n\n" + env: + projectId: PROJECT_ID + apiVersion: 2024-03-14 + ``` @@ -175,7 +179,7 @@ Granite models are recommended for tab auto complete. The configuration is simil - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Granite Code 8b provider: watsonx diff --git a/docs/docs/customize/model-providers/top-level/anthropic.mdx b/docs/docs/customize/model-providers/top-level/anthropic.mdx index 7844cf49c..d7d1e325c 100644 --- a/docs/docs/customize/model-providers/top-level/anthropic.mdx +++ b/docs/docs/customize/model-providers/top-level/anthropic.mdx @@ -3,8 +3,8 @@ title: Anthropic slug: ../anthropic --- -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; :::info You can get an API key from the [Anthropic console](https://console.anthropic.com/account/keys). @@ -44,19 +44,19 @@ We recommend configuring **Claude 3.5 Sonnet** as your chat model. Anthropic currently does not offer any autocomplete models. -[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers. +[Click here](../../model-roles/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. +[Click here](../../model-roles/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. +[Click here](../../model-roles/reranking.mdx) to see a list of reranking model providers. ## Prompt caching @@ -66,7 +66,7 @@ To enable caching of the system message and the turn-by-turn conversation, updat - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Anthropic provider: anthropic diff --git a/docs/docs/customize/model-providers/top-level/azure.mdx b/docs/docs/customize/model-providers/top-level/azure.mdx index a4f1a3f93..2c201d938 100644 --- a/docs/docs/customize/model-providers/top-level/azure.mdx +++ b/docs/docs/customize/model-providers/top-level/azure.mdx @@ -3,8 +3,8 @@ title: Azure AI Foundry slug: ../azure --- -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; 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). @@ -19,20 +19,20 @@ For details on OpenAI model setup, see [Azure OpenAI Service configuration](#azu 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 + + ```yaml title="config.yaml" + models: + - name: GPT-4o + provider: azure + model: gpt-4o + apiBase: + 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 - ``` - - + deployment: + apiType: azure-foundry # Or "azure-openai" if using OpenAI models + ``` + + ```json title="config.json" { "models": [{ @@ -46,35 +46,39 @@ We recommend configuring **GPT-4o** as your chat model. }] } ``` - + ## Autocomplete model -We recommend configuring **Codestral** as your autocomplete model. +We recommend configuring **Codestral** as your autocomplete model. If you use Azure AI Foundry to deploy Codestral: - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Codestral provider: mistral model: codestral-latest + apiBase: https://..models.ai.azure.com/v1 + apiKey: roles: - autocomplete - ``` - - - ```json title="config.json" + ``` + + + ```json title="config.json" { "tabAutocompleteModel": { "title": "Codestral", "provider": "mistral", - "model": "codestral-latest" + "model": "codestral-latest", + "apiBase": "https://..models.ai.azure.com/v1", + "apiKey": "" } } - ``` - + ``` + ## Embeddings model @@ -83,15 +87,15 @@ We recommend configuring **text-embedding-3-large** as your embeddings model. - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Text Embedding-3 Large provider: azure model: text-embedding-3-large apiBase: - deployment: apiKey: env: + deployment: apiType: azure ``` @@ -115,7 +119,7 @@ We recommend configuring **text-embedding-3-large** as your embeddings model. Azure OpenAI currently does not offer any reranking models. -[Click here](../../model-types/reranking.mdx) to see a list of reranking models. +[Click here](../../model-roles/reranking.mdx) to see a list of reranking models. ## Privacy @@ -135,20 +139,20 @@ For example, a Target URI of `https://just-an-example.openai.azure.com/openai/de - ```yaml title="Package or config.yaml" + ```yaml title="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 + apiVersion: 2023-03-15-preview + deployment: gpt-4o-july + apiType: azure-openai ``` - - + + ```json title="config.json" { "title": "GPT-4o Azure", @@ -161,5 +165,5 @@ For example, a Target URI of `https://just-an-example.openai.azure.com/openai/de "apiType": "azure-openai" } ``` - + diff --git a/docs/docs/customize/model-providers/top-level/bedrock.mdx b/docs/docs/customize/model-providers/top-level/bedrock.mdx index f472d42a5..9582428a4 100644 --- a/docs/docs/customize/model-providers/top-level/bedrock.mdx +++ b/docs/docs/customize/model-providers/top-level/bedrock.mdx @@ -3,8 +3,8 @@ title: Amazon Bedrock slug: ../bedrock --- -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; Amazon Bedrock is a fully managed service on AWS that provides access to foundation models from various AI companies through a single API. @@ -19,8 +19,9 @@ We recommend configuring **Claude 3.5 Sonnet** as your chat model. - name: Claude 3.5 Sonnet provider: bedrock model: anthropic.claude-3-5-sonnet-20240620-v1:0 - region: us-east-1 - profile: bedrock + env: + region: us-east-1 + profile: bedrock roles: - chat ``` @@ -53,8 +54,9 @@ We recommend configuring **Claude 3.5 Sonnet** as your chat model. - name: Claude 3.5 Sonnet provider: bedrock model: us.anthropic.claude-3-5-sonnet-20241022-v2:0 - region: us-east-1 - profile: bedrock + env: + region: us-east-1 + profile: bedrock roles: - chat ``` @@ -80,7 +82,7 @@ We recommend configuring **Claude 3.5 Sonnet** as your chat 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). +In the meantime, you can view a list of autocomplete model providers [here](../../model-roles/autocomplete.md). ## Embeddings model @@ -93,7 +95,8 @@ We recommend configuring [`amazon.titan-embed-text-v2:0`](https://docs.aws.amazo - name: Embeddings Model provider: bedrock model: amazon.titan-embed-text-v2:0 - region: us-west-2 + env: + region: us-west-2 roles: - embed ``` @@ -123,7 +126,8 @@ We recommend configuring `cohere.rerank-v3-5:0` as your reranking model, you may - name: Bedrock Reranker provider: bedrock model: cohere.rerank-v3-5:0 - region: us-west-2 + env: + region: us-west-2 roles: - rerank ``` diff --git a/docs/docs/customize/model-providers/top-level/deepseek.mdx b/docs/docs/customize/model-providers/top-level/deepseek.mdx index 0d15bb5f4..28f885192 100644 --- a/docs/docs/customize/model-providers/top-level/deepseek.mdx +++ b/docs/docs/customize/model-providers/top-level/deepseek.mdx @@ -3,8 +3,8 @@ title: DeepSeek slug: ../deepseek --- -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; :::info You can get an API key from the [DeepSeek console](https://www.deepseek.com/). @@ -74,10 +74,10 @@ We recommend configuring **DeepSeek Coder** as your autocomplete model. DeepSeek currently does not offer any embeddings models. -[Click here](../../model-types/embeddings.mdx) to see a list of embeddings model providers. +[Click here](../../model-roles/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. +[Click here](../../model-roles/reranking.mdx) 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 index 6911a14a0..5bde15a79 100644 --- a/docs/docs/customize/model-providers/top-level/gemini.mdx +++ b/docs/docs/customize/model-providers/top-level/gemini.mdx @@ -3,8 +3,8 @@ title: Gemini slug: ../gemini --- -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; :::info You can get an API key from the [Google AI Studio](https://aistudio.google.com/). @@ -12,15 +12,15 @@ 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. +We recommend configuring **Gemini 2.0 Flash** as your chat model. ```yaml title="config.yaml" models: - - name: Gemini 1.5 Pro + - name: Gemini 2.0 Flash provider: gemini - model: gemini-1.5-pro-latest + model: gemini-2.0-flash apiKey: ``` @@ -29,9 +29,9 @@ We recommend configuring **Gemini 1.5 Pro** as your chat model. { "models": [ { - "title": "Gemini 1.5 Pro", + "title": "Gemini 2.0 Flash", "provider": "gemini", - "model": "gemini-1.5-pro-latest", + "model": "gemini-2.0-flash", "apiKey": "" } ] @@ -44,7 +44,7 @@ We recommend configuring **Gemini 1.5 Pro** as your chat model. Gemini currently does not offer any autocomplete models. -[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers. +[Click here](../../model-roles/autocomplete.md) to see a list of autocomplete model providers. ## Embeddings model @@ -79,4 +79,4 @@ We recommend configuring **text-embedding-004** as your embeddings model. Gemini currently does not offer any reranking models. -[Click here](../../model-types/reranking.mdx) to see a list of reranking model providers. +[Click here](../../model-roles/reranking.mdx) 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 index dd584394d..df936fe54 100644 --- a/docs/docs/customize/model-providers/top-level/mistral.mdx +++ b/docs/docs/customize/model-providers/top-level/mistral.mdx @@ -3,8 +3,8 @@ title: Mistral slug: ../mistral --- -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; :::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`. @@ -107,4 +107,4 @@ We recommend configuring **Mistral Embed** as your embeddings model. Mistral currently does not offer any reranking models. -[Click here](../../model-types/reranking.mdx) to see a list of reranking model providers. +[Click here](../../model-roles/reranking.mdx) to see a list of reranking model providers. diff --git a/docs/docs/customize/model-providers/top-level/ollama.mdx b/docs/docs/customize/model-providers/top-level/ollama.mdx index f2a80386e..92759e2cb 100644 --- a/docs/docs/customize/model-providers/top-level/ollama.mdx +++ b/docs/docs/customize/model-providers/top-level/ollama.mdx @@ -3,8 +3,8 @@ title: Ollama slug: ../ollama --- -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; 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. @@ -14,7 +14,7 @@ We recommend configuring **Llama3.1 8B** as your chat model. - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Llama3.1 8B provider: ollama @@ -42,7 +42,7 @@ We recommend configuring **Qwen2.5-Coder 1.5B** as your autocomplete model. - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Qwen2.5-Coder 1.5B provider: ollama @@ -70,7 +70,7 @@ We recommend configuring **Nomic Embed Text** as your embeddings model. - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Nomic Embed Text provider: ollama @@ -95,7 +95,7 @@ We recommend configuring **Nomic Embed Text** as your embeddings model. Ollama currently does not offer any reranking models. -[Click here](../../model-types/reranking.mdx) to see a list of reranking model providers. +[Click here](../../model-roles/reranking.mdx) to see a list of reranking model providers. ## Using a remote instance @@ -103,7 +103,7 @@ To configure a remote instance of Ollama, add the `"apiBase"` property to your m - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Llama3.1 8B provider: ollama diff --git a/docs/docs/customize/model-providers/top-level/openai.mdx b/docs/docs/customize/model-providers/top-level/openai.mdx index 71a117850..8ed706213 100644 --- a/docs/docs/customize/model-providers/top-level/openai.mdx +++ b/docs/docs/customize/model-providers/top-level/openai.mdx @@ -3,8 +3,8 @@ title: OpenAI slug: ../openai --- -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; :::info You can get an API key from the [OpenAI console](https://platform.openai.com/account/api-keys) @@ -44,7 +44,7 @@ We recommend configuring **GPT-4o** as your chat model. OpenAI currently does not offer any autocomplete models. -[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers. +[Click here](../../model-roles/autocomplete.md) to see a list of autocomplete model providers. ## Embeddings model @@ -79,7 +79,7 @@ We recommend configuring **text-embedding-3-large** as your embeddings model. OpenAI currently does not offer any reranking models. -[Click here](../../model-types/reranking.mdx) to see a list of reranking model providers. +[Click here](../../model-roles/reranking.mdx) to see a list of reranking model providers. ## OpenAI compatible servers / APIs diff --git a/docs/docs/customize/model-providers/top-level/vertexai.mdx b/docs/docs/customize/model-providers/top-level/vertexai.mdx index 514b67cb4..2863acc31 100644 --- a/docs/docs/customize/model-providers/top-level/vertexai.mdx +++ b/docs/docs/customize/model-providers/top-level/vertexai.mdx @@ -3,8 +3,8 @@ title: Vertex AI slug: ../vertexai --- -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; :::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). @@ -16,13 +16,14 @@ We recommend configuring **Claude 3.5 Sonnet** as your chat model. - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Claude 3.5 Sonnet provider: vertexai model: claude-3-5-sonnet-20240620 - projectId: - region: us-east5 + env: + projectId: + region: us-east5 ``` @@ -53,10 +54,12 @@ We recommend configuring **Codestral** or **code-gecko** as your autocomplete mo - name: Codestral (Vertex AI) provider: vertexai model: codestral - projectId: - region: us-central1 roles: - autocomplete + env: + projectId: + region: us-central1 + ``` @@ -85,8 +88,9 @@ We recommend configuring **text-embedding-004** as your embeddings model. - name: Text Embedding-004 provider: vertexai model: text-embedding-004 - projectId: - region: us-central1 + env: + projectId: + region: us-central1 roles: - embed ``` @@ -109,4 +113,4 @@ We recommend configuring **text-embedding-004** as your embeddings model. Vertex AI currently does not offer any reranking models. -[Click here](../../model-types/reranking.mdx) to see a list of reranking model providers. +[Click here](../../model-roles/reranking.mdx) to see a list of reranking model providers. diff --git a/docs/docs/customize/model-providers/top-level/xAI.mdx b/docs/docs/customize/model-providers/top-level/xAI.mdx index 6fb459736..3c049790d 100644 --- a/docs/docs/customize/model-providers/top-level/xAI.mdx +++ b/docs/docs/customize/model-providers/top-level/xAI.mdx @@ -3,8 +3,8 @@ title: xAI slug: ../xai --- -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; :::info You can get an API key from the [xAI console](https://console.x.ai/) @@ -14,7 +14,10 @@ You can get an API key from the [xAI console](https://console.x.ai/) 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). - + + + Add the [xAI Grok 2 model block](https://hub.continue.dev/xai/grok-2) on the hub. + ```yaml title="config.yaml" models: @@ -44,16 +47,16 @@ We recommend configuring **grok-2-latest** as your chat model. For information o xAI currently does not offer any autocomplete models. -[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers. +[Click here](../../model-roles/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. +[Click here](../../model-roles/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. +[Click here](../../model-roles/reranking.mdx) to see a list of reranking model providers. diff --git a/docs/docs/customize/model-roles/apply.mdx b/docs/docs/customize/model-roles/apply.mdx new file mode 100644 index 000000000..1ecace184 --- /dev/null +++ b/docs/docs/customize/model-roles/apply.mdx @@ -0,0 +1,15 @@ +--- +title: Apply Role +description: Apply model role +keywords: [apply, model, role] +sidebar_position: 4 +--- + +import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; + +When editing code, Chat and Edit model output often doesn't clearly align with existing code. A model with the `apply` role is used to generate a more precise diff to apply changes to a file. + +Generally speaking, models proficient in chat and edit can also be used for applying code. + +Explore apply models in [the hub](https://hub.continue.dev/explore/models?roles=apply). diff --git a/docs/docs/customize/model-roles/autocomplete.md b/docs/docs/customize/model-roles/autocomplete.md new file mode 100644 index 000000000..9641d5dcb --- /dev/null +++ b/docs/docs/customize/model-roles/autocomplete.md @@ -0,0 +1,14 @@ +--- +title: Autocomplete Role +description: Autocomplete model role +keywords: [autocomplete, model, role] +sidebar_position: 2 +--- + +An "autocomplete model" is an LLM that is trained on a special format called fill-in-the-middle (FIM). This format is designed to be given the prefix and suffix of a code file and predict what goes between. This task is very specific, which on one hand means that the models can be smaller (even a 3B parameter model can perform well). On the other hand, this means that Chat models, though larger, will often perform poorly even with extensive prompting. + +In Continue, autocomplete models are used to display inline [Autocomplete](../../autocomplete/how-to-use-it.md) suggestions as you type. Autocomplete models are designated by adding the `autocomplete` to the model's `roles` in `config.yaml`. + +## Recommended Autocomplete models + +Visit the [Autocomplete Deep Dive](../deep-dives/autocomplete.mdx) for recommended models and more details. diff --git a/docs/docs/customize/model-roles/chat.mdx b/docs/docs/customize/model-roles/chat.mdx new file mode 100644 index 000000000..90b97e17c --- /dev/null +++ b/docs/docs/customize/model-roles/chat.mdx @@ -0,0 +1,416 @@ +--- +title: Chat Role +description: Chat model role +keywords: [chat, model, role] +sidebar_position: 1 +--- + +import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; + +A "chat model" is an LLM that is trained to respond in a conversational format. Because they should be able to answer general questions and generate complex code, the best chat models are typically large, often 405B+ parameters. + +In Continue, these models are used for [Chat](../../chat/how-to-use-it.md) and [Actions](../../actions/how-to-use-it.md). The selected chat model will also be used for [Edit](../../edit/how-to-use-it.md) and [Apply](./apply.mdx) if no `edit` or `apply` models are specified, respectively. + +## Recommended Chat models + +## Best overall experience + +For the best overall Chat experience, you will want to use a 400B+ parameter model or one of the frontier models. + +### Claude Sonnet 3.5 from Anthropic + +Our current top recommendation is Claude 3.7 Sonnet from [Anthropic](../model-providers/top-level/anthropic.mdx). + + + + View the [Claude 3.7 Sonnet model block](https://hub.continue.dev/anthropic/claude-3-7-sonnet) on the hub. + + + ```yaml title="config.yaml" + models: + - name: Claude 3.7 Sonnet + provider: anthropic + model: claude-3-7-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](../model-providers/more/together.mdx) or [Groq](../model-providers/more/groq.mdx)) or self-host it (e.g. using [vLLM](../model-providers//more/vllm.mdx) or [Ollama](../model-providers/top-level/ollama.mdx)). + + + {/* HUB_TODO nonexistent blocks */} + {/* + + + Add the [Together Llama 3.1 405b block](https://hub.continue.dev/explore/assistants) from the hub + + + Add the [Groq Llama 3.1 405b block](https://hub.continue.dev/explore/assistants) from the hub + + + Add the [vLLM Llama 3.1 405b block](https://hub.continue.dev/explore/assistants) from the hub + + + Add the [Ollama Llama 3.1 405b block](https://hub.continue.dev/explore/assistants) from the hub + + + */} + + + + ```yaml title="config.yaml" + models: + - name: "Llama 3.1 405B" + provider: "together" + model: "llama3.1-405b" + apiKey: + ``` + + + ```yaml title="config.yaml" + models: + - name: "Llama 3.1 405B" + provider: "groq" + model: "llama3.1-405b" + apiKey: + ``` + + + ```yaml title="config.yaml" + models: + - name: "Llama 3.1 405B" + provider: "vllm" + model: "llama3.1-405b" + ``` + + + ```yaml title="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](../model-providers/top-level/openai.mdx), then we recommend GPT-4o. + + + + Add the [OpenAI GPT-4o block](https://hub.continue.dev/openai/gpt-4o) from the hub + + + ```yaml title="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](../model-providers/top-level/xAI.mdx), then we recommend Grok-2. + + + + Add the [xAI Grok-2 block](https://hub.continue.dev/xai/grok-2) from the hub + + + ```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": "" + } + ] + } + ``` + + + +### Gemini 2.0 Flash from Google + +If you prefer to use a model from [Google](../model-providers/top-level/gemini.mdx), then we recommend Gemini 2.0 Flash. + + + + Add the [Gemini 2.0 Flash block](https://hub.continue.dev/google/gemini-2.0-flash) from the hub + + + ```yaml title="config.yaml" + models: + - name: Gemini 2.0 Flash + provider: gemini + model: gemini-2.0-flash + apiKey: + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Gemini 2.0 Flash", + "provider": "gemini", + "model": "gemini-2.0-flash", + "apiKey": "" + } + ] + } + ``` + + + +## Local, offline experience + +For the best local, offline Chat experience, you will want to use a model that is large but fast enough on your machine. + +### 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](../model-providers/top-level/ollama.mdx) or [LM Studio](../model-providers/more/lmstudio.mdx)). + + + + + + Add the [Ollama Llama 3.1 8b block](https://hub.continue.dev/ollama/llama3.1-8b) from the hub + + {/* HUB_TODO nonexistent block */} + {/* + Add the [LM Studio Llama 3.1 8b block](https://hub.continue.dev/explore/models) from the hub + */} + + + + + + ```yaml title="config.yaml" + models: + - name: Llama 3.1 8B + provider: ollama + model: llama3.1:8b + ``` + + + ```yaml title="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](../model-providers/top-level/ollama.mdx) or [LM Studio](../model-providers/more/lmstudio.mdx)). + + + {/* HUB_TODO nonexistent blocks */} + {/* + + + Add the [Ollama Deepseek Coder 2 16B block](https://hub.continue.dev/explore/models) from the hub + + + Add the [LM Studio Deepseek Coder 2 16B block](https://hub.continue.dev/explore/models) from the hub + + + */} + + + + ```yaml title="config.yaml" + models: + - name: DeepSeek Coder 2 16B + provider: ollama + model: deepseek-coder-v2:16b + ``` + + + ```yaml title="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 + +There are many more models and providers you can use with Chat beyond those mentioned above. Read more [here](../model-roles/chat.mdx) diff --git a/docs/docs/customize/model-roles/edit.mdx b/docs/docs/customize/model-roles/edit.mdx new file mode 100644 index 000000000..de817ed42 --- /dev/null +++ b/docs/docs/customize/model-roles/edit.mdx @@ -0,0 +1,48 @@ +--- +title: Edit Role +description: Edit model role +keywords: [edit, editing, model, role] +sidebar_position: 3 +--- + +import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; + +It's often useful to select a different model to respond to Edit prompts than for chat prompts, as Edits are often more code-specific and may require less conversational readability. + +In Continue, you can add `edit` to a model's roles to specify that it can be used for Edit requests. If no edit models are specified, the selected `chat` model is used. + + + + Use model roles. + ```yaml title="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", + } + } + } + ``` + + + +Explore edit models in [the hub](https://hub.continue.dev/explore/models?roles=edit). Generally, our recommendations for Edit overlap with recommendations for Chat. diff --git a/docs/docs/customize/model-types/embeddings.mdx b/docs/docs/customize/model-roles/embeddings.mdx similarity index 84% rename from docs/docs/customize/model-types/embeddings.mdx rename to docs/docs/customize/model-roles/embeddings.mdx index ee22f7301..a58cd520d 100644 --- a/docs/docs/customize/model-types/embeddings.mdx +++ b/docs/docs/customize/model-roles/embeddings.mdx @@ -1,23 +1,21 @@ --- -title: Embeddings model -description: Embeddings model -keywords: [embedding] -sidebar_position: 3 +title: Embed Role +description: Embed model role +keywords: [embedding, model, role, embeddings] +sidebar_position: 5 --- -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; 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. -::: +You can add `embed` to a model's `roles` to specify that it can be used to embed. -:::info[Free Trial] -The free trial supports embeddings (provider: `free-trial`) +:::info[Built-in model (VS Code only)] +`transformers.js` is used as a built-in embeddings model in VS Code. In JetBrains, there currently is no built-in embedder. ::: ## Recommended embedding models @@ -30,9 +28,12 @@ If you want to generate embeddings locally, we recommend using `nomic-embed-text After obtaining an API key from [here](https://www.voyageai.com/), you can configure like this: - + + + [Voyage Code 3 Embedder Block](https://hub.continue.dev/voyageai/voyage-code-3) + - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Voyage Code 3 provider: voyage @@ -65,7 +66,7 @@ See [here](../model-providers/top-level/ollama.mdx#embeddings-model) for instruc - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: default-transformers provider: transformers.js @@ -89,8 +90,12 @@ See [here](../model-providers/top-level/ollama.mdx#embeddings-model) for instruc [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: + {/* HUB_TODO nonexistent block */} + {/* + [HuggingFace Text Embedder Block](https://hub.continue.dev/) + */} - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Huggingface TEI Embedder provider: huggingface-tei diff --git a/docs/docs/customize/model-roles/intro.mdx b/docs/docs/customize/model-roles/intro.mdx new file mode 100644 index 000000000..3c3a6476e --- /dev/null +++ b/docs/docs/customize/model-roles/intro.mdx @@ -0,0 +1,31 @@ +--- +title: Intro to Roles +description: Apply model role +keywords: [apply, model, role] +sidebar_position: 0 +sidebar_label: Introduction +--- + +import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; + +Models in Continue can be configured to be used for various roles in the extension. + +- [`chat`](./chat.mdx): Used for chat conversations in the extension sidebar +- [`autocomplete`](./autocomplete.md): Used for autocomplete code suggestions in the editor +- [`edit`](./edit.mdx): Used to generate code based on edit prompts +- [`apply`](./apply.mdx): Used to decide how to apply edits to a file +- [`embed`](./embeddings.mdx): Used to generate embeddings used for vector search (@Codebase and @Docs context providers) +- [`rerank`](./reranking.mdx): Used to rerank results from vector search + +These roles can be specified for a `config.yaml` model block using `roles`. See the [YAML Specification](../../yaml-reference.md#models) for more details. + +## Selecting model roles + +You can control which of the models in your assistant for a given role will be currently used for that role. Visit the [Settings page](../settings.md) and go to the **Active Models** section. + +![Settings Active Models Section](/img/settings-model-roles.png) + +:::info +Note that `roles` do not exist within `config.json` - they are infered by the top level keys like `embeddingsProvider` +::: diff --git a/docs/docs/customize/model-types/reranking.mdx b/docs/docs/customize/model-roles/reranking.mdx similarity index 79% rename from docs/docs/customize/model-types/reranking.mdx rename to docs/docs/customize/model-roles/reranking.mdx index 098dd94bc..c16dab7a0 100644 --- a/docs/docs/customize/model-types/reranking.mdx +++ b/docs/docs/customize/model-roles/reranking.mdx @@ -1,16 +1,16 @@ --- -title: Reranking model -description: Reranking model -keywords: [rerank] -sidebar_position: 4 +title: Rerank Role +description: Rerank model role +keywords: [rerank, reranking, model, role] +sidebar_position: 6 --- -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; 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. +In Continue, rerankers are designated using the `rerank` role and used by [@Codebase](../deep-dives/codebase.mdx) in order to select the most relevant code snippets after vector search. ## Recommended reranking models @@ -18,9 +18,12 @@ If you have the ability to use any model, we recommend `rerank-2` by Voyage AI, ### 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: +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 a reranker as follows: - + + + [Voyage Rerank 2 Block](https://hub.continue.dev/voyageai/rerank-2) + ```yaml title="config.yaml" models: @@ -52,6 +55,10 @@ Voyage AI offers the best reranking model for code with their `rerank-2` model. See Cohere's documentation for rerankers [here](https://docs.cohere.com/docs/rerank-2). + {/* HUB_TODO block doesn't exist */} + {/* + [Cohere Reranker English v3](https://hub.continue.dev/) + */} ```yaml title="config.yaml" models: @@ -83,6 +90,10 @@ See Cohere's documentation for rerankers [here](https://docs.cohere.com/docs/rer 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. + {/* HUB_TODO block doesn't exist */} + {/* + [GPT-4o LLM Reranker Block](https://hub.continue.dev/) + */} ```yaml title="config.yaml" models: @@ -114,8 +125,12 @@ The `"modelTitle"` field must match one of the models in your "models" array in [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: + {/* HUB_TODO */} + {/* + [HuggingFace TEI Reranker block](https://hub.continue.dev/) + */} - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Huggingface-tei Reranker provider: huggingface-tei @@ -139,28 +154,3 @@ The `"modelTitle"` field must match one of the models in your "models" array in ``` - -### 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/model-types/autocomplete.md b/docs/docs/customize/model-types/autocomplete.md deleted file mode 100644 index 4b14775d1..000000000 --- a/docs/docs/customize/model-types/autocomplete.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -title: Autocomplete model -description: Autocomplete model -keywords: [autocomplete] -sidebar_position: 1 ---- - -An "autocomplete model" is an LLM that is trained on a special format called fill-in-the-middle (FIM). This format is designed to be given the prefix and suffix of a code file and predict what goes between. This task is very specific, which on one hand means that the models can be smaller (even a 3B parameter model can perform well). On the other hand, this means that Chat models, though larger, will perform poorly. - -In Continue, these models are used to display inline [Autocomplete](../../autocomplete/how-to-use-it.md) suggestions as you type. - -## Recommended Autocomplete models - -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.mdx#autocomplete-model). diff --git a/docs/docs/customize/model-types/chat.md b/docs/docs/customize/model-types/chat.md deleted file mode 100644 index bde3d5557..000000000 --- a/docs/docs/customize/model-types/chat.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -title: Chat model -description: Chat model -keywords: [chat] -sidebar_position: 2 ---- - -A "chat model" is an LLM that is trained to respond in a conversational format. Because they should be able to answer general questions and generate complex code, the best chat models are typically large, often 405B+ parameters. In Continue, these models are used for [Chat](../../chat/how-to-use-it.md), [Edit](../../edit/how-to-use-it.md), and [Actions](../../actions/how-to-use-it.md). - -## Recommended Chat models - -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.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/overview.md b/docs/docs/customize/overview.md index 1a52712b9..2024673f9 100644 --- a/docs/docs/customize/overview.md +++ b/docs/docs/customize/overview.md @@ -7,7 +7,7 @@ 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/) . +- **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-roles/) . - **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). @@ -21,7 +21,7 @@ Most custom configuration is done by editing `config.yaml` (or the older `config - MacOS and Linux: `~/.continue/config.yaml` - Windows: `%USERPROFILE%\.continue\config.yaml` -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`. +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 configuration file`. ![configure-continue](/img/configure-continue.png) @@ -47,4 +47,4 @@ If you'd like to scope certain settings to a particular workspace, you can add a `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). +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.mdx). diff --git a/docs/docs/customize/slash-commands.mdx b/docs/docs/customize/slash-commands.mdx index 710d5fd69..e1890ba81 100644 --- a/docs/docs/customize/slash-commands.mdx +++ b/docs/docs/customize/slash-commands.mdx @@ -4,11 +4,11 @@ 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"; +import Tabs from "@theme/Tabs"; :::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 can currently only be added using [`config.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. @@ -120,7 +120,7 @@ The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" mcpServers: - name: My MCP Server command: uvx diff --git a/docs/docs/customize/tools.mdx b/docs/docs/customize/tools.mdx index 2f06f5081..1aad549f1 100644 --- a/docs/docs/customize/tools.mdx +++ b/docs/docs/customize/tools.mdx @@ -4,13 +4,15 @@ description: Tool use and customization keywords: [tool, use, function calling, claude, automatic] --- -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; 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.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). +- [OpenAI](./model-providers/top-level/openai.mdx) +- [Gemini](./model-providers/top-level/gemini.mdx) To use tools, click on the icon in the input toolbar like below. @@ -24,11 +26,15 @@ 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](../customize/deep-dives/configuration.md) 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. + +MCP Servers can be added to hub Assistants using `mcpServers` blocks. You can explore available MCP server blocks [here](https://hub.continue.dev/explore/mcp). + +To set up your own MCP server, read the [MCP quickstart](https://modelcontextprotocol.io/quickstart) and then [create an `mcpServers` block](https://hub.continue.dev/new?type=block&blockType=mcpServers) or add the following to your [config file](../customize/deep-dives/configuration.md): - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" mcpServers: - name: My MCP Server command: uvx diff --git a/docs/docs/customize/tutorials/build-your-own-context-provider.md b/docs/docs/customize/tutorials/build-your-own-context-provider.mdx similarity index 83% rename from docs/docs/customize/tutorials/build-your-own-context-provider.md rename to docs/docs/customize/tutorials/build-your-own-context-provider.mdx index 33ba4441a..7710a84c2 100644 --- a/docs/docs/customize/tutorials/build-your-own-context-provider.md +++ b/docs/docs/customize/tutorials/build-your-own-context-provider.mdx @@ -2,14 +2,60 @@ title: Build your own context provider --- +import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; + +# Build Your Own Context Provider + +Continue offers several way to provide your custom context to the extension. + +## HTTP Context Provider + +Continue can retrieve context from a custom HTTP server that you create and serve. Add the `@HTTP` context provider to your configuration like this: + + + + ```yaml title="config.yaml" + context: + provider: http + params: + url: https://myserver.com/context-provider + title: http + displayTitle: My Custom Context + description: Gets things from my private list + options: + maxItems: 20 + ``` + + + ```json title="config.json" + { + "name": "http", + "params": { + "url": "https://myserver.com/context-provider", + "title": "http", + "description": "Custom HTTP Context Provider", + "displayTitle": "My Custom Context", + "options": { + "maxItems": 20 + } + } + } + ``` + + + +Then, create a server that responds to requests as are made from [HttpContextProvider.ts](https://github.com/continuedev/continue/blob/main/core/context/providers/HttpContextProvider.ts). See the `hello` endpoint in [context_provider_server.py](https://github.com/continuedev/continue/blob/main/core/context/providers/context_provider_server.py) for an example that uses FastAPI. + +The `"options"` property can be used to send additional parameters to your endpoint, which will be included in the request body. + :::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. +The following methods for creating custom context providers are deprecated. We recommend using HTTP context providers, [MCP Servers](../context-providers.mdx#model-context-protocol), and [Prompt files](../deep-dives/prompt-files.md) where possible. ::: -## Introductory Example +## Using CustomContextProvider -To write your own context provider, you just have to implement the `CustomContextProvider` -interface: +Custom context providers can be implemented in a `config.ts` placed in your Continue global directory (`~/.continue` for MacOS, `%USERPROFILE%/.continue` for Windows). You can implement the `CustomContextProvider` interface in your `config.ts` ```typescript interface CustomContextProvider { @@ -75,7 +121,7 @@ export function modifyConfig(config: Config): Config { This is automatically appended to your configuration. -## Custom Context Providers with Submenu or Query +### Custom Context Providers with Submenu or Query There are 3 types of context providers: "normal", "query", and "submenu". The "normal" type is the default, and is what we've seen so far. @@ -163,13 +209,13 @@ The flow of information in the above example is as follows: 3. The `id` of the chosen `ContextSubmenuItem` is passed to `getContextItems` as the `query` argument. In this case it is the filepath of the README. 4. The `getContextItems` function can then use the `query` to retrieve the full contents of the README and format the content before returning the context item which will be included in the prompt. -## Importing outside modules +### Importing outside modules To include outside Node modules in your config.ts, run `npm install ` from the `~/.continue` directory, and then import them in config.ts. Continue will use [esbuild](https://esbuild.github.io/) to bundle your `config.ts` and any dependencies into a single Javascript file. The exact configuration used can be found [here](https://github.com/continuedev/continue/blob/5c9874400e223bbc9786a8823614a2e501fbdaf7/extensions/vscode/src/ideProtocol.ts#L45-L52). -## `CustomContextProvider` Reference +### `CustomContextProvider` Reference - `title`: An identifier for the context provider - `displayTitle` (optional): The title displayed in the dropdown @@ -183,27 +229,7 @@ Continue will use [esbuild](https://esbuild.github.io/) to bundle your `config.t - `extras.ide`: An instance of the `IDE` class, which lets you gather various sources of information from the IDE, including the contents of the terminal, the list of open files, or any warnings in the currently open file. - `query`: (not currently used) A string representing the query - `loadSubmenuItems` (optional): A function that returns a list of `ContextSubmenuItem`s to display in a submenu. It is given access to an `IDE`, the same that is passed to `getContextItems`. - -## Writing Context Providers in Other Languages - -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 title="config.json" -{ - "name": "http", - "params": { - "url": "https://myserver.com/context-provider", - "title": "http", - "description": "Custom HTTP Context Provider", - "displayTitle": "My Custom Context", - "options": {} - } -} -``` - -Then, create a server that responds to requests as are made from [HttpContextProvider.ts](../../../../core/context/providers/HttpContextProvider.ts). See the `hello` endpoint in [context_provider_server.py](../../../../core/context/providers/context_provider_server.py) for an example that uses FastAPI. - -The `"options"` property can be used to send additional parameters to your endpoint, which will be included in the request body. + . ## Extension API for VSCode 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 27b0517b3..f0cc1147f 100644 --- a/docs/docs/customize/tutorials/build-your-own-slash-command.md +++ b/docs/docs/customize/tutorials/build-your-own-slash-command.md @@ -3,7 +3,7 @@ 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. +Slash commands can currently only be added using [`config.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: 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 index abd726aba..ab3c9b1b5 100644 --- a/docs/docs/customize/tutorials/how-to-self-host-a-model.mdx +++ b/docs/docs/customize/tutorials/how-to-self-host-a-model.mdx @@ -2,8 +2,8 @@ title: How to self-host a model --- -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; 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: @@ -25,7 +25,7 @@ Basic authentication can be done with any provider using the `apiKey` field: - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Ollama provider: ollama @@ -55,7 +55,7 @@ If you need to send custom headers for authentication, you may use the `requestO - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Ollama provider: ollama diff --git a/docs/docs/customize/tutorials/llama3.1.mdx b/docs/docs/customize/tutorials/llama3.1.mdx index 294fc4e8b..413214fb4 100644 --- a/docs/docs/customize/tutorials/llama3.1.mdx +++ b/docs/docs/customize/tutorials/llama3.1.mdx @@ -4,8 +4,8 @@ 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"; +import Tabs from "@theme/Tabs"; 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. @@ -23,7 +23,7 @@ Ollama is the fastest way to get up and running with local language models. We r - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Llama 3.1 8b provider: ollama @@ -92,7 +92,7 @@ Together AI provides fast and reliable inference of open-source models. You'll b - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Llama 3.1 405b provider: together @@ -125,7 +125,7 @@ Replicate makes it easy to host and run open-source AI with an API. - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Llama 3.1 405b provider: replicate @@ -193,7 +193,7 @@ Cerebras Inference uses specialized silicon to provides fast inference for the L - ```yaml title="Package or config.yaml" + ```yaml title="config.yaml" models: - name: Cerebras Llama 3.1 70B provider: cerebras diff --git a/docs/docs/edit/how-to-customize.mdx b/docs/docs/edit/how-to-customize.mdx index ef8e44a54..35b918393 100644 --- a/docs/docs/edit/how-to-customize.mdx +++ b/docs/docs/edit/how-to-customize.mdx @@ -5,40 +5,7 @@ description: How to customize Edit keywords: [edit, cmd i, works] --- -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; -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", - } - } - } - ``` - - +You can configure a particular model to be used for Edit by setting/overriding `roles` in the model's YAML config. See [Edit role](../customize/model-roles/edit.mdx) for more details. diff --git a/docs/docs/edit/model-setup.md b/docs/docs/edit/model-setup.md index ad884b334..606bd0654 100644 --- a/docs/docs/edit/model-setup.md +++ b/docs/docs/edit/model-setup.md @@ -7,4 +7,6 @@ keywords: [edit, cmd l, model] By default, Edit uses the [same model as Chat](../chat/model-setup.mdx) since we recommend a similar, 400B+ parameter model or one of the frontier model for code edits. -You can configure a different model to be used for edits by updating your [configuration](../reference.md). +Visit [the hub](https://hub.continue.dev/explore/models?roles=edit) to explore Edit models. + +You can configure a different model to be used for edits by updating your [configuration](../customize/model-roles/edit.mdx). diff --git a/docs/docs/getting-started/install.md b/docs/docs/getting-started/install.md index f144a37a1..b62dbacd8 100644 --- a/docs/docs/getting-started/install.md +++ b/docs/docs/getting-started/install.md @@ -9,6 +9,7 @@ keywords: [install, installation, getting started, vs code, jetbrains] 1. Click `Install` on the [Continue extension page in the Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=Continue.continue) 2. This will open the Continue extension page in VS Code, where you will need to click `Install` again 3. The Continue logo will appear on the left sidebar. For a better experience, move Continue to the right sidebar +4. [Sign in to the hub](#signing-in) to get started with your first assistant. ![move-to-right-sidebar](/img/move-to-right-sidebar.gif) @@ -21,9 +22,16 @@ If you have any problems, see the [troubleshooting guide](../troubleshooting.mdx 1. Open your JetBrains IDE and open **Settings** using Ctrl + Alt + S 2. Select **Plugins** on the sidebar and search for "Continue" in the marketplace 3. Click `Install`, which will cause the Continue logo to show up on the right toolbar +4. [Sign in to the hub](#signing-in) to get started with your first assistant. ![jetbrains-getting-started.png](/img/jetbrains-getting-started.png) :::info[Troubleshooting] If you have any problems, see the [troubleshooting guide](../troubleshooting.mdx) or ask for help in [our Discord](https://discord.com/invite/EfJEfdFnDQ) ::: + +## Signing in + +Click "Get started" to sign in to the hub and start using assistants. + +![Hub Onboarding in the Extension](/img/hub/hub-onboarding-card.png) diff --git a/docs/docs/hub/assistants/create-an-assistant.md b/docs/docs/hub/assistants/create-an-assistant.md new file mode 100644 index 000000000..207f1c955 --- /dev/null +++ b/docs/docs/hub/assistants/create-an-assistant.md @@ -0,0 +1,38 @@ +--- +title: Create an assistant +sidebar_label: Create an assistant +description: How to create a custom AI code assistant +keywords: [assistants, creation, guide] +--- + +# Create an assistant + +## Remix an assistant + +You should remix an assistant if you want to use it after some modifications. + +By clicking the “remix” button, you’ll be taken to the “Create a remix” page. + +![Remix Assistant Button](/img/hub/assistant-remix-button.png) + +Once here, you’ll be able to + +1. add or remove blocks in YAML configuration +2. change the name, description, icon, etc. + +Clicking “Create assistant” will make this assistant available for use. + +## Create an assistant from scratch + +To create an assistant from scratch, select “New assistant” in the top bar. + +![New assistant button](/img/hub/assistant-new-button.png) + +Choose a name, slug, description, and icon for your assistant. + +The easiest way to create an assistant is to click "Create assistant" with the default configuration and then add / remove blocks using the sidebar. + +Alternatively, you can edit the assistant YAML directly before clicking "Create assistant". Refer to examples of assistants on [hub.continue.dev](https://hub.continue.dev/explore/assistants) and visit the [YAML Reference](../../yaml-reference.md#complete-yaml-config-example) docs for more details. + +![New assistant YAML](/img/hub/assistant-create-yaml.png) + diff --git a/docs/docs/hub/assistants/edit-an-assistant.md b/docs/docs/hub/assistants/edit-an-assistant.md new file mode 100644 index 000000000..9a4c8aeee --- /dev/null +++ b/docs/docs/hub/assistants/edit-an-assistant.md @@ -0,0 +1,26 @@ +--- +title: Edit an Assistant +sidebar_label: Edit an Assistant +description: How to edit a custom AI coding assistant. +keywords: [assistants, creation, guide] +--- + +# Edit an Assistant + +New versions of an assistant can be created and published using the sidebar. + +![Remix Assistant Button](/img/hub/assistant-create-sidebar.png) + +First, select an assistant from the dropdown at the top. + +While editing an assistant, you can explore the hub and click "Add Block" from a block page to add it to your assistant. + +For blocks that require secret values like API keys, you will see a small notification on the block's tile in the sidebar that will indicate if action is needed. + +To delete a block, click the trash icon. + +If a block you want to use does not exist yet, you can [create a new block](../blocks/create-a-block.md). + +When you are done editing, click "Publish" to publish a new version of the assistant. + +Click "Open VS Code" or "Open JetBrains" to open your IDE for using the assistant. \ No newline at end of file diff --git a/docs/docs/hub/assistants/intro.md b/docs/docs/hub/assistants/intro.md new file mode 100644 index 000000000..716e8f0d8 --- /dev/null +++ b/docs/docs/hub/assistants/intro.md @@ -0,0 +1,14 @@ +--- +title: Assistants Introduction +sidebar_label: Introduction +description: Overview of assistants functionality. +keywords: [assistants, overview, customization] +--- + +# Introduction to Assistants + +Custom AI code assistants are configurations of building [blocks](../blocks/intro.md) that enable a coding experience tailored to your specific use cases. + +`config.yaml` is a format for defining custom AI code assistants. An assistant has some top-level properties (e.g. `name`, `version`), but otherwise consists of composable lists of **blocks** such as `models` and `rules`, which are the atomic building blocks of an assistant. + +The `config.yaml` is parsed by the open-source Continue IDE extensions to create custom assistant experiences. When you log in to [hub.continue.dev](https://hub.continue.dev/), your assistants will automatically be synced with the IDE extensions. diff --git a/docs/docs/hub/assistants/use-an-assistant.md b/docs/docs/hub/assistants/use-an-assistant.md new file mode 100644 index 000000000..081118c23 --- /dev/null +++ b/docs/docs/hub/assistants/use-an-assistant.md @@ -0,0 +1,20 @@ +--- +title: Use an assistant +sidebar_label: Use an assistant +description: Guide to using assistants in your Continue workflow. +keywords: [assistants, usage, use, guide] +--- + +# Use an assistant + +To use an existing assistant, you can explore other assistants [here](https://hub.continue.dev/explore/assistants). + +Once you've found the assistant you want to use + +1. Click “Add Assistant” on its page +2. Add any required inputs (e.g. secrets like API keys) +3. Select “Save changes” in assistant sidebar on the right hand side + +After this, you can then go to your IDE extension and begin using the assistant by selecting it from the assistant dropdown. + +[Extension Assistant Selector](/img/hub/assistant-extension-select.png) \ No newline at end of file diff --git a/docs/docs/hub/blocks/block-types.md b/docs/docs/hub/blocks/block-types.md new file mode 100644 index 000000000..51ec97b10 --- /dev/null +++ b/docs/docs/hub/blocks/block-types.md @@ -0,0 +1,55 @@ +--- +title: Block Types +description: Overview of different block types +keywords: [blocks, types, overview] +sidebar_label: Types +--- + +# Block Types + +## Models + +Models are blocks that let you specify Large Language Models (LLMs) and other deep learning models to be used for various roles in the open-source IDE extension like Chat, Autocomplete, Edit, Embed, Rerank, etc. You can explore available models on [the hub](https://hub.continue.dev/explore/models). + +Continue supports [many model providers](../../customize/model-providers), including Anthropic, OpenAI, Gemini, Ollama, Amazon Bedrock, Azure, xAI, DeepSeek, and more. Models can have one or more of the following roles depending on its capabilities, including `chat`, `edit`, `apply`, `autocomplete`, `embed`, and `rerank`. Read more about roles [here](../../customize/model-roles). View [`models`](../../yaml-reference.md#models) in the YAML Reference for more details. + +## Context + +Context blocks define a context provider which can be referenced in Chat with `@` to pull in data from external sources such as files and folders, a URL, Jira or Confluence, and Github issues, among others. [Explore context provider blocks](https://hub.continue.dev/explore/context) on the hub. + +Learn more about context providers [here](../../yaml-reference.md#context), and check out [this guide](../../customize/tutorials/build-your-own-context-provider.mdx) to creating your own custom context provider. The `config.yaml` spec for context can be found [`here`](../../yaml-reference.md#context). + +## Docs + +Docs are blocks that point to documentation sites, which will be indexed locally and then can be referenced as context using @Docs in Chat. [Explore docs](https://hub.continue.dev/explore/docs) on the hub. + +Learn more in the [@Docs deep dive](../../customize/deep-dives/docs.mdx), and view [`docs`](../../yaml-reference.md#docs) in the YAML Reference for more details. + +## MCP Servers + +Model Context Protocol (MCP) is a standard way of building and sharing tools for language models. MCP Servers can be defined in `mcpServers` blocks. [Explore MCP Servers](https://hub.continue.dev/explore/mcp) on the hub. + +Learn more in the [Tools deep dive](../../customize/tools.mdx), and view [`mcpServers`](../../yaml-reference.md#mcpservers) in the YAML Reference for more details. + +## Rules + +Rules blocks are instructions that your custom AI code assistant will always keep in mind - the contents of rules are inserted into the system message for all Chat requests. [Explore rules](https://hub.continue.dev/explore/rules) on the hub. + +Learn more in the [rules deep dive](../../customize/deep-dives/rules.md), and view [`rules`](../../yaml-reference.md#rules) in the YAML Reference for more details. + +## Prompts + +Prompts blocks are pre-written, reusable prompts that can be referenced at any time during chat. They are especially useful as context for repetitive and/or complex tasks. [Explore prompts](https://hub.continue.dev/explore/prompts) on the hub. + +Prompt blocks have the same syntax as [prompt files](../../customize/deep-dives/prompt-files.md). There are two important differences between prompt blocks and prompt files: + +1. Prompt blocks are stored within `config.yaml` rather than `.continue/prompts` in project directory and +2. Prompt blocks only show up as slash commands in Chat, not under the `@Prompt Files` context provider + +The `config.yaml` spec for `prompts` can be found [here](../../yaml-reference.md#prompts). + +## Data + +Data blocks allow you send your development data to custom destinations of your choice. Development data can be used for a variety of purposes, including analyzing usage, gathering insights, or fine-tuning models. You can read more about development data [here](../../customize/deep-dives/development-data.md). Explore data block examples [here](https://hub.continue.dev/explore/data). + +Data destinations are configured in the[`data`](../../yaml-reference.md#data) section of `config.yaml`. \ No newline at end of file diff --git a/docs/docs/hub/blocks/bundles.md b/docs/docs/hub/blocks/bundles.md new file mode 100644 index 000000000..6d54ed519 --- /dev/null +++ b/docs/docs/hub/blocks/bundles.md @@ -0,0 +1,39 @@ +--- +title: Bundles +sidebar_label: Bundles +description: Introduction to bundles +keywords: [blocks, bundles] +--- + +# Bundles + +Bundles are collections of blocks that are commonly used together. You can use them to add multiple building blocks to your custom AI code assistants at once. They are only a concept on [hub.continue.dev](https://hub.continue.dev), so they are not represented in `config.yaml`. + +## Use a bundle + +Once you know which bundle you want to use, you’ll need to + +1. Make sure the correct assistant is in the sidebar +2. Click “Add all blocks". This adds the individual blocks to your assistant. +3. Add any required inputs (e.g. secrets) for each block. +4. Select “Save changes” in assistant sidebar on the right hand side + +After this, you can then go to your IDE extension using the "Open VS Code" or "Open Jetbrains" buttons and begin using the new blocks. + +## Create a bundle + +To create a bundle, click “New bundle” in the header. + +![New bundle button](/img/hub/bundle-new-button.png) + +Choose a name, slug, description, and visibility for your bundle. + +Then, search blocks using the "Search blocks" input and add them to your bundle. + +![Create bundle page](/img/hub/bundle-create-page.png) + +Once you have added all the blocks you want in your bundle, click "Create Bundle" to save it and make it available for use. + +## Remix a bundle + +It is not currently possible to remix a bundle. \ No newline at end of file diff --git a/docs/docs/hub/blocks/create-a-block.md b/docs/docs/hub/blocks/create-a-block.md new file mode 100644 index 000000000..870295c99 --- /dev/null +++ b/docs/docs/hub/blocks/create-a-block.md @@ -0,0 +1,32 @@ +--- +title: Create a block +sidebar_label: Create a block +description: Guide to creating blocks +keywords: [blocks, creation, create, use] +--- + +# Create a block + +## Remix a block + +You should remix a block if you want to use it after some modifications. + +By clicking the “remix” button, you’ll be taken to the “Create a remix” page. + +![Remix block button](/img/hub/block-remix-button.png) + +Once here, you’ll be able to 1) edit YAML configuration for the block and 2) change name, description, icon, etc. Clicking “Create block” will make this block available for use in an assistant. + +## Create a block from scratch + +To create a block from scratch, you will need to click “New block” in the top bar. + +![New block button](/img/hub/block-new-button.png) + +After filling out information on the block, you will want to create a block following the `config.yaml` [reference documentation](../../yaml-reference.md). Refer to examples of blocks on [hub.continue.dev](https://hub.continue.dev/explore/models) and visit the [YAML Reference](../../yaml-reference.md#complete-yaml-config-example) docs for more details. + +![New block page](/img/hub/block-new-page.png) + +### Block inputs + +Blocks can receive values, including secrets, as inputs through templating. For values that the user of the block needs to set, you can use template variables (e.g. `${{ inputs.API_KEY}}`). Then, the user can set `API_KEY: ${{ secrets.MY_API_KEY }}` in the `with` clause of their assistant. \ No newline at end of file diff --git a/docs/docs/hub/blocks/intro.md b/docs/docs/hub/blocks/intro.md new file mode 100644 index 000000000..919aa9f7d --- /dev/null +++ b/docs/docs/hub/blocks/intro.md @@ -0,0 +1,12 @@ +--- +title: Introduction +sidebar_label: Introduction +description: Introduction to blocks +keywords: [blocks, introduction, basics] +--- + +# Introduction + +Blocks are the components you use to build a custom AI code assistant. These include [models](./block-types.md#models), [rules](./block-types.md#rules), [context providers](./block-types.md#context), [prompts](./block-types.md#prompts), [docs](./block-types.md#docs), [data destinations](./block-types.md#data), and [MCP servers](./block-types.md#mcp-servers). + +Blocks follow the [`config.yaml`](../../yaml-reference.md) format. When combined with other blocks into a complete `config.yaml`, they form a custom AI code assistant. diff --git a/docs/docs/hub/blocks/use-a-block.md b/docs/docs/hub/blocks/use-a-block.md new file mode 100644 index 000000000..ca4b6e067 --- /dev/null +++ b/docs/docs/hub/blocks/use-a-block.md @@ -0,0 +1,15 @@ +--- +title: Use a block +description: Guide to using blocks +keywords: [blocks, usage, use] +--- + +# Use a block + +Blocks can be used by adding them to assistants: +- [Create an assistant](../assistants/create-an-assistant.md) +- [Edit an assistant](../assistants/edit-an-assistant.md) + +Some blocks require inputs. If you are missing an input for a block, a notification icon will show up in the sidebar next to the block. Click the notification to select which secret to use for the block input: + +![Block inputs](/img/hub/block-inputs.png) \ No newline at end of file diff --git a/docs/docs/hub/governance/org-permissions.md b/docs/docs/hub/governance/org-permissions.md new file mode 100644 index 000000000..85d4f613e --- /dev/null +++ b/docs/docs/hub/governance/org-permissions.md @@ -0,0 +1,18 @@ +--- +title: Org Permissions +description: Org Permissions +keywords: [governance, organization, org, permissions] +--- + +# Organization Permissions + +**Users can have the following roles within an organization:** + +1. Admins are users who can manage members, secrets, blocks, assistants, etc. +2. Members are users who can use assistants, blocks, secrets, etc. + +**User permissions for each role depend on the pricing plan:** + +- [Solo](./pricing.md#solo) +- [Teams](./pricing.md#teams) +- [Enterprise](./pricing.md#enterprise) \ No newline at end of file diff --git a/docs/docs/hub/governance/pricing.md b/docs/docs/hub/governance/pricing.md new file mode 100644 index 000000000..06dd03c1e --- /dev/null +++ b/docs/docs/hub/governance/pricing.md @@ -0,0 +1,35 @@ +--- +title: Pricing +description: Solo, Teams, Enterprise, and Models Add-On pricing +keywords: [solo, teams, enterprise, models add-on] +--- + +# Pricing + +## Solo + +**Solo** is best suited for individuals and small teams with "single-player" problems. + +You can read more about what **Solo** includes [here](https://hub.continue.dev/pricing). + +## Teams + +**Teams** is best suited for growing teams with "multiplayer" problems. + +You can read more about what **Teams** includes [here](https://hub.continue.dev/pricing). + +## Enterprise + +**Enterprise** is best suited for large teams with enterprise-grade requirements. + +You can read more about what **Enterprise** includes [here](https://hub.continue.dev/pricing). + +## Models Add-On + +The **Models Add-On** allows you to use a variety of frontier models for a flat monthly fee. It’s designed to cover the usage of most developers. + +You can read more about usage limits and what models are included [here](https://hub.continue.dev/pricing). + +### Free Trial + +To try out Continue, we offer a free trial of the **Models Add-On** that allows you to use 50 Chat requests and 2,000 autocomplete requests. \ No newline at end of file diff --git a/docs/docs/hub/introduction.md b/docs/docs/hub/introduction.md new file mode 100644 index 000000000..88cca05f0 --- /dev/null +++ b/docs/docs/hub/introduction.md @@ -0,0 +1,16 @@ +--- +title: Introduction +description: Introduction +keywords: [continue, hub, introduction] +sidebar_label: Introduction +--- + +# Introduction + +![Continue Hub](/img/hub/models-page.png) + +[Continue Hub](https://hub.continue.dev) makes it simple to create custom AI code [assistants](./assistants/intro.md), providing a registry for defining, managing, and sharing assistant [building blocks](./blocks/intro.md). + +Assistants can contain several types of blocks, including [models](./blocks/block-types.md#models), [rules](./blocks/block-types.md#rules), [context providers](./blocks/block-types.md#context), [prompts](./blocks/block-types.md#prompts), [docs](./blocks/block-types.md#docs), [data destinations](./blocks/block-types.md#data), and [MCP servers](./blocks/block-types.md#mcp-servers). + +Continue Hub also makes it easy for engineering leaders to centrally [configure](./secrets/secret-types.md) and [govern](./governance/org-permissions.md) blocks and assistants for their organization. diff --git a/docs/docs/hub/secrets/secret-resolution.md b/docs/docs/hub/secrets/secret-resolution.md new file mode 100644 index 000000000..7fe357c8f --- /dev/null +++ b/docs/docs/hub/secrets/secret-resolution.md @@ -0,0 +1,22 @@ +--- +title: Secret Resolution +description: Intro to Secret Resolution +keywords: [secrets, resolution] +sidebar_label: Resolution +--- + +# Secret Resolution + +[User or Org secrets](./secret-types.md) should be used depending on how users want them to be shared within their organization and assistants. + +For individual users and [Solo](../governance/pricing.md#solo) organizations, secret resolution is performed in the following order: + +1. User [models add-on](../governance/pricing.md#models-add-on) (if subscribed) +2. [User secrets](../secrets/secret-types.md#user-secrets) (if set) +3. [Free trial](../governance/pricing.md#free-trial) (if below limit) + +For [Teams](../governance/pricing.md#teams) and [Enterprise](../governance/pricing.md#enterprise) organizations, secret resolution is performed in the following order: + +1. Org [models add-on](../governance/pricing.md#models-add-on) (if subscribed) +2. [Org secrets](../secrets/secret-types.md#org-secrets) (if set) +3. [User secrets](../secrets/secret-types.md#user-secrets) (if set) \ No newline at end of file diff --git a/docs/docs/hub/secrets/secret-types.md b/docs/docs/hub/secrets/secret-types.md new file mode 100644 index 000000000..655825ca9 --- /dev/null +++ b/docs/docs/hub/secrets/secret-types.md @@ -0,0 +1,22 @@ +--- +title: Secret Types +description: Intro to Secret Types +keywords: [secrets, types] +sidebar_label: Types +--- + +# Secret Types + +The Continue Hub comes with secrets management built-in. Secrets are values such as API keys or endpoints that can be shared across assistants and within organizations. + +## User secrets + +User secrets are defined by the user for themselves. This means that user secrets are available only to the user that created them. User secrets are assumed to be safe for the user to know, so they will be sent to the IDE extensions alongside the assistant `config.yaml`. + +This allows API requests to be made directly from the IDE extensions. You can use user secrets with [Solo](../governance/pricing.md#solo), [Teams](../governance/pricing.md#teams), and [Enterprise](../governance/pricing.md#enterprise). User secrets can be managed [here](https://hub.continue.dev/settings/secrets) in the hub. + +## Org secrets + +Org secrets are defined by admins for their organization. Org secrets are available to anyone in the organization to use with assistants in that organization. Org secrets are assumed to not be shareable with the user (e.g. you are a team lead who wants to give team members access to models without passing out API keys). + +This is why LLM requests are proxied through api.continue.dev / on-premise proxy and secrets are never sent to the IDE extensions. You can only use org secrets on [Teams](../governance/pricing.md#teams) and [Enterprise](../governance/pricing.md#enterprise). If you are an admin, you can manage secrets for your organization from the org settings page. \ No newline at end of file diff --git a/docs/docs/introduction.md b/docs/docs/introduction.md index cfa1301cd..9628dd4cb 100644 --- a/docs/docs/introduction.md +++ b/docs/docs/introduction.md @@ -1,6 +1,6 @@ --- title: Introduction -description: The open-source AI code assistant for developers +description: Create, share, and use custom AI code assistants slug: / keywords: [ @@ -17,7 +17,7 @@ keywords: ![Continue Logo](../static/img/intro.png) -**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)** +**Continue enables developers to create, share, and use custom AI code assistants with our open-source [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension) extensions and [hub of models, rules, prompts, docs, and other building blocks](https://hub.continue.dev)** - [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 diff --git a/docs/docs/json-reference.md b/docs/docs/json-reference.md index ac5573b76..a80e77e36 100644 --- a/docs/docs/json-reference.md +++ b/docs/docs/json-reference.md @@ -111,7 +111,7 @@ 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 +- `provider` (**required**): Specifies the embeddings provider, with options including `transformers.js`, `ollama`, `openai`, `cohere`, `gemini`, etc - `model`: Model name for embeddings. - `apiKey`: API key for the provider. - `apiBase`: Base URL for API requests. @@ -206,7 +206,7 @@ Configuration for the reranker model used in response ranking. **Properties:** -- `name` (**required**): Reranker name, e.g., `cohere`, `voyage`, `llm`, `free-trial`, `huggingface-tei`, `bedrock` +- `name` (**required**): Reranker name, e.g., `cohere`, `voyage`, `llm`, `huggingface-tei`, `bedrock` - `params`: - `model`: Model name - `apiKey`: Api key diff --git a/docs/docs/reference.md b/docs/docs/reference.md index 7891ebc4a..f966ec451 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -113,13 +113,13 @@ 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 +- `provider` (**required**): Specifies the embeddings provider, with options including `transformers.js`, `ollama`, `openai`, `cohere`, `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. +- `maxEmbeddingChunkSize`: Maximum tokens per document chunk. Minimum is 128 tokens. +- `maxEmbeddingBatchSize`: Maximum number of chunks per request. Minimum is 1 chunk. (AWS ONLY) @@ -134,8 +134,8 @@ Example: "provider": "openai", "model": "text-embedding-ada-002", "apiKey": "", - "maxChunkSize": 256, - "maxBatchSize": 5 + "maxEmbeddingChunkSize": 256, + "maxEmbeddingBatchSize": 5 } } ``` @@ -151,7 +151,7 @@ Parameters that control the behavior of text generation and completion settings. - `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. +- `frequencyPenalty`: 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`). @@ -208,7 +208,7 @@ Configuration for the reranker model used in response ranking. **Properties:** -- `name` (**required**): Reranker name, e.g., `cohere`, `voyage`, `llm`, `free-trial`, `huggingface-tei`, `bedrock` +- `name` (**required**): Reranker name, e.g., `cohere`, `voyage`, `llm`, `huggingface-tei`, `bedrock` - `params`: - `model`: Model name - `apiKey`: Api key diff --git a/docs/docs/telemetry.md b/docs/docs/telemetry.md index e086d409d..e21a93164 100644 --- a/docs/docs/telemetry.md +++ b/docs/docs/telemetry.md @@ -6,13 +6,13 @@ keywords: [telemetry, anonymous, usage info, opt out] ## Overview -Continue collects and reports **anonymous** usage information to help us improve our product. This data enables us to understand user interactions and optimize the user experience effectively. You can opt out of telemetry collection at any time if you prefer not to share your usage information. +The open-source Continue Extensions collect and report **anonymous** usage information to help us improve our product. This data enables us to understand user interactions and optimize the user experience effectively. You can opt out of telemetry collection at any time if you prefer not to share your usage information. We utilize [Posthog](https://posthog.com/), an open-source platform for product analytics, to gather and store this data. For transparency, you can review the implementation code [here](https://github.com/continuedev/continue/blob/main/gui/src/hooks/CustomPostHogProvider.tsx) or read our [official privacy policy](https://continue.dev/privacy). ## Tracking Policy -All data collected by Continue is anonymized and stripped of personally identifiable information (PII) before being sent to PostHog. We are committed to maintaining the privacy and security of your data. +All data collected by the open-source Continue extensions is anonymized and stripped of personally identifiable information (PII) before being sent to PostHog. We are committed to maintaining the privacy and security of your data. ## What We Track diff --git a/docs/docs/troubleshooting.mdx b/docs/docs/troubleshooting.mdx index ae54ee8ac..79ebefecb 100644 --- a/docs/docs/troubleshooting.mdx +++ b/docs/docs/troubleshooting.mdx @@ -151,6 +151,14 @@ This can be accomplished using the following command: `Continue: Rebuild codebas This can be fixed by selecting `Actions > Choose Boot runtime for the IDE` then selecting the latest version, and then restarting Android Studio. [See this thread](https://github.com/continuedev/continue/issues/596#issuecomment-1789327178) for details. +### I received a "Codebase indexing disabled - Your Linux system lacks required CPU features (AVX2, FMA)" notification + +We use LanceDB as our vector database for codebase search features. On x64 Linux systems, LanceDB requires specific CPU features (FMA and AVX2) which may not be available on older processors. + +Most Continue features will work normally, including autocomplete and chat. However, commands that rely on codebase indexing, such as `@codebase`, `@files`, and `@folder`, will be disabled. + +For more details about this requirement, see the [LanceDB issue #2195](https://github.com/lancedb/lance/issues/2195). + ## Still having trouble? You can also join our Discord community [here](https://discord.gg/vapESyrFmJ) for additional support and discussions. Alternatively, you can create a GitHub issue [here](https://github.com/continuedev/continue/issues/new?assignees=&labels=bug&projects=&template=bug-report-%F0%9F%90%9B.md&title=), providing details of your problem, and we'll be able to help you out more quickly. diff --git a/docs/docs/yaml-migration.md b/docs/docs/yaml-migration.md index cc603ce1c..4619018f2 100644 --- a/docs/docs/yaml-migration.md +++ b/docs/docs/yaml-migration.md @@ -12,7 +12,7 @@ See also - [Intro to YAML](https://yaml.org/) - [JSON Continue Config Reference](/json-reference) -- [YAML Continue Config Reference](/reference) +- [YAML Continue Config Reference](/yaml-reference) ## Create YAML file @@ -37,9 +37,9 @@ 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](/reference#requestoptions) +Model-level `requestOptions` remain, with minor changes. See [YAML Continue Config Reference](/yaml-reference#requestoptions) -Model-level `completionOptions` are replaced by `defaultCompletionOptions`, with minor changes. See [YAML Continue Config Reference](/reference#completionoptions) +Model-level `completionOptions` are replaced by `defaultCompletionOptions`, with minor changes. See [YAML Continue Config Reference](/yaml-reference#completionoptions) @@ -82,8 +82,8 @@ Model-level `completionOptions` are replaced by `defaultCompletionOptions`, with "provider": "openai", "model": "text-embedding-ada-002", "apiKey": "", - "maxChunkSize": 256, - "maxBatchSize": 5 + "maxEmbeddingChunkSize": 256, + "maxEmbeddingBatchSize": 5 }, "reranker": { "name": "voyage", @@ -126,6 +126,9 @@ models: apiKey: roles: - embed + embedOptions: + - maxChunkSize: 256 + - maxBatchSize: 5 - name: Ollama Autodetect provider: ollama @@ -143,7 +146,7 @@ models: - apply ``` -Note that the `repoMapFileSelection` experimental model role has been deprecated. +Note that the `repoMapFileSelection` experimental model role has been deprecated and is only available in `config.json`. ### Context Providers diff --git a/docs/docs/yaml-reference.md b/docs/docs/yaml-reference.md index 427d3e865..d4e63d1b4 100644 --- a/docs/docs/yaml-reference.md +++ b/docs/docs/yaml-reference.md @@ -4,35 +4,103 @@ description: Reference for the Continue configuration YAML file keywords: [config, yaml, configuration, customize, customization] --- -# confg.yaml Reference +# config.yaml Reference - +## Introduction -Continue can be configured using a YAML file `config.yaml` which for local configuration can be placed in your global `.continue` folder (`~/.continue` on Mac, `%USERPROFILE%\.continue`) +Continue hub assistants are defined using the `config.yaml` specification. Local assistants can also be configured using a YAML file `config.yaml` placed in your global `.continue` folder (`~/.continue` on Mac, `%USERPROFILE%\.continue`) + +:::info +Config YAML replaces `config.json`. View the **[Migration Guide](/yaml-migration)**. +::: + +An assistant is made up of: + +1. **Top level properties**, which specify the `name`, `version`, and `config.yaml` `schema` for the assistant +2. **Block lists**, which are composable arrays of coding assistant building blocks available to the assistant, such as models, docs, and context providers. + +A block is a single standalone building block of a coding assistants, e.g., one model or one documentation source. In `config.yaml` syntax, a block consists of the same top-level properties as assistants (`name`, `version`, and `schema`), but only has **ONE** item under whichever block type it is. + +Examples of blocks and assistants can be found on the [Continue hub](https://hub.continue.dev/explore/assistants). + +Assistants can either explicitly define blocks - see [Properties](#properties) below - or import and configure existing hub blocks. + +### Using Blocks + +Hub blocks and assistants are identified with a slug in the format `owner-slug/block-or-assistant-slug`, where an owner can be a user or organization. + +Blocks can be imported into an assistant by adding a `uses` clause under the block type. This can be alongside other `uses` clauses or explicit blocks of that type. + +For example, the following assistant imports an Anthropic model and defines an Ollama DeepSeek one. + +```yaml title="Assistant models section" +models: + - uses: anthropic/claude-3.5-sonnet # an imported model block + - model: deepseek-reasoner # an explicit model block + provider: ollama +``` + +### Inputs + +Blocks can be passed user inputs, including hub secrets and raw text values. To create a block that has an input, use mustache templating as follows: + +```yaml title="Block config.yaml" +name: myprofile/custom-model +models: + - name: My Favorite Model + provider: anthropic + apiKey: ${{ inputs.ANTHROPIC_API_KEY }} + defaultCompletionOptions: + temperature: ${{ inputs.TEMP }} +``` + +Which can then be imported like + +```yaml title="Assistant config.yaml" +name: myprofile/custom-assistant +models: + - uses: myprofile/custom-model + with: + ANTHROPIC_API_KEY: ${{ secrets.MY_ANTHROPIC_API_KEY }} + TEMP: 0.9 +``` + +Note that hub secrets can be passed as inputs, using the a similar mustache format: `secrets.SECRET_NAME`. + +### Overrides + +Block properties can be also be directly overriden using `override`. For example: + +```yaml title="Assistant config.yaml" +name: myprofile/custom-assistant +models: + - uses: myprofile/custom-model + with: + ANTHROPIC_API_KEY: ${{ secrets.MY_ANTHROPIC_API_KEY }} + TEMP: 0.9 + override: + roles: + - chat +``` + +## Properties Below are details for each property that can be set in `config.yaml`. -:::info -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.** -## Properties - The top-level properties in the `config.yaml` configuration file are: - [`name`](#name) (**required**) - - [`version`](#version) (**required**) +- [`schema`](#schema) (**required**) - [`models`](#models) - [`context`](#context) - [`rules`](#rules) - [`prompts`](#prompts) - [`docs`](#docs) - - - [`mcpServers`](#mcpservers) +- [`data`](#data) --- @@ -44,10 +112,16 @@ The `name` property specifies the name of your project or configuration. name: MyProject ``` +--- + ### `version` The `version` property specifies the version of your project or configuration. +### `schema` + +The `schema` property specifies the schema version used for the `config.yaml`, e.g. `v1` + --- ### `models` @@ -59,7 +133,12 @@ The `models` section defines the language models used in your configuration. Mod - `name` (**required**): A unique name to identify the model within your configuration. - `provider` (**required**): The provider of the model (e.g., `openai`, `ollama`). - `model` (**required**): The specific model name (e.g., `gpt-4`, `starcoder`). -- `roles`: An array specifying the roles this model can fulfill, such as `chat`, `autocomplete`, `embed`, `rerank`, `edit`, `apply`, `summarize`. +- `roles`: An array specifying the roles this model can fulfill, such as `chat`, `autocomplete`, `embed`, `rerank`, `edit`, `apply`, `summarize`. The default value is `[chat, edit, apply, summarize]`. Note that the `summarize` role is not currently used. +- `embedOptions`: If the model includes role `embed`, these settings apply for embeddings: + + - `maxChunkSize`: Maximum tokens per document chunk. Minimum is 128 tokens. + - `maxBatchSize`: Maximum number of chunks per request. Minimum is 1 chunk. + - `defaultCompletionOptions`: Default completion options for model settings. **Properties:** @@ -148,6 +227,9 @@ Example ```yaml title="config.yaml" rules: + - uses: myprofile/my-mood-setter + with: + MOOD: happy - Always annotate Python functions with their parameter and return types - Always write Google style docstrings for functions and classes ``` @@ -195,25 +277,6 @@ docs: --- - - ### `mcpServers` @@ -239,21 +302,38 @@ mcpServers: - /Users/NAME/test.db ``` - --- @@ -264,8 +344,15 @@ Putting it all together, here's a complete example of a `config.yaml` configurat ```yaml title="config.yaml" name: MyProject version: 0.0.1 +schema: v1 models: + - uses: anthropic/claude-3.5-sonnet + with: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + override: + defaultCompletionOptions: + temperature: 0.8 - name: GPT-4 provider: openai model: gpt-4 @@ -298,6 +385,7 @@ prompts: description: Unit test a function prompt: | Please write a complete suite of unit tests for this function. You should use the Jest testing framework. The tests should cover all possible edge cases and should be as thorough as possible. You should also include a description of each test case. + - uses: myprofile/my-favorite-prompt context: - provider: diff @@ -318,6 +406,15 @@ mcpServers: - dev env: PORT: "3000" + +data: + - name: My Private Company + destination: https://mycompany.com/ingest + schema: 0.2.0 + level: noCode + events: + - autocomplete + - chatInteraction ``` ## Using YAML anchors to avoid config duplication @@ -338,26 +435,26 @@ model_defaults: &model_defaults apiBase: https://api.example.com/llm models: -- name: mistral - <<: *model_defaults - model: mistral-7b-instruct - roles: - - chat - - edit + - name: mistral + <<: *model_defaults + model: mistral-7b-instruct + roles: + - chat + - edit -- name: qwen2.5-coder-7b-instruct - <<: *model_defaults - model: qwen2.5-coder-7b-instruct - roles: - - chat - - edit + - name: qwen2.5-coder-7b-instruct + <<: *model_defaults + model: qwen2.5-coder-7b-instruct + roles: + - chat + - edit -- name: qwen2.5-coder-7b - <<: *model_defaults - model: qwen2.5-coder-7b - useLegacyCompletionsEndpoint: false - roles: - - autocomplete + - name: qwen2.5-coder-7b + <<: *model_defaults + model: qwen2.5-coder-7b + useLegacyCompletionsEndpoint: false + roles: + - autocomplete ``` ### Fully deprecated settings diff --git a/docs/docusaurus.config.js b/docs/docusaurus.config.js index c97113a0a..8216da215 100644 --- a/docs/docusaurus.config.js +++ b/docs/docusaurus.config.js @@ -107,6 +107,13 @@ const config = { label: "Reference", href: "/reference", }, + { + type: "docSidebar", + sidebarId: "hubSidebar", + position: "left", + label: "Hub", + href: "/hub/introduction", + }, { to: "https://github.com/continuedev/continue", label: "GitHub", @@ -193,6 +200,30 @@ const config = { "@docusaurus/plugin-client-redirects", { redirects: [ + { + to: "/hub/introduction", + from: "/hub", + }, + { + to: "/hub/governance/org-permissions", + from: "/hub/governance", + }, + { + to: "/hub/secrets/secret-types", + from: "/hub/secrets", + }, + { + to: "/hub/assistants/intro", + from: "/hub/assistants", + }, + { + to: "/hub/blocks/intro", + from: "/hub/blocks", + }, + { + to: "/customize/overview", + from: "/customize", + }, { to: "/customize/overview", from: "/customization", @@ -206,8 +237,24 @@ const config = { // from: "/getting-started", // }, { - to: "/customize/model-types", - from: "/setup/overview", + to: "/customize/model-roles", + from: ["/customize/model-types", "/setup/overview"], + }, + { + to: "/customize/model-roles/embeddings", + from: "/customize/model-types/embeddings", + }, + { + to: "/customize/model-roles/autocomplete", + from: "/customize/model-types/autocomplete", + }, + { + to: "/customize/model-roles/chat", + from: "/customize/model-types/chat", + }, + { + to: "/customize/model-roles/reranking", + from: "/customize/model-types/reranking", }, { to: "/getting-started/overview", @@ -255,11 +302,11 @@ const config = { }, { to: "/customize/context-providers", - from: "/customization/context-providers", + from: ["/customization/context-providers"], }, { - to: "/customize/development-data", - from: "/development-data", + to: "/customize/deep-dives/development-data", + from: ["/development-data", "/customize/development-data"], }, { to: "/customize/deep-dives/docs", @@ -282,7 +329,7 @@ const config = { from: "/reference/Model Providers/deepseek", }, { - to: "/customize/model-providers/free-trial", + to: "/customize/model-providers", from: "/reference/Model Providers/freetrial", }, { 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 aeadb68f8..2ffc4d0f2 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](../json-reference.md) 并添加它们到 `slashCommands` 列表中。 +Continue 有一个大的内置斜杠命令库,但是当你首次安装时,我们只显示最常用的一些,比如 "/edit", "/comment" 和 "/share" 。为了添加更多的 action ,你可以打开 [config.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 14a062a50..143645591 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`](../json-reference.md) 提供少量的参数,对于你的特定需求和硬件能力,可以调整找到建议质量和系统性能之间的最佳平衡: +Continue 在 [`config.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 a7d9c3173..ba803e149 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 @@ -49,4 +49,4 @@ Codestral 的 API key 和通常的 Mistral API 是不同的。如果你使用 Co ## 其他体验 -有很多更多的模型或提供者可以用来补全。在 [这里](../customize/model-types/autocomplete.md) 查看它们。 +有很多更多的模型或提供者可以用来补全。在 [这里](../customize/model-roles/autocomplete.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 b6360c8d3..32f9ab63f 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 @@ -5,11 +5,11 @@ keywords: [模型] sidebar_position: 2 --- -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; :::info -这个页面推荐聊天的模型和提供者。在 [这里](../json-reference.md) 了解更多关于如何设置你的 `config.json` 。 +这个页面推荐聊天的模型和提供者。在 [这里](../reference.md) 了解更多关于如何设置你的 `config.json` 。 ::: ## 最好的总体体验 @@ -111,16 +111,16 @@ import TabItem from "@theme/TabItem"; ] ``` -### 来自 Google 的 Gemini 1.5 Pro +### 来自 Google 的 Gemini 2.0 Flash -如果你倾向于使用来自 [Google](../customize/model-providers/top-level/gemini.md) 的模型,那么我们推荐 Gemini 1.5 Pro 。 +如果你倾向于使用来自 [Google](../customize/model-providers/top-level/gemini.md) 的模型,那么我们推荐 Gemini 2.0 Flash。 ```json title="config.json" "models": [ { - "title": "Gemini 1.5 Pro", + "title": "Gemini 2.0 Flash", "provider": "gemini", - "model": "gemini-1.5-pro-latest", + "model": "gemini-2.0-flash", "apiKey": "[GEMINI_API_KEY]" } ] @@ -193,4 +193,4 @@ import TabItem from "@theme/TabItem"; ## 其他体验 -除了以上提到的这些,还有更多的模型和提供者,你可以使用来聊天。在 [这里](../customize/model-types/chat.md) 了解更多。 +除了以上提到的这些,还有更多的模型和提供者,你可以使用来聊天。在 [这里](../customize/model-roles/chat.md) 了解更多。 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 e6774dfe5..985a66809 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 } ``` -如果你对可用选项不熟悉,你可以在 [这里](../../json-reference.md) 查找完整的参考。 +如果你对可用选项不熟悉,你可以在 [这里](../../reference.md) 查找完整的参考。 ## 配置选项 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/development-data.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/development-data.md similarity index 100% rename from docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/development-data.md rename to docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/development-data.md diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/cohere.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/cohere.md index 274c1942d..e69029b00 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/cohere.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/cohere.md @@ -23,7 +23,7 @@ Cohere 当前没有提供任何自动补全模型。 -[点击这里](../../model-types/autocomplete.md) 查看自动补全模型提供者列表。 +[点击这里](../../model-roles/autocomplete.md) 查看自动补全模型提供者列表。 ## 嵌入模型 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/free-trial.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/free-trial.md deleted file mode 100644 index 746038bdf..000000000 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/free-trial.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: 免费试用 -slug: ../free-trial ---- - -`"免费试用"` 提供者提供新用户在 Continue 快速尝试最好的体验,通过一个安全的代理服务器使用我们的 API key 。为了避免滥用,我们要求你使用 Github 登录,你可以在下面看到更多。 - -虽然 Continue 扩展总是免费使用,我们不能为所有用户提供无限免费 LLM 使用。你最终需要: - -1. 选择一个开源模型免费使用 [本地的](../top-level/ollama.md), 或者 -2. 添加你自己的 [Anthropic](../top-level/anthropic.md) API key 或者 [其他的 LLM 提供者](/customize/model-providers) - -## 试用的常见问题 - -Continue 要求免费试用用户登录,让我们可以避免我们的 API 端点滥用。如果你不使用免费试用,我们不会要求你登录。 - -### 我如何停止 Continue 询问我登录? - -移除 "models" 列表或 "tabAutocompleteModel" 中 `"provider": "free-trial"` 的所有模型,我们将不会再请求登录。 - -### 什么信息被收集? - -Continue 使用你的 GitHub 用户名,没有其他信息,唯一的目的是限制请求。 - -### 如果我没有登录,会发生什么? - -如果你没有登录,你仍然可以使用 Continue 的每个特性,你只需要提供自己的 LLM ,不论使用 API key 或运行本地的模型。 - -### 遥测与登录有什么关系? - -它没有。我们没有关联你的 GitHub 用户名到遥测数据。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/nvidia.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/nvidia.md index 049ff7754..6d8e1269b 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/nvidia.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/nvidia.md @@ -29,7 +29,7 @@ We recommend configuring **Nemotron-4-340B-Instruct** as your chat model. NVIDIA currently does not offer any autocomplete models. -[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers. +[Click here](../../model-roles/autocomplete.md) to see a list of autocomplete model providers. ## Embeddings model @@ -49,4 +49,4 @@ We recommend configuring **NVIDIA Retrieval QA Mistral 7B** as your embeddings m NVIDIA currently does not offer any reranking models. -[Click here](../../model-types/reranking.md) to see a list of reranking model providers. +[Click here](../../model-roles/reranking.md) to see a list of reranking model providers. diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/anthropic.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/anthropic.md index 7380e7673..f419f0def 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/anthropic.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/anthropic.md @@ -28,19 +28,19 @@ slug: ../anthropic Anthropic 当前没有提供任何自动补全模型。 -[点击这里](../../model-types/autocomplete.md) 查看自动补全模型提供者列表。 +[点击这里](../../model-roles/autocomplete.md) 查看自动补全模型提供者列表。 ## 嵌入模型 Anthropic 当前没有提供任何嵌入模型。 -[点击这里](../../model-types/embeddings.md) 查看嵌入模型提供者列表。 +[点击这里](../../model-roles/embeddings.md) 查看嵌入模型提供者列表。 ## 重排序模型 Anthropic 当前没有提供任何重排序模型。 -[点击这里](../../model-types/reranking.md) 查看重排序模型提供者列表。 +[点击这里](../../model-roles/reranking.md) 查看重排序模型提供者列表。 ## 提示词缓存 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/azure.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/azure.md index 6fa50faaa..3a5a48614 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/azure.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/azure.md @@ -57,7 +57,7 @@ slug: ../azure Azure OpenAI 当前没有提供任何重排序模型。 -[点击这里](../../model-types/reranking.md) 查看重排序模型列表。 +[点击这里](../../model-roles/reranking.md) 查看重排序模型列表。 ## 隐私 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/bedrock.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/bedrock.md index a1a4d6234..e13bc715d 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/bedrock.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/bedrock.md @@ -25,7 +25,7 @@ slug: ../bedrock Bedrock 当前不支持任何自动补全模型。 -[点击这里](../../model-types/autocomplete.md) 查看自动补全模型提供者列表。 +[点击这里](../../model-roles/autocomplete.md) 查看自动补全模型提供者列表。 ## 嵌入模型 @@ -46,7 +46,7 @@ Bedrock 当前不支持任何自动补全模型。 Bedrock 当前没有任何重排序模型。 -[点击这里](../../model-types/reranking.md) 查看重排序模型提供者列表。 +[点击这里](../../model-roles/reranking.md) 查看重排序模型提供者列表。 ## 认证 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/deepseek.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/deepseek.md index 61e01e701..10c0baeb8 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/deepseek.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/deepseek.md @@ -42,10 +42,10 @@ slug: ../deepseek DeepSeek 当前没有提供任何嵌入模型。 -[点击这里](../../model-types/embeddings.md) 查看嵌入模型提供者列表。 +[点击这里](../../model-roles/embeddings.md) 查看嵌入模型提供者列表。 ## 重排序模型 DeepSeek 当前没有提供任何重排序模型。 -[点击这里](../../model-types/reranking.md) 查看重排序模型提供者列表。 +[点击这里](../../model-roles/reranking.md) 查看重排序模型提供者列表。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/gemini.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/gemini.md index 13778e379..8caec3c1f 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/gemini.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/gemini.md @@ -28,7 +28,7 @@ slug: ../gemini Gemini 当前没有提供任何自动补全模型。 -[点击这里](../../model-types/autocomplete.md) 查看自动补全模型提供者列表。 +[点击这里](../../model-roles/autocomplete.md) 查看自动补全模型提供者列表。 ## 嵌入模型 @@ -48,4 +48,4 @@ Gemini 当前没有提供任何自动补全模型。 Gemini 当前没有提供任何重排序模型。 -[点击这里](../../model-types/reranking.md) 查看重排序模型提供者列表。 +[点击这里](../../model-roles/reranking.md) 查看重排序模型提供者列表。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/mistral.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/mistral.md index 2e853affc..8b9963fbb 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/mistral.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/mistral.md @@ -57,4 +57,4 @@ slug: ../mistral Mistral 当前没有提供任何重排序模型。 -[点击这里](../../model-types/reranking.md) 查看重排序模型提供者列表。 +[点击这里](../../model-roles/reranking.md) 查看重排序模型提供者列表。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/ollama.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/ollama.md index 9119116ef..69ea9752d 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/ollama.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/ollama.md @@ -50,4 +50,4 @@ slug: ../ollama Ollama 当前没有提供任何重排序模型。 -[点击这里](../../model-types/reranking.md) 查看重排序模型提供者列表。 +[点击这里](../../model-roles/reranking.md) 查看重排序模型提供者列表。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/openai.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/openai.md index ba84723da..18f3312a7 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/openai.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/openai.md @@ -28,7 +28,7 @@ slug: ../openai OpenAI 当前没有提供任何自动补全模型。 -[点击这里](../../model-types/autocomplete.md) 查看自动补全模型提供者列表。 +[点击这里](../../model-roles/autocomplete.md) 查看自动补全模型提供者列表。 ## 嵌入模型 @@ -48,7 +48,7 @@ OpenAI 当前没有提供任何自动补全模型。 OpenAI 当前没有提供任何重排序模型。 -[点击这里](../../model-types/reranking.md) 查看重排序模型提供者列表。 +[点击这里](../../model-roles/reranking.md) 查看重排序模型提供者列表。 ## OpenAI 兼容服务器 / API diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/vertexai.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/vertexai.md index daf966d9e..0a280cda8 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/vertexai.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/vertexai.md @@ -62,4 +62,4 @@ We recommend configuring **text-embedding-004** as your embeddings model. +[Click here](../../model-roles/reranking.md) to see a list of reranking model providers. --> 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 c920114b0..866e7108d 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 @@ -30,19 +30,19 @@ We recommend configuring **grok-beta** as your chat model. xAI currently does not offer any autocomplete models. -[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers. +[Click here](../../model-roles/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. +[Click here](../../model-roles/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. +[Click here](../../model-roles/reranking.md) to see a list of reranking model providers. ## Legacy Completions diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-types/autocomplete.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-roles/autocomplete.md similarity index 100% rename from docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-types/autocomplete.md rename to docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-roles/autocomplete.md diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-types/chat.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-roles/chat.md similarity index 92% rename from docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-types/chat.md rename to docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-roles/chat.md index c49051360..a294cfaa1 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-types/chat.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-roles/chat.md @@ -14,5 +14,5 @@ sidebar_position: 2 否则,以下是一些最好的选择: - [GPT-4o](../model-providers/top-level/openai.md) -- [Gemini 1.5 Pro](../model-providers/top-level/gemini.md) +- [Gemini 2.0 Flash](../model-providers/top-level/gemini.md) - [Llama3.1 405B](../tutorials/llama3.1.md) diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-types/embeddings.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-roles/embeddings.md similarity index 100% rename from docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-types/embeddings.md rename to docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-roles/embeddings.md diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-types/reranking.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-roles/reranking.md similarity index 93% rename from docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-types/reranking.md rename to docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-roles/reranking.md index 4e530b985..b5f1c835a 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-types/reranking.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-roles/reranking.md @@ -78,15 +78,3 @@ Voyage AI 提供代码最好的重排序模型, 使用他们的 `rerank-1` 模 } } ``` - -### 免费试用 (Voyage AI) - -Continue 提供 Voyage AI 重排序模型的免费试用。 - -```json title="config.json" -{ - "reranker": { - "name": "free-trial" - } -} -``` 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 0d94978c1..1c5d041e2 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 ,随着你的输入来查看有效的选项,或者你可以查看 [完整参考](../json-reference.md) 。 +要打开 `config.json` ,在 Continue 聊天侧边栏的右下角点击 "齿轮" 图标。当编辑这个文件时,你可以使用 IntelliSense ,随着你的输入来查看有效的选项,或者你可以查看 [完整参考](../reference.md) 。 当你保存 `config.json` 时, Continue 会自动地刷新,应用你的变更。 ## 每个工作区的配置 -如果你想要限制指定的配置到一个特定的工作区,你可以添加一个 `.continuerc.json` 到你的项目根目录。它有和 `config.json` 相同的 [定义](../json-reference.md) ,会自动地应用到本地 `config.json` 之上。 +如果你想要限制指定的配置到一个特定的工作区,你可以添加一个 `.continuerc.json` 到你的项目根目录。它有和 `config.json` 相同的 [定义](../reference.md) ,会自动地应用到本地 `config.json` 之上。 ## 可编程的配置 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 f0db33bbc..07a0a6c65 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`](../json-reference.md) 为编辑配置一个不同的模型。 +你可以通过更新你的 [`config.json`](../reference.md) 为编辑配置一个不同的模型。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/reference.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/reference.md index 1252bd2fd..c8bb5c305 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/reference.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/reference.md @@ -111,13 +111,13 @@ 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 +- `provider` (**required**): Specifies the embeddings provider, with options including `transformers.js`, `ollama`, `openai`, `cohere`, `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. +- `maxEmbeddingChunkSize`: Maximum tokens per document chunk. Minimum is 128 tokens. +- `maxEmbeddingBatchSize`: Maximum number of chunks per request. Minimum is 1 chunk. (AWS ONLY) @@ -132,8 +132,8 @@ Example: "provider": "openai", "model": "text-embedding-ada-002", "apiKey": "", - "maxChunkSize": 256, - "maxBatchSize": 5 + "maxEmbeddingChunkSize": 256, + "maxEmbeddingBatchSize": 5 } } ``` @@ -149,7 +149,7 @@ Parameters that control the behavior of text generation and completion settings. - `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. +- `frequencyPenalty`: 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`). @@ -206,7 +206,7 @@ Configuration for the reranker model used in response ranking. **Properties:** -- `name` (**required**): Reranker name, e.g., `cohere`, `voyage`, `llm`, `free-trial`, `huggingface-tei` +- `name` (**required**): Reranker name, e.g., `cohere`, `voyage`, `llm`, `huggingface-tei` - `params`: - `model`: Model name - `apiKey`: Api key diff --git a/docs/sidebars.js b/docs/sidebars.js index bb7f80604..0e83628a4 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -96,22 +96,18 @@ const sidebars = { }, { type: "category", - label: "Model types", + label: "Model roles", link: { - slug: "/customize/model-types", + slug: "/customize/model-roles", type: "generated-index", }, items: [ { type: "autogenerated", - dirName: "customize/model-types", + dirName: "customize/model-roles", }, ], }, - "customize/context-providers", - "customize/slash-commands", - "customize/tools", - "customize/development-data", { type: "category", label: "Deep dives", @@ -140,20 +136,44 @@ const sidebars = { }, { type: "link", - label: "JSON Reference", - href: "/json-reference", + label: "YAML Reference", + href: "/yaml-reference", }, "customize/changelog", - // { - // type: "link", - // label: "YAML Reference", - // href: "/yaml-reference", - // }, - // { - // type: "link", - // label: "YAML Migration", - // href: "/yaml-migration", - // }, + ], + hubSidebar: [ + "hub/introduction", + { + type: "category", + label: "Assistants", + items: [ + "hub/assistants/intro", + "hub/assistants/use-an-assistant", + "hub/assistants/create-an-assistant", + "hub/assistants/edit-an-assistant", + ], + }, + { + type: "category", + label: "Blocks", + items: [ + "hub/blocks/intro", + "hub/blocks/block-types", + "hub/blocks/use-a-block", + "hub/blocks/create-a-block", + "hub/blocks/bundles", + ], + }, + { + type: "category", + label: "Secrets", + items: ["hub/secrets/secret-types", "hub/secrets/secret-resolution"], + }, + { + type: "category", + label: "Governance", + items: ["hub/governance/org-permissions", "hub/governance/pricing"], + }, ], }; diff --git a/docs/static/img/actions.gif b/docs/static/img/actions.gif index 3a90748f1..1ad37ad93 100644 Binary files a/docs/static/img/actions.gif and b/docs/static/img/actions.gif differ diff --git a/docs/static/img/autocomplete.gif b/docs/static/img/autocomplete.gif index 7340b3cb9..cede26acf 100644 Binary files a/docs/static/img/autocomplete.gif and b/docs/static/img/autocomplete.gif differ diff --git a/docs/static/img/chat.gif b/docs/static/img/chat.gif index 2979f6c28..f9eedc300 100644 Binary files a/docs/static/img/chat.gif and b/docs/static/img/chat.gif differ diff --git a/docs/static/img/edit.gif b/docs/static/img/edit.gif index 286cf2e5c..a1629930c 100644 Binary files a/docs/static/img/edit.gif and b/docs/static/img/edit.gif differ diff --git a/docs/static/img/hub/assistant-create-page.png b/docs/static/img/hub/assistant-create-page.png new file mode 100644 index 000000000..2d70f956e Binary files /dev/null and b/docs/static/img/hub/assistant-create-page.png differ diff --git a/docs/static/img/hub/assistant-create-sidebar.png b/docs/static/img/hub/assistant-create-sidebar.png new file mode 100644 index 000000000..159806d31 Binary files /dev/null and b/docs/static/img/hub/assistant-create-sidebar.png differ diff --git a/docs/static/img/hub/assistant-create-yaml.png b/docs/static/img/hub/assistant-create-yaml.png new file mode 100644 index 000000000..6806c808c Binary files /dev/null and b/docs/static/img/hub/assistant-create-yaml.png differ diff --git a/docs/static/img/hub/assistant-extension-select.png b/docs/static/img/hub/assistant-extension-select.png new file mode 100644 index 000000000..e1365d304 Binary files /dev/null and b/docs/static/img/hub/assistant-extension-select.png differ diff --git a/docs/static/img/hub/assistant-new-button.png b/docs/static/img/hub/assistant-new-button.png new file mode 100644 index 000000000..d6088a061 Binary files /dev/null and b/docs/static/img/hub/assistant-new-button.png differ diff --git a/docs/static/img/hub/assistant-remix-button.png b/docs/static/img/hub/assistant-remix-button.png new file mode 100644 index 000000000..02c9d34ef Binary files /dev/null and b/docs/static/img/hub/assistant-remix-button.png differ diff --git a/docs/static/img/hub/block-inputs.png b/docs/static/img/hub/block-inputs.png new file mode 100644 index 000000000..9af87002c Binary files /dev/null and b/docs/static/img/hub/block-inputs.png differ diff --git a/docs/static/img/hub/block-new-button.png b/docs/static/img/hub/block-new-button.png new file mode 100644 index 000000000..456db04a9 Binary files /dev/null and b/docs/static/img/hub/block-new-button.png differ diff --git a/docs/static/img/hub/block-new-page.png b/docs/static/img/hub/block-new-page.png new file mode 100644 index 000000000..9addc9238 Binary files /dev/null and b/docs/static/img/hub/block-new-page.png differ diff --git a/docs/static/img/hub/block-remix-button.png b/docs/static/img/hub/block-remix-button.png new file mode 100644 index 000000000..16a682e9d Binary files /dev/null and b/docs/static/img/hub/block-remix-button.png differ diff --git a/docs/static/img/hub/bundle-create-page.png b/docs/static/img/hub/bundle-create-page.png new file mode 100644 index 000000000..693070326 Binary files /dev/null and b/docs/static/img/hub/bundle-create-page.png differ diff --git a/docs/static/img/hub/bundle-new-button.png b/docs/static/img/hub/bundle-new-button.png new file mode 100644 index 000000000..60ccc23d6 Binary files /dev/null and b/docs/static/img/hub/bundle-new-button.png differ diff --git a/docs/static/img/hub/hub-onboarding-card.png b/docs/static/img/hub/hub-onboarding-card.png new file mode 100644 index 000000000..8c75631fe Binary files /dev/null and b/docs/static/img/hub/hub-onboarding-card.png differ diff --git a/docs/static/img/hub/models-page.png b/docs/static/img/hub/models-page.png new file mode 100644 index 000000000..647504941 Binary files /dev/null and b/docs/static/img/hub/models-page.png differ diff --git a/docs/static/img/settings-model-roles.png b/docs/static/img/settings-model-roles.png new file mode 100644 index 000000000..7a2d24407 Binary files /dev/null and b/docs/static/img/settings-model-roles.png differ diff --git a/extensions/intellij/.run/Prompt Logs.run.xml b/extensions/intellij/.run/Prompt Logs.run.xml index ce8c399dd..7bee897b2 100644 --- a/extensions/intellij/.run/Prompt Logs.run.xml +++ b/extensions/intellij/.run/Prompt Logs.run.xml @@ -1,6 +1,6 @@ -