diff --git a/.continue/prompts/core-unit-test.prompt b/.continue/prompts/core-unit-test.prompt new file mode 100644 index 000000000..42ecef7bb --- /dev/null +++ b/.continue/prompts/core-unit-test.prompt @@ -0,0 +1,41 @@ +name: Write Core Unit Test +description: Generate unit tests for core utilities +--- +Write jest tests for the provided code. +Use jest version ^29 (e.g. jest 29.7.0) + +Use best practices. Be clear and consise. +Aim for 100% code coverage where reasonable. +Multiple tests can be written, split up tests for best clarity and readability. +Only use typescript, and if the file/code is not typescript, warn the user. +IMPORTANT Use ESM to import modules, do NOT use `require` anywhere +Tests are to be described in an adjacent file with a path identical except for a `.test.ts` rather than a `.ts` file extension +Use double quotes (or backticks if needed) for strings + +The code being tested is used in IDE extensions, and it: +- accesses code workspaces through the IDE ("workspace directories") +- persists extension-related data to the the local machine of the user ("global directory"), and +- uses configuration via a `ConfigHandler`, which is stored in either the global directory (default) or accesed via a remote "control plane" using the `ControlPlaneClient` + +Jest testing setup includes +- @core/test/jest.global-setup.ts initializes a temporary global directory, which is where files that store persisted extension data live. +- @core/test/testDir.ts provides utils for creating and working with the temporary workspace directory. Use `setUpTestDir` and `tearDownTestDir` explicitly in tests that work with workspace files +- @core/test/jest.setup-after-env.ts gives tests access to node and jest globals + +@core/test/fixtures.ts provides fixtures that should be used in tests to emulate extension behavior +- import `testIde` for IDE/workspace operations +- import `testConfigHandler` for any ConfigHandler needs +- import `testControlPlaneClient` for control plane operations +- import `ideSettingsPromise` for any IdeSettings needs +- import `testLLM` for any ILLM/BaseLLM needs. Set the `completion` property to the desired completion, e.g. `testLLM.completion = "Desired completion";` + +Do NOT write tests for any files in `core/test`, only use them as helpers for testing other files. If no other files are provided, warn the user and write no tests. + +IMPORTANT: Do NOT mock the fixtures above other than using `jest.spyOn`. DO mock 3rd party modules, etc. when sensible. +Instead, generate actual mock files and data for operations +Pure mocks should only be used to emulate specific network responses/error or hard-to-duplicate errors, or to prevent long-duration tests + +Additional types can be imported from @core/index.d.ts +If any needed types, functions, constants, or classes are still not found, warn the user and do not generate tests. + +Write the comment "// Generated by continue" at the top of the generated code/file (not the filepath) \ No newline at end of file diff --git a/.continue/prompts/core-util-test.prompt b/.continue/prompts/core-util-test.prompt deleted file mode 100644 index 6cc7351a2..000000000 --- a/.continue/prompts/core-util-test.prompt +++ /dev/null @@ -1,27 +0,0 @@ -name: Write Core Utility Test -description: Generate unit tests for core utilities ---- -Write jest tests for the provided code. -Use jest version ^29 (e.g. jest 29.7.0) - -Use best practices. Be clear and consise. -Aim for 100% code coverage where reasonable. -Multiple tests can be written, split up tests for best clarity and readability. -Only use typescript, and if the file/code is not typescript, warn the user. -Use given types to generate mock data if needed. - -Additional types can be imported from @core/index.d.ts -If any needed type declaration is still not found, warn the user. - -Existing test fixtures can be found in @core/test/fixtures.ts -- import and use `testIde` for any IDE type needs -- import and use `testControlPlaneClient` for any ControlPlaneClient needs -- import and use `testConfigHandler` for any ConfigHandler needs -- import and use `ideSettingsPromise` for any IdeSettings needs - -Do NOT write tests for `core/test/util/fixtures.ts` or `core/index.d.ts`, only use them as helpers for testing other files. If no other files are attached, just warn the user. - -// This note is for if using edit mode to encourage it to create new files -The tests are to be put in a new file with the same filepath but with a .test.ts extension rather than a .ts extension -Avoid casting functions to the jest.Mock type. Instead, use `jest.mocked(fn)` -Use double quotes (or backticks if needed) for strings, and observe eslint import order standards \ No newline at end of file diff --git a/.github/auto_assign.yml b/.github/auto_assign.yml new file mode 100644 index 000000000..ed05df6f9 --- /dev/null +++ b/.github/auto_assign.yml @@ -0,0 +1,10 @@ +# Reference: https://github.com/marketplace/actions/auto-assign-action +addAssignees: true + +assignees: + - sestinj + - Patrick-Erichsen + - tomasz-stefaniak + - RomneyDa + +numberOfAssignees: 2 diff --git a/.github/workflows/auto-assign.yaml b/.github/workflows/auto-assign-issue.yaml similarity index 100% rename from .github/workflows/auto-assign.yaml rename to .github/workflows/auto-assign-issue.yaml diff --git a/.github/workflows/auto-assign-pr.yaml b/.github/workflows/auto-assign-pr.yaml new file mode 100644 index 000000000..4fd701a15 --- /dev/null +++ b/.github/workflows/auto-assign-pr.yaml @@ -0,0 +1,10 @@ +name: PR assignment +on: + pull_request: + types: [opened, ready_for_review] + +jobs: + add-reviews: + runs-on: ubuntu-latest + steps: + - uses: kentaro-m/auto-assign-action@v2.0.0 diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index 02bd2c333..b4e0dd677 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -4,90 +4,204 @@ on: pull_request: branches: - main - paths: - "extensions/vscode/**" - "core/**" - "gui/**" + - ".github/workflows**" jobs: - tsc-check: + install-root: runs-on: ubuntu-latest - steps: - # 1. Check-out repository - - name: Check-out repository - uses: actions/checkout@v4 - - # 2. Install npm dependencies - - name: Use Node.js from .nvmrc - uses: actions/setup-node@v4 + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" - - name: Cache root node_modules - uses: actions/cache@v3 + - uses: actions/cache@v3 with: path: node_modules - key: ${{ runner.os }}-node-${{ hashFiles('package-lock.json') }} + key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }} - - name: Cache extension node_modules - uses: actions/cache@v3 + - name: Install root dependencies + run: npm ci + + core-checks: + needs: install-root + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 with: - path: extensions/vscode/node_modules - key: ${{ runner.os }}-node-${{ hashFiles('extensions/vscode/package-lock.json') }} + node-version-file: ".nvmrc" - - name: Cache core node_modules - uses: actions/cache@v3 + - uses: actions/cache@v3 + with: + path: node_modules + key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }} + + - uses: actions/cache@v3 with: path: core/node_modules - key: ${{ runner.os }}-node-${{ hashFiles('core/package-lock.json') }} + key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }} - - name: Cache gui node_modules - uses: actions/cache@v3 - with: - path: gui/node_modules - key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }} - - - name: Cache binary node_modules - uses: actions/cache@v3 - with: - path: binary/node_modules - key: ${{ runner.os }}-node-${{ hashFiles('binary/package-lock.json') }} - - - name: root install - run: | - npm ci - - - name: extensions/vscode install - run: | - cd extensions/vscode - npm ci - env: - # https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333 - GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }} - - - name: core install + - name: Install core dependencies run: | cd core npm ci - - name: gui install + - name: Type check and lint + run: | + cd core + npx tsc --noEmit + npm run lint + env: + OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} + + gui-checks: + needs: [install-root, core-checks] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version-file: ".nvmrc" + + - uses: actions/cache@v3 + with: + path: node_modules + key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }} + + - uses: actions/cache@v3 + with: + path: core/node_modules + key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }} + + - uses: actions/cache@v3 + with: + path: gui/node_modules + key: ${{ runner.os }}-gui-node-modules-${{ hashFiles('gui/package-lock.json') }} + + - name: Install gui dependencies run: | cd gui npm ci - - name: binary install + - name: Type check + run: | + cd gui + npx tsc --noEmit + + binary-checks: + needs: [install-root, core-checks] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version-file: ".nvmrc" + + - uses: actions/cache@v3 + with: + path: node_modules + key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }} + + - uses: actions/cache@v3 + with: + path: core/node_modules + key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }} + + - uses: actions/cache@v3 + with: + path: binary/node_modules + key: ${{ runner.os }}-binary-node-modules-${{ hashFiles('binary/package-lock.json') }} + + - name: Install binary dependencies run: | cd binary npm ci - - name: extensions/vscode checks + - name: Type check + run: | + cd binary + npx tsc --noEmit + + vscode-checks: + needs: [install-root, core-checks] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version-file: ".nvmrc" + + - uses: actions/cache@v3 + with: + path: node_modules + key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }} + + - uses: actions/cache@v3 + with: + path: core/node_modules + key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }} + + - uses: actions/cache@v3 + with: + path: extensions/vscode/node_modules + key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }} + + - name: Install vscode dependencies + run: | + cd extensions/vscode + npm ci + env: + GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }} + + - name: Type check and lint run: | cd extensions/vscode npx tsc --noEmit npm run lint + core-tests: + needs: [core-checks] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version-file: ".nvmrc" + + - uses: actions/cache@v3 + with: + path: core/node_modules + key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }} + + - name: Run core tests + run: | + cd core + npm test + + vscode-tests: + needs: [vscode-checks, core-checks] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version-file: ".nvmrc" + + - uses: actions/cache@v3 + with: + path: extensions/vscode/node_modules + key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }} + + - uses: actions/cache@v3 + with: + path: core/node_modules + key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }} + - name: Install Xvfb for Linux and run e2e tests run: | sudo apt-get install -y xvfb # Install Xvfb @@ -97,29 +211,29 @@ jobs: npm run package npm run e2e:ci - - name: core checks - run: | - cd core - npm ci - npx tsc --noEmit - npm run lint + gui-tests: + needs: [gui-checks, core-checks] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version-file: ".nvmrc" + + - uses: actions/cache@v3 + with: + path: gui/node_modules + key: ${{ runner.os }}-gui-node-modules-${{ hashFiles('gui/package-lock.json') }} + + - uses: actions/cache@v3 + with: + path: core/node_modules + key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }} + + - name: Install GUI dependencies + run: cd gui && npm ci env: - OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} - - - name: gui checks - run: | - cd gui - npx tsc --noEmit - - - name: binary checks - run: | - cd binary - npx tsc --noEmit - - - name: Run core tests - run: | - cd core - npm test + GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }} - name: Run gui tests run: | diff --git a/.gitignore b/.gitignore index 7c18e6b16..4a588442a 100644 --- a/.gitignore +++ b/.gitignore @@ -152,7 +152,6 @@ Icon Icon? .continuerc.json -.prompts/ .aider* notes.md @@ -167,6 +166,4 @@ extensions/intellij/.idea/** extensions/intellij/bin extensions/.continue-debug/ -*.vsix - -binary/.continue \ No newline at end of file +*.vsix \ No newline at end of file diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 8331b5380..968b98964 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -1,12 +1,29 @@ { "version": "2.0.0", "tasks": [ + { + "label": "tsc:watch", + "type": "npm", + "script": "tsc:watch", + "isBackground": true, + "problemMatcher": { + "base": "$tsc-watch", + "background": { + "activeOnStart": true, + "beginsPattern": "Starting compilation in watch mode...", + "endsPattern": "Found 0 errors" + } + }, + "presentation": { + "revealProblems": "onProblem" + } + }, // Compile and bundle the extension { "label": "vscode-extension:build", "dependsOn": [ - // To detect compile errors - "vscode-extension:tsc", + // TSC type checking + "tsc:watch", // To build the React app that is used in the extension "vscode-extension:continue-ui:build", // // To bundle the code the same way we do for publishing @@ -46,17 +63,6 @@ } ] }, - { - "label": "vscode-extension:tsc", - "type": "npm", - "script": "tsc", - "path": "extensions/vscode", - "problemMatcher": ["$tsc"], - "presentation": { - "revealProblems": "onProblem", - "clear": true - } - }, // Build the React app. It gets bundled into the extension as a file resource and has a seprate build step { "label": "vscode-extension:continue-ui:build", @@ -80,7 +86,7 @@ // Build the extension "vscode-extension:build", // To detect compile errors - this type checks both the extension and the tests - "vscode-extension:tsc", + "tsc:watch", "vscode-extension:tests:esbuild" ] }, diff --git a/binary/package-lock.json b/binary/package-lock.json index c855ad5d1..6f7c394d1 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -48,7 +48,9 @@ "@aws-sdk/client-sagemaker-runtime": "^3.621.0", "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.13", + "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", + "@continuedev/openai-adapters": "^1.0.10", "@modelcontextprotocol/sdk": "^1.0.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", @@ -81,7 +83,7 @@ "node-html-markdown": "^1.3.0", "ollama": "^0.4.6", "onnxruntime-node": "1.14.0", - "openai": "^4.20.1", + "openai": "^4.76.0", "p-limit": "^6.1.0", "partial-json": "^0.1.7", "pg": "^8.11.3", diff --git a/binary/src/IpcIde.ts b/binary/src/IpcIde.ts index ee2649c36..5c9ad1afe 100644 --- a/binary/src/IpcIde.ts +++ b/binary/src/IpcIde.ts @@ -1,5 +1,5 @@ import { TODO } from "core/util"; -import { MessageIde } from "core/util/messageIde"; +import { MessageIde } from "core/protocol/messenger/messageIde"; export class IpcIde extends MessageIde { constructor(messenger: TODO) { diff --git a/binary/src/IpcMessenger.ts b/binary/src/IpcMessenger.ts index 341372d8e..ec6f160c7 100644 --- a/binary/src/IpcMessenger.ts +++ b/binary/src/IpcMessenger.ts @@ -1,5 +1,5 @@ import { IProtocol } from "core/protocol/index.js"; -import { IMessenger, type Message } from "core/util/messenger"; +import { IMessenger, type Message } from "core/protocol/messenger"; import { ChildProcessWithoutNullStreams } from "node:child_process"; import * as fs from "node:fs"; import net from "node:net"; diff --git a/binary/src/TcpMessenger.ts b/binary/src/TcpMessenger.ts index 9dc506d15..ecd5d0d70 100644 --- a/binary/src/TcpMessenger.ts +++ b/binary/src/TcpMessenger.ts @@ -1,5 +1,5 @@ import { IProtocol } from "core/protocol"; -import { IMessenger, Message } from "core/util/messenger"; +import { IMessenger, Message } from "core/protocol/messenger"; import net from "net"; import { v4 as uuidv4 } from "uuid"; diff --git a/binary/src/index.ts b/binary/src/index.ts index 04be5de5a..df0a8520f 100644 --- a/binary/src/index.ts +++ b/binary/src/index.ts @@ -2,7 +2,7 @@ process.env.IS_BINARY = "true"; import { Command } from "commander"; import { Core } from "core/core"; import { FromCoreProtocol, ToCoreProtocol } from "core/protocol"; -import { IMessenger } from "core/util/messenger"; +import { IMessenger } from "core/protocol/messenger"; import { getCoreLogsPath, getPromptLogsPath } from "core/util/paths"; import fs from "node:fs"; import { IpcIde } from "./IpcIde"; diff --git a/binary/test/binary.test.ts b/binary/test/binary.test.ts index 3554aed27..f84b23a2d 100644 --- a/binary/test/binary.test.ts +++ b/binary/test/binary.test.ts @@ -2,8 +2,7 @@ import { SerializedContinueConfig } from "core"; // import Mock from "core/llm/llms/Mock.js"; import { FromIdeProtocol, ToIdeProtocol } from "core/protocol/index.js"; import FileSystemIde from "core/util/filesystem"; -import { IMessenger } from "core/util/messenger"; -import { ReverseMessageIde } from "core/util/reverseMessageIde"; +import { IMessenger } from "core/protocol/messenger"; import fs from "fs"; import { ChildProcessWithoutNullStreams, @@ -133,7 +132,7 @@ describe("Test Suite", () => { fs.mkdirSync(testDir); } const ide = new FileSystemIde(testDir); - const reverseIde = new ReverseMessageIde(messenger.on.bind(messenger), ide); + // const reverseIde = new ReverseMessageIde(messenger.on.bind(messenger), ide); // Wait for core to set itself up await new Promise((resolve) => setTimeout(resolve, 1000)); diff --git a/binary/tsconfig.json b/binary/tsconfig.json index 215a5aee7..9b3259730 100644 --- a/binary/tsconfig.json +++ b/binary/tsconfig.json @@ -7,7 +7,8 @@ "sourceMap": true, "rootDirs": ["src", "../core"], "allowJs": true, - "strict": true /* enable all strict type-checking options */, + "skipLibCheck": true, + "strict": true /* enable all strict tsc:watching options */, /* Additional Checks */ // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ diff --git a/core/.gitignore b/core/.gitignore index 7d8f1fa53..b34a983de 100644 --- a/core/.gitignore +++ b/core/.gitignore @@ -3,6 +3,5 @@ target **/.DS_Store npm-debug.log* .env -.continue-test -testDir +test/.continue-test coverage \ No newline at end of file diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index a6e1e551b..e37d8227c 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -3,7 +3,7 @@ import { TRIAL_FIM_MODEL } from "../config/onboarding.js"; import { IDE, ILLM } from "../index.js"; import OpenAI from "../llm/llms/OpenAI.js"; import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js"; -import { EXPERIMENTS, PosthogFeatureFlag, Telemetry } from "../util/posthog.js"; +import { PosthogFeatureFlag, Telemetry } from "../util/posthog.js"; import { shouldCompleteMultiline } from "./classification/shouldCompleteMultiline.js"; import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; @@ -59,6 +59,11 @@ export class CompletionProvider { return undefined; } + // Temporary fix for JetBrains autocomplete bug as described in https://github.com/continuedev/continue/pull/3022 + if (llm.model === undefined && llm.completionOptions?.model !== undefined) { + llm.model = llm.completionOptions.model; + } + // Ignore empty API keys for Mistral since we currently write // a template provider without one during onboarding if (llm.providerName === "mistral" && llm.apiKey === "") { diff --git a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts index 55cde067a..180c339e6 100644 --- a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts +++ b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts @@ -10,6 +10,7 @@ import { showWhateverWeHaveAtXMs, skipPrefixes, stopAtLines, + stopAtLinesExact, stopAtRepeatingLines, stopAtSimilarLine, streamWithNewLines, @@ -42,6 +43,12 @@ export class StreamTransformPipeline { let lineGenerator = streamLines(charGenerator); lineGenerator = stopAtLines(lineGenerator, fullStop); + const lineBelowCursor = this.getLineBelowCursor(helper); + if (lineBelowCursor.trim() !== "") { + lineGenerator = stopAtLinesExact(lineGenerator, fullStop, [ + lineBelowCursor, + ]); + } lineGenerator = stopAtRepeatingLines(lineGenerator, fullStop); lineGenerator = avoidEmptyComments( lineGenerator, diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts index aaeec1291..851dea88a 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts @@ -2,7 +2,6 @@ import { distance } from "fastest-levenshtein"; import { DiffLine } from "../../.."; import { LineStream } from "../../../diff/util"; -import { BRACKETS, BRACKETS_REVERSE } from "../BracketMatchingService"; export type LineFilter = (args: { lines: LineStream; @@ -270,6 +269,20 @@ export async function* stopAtLines( } } +export async function* stopAtLinesExact( + stream: LineStream, + fullStop: () => void, + linesToStopAt: string[], +): LineStream { + for await (const line of stream) { + if (linesToStopAt.some((stopAt) => line === stopAt)) { + fullStop(); + break; + } + yield line; + } +} + /** * Filters a LineStream, skipping specified prefixes on the first line. * @param {LineStream} lines - The input stream of lines. diff --git a/core/autocomplete/filtering/test/testCases.ts b/core/autocomplete/filtering/test/testCases.ts index 277c8cdc8..f83de1607 100644 --- a/core/autocomplete/filtering/test/testCases.ts +++ b/core/autocomplete/filtering/test/testCases.ts @@ -810,8 +810,7 @@ func main() {}`, }`, expectedCompletion: `string State string - ZipCode string -}`, + ZipCode string`, }, { @@ -1118,8 +1117,7 @@ impl Calculator { self.result /= number; } else { println!("Cannot divide by zero."); - } -}`, + }`, }, { description: "Should autocomplete Rust struct definition", @@ -1600,8 +1598,7 @@ interface User { age: number; }`, expectedCompletion: `mail: string; - age: number; -}`, + age: number;`, }, { description: "Should autocomplete TypeScript interface declarations", @@ -1853,8 +1850,7 @@ let john = { FirstName = "John"; LastName = "Doe"; Age = 30 }`, Address: string }`, expectedCompletion: ` - Address: string -}`, + Address: string`, }, { diff --git a/core/commands/util.test.ts b/core/commands/util.test.ts new file mode 100644 index 000000000..447ec0e60 --- /dev/null +++ b/core/commands/util.test.ts @@ -0,0 +1,149 @@ +import { ctxItemToRifWithContents } from "./util"; +import { ContextItemWithId, RangeInFileWithContents } from "../index"; + +describe("ctxItemToRifWithContents", () => { + it("should parse start and end lines from the item name when format is valid", () => { + const item: ContextItemWithId = { + id: { providerTitle: "testProvider", itemId: "1" }, + name: "myFunction(10-20)", + content: "function content", + description: "test description", + uri: { type: "file", value: "/path/to/file" }, + }; + + const expected: RangeInFileWithContents = { + filepath: "/path/to/file", + range: { + start: { line: 10, character: 0 }, + end: { line: 20, character: 0 }, + }, + contents: "function content", + }; + + const result = ctxItemToRifWithContents(item); + expect(result).toEqual(expected); + }); + + it("should set startLine and endLine to 0 when name format is invalid", () => { + const item: ContextItemWithId = { + id: { providerTitle: "testProvider", itemId: "2" }, + name: "myFunction", + content: "function content", + description: "test description", + uri: { type: "file", value: "/path/to/file" }, + }; + + const expected: RangeInFileWithContents = { + filepath: "/path/to/file", + range: { + start: { line: 0, character: 0 }, + end: { line: 0, character: 0 }, + }, + contents: "function content", + }; + + const result = ctxItemToRifWithContents(item); + expect(result).toEqual(expected); + }); + + it("should handle missing uri by setting filepath to empty string", () => { + const item: ContextItemWithId = { + id: { providerTitle: "testProvider", itemId: "3" }, + name: "myFunction(10-20)", + content: "function content", + description: "test description", + }; + + const expected: RangeInFileWithContents = { + filepath: "", + range: { + start: { line: 10, character: 0 }, + end: { line: 20, character: 0 }, + }, + contents: "function content", + }; + + const result = ctxItemToRifWithContents(item); + expect(result).toEqual(expected); + }); + + it("should handle uri with undefined value by setting filepath to empty string", () => { + const item: ContextItemWithId = { + id: { providerTitle: "testProvider", itemId: "4" }, + name: "myFunction(10-20)", + content: "function content", + description: "test description", + }; + + const expected: RangeInFileWithContents = { + filepath: "", + range: { + start: { line: 10, character: 0 }, + end: { line: 20, character: 0 }, + }, + contents: "function content", + }; + + const result = ctxItemToRifWithContents(item); + expect(result).toEqual(expected); + }); + + it("should handle invalid line numbers gracefully", () => { + const item: ContextItemWithId = { + id: { providerTitle: "testProvider", itemId: "6" }, + name: "myFunction(invalid-lines)", + content: "function content", + description: "test description", + uri: { type: "file", value: "/path/to/file" }, + }; + + const result = ctxItemToRifWithContents(item); + + expect(result.range.start.line).toBeNaN(); + expect(result.range.end.line).toBeNaN(); + }); + + it("should handle missing closing parenthesis in name", () => { + const item: ContextItemWithId = { + id: { providerTitle: "testProvider", itemId: "7" }, + name: "myFunction(10-20", + content: "function content", + description: "test description", + uri: { type: "file", value: "/path/to/file" }, + }; + + const expected: RangeInFileWithContents = { + filepath: "/path/to/file", + range: { + start: { line: 10, character: 0 }, + end: { line: 20, character: 0 }, + }, + contents: "function content", + }; + + const result = ctxItemToRifWithContents(item); + expect(result).toEqual(expected); + }); + + it("should handle name with multiple '-' characters", () => { + const item: ContextItemWithId = { + id: { providerTitle: "testProvider", itemId: "8" }, + name: "myFunction(10-20-30)", + content: "function content", + description: "test description", + uri: { type: "file", value: "/path/to/file" }, + }; + + const expected: RangeInFileWithContents = { + filepath: "/path/to/file", + range: { + start: { line: 10, character: 0 }, + end: { line: 20, character: 0 }, + }, + contents: "function content", + }; + + const result = ctxItemToRifWithContents(item); + expect(result).toEqual(expected); + }); +}); diff --git a/core/config/default.ts b/core/config/default.ts index 54f601b53..8662be678 100644 --- a/core/config/default.ts +++ b/core/config/default.ts @@ -95,14 +95,6 @@ export const defaultSlashCommandsJetBrains = [ export const defaultConfig: SerializedContinueConfig = { models: [DEFAULT_CHAT_MODEL_CONFIG], tabAutocompleteModel: DEFAULT_AUTOCOMPLETE_MODEL_CONFIG, - customCommands: [ - { - name: "test", - prompt: - "{{{ input }}}\n\nWrite a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.", - description: "Write unit tests for highlighted code", - }, - ], contextProviders: defaultContextProvidersVsCode, slashCommands: defaultSlashCommandsVscode, }; @@ -110,14 +102,6 @@ export const defaultConfig: SerializedContinueConfig = { export const defaultConfigJetBrains: SerializedContinueConfig = { models: [DEFAULT_CHAT_MODEL_CONFIG], tabAutocompleteModel: DEFAULT_AUTOCOMPLETE_MODEL_CONFIG, - customCommands: [ - { - name: "test", - prompt: - "{{{ input }}}\n\nWrite a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.", - description: "Write unit tests for highlighted code", - }, - ], contextProviders: defaultContextProvidersJetBrains, slashCommands: defaultSlashCommandsJetBrains, }; diff --git a/core/config/load.ts b/core/config/load.ts index 1e16913e5..b28734c46 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -3,6 +3,7 @@ import * as fs from "fs"; import os from "os"; import path from "path"; +import { fetchwithRequestOptions } from "@continuedev/fetch"; import * as JSONC from "comment-json"; import * as tar from "tar"; @@ -19,8 +20,8 @@ import { IDE, IdeSettings, IdeType, + ILLM, ModelDescription, - Reranker, RerankerDescription, SerializedContinueConfig, SlashCommand, @@ -29,6 +30,7 @@ import { slashCommandFromDescription, slashFromCustomCommand, } from "../commands/index.js"; +import { AllRerankers } from "../context/allRerankers"; import MCPConnectionSingleton from "../context/mcp"; import CodebaseContextProvider from "../context/providers/CodebaseContextProvider"; import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider"; @@ -36,30 +38,29 @@ import CustomContextProviderClass from "../context/providers/CustomContextProvid import FileContextProvider from "../context/providers/FileContextProvider"; import { contextProviderClassFromName } from "../context/providers/index"; import PromptFilesContextProvider from "../context/providers/PromptFilesContextProvider"; -import { AllRerankers } from "../context/rerankers/index"; -import { LLMReranker } from "../context/rerankers/llm"; -import { allEmbeddingsProviders } from "../indexing/embeddings"; -import TransformersJsEmbeddingsProvider from "../indexing/embeddings/TransformersJsEmbeddingsProvider"; +import { allEmbeddingsProviders } from "../indexing/allEmbeddingsProviders"; import { BaseLLM } from "../llm"; import { llmFromDescription } from "../llm/llms"; import CustomLLMClass from "../llm/llms/CustomLLM"; import FreeTrial from "../llm/llms/FreeTrial"; +import { LLMReranker } from "../llm/llms/llm"; +import TransformersJsEmbeddingsProvider from "../llm/llms/TransformersJsEmbeddingsProvider"; import { allTools } from "../tools"; import { copyOf } from "../util"; -import { fetchwithRequestOptions } from "../util/fetchWithOptions"; import { GlobalContext } from "../util/GlobalContext"; import mergeJson from "../util/merge"; import { DEFAULT_CONFIG_TS_CONTENTS, - getConfigJsPath, - getConfigJsPathForRemote, getConfigJsonPath, getConfigJsonPathForRemote, + getConfigJsPath, + getConfigJsPathForRemote, getConfigTsPath, getContinueDotEnv, getEsbuildBinaryPath, readAllGlobalPromptFiles, } from "../util/paths"; + import { defaultContextProvidersJetBrains, defaultContextProvidersVsCode, @@ -470,7 +471,7 @@ async function intermediateToFinalConfig( } // Reranker - if (config.reranker && !(config.reranker as Reranker | undefined)?.rerank) { + if (config.reranker && !(config.reranker as ILLM | undefined)?.rerank) { const { name, params } = config.reranker as RerankerDescription; const rerankerClass = AllRerankers[name]; @@ -548,7 +549,7 @@ function finalToBrowserConfig( disableIndexing: final.disableIndexing, disableSessionTitles: final.disableSessionTitles, userToken: final.userToken, - embeddingsProvider: final.embeddingsProvider?.id, + embeddingsProvider: final.embeddingsProvider?.embeddingId, ui: final.ui, experimental: final.experimental, docs: final.docs, diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 7d1255618..e8d887303 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -5,12 +5,10 @@ import { IdeSettings, SerializedContinueConfig, } from "../../"; -import { ContinueProxyReranker } from "../../context/rerankers/ContinueProxyReranker.js"; import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js"; import { ControlPlaneClient } from "../../control-plane/client.js"; import { controlPlaneEnv } from "../../control-plane/env.js"; import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js"; -import ContinueProxyEmbeddingsProvider from "../../indexing/embeddings/ContinueProxyEmbeddingsProvider"; import ContinueProxy from "../../llm/llms/stubs/ContinueProxy"; import { Telemetry } from "../../util/posthog"; import { TTS } from "../../util/tts"; @@ -111,13 +109,11 @@ async function injectControlPlaneProxyInfo( ); if (config.embeddingsProvider?.providerName === "continue-proxy") { - ( - config.embeddingsProvider as ContinueProxyEmbeddingsProvider - ).controlPlaneProxyInfo = info; + (config.embeddingsProvider as ContinueProxy).controlPlaneProxyInfo = info; } - if (config.reranker?.name === "continue-proxy") { - (config.reranker as ContinueProxyReranker).controlPlaneProxyInfo = info; + if (config.reranker?.providerName === "continue-proxy") { + (config.reranker as ContinueProxy).controlPlaneProxyInfo = info; } return config; diff --git a/core/config/types.ts b/core/config/types.ts index 077c07699..625f4812f 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -846,6 +846,7 @@ declare global { codeBlockToolbarPosition?: "top" | "bottom"; fontSize?: number; displayRawMarkdown?: boolean; + codeWrap?: boolean; } interface ContextMenuConfig { diff --git a/core/context/allRerankers.ts b/core/context/allRerankers.ts new file mode 100644 index 000000000..56aa13474 --- /dev/null +++ b/core/context/allRerankers.ts @@ -0,0 +1,17 @@ +import Bedrock from "../llm/llms/Bedrock"; +import Cohere from "../llm/llms/Cohere"; +import FreeTrial from "../llm/llms/FreeTrial"; +import HuggingFaceTEI from "../llm/llms/HuggingFaceTEI"; +import { LLMReranker } from "../llm/llms/llm"; +import ContinueProxy from "../llm/llms/stubs/ContinueProxy"; +import Voyage from "../llm/llms/Voyage"; + +export const AllRerankers: { [key: string]: any } = { + cohere: Cohere, + bedrock: Bedrock, + llm: LLMReranker, + voyage: Voyage, + "free-trial": FreeTrial, + "huggingface-tei": HuggingFaceTEI, + "continue-proxy": ContinueProxy, +}; diff --git a/core/context/rerankers/ContinueProxyReranker.ts b/core/context/rerankers/ContinueProxyReranker.ts deleted file mode 100644 index a2404dac4..000000000 --- a/core/context/rerankers/ContinueProxyReranker.ts +++ /dev/null @@ -1,44 +0,0 @@ -import fetch from "node-fetch"; - -import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js"; -import { Chunk, Reranker } from "../../index.js"; - -export class ContinueProxyReranker implements Reranker { - name = "continue-proxy"; - - private _controlPlaneProxyInfo?: ControlPlaneProxyInfo; - - set controlPlaneProxyInfo(value: ControlPlaneProxyInfo) { - this.params.apiKey = value.workOsAccessToken!; - this._controlPlaneProxyInfo = value; - } - - constructor( - private readonly params: { - apiKey: string; - model?: string; - }, - ) {} - - async rerank(query: string, chunks: Chunk[]): Promise { - const url = new URL( - "openai/v1/rerank", - this._controlPlaneProxyInfo?.controlPlaneProxyUrl, - ); - const resp = await fetch(url, { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${this.params.apiKey}`, - }, - body: JSON.stringify({ - query, - documents: chunks.map((chunk) => chunk.content), - model: this.params.model, - }), - }); - const data: any = await resp.json(); - const results = data.data.sort((a: any, b: any) => a.index - b.index); - return results.map((result: any) => result.relevance_score); - } -} diff --git a/core/context/rerankers/bedrock.ts b/core/context/rerankers/bedrock.ts deleted file mode 100644 index 071910bd9..000000000 --- a/core/context/rerankers/bedrock.ts +++ /dev/null @@ -1,99 +0,0 @@ -import { - BedrockRuntimeClient, - InvokeModelCommand, -} from "@aws-sdk/client-bedrock-runtime"; -import { fromIni } from "@aws-sdk/credential-providers"; -import { Chunk, Reranker, RerankerName } from "../../index.js"; - -export class BedrockReranker implements Reranker { - name: RerankerName = "bedrock"; - - static defaultOptions = { - region: "us-east-1", - model: "amazon.rerank-v1:0", - profile: "bedrock", - }; - - private supportedModels = ["amazon.rerank-v1:0", "cohere.rerank-v3-5:0"]; - - constructor( - private readonly params: { - region?: string; - model?: string; - profile?: string; - } = {}, - ) { - if (params.model && !this.supportedModels.includes(params.model)) { - throw new Error( - `Unsupported model: ${params.model}. Supported models are: ${this.supportedModels.join(", ")}`, - ); - } - } - - async rerank(query: string, chunks: Chunk[]): Promise { - if (!query || !chunks.length) { - throw new Error("Query and chunks must not be empty"); - } - - try { - const credentials = await this._getCredentials(); - const client = new BedrockRuntimeClient({ - region: this.params.region ?? BedrockReranker.defaultOptions.region, - credentials, - }); - - const model = this.params.model ?? BedrockReranker.defaultOptions.model; - - // Base payload for both models - const payload: any = { - query: query, - documents: chunks.map((chunk) => chunk.content), - top_n: chunks.length, - }; - - // Add api_version for Cohere model - if (model.startsWith("cohere.rerank")) { - payload.api_version = 2; - } - - const input = { - body: JSON.stringify(payload), - modelId: model, - accept: "*/*", - contentType: "application/json", - }; - - const command = new InvokeModelCommand(input); - const response = await client.send(command); - - if (!response.body) { - throw new Error("Empty response received from Bedrock"); - } - - const responseBody = JSON.parse(new TextDecoder().decode(response.body)); - - // Sort results by index to maintain original order - 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; - } - } - - private async _getCredentials() { - try { - const credentials = await fromIni({ - profile: this.params.profile ?? BedrockReranker.defaultOptions.profile, - ignoreCache: true, - })(); - return credentials; - } catch (e) { - console.warn( - `AWS profile with name ${this.params.profile ?? BedrockReranker.defaultOptions.profile} not found in ~/.aws/credentials, using default profile`, - ); - return await fromIni()(); - } - } -} diff --git a/core/context/rerankers/cohere.ts b/core/context/rerankers/cohere.ts deleted file mode 100644 index 170565c4d..000000000 --- a/core/context/rerankers/cohere.ts +++ /dev/null @@ -1,48 +0,0 @@ -import fetch from "node-fetch"; - -import { Chunk, Reranker } from "../../index.js"; - -export class CohereReranker implements Reranker { - name = "cohere"; - - static defaultOptions = { - apiBase: "https://api.cohere.ai/v1/", - model: "rerank-english-v3.0", - }; - - constructor( - private readonly params: { - apiBase?: string; - apiKey: string; - model?: string; - }, - ) {} - - async rerank(query: string, chunks: Chunk[]): Promise { - let apiBase = this.params.apiBase ?? CohereReranker.defaultOptions.apiBase; - if (!apiBase.endsWith("/")) { - apiBase += "/"; - } - - const resp = await fetch(new URL("rerank", apiBase), { - method: "POST", - headers: { - Authorization: `Bearer ${this.params.apiKey}`, - "Content-Type": "application/json", - }, - body: JSON.stringify({ - model: this.params.model ?? CohereReranker.defaultOptions.model, - query, - documents: chunks.map((chunk) => chunk.content), - }), - }); - - if (!resp.ok) { - throw new Error(await resp.text()); - } - - const data = (await resp.json()) as any; - const results = data.results.sort((a: any, b: any) => a.index - b.index); - return results.map((result: any) => result.relevance_score); - } -} diff --git a/core/context/rerankers/freeTrial.ts b/core/context/rerankers/freeTrial.ts deleted file mode 100644 index 14a639b0d..000000000 --- a/core/context/rerankers/freeTrial.ts +++ /dev/null @@ -1,34 +0,0 @@ -import fetch from "node-fetch"; - -import { getHeaders } from "../../continueServer/stubs/headers.js"; -import { TRIAL_PROXY_URL } from "../../control-plane/client.js"; -import { Chunk, Reranker } from "../../index.js"; - -export class FreeTrialReranker implements Reranker { - name = "free-trial"; - - async rerank(query: string, chunks: Chunk[]): Promise { - if (chunks.length === 0) { - return []; - } - const resp = await fetch(new URL("rerank", TRIAL_PROXY_URL), { - method: "POST", - headers: { - "Content-Type": "application/json", - ...(await getHeaders()), - }, - body: JSON.stringify({ - query, - documents: chunks.map((chunk) => chunk.content), - }), - }); - - if (!resp.ok) { - throw new Error(await resp.text()); - } - - const data = (await resp.json()) as any; - const results = data.sort((a: any, b: any) => a.index - b.index); - return results.map((result: any) => result.relevance_score); - } -} diff --git a/core/context/rerankers/index.ts b/core/context/rerankers/index.ts deleted file mode 100644 index ba6af849c..000000000 --- a/core/context/rerankers/index.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { RerankerName } from "../../index.js"; - -import { BedrockReranker } from "./bedrock.js"; -import { CohereReranker } from "./cohere.js"; -import { ContinueProxyReranker } from "./ContinueProxyReranker.js"; -import { FreeTrialReranker } from "./freeTrial.js"; -import { LLMReranker } from "./llm.js"; -import { HuggingFaceTEIReranker } from "./tei.js"; -import { VoyageReranker } from "./voyage.js"; - -export const AllRerankers: { [key in RerankerName]: any } = { - cohere: CohereReranker, - bedrock: BedrockReranker, - llm: LLMReranker, - voyage: VoyageReranker, - "free-trial": FreeTrialReranker, - "huggingface-tei": HuggingFaceTEIReranker, - "continue-proxy": ContinueProxyReranker, -}; \ No newline at end of file diff --git a/core/context/rerankers/tei.ts b/core/context/rerankers/tei.ts deleted file mode 100644 index 315964560..000000000 --- a/core/context/rerankers/tei.ts +++ /dev/null @@ -1,59 +0,0 @@ -import fetch from "node-fetch"; - -import { Chunk, Reranker } from "../../index.js"; - -export class HuggingFaceTEIReranker implements Reranker { - name = "huggingface-tei"; - - static defaultOptions = { - apiBase: "http://localhost:8080", - truncate: true, - truncation_direction: "Right" - }; - - constructor( - private readonly params: { - apiBase?: string; - truncate?: boolean; - truncation_direction?: string; - apiKey?: string; - }, - ) {} - - async rerank(query: string, chunks: Chunk[]): Promise { - let apiBase = this.params.apiBase ?? HuggingFaceTEIReranker.defaultOptions.apiBase; - if (!apiBase.endsWith("/")) { - apiBase += "/"; - } - - const headers: Record = { - "Content-Type": "application/json", - }; - - if (this.params.apiKey) { - headers["Authorization"] = `Bearer ${this.params.apiKey}`; - } - - const resp = await fetch(new URL("rerank", apiBase), { - method: "POST", - headers, - body: JSON.stringify({ - query: query, - return_text: false, - raw_scores: false, - texts: chunks.map((chunk) => chunk.content), - truncation_direction: this.params.truncation_direction ?? HuggingFaceTEIReranker.defaultOptions.truncation_direction, - truncate: this.params.truncate ?? HuggingFaceTEIReranker.defaultOptions.truncate - }), - }); - - if (!resp.ok) { - throw new Error(await resp.text()); - } - - const data = (await resp.json()) as any; - // Resort into original order and extract scores - const results = data.sort((a: any, b: any) => a.index - b.index); - return results.map((result: any) => result.score); - } -} diff --git a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts index 3f23cebf7..0ba94964c 100644 --- a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts @@ -108,7 +108,8 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline { const fileChunks = chunkDocument({ filepath, contents, - maxChunkSize: this.options.config.embeddingsProvider.maxChunkSize, + maxChunkSize: + this.options.config.embeddingsProvider.maxEmbeddingChunkSize, digest: filepath, }); diff --git a/core/context/retrieval/retrieval.ts b/core/context/retrieval/retrieval.ts index c97c65670..a2b129dc8 100644 --- a/core/context/retrieval/retrieval.ts +++ b/core/context/retrieval/retrieval.ts @@ -1,5 +1,5 @@ import { BranchAndDir, ContextItem, ContextProviderExtras } from "../../"; -import TransformersJsEmbeddingsProvider from "../../indexing/embeddings/TransformersJsEmbeddingsProvider"; +import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider"; import { resolveRelativePathInWorkspace } from "../../util/ideUtils"; import { getUriPathBasename } from "../../util/uri"; import { INSTRUCTIONS_BASE_ITEM } from "../providers/utils"; diff --git a/core/context/retrieval/util.ts b/core/context/retrieval/util.ts index 5343d8dbd..38dcb87ab 100644 --- a/core/context/retrieval/util.ts +++ b/core/context/retrieval/util.ts @@ -1,5 +1,5 @@ -import { Chunk } from "../../index.js"; -import { deduplicateArray } from "../../util/index.js"; +import { Chunk } from "../../index"; +import { deduplicateArray } from "../../util/index"; export function deduplicateChunks(chunks: Chunk[]): Chunk[] { return deduplicateArray(chunks, (a, b) => { diff --git a/core/context/retrieval/utils.test.ts b/core/context/retrieval/utils.test.ts new file mode 100644 index 000000000..4b8d9d3fe --- /dev/null +++ b/core/context/retrieval/utils.test.ts @@ -0,0 +1,117 @@ +// Generated by Continue +import { Chunk } from "../../index"; + +import { deduplicateChunks } from "./util"; + +describe("deduplicateChunks", () => { + it("returns an empty array when given an empty array", () => { + const chunks: Chunk[] = []; + const result = deduplicateChunks(chunks); + expect(result).toEqual([]); + }); + + it("returns the same array when given an array with no duplicates", () => { + const chunks: Chunk[] = [ + { + filepath: "file1.ts", + startLine: 0, + endLine: 1, + content: "chunk 1", + digest: "", + index: 0, + }, + { + filepath: "file2.ts", + startLine: 2, + endLine: 3, + content: "chunk 2", + digest: "", + index: 1, + }, + ]; + const result = deduplicateChunks(chunks); + expect(result).toEqual(chunks); + }); + + it("removes duplicate chunks", () => { + const chunks: Chunk[] = [ + { + filepath: "file1.ts", + startLine: 0, + endLine: 1, + content: "chunk 1", + digest: "", + index: 0, + }, + { + filepath: "file1.ts", + startLine: 0, + endLine: 1, + content: "chunk 1 duplicate", + digest: "", + index: 0, + }, + { + filepath: "file2.ts", + startLine: 2, + endLine: 3, + content: "chunk 2", + digest: "", + index: 1, + }, + ]; + const result = deduplicateChunks(chunks); + + expect(result).toEqual([ + { + filepath: "file1.ts", + startLine: 0, + endLine: 1, + content: "chunk 1", + digest: "", + index: 0, + }, + { + filepath: "file2.ts", + startLine: 2, + endLine: 3, + content: "chunk 2", + digest: "", + index: 1, + }, + ]); + }); + + it("handles chunks with different contents but the same file lines as duplicates", () => { + const chunks: Chunk[] = [ + { + filepath: "file1.ts", + startLine: 0, + endLine: 1, + content: "chunk 1", + digest: "", + index: 0, + }, + { + filepath: "file1.ts", + startLine: 0, + endLine: 1, + content: "chunk 1 different content", + digest: "", + index: 0, + }, + ]; + const result = deduplicateChunks(chunks); + + expect(result).toEqual([ + { + filepath: "file1.ts", + startLine: 0, + endLine: 1, + content: "chunk 1", + digest: "", + index: 0, + }, + ]); + }); +}); diff --git a/core/core.ts b/core/core.ts index c8deeb373..eadb02745 100644 --- a/core/core.ts +++ b/core/core.ts @@ -1,5 +1,6 @@ import path from "path"; +import { fetchwithRequestOptions } from "@continuedev/fetch"; import ignore from "ignore"; import { v4 as uuidv4 } from "uuid"; @@ -27,7 +28,6 @@ import { callTool } from "./tools/callTool"; import { ChatDescriber } from "./util/chatDescriber"; import { logDevData } from "./util/devdata"; import { DevDataSqliteDb } from "./util/devdataSqlite"; -import { fetchwithRequestOptions } from "./util/fetchWithOptions"; import { GlobalContext } from "./util/GlobalContext"; import historyManager from "./util/history"; import { @@ -41,9 +41,10 @@ import { TTS } from "./util/tts"; import type { ContextItemId, IDE, IndexingProgressUpdate } from "."; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; -import type { IMessenger, Message } from "./util/messenger"; -import { fileURLToPath } from "url"; + import { SYSTEM_PROMPT_DOT_FILE } from "./config/getSystemPromptDotFile"; +import type { IMessenger, Message } from "./protocol/messenger"; +import { getFullPath } from "./util/uri"; export class Core { // implements IMessenger @@ -372,7 +373,6 @@ export class Core { msg: Message, ) { const config = await configHandler.loadConfig(); - // Stop TTS on new StreamChat if (config.experimental?.readResponseTTS) { void TTS.kill(); @@ -729,7 +729,7 @@ export class Core { if (data?.uris?.length) { for (const uri of data.uris) { // Listen for file changes in the workspace - const filePath = fileURLToPath(uri); + const filePath = getFullPath(uri); if (filePath === getConfigJsonPath()) { // Trigger a toast notification to provide UI feedback that config // has been updated @@ -799,7 +799,7 @@ export class Core { }); on("indexing/setPaused", async (msg) => { if (msg.data.type === "docs") { - this.docsService.setPaused(msg.data.id, msg.data.paused); + // this.docsService.setPaused(msg.data.id, msg.data.paused); } }); on("docs/getSuggestedDocs", async (msg) => { diff --git a/core/diff/myers.test.ts b/core/diff/myers.test.ts index d07b298c7..2b47fa548 100644 --- a/core/diff/myers.test.ts +++ b/core/diff/myers.test.ts @@ -19,6 +19,14 @@ describe("Test myers diff function", () => { E `; const diffLines = myersDiff(linesA, linesB); - console.log(diffLines); + expect(diffLines).toEqual([ + { type: "same", line: "A" }, + { type: "same", line: "B" }, + { type: "old", line: "C" }, + { type: "old", line: "D" }, + { type: "new", line: "C'" }, + { type: "new", line: "D'" }, + { type: "same", line: "E" }, + ]); }); }); diff --git a/core/diff/util.test.ts b/core/diff/util.test.ts new file mode 100644 index 000000000..fca80ba6a --- /dev/null +++ b/core/diff/util.test.ts @@ -0,0 +1,200 @@ +// Generated by continue + +import { matchLine, streamLines, generateLines } from "./util"; +import { ChatMessage } from "../index"; +import { jest } from "@jest/globals"; + +describe.skip("matchLine", () => { + it("should match empty lines if the first old line is also empty", () => { + const newLine = " "; + const oldLines = [" ", "some code"]; + const result = matchLine(newLine, oldLines); + expect(result).toEqual({ + matchIndex: 0, + isPerfectMatch: true, + newLine: "", + }); + }); + + it("should return matchIndex -1 if newLine is an end bracket and i > 4", () => { + const newLine = "}"; + const oldLines = ["line 1", "line 2", "line 3", "line 4", "line 5", "}"]; + const result = matchLine(newLine, oldLines); + expect(result).toEqual({ + matchIndex: -1, + isPerfectMatch: false, + newLine: "}", + }); + }); + + it("should match end bracket if within first 5 lines", () => { + const newLine = "}"; + const oldLines = ["line 1", "line 2", "line 3", "}", "line 5", "}"]; + const result = matchLine(newLine, oldLines); + expect(result).toEqual({ + matchIndex: 3, + isPerfectMatch: true, + newLine: "}", + }); + }); + + it("should match lines perfectly", () => { + const newLine = "const a = 5;"; + const oldLines = ["let b = 6;", "const a = 5;", "console.log(a);"]; + const result = matchLine(newLine, oldLines); + expect(result).toEqual({ + matchIndex: 1, + isPerfectMatch: true, + newLine: "const a = 5;", + }); + }); + + it("should match lines with tolerable differences", () => { + const newLine = "console.log(a);"; + const oldLines = ["const a = 5;", "console.log(b);", "console.log( a );"]; + const result = matchLine(newLine, oldLines); + expect(result).toEqual({ + matchIndex: 2, + isPerfectMatch: false, + newLine: "console.log(a);", + }); + }); + + it("should return matchIndex -1 if no match found", () => { + const newLine = "new line that does not exist"; + const oldLines = ["line 1", "line 2", "line 3"]; + const result = matchLine(newLine, oldLines); + expect(result).toEqual({ + matchIndex: -1, + isPerfectMatch: false, + newLine: "new line that does not exist", + }); + }); + + it("should fix indentation if permissible and line length > 8", () => { + const newLine = " const a = 5;"; + const oldLines = ["const a = 5;"]; + const result = matchLine(newLine, oldLines, false); + expect(result).toEqual({ + matchIndex: 0, + isPerfectMatch: true, + newLine: "const a = 5;", + }); + }); + + it("should not fix indentation if not permissible and line length is short", () => { + const newLine = " for"; + const oldLines = ["for"]; + const result = matchLine(newLine, oldLines, false); + expect(result).toEqual({ + matchIndex: 0, + isPerfectMatch: false, + newLine: " for", + }); + }); + + it("should fix indentation even if line length <=8 when permissiveAboutIndentation is true", () => { + const newLine = " for"; + const oldLines = ["for"]; + const result = matchLine(newLine, oldLines, true); + expect(result).toEqual({ + matchIndex: 0, + isPerfectMatch: true, + newLine: "for", + }); + }); + + it("should match lines that are empty strings", () => { + const newLine = ""; + const oldLines = [""]; + const result = matchLine(newLine, oldLines); + expect(result).toEqual({ + matchIndex: 0, + isPerfectMatch: true, + newLine: "", + }); + }); +}); + +describe("streamLines", () => { + it("should split chunks into lines correctly", async () => { + async function* streamCompletion(): AsyncGenerator { + yield "line1\nline"; + yield "2\nline3\n"; + yield "line4"; + } + + const resultLines: string[] = []; + for await (const line of streamLines(streamCompletion())) { + resultLines.push(line); + } + + expect(resultLines).toEqual(["line1", "line2", "line3", "line4"]); + }); + + it("should handle ChatMessage chunks", async () => { + const messageChunk1: ChatMessage = { + role: "assistant", + content: "line1\nline", + }; + const messageChunk2: ChatMessage = { + role: "assistant", + content: "2\nline3\n", + }; + const messageChunk3: ChatMessage = { + role: "assistant", + content: "line4", + }; + + // const spy = jest.spyOn(messageContentModule, "renderChatMessage"); + + async function* streamCompletion(): AsyncGenerator { + yield messageChunk1; + yield messageChunk2; + yield messageChunk3; + } + + const resultLines: string[] = []; + for await (const line of streamLines(streamCompletion())) { + resultLines.push(line); + } + + expect(resultLines).toEqual(["line1", "line2", "line3", "line4"]); + // expect(spy).toHaveBeenCalledTimes(3); + }); + + it("should log lines if log parameter is true", async () => { + const consoleSpy = jest.spyOn(console, "log").mockImplementation(() => {}); + + async function* streamCompletion(): AsyncGenerator { + yield "line1\nline2\n"; + yield "line3"; + } + + const resultLines: string[] = []; + for await (const line of streamLines(streamCompletion(), true)) { + resultLines.push(line); + } + + expect(resultLines).toEqual(["line1", "line2", "line3"]); + expect(consoleSpy).toHaveBeenCalledWith( + "Streamed lines: ", + "line1\nline2\nline3", + ); + + consoleSpy.mockRestore(); + }); +}); + +describe("generateLines", () => { + it("should yield the lines provided in the array", async () => { + const lines = ["line1", "line2", "line3"]; + const resultLines: string[] = []; + + for await (const line of generateLines(lines)) { + resultLines.push(line); + } + + expect(resultLines).toEqual(lines); + }); +}); diff --git a/core/edit/lazy/findInAst.test.ts b/core/edit/lazy/findInAst.test.ts new file mode 100644 index 000000000..f9e95613b --- /dev/null +++ b/core/edit/lazy/findInAst.test.ts @@ -0,0 +1,109 @@ +// Generated by continue + +import { findInAst } from "./findInAst"; +import Parser from "web-tree-sitter"; + +describe("findInAst", () => { + it("should find a node matching the criterion", () => { + const mockAst = createMockSyntaxNode("root", [ + createMockSyntaxNode("child1", []), + createMockSyntaxNode("function", [createMockSyntaxNode("child2", [])]), + ]); + + const criterion = (node: Parser.SyntaxNode) => node.type === "function"; + + const result = findInAst(mockAst, criterion); + + expect(result).not.toBeNull(); + expect(result!.type).toBe("function"); + }); + + it("should return null if no node matches the criterion", () => { + const mockAst = createMockSyntaxNode("root", [ + createMockSyntaxNode("child1", []), + createMockSyntaxNode("child2", []), + ]); + + const criterion = (node: Parser.SyntaxNode) => node.type === "function"; + + const result = findInAst(mockAst, criterion); + + expect(result).toBeNull(); + }); + + it("should find a nested node matching the criterion", () => { + const mockAst = createMockSyntaxNode("root", [ + createMockSyntaxNode("child1", [ + createMockSyntaxNode("child2", [createMockSyntaxNode("function", [])]), + ]), + createMockSyntaxNode("child3", []), + ]); + + const criterion = (node: Parser.SyntaxNode) => node.type === "function"; + + const result = findInAst(mockAst, criterion); + + expect(result).not.toBeNull(); + expect(result!.type).toBe("function"); + }); + + it("should return the first node matching the criterion in depth-first traversal", () => { + const firstFunctionNode = createMockSyntaxNode("function", []); + const secondFunctionNode = createMockSyntaxNode("function", []); + const mockAst = createMockSyntaxNode("root", [ + firstFunctionNode, // First function node + createMockSyntaxNode("child1", [ + secondFunctionNode, // Second function node + ]), + ]); + + const criterion = (node: Parser.SyntaxNode) => node.type === "function"; + + const result = findInAst(mockAst, criterion); + + expect(result).not.toBeNull(); + expect(result!.type).toBe("function"); + expect(JSON.stringify(result)).toBe(JSON.stringify(firstFunctionNode)); // Ensure it's the first function node + }); + + it("should return the root node if it matches the criterion", () => { + const mockAst = createMockSyntaxNode("function", [ + createMockSyntaxNode("child1", []), + createMockSyntaxNode("child2", []), + ]); + + const criterion = (node: Parser.SyntaxNode) => node.type === "function"; + + const result = findInAst(mockAst, criterion); + + expect(result).not.toBeNull(); + expect(result!.type).toBe("function"); + expect(result).toBe(mockAst); + }); + + it("should return null when searching an empty tree", () => { + const mockAst = createMockSyntaxNode("root", []); + + const criterion = (node: Parser.SyntaxNode) => node.type === "function"; + + const result = findInAst(mockAst, criterion); + + expect(result).toBeNull(); + }); +}); + +function createMockSyntaxNode( + type: string, + children: Parser.SyntaxNode[], +): Parser.SyntaxNode { + // Define minimal properties of SyntaxNode required for the test + const node: Partial = { + type, + children, + childCount: children.length, + child: (index: number) => { + return children[index] || null; + }, + }; + return node as Parser.SyntaxNode; +} diff --git a/core/edit/lazy/prompts.ts b/core/edit/lazy/prompts.ts index 9b8d6abb9..f821a3b07 100644 --- a/core/edit/lazy/prompts.ts +++ b/core/edit/lazy/prompts.ts @@ -1,4 +1,4 @@ -import { ChatMessage, ModelProvider } from "../.."; +import { ChatMessage } from "../.."; import { dedent } from "../../util"; export const UNCHANGED_CODE = "UNCHANGED CODE"; @@ -52,7 +52,7 @@ function claude35SonnetLazyApplyPrompt( export function lazyApplyPromptForModel( model: string, - provider: ModelProvider, + provider: string, ): LazyApplyPrompt | undefined { if (model.includes("sonnet")) { return claude35SonnetLazyApplyPrompt; diff --git a/core/edit/streamDiffLines.test.ts b/core/edit/streamDiffLines.test.ts new file mode 100644 index 000000000..508da27c1 --- /dev/null +++ b/core/edit/streamDiffLines.test.ts @@ -0,0 +1,77 @@ +// Generated by continue + +import { addIndentation } from "./streamDiffLines"; +import type { DiffLine } from "../index"; + +describe("addIndentation", () => { + async function* mockDiffLineGenerator(lines: DiffLine[]) { + for (const line of lines) { + yield line; + } + } + + test("should add indentation to each line", async () => { + const lines: DiffLine[] = [ + { type: "same", line: "Line 1" }, + { type: "new", line: "Line 2" }, + { type: "old", line: "Line 3" }, + ]; + const indentation = " "; + + const generator = addIndentation(mockDiffLineGenerator(lines), indentation); + + const result: DiffLine[] = []; + for await (const diffLine of generator) { + result.push(diffLine); + } + + expect(result).toEqual([ + { type: "same", line: " Line 1" }, + { type: "new", line: " Line 2" }, + { type: "old", line: " Line 3" }, + ]); + }); + + test("should handle empty generator", async () => { + const lines: DiffLine[] = []; + const indentation = "\t"; + + const generator = addIndentation(mockDiffLineGenerator(lines), indentation); + + const result: DiffLine[] = []; + for await (const diffLine of generator) { + result.push(diffLine); + } + + expect(result).toEqual([]); + }); + + test("should handle no indentation", async () => { + const lines: DiffLine[] = [{ type: "same", line: "Line 1" }]; + const indentation = ""; + + const generator = addIndentation(mockDiffLineGenerator(lines), indentation); + + const result: DiffLine[] = []; + for await (const diffLine of generator) { + result.push(diffLine); + } + + expect(result).toEqual([{ type: "same", line: "Line 1" }]); + }); + + test("should propagate errors from the source generator", async () => { + async function* errorGenerator(): AsyncGenerator { + throw new Error("Test error"); + } + const indentation = " "; + + const generator = addIndentation(errorGenerator(), indentation); + + await expect(async () => { + for await (const _ of generator) { + // Consume the generator + } + }).rejects.toThrow("Test error"); + }); +}); diff --git a/core/edit/streamDiffLines.ts b/core/edit/streamDiffLines.ts index 5ecf273c5..d0a6154c1 100644 --- a/core/edit/streamDiffLines.ts +++ b/core/edit/streamDiffLines.ts @@ -30,7 +30,7 @@ function constructPrompt( }); } -async function* addIndentation( +export async function* addIndentation( diffLineGenerator: AsyncGenerator, indentation: string, ): AsyncGenerator { @@ -96,8 +96,11 @@ export async function* streamDiffLines( const completion = typeof prompt === "string" - ? llm.streamComplete(prompt, new AbortController().signal, { raw: true, prediction }) - : llm.streamChat(prompt, new AbortController().signal, { + ? llm.streamComplete(prompt, new AbortController().signal, { + raw: true, + prediction, + }) + : llm.streamChat(prompt, new AbortController().signal, { prediction, }); diff --git a/core/index.d.ts b/core/index.d.ts index cd3518c36..08e7a1fc5 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1,6 +1,5 @@ import Parser from "web-tree-sitter"; import { GetGhTokenArgs } from "./protocol/ide"; - declare global { interface Window { ide?: "vscode"; @@ -59,14 +58,7 @@ export interface IndexingStatus { type: "docs"; progress: number; description: string; - status: - | "indexing" - | "complete" - | "paused" - | "failed" - | "aborted" - | "deleted" - | "pending"; + status: "indexing" | "complete" | "paused" | "failed" | "aborted" | "pending"; embeddingsProviderId: string; isReindexing?: boolean; debugInfo?: string; @@ -83,7 +75,7 @@ export type PromptTemplateFunction = ( export type PromptTemplate = string | PromptTemplateFunction; export interface ILLM extends LLMOptions { - get providerName(): ModelProvider; + get providerName(): string; uniqueId: string; model: string; @@ -108,6 +100,11 @@ export interface ILLM extends LLMOptions { region?: string; projectId?: string; + // Embedding options + embeddingId: string; + maxEmbeddingChunkSize: number; + maxEmbeddingBatchSize: number; + complete( prompt: string, signal: AbortSignal, @@ -139,6 +136,10 @@ export interface ILLM extends LLMOptions { options?: LLMFullCompletionOptions, ): Promise; + embed(chunks: string[]): Promise; + + rerank(query: string, chunks: Chunk[]): Promise; + countTokens(text: string): number; supportsImages(): boolean; @@ -175,8 +176,8 @@ export type FetchFunction = (url: string | URL, init?: any) => Promise; export interface ContextProviderExtras { config: ContinueConfig; fullInput: string; - embeddingsProvider: EmbeddingsProvider; - reranker: Reranker | undefined; + embeddingsProvider: ILLM; + reranker: ILLM | undefined; llm: ILLM; ide: IDE; selectedCode: RangeInFile[]; @@ -389,6 +390,7 @@ export interface InputModifiers { export interface SymbolWithRange extends RangeInFile { name: string; type: Parser.SyntaxNode["type"]; + content: string; } export type FileSymbolMap = Record; @@ -459,6 +461,11 @@ export interface LLMOptions { useLegacyCompletionsEndpoint?: boolean; + // Embedding options + embeddingId?: string; + maxEmbeddingChunkSize?: number; + maxEmbeddingBatchSize?: number; + // Cloudflare options accountId?: string; @@ -770,152 +777,6 @@ type TemplateType = | "granite" | "llama3"; -type ModelProvider = - | "openai" - | "free-trial" - | "anthropic" - | "cohere" - | "together" - | "ollama" - | "huggingface-tgi" - | "huggingface-inference-api" - | "kindo" - | "llama.cpp" - | "replicate" - | "text-gen-webui" - | "lmstudio" - | "llamafile" - | "gemini" - | "mistral" - | "bedrock" - | "bedrockimport" - | "sagemaker" - | "deepinfra" - | "flowise" - | "groq" - | "continue-proxy" - | "fireworks" - | "custom" - | "cloudflare" - | "deepseek" - | "azure" - | "openai-aiohttp" - | "msty" - | "watsonx" - | "openrouter" - | "sambanova" - | "nvidia" - | "vllm" - | "mock" - | "test" - | "cerebras" - | "askSage" - | "vertexai" - | "nebius" - | "xAI" - | "moonshot" - | "siliconflow" - | "function-network"; - -export type ModelName = - | "AUTODETECT" - // OpenAI - | "gpt-3.5-turbo" - | "gpt-3.5-turbo-16k" - | "gpt-4" - | "gpt-3.5-turbo-0613" - | "gpt-4-32k" - | "gpt-4o" - | "gpt-4o-mini" - | "gpt-4-turbo" - | "gpt-4-turbo-preview" - | "gpt-4-vision-preview" - | "o1-preview" - | "o1-mini" - // Mistral - | "codestral-latest" - | "open-mistral-7b" - | "open-mixtral-8x7b" - | "open-mixtral-8x22b" - | "mistral-small-latest" - | "mistral-large-latest" - | "mistral-7b" - | "mistral-8x7b" - | "mistral-8x22b" - | "mistral-tiny" - | "mistral-small" - | "mistral-medium" - | "mistral-embed" - | "mistral-nemo" - // Llama 2 - | "llama2-7b" - | "llama2-13b" - | "llama2-70b" - | "codellama-7b" - | "codellama-13b" - | "codellama-34b" - | "codellama-70b" - // Llama 3 - | "llama3-8b" - | "llama3-70b" - // Llama 3.1 - | "llama3.1-8b" - | "llama3.1-70b" - | "llama3.1-405b" - // Llama 3.2 - | "llama3.2-1b" - | "llama3.2-3b" - | "llama3.2-11b" - | "llama3.2-90b" - // xAI - | "grok-beta" - // Other Open-source - | "phi2" - | "phi-3-mini" - | "phi-3-medium" - | "phind-codellama-34b" - | "wizardcoder-7b" - | "wizardcoder-13b" - | "wizardcoder-34b" - | "zephyr-7b" - | "codeup-13b" - | "deepseek-7b" - | "deepseek-33b" - | "deepseek-2-lite" - | "neural-chat-7b" - | "gemma-7b-it" - | "gemma2-2b-it" - | "gemma2-9b-it" - | "olmo-7b" - | "qwen-coder2.5-7b" - // Anthropic - | "claude-3-5-sonnet-latest" - | "claude-3-5-sonnet-20240620" - | "claude-3-opus-20240229" - | "claude-3-sonnet-20240229" - | "claude-3-haiku-20240307" - | "claude-2.1" - | "claude-2" - // Cohere - | "command-r" - | "command-r-plus" - // Gemini - | "gemini-pro" - | "gemini-1.5-pro-latest" - | "gemini-1.5-pro" - | "gemini-1.5-flash-latest" - | "gemini-1.5-flash" - // Tab autocomplete - | "deepseek-1b" - | "starcoder-1b" - | "starcoder-3b" - | "starcoder2-3b" - | "stable-code-3b" - // Moonshot - | "moonshot-v1-8k" - | "moonshot-v1-32k" - | "moonshot-v1-128k"; - export interface RequestOptions { timeout?: number; verifySsl?: boolean; @@ -1016,7 +877,7 @@ export interface ModelCapability { export interface ModelDescription { title: string; - provider: ModelProvider; + provider: string; model: string; apiKey?: string; apiBase?: string; @@ -1031,28 +892,6 @@ export interface ModelDescription { cacheBehavior?: CacheBehavior; } -export type EmbeddingsProviderName = - | "sagemaker" - | "bedrock" - | "huggingface-tei" - | "transformers.js" - | "ollama" - | "openai" - | "cohere" - | "lmstudio" - | "free-trial" - | "gemini" - | "continue-proxy" - | "deepinfra" - | "nvidia" - | "voyage" - | "mistral" - | "nebius" - | "vertexai" - | "watsonx" - | "function-network" - | "siliconflow"; - export interface EmbedOptions { apiBase?: string; apiKey?: string; @@ -1074,35 +913,12 @@ export interface EmbedOptions { } export interface EmbeddingsProviderDescription extends EmbedOptions { - provider: EmbeddingsProviderName; + provider: string; } -export interface EmbeddingsProvider { - id: string; - providerName: EmbeddingsProviderName; - maxChunkSize: number; - - embed(chunks: string[]): Promise; -} - -export type RerankerName = - | "cohere" - | "bedrock" - | "voyage" - | "llm" - | "free-trial" - | "huggingface-tei" - | "continue-proxy"; - export interface RerankerDescription { - name: RerankerName; - params?: { [key: string]: any }; -} - -export interface Reranker { name: string; - - rerank(query: string, chunks: Chunk[]): Promise; + params?: { [key: string]: any }; } export interface TabAutocompleteOptions { @@ -1153,6 +969,7 @@ export interface ContinueUIConfig { displayRawMarkdown?: boolean; showChatScrollbar?: boolean; getChatTitles?: boolean; + codeWrap?: boolean; } interface ContextMenuConfig { @@ -1320,7 +1137,7 @@ export interface Config { /** An optional token to identify a user. Not used by Continue unless you write custom coniguration that requires such a token */ userToken?: string; /** The provider used to calculate embeddings. If left empty, Continue will use transformers.js to calculate the embeddings with all-MiniLM-L6-v2 */ - embeddingsProvider?: EmbeddingsProviderDescription | EmbeddingsProvider; + embeddingsProvider?: EmbeddingsProviderDescription | ILLM; /** The model that Continue will use for tab autocompletions. */ tabAutocompleteModel?: | CustomLLM @@ -1331,7 +1148,7 @@ export interface Config { /** UI styles customization */ ui?: ContinueUIConfig; /** Options for the reranker */ - reranker?: RerankerDescription | Reranker; + reranker?: RerankerDescription | ILLM; /** Experimental configuration */ experimental?: ExperimentalConfig; /** Analytics configuration */ @@ -1350,11 +1167,11 @@ export interface ContinueConfig { disableSessionTitles?: boolean; disableIndexing?: boolean; userToken?: string; - embeddingsProvider: EmbeddingsProvider; + embeddingsProvider: ILLM; tabAutocompleteModels?: ILLM[]; tabAutocompleteOptions?: Partial; ui?: ContinueUIConfig; - reranker?: Reranker; + reranker?: ILLM; experimental?: ExperimentalConfig; analytics?: AnalyticsConfig; docs?: SiteIndexingConfig[]; diff --git a/core/indexing/CodebaseIndexer.test.ts b/core/indexing/CodebaseIndexer.test.ts index 950e23ffd..cc0162562 100644 --- a/core/indexing/CodebaseIndexer.test.ts +++ b/core/indexing/CodebaseIndexer.test.ts @@ -135,7 +135,6 @@ describe("CodebaseIndexer", () => { del: number, ) { const plan = await getIndexPlan(); - console.log("PLAN: ", plan); expect(plan.compute).toHaveLength(compute); expect(plan.addTag).toHaveLength(addTag); expect(plan.removeTag).toHaveLength(removeTag); diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index af204a723..4b2138d5a 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -17,7 +17,6 @@ import { RefreshIndexResults, } from "./types.js"; import { walkDirAsync } from "./walkDir.js"; -import { getBasename } from "../util/index.js"; export class PauseToken { constructor(private _paused: boolean) {} @@ -83,7 +82,7 @@ export class CodebaseIndexer { this.ide.readFile.bind(this.ide), pathSep, this.continueServerClient, - config.embeddingsProvider.maxChunkSize, + config.embeddingsProvider.maxEmbeddingChunkSize, ), // Chunking must come first new LanceDbIndex( config.embeddingsProvider, diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 3759cf5b0..d11feb1d1 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -7,11 +7,10 @@ import { IContinueServerClient } from "../continueServer/interface.js"; import { BranchAndDir, Chunk, - EmbeddingsProvider, + ILLM, IndexTag, IndexingProgressUpdate, } from "../index.js"; -import { getBasename } from "../util/index.js"; import { getLanceDbPath, migrate } from "../util/paths.js"; import { chunkDocument, shouldChunk } from "./chunk/chunk.js"; @@ -23,6 +22,7 @@ import { PathAndCacheKey, RefreshIndexResults, } from "./types.js"; +import { getUriPathBasename } from "../util/uri.js"; // LanceDB converts to lowercase, so names must all be lowercase interface LanceDbRow { @@ -40,13 +40,12 @@ type ChunkMap = Map; export class LanceDbIndex implements CodebaseIndex { relativeExpectedTime: number = 13; get artifactId(): string { - return `vectordb::${this.embeddingsProvider.id}`; + return `vectordb::${this.embeddingsProvider.embeddingId}`; } constructor( - private readonly embeddingsProvider: EmbeddingsProvider, + private readonly embeddingsProvider: ILLM, private readonly readFile: (filepath: string) => Promise, - private readonly pathSep: string, private readonly continueServerClient?: IContinueServerClient, ) {} @@ -125,7 +124,7 @@ export class LanceDbIndex implements CodebaseIndex { try { const content = await this.readFile(item.path); - if (!shouldChunk(this.pathSep, item.path, content)) { + if (!shouldChunk(item.path, content)) { continue; } @@ -148,7 +147,7 @@ export class LanceDbIndex implements CodebaseIndex { const chunkParams = { filepath: item.path, contents: content, - maxChunkSize: this.embeddingsProvider.maxChunkSize, + maxChunkSize: this.embeddingsProvider.maxEmbeddingChunkSize, digest: item.cacheKey, }; @@ -168,7 +167,7 @@ export class LanceDbIndex implements CodebaseIndex { return await this.embeddingsProvider.embed(chunks.map((c) => c.content)); } catch (err) { throw new Error( - `Failed to generate embeddings for ${chunks.length} chunks with provider: ${this.embeddingsProvider.id}: ${err}`, + `Failed to generate embeddings for ${chunks.length} chunks with provider: ${this.embeddingsProvider.embeddingId}: ${err}`, { cause: err }, ); } @@ -350,7 +349,7 @@ export class LanceDbIndex implements CodebaseIndex { accumulatedProgress += 1 / results.addTag.length / 3; yield { progress: accumulatedProgress, - desc: `Indexing ${getBasename(path)}`, + desc: `Indexing ${getUriPathBasename(path)}`, status: "indexing", }; } @@ -372,7 +371,7 @@ export class LanceDbIndex implements CodebaseIndex { accumulatedProgress += 1 / toDel.length / 3; yield { progress: accumulatedProgress, - desc: `Stashing ${getBasename(path)}`, + desc: `Stashing ${getUriPathBasename(path)}`, status: "indexing", }; } @@ -391,7 +390,7 @@ export class LanceDbIndex implements CodebaseIndex { accumulatedProgress += 1 / results.del.length / 3; yield { progress: accumulatedProgress, - desc: `Removing ${getBasename(path)}`, + desc: `Removing ${getUriPathBasename(path)}`, status: "indexing", }; } diff --git a/core/indexing/allEmbeddingsProviders.ts b/core/indexing/allEmbeddingsProviders.ts new file mode 100644 index 000000000..b50aa91f9 --- /dev/null +++ b/core/indexing/allEmbeddingsProviders.ts @@ -0,0 +1,49 @@ +import { ILLM } from "../index.js"; +import Bedrock from "../llm/llms/Bedrock.js"; +import Cohere from "../llm/llms/Cohere.js"; +import DeepInfra from "../llm/llms/DeepInfra.js"; +import FreeTrial from "../llm/llms/FreeTrial.js"; +import FunctionNetwork from "../llm/llms/FunctionNetwork.js"; +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 Nebius from "../llm/llms/Nebius.js"; +import Nvidia from "../llm/llms/Nvidia.js"; +import Ollama from "../llm/llms/Ollama.js"; +import OpenAI from "../llm/llms/OpenAI.js"; +import SageMaker from "../llm/llms/SageMaker.js"; +import SiliconFlow from "../llm/llms/SiliconFlow.js"; +import ContinueProxy from "../llm/llms/stubs/ContinueProxy.js"; +import TransformersJsEmbeddingsProvider from "../llm/llms/TransformersJsEmbeddingsProvider.js"; +import VertexAI from "../llm/llms/VertexAI.js"; +import Voyage from "../llm/llms/Voyage.js"; +import WatsonX from "../llm/llms/WatsonX.js"; + +type EmbeddingsProviderConstructor = new (...args: any[]) => ILLM; + +export const allEmbeddingsProviders: Record< + string, + EmbeddingsProviderConstructor +> = { + sagemaker: SageMaker, + bedrock: Bedrock, + ollama: Ollama, + "transformers.js": TransformersJsEmbeddingsProvider, + openai: OpenAI, + cohere: Cohere, + "free-trial": FreeTrial, + "function-network": FunctionNetwork, + "huggingface-tei": HuggingFaceTEIEmbeddingsProvider, + gemini: Gemini, + "continue-proxy": ContinueProxy, + deepinfra: DeepInfra, + nvidia: Nvidia, + voyage: Voyage, + mistral: Mistral, + nebius: Nebius, + vertexai: VertexAI, + watsonx: WatsonX, + lmstudio: LMStudio, + siliconflow: SiliconFlow, +}; diff --git a/core/indexing/chunk/basic.test.ts b/core/indexing/chunk/basic.test.ts new file mode 100644 index 000000000..4c65f2fa8 --- /dev/null +++ b/core/indexing/chunk/basic.test.ts @@ -0,0 +1,87 @@ +// Generated by continue +// core/indexing/chunk/basic.test.ts + +import { basicChunker } from "./basic.js"; +import { countTokensAsync } from "../../llm/countTokens"; +import { ChunkWithoutID } from "../../index"; + +// jest.mock("../../llm/countTokens", () => ({ +// countTokensAsync: jest.fn(), +// })); + +describe.skip("basicChunker", () => { + beforeEach(() => { + jest.resetAllMocks(); + }); + + it("should yield no chunks for empty content", async () => { + const contents = ""; + const maxChunkSize = 10; + const chunks: ChunkWithoutID[] = []; + + for await (const chunk of basicChunker(contents, maxChunkSize)) { + chunks.push(chunk); + } + + expect(chunks).toHaveLength(0); + }); + + it("should yield a single chunk if whole content fits within the max size", async () => { + (countTokensAsync as jest.Mock).mockResolvedValue(1); + const contents = "line1\nline2\nline3"; + const maxChunkSize = 10; + const expectedChunks: ChunkWithoutID[] = [ + { content: "line1\nline2\nline3\n", startLine: 0, endLine: 2 }, + ]; + + const chunks: ChunkWithoutID[] = []; + for await (const chunk of basicChunker(contents, maxChunkSize)) { + chunks.push(chunk); + } + + expect(chunks).toEqual(expectedChunks); + }); + + it("should yield multiple chunks when content exceeds the max size", async () => { + (countTokensAsync as jest.Mock).mockImplementation(async (line: string) => { + if (line === "line3") return 5; + return 3; // Mock returning 3 tokens per line except for "line3" + }); + + const contents = "line1\nline2\nline3\nline4\nline5"; + const maxChunkSize = 8; + const expectedChunks: ChunkWithoutID[] = [ + { content: "line1\nline2\n", startLine: 0, endLine: 1 }, + { content: "line3\n", startLine: 2, endLine: 2 }, + { content: "line4\nline5\n", startLine: 3, endLine: 4 }, + ]; + + const chunks: ChunkWithoutID[] = []; + for await (const chunk of basicChunker(contents, maxChunkSize)) { + chunks.push(chunk); + } + + expect(chunks).toEqual(expectedChunks); + }); + + it("should skip lines that exceed the max chunk size", async () => { + (countTokensAsync as jest.Mock).mockImplementation(async (line: string) => { + if (line === "line3") return 15; // Making it explicitly exceed max size + return 3; + }); + + const contents = "line1\nline2\nline3\nline4\nline5"; + const maxChunkSize = 8; + const expectedChunks: ChunkWithoutID[] = [ + { content: "line1\nline2\n", startLine: 0, endLine: 1 }, + { content: "line4\nline5\n", startLine: 3, endLine: 4 }, + ]; + + const chunks: ChunkWithoutID[] = []; + for await (const chunk of basicChunker(contents, maxChunkSize)) { + chunks.push(chunk); + } + + expect(chunks).toEqual(expectedChunks); + }); +}); diff --git a/core/indexing/docs/DocsService.test.ts b/core/indexing/docs/DocsService.skip.ts similarity index 96% rename from core/indexing/docs/DocsService.test.ts rename to core/indexing/docs/DocsService.skip.ts index 67d33020d..22c307f35 100644 --- a/core/indexing/docs/DocsService.test.ts +++ b/core/indexing/docs/DocsService.skip.ts @@ -4,9 +4,9 @@ import { ConfigHandler } from "../../config/ConfigHandler.js"; import { ControlPlaneClient } from "../../control-plane/client.js"; import { SiteIndexingConfig } from "../../index.js"; +import FreeTrial from "../../llm/llms/FreeTrial.js"; import FileSystemIde from "../../util/filesystem.js"; import { editConfigJson } from "../../util/paths.js"; -import FreeTrialEmbeddingsProvider from "../embeddings/FreeTrialEmbeddingsProvider.js"; import DocsService from "./DocsService.js"; import preIndexedDocs from "./preIndexedDocs.js"; @@ -113,7 +113,7 @@ describe.skip("DocsService Integration Tests", () => { editConfigJson((config) => ({ ...config, embeddingsProvider: { - provider: FreeTrialEmbeddingsProvider.providerName, + provider: FreeTrial.providerName, }, })); diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index b52577a5f..f35f83466 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -5,26 +5,26 @@ import lancedb, { Connection } from "vectordb"; import { Chunk, ContinueConfig, - EmbeddingsProvider, IDE, IdeInfo, + ILLM, IndexingStatus, SiteIndexingConfig, } from "../.."; import { ConfigHandler } from "../../config/ConfigHandler"; import { addContextProvider } from "../../config/util"; import DocsContextProvider from "../../context/providers/DocsContextProvider"; +import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider"; import { FromCoreProtocol, ToCoreProtocol } from "../../protocol"; import { fetchFavicon, getFaviconBase64 } from "../../util/fetchFavicon"; import { GlobalContext } from "../../util/GlobalContext"; -import { IMessenger } from "../../util/messenger"; +import { IMessenger } from "../../protocol/messenger"; import { editConfigJson, getDocsSqlitePath, getLanceDbPath, } from "../../util/paths"; import { Telemetry } from "../../util/posthog"; -import TransformersJsEmbeddingsProvider from "../embeddings/TransformersJsEmbeddingsProvider"; import { Article, chunkArticle, pageToArticle } from "./article"; import DocsCrawler from "./DocsCrawler"; @@ -37,12 +37,6 @@ import { } from "./preIndexed"; import preIndexedDocs from "./preIndexedDocs"; -// Progress heuristic values -// subpages -> embeddings -> delete from db -> add to db -const PROGRESS_AT_EMBEDDING = 0.5; -const PROGRESS_AT_DELETE_OPERATIONS = 0.7; -const PROGRESS_AT_ADD_OPERATIONS = 0.8; - // Purposefully lowercase because lancedb converts export interface LanceDbDocsRow { title: string; @@ -162,7 +156,7 @@ export default class DocsService { const sharedStatus = { type: "docs" as IndexingStatus["type"], id: doc.startUrl, - embeddingsProviderId: this.config.embeddingsProvider.id, + embeddingsProviderId: this.config.embeddingsProvider.embeddingId, isReindexing: false, title: doc.title, debugInfo: `max depth: ${doc.maxDepth}`, @@ -206,19 +200,19 @@ export default class DocsService { } // NOTE Pausing not supported for docs yet - setPaused(startUrl: string, pause: boolean) { - const status = this.statuses.get(startUrl); - if (status) { - this.handleStatusUpdate({ - ...status, - status: pause ? "paused" : "indexing", - }); - } - } + // setPaused(startUrl: string, pause: boolean) { + // const status = this.statuses.get(startUrl); + // if (status) { + // this.handleStatusUpdate({ + // ...status, + // status: pause ? "paused" : "indexing", + // }); + // } + // } - isPaused(startUrl: string) { - return this.statuses.get(startUrl)?.status === "paused"; - } + // isPaused(startUrl: string) { + // return this.statuses.get(startUrl)?.status === "paused"; + // } /* * Currently, we generate and host embeddings for pre-indexed docs using transformers. @@ -235,15 +229,13 @@ export default class DocsService { async isUsingUnsupportedPreIndexedEmbeddingsProvider() { const isPreIndexedDocsProvider = - this.config.embeddingsProvider.id === - DocsService.preIndexedDocsEmbeddingsProvider.id; + this.config.embeddingsProvider.embeddingId === + DocsService.preIndexedDocsEmbeddingsProvider.embeddingId; const canUsePreindexedDocs = await this.canUsePreindexedDocs(); return isPreIndexedDocsProvider && !canUsePreindexedDocs; } - async getEmbeddingsProvider( - isPreIndexedDoc: boolean = false, - ): Promise { + async getEmbeddingsProvider(isPreIndexedDoc: boolean = false): Promise { const canUsePreindexedDocs = await this.canUsePreindexedDocs(); if (canUsePreindexedDocs && isPreIndexedDoc) { @@ -286,7 +278,7 @@ export default class DocsService { ); if ( !curEmbeddingsProviderId || - curEmbeddingsProviderId !== newConfig.embeddingsProvider.id + curEmbeddingsProviderId !== newConfig.embeddingsProvider.embeddingId ) { // If not set, we're initializing const currentDocs = await this.listMetadata(); @@ -383,20 +375,13 @@ export default class DocsService { const indexExists = await this.hasMetadata(startUrl); // Build status update - most of it is fixed values - const fixedStatus: Pick< + const fixedStatus: Omit< IndexingStatus, - | "type" - | "id" - | "embeddingsProviderId" - | "isReindexing" - | "debugInfo" - | "icon" - | "url" - | "title" + "progress" | "description" | "status" > = { type: "docs", id: siteIndexingConfig.startUrl, - embeddingsProviderId: embeddingsProvider.id, + embeddingsProviderId: embeddingsProvider.embeddingId, isReindexing: reIndex && indexExists, title: siteIndexingConfig.title, debugInfo: `max depth: ${siteIndexingConfig.maxDepth}`, @@ -405,7 +390,6 @@ export default class DocsService { }; // Clear current indexes if reIndexing - // if (indexExists) { if (reIndex) { await this.deleteIndexes(startUrl); @@ -452,9 +436,9 @@ export default class DocsService { description: `Finding subpages (${page.path})`, status: "indexing", progress: - 0.3 * estimatedProgress + - Math.min(0.2, (0.2 * processedPages) / 500), - // For the first 50%, 30% is sum of series 1/(2^n) and the other 20% is based on number of files/ 500 max + 0.15 * estimatedProgress + + Math.min(0.35, (0.35 * processedPages) / 500), + // For the first 50%, 15% is sum of series 1/(2^n) and the other 35% is based on number of files/ 500 max }); const article = pageToArticle(page); @@ -464,7 +448,11 @@ export default class DocsService { articles.push(article); processedPages++; - await new Promise((resolve) => setTimeout(resolve, 100)); // Locks down GUI if no sleeping + + // Locks down GUI if no sleeping + // Wait proportional to how many docs are indexing + const toWait = 100 * this.docsIndexingQueue.size + 50; + await new Promise((resolve) => setTimeout(resolve, toWait)); } void Telemetry.capture("docs_pages_crawled", { @@ -491,7 +479,7 @@ export default class DocsService { try { const chunkedArticle = chunkArticle( article, - embeddingsProvider.maxChunkSize, + embeddingsProvider.maxEmbeddingChunkSize, ); const chunkedArticleContents = chunkedArticle.map( @@ -606,7 +594,7 @@ export default class DocsService { const data = await downloadFromS3( S3Buckets.continueIndexedDocs, - getS3Filename(embeddingsProvider.id, title), + getS3Filename(embeddingsProvider.embeddingId, title), ); const siteEmbeddings = JSON.parse(data) as SiteIndexingResults; @@ -638,7 +626,7 @@ export default class DocsService { if (await this.isUsingUnsupportedPreIndexedEmbeddingsProvider()) { await this.ide.showToast( "error", - `${DocsService.preIndexedDocsEmbeddingsProvider.id} is configured as ` + + `${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.", @@ -799,7 +787,7 @@ export default class DocsService { this.handleStatusUpdate({ type: "docs", id: doc.startUrl, - embeddingsProviderId: this.config.embeddingsProvider.id, + embeddingsProviderId: this.config.embeddingsProvider.embeddingId, isReindexing: false, title: doc.title, debugInfo: "Config sync: not changed", @@ -882,7 +870,7 @@ export default class DocsService { await this.getEmbeddingsProvider(isPreIndexedDoc); const tableName = this.sanitizeLanceTableName( - `${DocsService.lanceTableName}${embeddingsProvider.id}`, + `${DocsService.lanceTableName}${embeddingsProvider.embeddingId}`, ); return tableName; @@ -1017,13 +1005,10 @@ export default class DocsService { } async delete(startUrl: string) { + this.docsIndexingQueue.delete(startUrl); + this.abort(startUrl); await this.deleteIndexes(startUrl); this.deleteFromConfig(startUrl); - - const status = this.statuses.get(startUrl); - if (status) { - this.handleStatusUpdate({ ...status, status: "deleted" }); - } this.messenger?.send("refreshSubmenuItems", undefined); } @@ -1042,14 +1027,17 @@ export default class DocsService { } console.log( - `Reindexing non-preindexed docs with new embeddings provider: ${embeddingsProvider.id}`, + `Reindexing non-preindexed docs with new embeddings provider: ${embeddingsProvider.embeddingId}`, ); await Promise.allSettled(docs.map((doc) => this.indexAndAdd(doc))); // Important that this only is invoked after we have successfully // cleared and reindex the docs so that the table cannot end up in an // invalid state. - this.globalContext.update("curEmbeddingsProviderId", embeddingsProvider.id); + this.globalContext.update( + "curEmbeddingsProviderId", + embeddingsProvider.embeddingId, + ); console.log("Completed reindexing of all non-preindexed docs"); } diff --git a/core/indexing/docs/preIndexedDocs.ts b/core/indexing/docs/preIndexedDocs.ts index 99a8ddc8a..93eaa8411 100644 --- a/core/indexing/docs/preIndexedDocs.ts +++ b/core/indexing/docs/preIndexedDocs.ts @@ -336,6 +336,18 @@ const preIndexedDocs: Record< rootUrl: "https://go.dev", faviconUrl: "https://go.dev/favicon.ico", }, + "https://api.flutter.dev": { + title: "Flutter", + startUrl: "https://api.flutter.dev", + rootUrl: "https://api.flutter.dev", + faviconUrl: "https://api.flutter.dev/flutter/static-assets/favicon.png", + }, + "https://api.dart.dev": { + title: "Dart", + startUrl: "https://api.dart.dev", + rootUrl: "https://api.dart.dev", + faviconUrl: "https://api.dart.dev/static-assets/favicon.png", + }, }; export default preIndexedDocs; diff --git a/core/indexing/docs/suggestions/suggestions.test.ts b/core/indexing/docs/suggestions/suggestions.test.ts new file mode 100644 index 000000000..60b58caa6 --- /dev/null +++ b/core/indexing/docs/suggestions/suggestions.test.ts @@ -0,0 +1,283 @@ +// Generated by continue + +import { getAllSuggestedDocs } from "./index"; +import { testIde } from "../../../test/fixtures"; +import { + setUpTestDir, + tearDownTestDir, + addToTestDir, +} from "../../../test/testDir"; +import fetch, { RequestInfo } from "node-fetch"; + +jest.mock("node-fetch", undefined, { + virtual: false, +}); + +describe.skip("getAllSuggestedDocs", () => { + beforeEach(() => { + setUpTestDir(); + jest.clearAllMocks(); + }); + + afterEach(() => { + tearDownTestDir(); + jest.restoreAllMocks(); + }); + + it("should return package docs for JavaScript and Python projects", async () => { + // Set up test files + addToTestDir([ + [ + "package.json", + JSON.stringify({ + dependencies: { + express: "^4.17.1", + lodash: "^4.17.21", + }, + devDependencies: { + typescript: "^4.0.0", + }, + }), + ], + ["requirements.txt", "requests==2.25.1\nflask==1.1.2"], + ]); + + const mockedFetch = fetch as jest.MockedFunction; + mockedFetch.mockImplementation((url: URL | RequestInfo) => { + if (url.toString().includes("registry.npmjs.org/express")) { + return Promise.resolve({ + ok: true, + json: jest.fn().mockResolvedValue({ + homepage: "https://expressjs.com/", + name: "express", + description: "Fast, unopinionated, minimalist web framework", + license: "MIT", + }), + }) as any; + } else if (url.toString().includes("registry.npmjs.org/lodash")) { + return Promise.resolve({ + ok: true, + json: jest.fn().mockResolvedValue({ + homepage: "https://lodash.com/", + name: "lodash", + description: "Lodash modular utilities.", + license: "MIT", + }), + }) as any; + } else if (url.toString().includes("pypi.org/pypi/requests/json")) { + return Promise.resolve({ + ok: true, + json: jest.fn().mockResolvedValue({ + info: { + home_page: "https://docs.python-requests.org/", + name: "requests", + summary: "Python HTTP for Humans.", + license: "Apache 2.0", + }, + }), + }) as any; + } else if (url.toString().includes("pypi.org/pypi/flask/json")) { + return Promise.resolve({ + ok: true, + json: jest.fn().mockResolvedValue({ + info: { + home_page: "https://palletsprojects.com/p/flask/", + name: "flask", + summary: + "A simple framework for building complex web applications.", + license: "BSD-3-Clause", + }, + }), + }) as any; + } else { + return Promise.reject(new Error(`Unhandled URL: ${url}`)); + } + }); + + const results = await getAllSuggestedDocs(testIde); + + expect(results).toHaveLength(4); + expect(results).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + packageInfo: expect.objectContaining({ name: "express" }), + details: expect.objectContaining({ + docsLink: "https://expressjs.com/", + }), + }), + expect.objectContaining({ + packageInfo: expect.objectContaining({ name: "lodash" }), + details: expect.objectContaining({ + docsLink: "https://lodash.com/", + }), + }), + expect.objectContaining({ + packageInfo: expect.objectContaining({ name: "requests" }), + details: expect.objectContaining({ + docsLink: "https://docs.python-requests.org/", + }), + }), + expect.objectContaining({ + packageInfo: expect.objectContaining({ name: "flask" }), + details: expect.objectContaining({ + docsLink: "https://palletsprojects.com/p/flask/", + }), + }), + ]), + ); + + // Verify no errors are present + results.forEach((result) => { + expect(result.error).toBeUndefined(); + }); + }); + + it("should handle packages without documentation links", async () => { + addToTestDir([ + [ + "package.json", + JSON.stringify({ + dependencies: { + "no-docs-package": "^1.0.0", + }, + }), + ], + ]); + + // Mock fetch + const mockedFetch = fetch as jest.MockedFunction; + mockedFetch.mockImplementation((url: RequestInfo | URL) => { + if (url.toString().includes("registry.npmjs.org/no-docs-package")) { + return Promise.resolve({ + ok: true, + json: jest.fn().mockResolvedValue({ + name: "no-docs-package", + description: "A package without docs", + license: "MIT", + // No homepage provided + }), + }) as any; + } else { + return Promise.reject(new Error(`Unhandled URL: ${url}`)); + } + }); + + const results = await getAllSuggestedDocs(testIde); + + expect(results).toHaveLength(1); + expect(results[0].error).toContain( + "No documentation link found for no-docs-package", + ); + expect(results[0].details).toBeUndefined(); + }); + + it("should handle errors when fetching package details", async () => { + addToTestDir([ + [ + "package.json", + JSON.stringify({ + dependencies: { + "error-package": "^1.0.0", + }, + }), + ], + ]); + + // Mock fetch + const mockedFetch = fetch as jest.MockedFunction; + mockedFetch.mockImplementation((url: URL | RequestInfo) => { + if (url.toString().includes("registry.npmjs.org/error-package")) { + return Promise.resolve({ + ok: false, + }) as any; + } else { + return Promise.reject(new Error(`Unhandled URL: ${url}`)); + } + }); + + const results = await getAllSuggestedDocs(testIde); + + expect(results).toHaveLength(1); + expect(results[0].error).toContain( + "Error getting package details for error-package", + ); + expect(results[0].details).toBeUndefined(); + }); + + it("should handle workspaces with no package files", async () => { + const results = await getAllSuggestedDocs(testIde); + + expect(results).toEqual([]); + }); + + it("should handle packages with GitHub documentation links", async () => { + addToTestDir([ + [ + "package.json", + JSON.stringify({ + dependencies: { + "github-docs-package": "^1.0.0", + }, + }), + ], + ]); + + // Mock fetch + const mockedFetch = fetch as jest.MockedFunction; + mockedFetch.mockImplementation((url: URL | RequestInfo) => { + if (url.toString().includes("registry.npmjs.org/github-docs-package")) { + return Promise.resolve({ + ok: true, + json: jest.fn().mockResolvedValue({ + homepage: "https://github.com/user/repo", + name: "github-docs-package", + description: "A package with GitHub docs", + license: "MIT", + }), + }) as any; + } else { + return Promise.reject(new Error(`Unhandled URL: ${url}`)); + } + }); + + const results = await getAllSuggestedDocs(testIde); + + expect(results).toHaveLength(1); + expect(results[0].details?.docsLink).toBe("https://github.com/user/repo"); + expect(results[0].details?.docsLinkWarning).toBe( + "Github docs not supported, find the docs site", + ); + }); + + it("should handle packages with non-docs links", async () => { + addToTestDir([["requirements.txt", "non-docs-package==1.0.0"]]); + + // Mock fetch + const mockedFetch = fetch as jest.MockedFunction; + mockedFetch.mockImplementation((url: URL | RequestInfo) => { + if (url.toString().includes("pypi.org/pypi/non-docs-package/json")) { + return Promise.resolve({ + ok: true, + json: jest.fn().mockResolvedValue({ + info: { + home_page: "https://somewebsite.com", + name: "non-docs-package", + summary: "A package with non-docs homepage", + license: "MIT", + }, + }), + }) as any; + } else { + return Promise.reject(new Error(`Unhandled URL: ${url}`)); + } + }); + + const results = await getAllSuggestedDocs(testIde); + + expect(results).toHaveLength(1); + expect(results[0].details?.docsLink).toBe("https://somewebsite.com"); + expect(results[0].details?.docsLinkWarning).toBe( + "May not be a docs site, check the URL", + ); + }); +}); diff --git a/core/indexing/embeddings/BaseEmbeddingsProvider.ts b/core/indexing/embeddings/BaseEmbeddingsProvider.ts deleted file mode 100644 index 4f988705d..000000000 --- a/core/indexing/embeddings/BaseEmbeddingsProvider.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { - EmbedOptions, - EmbeddingsProvider, - EmbeddingsProviderName, - FetchFunction, -} from "../../index.js"; -import { DEFAULT_MAX_CHUNK_SIZE } from "../../llm/constants.js"; - -export interface IBaseEmbeddingsProvider extends EmbeddingsProvider { - options: EmbedOptions; - fetch: FetchFunction; - defaultOptions?: EmbedOptions; - maxBatchSize?: number; -} - -abstract class BaseEmbeddingsProvider implements IBaseEmbeddingsProvider { - static maxBatchSize: IBaseEmbeddingsProvider["maxBatchSize"]; - static defaultOptions: IBaseEmbeddingsProvider["defaultOptions"]; - - static providerName: EmbeddingsProviderName; - get providerName(): EmbeddingsProviderName { - return (this.constructor as typeof BaseEmbeddingsProvider).providerName; - } - - options: IBaseEmbeddingsProvider["options"]; - fetch: IBaseEmbeddingsProvider["fetch"]; - id: IBaseEmbeddingsProvider["id"]; - - constructor( - options: IBaseEmbeddingsProvider["options"], - fetch: IBaseEmbeddingsProvider["fetch"], - ) { - // Overwrite default options with any runtime options - this.options = { - ...(this.constructor as typeof BaseEmbeddingsProvider).defaultOptions, - ...options, - }; - this.fetch = fetch; - // Include the `max_chunk_size` if it is not the default, since we need to create other indices for different chunk_sizes - if (this.maxChunkSize !== DEFAULT_MAX_CHUNK_SIZE) { - this.id = `${this.constructor.name}::${this.options.model}::${this.maxChunkSize}`; - } else { - this.id = `${this.constructor.name}::${this.options.model}`; - } - } - defaultOptions?: EmbedOptions | undefined; - get maxBatchSize(): number | undefined { - return this.options.maxBatchSize ?? (this.constructor as typeof BaseEmbeddingsProvider).maxBatchSize; - } - - abstract embed(chunks: string[]): Promise; - - get maxChunkSize(): number { - return this.options.maxChunkSize ?? DEFAULT_MAX_CHUNK_SIZE; - } - - getBatchedChunks(chunks: string[]): string[][] { - if (!this.maxBatchSize) { - console.warn( - `${this.getBatchedChunks.name} should only be called if 'maxBatchSize' is defined`, - ); - - return [chunks]; - } - - const batchedChunks = []; - - for (let i = 0; i < chunks.length; i += this.maxBatchSize) { - batchedChunks.push(chunks.slice(i, i + this.maxBatchSize)); - } - - return batchedChunks; - } -} - -export default BaseEmbeddingsProvider; diff --git a/core/indexing/embeddings/BedrockEmbeddingsProvider.ts b/core/indexing/embeddings/BedrockEmbeddingsProvider.ts deleted file mode 100644 index a490cf0ff..000000000 --- a/core/indexing/embeddings/BedrockEmbeddingsProvider.ts +++ /dev/null @@ -1,122 +0,0 @@ -import { - BedrockRuntimeClient, - InvokeModelCommand, -} from "@aws-sdk/client-bedrock-runtime"; -import { fromIni } from "@aws-sdk/credential-providers"; - -import { EmbeddingsProviderName, EmbedOptions, FetchFunction } from "../../index.js"; - -import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js"; - -interface ModelConfig { - formatPayload: (text: string) => any; - extractEmbeddings: (responseBody: any) => number[][]; -} - -class BedrockEmbeddingsProvider extends BaseEmbeddingsProvider { - static providerName: EmbeddingsProviderName = "bedrock"; - static defaultOptions: Partial = { - model: "amazon.titan-embed-text-v2:0", - region: "us-east-1" - }; - profile?: string | undefined; - - constructor(options: EmbedOptions, fetch: FetchFunction) { - super(options, fetch); - this.options.model = this.options.model || BedrockEmbeddingsProvider.defaultOptions.model!; - if (!options.apiBase) { - options.apiBase = `https://bedrock-runtime.${options.region}.amazonaws.com`; - } - - if (options.profile) { - this.profile = options.profile; - } else { - this.profile = "bedrock"; - } - } - - async embed(chunks: string[]): Promise { - const credentials = await this._getCredentials(); - const client = new BedrockRuntimeClient({ - region: this.options.region, - credentials: { - accessKeyId: credentials.accessKeyId, - secretAccessKey: credentials.secretAccessKey, - sessionToken: credentials.sessionToken || "", - }, - }); - - return ( - await Promise.all( - chunks.map(async (chunk) => { - const input = this._generateInvokeModelCommandInput(chunk); - const command = new InvokeModelCommand(input); - const response = await client.send(command); - if (response.body) { - const responseBody = JSON.parse(new TextDecoder().decode(response.body)); - return this._extractEmbeddings(responseBody); - } - return []; - }), - ) - ).flat(); - } - - private _generateInvokeModelCommandInput(text: string): any { - const modelConfig = this._getModelConfig(); - const payload = modelConfig.formatPayload(text); - - return { - body: JSON.stringify(payload), - modelId: this.options.model, - accept: "*/*", - contentType: "application/json", - }; - } - - private _extractEmbeddings(responseBody: any): number[][] { - const modelConfig = this._getModelConfig(); - return modelConfig.extractEmbeddings(responseBody); - } - - private _getModelConfig() { - const modelConfigs: { [key: string]: ModelConfig } = { - "cohere": { - formatPayload: (text: string) => ({ - texts: [text], - input_type: "search_document", - truncate: "END", - }), - extractEmbeddings: (responseBody: any) => responseBody.embeddings || [], - }, - "amazon.titan-embed": { - formatPayload: (text: string) => ({ - inputText: text, - }), - extractEmbeddings: (responseBody: any) => responseBody.embedding ? [responseBody.embedding] : [], - }, - }; - - const modelPrefix = Object.keys(modelConfigs).find(prefix => this.options.model!.startsWith(prefix)); - if (!modelPrefix) { - throw new Error(`Unsupported model: ${this.options.model}`); - } - return modelConfigs[modelPrefix]; - } - - private async _getCredentials() { - try { - return await fromIni({ - profile: this.profile, - ignoreCache: true - })(); - } catch (e) { - console.warn( - `AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`, - ); - return await fromIni()(); - } - } -} - -export default BedrockEmbeddingsProvider; diff --git a/core/indexing/embeddings/CohereEmbeddingsProvider.ts b/core/indexing/embeddings/CohereEmbeddingsProvider.ts deleted file mode 100644 index 46db24c27..000000000 --- a/core/indexing/embeddings/CohereEmbeddingsProvider.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { Response } from "node-fetch"; - -import { EmbeddingsProviderName, EmbedOptions } from "../../index.js"; -import { withExponentialBackoff } from "../../util/withExponentialBackoff.js"; - -import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js"; - -class CohereEmbeddingsProvider extends BaseEmbeddingsProvider { - static maxBatchSize = 96; - - static providerName: EmbeddingsProviderName = "cohere"; - - static defaultOptions: Partial | undefined = { - apiBase: "https://api.cohere.ai/v1/", - model: "embed-english-v3.0", - }; - - async embed(chunks: string[]) { - if (!this.options.apiBase?.endsWith("/")) { - this.options.apiBase += "/"; - } - - const batchedChunks = this.getBatchedChunks(chunks); - return ( - await Promise.all( - batchedChunks.map(async (batch) => { - const fetchWithBackoff = () => - withExponentialBackoff(() => - this.fetch(new URL("embed", this.options.apiBase), { - method: "POST", - body: JSON.stringify({ - texts: batch, - model: this.options.model, - input_type: "search_document", - embedding_types: ["float"], - truncate: "END", - }), - headers: { - Authorization: `Bearer ${this.options.apiKey}`, - "Content-Type": "application/json", - }, - }), - ); - const resp = await fetchWithBackoff(); - - if (!resp.ok) { - throw new Error(await resp.text()); - } - - const data = (await resp.json()) as any; - return data.embeddings.float; - }), - ) - ).flat(); - } -} - -export default CohereEmbeddingsProvider; diff --git a/core/indexing/embeddings/ContinueProxyEmbeddingsProvider.ts b/core/indexing/embeddings/ContinueProxyEmbeddingsProvider.ts deleted file mode 100644 index 8fa6fc15f..000000000 --- a/core/indexing/embeddings/ContinueProxyEmbeddingsProvider.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js"; -import { EmbeddingsProviderName } from "../../index.js"; - -import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider.js"; - -class ContinueProxyEmbeddingsProvider extends OpenAIEmbeddingsProvider { - static providerName: EmbeddingsProviderName = "continue-proxy"; - - set controlPlaneProxyInfo(value: ControlPlaneProxyInfo) { - this.options.apiKey = value.workOsAccessToken; - this.options.apiBase = new URL( - "openai/v1", - value.controlPlaneProxyUrl, - ).toString(); - } -} - -export default ContinueProxyEmbeddingsProvider; diff --git a/core/indexing/embeddings/DeepInfraEmbeddingsProvider.ts b/core/indexing/embeddings/DeepInfraEmbeddingsProvider.ts deleted file mode 100644 index 1249116d8..000000000 --- a/core/indexing/embeddings/DeepInfraEmbeddingsProvider.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { EmbeddingsProviderName, EmbedOptions } from "../../index.js"; -import { withExponentialBackoff } from "../../util/withExponentialBackoff.js"; - -import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js"; - -class DeepInfraEmbeddingsProvider extends BaseEmbeddingsProvider { - static providerName: EmbeddingsProviderName = "deepinfra"; - static defaultOptions: Partial | undefined = { - model: "sentence-transformers/all-MiniLM-L6-v2", - }; - - async embed(chunks: string[]) { - const fetchWithBackoff = () => - withExponentialBackoff(() => - this.fetch( - `https://api.deepinfra.com/v1/inference/${this.options.model}`, - { - method: "POST", - headers: { - Authorization: `bearer ${this.options.apiKey}`, - }, - body: JSON.stringify({ inputs: chunks }), - }, - ), - ); - const resp = await fetchWithBackoff(); - const data = await resp.json(); - return data.embeddings; - } -} - -export default DeepInfraEmbeddingsProvider; diff --git a/core/indexing/embeddings/FreeTrialEmbeddingsProvider.ts b/core/indexing/embeddings/FreeTrialEmbeddingsProvider.ts deleted file mode 100644 index 9e9d28474..000000000 --- a/core/indexing/embeddings/FreeTrialEmbeddingsProvider.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { Response } from "node-fetch"; - -import { getHeaders } from "../../continueServer/stubs/headers.js"; -import { TRIAL_PROXY_URL } from "../../control-plane/client.js"; -import { - EmbeddingsProviderName, - EmbedOptions, - FetchFunction, -} from "../../index.js"; -import { withExponentialBackoff } from "../../util/withExponentialBackoff.js"; - -import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js"; - -class FreeTrialEmbeddingsProvider extends BaseEmbeddingsProvider { - static providerName: EmbeddingsProviderName = "free-trial"; - static maxBatchSize = 128; - - static defaultOptions: Partial | undefined = { - model: "voyage-code-2", - }; - - constructor(options: EmbedOptions, fetch: FetchFunction) { - super(options, fetch); - this.options.model = FreeTrialEmbeddingsProvider.defaultOptions?.model; - this.id = `${this.constructor.name}::${this.options.model}`; - } - - async embed(chunks: string[]) { - const batchedChunks = this.getBatchedChunks(chunks); - return ( - await Promise.all( - batchedChunks.map(async (batch) => { - if (batch.length === 0) { - return []; - } - const fetchWithBackoff = () => - withExponentialBackoff(async () => - this.fetch(new URL("embeddings", TRIAL_PROXY_URL), { - method: "POST", - body: JSON.stringify({ - input: batch, - model: this.options.model, - }), - headers: { - "Content-Type": "application/json", - ...(await getHeaders()), - }, - }), - ); - const resp = await fetchWithBackoff(); - - if (resp.status !== 200) { - throw new Error( - `Failed to embed: ${resp.status} ${await resp.text()}`, - ); - } - - const data = (await resp.json()) as any; - return data.embeddings; - }), - ) - ).flat(); - } -} - -export default FreeTrialEmbeddingsProvider; diff --git a/core/indexing/embeddings/FunctionNetworkEmbeddingsProvider.ts b/core/indexing/embeddings/FunctionNetworkEmbeddingsProvider.ts deleted file mode 100644 index fe16dbc51..000000000 --- a/core/indexing/embeddings/FunctionNetworkEmbeddingsProvider.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { Response } from "node-fetch"; - -import { EmbeddingsProviderName, EmbedOptions } from "../../index.js"; -import { withExponentialBackoff } from "../../util/withExponentialBackoff.js"; - -import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js"; - -class FunctionNetworkEmbeddingsProvider extends BaseEmbeddingsProvider { - static providerName: EmbeddingsProviderName = "function-network"; - static maxBatchSize = 128; - - static defaultOptions: Partial | undefined = { - apiBase: "https://api.function.network/v1/", - model: "baai/bge-base-en-v1.5", - }; - - private _getEndpoint() { - if (!this.options.apiBase) { - throw new Error( - "No API base URL provided. Please set the 'apiBase' option in config.json", - ); - } - - this.options.apiBase = this.options.apiBase.endsWith("/") - ? this.options.apiBase - : `${this.options.apiBase}/`; - return new URL("embeddings", this.options.apiBase); - } - - async embed(chunks: string[]) { - const batchedChunks = this.getBatchedChunks(chunks); - return ( - await Promise.all( - batchedChunks.map(async (batch) => { - if (batch.length === 0) { - return []; - } - - const fetchWithBackoff = () => - withExponentialBackoff(() => - this.fetch(this._getEndpoint(), { - method: "POST", - body: JSON.stringify({ - input: batch, - model: this.options.model, - }), - headers: { - Authorization: `Bearer ${this.options.apiKey}`, - "Content-Type": "application/json", - }, - }), - ); - const resp = await fetchWithBackoff(); - - 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, - ); - }), - ) - ).flat(); - } -} - -export default FunctionNetworkEmbeddingsProvider; diff --git a/core/indexing/embeddings/GeminiEmbeddingsProvider.ts b/core/indexing/embeddings/GeminiEmbeddingsProvider.ts deleted file mode 100644 index f39cedc50..000000000 --- a/core/indexing/embeddings/GeminiEmbeddingsProvider.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { Response } from "node-fetch"; - -import { EmbeddingsProviderName } from "../../index.js"; -import { withExponentialBackoff } from "../../util/withExponentialBackoff.js"; - -import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js"; - -/** - * [View the Gemini Text Embedding docs.](https://ai.google.dev/gemini-api/docs/models/gemini#text-embedding-and-embedding) - */ -class GeminiEmbeddingsProvider extends BaseEmbeddingsProvider { - static providerName: EmbeddingsProviderName = "gemini"; - static maxBatchSize = 100; - - static defaultOptions = { - apiBase: "https://generativelanguage.googleapis.com/v1/", - model: "models/text-embedding-004", - }; - - get urlPath(): string { - return `${this.options.model}:batchEmbedContents`; - } - - async getSingleBatchEmbedding(batch: string[]) { - // Batch embed endpoint: https://ai.google.dev/api/embeddings?authuser=1#EmbedContentRequest - const requests = batch.map((text) => ({ - model: this.options.model, - content: { - role: "user", - parts: [{ text }], - }, - })); - - const fetchWithBackoff = () => - withExponentialBackoff(() => - this.fetch(new URL(this.urlPath, this.options.apiBase), { - method: "POST", - body: JSON.stringify({ - requests, - }), - headers: { - "x-goog-api-key": this.options.apiKey, - "Content-Type": "application/json", - }, - }), - ); - - const resp = await fetchWithBackoff(); - - if (!resp.ok) { - throw new Error(await resp.text()); - } - - const data = (await resp.json()) as any; - - return data.embeddings.map((embedding: any) => embedding.values); - } - - async embed(chunks: string[]) { - const batchedChunks = this.getBatchedChunks(chunks); - - const results = await Promise.all( - batchedChunks.map((batch) => this.getSingleBatchEmbedding(batch)), - ); - return results.flat(); - } -} - -export default GeminiEmbeddingsProvider; diff --git a/core/indexing/embeddings/LMStudio.ts b/core/indexing/embeddings/LMStudio.ts deleted file mode 100644 index 31a9d6edf..000000000 --- a/core/indexing/embeddings/LMStudio.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { EmbeddingsProviderName, EmbedOptions } from "../.."; - -import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider"; - -class LMStudioEmbeddingsProvider extends OpenAIEmbeddingsProvider { - static providerName: EmbeddingsProviderName = "lmstudio"; - - static defaultOptions: Partial | undefined = { - apiBase: "http://localhost:1234/v1", - model: "nomic-ai/nomic-embed-text-v1.5-GGUF", - }; -} - -export default LMStudioEmbeddingsProvider; \ No newline at end of file diff --git a/core/indexing/embeddings/MistralEmbeddingsProvider.ts b/core/indexing/embeddings/MistralEmbeddingsProvider.ts deleted file mode 100644 index ffff08ae5..000000000 --- a/core/indexing/embeddings/MistralEmbeddingsProvider.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { EmbeddingsProviderName, EmbedOptions } from "../../index.js"; - -import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider.js"; - -class MistralEmbeddingsProvider extends OpenAIEmbeddingsProvider { - static providerName: EmbeddingsProviderName = "mistral"; - static maxBatchSize = 128; - - static defaultOptions: Partial | undefined = { - apiBase: "https://api.mistral.ai/v1/", - model: "mistral-embed", - }; -} - -export default MistralEmbeddingsProvider; diff --git a/core/indexing/embeddings/NebiusEmbeddingsProvider.ts b/core/indexing/embeddings/NebiusEmbeddingsProvider.ts deleted file mode 100644 index c9cf44877..000000000 --- a/core/indexing/embeddings/NebiusEmbeddingsProvider.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { EmbeddingsProviderName, EmbedOptions } from "../.."; - -import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider"; - -class NebiusEmbeddingsProvider extends OpenAIEmbeddingsProvider { - static providerName: EmbeddingsProviderName = "nebius"; - - static defaultOptions: Partial | undefined = { - apiBase: "https://api.studio.nebius.ai/v1/", - model: "BAAI/bge-en-icl", - }; -} - -export default NebiusEmbeddingsProvider; diff --git a/core/indexing/embeddings/NvidiaEmbeddingsProvider.ts b/core/indexing/embeddings/NvidiaEmbeddingsProvider.ts deleted file mode 100644 index 04ae18ec4..000000000 --- a/core/indexing/embeddings/NvidiaEmbeddingsProvider.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { Response } from "node-fetch"; - -import { EmbeddingsProviderName, EmbedOptions } from "../../index.js"; -import { withExponentialBackoff } from "../../util/withExponentialBackoff.js"; - -import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js"; - -class NvidiaEmbeddingsProvider extends BaseEmbeddingsProvider { - static maxBatchSize = 96; - - static providerName: EmbeddingsProviderName = "nvidia"; - - static defaultOptions: Partial | undefined = { - apiBase: "https://integrate.api.nvidia.com/v1/", - model: "nvidia/nv-embedqa-mistral-7b-v2", - }; - - async embed(chunks: string[]) { - - if (!this.options.apiBase?.endsWith("/")) { - this.options.apiBase += "/"; - } - - const batchedChunks = []; - for ( - let i = 0; - i < chunks.length; - i += NvidiaEmbeddingsProvider.maxBatchSize - ) { - batchedChunks.push( - chunks.slice(i, i + NvidiaEmbeddingsProvider.maxBatchSize), - ); - } - return ( - await Promise.all( - batchedChunks.map(async (batch) => { - if (batch.length === 0) { - return []; - } - - // Input list must be non empty and all elements must be non empty, therefore, for all empty elements replace it with a token - const emptyToken = "[EMPTY]"; - for (let i = 0; i < batch.length; i++) { - if (batch[i].trim() === "") { - batch[i] = emptyToken; - } - } - - const fetchWithBackoff = () => - withExponentialBackoff(() => - this.fetch(new URL("embeddings", this.options.apiBase), { - method: "POST", - body: JSON.stringify({ - input: batch, - model: this.options.model, - input_type: "passage", - truncate: "END", - }), - headers: { - Authorization: `Bearer ${this.options.apiKey}`, - "Content-Type": "application/json", - }, - }), - ); - - const resp = await fetchWithBackoff(); - - 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, - ); - }), - ) - ).flat(); - } -} - -export default NvidiaEmbeddingsProvider; diff --git a/core/indexing/embeddings/OllamaEmbeddingsProvider.ts b/core/indexing/embeddings/OllamaEmbeddingsProvider.ts deleted file mode 100644 index ca4eee262..000000000 --- a/core/indexing/embeddings/OllamaEmbeddingsProvider.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { - EmbeddingsProviderName, - EmbedOptions, - FetchFunction, -} from "../../index.js"; -import { withExponentialBackoff } from "../../util/withExponentialBackoff.js"; - -import BaseEmbeddingsProvider, { - IBaseEmbeddingsProvider, -} from "./BaseEmbeddingsProvider.js"; - -async function embedOneBatch( - chunks: string[], - options: EmbedOptions, - customFetch: FetchFunction, -) { - const embedding = await withExponentialBackoff(async () => { - let apiBase = options.apiBase!; - - if (!apiBase.endsWith("/")) { - apiBase += "/"; - } - - const resp = await customFetch(new URL("api/embed", apiBase), { - method: "POST", - body: JSON.stringify({ - model: options.model, - input: chunks, - }), - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${options.apiKey}`, - }, - }); - - if (!resp.ok) { - throw new Error(`Failed to embed chunk: ${await resp.text()}`); - } - - const data = await resp.json(); - const embedding: number[][] = data.embeddings; - - if (!embedding || embedding.length === 0) { - throw new Error("Ollama generated empty embedding"); - } - return embedding; - }); - - return embedding; -} - -class OllamaEmbeddingsProvider extends BaseEmbeddingsProvider { - static providerName: EmbeddingsProviderName = "ollama"; - static defaultOptions: IBaseEmbeddingsProvider["defaultOptions"] = { - apiBase: "http://localhost:11434/", - model: "nomic-embed-text", - maxBatchSize: 64, - }; - - async embed(chunks: string[]) { - const batchedChunks = this.getBatchedChunks(chunks); - var results: number[][] = []; - - for (const batch of batchedChunks) { - results.push(...await embedOneBatch(batch, this.options, this.fetch)); - } - return results; - } -} - -export default OllamaEmbeddingsProvider; diff --git a/core/indexing/embeddings/OpenAIEmbeddingsProvider.ts b/core/indexing/embeddings/OpenAIEmbeddingsProvider.ts deleted file mode 100644 index 65c37cdf6..000000000 --- a/core/indexing/embeddings/OpenAIEmbeddingsProvider.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { Response } from "node-fetch"; - -import { EmbeddingsProviderName, EmbedOptions } from "../../index.js"; -import { withExponentialBackoff } from "../../util/withExponentialBackoff.js"; - -import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js"; - -class OpenAIEmbeddingsProvider extends BaseEmbeddingsProvider { - static providerName: EmbeddingsProviderName = "openai"; - // https://platform.openai.com/docs/api-reference/embeddings/create is 2048 - // but Voyage is 128 - static maxBatchSize = 128; - - static defaultOptions: Partial | undefined = { - apiBase: "https://api.openai.com/v1/", - model: "text-embedding-3-small", - apiVersion: "2024-02-15-preview", - }; - - private _getEndpoint() { - if (!this.options.apiBase) { - throw new Error( - "No API base URL provided. Please set the 'apiBase' option in config.json", - ); - } - - this.options.apiBase = this.options.apiBase.endsWith("/") - ? this.options.apiBase - : `${this.options.apiBase}/`; - - if (this.options.apiType === "azure") { - return new URL( - `openai/deployments/${this.options.deployment}/embeddings?api-version=${this.options.apiVersion}`, - this.options.apiBase, - ); - } - return new URL("embeddings", this.options.apiBase); - } - - async embed(chunks: string[]) { - const batchedChunks = this.getBatchedChunks(chunks); - return ( - await Promise.all( - batchedChunks.map(async (batch) => { - if (batch.length === 0) { - return []; - } - - const fetchWithBackoff = () => - withExponentialBackoff(() => - this.fetch(this._getEndpoint(), { - method: "POST", - body: JSON.stringify({ - input: batch, - model: this.options.model, - }), - headers: { - Authorization: `Bearer ${this.options.apiKey}`, - "Content-Type": "application/json", - "api-key": this.options.apiKey ?? "", // For Azure - }, - }), - ); - const resp = await fetchWithBackoff(); - - 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, - ); - }), - ) - ).flat(); - } -} - -export default OpenAIEmbeddingsProvider; diff --git a/core/indexing/embeddings/SageMakerEmbeddingsProvider.ts b/core/indexing/embeddings/SageMakerEmbeddingsProvider.ts deleted file mode 100644 index a8a3fb0a5..000000000 --- a/core/indexing/embeddings/SageMakerEmbeddingsProvider.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { - InvokeEndpointCommand, - SageMakerRuntimeClient, -} from "@aws-sdk/client-sagemaker-runtime"; -import { fromIni } from "@aws-sdk/credential-providers"; - -import { - EmbeddingsProviderName, - EmbedOptions, - FetchFunction, -} from "../../index.js"; - -import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js"; - - -class SageMakerEmbeddingsProvider extends BaseEmbeddingsProvider { - static providerName: EmbeddingsProviderName = "sagemaker"; - - static defaultOptions: Partial | undefined = { - region: "us-west-2", - maxBatchSize: 1, - }; - profile?: string | undefined; - - constructor(options: EmbedOptions, fetch: FetchFunction) { - super(options, fetch); - if (!options.apiBase) { - options.apiBase = `https://runtime.sagemaker.${options.region}.amazonaws.com`; - } - - if (options.profile) { - this.profile = options.profile; - } else { - this.profile = "sagemaker"; - } - } - - async embed(chunks: string[]) { - const credentials = await this._getCredentials(); - const client = new SageMakerRuntimeClient({ - region: this.options.region, - credentials: { - accessKeyId: credentials.accessKeyId, - secretAccessKey: credentials.secretAccessKey, - sessionToken: credentials.sessionToken || "", - }, - }); - - const batchedChunks = this.getBatchedChunks(chunks); - return ( - await Promise.all( - batchedChunks.map(async (batch) => { - const input = this._generateInvokeModelCommandInput( - batch, - this.options, - ); - const command = new InvokeEndpointCommand(input); - const response = await client.send(command); - - if (response.Body) { - const responseBody = JSON.parse( - new TextDecoder().decode(response.Body), - ); - // If the body contains a key called "embedding" or "embeddings", return the value, otherwise return the whole body - if (responseBody.embedding) { - return responseBody.embedding; - } else if (responseBody.embeddings) { - return responseBody.embeddings; - } else { - return responseBody; - } - } - }), - ) - ).flat(); - } - private _generateInvokeModelCommandInput( - prompts: string | string[], - options: EmbedOptions, - ): any { - const payload = { - inputs: prompts, - normalize: true, - // ...(options.requestOptions?.extraBodyProperties || {}), - }; - - if (options.requestOptions?.extraBodyProperties) { - Object.assign(payload, options.requestOptions.extraBodyProperties); - } - - return { - EndpointName: this.options.model, - Body: JSON.stringify(payload), - ContentType: "application/json", - CustomAttributes: "accept_eula=false", - }; - } - - private async _getCredentials() { - try { - return await fromIni({ - profile: this.profile, - ignoreCache: true, - })(); - } catch (e) { - console.warn( - `AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`, - ); - return await fromIni()(); - } - } -} - -export default SageMakerEmbeddingsProvider; diff --git a/core/indexing/embeddings/SiliconFlowEmbeddingsProvider.ts b/core/indexing/embeddings/SiliconFlowEmbeddingsProvider.ts deleted file mode 100644 index bc463b047..000000000 --- a/core/indexing/embeddings/SiliconFlowEmbeddingsProvider.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { EmbeddingsProviderName, EmbedOptions } from "../.."; - -import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider"; - -class SiliconFlowEmbeddingsProvider extends OpenAIEmbeddingsProvider { - static providerName: EmbeddingsProviderName = "siliconflow"; - - static defaultOptions: Partial | undefined = { - apiBase: "https://api.siliconflow.cn/v1/", - model: "BAAI/bge-m3", - }; -} - -export default SiliconFlowEmbeddingsProvider; diff --git a/core/indexing/embeddings/VertexEmbeddingsProvider.ts b/core/indexing/embeddings/VertexEmbeddingsProvider.ts deleted file mode 100644 index 67bd801c7..000000000 --- a/core/indexing/embeddings/VertexEmbeddingsProvider.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { GoogleAuth } from "google-auth-library"; -import { Response } from "node-fetch"; - -import { EmbeddingsProviderName, EmbedOptions, FetchFunction } from "../../index.js"; -import { withExponentialBackoff } from "../../util/withExponentialBackoff.js"; - -import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js"; - -/** - * [View the Vertex Text Embedding docs.](https://cloud.google.com/vertex-ai/generative-ai/docs/embeddings/get-text-embeddings) - */ -class VertexEmbeddingsProvider extends BaseEmbeddingsProvider { - static providerName: EmbeddingsProviderName = "vertexai"; - declare apiBase: string; - - - static defaultOptions: Partial | undefined = { - model: "text-embedding-004", - maxBatchSize: 5, - region: "us-central1" - }; - - private clientPromise = new GoogleAuth({ - scopes: "https://www.googleapis.com/auth/cloud-platform", - }).getClient(); - - private static getDefaultApiBaseFrom(options: EmbedOptions) { - const { region, projectId } = options; - if (!region || !projectId) { - throw new Error( - "region and projectId must be defined if apiBase is not provided", - ); - } - - return `https://${region}-aiplatform.googleapis.com/v1/projects/${projectId}/locations/${region}`; - } - - - - constructor(options: EmbedOptions, fetch: FetchFunction) { - super(options, fetch); - this.apiBase ??= VertexEmbeddingsProvider.getDefaultApiBaseFrom(options); - - } - - - - get urlPath(): string { - return `/publishers/google/models/${this.options.model}:predict`; - } - - async embed(chunks: string[]) { - const client = await this.clientPromise; - const { token } = await client.getAccessToken(); - if (!token) { - throw new Error( - "Could not get an access token. Set up your Google Application Default Credentials.", - ); - } - const batchedChunks = this.getBatchedChunks(chunks); - - return ( - await Promise.all( - batchedChunks.map(async (batch) => { - const fetchWithBackoff = () => - withExponentialBackoff(() => - this.fetch(new URL(this.apiBase + this.urlPath), { - method: "POST", - body: JSON.stringify({ - instances: batch.map((chunk) => ({ content: chunk })), - }), - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${token}`, - }, - }), - ); - const resp = await fetchWithBackoff(); - - if (!resp.ok) { - throw new Error(await resp.text()); - } - - const data = (await resp.json()) as any; - return data.predictions.map((prediction: any) => prediction.embeddings.values); - }), - ) - ).flat(); - } -} -export default VertexEmbeddingsProvider; diff --git a/core/indexing/embeddings/VoyageEmbeddingsProvider.ts b/core/indexing/embeddings/VoyageEmbeddingsProvider.ts deleted file mode 100644 index df78f401b..000000000 --- a/core/indexing/embeddings/VoyageEmbeddingsProvider.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { EmbeddingsProviderName, EmbedOptions } from "../.."; - -import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider"; - -class VoyageEmbeddingsProvider extends OpenAIEmbeddingsProvider { - static providerName: EmbeddingsProviderName = "voyage"; - - static defaultOptions: Partial | undefined = { - apiBase: "https://api.voyageai.com/v1/", - model: "voyage-code-2", - }; -} - -export default VoyageEmbeddingsProvider; diff --git a/core/indexing/embeddings/WatsonxEmbeddingsProvider.ts b/core/indexing/embeddings/WatsonxEmbeddingsProvider.ts deleted file mode 100644 index cb605d0c1..000000000 --- a/core/indexing/embeddings/WatsonxEmbeddingsProvider.ts +++ /dev/null @@ -1,151 +0,0 @@ -import { - EmbeddingsProviderName, - EmbedOptions, - FetchFunction, -} from "../../index.js"; -import { withExponentialBackoff } from "../../util/withExponentialBackoff.js"; - -import BaseEmbeddingsProvider, { - IBaseEmbeddingsProvider, -} from "./BaseEmbeddingsProvider.js"; - -let accessToken = { - expiration: 0, - token: "", -}; - - -class WatsonxEmbeddingsProvider extends BaseEmbeddingsProvider { - static providerName: EmbeddingsProviderName = "watsonx"; - static maxBatchSize = 1000; - static defaultOptions: Partial | undefined = { - model: "ibm/slate-125m-english-rtrvr-v2", - }; - - async getBearerToken(): Promise<{ token: string; expiration: number }> { - if ( - this.options.apiBase?.includes("cloud.ibm.com") - ) { - // watsonx SaaS - const wxToken = await ( - await fetch( - `https://iam.cloud.ibm.com/identity/token?apikey=${this.options.apiKey}&grant_type=urn:ibm:params:oauth:grant-type:apikey`, - { - method: "POST", - headers: { - "Content-Type": "application/x-www-form-urlencoded", - Accept: "application/json", - }, - }, - ) - ).json(); - return { - token: wxToken["access_token"], - expiration: wxToken["expiration"], - }; - } else { - // watsonx Software - if (!this.options.apiKey?.includes(":")) { - // Using ZenApiKey auth - return { - token: this.options.apiKey ?? "", - expiration: -1, - }; - } else { - // Using username/password auth - const userPass = this.options.apiKey?.split(":"); - const wxToken = await ( - await fetch(`${this.options.apiBase}/icp4d-api/v1/authorize`, { - method: "POST", - headers: { - "Content-Type": "application/json", - Accept: "application/json", - }, - body: JSON.stringify({ - username: userPass[0], - password: userPass[1], - }), - }) - ).json(); - const wxTokenExpiry = await ( - await fetch( - `${this.options.apiBase}/usermgmt/v1/user/tokenExpiry`, - { - method: "GET", - headers: { - Accept: "application/json", - Authorization: `Bearer ${wxToken["token"]}`, - }, - }, - ) - ).json(); - return { - token: wxToken["token"], - expiration: wxTokenExpiry["exp"], - }; - } - } - } - async getSingleBatchEmbedding(batch: string[]) { - var now = new Date().getTime() / 1000; - if ( - accessToken === undefined || - now > accessToken.expiration || - accessToken.token === undefined - ) { - accessToken = await this.getBearerToken(); - } else { - console.log( - `Reusing token (expires in ${(accessToken.expiration - now) / 60 - } mins)`, - ); - } - return await withExponentialBackoff(async () => { - const payload: any = { - inputs: batch, - parameters: { - truncate_input_tokens: 500, - return_options: { input_text: false }, - }, - model_id: this.options.model, - project_id: this.options.projectId, - }; - const headers = { - "Content-Type": "application/json", - Authorization: `${accessToken.expiration === -1 ? "ZenApiKey" : "Bearer" - } ${accessToken.token}`, - }; - const resp = await this.fetch( - new URL( - `${this.options.apiBase}/ml/v1/text/embeddings?version=${this.options.apiVersion}`, - ), - { - method: "POST", - body: JSON.stringify(payload), - headers: headers, - }, - ); - - if (!resp.ok) { - throw new Error(`Failed to embed chunk: ${await resp.text()}`); - } - const data = await resp.json(); - const embeddings = data.results; - - if (!embeddings || embeddings.length === 0) { - throw new Error("Watsonx generated empty embedding"); - } - return embeddings.map((e: any) => e.embedding); - }); - } - - async embed(chunks: string[]) { - const batchedChunks = this.getBatchedChunks(chunks); - const results = await Promise.all( - batchedChunks.map((batch) => this.getSingleBatchEmbedding(batch)), - ); - return results.flat(); - } -} - -export default WatsonxEmbeddingsProvider; diff --git a/core/indexing/embeddings/index.ts b/core/indexing/embeddings/index.ts deleted file mode 100644 index 5adc241ba..000000000 --- a/core/indexing/embeddings/index.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { EmbeddingsProviderName } from "../../index.js"; - -import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js"; -import BedrockEmbeddingsProvider from "./BedrockEmbeddingsProvider.js"; -import CohereEmbeddingsProvider from "./CohereEmbeddingsProvider.js"; -import ContinueProxyEmbeddingsProvider from "./ContinueProxyEmbeddingsProvider.js"; -import DeepInfraEmbeddingsProvider from "./DeepInfraEmbeddingsProvider.js"; -import FreeTrialEmbeddingsProvider from "./FreeTrialEmbeddingsProvider.js"; -import FunctionNetworkEmbeddingsProvider from "./FunctionNetworkEmbeddingsProvider.js"; -import GeminiEmbeddingsProvider from "./GeminiEmbeddingsProvider.js"; -import HuggingFaceTEIEmbeddingsProvider from "./HuggingFaceTEIEmbeddingsProvider.js"; -import LMStudioEmbeddingsProvider from "./LMStudio.js"; -import MistralEmbeddingsProvider from "./MistralEmbeddingsProvider.js"; -import NebiusEmbeddingsProvider from "./NebiusEmbeddingsProvider.js"; -import NvidiaEmbeddingsProvider from "./NvidiaEmbeddingsProvider.js"; -import OllamaEmbeddingsProvider from "./OllamaEmbeddingsProvider.js"; -import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider.js"; -import SageMakerEmbeddingsProvider from "./SageMakerEmbeddingsProvider.js"; -import SiliconFlowEmbeddingsProvider from "./SiliconFlowEmbeddingsProvider.js"; -import TransformersJsEmbeddingsProvider from "./TransformersJsEmbeddingsProvider.js"; -import VertexEmbeddingsProvider from "./VertexEmbeddingsProvider.js"; -import VoyageEmbeddingsProvider from "./VoyageEmbeddingsProvider.js"; -import WatsonxEmbeddingsProvider from "./WatsonxEmbeddingsProvider.js"; - -type EmbeddingsProviderConstructor = new ( - ...args: any[] -) => BaseEmbeddingsProvider; - -export const allEmbeddingsProviders: Record< - EmbeddingsProviderName, - EmbeddingsProviderConstructor -> = { - sagemaker: SageMakerEmbeddingsProvider, - bedrock: BedrockEmbeddingsProvider, - ollama: OllamaEmbeddingsProvider, - "transformers.js": TransformersJsEmbeddingsProvider, - openai: OpenAIEmbeddingsProvider, - cohere: CohereEmbeddingsProvider, - "free-trial": FreeTrialEmbeddingsProvider, - "function-network": FunctionNetworkEmbeddingsProvider, - "huggingface-tei": HuggingFaceTEIEmbeddingsProvider, - gemini: GeminiEmbeddingsProvider, - "continue-proxy": ContinueProxyEmbeddingsProvider, - deepinfra: DeepInfraEmbeddingsProvider, - nvidia: NvidiaEmbeddingsProvider, - voyage: VoyageEmbeddingsProvider, - mistral: MistralEmbeddingsProvider, - nebius: NebiusEmbeddingsProvider, - vertexai: VertexEmbeddingsProvider, - watsonx: WatsonxEmbeddingsProvider, - lmstudio: LMStudioEmbeddingsProvider, - siliconflow: SiliconFlowEmbeddingsProvider, -}; diff --git a/core/jest.config.js b/core/jest.config.js index d58b0b510..285fb2838 100644 --- a/core/jest.config.js +++ b/core/jest.config.js @@ -19,8 +19,14 @@ export default { __dirname: path.dirname(fileURLToPath(import.meta.url)), __filename: path.resolve(fileURLToPath(import.meta.url)), }, - - globalSetup: "/jest.global-setup.ts", - setupFilesAfterEnv: ["/jest.setup-after-env.ts"], - maxWorkers: 1 // equivalent to CLI --runInBand + // collectCoverage: true, + collectCoverageFrom: [ + "**/*.{js,ts}", // Adjust this pattern to match files you want coverage for + "!**/node_modules/**", // Exclude node_modules + "!**/vendor/**", + // "!**/autocomplete/context/root-path-context/test/files/**", + ], + globalSetup: "/test/jest.global-setup.ts", + setupFilesAfterEnv: ["/test/jest.setup-after-env.ts"], + maxWorkers: 1, // equivalent to CLI --runInBand }; diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index 363e7c28a..90d9f378d 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -1,4 +1,4 @@ -import { ModelCapability, ModelProvider, TemplateType } from "../index.js"; +import { ModelCapability, TemplateType } from "../index.js"; import { anthropicTemplateMessages, @@ -36,7 +36,7 @@ import { zephyrEditPrompt, } from "./templates/edit.js"; -const PROVIDER_HANDLES_TEMPLATING: ModelProvider[] = [ +const PROVIDER_HANDLES_TEMPLATING: string[] = [ "lmstudio", "openai", "ollama", @@ -52,7 +52,7 @@ const PROVIDER_HANDLES_TEMPLATING: ModelProvider[] = [ "watsonx", ]; -const PROVIDER_SUPPORTS_IMAGES: ModelProvider[] = [ +const PROVIDER_SUPPORTS_IMAGES: string[] = [ "openai", "ollama", "gemini", @@ -65,6 +65,7 @@ const PROVIDER_SUPPORTS_IMAGES: ModelProvider[] = [ "openrouter", "vertexai", "azure", + "scaleway", ]; const MODEL_SUPPORTS_IMAGES: string[] = [ @@ -92,7 +93,7 @@ function modelSupportsTools(modelName: string) { } function modelSupportsImages( - provider: ModelProvider, + provider: string, model: string, title: string | undefined, capabilities: ModelCapability | undefined, @@ -115,7 +116,7 @@ function modelSupportsImages( return false; } -const PARALLEL_PROVIDERS: ModelProvider[] = [ +const PARALLEL_PROVIDERS: string[] = [ "anthropic", "bedrock", "sagemaker", @@ -134,10 +135,7 @@ const PARALLEL_PROVIDERS: ModelProvider[] = [ "function-network", ]; -function llmCanGenerateInParallel( - provider: ModelProvider, - model: string, -): boolean { +function llmCanGenerateInParallel(provider: string, model: string): boolean { if (provider === "openai") { return model.includes("gpt"); } @@ -241,7 +239,7 @@ function autodetectTemplateType(model: string): TemplateType | undefined { function autodetectTemplateFunction( model: string, - provider: ModelProvider, + provider: string, explicitTemplate: TemplateType | undefined = undefined, ) { if ( diff --git a/core/llm/constants.ts b/core/llm/constants.ts index 59a9c301a..7e8b8e9f5 100644 --- a/core/llm/constants.ts +++ b/core/llm/constants.ts @@ -30,11 +30,13 @@ const TOKEN_BUFFER_FOR_SAFETY = 350; const PROXY_URL = "http://localhost:65433"; const DEFAULT_MAX_CHUNK_SIZE = 500; // 512 - buffer for safety (in case of differing tokenizers) +const DEFAULT_MAX_BATCH_SIZE = 64; export { CONTEXT_LENGTH_FOR_MODEL, DEFAULT_ARGS, DEFAULT_CONTEXT_LENGTH, + DEFAULT_MAX_BATCH_SIZE, DEFAULT_MAX_CHUNK_SIZE, DEFAULT_MAX_TOKENS, PROXY_URL, diff --git a/core/llm/countTokens.test.ts b/core/llm/countTokens.test.ts new file mode 100644 index 000000000..6895e9269 --- /dev/null +++ b/core/llm/countTokens.test.ts @@ -0,0 +1,109 @@ +// Generated by continue +import { ChatMessage, MessagePart } from "../index.js"; +import { + compileChatMessages, + countTokens, + countTokensAsync, + pruneLinesFromBottom, + pruneLinesFromTop, + pruneRawPromptFromTop, + pruneStringFromBottom, + pruneStringFromTop, +} from "./countTokens.js"; + +describe.skip("countTokens", () => { + it("should count tokens for a simple string", () => { + const content = "Hello world!"; + const tokenCount = countTokens(content, "gpt-4"); + expect(tokenCount).toBeGreaterThan(0); + }); + + it("should count tokens for an array of MessagePart", () => { + const content: MessagePart[] = [{ type: "text", text: "Hello world!" }]; + const tokenCount = countTokens(content, "gpt-4"); + expect(tokenCount).toBeGreaterThan(0); + }); +}); + +describe.skip("countTokensAsync", () => { + it("should count tokens asynchronously for a simple string", async () => { + const content = "Hello world!"; + const tokenCount = await countTokensAsync(content, "gpt-4"); + expect(tokenCount).toBeGreaterThan(0); + }); + + it("should count tokens asynchronously for an array of MessagePart", async () => { + const content: MessagePart[] = [{ type: "text", text: "Hello world!" }]; + const tokenCount = await countTokensAsync(content, "gpt-4"); + expect(tokenCount).toBeGreaterThan(0); + }); +}); + +describe.skip("pruneLinesFromTop", () => { + it("should prune lines from the top to fit within max tokens", () => { + const prompt = "Line 1\nLine 2\nLine 3\nLine 4"; + const pruned = pruneLinesFromTop(prompt, 5, "gpt-4"); + expect(pruned.split("\n").length).toBeLessThan(prompt.split("\n").length); + }); +}); + +describe.skip("pruneLinesFromBottom", () => { + it("should prune lines from the bottom to fit within max tokens", () => { + const prompt = "Line 1\nLine 2\nLine 3\nLine 4"; + const pruned = pruneLinesFromBottom(prompt, 5, "gpt-4"); + expect(pruned.split("\n").length).toBeLessThan(prompt.split("\n").length); + }); +}); + +describe.skip("pruneRawPromptFromTop", () => { + it("should prune string from the top based on maxTokens", () => { + const result = pruneRawPromptFromTop("gpt-4", 5, "Hello world!", 2); + expect(result.length).toBeLessThan("Hello world!".length); + }); +}); + +describe.skip("pruneStringFromTop", () => { + it("should prune string from the top based on maxTokens", () => { + const result = pruneStringFromTop("gpt-4", 5, "Hello world!"); + expect(result.length).toBeLessThan("Hello world!".length); + }); +}); + +describe.skip("pruneStringFromBottom", () => { + it("should prune string from the bottom based on maxTokens", () => { + const result = pruneStringFromBottom("gpt-4", 5, "Hello world!"); + expect(result.length).toBeLessThan("Hello world!".length); + }); +}); + +describe.skip("compileChatMessages", () => { + it("should compile and handle an empty or undefined message list", () => { + const compiled = compileChatMessages("gpt-4", undefined, 100, 50, false); + expect(compiled.length).toBe(0); + }); + + it("should compile chat messages without truncating if within context length", () => { + const msgs: ChatMessage[] = [ + { role: "user", content: "Hello world!" }, + { role: "assistant", content: "Hi there!" }, + ]; + const compiled = compileChatMessages("gpt-4", msgs, 100, 10, false); + expect(compiled.length).toBe(2); + }); + + it("should throw an error if maxTokens is close to or exceeds contextLength", () => { + expect(() => { + compileChatMessages("gpt-4", [], 100, 90, false); + }).toThrow(); + }); + + it("should filter out any empty or system messages", () => { + const msgs: ChatMessage[] = [ + { role: "system", content: "" }, + { role: "user", content: "" }, + { role: "assistant", content: "Hi there!" }, + ]; + const compiled = compileChatMessages("gpt-4", msgs, 100, 10, false); + expect(compiled.length).toBe(1); + }); +}); diff --git a/core/llm/index.test.ts b/core/llm/index.test.ts index 0ada014ab..404902e91 100644 --- a/core/llm/index.test.ts +++ b/core/llm/index.test.ts @@ -1,9 +1,9 @@ -import { ChatMessage, LLMOptions, ModelProvider } from ".."; +import { ChatMessage, LLMOptions } from ".."; import { BaseLLM } from "."; class DummyLLM extends BaseLLM { - static providerName: ModelProvider = "openai"; + static providerName = "openai"; static defaultOptions: Partial = { model: "dummy-model", contextLength: 200_000, @@ -123,7 +123,7 @@ describe("BaseLLM", () => { expect(baseLLM.supportsPrefill()).toBe(false); class PrefillLLM extends BaseLLM { - static providerName: ModelProvider = "ollama"; + static providerName = "ollama"; } const prefillLLM = new PrefillLLM({ model: "some-model" }); expect(prefillLLM.supportsPrefill()).toBe(true); diff --git a/core/llm/index.ts b/core/llm/index.ts index 144df72d2..82e413ae8 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -1,16 +1,17 @@ +import { fetchwithRequestOptions } from "@continuedev/fetch"; import { findLlmInfo } from "@continuedev/llm-info"; +import { BaseLlmApi, constructLlmApi } from "@continuedev/openai-adapters"; import Handlebars from "handlebars"; import { CacheBehavior, ChatMessage, + Chunk, CompletionOptions, ILLM, LLMFullCompletionOptions, LLMOptions, ModelCapability, - ModelName, - ModelProvider, PromptLog, PromptTemplate, RequestOptions, @@ -18,12 +19,11 @@ import { } from "../index.js"; import { logDevData } from "../util/devdata.js"; import { DevDataSqliteDb } from "../util/devdataSqlite.js"; -import { fetchwithRequestOptions } from "../util/fetchWithOptions.js"; import mergeJson from "../util/merge.js"; +import { renderChatMessage } from "../util/messageContent.js"; import { Telemetry } from "../util/posthog.js"; import { withExponentialBackoff } from "../util/withExponentialBackoff.js"; -import { renderChatMessage } from "../util/messageContent.js"; import { autodetectPromptTemplates, autodetectTemplateFunction, @@ -34,6 +34,8 @@ import { CONTEXT_LENGTH_FOR_MODEL, DEFAULT_ARGS, DEFAULT_CONTEXT_LENGTH, + DEFAULT_MAX_BATCH_SIZE, + DEFAULT_MAX_CHUNK_SIZE, DEFAULT_MAX_TOKENS, } from "./constants.js"; import { @@ -41,13 +43,19 @@ import { countTokens, pruneRawPromptFromTop, } from "./countTokens.js"; -import CompletionOptionsForModels from "./templates/options.js"; +import { + fromChatCompletionChunk, + LlmApiRequestType, + toChatBody, + toCompleteBody, + toFimBody, +} from "./openaiTypeConverters.js"; export abstract class BaseLLM implements ILLM { - static providerName: ModelProvider; + static providerName: string; static defaultOptions: Partial | undefined = undefined; - get providerName(): ModelProvider { + get providerName(): string { return (this.constructor as typeof BaseLLM).providerName; } @@ -114,12 +122,20 @@ export abstract class BaseLLM implements ILLM { projectId?: string; accountId?: string; aiGatewaySlug?: string; + profile?: string | undefined; // For IBM watsonx deploymentId?: string; + // Embedding options + embeddingId: string; + maxEmbeddingChunkSize: number; + maxEmbeddingBatchSize: number; + private _llmOptions: LLMOptions; + private openaiAdapter?: BaseLlmApi; + constructor(_options: LLMOptions) { this._llmOptions = _options; @@ -157,12 +173,6 @@ export abstract class BaseLLM implements ILLM { ) : DEFAULT_MAX_TOKENS), }; - if (CompletionOptionsForModels[options.model as ModelName]) { - this.completionOptions = mergeJson( - this.completionOptions, - CompletionOptionsForModels[options.model as ModelName] ?? {}, - ); - } this.requestOptions = options.requestOptions; this.promptTemplates = { ...autodetectPromptTemplates(options.model, templateType), @@ -196,6 +206,20 @@ export abstract class BaseLLM implements ILLM { this.apiType = options.apiType; this.region = options.region; this.projectId = options.projectId; + this.profile = options.profile; + + this.openaiAdapter = constructLlmApi({ + provider: this.providerName as any, + apiKey: this.apiKey ?? "", + apiBase: this.apiBase, + requestOptions: this.requestOptions, + }); + + this.maxEmbeddingBatchSize = + options.maxEmbeddingBatchSize ?? DEFAULT_MAX_BATCH_SIZE; + this.maxEmbeddingChunkSize = + options.maxEmbeddingChunkSize ?? DEFAULT_MAX_CHUNK_SIZE; + this.embeddingId = `${this.constructor.name}::${this.model}::${this.maxEmbeddingChunkSize}`; } listModels(): Promise { @@ -431,6 +455,15 @@ export abstract class BaseLLM implements ILLM { throw new Error("Not implemented"); } + protected useOpenAIAdapterFor: (LlmApiRequestType | "*")[] = []; + + private shouldUseOpenAIAdapter(requestType: LlmApiRequestType) { + return ( + this.useOpenAIAdapterFor.includes(requestType) || + this.useOpenAIAdapterFor.includes("*") + ); + } + async *streamFim( prefix: string, suffix: string, @@ -452,14 +485,30 @@ export abstract class BaseLLM implements ILLM { } let completion = ""; - for await (const chunk of this._streamFim( - prefix, - suffix, - signal, - completionOptions, - )) { - completion += chunk; - yield chunk; + + if (this.shouldUseOpenAIAdapter("streamFim") && this.openaiAdapter) { + const stream = this.openaiAdapter.fimStream( + toFimBody(prefix, suffix, completionOptions), + signal, + ); + for await (const chunk of stream) { + const result = fromChatCompletionChunk(chunk); + if (result) { + const content = renderChatMessage(result); + completion += content; + yield content; + } + } + } else { + for await (const chunk of this._streamFim( + prefix, + suffix, + signal, + completionOptions, + )) { + completion += chunk; + yield chunk; + } } this._logTokensGenerated( @@ -509,13 +558,27 @@ export abstract class BaseLLM implements ILLM { let completion = ""; try { - for await (const chunk of this._streamComplete( - prompt, - signal, - completionOptions, - )) { - completion += chunk; - yield chunk; + if (this.shouldUseOpenAIAdapter("streamComplete") && this.openaiAdapter) { + for await (const chunk of this.openaiAdapter.completionStream( + { + ...toCompleteBody(prompt, completionOptions), + stream: true, + }, + signal, + )) { + const content = chunk.choices[0]?.text ?? ""; + completion += content; + yield content; + } + } else { + for await (const chunk of this._streamComplete( + prompt, + signal, + completionOptions, + )) { + completion += chunk; + yield chunk; + } } } finally { this._logTokensGenerated(completionOptions.model, prompt, completion); @@ -561,7 +624,19 @@ export abstract class BaseLLM implements ILLM { } } - const completion = await this._complete(prompt, signal, completionOptions); + let completion: string; + if (this.shouldUseOpenAIAdapter("complete") && this.openaiAdapter) { + const result = await this.openaiAdapter.completionNonStream( + { + ...toCompleteBody(prompt, completionOptions), + stream: false, + }, + signal, + ); + completion = result.choices[0].text; + } else { + completion = await this._complete(prompt, signal, completionOptions); + } this._logTokensGenerated(completionOptions.model, prompt, completion); @@ -619,13 +694,29 @@ export abstract class BaseLLM implements ILLM { yield { role: "assistant", content: chunk }; } } else { - for await (const chunk of this._streamChat( - messages, - signal, - completionOptions, - )) { - completion += chunk.content; - yield chunk; + if (this.shouldUseOpenAIAdapter("streamChat") && this.openaiAdapter) { + const stream = this.openaiAdapter.chatCompletionStream( + { + ...toChatBody(messages, completionOptions), + stream: true, + }, + signal, + ); + for await (const chunk of stream) { + const result = fromChatCompletionChunk(chunk); + if (result) { + yield result; + } + } + } else { + for await (const chunk of this._streamChat( + messages, + signal, + completionOptions, + )) { + completion += chunk.content; + yield chunk; + } } } } catch (error) { @@ -647,7 +738,64 @@ export abstract class BaseLLM implements ILLM { }; } - // biome-ignore lint/correctness/useYield: Purposefully not implemented + getBatchedChunks(chunks: string[]): string[][] { + const batchedChunks = []; + + for (let i = 0; i < chunks.length; i += this.maxEmbeddingBatchSize) { + batchedChunks.push(chunks.slice(i, i + this.maxEmbeddingBatchSize)); + } + + return batchedChunks; + } + + async embed(chunks: string[]): Promise { + const batches = this.getBatchedChunks(chunks); + + return ( + await Promise.all( + batches.map(async (batch) => { + if (batch.length === 0) { + return []; + } + + const embeddings = await withExponentialBackoff( + async () => { + if (this.shouldUseOpenAIAdapter("embed") && this.openaiAdapter) { + const result = await this.openaiAdapter.embed({ + model: this.model, + input: chunks, + }); + return result.data.map((chunk) => chunk.embedding); + } + + return await this._embed(chunks); + }, + ); + + return embeddings; + }), + ) + ).flat(); + } + + async rerank(query: string, chunks: Chunk[]): Promise { + if (this.shouldUseOpenAIAdapter("rerank") && this.openaiAdapter) { + const results = await this.openaiAdapter.rerank({ + model: this.model, + query, + documents: chunks.map((chunk) => chunk.content), + }); + + // Put them in the order they were given + const sortedResults = results.data.sort((a, b) => a.index - b.index); + return sortedResults.map((result) => result.relevance_score); + } + + throw new Error( + `Reranking is not supported for provider type ${this.providerName}`, + ); + } + protected async *_streamComplete( prompt: string, signal: AbortSignal, @@ -688,6 +836,12 @@ export abstract class BaseLLM implements ILLM { return completion; } + protected async _embed(chunks: string[]): Promise { + throw new Error( + `Embedding is not supported for provider type ${this.providerName}`, + ); + } + countTokens(text: string): number { return countTokens(text, this.model); } diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index a10d2c4a4..31642ea66 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -1,15 +1,10 @@ -import { - ChatMessage, - CompletionOptions, - LLMOptions, - ModelProvider, -} from "../../index.js"; +import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; import { renderChatMessage, stripImages } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamSse } from "../stream.js"; class Anthropic extends BaseLLM { - static providerName: ModelProvider = "anthropic"; + static providerName = "anthropic"; static defaultOptions: Partial = { model: "claude-3-5-sonnet-latest", contextLength: 200_000, diff --git a/core/llm/llms/Asksage.ts b/core/llm/llms/Asksage.ts index 74b1ddc27..316540c48 100644 --- a/core/llm/llms/Asksage.ts +++ b/core/llm/llms/Asksage.ts @@ -1,13 +1,8 @@ -import { - ChatMessage, - CompletionOptions, - LLMOptions, - ModelProvider, -} from "../../index.js"; +import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; import { BaseLLM } from "../index.js"; class Asksage extends BaseLLM { - static providerName: ModelProvider = "askSage"; + static providerName = "askSage"; static defaultOptions: Partial = { apiBase: "https://api.asksage.ai/server/", model: "gpt-4o", @@ -62,13 +57,15 @@ class Asksage extends BaseLLM { temperature: options.temperature ?? 0.0, live: options.live ?? 0, model: this._convertModelName(options.model), - system_prompt: options.systemPrompt ?? "You are an expert software developer. You give helpful and concise responses.", + system_prompt: + options.systemPrompt ?? + "You are an expert software developer. You give helpful and concise responses.", tools: options.tools, tool_choice: options.toolChoice, }; Object.keys(args).forEach( - (key) => args[key] === undefined && delete args[key] + (key) => args[key] === undefined && delete args[key], ); return args; @@ -89,7 +86,7 @@ class Asksage extends BaseLLM { protected _getEndpoint(endpoint: string) { if (!this.apiBase) { throw new Error( - "No API base URL provided. Please set the 'apiBase' option." + "No API base URL provided. Please set the 'apiBase' option.", ); } @@ -99,7 +96,7 @@ class Asksage extends BaseLLM { protected async _complete( prompt: string, signal: AbortSignal, - options: CompletionOptions + options: CompletionOptions, ): Promise { if (typeof prompt !== "string" || prompt.trim() === "") { throw new Error("Prompt must be a non-empty string."); @@ -117,7 +114,7 @@ class Asksage extends BaseLLM { if (!response.ok) { throw new Error( - `API request failed with status ${response.status}: ${response.statusText}` + `API request failed with status ${response.status}: ${response.statusText}`, ); } @@ -128,7 +125,7 @@ class Asksage extends BaseLLM { protected async *_streamComplete( prompt: string, signal: AbortSignal, - options: CompletionOptions + options: CompletionOptions, ): AsyncGenerator { const completion = await this._complete(prompt, signal, options); yield completion; @@ -137,7 +134,7 @@ class Asksage extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], signal: AbortSignal, - options: CompletionOptions + options: CompletionOptions, ): AsyncGenerator { const args = this._convertArgs(options, messages); @@ -145,12 +142,12 @@ class Asksage extends BaseLLM { method: "POST", headers: this._getHeaders(), body: JSON.stringify(args), - signal + signal, }); if (!response.ok) { throw new Error( - `API request failed with status ${response.status}: ${response.statusText}` + `API request failed with status ${response.status}: ${response.statusText}`, ); } @@ -169,4 +166,4 @@ class Asksage extends BaseLLM { } } -export default Asksage; \ No newline at end of file +export default Asksage; diff --git a/core/llm/llms/Azure.ts b/core/llm/llms/Azure.ts index d563ca78e..5b3ba4338 100644 --- a/core/llm/llms/Azure.ts +++ b/core/llm/llms/Azure.ts @@ -1,9 +1,9 @@ -import { LLMOptions, ModelProvider } from "../../index.js"; +import { LLMOptions } from "../../index.js"; import OpenAI from "./OpenAI.js"; class Azure extends OpenAI { - static providerName: ModelProvider = "azure"; + static providerName = "azure"; protected supportsPrediction(model: string): boolean { return false; diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 31445c84a..17d2911b8 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -1,32 +1,33 @@ import { BedrockRuntimeClient, ConverseStreamCommand, + InvokeModelCommand, } from "@aws-sdk/client-bedrock-runtime"; import { fromIni } from "@aws-sdk/credential-providers"; import { ChatMessage, + Chunk, CompletionOptions, LLMOptions, MessageContent, - ModelProvider, } from "../../index.js"; import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; -/** - * Bedrock class implements AWS Bedrock LLM integration. - * It handles streaming completions and chat messages using AWS Bedrock runtime. - * Supports both text and image inputs through Claude 3 models. - */ +interface ModelConfig { + formatPayload: (text: string) => any; + extractEmbeddings: (responseBody: any) => number[][]; +} + class Bedrock extends BaseLLM { - static providerName: ModelProvider = "bedrock"; + static providerName = "bedrock"; static defaultOptions: Partial = { region: "us-east-1", model: "anthropic.claude-3-sonnet-20240229-v1:0", contextLength: 200_000, + profile: "bedrock", }; - profile?: string | undefined; constructor(options: LLMOptions) { super(options); @@ -180,6 +181,131 @@ class Bedrock extends BaseLLM { return await fromIni()(); } } + + // EMBED // + async embed(chunks: string[]): Promise { + const credentials = await this._getCredentials(); + const client = new BedrockRuntimeClient({ + region: this.region, + credentials: { + accessKeyId: credentials.accessKeyId, + secretAccessKey: credentials.secretAccessKey, + sessionToken: credentials.sessionToken || "", + }, + }); + + return ( + await Promise.all( + chunks.map(async (chunk) => { + const input = this._generateInvokeModelCommandInput(chunk); + const command = new InvokeModelCommand(input); + const response = await client.send(command); + if (response.body) { + const responseBody = JSON.parse( + new TextDecoder().decode(response.body), + ); + return this._extractEmbeddings(responseBody); + } + return []; + }), + ) + ).flat(); + } + + private _generateInvokeModelCommandInput(text: string): any { + const modelConfig = this._getModelConfig(); + const payload = modelConfig.formatPayload(text); + + return { + body: JSON.stringify(payload), + modelId: this.model, + accept: "*/*", + contentType: "application/json", + }; + } + + private _extractEmbeddings(responseBody: any): number[][] { + const modelConfig = this._getModelConfig(); + return modelConfig.extractEmbeddings(responseBody); + } + + private _getModelConfig() { + const modelConfigs: { [key: string]: ModelConfig } = { + cohere: { + formatPayload: (text: string) => ({ + texts: [text], + input_type: "search_document", + truncate: "END", + }), + extractEmbeddings: (responseBody: any) => responseBody.embeddings || [], + }, + "amazon.titan-embed": { + formatPayload: (text: string) => ({ + inputText: text, + }), + extractEmbeddings: (responseBody: any) => + responseBody.embedding ? [responseBody.embedding] : [], + }, + }; + + const modelPrefix = Object.keys(modelConfigs).find((prefix) => + this.model!.startsWith(prefix), + ); + if (!modelPrefix) { + throw new Error(`Unsupported model: ${this.model}`); + } + return modelConfigs[modelPrefix]; + } + + async rerank(query: string, chunks: Chunk[]): Promise { + if (!query || !chunks.length) { + throw new Error("Query and chunks must not be empty"); + } + + try { + const credentials = await this._getCredentials(); + const client = new BedrockRuntimeClient({ + region: this.region, + credentials, + }); + + // Base payload for both models + const payload: any = { + query: query, + documents: chunks.map((chunk) => chunk.content), + top_n: chunks.length, + }; + + // Add api_version for Cohere model + if (this.model.startsWith("cohere.rerank")) { + payload.api_version = 2; + } + + const input = { + body: JSON.stringify(payload), + modelId: this.model, + accept: "*/*", + contentType: "application/json", + }; + + const command = new InvokeModelCommand(input); + const response = await client.send(command); + + if (!response.body) { + throw new Error("Empty response received from Bedrock"); + } + + const responseBody = JSON.parse(new TextDecoder().decode(response.body)); + + // Sort results by index to maintain original order + 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; + } + } } export default Bedrock; diff --git a/core/llm/llms/BedrockImport.ts b/core/llm/llms/BedrockImport.ts index 5726cd91e..45ef554a6 100644 --- a/core/llm/llms/BedrockImport.ts +++ b/core/llm/llms/BedrockImport.ts @@ -4,21 +4,16 @@ import { } from "@aws-sdk/client-bedrock-runtime"; import { fromIni } from "@aws-sdk/credential-providers"; -import { - CompletionOptions, - LLMOptions, - ModelProvider, -} from "../../index.js"; +import { CompletionOptions, LLMOptions } from "../../index.js"; import { BaseLLM } from "../index.js"; class BedrockImport extends BaseLLM { - static providerName: ModelProvider = "bedrockimport"; + static providerName = "bedrockimport"; static defaultOptions: Partial = { - region: "us-east-1" + region: "us-east-1", }; // the BedRock imported custom model ARN modelArn?: string | undefined; - profile?: string | undefined; constructor(options: LLMOptions) { super(options); @@ -52,7 +47,7 @@ class BedrockImport extends BaseLLM { const input = this._generateInvokeModelCommandInput(prompt, options); const command = new InvokeModelWithResponseStreamCommand(input); - const response = await client.send(command, {abortSignal: signal}); + const response = await client.send(command, { abortSignal: signal }); if (response.body) { for await (const item of response.body) { @@ -69,23 +64,22 @@ class BedrockImport extends BaseLLM { options: CompletionOptions, ): any { const payload = { - prompt: prompt + prompt: prompt, }; return { body: JSON.stringify(payload), modelId: this.modelArn, accept: "application/json", - contentType: "application/json" + contentType: "application/json", }; } private async _getCredentials() { try { - return await - fromIni({ + return await fromIni({ profile: this.profile, - ignoreCache: true + ignoreCache: true, })(); } catch (e) { console.warn( diff --git a/core/llm/llms/Cerebras.ts b/core/llm/llms/Cerebras.ts index 0c5a95147..83fc2c52a 100644 --- a/core/llm/llms/Cerebras.ts +++ b/core/llm/llms/Cerebras.ts @@ -1,9 +1,9 @@ -import { LLMOptions, ModelProvider } from "../../index.js"; +import { LLMOptions } from "../../index.js"; import OpenAI from "./OpenAI.js"; class Cerebras extends OpenAI { - static providerName: ModelProvider = "cerebras"; + static providerName = "cerebras"; static defaultOptions: Partial = { apiBase: "https://api.cerebras.ai/v1/", }; diff --git a/core/llm/llms/Cloudflare.ts b/core/llm/llms/Cloudflare.ts index 3c4766365..ea3f51a74 100644 --- a/core/llm/llms/Cloudflare.ts +++ b/core/llm/llms/Cloudflare.ts @@ -1,10 +1,10 @@ -import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js"; +import { ChatMessage, CompletionOptions } from "../../index.js"; import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamSse } from "../stream.js"; export default class Cloudflare extends BaseLLM { - static providerName: ModelProvider = "cloudflare"; + static providerName = "cloudflare"; private _convertArgs(options: CompletionOptions) { const finalOptions = { diff --git a/core/llm/llms/Cohere.ts b/core/llm/llms/Cohere.ts index a43df7a62..1c895c2fe 100644 --- a/core/llm/llms/Cohere.ts +++ b/core/llm/llms/Cohere.ts @@ -1,17 +1,18 @@ import { ChatMessage, + Chunk, CompletionOptions, LLMOptions, - ModelProvider, } from "../../index.js"; import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamJSON } from "../stream.js"; class Cohere extends BaseLLM { - static providerName: ModelProvider = "cohere"; + static providerName = "cohere"; static defaultOptions: Partial = { apiBase: "https://api.cohere.ai/v1", + maxEmbeddingBatchSize: 96, }; static maxStopSequences = 5; @@ -90,6 +91,53 @@ class Cohere extends BaseLLM { } } } + + protected async _embed(chunks: string[]): Promise { + const resp = await this.fetch(new URL("embed", this.apiBase), { + method: "POST", + body: JSON.stringify({ + texts: chunks, + model: this.model, + input_type: "search_document", + embedding_types: ["float"], + truncate: "END", + }), + 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.embeddings.float; + } + + async rerank(query: string, chunks: Chunk[]): Promise { + const resp = await fetch(new URL("rerank", this.apiBase), { + method: "POST", + headers: { + Authorization: `Bearer ${this.apiKey}`, + "Content-Type": "application/json", + }, + body: JSON.stringify({ + model: this.model, + query, + documents: chunks.map((chunk) => chunk.content), + }), + }); + + if (!resp.ok) { + throw new Error(await resp.text()); + } + + const data = (await resp.json()) as any; + const results = data.results.sort((a: any, b: any) => a.index - b.index); + return results.map((result: any) => result.relevance_score); + } } export default Cohere; diff --git a/core/llm/llms/CustomLLM.ts b/core/llm/llms/CustomLLM.ts index 81d038f9d..062f141f6 100644 --- a/core/llm/llms/CustomLLM.ts +++ b/core/llm/llms/CustomLLM.ts @@ -1,13 +1,8 @@ -import { - ChatMessage, - CompletionOptions, - CustomLLM, - ModelProvider, -} from "../../index.js"; +import { ChatMessage, CompletionOptions, CustomLLM } from "../../index.js"; import { BaseLLM } from "../index.js"; class CustomLLMClass extends BaseLLM { - get providerName(): ModelProvider { + get providerName() { return "custom"; } diff --git a/core/llm/llms/DeepInfra.ts b/core/llm/llms/DeepInfra.ts index 0bcbbb596..fa68ce345 100644 --- a/core/llm/llms/DeepInfra.ts +++ b/core/llm/llms/DeepInfra.ts @@ -1,13 +1,29 @@ -import { LLMOptions, ModelProvider } from "../../index.js"; +import { LLMOptions } from "../../index.js"; import OpenAI from "./OpenAI.js"; class DeepInfra extends OpenAI { - static providerName: ModelProvider = "deepinfra"; + static providerName = "deepinfra"; static defaultOptions: Partial = { apiBase: "https://api.deepinfra.com/v1/openai/", }; maxStopWords: number | undefined = 16; + + protected async _embed(chunks: string[]): Promise { + const resp = await this.fetch( + `https://api.deepinfra.com/v1/inference/${this.model}`, + { + method: "POST", + headers: { + Authorization: `bearer ${this.apiKey}`, + }, + body: JSON.stringify({ inputs: chunks }), + }, + ); + + const data = await resp.json(); + return data.embeddings; + } } export default DeepInfra; diff --git a/core/llm/llms/Deepseek.ts b/core/llm/llms/Deepseek.ts index 177ac7efa..c1453d0db 100644 --- a/core/llm/llms/Deepseek.ts +++ b/core/llm/llms/Deepseek.ts @@ -1,11 +1,11 @@ -import { CompletionOptions, LLMOptions, ModelProvider } from "../../index.js"; +import { CompletionOptions, LLMOptions } from "../../index.js"; import { streamSse } from "../stream.js"; import { osModelsEditPrompt } from "../templates/edit.js"; import OpenAI from "./OpenAI.js"; class Deepseek extends OpenAI { - static providerName: ModelProvider = "deepseek"; + static providerName = "deepseek"; static defaultOptions: Partial = { apiBase: "https://api.deepseek.com/", model: "deepseek-coder", @@ -46,7 +46,7 @@ class Deepseek extends OpenAI { Accept: "application/json", Authorization: `Bearer ${this.apiKey}`, }, - signal + signal, }); for await (const chunk of streamSse(resp)) { yield chunk.choices[0].text; diff --git a/core/llm/llms/Fireworks.ts b/core/llm/llms/Fireworks.ts index a9dc44707..558cc77a9 100644 --- a/core/llm/llms/Fireworks.ts +++ b/core/llm/llms/Fireworks.ts @@ -1,9 +1,9 @@ -import { LLMOptions, ModelProvider } from "../../index.js"; +import { LLMOptions } from "../../index.js"; import OpenAI from "./OpenAI.js"; class Fireworks extends OpenAI { - static providerName: ModelProvider = "fireworks"; + static providerName = "fireworks"; static defaultOptions: Partial = { apiBase: "https://api.fireworks.ai/inference/v1", }; diff --git a/core/llm/llms/Flowise.ts b/core/llm/llms/Flowise.ts index 8c5b0f459..cdc4f8f77 100644 --- a/core/llm/llms/Flowise.ts +++ b/core/llm/llms/Flowise.ts @@ -1,11 +1,6 @@ import socketIOClient, { Socket } from "socket.io-client"; -import { - ChatMessage, - CompletionOptions, - LLMOptions, - ModelProvider, -} from "../../index.js"; +import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; @@ -58,7 +53,7 @@ interface IFlowiseProviderLLMOptions extends LLMOptions { } class Flowise extends BaseLLM { - static providerName: ModelProvider = "flowise"; + static providerName = "flowise"; static defaultOptions: Partial = { apiBase: "http://localhost:3000", }; diff --git a/core/llm/llms/FreeTrial.ts b/core/llm/llms/FreeTrial.ts index 895d6c42f..34b916346 100644 --- a/core/llm/llms/FreeTrial.ts +++ b/core/llm/llms/FreeTrial.ts @@ -1,15 +1,29 @@ import { TRIAL_FIM_MODEL } from "../../config/onboarding.js"; import { getHeaders } from "../../continueServer/stubs/headers.js"; import { TRIAL_PROXY_URL } from "../../control-plane/client.js"; -import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js"; +import { + ChatMessage, + Chunk, + CompletionOptions, + LLMOptions, +} from "../../index.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; class FreeTrial extends BaseLLM { - static providerName: ModelProvider = "free-trial"; + static providerName = "free-trial"; + static defaultOptions: Partial | undefined = { + maxEmbeddingBatchSize: 128, + model: "voyage-code-2", + }; private ghAuthToken: string | undefined = undefined; + constructor(options: LLMOptions) { + super(options); + this.embeddingId = `${this.constructor.name}::${this.model}`; + } + setupGhAuthToken(ghAuthToken: string | undefined) { this.ghAuthToken = ghAuthToken; } @@ -142,7 +156,7 @@ class FreeTrial extends BaseLLM { }; completion += chunk; } - this._countTokens(completion, args.model, false); + await this._countTokens(completion, args.model, false); } supportsFim(): boolean { @@ -174,7 +188,7 @@ class FreeTrial extends BaseLLM { yield value; completion += value; } - this._countTokens(completion, args.model, false); + await this._countTokens(completion, args.model, false); } catch (e: any) { if (e.message.startsWith("HTTP 429")) { throw new Error( @@ -197,6 +211,52 @@ class FreeTrial extends BaseLLM { "gemini-1.5-pro-latest", ]; } + + protected async _embed(chunks: string[]): Promise { + const resp = await this.fetch(new URL("embeddings", TRIAL_PROXY_URL), { + method: "POST", + body: JSON.stringify({ + input: chunks, + model: this.model, + }), + headers: { + "Content-Type": "application/json", + ...(await getHeaders()), + }, + }); + + if (resp.status !== 200) { + throw new Error(`Failed to embed: ${resp.status} ${await resp.text()}`); + } + + const data = (await resp.json()) as any; + return data.embeddings; + } + + async rerank(query: string, chunks: Chunk[]): Promise { + if (chunks.length === 0) { + return []; + } + const resp = await this.fetch(new URL("rerank", TRIAL_PROXY_URL), { + method: "POST", + headers: { + "Content-Type": "application/json", + ...(await getHeaders()), + }, + body: JSON.stringify({ + query, + documents: chunks.map((chunk) => chunk.content), + }), + }); + + if (!resp.ok) { + throw new Error(await resp.text()); + } + + const data = (await resp.json()) as any; + const results = data.sort((a: any, b: any) => a.index - b.index); + return results.map((result: any) => result.relevance_score); + } } export default FreeTrial; diff --git a/core/llm/llms/FunctionNetwork.ts b/core/llm/llms/FunctionNetwork.ts index 1010e47ed..7f5b576f4 100644 --- a/core/llm/llms/FunctionNetwork.ts +++ b/core/llm/llms/FunctionNetwork.ts @@ -1,12 +1,13 @@ -import { LLMOptions, ModelProvider } from "../../index.js"; +import { LLMOptions } from "../../index.js"; import OpenAI from "./OpenAI.js"; class FunctionNetwork extends OpenAI { - static providerName: ModelProvider = "function-network"; + static providerName = "function-network"; static defaultOptions: Partial = { apiBase: "https://api.function.network/v1/", model: "meta/llama-3.1-70b-instruct", + maxEmbeddingBatchSize: 128, }; private static modelConversion: { [key: string]: string } = { @@ -36,6 +37,27 @@ class FunctionNetwork extends OpenAI { public supportsPrefill(): boolean { return false; } + + protected async _embed(chunks: string[]): Promise { + const resp = await this.fetch(new URL("embeddings", this.apiBase), { + method: "POST", + body: JSON.stringify({ + input: chunks, + model: this.model, + }), + 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 FunctionNetwork; diff --git a/core/llm/llms/Gemini.ts b/core/llm/llms/Gemini.ts index e9cc484c8..02abd8bf9 100644 --- a/core/llm/llms/Gemini.ts +++ b/core/llm/llms/Gemini.ts @@ -3,19 +3,19 @@ import { CompletionOptions, LLMOptions, MessagePart, - ModelProvider, } from "../../index.js"; import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; class Gemini extends BaseLLM { - static providerName: ModelProvider = "gemini"; + static providerName = "gemini"; static defaultOptions: Partial = { model: "gemini-pro", apiBase: "https://generativelanguage.googleapis.com/v1beta/", maxStopWords: 5, + maxEmbeddingBatchSize: 100, }; // Function to convert completion options to Gemini format @@ -245,10 +245,39 @@ class Gemini extends BaseLLM { const data = await response.json(); yield { role: "assistant", content: data.candidates[0].content }; } -} -async function delay(seconds: number) { - return new Promise((resolve) => setTimeout(resolve, seconds * 1000)); + async _embed(batch: string[]): Promise { + // Batch embed endpoint: https://ai.google.dev/api/embeddings?authuser=1#EmbedContentRequest + const requests = batch.map((text) => ({ + model: this.model, + content: { + role: "user", + parts: [{ text }], + }, + })); + + const resp = await this.fetch( + new URL(`${this.model}:batchEmbedContents`, this.apiBase), + { + method: "POST", + body: JSON.stringify({ + requests, + }), + headers: { + "x-goog-api-key": this.apiKey, + "Content-Type": "application/json", + } as any, + }, + ); + + if (!resp.ok) { + throw new Error(await resp.text()); + } + + const data = (await resp.json()) as any; + + return data.embeddings.map((embedding: any) => embedding.values); + } } export default Gemini; diff --git a/core/llm/llms/Groq.ts b/core/llm/llms/Groq.ts index 0f28f8eb9..cf26f993c 100644 --- a/core/llm/llms/Groq.ts +++ b/core/llm/llms/Groq.ts @@ -1,9 +1,9 @@ -import { LLMOptions, ModelProvider } from "../../index.js"; +import { LLMOptions } from "../../index.js"; import OpenAI from "./OpenAI.js"; class Groq extends OpenAI { - static providerName: ModelProvider = "groq"; + static providerName = "groq"; static defaultOptions: Partial = { apiBase: "https://api.groq.com/openai/v1/", }; diff --git a/core/llm/llms/HuggingFaceInferenceAPI.ts b/core/llm/llms/HuggingFaceInferenceAPI.ts index 7e8d11c56..40e67b3e5 100644 --- a/core/llm/llms/HuggingFaceInferenceAPI.ts +++ b/core/llm/llms/HuggingFaceInferenceAPI.ts @@ -1,9 +1,9 @@ -import { CompletionOptions, ModelProvider } from "../../index.js"; +import { CompletionOptions } from "../../index.js"; import { BaseLLM } from "../index.js"; import { streamSse } from "../stream.js"; class HuggingFaceInferenceAPI extends BaseLLM { - static providerName: ModelProvider = "huggingface-inference-api"; + static providerName = "huggingface-inference-api"; private _convertArgs(options: CompletionOptions) { return { @@ -37,7 +37,7 @@ class HuggingFaceInferenceAPI extends BaseLLM { stream: true, parameters: this._convertArgs(options), }), - signal + signal, }); async function* stream() { diff --git a/core/indexing/embeddings/HuggingFaceTEIEmbeddingsProvider.ts b/core/llm/llms/HuggingFaceTEI.ts similarity index 55% rename from core/indexing/embeddings/HuggingFaceTEIEmbeddingsProvider.ts rename to core/llm/llms/HuggingFaceTEI.ts index c331f4529..206bbd5e2 100644 --- a/core/indexing/embeddings/HuggingFaceTEIEmbeddingsProvider.ts +++ b/core/llm/llms/HuggingFaceTEI.ts @@ -1,36 +1,29 @@ -import { Response } from "node-fetch"; - -import { - EmbeddingsProviderName, - EmbedOptions, - FetchFunction, -} from "../../index.js"; +import { Chunk, LLMOptions } from "../../index.js"; import { withExponentialBackoff } from "../../util/withExponentialBackoff.js"; +import { BaseLLM } from "../index.js"; -import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js"; +class HuggingFaceTEIEmbeddingsProvider extends BaseLLM { + static providerName = "huggingface-tei"; -class HuggingFaceTEIEmbeddingsProvider extends BaseEmbeddingsProvider { - static providerName: EmbeddingsProviderName = "huggingface-tei"; - private _maxBatchSize?: number; - get maxBatchSize(): number | undefined { - return this._maxBatchSize ?? super.maxBatchSize; - } - - static defaultOptions: Partial | undefined = { + static defaultOptions: Partial | undefined = { apiBase: "http://localhost:8080", model: "tei", }; - constructor(options: EmbedOptions, fetch: FetchFunction) { - super(options, fetch); - // without this extra slash the last portion of the path will be dropped from the URL when using the node.js URL constructor - if (!this.options.apiBase?.endsWith("/")) { - this.options.apiBase += "/"; - } - this.doInfoRequest().then((response) => { - this.options.model = response.model_id; - this._maxBatchSize = response.max_client_batch_size; - }); + constructor(options: LLMOptions) { + super(options); + + this.doInfoRequest() + .then((response) => { + this.model = response.model_id; + this.maxEmbeddingBatchSize = response.max_client_batch_size; + }) + .catch((error) => { + console.error( + "Failed to fetch info from HuggingFace TEI Embeddings Provider:", + error, + ); + }); } async embed(chunks: string[]) { @@ -44,7 +37,7 @@ class HuggingFaceTEIEmbeddingsProvider extends BaseEmbeddingsProvider { async doEmbedRequest(batch: string[]): Promise { const resp = await withExponentialBackoff(() => - this.fetch(new URL("embed", this.options.apiBase), { + this.fetch(new URL("embed", this.apiBase), { method: "POST", body: JSON.stringify({ inputs: batch, @@ -67,7 +60,7 @@ class HuggingFaceTEIEmbeddingsProvider extends BaseEmbeddingsProvider { async doInfoRequest(): Promise { const resp = await withExponentialBackoff(() => - this.fetch(new URL("info", this.options.apiBase), { + this.fetch(new URL("info", this.apiBase), { method: "GET", }), ); @@ -76,6 +69,38 @@ class HuggingFaceTEIEmbeddingsProvider extends BaseEmbeddingsProvider { } return (await resp.json()) as TEIInfoResponse; } + + async rerank(query: string, chunks: Chunk[]): Promise { + const headers: Record = { + "Content-Type": "application/json", + }; + + if (this.apiKey) { + headers["Authorization"] = `Bearer ${this.apiKey}`; + } + + const resp = await fetch(new URL("rerank", this.apiBase), { + method: "POST", + headers, + body: JSON.stringify({ + query: query, + return_text: false, + raw_scores: false, + texts: chunks.map((chunk) => chunk.content), + truncation_direction: "Right", + truncate: true, + }), + }); + + if (!resp.ok) { + throw new Error(await resp.text()); + } + + const data = (await resp.json()) as any; + // Resort into original order and extract scores + const results = data.sort((a: any, b: any) => a.index - b.index); + return results.map((result: any) => result.score); + } } class TEIEmbedError extends Error { diff --git a/core/llm/llms/HuggingFaceTGI.ts b/core/llm/llms/HuggingFaceTGI.ts index df84083dc..481532f95 100644 --- a/core/llm/llms/HuggingFaceTGI.ts +++ b/core/llm/llms/HuggingFaceTGI.ts @@ -1,10 +1,10 @@ -import { CompletionOptions, LLMOptions, ModelProvider } from "../../index.js"; +import { CompletionOptions, LLMOptions } from "../../index.js"; import { BaseLLM } from "../index.js"; import { streamSse } from "../stream.js"; class HuggingFaceTGI extends BaseLLM { private static MAX_STOP_TOKENS = 4; - static providerName: ModelProvider = "huggingface-tgi"; + static providerName = "huggingface-tgi"; static defaultOptions: Partial = { apiBase: "http://localhost:8080/", }; @@ -61,7 +61,7 @@ class HuggingFaceTGI extends BaseLLM { "Content-Type": "application/json", }, body: JSON.stringify({ inputs: prompt, parameters: args }), - signal + signal, }, ); diff --git a/core/llm/llms/Kindo.ts b/core/llm/llms/Kindo.ts index 8010fff16..88df3c2fd 100644 --- a/core/llm/llms/Kindo.ts +++ b/core/llm/llms/Kindo.ts @@ -1,17 +1,17 @@ -import { LLMOptions, ModelProvider } from "../.."; +import { LLMOptions } from "../.."; import OpenAI from "./OpenAI"; class Kindo extends OpenAI { - static providerName: ModelProvider = "kindo"; - static defaultOptions: Partial = { - apiBase: "https://llm.kindo.ai/v1", - requestOptions: { - headers: { - "kindo-token-transaction-type": "CONTINUE" - } - } - }; + static providerName = "kindo"; + static defaultOptions: Partial = { + apiBase: "https://llm.kindo.ai/v1", + requestOptions: { + headers: { + "kindo-token-transaction-type": "CONTINUE", + }, + }, + }; } -export default Kindo; \ No newline at end of file +export default Kindo; diff --git a/core/llm/llms/LMStudio.ts b/core/llm/llms/LMStudio.ts index 03a3378d4..d7acc91f3 100644 --- a/core/llm/llms/LMStudio.ts +++ b/core/llm/llms/LMStudio.ts @@ -1,9 +1,9 @@ -import { LLMOptions, ModelProvider } from "../../index.js"; +import { LLMOptions } from "../../index.js"; import OpenAI from "./OpenAI.js"; class LMStudio extends OpenAI { - static providerName: ModelProvider = "lmstudio"; + static providerName = "lmstudio"; static defaultOptions: Partial = { apiBase: "http://localhost:1234/v1/", }; diff --git a/core/llm/llms/LlamaCpp.ts b/core/llm/llms/LlamaCpp.ts index 80ada3fdf..a8b7e08b3 100644 --- a/core/llm/llms/LlamaCpp.ts +++ b/core/llm/llms/LlamaCpp.ts @@ -1,9 +1,9 @@ -import { CompletionOptions, LLMOptions, ModelProvider } from "../../index.js"; +import { CompletionOptions, LLMOptions } from "../../index.js"; import { BaseLLM } from "../index.js"; import { streamSse } from "../stream.js"; class LlamaCpp extends BaseLLM { - static providerName: ModelProvider = "llama.cpp"; + static providerName = "llama.cpp"; static defaultOptions: Partial = { apiBase: "http://127.0.0.1:8080/", }; @@ -43,7 +43,7 @@ class LlamaCpp extends BaseLLM { stream: true, ...this._convertArgs(options, prompt), }), - signal + signal, }); for await (const value of streamSse(resp)) { diff --git a/core/llm/llms/Llamafile.ts b/core/llm/llms/Llamafile.ts index 91f7e8a50..a4c9f1037 100644 --- a/core/llm/llms/Llamafile.ts +++ b/core/llm/llms/Llamafile.ts @@ -1,9 +1,7 @@ -import { ModelProvider } from "../../index.js"; - import LlamaCpp from "./LlamaCpp.js"; class Llamafile extends LlamaCpp { - static providerName: ModelProvider = "llamafile"; + static providerName = "llamafile"; } export default Llamafile; diff --git a/core/llm/llms/Mistral.ts b/core/llm/llms/Mistral.ts index f18aff0e7..b723016fe 100644 --- a/core/llm/llms/Mistral.ts +++ b/core/llm/llms/Mistral.ts @@ -1,16 +1,17 @@ -import { ChatMessage, LLMOptions, ModelProvider } from "../../index.js"; +import { ChatMessage, LLMOptions } from "../../index.js"; import { gptEditPrompt } from "../templates/edit.js"; import OpenAI from "./OpenAI.js"; class Mistral extends OpenAI { - static providerName: ModelProvider = "mistral"; + static providerName = "mistral"; static defaultOptions: Partial = { apiBase: "https://api.mistral.ai/v1/", model: "codestral-latest", promptTemplates: { edit: gptEditPrompt, }, + maxEmbeddingBatchSize: 128, }; constructor(options: LLMOptions) { diff --git a/core/llm/llms/Mock.ts b/core/llm/llms/Mock.ts index 6f564cce7..811ecba94 100644 --- a/core/llm/llms/Mock.ts +++ b/core/llm/llms/Mock.ts @@ -1,9 +1,9 @@ -import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js"; +import { ChatMessage, CompletionOptions } from "../../index.js"; import { BaseLLM } from "../index.js"; class MockLLM extends BaseLLM { public completion: string = "Test Completion"; - static providerName: ModelProvider = "mock"; + static providerName = "mock"; protected async *_streamComplete( prompt: string, diff --git a/core/llm/llms/Moonshot.ts b/core/llm/llms/Moonshot.ts index 5a015dcca..732ce81cd 100644 --- a/core/llm/llms/Moonshot.ts +++ b/core/llm/llms/Moonshot.ts @@ -1,11 +1,11 @@ -import { CompletionOptions, LLMOptions, ModelProvider } from "../../index.js"; +import { CompletionOptions, LLMOptions } from "../../index.js"; import { streamSse } from "../stream.js"; import { osModelsEditPrompt } from "../templates/edit.js"; import OpenAI from "./OpenAI.js"; class Moonshot extends OpenAI { - static providerName: ModelProvider = "moonshot"; + static providerName = "moonshot"; static defaultOptions: Partial = { apiBase: "https://api.moonshot.cn/v1/", model: "moonshot-v1-8k", @@ -50,7 +50,7 @@ class Moonshot extends OpenAI { Accept: "application/json", Authorization: `Bearer ${this.apiKey}`, }, - signal + signal, }); for await (const chunk of streamSse(resp)) { yield chunk.choices[0].delta.content; diff --git a/core/llm/llms/Msty.ts b/core/llm/llms/Msty.ts index 73c3e7aa1..e078a299d 100644 --- a/core/llm/llms/Msty.ts +++ b/core/llm/llms/Msty.ts @@ -1,9 +1,9 @@ -import { LLMOptions, ModelProvider } from "../../index.js"; +import { LLMOptions } from "../../index.js"; import Ollama from "./Ollama.js"; class Msty extends Ollama { - static providerName: ModelProvider = "msty"; + static providerName = "msty"; static defaultOptions: Partial = { apiBase: "http://localhost:10000", model: "codellama-7b", diff --git a/core/llm/llms/Nebius.ts b/core/llm/llms/Nebius.ts index e1935815d..dc97f94d0 100644 --- a/core/llm/llms/Nebius.ts +++ b/core/llm/llms/Nebius.ts @@ -1,9 +1,9 @@ -import { LLMOptions, ModelProvider } from "../.."; +import { LLMOptions } from "../.."; import OpenAI from "./OpenAI"; class Nebius extends OpenAI { - static providerName: ModelProvider = "nebius"; + static providerName = "nebius"; static defaultOptions: Partial = { apiBase: "https://api.studio.nebius.ai/v1/", useLegacyCompletionsEndpoint: false, diff --git a/core/llm/llms/Nvidia.ts b/core/llm/llms/Nvidia.ts index 159f34222..302687651 100644 --- a/core/llm/llms/Nvidia.ts +++ b/core/llm/llms/Nvidia.ts @@ -1,33 +1,39 @@ -import { LLMOptions, ModelProvider, ChatMessage } from "../../index.js"; +import { LLMOptions } from "../../index.js"; import OpenAI from "./OpenAI.js"; class Nvidia extends OpenAI { // NVIDIA NIMs currently limits the number of stops for Starcoder 2 to 4 // https://docs.api.nvidia.com/nim/reference/bigcode-starcoder2-7b-infer - protected maxStopWordsStarCoder = 4; - static providerName: ModelProvider = "nvidia"; + maxStopWords = 4; + static providerName = "nvidia"; static defaultOptions: Partial = { apiBase: "https://integrate.api.nvidia.com/v1/", useLegacyCompletionsEndpoint: false, + maxEmbeddingBatchSize: 96, }; - protected _convertArgs(options: any, messages: ChatMessage[]) { - const url = new URL(this.apiBase!); - const finalOptions = { - messages: messages.map(this._convertMessage), - model: this._convertModelName(options.model), - max_tokens: options.maxTokens, - temperature: options.temperature, - top_p: options.topP, - frequency_penalty: options.frequencyPenalty, - presence_penalty: options.presencePenalty, - stop: options.model.includes("starcoder2") - ? options.stop?.slice(0, this.maxStopWordsStarCoder) - : options.stop, - }; + protected async _embed(chunks: string[]): Promise { + const resp = await this.fetch(new URL("embeddings", this.apiBase), { + method: "POST", + body: JSON.stringify({ + input: chunks, + model: this.model, + input_type: "passage", + truncate: "END", + }), + headers: { + Authorization: `Bearer ${this.apiKey}`, + "Content-Type": "application/json", + }, + }); - return finalOptions; + 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); } } diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index c56884e4b..c6be1c98b 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -1,9 +1,4 @@ -import { - ChatMessage, - CompletionOptions, - LLMOptions, - ModelProvider, -} from "../../index.js"; +import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; @@ -59,10 +54,11 @@ interface ChatOptions extends BaseOptions { } class Ollama extends BaseLLM { - static providerName: ModelProvider = "ollama"; + static providerName = "ollama"; static defaultOptions: Partial = { apiBase: "http://localhost:11434/", model: "codellama-7b", + maxEmbeddingBatchSize: 64, }; private fimSupported: boolean = false; @@ -405,6 +401,32 @@ class Ollama extends BaseLLM { ); } } + + protected async _embed(chunks: string[]): Promise { + 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}`, + }, + }); + + if (!resp.ok) { + throw new Error(`Failed to embed chunk: ${await resp.text()}`); + } + + const data = await resp.json(); + const embedding: number[][] = data.embeddings; + + if (!embedding || embedding.length === 0) { + throw new Error("Ollama generated empty embedding"); + } + return embedding; + } } export default Ollama; diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 1ac63f8af..82afb8cea 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -1,12 +1,18 @@ +import { ChatCompletionCreateParams } from "openai/resources/index"; + import { ChatMessage, CompletionOptions, LLMOptions, - ModelProvider, Tool, } from "../../index.js"; import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; +import { + fromChatCompletionChunk, + LlmApiRequestType, + toChatBody, +} from "../openaiTypeConverters.js"; import { streamSse } from "../stream.js"; const NON_CHAT_MODELS = [ @@ -51,48 +57,20 @@ class OpenAI extends BaseLLM { this.apiVersion = options.apiVersion ?? "2023-07-01-preview"; } - static providerName: ModelProvider = "openai"; - static defaultOptions: Partial = { + static providerName = "openai"; + static defaultOptions: Partial | undefined = { apiBase: "https://api.openai.com/v1/", + maxEmbeddingBatchSize: 128, }; - protected _convertMessage(message: ChatMessage) { - if (message.role === "tool") { - return { - role: "tool", - content: message.content, - tool_call_id: message.toolCallId, - }; - } - - if (typeof message.content === "string") { - return message; - } else if (!message.content.some((item) => item.type !== "text")) { - // If no multi-media is in the message, just send as text - // for compatibility with OpenAI "compatible" servers - // that don't support multi-media format - return { - ...message, - content: message.content.map((item) => item.text).join(""), - }; - } - - const parts = message.content.map((part) => { - const msg: any = { - type: part.type, - text: part.text, - }; - if (part.type === "imageUrl") { - msg.image_url = { ...part.imageUrl, detail: "auto" }; - msg.type = "image_url"; - } - return msg; - }); - return { - ...message, - content: parts, - }; - } + protected useOpenAIAdapterFor: (LlmApiRequestType | "*")[] = [ + "chat", + "embed", + "list", + "rerank", + "streamChat", + "streamFim", + ]; protected _convertModelName(model: string): string { return model; @@ -121,33 +99,32 @@ class OpenAI extends BaseLLM { }; } - protected _convertArgs(options: CompletionOptions, messages: ChatMessage[]) { + protected getMaxStopWords(): number { const url = new URL(this.apiBase!); - const tools = options.tools?.map(this.convertTool); - const finalOptions: any = { - messages: messages.map(this._convertMessage), - model: this._convertModelName(options.model), - max_tokens: options.maxTokens, - temperature: options.temperature, - top_p: options.topP, - frequency_penalty: options.frequencyPenalty, - presence_penalty: options.presencePenalty, - stream: options.stream ?? true, - stop: - // Jan + Azure OpenAI don't truncate and will throw an error - this.maxStopWords !== undefined - ? options.stop?.slice(0, this.maxStopWords) - : url.host === "api.deepseek.com" - ? options.stop?.slice(0, 16) - : url.port === "1337" || - url.host === "api.openai.com" || - url.host === "api.groq.com" || - this.apiType === "azure" - ? options.stop?.slice(0, 4) - : options.stop, - tools, - }; + if (this.maxStopWords !== undefined) { + return this.maxStopWords; + } else if (url.host === "api.deepseek.com") { + return 16; + } else if ( + url.port === "1337" || + url.host === "api.openai.com" || + url.host === "api.groq.com" || + this.apiType === "azure" + ) { + return 4; + } else { + return Infinity; + } + } + + protected _convertArgs( + options: CompletionOptions, + messages: ChatMessage[], + ): ChatCompletionCreateParams { + const finalOptions = toChatBody(messages, options); + + finalOptions.stop = options.stop?.slice(0, this.getMaxStopWords()); // OpenAI o1-preview and o1-mini: if (this.isO1Model(options.model)) { @@ -310,26 +287,9 @@ class OpenAI extends BaseLLM { } for await (const value of streamSse(response)) { - if (value.choices?.[0]?.delta?.content) { - yield { - role: "assistant", - content: value.choices[0].delta.content, - }; - } else if (value.choices?.[0]?.delta?.tool_calls) { - yield { - role: "assistant", - content: "", - toolCalls: value.choices?.[0]?.delta?.tool_calls.map( - (tool_call: any) => ({ - id: tool_call.id, - type: tool_call.type, - function: { - name: tool_call.function.name, - arguments: tool_call.function.arguments, - }, - }), - ), - }; + const chunk = fromChatCompletionChunk(value); + if (chunk) { + yield chunk; } } } @@ -377,6 +337,44 @@ class OpenAI extends BaseLLM { const data = await response.json(); return data.data.map((m: any) => m.id); } + + private _getEmbedEndpoint() { + if (!this.apiBase) { + throw new Error( + "No API base URL provided. Please set the 'apiBase' option in config.json", + ); + } + + if (this.apiType === "azure") { + return new URL( + `openai/deployments/${this.deployment}/embeddings?api-version=${this.apiVersion}`, + this.apiBase, + ); + } + return new URL("embeddings", this.apiBase); + } + + protected async _embed(chunks: string[]): Promise { + const resp = await this.fetch(this._getEmbedEndpoint(), { + method: "POST", + body: JSON.stringify({ + input: chunks, + model: this.model, + }), + headers: { + Authorization: `Bearer ${this.apiKey}`, + "Content-Type": "application/json", + "api-key": this.apiKey ?? "", // For Azure + }, + }); + + 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 OpenAI; diff --git a/core/llm/llms/OpenRouter.ts b/core/llm/llms/OpenRouter.ts index 46b5afecd..b35aaa59c 100644 --- a/core/llm/llms/OpenRouter.ts +++ b/core/llm/llms/OpenRouter.ts @@ -1,10 +1,10 @@ -import { LLMOptions, ModelProvider } from "../../index.js"; +import { LLMOptions } from "../../index.js"; import { osModelsEditPrompt } from "../templates/edit.js"; import OpenAI from "./OpenAI.js"; class OpenRouter extends OpenAI { - static providerName: ModelProvider = "openrouter"; + static providerName = "openrouter"; static defaultOptions: Partial = { apiBase: "https://openrouter.ai/api/v1/", model: "gpt-4o-mini", diff --git a/core/llm/llms/Replicate.ts b/core/llm/llms/Replicate.ts index 59994cec1..c394ed29f 100644 --- a/core/llm/llms/Replicate.ts +++ b/core/llm/llms/Replicate.ts @@ -1,6 +1,6 @@ import ReplicateClient from "replicate"; -import { CompletionOptions, LLMOptions, ModelProvider } from "../../index.js"; +import { CompletionOptions, LLMOptions } from "../../index.js"; import { BaseLLM } from "../index.js"; class Replicate extends BaseLLM { @@ -35,19 +35,19 @@ class Replicate extends BaseLLM { "phind-codellama-34b": "kcaverly/phind-codellama-34b-v2-gguf" as any, }; - static providerName: ModelProvider = "replicate"; + static providerName = "replicate"; private _replicate: ReplicateClient; private _convertArgs( options: CompletionOptions, prompt: string, - signal: AbortSignal - ): [`${string}/${string}:${string}`, { input: any, signal: AbortSignal }] { + signal: AbortSignal, + ): [`${string}/${string}:${string}`, { input: any; signal: AbortSignal }] { return [ Replicate.MODEL_IDS[options.model] || (options.model as any), { input: { prompt, message: prompt }, - signal + signal, }, ]; } diff --git a/core/llm/llms/SageMaker.ts b/core/llm/llms/SageMaker.ts index edbda4d34..1f11d41ea 100644 --- a/core/llm/llms/SageMaker.ts +++ b/core/llm/llms/SageMaker.ts @@ -1,26 +1,25 @@ import { + InvokeEndpointCommand, InvokeEndpointWithResponseStreamCommand, - SageMakerRuntimeClient + SageMakerRuntimeClient, } from "@aws-sdk/client-sagemaker-runtime"; import { fromIni } from "@aws-sdk/credential-providers"; // @ts-ignore import jinja from "jinja-js"; -import { - ChatMessage, - CompletionOptions, - LLMOptions, - ModelProvider -} from "../../index.js"; +import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; import { BaseLLM } from "../index.js"; class SageMaker extends BaseLLM { - private static PROFILE_NAME: string = "sagemaker"; - static providerName: ModelProvider = "sagemaker"; + private static DEFAULT_PROFILE_NAME: string = "sagemaker"; + + static providerName = "sagemaker"; + static defaultOptions: Partial = { region: "us-west-2", contextLength: 200_000, + maxEmbeddingBatchSize: 1, }; constructor(options: LLMOptions) { @@ -28,6 +27,8 @@ class SageMaker extends BaseLLM { if (!options.apiBase) { this.apiBase = `https://runtime.sagemaker.${options.region}.amazonaws.com`; } + + this.profile ??= SageMaker.DEFAULT_PROFILE_NAME; } protected async *_streamComplete( @@ -62,19 +63,16 @@ class SageMaker extends BaseLLM { if ("choices" in data) { if ("delta" in data.choices[0]) { text = data.choices[0].delta.content; - } - else { + } else { text = data.choices[0].text; } - } - else if ("token" in data) { + } else if ("token" in data) { text = data.token.text; } if (text !== undefined) { yield text; } - } catch (e) { - } + } catch (e) {} buffer = buffer.slice(position + 1); } } @@ -114,19 +112,16 @@ class SageMaker extends BaseLLM { if ("choices" in data) { if ("delta" in data.choices[0]) { text = data.choices[0].delta.content; - } - else { + } else { text = data.choices[0].text; } - } - else if ("token" in data) { + } else if ("token" in data) { text = data.token.text; } if (text !== undefined) { yield { role: "assistant", content: text }; } - } catch (e) { - } + } catch (e) {} buffer = buffer.slice(position + 1); } } @@ -136,16 +131,61 @@ class SageMaker extends BaseLLM { private async _getCredentials() { try { return await fromIni({ - profile: SageMaker.PROFILE_NAME, + profile: this.profile, })(); } catch (e) { console.warn( - `AWS profile with name ${SageMaker.PROFILE_NAME} not found in ~/.aws/credentials, using default profile`, + `AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`, ); return await fromIni()(); } } + async embed(chunks: string[]) { + const credentials = await this._getCredentials(); + const client = new SageMakerRuntimeClient({ + region: this.region, + credentials: { + accessKeyId: credentials.accessKeyId, + secretAccessKey: credentials.secretAccessKey, + sessionToken: credentials.sessionToken || "", + }, + }); + + const input = this._generateInvokeModelCommandInput(chunks); + const command = new InvokeEndpointCommand(input); + const response = await client.send(command); + + if (response.Body) { + const responseBody = JSON.parse(new TextDecoder().decode(response.Body)); + // If the body contains a key called "embedding" or "embeddings", return the value, otherwise return the whole body + if (responseBody.embedding) { + return responseBody.embedding; + } else if (responseBody.embeddings) { + return responseBody.embeddings; + } else { + return responseBody; + } + } + } + private _generateInvokeModelCommandInput(prompts: string | string[]): any { + const payload = { + inputs: prompts, + normalize: true, + // ...(options.requestOptions?.extraBodyProperties || {}), + }; + + if (this.requestOptions?.extraBodyProperties) { + Object.assign(payload, this.requestOptions.extraBodyProperties); + } + + return { + EndpointName: this.model, + Body: JSON.stringify(payload), + ContentType: "application/json", + CustomAttributes: "accept_eula=false", + }; + } } interface SageMakerModelToolkit { @@ -157,19 +197,20 @@ interface SageMakerModelToolkit { } class MessageAPIToolkit implements SageMakerModelToolkit { - constructor(private sagemaker: SageMaker) { } + constructor(private sagemaker: SageMaker) {} generateCommand( messages: ChatMessage[], prompt: string, options: CompletionOptions, ): InvokeEndpointWithResponseStreamCommand { - if ("chat_template" in this.sagemaker.completionOptions) { // for some model you can apply chat_template to the model - let prompt = jinja.compile(this.sagemaker.completionOptions.chat_template).render( - { messages: messages, add_generation_prompt: true }, - { autoEscape: false } - ); + let prompt = jinja + .compile(this.sagemaker.completionOptions.chat_template) + .render( + { messages: messages, add_generation_prompt: true }, + { autoEscape: false }, + ); const payload = { inputs: prompt, parameters: this.sagemaker.completionOptions, @@ -182,8 +223,7 @@ class MessageAPIToolkit implements SageMakerModelToolkit { ContentType: "application/json", CustomAttributes: "accept_eula=false", }); - } - else { + } else { const payload = { messages: messages, max_tokens: options.maxTokens, @@ -203,11 +243,10 @@ class MessageAPIToolkit implements SageMakerModelToolkit { CustomAttributes: "accept_eula=false", }); } - } } class CompletionAPIToolkit implements SageMakerModelToolkit { - constructor(private sagemaker: SageMaker) { } + constructor(private sagemaker: SageMaker) {} generateCommand( messages: ChatMessage[], prompt: string, diff --git a/core/llm/llms/SambaNova.ts b/core/llm/llms/SambaNova.ts index 7719a6e9b..7c1f83c89 100644 --- a/core/llm/llms/SambaNova.ts +++ b/core/llm/llms/SambaNova.ts @@ -1,10 +1,9 @@ import OpenAI from "./OpenAI.js"; -import type { LLMOptions, ModelProvider } from "../../index.js"; - +import type { LLMOptions } from "../../index.js"; class SambaNova extends OpenAI { - static providerName: ModelProvider = "sambanova"; + static providerName = "sambanova"; static defaultOptions: Partial = { apiBase: "https://api.sambanova.ai/v1/", }; diff --git a/core/llm/llms/Scaleway.ts b/core/llm/llms/Scaleway.ts new file mode 100644 index 000000000..95b8d6db3 --- /dev/null +++ b/core/llm/llms/Scaleway.ts @@ -0,0 +1,27 @@ +import OpenAI from "./OpenAI"; + +import { LLMOptions } from "../../index.js"; + + +class Scaleway extends OpenAI { + static providerName = "scaleway"; + static defaultOptions: Partial = { + apiBase: "https://api.scaleway.ai/v1/", + model: "qwen2.5-coder-32b-instruct", + useLegacyCompletionsEndpoint: false, + }; + + private static MODEL_IDS: { [name: string]: string } = { + "llama3.1-8b": "llama-3.1-8b-instruct", + "llama3.1-70b": "llama-3.1-70b-instruct", + "mistral-nemo": "mistral-nemo-instruct-2407", + "qwen2.5-coder-32b": "qwen2.5-coder-32b-instruct", + "pixtral": "pixtral-12b-2409", + }; + + protected _convertModelName(model: string) { + return Scaleway.MODEL_IDS[model] || this.model; + } +} + +export default Scaleway; diff --git a/core/llm/llms/SiliconFlow.ts b/core/llm/llms/SiliconFlow.ts index 86804cb45..6f522f920 100644 --- a/core/llm/llms/SiliconFlow.ts +++ b/core/llm/llms/SiliconFlow.ts @@ -1,11 +1,11 @@ -import { CompletionOptions, LLMOptions, ModelProvider } from "../../index.js"; +import { CompletionOptions, LLMOptions } from "../../index.js"; import { streamSse } from "../stream.js"; import { osModelsEditPrompt } from "../templates/edit.js"; import OpenAI from "./OpenAI.js"; class SiliconFlow extends OpenAI { - static providerName: ModelProvider = "siliconflow"; + static providerName = "siliconflow"; static defaultOptions: Partial = { apiBase: "https://api.siliconflow.cn/v1/", model: "Qwen/Qwen2.5-Coder-32B-Instruct", @@ -46,13 +46,12 @@ class SiliconFlow extends OpenAI { Accept: "application/json", Authorization: `Bearer ${this.apiKey}`, }, - signal + signal, }); for await (const chunk of streamSse(resp)) { yield chunk.choices[0].text; } } - } export default SiliconFlow; diff --git a/core/llm/llms/Test.ts b/core/llm/llms/Test.ts index b35984f3e..202046cc6 100644 --- a/core/llm/llms/Test.ts +++ b/core/llm/llms/Test.ts @@ -1,17 +1,22 @@ -import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js"; +import { ChatMessage, CompletionOptions } from "../../index.js"; import { BaseLLM } from "../index.js"; -const RESPONSES: Record = { - "How are you?": "I'm fine", -}; - const HARDCODED_CHAT_RESPONSE = "THIS IS A HARDCODED RESPONSE"; class TestLLM extends BaseLLM { - static providerName: ModelProvider = "test"; + static providerName = "test"; private findResponse(prompt: string) { - return Object.entries(RESPONSES).find(([key]) => prompt.includes(key))?.[1]; + // Matches TEST_USER_MESSAGE_ followed by digits, preceded and followed by non-digit characters + const matches = Array.from( + prompt.matchAll(/[^0-9]*TEST_USER_MESSAGE_(\d+)[^0-9]*/g), + ); + if (matches.length > 0) { + const lastMatch = matches[matches.length - 1]; + const number = lastMatch[1]; + return `TEST_LLM_RESPONSE_${number}`; + } + return undefined; } protected async *_streamComplete( diff --git a/core/llm/llms/TextGenWebUI.ts b/core/llm/llms/TextGenWebUI.ts index 8aa701286..ff2f26343 100644 --- a/core/llm/llms/TextGenWebUI.ts +++ b/core/llm/llms/TextGenWebUI.ts @@ -1,9 +1,9 @@ -import { LLMOptions, ModelProvider } from "../../index.js"; +import { LLMOptions } from "../../index.js"; import OpenAI from "./OpenAI.js"; class TextGenWebUI extends OpenAI { - static providerName: ModelProvider = "text-gen-webui"; + static providerName = "text-gen-webui"; static defaultOptions: Partial = { apiBase: "http://localhost:5000/v1/", }; diff --git a/core/llm/llms/Together.ts b/core/llm/llms/Together.ts index b0044c4a8..eaa7a2255 100644 --- a/core/llm/llms/Together.ts +++ b/core/llm/llms/Together.ts @@ -1,14 +1,9 @@ import OpenAI from "./OpenAI.js"; -import type { - CompletionOptions, - LLMOptions, - ModelProvider, -} from "../../index.js"; - +import type { CompletionOptions, LLMOptions } from "../../index.js"; class Together extends OpenAI { - static providerName: ModelProvider = "together"; + static providerName = "together"; static defaultOptions: Partial = { apiBase: "https://api.together.xyz/v1/", }; @@ -44,7 +39,11 @@ class Together extends OpenAI { signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { - for await (const chunk of this._legacystreamComplete(prompt,signal, options)) { + for await (const chunk of this._legacystreamComplete( + prompt, + signal, + options, + )) { yield chunk; } } diff --git a/core/indexing/embeddings/TransformersJsEmbeddingsProvider.ts b/core/llm/llms/TransformersJsEmbeddingsProvider.ts similarity index 85% rename from core/indexing/embeddings/TransformersJsEmbeddingsProvider.ts rename to core/llm/llms/TransformersJsEmbeddingsProvider.ts index f0d1ea0c4..206d534d3 100644 --- a/core/indexing/embeddings/TransformersJsEmbeddingsProvider.ts +++ b/core/llm/llms/TransformersJsEmbeddingsProvider.ts @@ -1,12 +1,11 @@ import path from "path"; -import { EmbeddingsProviderName } from "../../index.js"; +import { LLMOptions } from "../../index.js"; +import { BaseLLM } from "../../llm/index.js"; // @ts-ignore // prettier-ignore import { type PipelineType } from "../../vendor/modules/@xenova/transformers/src/transformers.js"; -import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js"; - class EmbeddingsPipeline { static task: PipelineType = "feature-extraction"; static model = "all-MiniLM-L6-v2"; @@ -39,16 +38,18 @@ class EmbeddingsPipeline { } } -export class TransformersJsEmbeddingsProvider extends BaseEmbeddingsProvider { - static providerName: EmbeddingsProviderName = "transformers.js"; +export class TransformersJsEmbeddingsProvider extends BaseLLM { + static providerName = "transformers.js"; static maxGroupSize: number = 1; static model: string = "all-MiniLM-L6-v2"; static mockVector: number[] = Array.from({ length: 384 }).fill(2) as number[]; + static defaultOptions: Partial | undefined = { + model: TransformersJsEmbeddingsProvider.model, + }; + constructor() { - super({ model: TransformersJsEmbeddingsProvider.model }, () => - Promise.resolve(null), - ); + super({ model: TransformersJsEmbeddingsProvider.model }); } async embed(chunks: string[]) { diff --git a/core/indexing/embeddings/TransformersJsWorkerThread.js b/core/llm/llms/TransformersJsWorkerThread.js similarity index 96% rename from core/indexing/embeddings/TransformersJsWorkerThread.js rename to core/llm/llms/TransformersJsWorkerThread.js index f53708664..6ea26172e 100644 --- a/core/indexing/embeddings/TransformersJsWorkerThread.js +++ b/core/llm/llms/TransformersJsWorkerThread.js @@ -1,10 +1,12 @@ import path from "node:path"; +import { parentPort } from "node:worker_threads"; + import { env, pipeline, } from "../../vendor/node_modules/@xenova/transformers/types/transformers"; + import TransformersJsEmbeddingsProvider from "./TransformersJsEmbeddingsProvider"; -const { parentPort } = require("node:worker_threads"); env.allowLocalModels = true; env.allowRemoteModels = false; diff --git a/core/llm/llms/VertexAI.ts b/core/llm/llms/VertexAI.ts index c9254eacc..43aa4d6ac 100644 --- a/core/llm/llms/VertexAI.ts +++ b/core/llm/llms/VertexAI.ts @@ -1,11 +1,6 @@ import { GoogleAuth } from "google-auth-library"; -import { - ChatMessage, - CompletionOptions, - LLMOptions, - ModelProvider, -} from "../../index.js"; +import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamResponse, streamSse } from "../stream.js"; @@ -14,12 +9,17 @@ import Anthropic from "./Anthropic.js"; import Gemini from "./Gemini.js"; class VertexAI extends BaseLLM { - static providerName: ModelProvider = "vertexai"; + static providerName = "vertexai"; declare apiBase: string; declare vertexProvider: string; declare anthropicInstance: Anthropic; declare geminiInstance: Gemini; + static defaultOptions: Partial | undefined = { + maxEmbeddingBatchSize: 5, + region: "us-central1", + }; + private clientPromise = new GoogleAuth({ scopes: "https://www.googleapis.com/auth/cloud-platform", }).getClient(); @@ -434,6 +434,39 @@ class VertexAI extends BaseLLM { supportsFim(): boolean { return ["code-gecko", "codestral-latest"].includes(this.model); } + + protected async _embed(chunks: string[]): Promise { + const client = await this.clientPromise; + const { token } = await client.getAccessToken(); + if (!token) { + throw new Error( + "Could not get an access token. Set up your Google Application Default Credentials.", + ); + } + + const resp = await this.fetch( + new URL(this.apiBase + `/publishers/google/models/${this.model}:predict`), + { + method: "POST", + body: JSON.stringify({ + instances: chunks.map((chunk) => ({ content: chunk })), + }), + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${token}`, + }, + }, + ); + + if (!resp.ok) { + throw new Error(await resp.text()); + } + + const data = (await resp.json()) as any; + return data.predictions.map( + (prediction: any) => prediction.embeddings.values, + ); + } } async function delay(seconds: number) { diff --git a/core/llm/llms/Vllm.ts b/core/llm/llms/Vllm.ts index 8877fed27..c9308d771 100644 --- a/core/llm/llms/Vllm.ts +++ b/core/llm/llms/Vllm.ts @@ -1,9 +1,9 @@ -import { LLMOptions, ModelProvider } from "../../index.js"; +import { LLMOptions } from "../../index.js"; import OpenAI from "./OpenAI.js"; class Vllm extends OpenAI { - static providerName: ModelProvider = "vllm"; + static providerName = "vllm"; constructor(options: LLMOptions) { super(options); this._setupCompletionOptions(); diff --git a/core/context/rerankers/voyage.ts b/core/llm/llms/Voyage.ts similarity index 63% rename from core/context/rerankers/voyage.ts rename to core/llm/llms/Voyage.ts index f7c6fb8a4..27db04e17 100644 --- a/core/context/rerankers/voyage.ts +++ b/core/llm/llms/Voyage.ts @@ -1,21 +1,13 @@ -import fetch from "node-fetch"; +import { Chunk, LLMOptions } from "../../index.js"; -import { Chunk, Reranker } from "../../index.js"; +import OpenAI from "./OpenAI.js"; -export class VoyageReranker implements Reranker { - name = "voyage"; - - constructor( - private readonly params: { - apiKey: string; - model?: string; - apiBase?: string; - }, - ) {} - - private get apiBase() { - return this.params.apiBase ?? "https://api.voyageai.com/v1/"; - } +class Voyage extends OpenAI { + static providerName = "voyage"; + static defaultOptions: Partial | undefined = { + apiBase: "https://api.voyageai.com/v1/", + maxEmbeddingBatchSize: 128, + }; async rerank(query: string, chunks: Chunk[]): Promise { if (!query || chunks.length === 0) { @@ -26,12 +18,12 @@ export class VoyageReranker implements Reranker { method: "POST", headers: { "Content-Type": "application/json", - Authorization: `Bearer ${this.params.apiKey}`, + Authorization: `Bearer ${this.apiKey}`, }, body: JSON.stringify({ query, documents: chunks.map((chunk) => chunk.content), - model: this.params.model ?? "rerank-2", + model: this.model ?? "rerank-2", }), }); @@ -48,3 +40,5 @@ export class VoyageReranker implements Reranker { return results.map((result) => result.relevance_score); } } + +export default Voyage; diff --git a/core/llm/llms/WatsonX.ts b/core/llm/llms/WatsonX.ts index fb82dacf9..bbc967519 100644 --- a/core/llm/llms/WatsonX.ts +++ b/core/llm/llms/WatsonX.ts @@ -1,9 +1,4 @@ -import { - ChatMessage, - CompletionOptions, - LLMOptions, - ModelProvider, -} from "../../index.js"; +import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; @@ -14,6 +9,10 @@ let watsonxToken = { }; class WatsonX extends BaseLLM { + static defaultOptions: Partial | undefined = { + maxEmbeddingBatchSize: 1000, + }; + constructor(options: LLMOptions) { super(options); } @@ -84,7 +83,7 @@ class WatsonX extends BaseLLM { : `${this.apiBase}/ml/v1/text/generation_stream?version=${this.apiVersion}`; } - static providerName: ModelProvider = "watsonx"; + static providerName = "watsonx"; protected _convertMessage(message: ChatMessage) { if (typeof message.content === "string") { @@ -265,6 +264,59 @@ class WatsonX extends BaseLLM { } } } + + protected async _embed(chunks: string[]): Promise { + var now = new Date().getTime() / 1000; + if ( + watsonxToken === undefined || + now > watsonxToken.expiration || + watsonxToken.token === undefined + ) { + watsonxToken = await this.getBearerToken(); + } else { + console.log( + `Reusing token (expires in ${ + (watsonxToken.expiration - now) / 60 + } mins)`, + ); + } + const payload: any = { + inputs: chunks, + parameters: { + truncate_input_tokens: 500, + return_options: { input_text: false }, + }, + model_id: this.model, + project_id: this.projectId, + }; + const headers = { + "Content-Type": "application/json", + Authorization: `${ + watsonxToken.expiration === -1 ? "ZenApiKey" : "Bearer" + } ${watsonxToken.token}`, + }; + const resp = await this.fetch( + new URL( + `${this.apiBase}/ml/v1/text/embeddings?version=${this.apiVersion}`, + ), + { + method: "POST", + body: JSON.stringify(payload), + headers: headers, + }, + ); + + if (!resp.ok) { + throw new Error(`Failed to embed chunk: ${await resp.text()}`); + } + const data = await resp.json(); + const embeddings = data.results; + + if (!embeddings || embeddings.length === 0) { + throw new Error("Watsonx generated empty embedding"); + } + return embeddings.map((e: any) => e.embedding); + } } export default WatsonX; diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index 9604cb9f6..19855fc12 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -42,6 +42,7 @@ import OpenRouter from "./OpenRouter"; import Replicate from "./Replicate"; import SageMaker from "./SageMaker"; import SambaNova from "./SambaNova"; +import Scaleway from "./Scaleway"; import ContinueProxy from "./stubs/ContinueProxy"; import TextGenWebUI from "./TextGenWebUI"; import Together from "./Together"; diff --git a/core/context/rerankers/llm.ts b/core/llm/llms/llm.ts similarity index 85% rename from core/context/rerankers/llm.ts rename to core/llm/llms/llm.ts index a673f5dc4..4cd433232 100644 --- a/core/context/rerankers/llm.ts +++ b/core/llm/llms/llm.ts @@ -1,5 +1,6 @@ -import { Chunk, ILLM, Reranker } from "../../index.js"; +import { Chunk } from "../../index.js"; import { getBasename } from "../../util/index.js"; +import { BaseLLM } from "../index.js"; const RERANK_PROMPT = ( query: string, @@ -41,22 +42,20 @@ const RERANK_PROMPT = ( Relevant: `; -export class LLMReranker implements Reranker { - name = "llmReranker"; - - constructor(private readonly llm: ILLM) {} +export class LLMReranker extends BaseLLM { + static providerName = "llmReranker"; async scoreChunk(chunk: Chunk, query: string): Promise { - const completion = await this.llm.complete( + const completion = await this.complete( RERANK_PROMPT(query, getBasename(chunk.filepath), chunk.content), new AbortController().signal, { maxTokens: 1, model: - this.llm.providerName.startsWith("openai") && - this.llm.model.startsWith("gpt-4") + this.providerName.startsWith("openai") && + this.model.startsWith("gpt-4") ? "gpt-3.5-turbo" - : this.llm.model, + : this.model, }, ); diff --git a/core/llm/llms/stubs/ContinueProxy.ts b/core/llm/llms/stubs/ContinueProxy.ts index 97dec3a35..c037ebd61 100644 --- a/core/llm/llms/stubs/ContinueProxy.ts +++ b/core/llm/llms/stubs/ContinueProxy.ts @@ -2,7 +2,7 @@ import { ControlPlaneProxyInfo } from "../../../control-plane/analytics/IAnalyti import { Telemetry } from "../../../util/posthog.js"; import OpenAI from "../OpenAI.js"; -import type { LLMOptions, ModelProvider } from "../../../index.js"; +import type { Chunk, LLMOptions } from "../../../index.js"; class ContinueProxy extends OpenAI { set controlPlaneProxyInfo(value: ControlPlaneProxyInfo) { @@ -10,7 +10,7 @@ class ContinueProxy extends OpenAI { this.apiBase = new URL("openai/v1/", value.controlPlaneProxyUrl).toString(); } - static providerName: ModelProvider = "continue-proxy"; + static providerName = "continue-proxy"; static defaultOptions: Partial = { useLegacyCompletionsEndpoint: false, }; @@ -28,6 +28,25 @@ class ContinueProxy extends OpenAI { supportsFim(): boolean { return true; } + + async rerank(query: string, chunks: Chunk[]): Promise { + const url = new URL("rerank", this.apiBase); + const resp = await fetch(url, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${this.apiKey}`, + }, + body: JSON.stringify({ + query, + documents: chunks.map((chunk) => chunk.content), + model: this.model, + }), + }); + const data: any = await resp.json(); + const results = data.data.sort((a: any, b: any) => a.index - b.index); + return results.map((result: any) => result.relevance_score); + } } export default ContinueProxy; diff --git a/core/llm/llms/xAI.ts b/core/llm/llms/xAI.ts index aa33ee70d..a6b29f01a 100644 --- a/core/llm/llms/xAI.ts +++ b/core/llm/llms/xAI.ts @@ -1,9 +1,9 @@ -import { LLMOptions, ModelProvider } from "../../index.js"; +import { LLMOptions } from "../../index.js"; import OpenAI from "./OpenAI.js"; class xAI extends OpenAI { - static providerName: ModelProvider = "xAI"; + static providerName = "xAI"; static defaultOptions: Partial = { apiBase: "https://api.x.ai/v1/", }; diff --git a/core/llm/openaiTypeConverters.ts b/core/llm/openaiTypeConverters.ts new file mode 100644 index 000000000..eaf4b0077 --- /dev/null +++ b/core/llm/openaiTypeConverters.ts @@ -0,0 +1,174 @@ +import { + ChatCompletion, + ChatCompletionChunk, + ChatCompletionCreateParams, + ChatCompletionMessageParam, + CompletionCreateParams, +} from "openai/resources/index"; + +import { FimCreateParamsStreaming } from "@continuedev/openai-adapters/dist/apis/base"; +import { ChatMessage, CompletionOptions } from ".."; + +export function toChatMessage( + message: ChatMessage, +): ChatCompletionMessageParam { + if (message.role === "tool") { + return { + role: "tool", + content: message.content, + tool_call_id: message.toolCallId, + }; + } + + if (typeof message.content === "string") { + return { + role: message.role, + content: message.content, + }; + } else if (!message.content.some((item) => item.type !== "text")) { + // If no multi-media is in the message, just send as text + // for compatibility with OpenAI-"compatible" servers + // that don't support multi-media format + return { + ...message, + content: message.content.map((item) => item.text).join(""), + }; + } + + const parts = message.content.map((part) => { + const msg: any = { + type: part.type, + text: part.text, + }; + if (part.type === "imageUrl") { + msg.image_url = { ...part.imageUrl, detail: "auto" }; + msg.type = "image_url"; + } + return msg; + }); + + return { + ...message, + content: parts, + }; +} + +export function toChatBody( + messages: ChatMessage[], + options: CompletionOptions, +): ChatCompletionCreateParams { + const tools = options.tools?.map((tool) => ({ + type: tool.type, + function: { + name: tool.function.name, + description: tool.function.description, + parameters: tool.function.parameters, + strict: tool.function.strict, + }, + })); + + return { + messages: messages.map(toChatMessage), + model: options.model, + max_tokens: options.maxTokens, + temperature: options.temperature, + top_p: options.topP, + frequency_penalty: options.frequencyPenalty, + presence_penalty: options.presencePenalty, + stream: options.stream ?? true, + stop: options.stop, + tools, + prediction: options.prediction, + }; +} + +export function toCompleteBody( + prompt: string, + options: CompletionOptions, +): CompletionCreateParams { + return { + prompt, + model: options.model, + max_tokens: options.maxTokens, + temperature: options.temperature, + top_p: options.topP, + frequency_penalty: options.frequencyPenalty, + presence_penalty: options.presencePenalty, + stream: options.stream ?? true, + stop: options.stop, + }; +} + +export function toFimBody( + prefix: string, + suffix: string, + options: CompletionOptions, +): FimCreateParamsStreaming { + return { + model: options.model, + prompt: prefix, + suffix, + max_tokens: options.maxTokens, + temperature: options.temperature, + top_p: options.topP, + frequency_penalty: options.frequencyPenalty, + presence_penalty: options.presencePenalty, + stop: options.stop, + stream: true, + } as any; +} + +export function fromChatResponse(response: ChatCompletion): ChatMessage { + const message = response.choices[0].message; + const toolCall = message.tool_calls?.[0]; + if (toolCall) { + return { + role: "assistant", + content: "", + toolCalls: message.tool_calls, + }; + } + + return { + role: "assistant", + content: message.content ?? "", + }; +} + +export function fromChatCompletionChunk( + chunk: ChatCompletionChunk, +): ChatMessage | undefined { + const delta = chunk.choices?.[0]?.delta; + + if (delta?.content) { + return { + role: "assistant", + content: delta.content, + }; + } else if (delta?.tool_calls) { + return { + role: "assistant", + content: "", + toolCalls: delta?.tool_calls.map((tool_call: any) => ({ + id: tool_call.id, + type: tool_call.type, + function: { + name: tool_call.function.name, + arguments: tool_call.function.arguments, + }, + })), + }; + } + + return undefined; +} + +export type LlmApiRequestType = + | "chat" + | "streamChat" + | "complete" + | "streamComplete" + | "streamFim" + | "embed" + | "rerank" + | "list"; diff --git a/core/llm/templates/chat.test.ts b/core/llm/templates/chat.test.ts new file mode 100644 index 000000000..fbe84c40f --- /dev/null +++ b/core/llm/templates/chat.test.ts @@ -0,0 +1,302 @@ +// Generated by continue +import { ChatMessage } from "../../index"; + +import { + anthropicTemplateMessages, + chatmlTemplateMessages, + codeLlama70bTemplateMessages, + deepseekTemplateMessages, + gemmaTemplateMessage, + graniteTemplateMessages, + llama2TemplateMessages, + llama3TemplateMessages, + llavaTemplateMessages, + neuralChatTemplateMessages, + openchatTemplateMessages, + phi2TemplateMessages, + phindTemplateMessages, + templateAlpacaMessages, + xWinCoderTemplateMessages, + zephyrTemplateMessages, +} from "./chat.js"; + +describe.skip("Chat Templates", () => { + describe("llama2TemplateMessages", () => { + it("should generate the correct prompt with system message and user messages", () => { + const messages: ChatMessage[] = [ + { role: "system", content: "You are a helpful assistant." }, + { role: "user", content: "Hello" }, + { role: "assistant", content: "Hi there!" }, + { role: "user", content: "How are you?" }, + ]; + const prompt = llama2TemplateMessages(messages); + const expectedPrompt = `[INST] <> + You are a helpful assistant. + <> + + Hello [/INST]Hi there![INST] How are you? [/INST]`; + expect(prompt).toBe(expectedPrompt); + }); + + it("should generate the correct prompt without system message", () => { + const messages: ChatMessage[] = [ + { role: "user", content: "Tell me a joke." }, + ]; + const prompt = llama2TemplateMessages(messages); + const expectedPrompt = `[INST] Tell me a joke. [/INST]`; + expect(prompt).toBe(expectedPrompt); + }); + + it("should skip initial assistant messages", () => { + const messages: ChatMessage[] = [ + { role: "assistant", content: "Initial assistant message." }, + { role: "user", content: "What is the time?" }, + ]; + const prompt = llama2TemplateMessages(messages); + const expectedPrompt = `[INST] What is the time? [/INST]`; + expect(prompt).toBe(expectedPrompt); + }); + + it("should handle empty messages", () => { + const messages: ChatMessage[] = []; + const prompt = llama2TemplateMessages(messages); + expect(prompt).toBe(""); + }); + + it("should handle messages with empty system message", () => { + const messages: ChatMessage[] = [ + { role: "system", content: "" }, + { role: "user", content: "Hello" }, + ]; + const prompt = llama2TemplateMessages(messages); + const expectedPrompt = `[INST] Hello [/INST]`; + expect(prompt).toBe(expectedPrompt); + }); + }); + + describe("anthropicTemplateMessages", () => { + it("should generate the correct prompt with user and assistant messages", () => { + const messages: ChatMessage[] = [ + { role: "user", content: "Hello" }, + { role: "assistant", content: "Hi there!" }, + { role: "user", content: "How are you?" }, + ]; + const prompt = anthropicTemplateMessages(messages); + const expectedPrompt = + "\n\nHuman: Hello \n\nAssistant: Hi there! \n\nHuman: How are you? \n\nAssistant:"; + expect(prompt).toBe(expectedPrompt); + }); + + it("should start with 'Hello.' if first message is not from user or system", () => { + const messages: ChatMessage[] = [ + { role: "assistant", content: "I am an assistant." }, + { role: "user", content: "Tell me a joke." }, + ]; + const prompt = anthropicTemplateMessages(messages); + const expectedPrompt = + "\n\nHuman: Hello.\n\nAssistant: I am an assistant. \n\nHuman: Tell me a joke. \n\nAssistant:"; + expect(prompt).toBe(expectedPrompt); + }); + + it("should handle empty messages", () => { + const messages: ChatMessage[] = []; + const prompt = anthropicTemplateMessages(messages); + const expectedPrompt = "\n\nHuman: Hello.\n\nAssistant:"; + expect(prompt).toBe(expectedPrompt); + }); + }); + + describe("llavaTemplateMessages", () => { + it("should generate the correct prompt with user messages", () => { + const messages: ChatMessage[] = [ + { role: "user", content: "Describe this image." }, + ]; + const prompt = llavaTemplateMessages(messages); + const expectedPrompt = + "A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions.USER: Describe this image.ASSISTANT: "; + expect(prompt).toBe(expectedPrompt); + }); + }); + + describe("zephyrTemplateMessages", () => { + it("should generate the correct prompt with system and user messages", () => { + const messages: ChatMessage[] = [ + { role: "system", content: "System message." }, + { role: "user", content: "Hello" }, + ]; + const prompt = zephyrTemplateMessages(messages); + const expectedPrompt = + "<|system|>System message.\n<|user|>\nHello\n<|assistant|>\n"; + expect(prompt).toBe(expectedPrompt); + }); + + it("should handle empty system message", () => { + const messages: ChatMessage[] = [ + { role: "system", content: "" }, + { role: "user", content: "Hello" }, + ]; + const prompt = zephyrTemplateMessages(messages); + const expectedPrompt = + "<|system|> \n<|user|>\nHello\n<|assistant|>\n"; + expect(prompt).toBe(expectedPrompt); + }); + }); + + describe("chatmlTemplateMessages", () => { + it("should generate the correct prompt with system and user messages", () => { + const messages: ChatMessage[] = [ + { role: "system", content: "System prompt" }, + { role: "user", content: "Hello" }, + ]; + const prompt = chatmlTemplateMessages(messages); + const expectedPrompt = + "<|im_start|>system\nSystem prompt<|im_end|>\n<|im_start|>user\nHello<|im_end|>\n<|im_start|>assistant\n"; + expect(prompt).toBe(expectedPrompt); + }); + }); + + describe("templateAlpacaMessages", () => { + it("should generate the correct prompt with user message", () => { + const messages: ChatMessage[] = [ + { role: "user", content: "Explain recursion." }, + ]; + const prompt = templateAlpacaMessages(messages); + const expectedPrompt = + "Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nExplain recursion.\n\n### Response:\n"; + expect(prompt).toBe(expectedPrompt); + }); + }); + + describe("deepseekTemplateMessages", () => { + it("should generate the correct prompt with user and assistant messages", () => { + const messages: ChatMessage[] = [ + { role: "user", content: "What is polymorphism in OOP?" }, + { role: "assistant", content: "Explanation of polymorphism." }, + ]; + const prompt = deepseekTemplateMessages(messages); + const expectedPrompt = + "You are an AI programming assistant, utilizing the DeepSeek Coder model, developed by DeepSeek Company, and you only answer questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will refuse to answer.\n### Instruction:\nWhat is polymorphism in OOP?\n### Response:\nExplanation of polymorphism.<|EOT|>\n"; + expect(prompt).toBe(expectedPrompt); + }); + }); + + describe("phi2TemplateMessages", () => { + it("should generate the correct prompt with system and user messages", () => { + const messages: ChatMessage[] = [ + { role: "system", content: "System message." }, + { role: "user", content: "Tell me a story." }, + ]; + const prompt = phi2TemplateMessages(messages); + const expectedPrompt = + "\n\nInstruct: System message. \n\nInstruct: Tell me a story. \n\nOutput: "; + expect(prompt).toBe(expectedPrompt); + }); + }); + + describe("phindTemplateMessages", () => { + it("should generate the correct prompt with system and user messages", () => { + const messages: ChatMessage[] = [ + { role: "system", content: "System prompt" }, + { role: "user", content: "What's the weather?" }, + ]; + const prompt = phindTemplateMessages(messages); + const expectedPrompt = + "### System Prompt\nSystem prompt\n\n### User Message\nWhat's the weather?\n### Assistant\n"; + expect(prompt).toBe(expectedPrompt); + }); + }); + + describe("openchatTemplateMessages", () => { + it("should generate the correct prompt with user and assistant messages", () => { + const messages: ChatMessage[] = [ + { role: "user", content: "Hello" }, + { role: "assistant", content: "Hi!" }, + { role: "user", content: "How are you?" }, + ]; + const prompt = openchatTemplateMessages(messages); + const expectedPrompt = + "GPT4 Correct User: Hello<|end_of_turn|>GPT4 Correct Assistant: Hi!<|end_of_turn|>GPT4 Correct User: How are you?<|end_of_turn|>GPT4 Correct Assistant:"; + expect(prompt).toBe(expectedPrompt); + }); + }); + + describe("xWinCoderTemplateMessages", () => { + it("should generate the correct prompt with system and user messages", () => { + const messages: ChatMessage[] = [ + { role: "system", content: "System prompt" }, + { role: "user", content: "Explain closures in JavaScript." }, + ]; + const prompt = xWinCoderTemplateMessages(messages); + const expectedPrompt = + ": System prompt: Explain closures in JavaScript.: "; + expect(prompt).toBe(expectedPrompt); + }); + }); + + describe("codeLlama70bTemplateMessages", () => { + it("should generate the correct prompt with multiple messages", () => { + const messages: ChatMessage[] = [ + { role: "system", content: "System prompt" }, + { role: "user", content: "First user query" }, + { role: "assistant", content: "Model response to first query" }, + { role: "user", content: "Second user query" }, + ]; + const prompt = codeLlama70bTemplateMessages(messages); + const expectedPrompt = + "Source: system\n\n System prompt Source: user\n\n First user query Source: assistant\n\n Model response to first query Source: user\n\n Second user query Source: assistant\nDestination: user\n\n"; + expect(prompt).toBe(prompt); // Since the function returns prompt + }); + }); + + describe("llama3TemplateMessages", () => { + it("should generate the correct prompt with messages", () => { + const messages: ChatMessage[] = [ + { role: "system", content: "System prompt" }, + { role: "user", content: "Tell me about AI." }, + ]; + const prompt = llama3TemplateMessages(messages); + const expectedPrompt = + "<|begin_of_text|><|start_header_id|>system<|end_header_id|>\nSystem prompt<|eot_id|>\n<|start_header_id|>user<|end_header_id|>\nTell me about AI.<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n"; + expect(prompt).toBe(expectedPrompt); + }); + }); + + describe("gemmaTemplateMessage", () => { + it("should generate the correct prompt with messages", () => { + const messages: ChatMessage[] = [ + { role: "user", content: "How do I reverse a string in Python?" }, + ]; + const prompt = gemmaTemplateMessage(messages); + const expectedPrompt = + "user\nHow do I reverse a string in Python?\nmodel\n"; + expect(prompt).toBe(expectedPrompt); + }); + }); + + describe("graniteTemplateMessages", () => { + it("should generate the correct prompt with system, user, and assistant messages", () => { + const messages: ChatMessage[] = [ + { role: "system", content: "System prompt" }, + { role: "user", content: "What's the capital of France?" }, + { role: "assistant", content: "Paris is the capital of France." }, + ]; + const prompt = graniteTemplateMessages(messages); + const expectedPrompt = + "\n\nSystem:\n System prompt\n\nQuestion:\nWhat's the capital of France?\n\nAnswer:\nParis is the capital of France.\n\n"; + expect(prompt).toBe(expectedPrompt); + }); + }); + + describe("neuralChatTemplateMessages", () => { + it("should generate the correct prompt with system and user messages", () => { + const messages: ChatMessage[] = [ + { role: "system", content: "You are a helpful assistant." }, + { role: "user", content: "Tell me a joke." }, + ]; + const prompt = neuralChatTemplateMessages(messages); + const expectedPrompt = + "### System:\nYou are a helpful assistant.\n### User:\nTell me a joke.\n### Assistant:\n"; + expect(prompt).toBe(expectedPrompt); + }); + }); +}); diff --git a/core/llm/templates/options.ts b/core/llm/templates/options.ts deleted file mode 100644 index 614cca52a..000000000 --- a/core/llm/templates/options.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { CompletionOptions, ModelName } from "../../index.js"; - -const CompletionOptionsForModels: { - [key in ModelName]?: Partial; -} = { - "codellama-70b": { - stop: ["Source: assistant"], - }, -}; - -export default CompletionOptionsForModels; diff --git a/core/package-lock.json b/core/package-lock.json index 41aeca5cb..68805e36f 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -13,7 +13,9 @@ "@aws-sdk/client-sagemaker-runtime": "^3.621.0", "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.13", + "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", + "@continuedev/openai-adapters": "^1.0.10", "@modelcontextprotocol/sdk": "^1.0.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", @@ -46,7 +48,7 @@ "node-html-markdown": "^1.3.0", "ollama": "^0.4.6", "onnxruntime-node": "1.14.0", - "openai": "^4.20.1", + "openai": "^4.76.0", "p-limit": "^6.1.0", "partial-json": "^0.1.7", "pg": "^8.11.3", @@ -1231,6 +1233,22 @@ } } }, + "node_modules/@azure-rest/core-client": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@azure-rest/core-client/-/core-client-1.4.0.tgz", + "integrity": "sha512-ozTDPBVUDR5eOnMIwhggbnVmOrka4fXCs8n8mvUo4WLLc38kki6bAOByDoVZZPz/pZy2jMt2kwfpvy/UjALj6w==", + "dependencies": { + "@azure/abort-controller": "^2.0.0", + "@azure/core-auth": "^1.3.0", + "@azure/core-rest-pipeline": "^1.5.0", + "@azure/core-tracing": "^1.0.1", + "@azure/core-util": "^1.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, "node_modules/@azure/abort-controller": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/@azure/abort-controller/-/abort-controller-2.1.2.tgz", @@ -1328,6 +1346,17 @@ "node": ">=18.0.0" } }, + "node_modules/@azure/core-sse": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/@azure/core-sse/-/core-sse-2.1.3.tgz", + "integrity": "sha512-KSSdIKy8kvWCpYr8Hzpu22j3wcXsVTYE0IlgmI1T/aHvBDsLgV91y90UTfVWnuiuApRLCCVC4gS09ApBGOmYQA==", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, "node_modules/@azure/core-tracing": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/@azure/core-tracing/-/core-tracing-1.2.0.tgz", @@ -1466,6 +1495,23 @@ "uuid": "dist/bin/uuid" } }, + "node_modules/@azure/openai": { + "version": "1.0.0-beta.13", + "resolved": "https://registry.npmjs.org/@azure/openai/-/openai-1.0.0-beta.13.tgz", + "integrity": "sha512-oHE5ScnPTXALmyEBgqokZlYVT7F76EfrKjMWF+YcFJdUxk9Adhvht2iL5v+QpmlAIMdkih1q8DkTs/tApDjBpw==", + "dependencies": { + "@azure-rest/core-client": "^1.1.7", + "@azure/core-auth": "^1.4.0", + "@azure/core-rest-pipeline": "^1.13.0", + "@azure/core-sse": "^2.0.0", + "@azure/core-util": "^1.4.0", + "@azure/logger": "^1.0.3", + "tslib": "^2.4.0" + }, + "engines": { + "node": ">=18.0.0" + } + }, "node_modules/@babel/code-frame": { "version": "7.24.7", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.24.7.tgz", @@ -3378,11 +3424,36 @@ "zod": "^3.23.8" } }, + "node_modules/@continuedev/fetch": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.4.tgz", + "integrity": "sha512-lFLMQMdyo3y5ZpgAxTtOLj3lvhQAQUoI96SPCXjdV6NQp2gF/XmmIadCD+Hfx03Iz750Y5PF8jYdrGTMFxwlaQ==", + "dependencies": { + "@continuedev/config-types": "^1.0.5", + "follow-redirects": "^1.15.6", + "http-proxy-agent": "^7.0.2", + "https-proxy-agent": "^7.0.5", + "node-fetch": "^3.3.2" + } + }, "node_modules/@continuedev/llm-info": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/@continuedev/llm-info/-/llm-info-1.0.2.tgz", "integrity": "sha512-B5VFcZlwlwQg6htbIjCjj3z/pj3I929BzgWowiLzxYC40ag+v3e/hM9EDGWCEdNIT+PDMchAwS67iNB+WhE7qg==" }, + "node_modules/@continuedev/openai-adapters": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/@continuedev/openai-adapters/-/openai-adapters-1.0.10.tgz", + "integrity": "sha512-hTiCxlXsek/jpVbtHDQCe4JnCmJ+jbye9ionXCDmg9oAKKEymW1UVVrX08xcdCkfKnxAP2ESgqFSMok314q+fg==", + "dependencies": { + "@azure/openai": "^1.0.0-beta.12", + "@continuedev/config-types": "^1.0.5", + "@continuedev/fetch": "^1.0.3", + "node-fetch": "^3.3.2", + "openai": "^4.76.0", + "zod": "^3.23.8" + } + }, "node_modules/@esbuild/android-arm": { "version": "0.17.19", "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.17.19.tgz", @@ -12606,9 +12677,9 @@ } }, "node_modules/openai": { - "version": "4.47.1", - "resolved": "https://registry.npmjs.org/openai/-/openai-4.47.1.tgz", - "integrity": "sha512-WWSxhC/69ZhYWxH/OBsLEirIjUcfpQ5+ihkXKp06hmeYXgBBIUCa9IptMzYx6NdkiOCsSGYCnTIsxaic3AjRCQ==", + "version": "4.76.0", + "resolved": "https://registry.npmjs.org/openai/-/openai-4.76.0.tgz", + "integrity": "sha512-QBGIetjX1C9xDp5XGa/3mPnfKI9BgAe2xHQX6PmO98wuW9qQaurBaumcYptQWc9LHZZq7cH/Y1Rjnsr6uUDdVw==", "dependencies": { "@types/node": "^18.11.18", "@types/node-fetch": "^2.6.4", @@ -12616,11 +12687,18 @@ "agentkeepalive": "^4.2.1", "form-data-encoder": "1.7.2", "formdata-node": "^4.3.2", - "node-fetch": "^2.6.7", - "web-streams-polyfill": "^3.2.1" + "node-fetch": "^2.6.7" }, "bin": { "openai": "bin/cli" + }, + "peerDependencies": { + "zod": "^3.23.8" + }, + "peerDependenciesMeta": { + "zod": { + "optional": true + } } }, "node_modules/openai/node_modules/@types/node": { diff --git a/core/package.json b/core/package.json index b02671dba..546530aef 100644 --- a/core/package.json +++ b/core/package.json @@ -45,7 +45,9 @@ "@aws-sdk/client-sagemaker-runtime": "^3.621.0", "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.13", + "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", + "@continuedev/openai-adapters": "^1.0.10", "@modelcontextprotocol/sdk": "^1.0.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", @@ -78,7 +80,7 @@ "node-html-markdown": "^1.3.0", "ollama": "^0.4.6", "onnxruntime-node": "1.14.0", - "openai": "^4.20.1", + "openai": "^4.76.0", "p-limit": "^6.1.0", "partial-json": "^0.1.7", "pg": "^8.11.3", diff --git a/core/util/messenger.ts b/core/protocol/messenger/index.ts similarity index 97% rename from core/util/messenger.ts rename to core/protocol/messenger/index.ts index ea7efebed..8b7245224 100644 --- a/core/util/messenger.ts +++ b/core/protocol/messenger/index.ts @@ -1,6 +1,6 @@ import { v4 as uuidv4 } from "uuid"; -import type { IProtocol } from "../protocol/index.js"; +import type { IProtocol } from "../index"; export interface Message { messageType: string; @@ -76,7 +76,9 @@ export class InProcessMessenger< messageId?: string, ): ToProtocol[T][1] { const listener = this.myTypeListeners.get(messageType); - if (!listener) {return;} + if (!listener) { + return; + } const msg: Message = { messageType: messageType as string, diff --git a/core/util/messageIde.ts b/core/protocol/messenger/messageIde.ts similarity index 97% rename from core/util/messageIde.ts rename to core/protocol/messenger/messageIde.ts index 4c2709f23..febdf559c 100644 --- a/core/util/messageIde.ts +++ b/core/protocol/messenger/messageIde.ts @@ -1,8 +1,5 @@ -import { - GetGhTokenArgs, - ToIdeFromWebviewOrCoreProtocol, -} from "../protocol/ide.js"; -import { FromIdeProtocol } from "../protocol/index.js"; +import { GetGhTokenArgs, ToIdeFromWebviewOrCoreProtocol } from "../ide"; +import { FromIdeProtocol } from ".."; import type { ContinueRcJson, @@ -16,7 +13,7 @@ import type { Range, RangeInFile, Thread, -} from "../index.js"; +} from "../.."; export class MessageIde implements IDE { constructor( diff --git a/core/util/reverseMessageIde.ts b/core/protocol/messenger/reverseMessageIde.ts similarity index 96% rename from core/util/reverseMessageIde.ts rename to core/protocol/messenger/reverseMessageIde.ts index 256251f94..46e6418c0 100644 --- a/core/util/reverseMessageIde.ts +++ b/core/protocol/messenger/reverseMessageIde.ts @@ -1,7 +1,7 @@ -import { IDE } from "../index.js"; -import { ToIdeFromWebviewOrCoreProtocol } from "../protocol/ide.js"; +import { IDE } from "../../index"; +import { ToIdeFromWebviewOrCoreProtocol } from "../ide"; -import { Message } from "./messenger.js"; +import { Message } from "."; export class ReverseMessageIde { private on( diff --git a/core/test/fixtures.ts b/core/test/fixtures.ts index add71d029..78ee60150 100644 --- a/core/test/fixtures.ts +++ b/core/test/fixtures.ts @@ -1,5 +1,6 @@ import { ConfigHandler } from "../config/ConfigHandler"; import { ControlPlaneClient } from "../control-plane/client"; +import Mock from "../llm/llms/Mock"; import FileSystemIde from "../util/filesystem"; import { TEST_DIR } from "./testDir"; @@ -18,3 +19,9 @@ export const testConfigHandler = new ConfigHandler( async (text) => {}, testControlPlaneClient, ); + +export const testLLM = new Mock({ + model: "mock-model", + title: "Mock LLM", + uniqueId: "not-unique", +}); diff --git a/core/jest.global-setup.ts b/core/test/jest.global-setup.ts similarity index 61% rename from core/jest.global-setup.ts rename to core/test/jest.global-setup.ts index 218e10baf..c1194e3d1 100644 --- a/core/jest.global-setup.ts +++ b/core/test/jest.global-setup.ts @@ -1,6 +1,8 @@ import fs from "fs"; import path from "path"; +// Sets up the GLOBAL directory for testing - equivalent to ~/.continue +// IMPORTANT: the CONTINUE_GLOBAL_DIR environment variable is used in utils/paths for getting all local paths export default async function () { process.env.CONTINUE_GLOBAL_DIR = path.join(__dirname, ".continue-test"); if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR)) { diff --git a/core/jest.setup-after-env.ts b/core/test/jest.setup-after-env.ts similarity index 94% rename from core/jest.setup-after-env.ts rename to core/test/jest.setup-after-env.ts index 53f94ecea..0d8d904fb 100644 --- a/core/jest.setup-after-env.ts +++ b/core/test/jest.setup-after-env.ts @@ -1,9 +1,10 @@ -import fs from "fs"; import { TextDecoder, TextEncoder } from "util"; import { jest } from "@jest/globals"; import fetch, { Request, Response } from "node-fetch"; +console.log("Process debug", process.env.DEBUG); + if (process.env.DEBUG === "jest") { jest.setTimeout(5 * 60 * 1000); } diff --git a/core/test/testDir.ts b/core/test/testDir.ts index 0eae7ad0b..7bc63105b 100644 --- a/core/test/testDir.ts +++ b/core/test/testDir.ts @@ -18,6 +18,12 @@ export function tearDownTestDir() { } } +/* + accepts array of items in 3 formats, e.g. + "index/" creates index directory + "index/index.ts" creates an empty index/index.ts + ["index/index.ts", "hello"] creates index/index.ts with contents "hello" +*/ export function addToTestDir(paths: (string | string[])[]) { for (const p of paths) { const filepath = path.join(TEST_DIR, Array.isArray(p) ? p[0] : p); diff --git a/core/tools/implementations/runTerminalCommand.ts b/core/tools/implementations/runTerminalCommand.ts index ddc8575c4..5a159b04a 100644 --- a/core/tools/implementations/runTerminalCommand.ts +++ b/core/tools/implementations/runTerminalCommand.ts @@ -1,6 +1,9 @@ +import childProcess from "node:child_process"; +import util from "node:util"; + import { ToolImpl } from "."; -const util = require("node:util"); -const asyncExec = util.promisify(require("node:child_process").exec); + +const asyncExec = util.promisify(childProcess.exec); export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { const ideInfo = await extras.ide.getIdeInfo(); diff --git a/core/util/GlobalContext.test.ts b/core/util/GlobalContext.test.ts new file mode 100644 index 000000000..6014a1d1d --- /dev/null +++ b/core/util/GlobalContext.test.ts @@ -0,0 +1,140 @@ +// core/util/GlobalContext.test.ts +import { GlobalContext, GlobalContextType } from "./GlobalContext"; +import fs from "node:fs"; +import path from "path"; +import { getGlobalContextFilePath } from "./paths"; + +describe("GlobalContext", () => { + let globalContext: GlobalContext; + const globalContextFilePath = getGlobalContextFilePath(); + + beforeEach(() => { + // Remove the global context file if it exists + if (fs.existsSync(globalContextFilePath)) { + fs.unlinkSync(globalContextFilePath); + } + globalContext = new GlobalContext(); + }); + + afterEach(() => { + // Clean up + if (fs.existsSync(globalContextFilePath)) { + fs.unlinkSync(globalContextFilePath); + } + }); + + it("should update and get a boolean value correctly", () => { + globalContext.update("indexingPaused", true); + const value = globalContext.get("indexingPaused"); + 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", { + [workspaceIdentifier]: "profile-1", + }); + + const value = globalContext.get("lastSelectedProfileForWorkspace"); + expect(value).toEqual({ "workspace-1": "profile-1" }); + }); + + it("should handle non-existent global context file gracefully on get", () => { + const value = globalContext.get("indexingPaused"); + expect(value).toBeUndefined(); + }); + + it("should handle non-existent global context file gracefully on update", () => { + globalContext.update("indexingPaused", true); + const value = globalContext.get("indexingPaused"); + expect(value).toBe(true); + }); + + it("should overwrite existing values", () => { + globalContext.update("indexingPaused", true); + expect(globalContext.get("indexingPaused")).toBe(true); + + globalContext.update("indexingPaused", false); + expect(globalContext.get("indexingPaused")).toBe(false); + }); + + it("should handle JSON parsing errors gracefully on get", () => { + // Write invalid JSON to the file + fs.writeFileSync(globalContextFilePath, "{ invalid json }"); + + const consoleWarnMock = jest + .spyOn(console, "warn") + .mockImplementation(() => {}); + + const value = globalContext.get("indexingPaused"); + expect(value).toBeUndefined(); + expect(consoleWarnMock).toHaveBeenCalledWith( + expect.stringContaining("Error parsing global context") + ); + + // Clean up + consoleWarnMock.mockRestore(); + }); + + it("should handle JSON parsing errors gracefully on update", () => { + // Write invalid JSON to the file + fs.writeFileSync(globalContextFilePath, "{ invalid json }"); + + const consoleWarnMock = jest + .spyOn(console, "warn") + .mockImplementation(() => {}); + + // Attempt to update + globalContext.update("indexingPaused", true); + + // The update should have been skipped due to JSON parsing error + // So attempting to get the value should return undefined + const value = globalContext.get("indexingPaused"); + expect(value).toBeUndefined(); + + expect(consoleWarnMock).toHaveBeenCalledWith( + expect.stringContaining("Error updating global context") + ); + + // Clean up + consoleWarnMock.mockRestore(); + }); + + 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 + ); + }); + + it("should handle updating hasAlreadyCreatedAPromptFile correctly", () => { + globalContext.update("hasAlreadyCreatedAPromptFile", true); + expect(globalContext.get("hasAlreadyCreatedAPromptFile")).toBe(true); + }); + + it("should handle curEmbeddingsProviderId correctly", () => { + globalContext.update("curEmbeddingsProviderId", "test-provider-id"); + expect(globalContext.get("curEmbeddingsProviderId")).toBe( + "test-provider-id" + ); + }); + + it("should not crash or throw when getting a key that hasn't been set", () => { + expect( + globalContext.get("hasAlreadyCreatedAPromptFile") + ).toBeUndefined(); + }); +}); \ No newline at end of file diff --git a/core/util/GlobalContext.ts b/core/util/GlobalContext.ts index 41daa8de2..1095234d8 100644 --- a/core/util/GlobalContext.ts +++ b/core/util/GlobalContext.ts @@ -1,7 +1,5 @@ import fs from "node:fs"; -import { EmbeddingsProvider } from "../"; - import { getGlobalContextFilePath } from "./paths"; export type GlobalContextType = { @@ -14,7 +12,7 @@ export type GlobalContextType = { * * For VS Code users, it is unnecessary since we use transformers.js by default. */ - curEmbeddingsProviderId: EmbeddingsProvider["id"]; + curEmbeddingsProviderId: string; hasDismissedConfigTsNoticeJetBrains: boolean; hasAlreadyCreatedAPromptFile: boolean; showConfigUpdateToast: boolean; diff --git a/core/util/LruCache.test.ts b/core/util/LruCache.test.ts new file mode 100644 index 000000000..8e34543ef --- /dev/null +++ b/core/util/LruCache.test.ts @@ -0,0 +1,64 @@ +import { PrecalculatedLruCache } from "./LruCache"; + +describe("PrecalculatedLruCache", () => { + const N = 2; + + let calculateValue: jest.MockedFunction<(key: string) => Promise>; + let cache: PrecalculatedLruCache; + + beforeEach(() => { + calculateValue = jest.fn(async (key: string) => { + return parseInt(key, 10) * 2; + }); + + cache = new PrecalculatedLruCache(calculateValue, N); + }); + + it("should calculate and cache values", async () => { + await cache.initKey("1"); + expect(calculateValue).toHaveBeenCalledWith("1"); + expect(cache.get("1")).toBe(2); + }); + + it("should not recalculate cached values", async () => { + await cache.initKey("1"); + calculateValue.mockClear(); + + await cache.initKey("1"); + expect(calculateValue).not.toHaveBeenCalled(); + expect(cache.get("1")).toBe(2); + }); + + it("should evict least recently used items when capacity is exceeded", async () => { + await cache.initKey("1"); + await cache.initKey("2"); + await cache.initKey("3"); // Exceeds capacity, should evict "1" + + expect(cache.get("1")).toBeUndefined(); + expect(cache.get("2")).toBe(4); + expect(cache.get("3")).toBe(6); + }); + + it("should update LRU order when keys are accessed", async () => { + await cache.initKey("1"); + await cache.initKey("2"); + + // Access "1" to make it most recently used + await cache.initKey("1"); + await cache.initKey("3"); // Exceeds capacity, should evict "2" + + expect(cache.get("1")).toBe(2); + expect(cache.get("2")).toBeUndefined(); + expect(cache.get("3")).toBe(6); + }); + + it("should handle get for keys not initialized", () => { + expect(cache.get("not-initialized")).toBeUndefined(); + }); + + it("should propagate errors from calculateValue", async () => { + calculateValue.mockRejectedValue(new Error("Calculation failed")); + await expect(cache.initKey("error")).rejects.toThrow("Calculation failed"); + expect(cache.get("error")).toBeUndefined(); + }); +}); diff --git a/core/util/chatDescriber.test.ts b/core/util/chatDescriber.test.ts new file mode 100644 index 000000000..0b9e4aaf4 --- /dev/null +++ b/core/util/chatDescriber.test.ts @@ -0,0 +1,91 @@ +import { ChatDescriber } from "./chatDescriber"; +import { testLLM } from "../test/fixtures"; +import { LLMFullCompletionOptions } from ".."; + +describe("ChatDescriber", () => { + beforeEach(() => { + // Reset the prompt to the initial value before each test + ChatDescriber.prompt = + "Given the following... please reply with a short summary that is 4-12 words in length, you should summarize what the user is asking for OR what the user is trying to accomplish. You should only respond with the summary, no additional text or explanation, you don't need ending punctuation.\n\n"; + }); + + afterEach(() => { + jest.restoreAllMocks(); + }); + + describe("describe method", () => { + it("should return undefined if ChatDescriber.prompt is undefined", async () => { + ChatDescriber.prompt = undefined; + + const result = await ChatDescriber.describe(testLLM, {}, "Test message"); + + expect(result).toBeUndefined(); + }); + + it("should return undefined if message is empty after cleaning", async () => { + const message = " "; + + const result = await ChatDescriber.describe(testLLM, {}, message); + + expect(result).toBeUndefined(); + }); + + it("should set completionOptions.maxTokens to 6", async () => { + const message = "Test message"; + const completionOptions: LLMFullCompletionOptions = { temperature: 0.7 }; + + testLLM.chat = jest.fn().mockResolvedValue({ content: "Test response" }); + + await ChatDescriber.describe(testLLM, completionOptions, message); + + expect(completionOptions.maxTokens).toBe(6); + }); + + it("should call model.chat with correct parameters", async () => { + const message = "Test message"; + const cleanedMessage = "Test message"; + const expectedPrompt = ChatDescriber.prompt + cleanedMessage; + const completionOptions: LLMFullCompletionOptions = {}; + + testLLM.chat = jest.fn().mockResolvedValue({ content: "Test response" }); + + await ChatDescriber.describe(testLLM, completionOptions, message); + + expect(testLLM.chat).toHaveBeenCalledWith( + [ + { + role: "user", + content: expectedPrompt, + }, + ], + expect.any(AbortSignal), + completionOptions, + ); + }); + + it("should return processed content from the model response", async () => { + const message = "Test message"; + const modelResponseContent = "Model response content"; + const expectedResult = "Model response content"; + + testLLM.chat = jest + .fn() + .mockResolvedValue({ content: modelResponseContent }); + + const result = await ChatDescriber.describe(testLLM, {}, message); + + expect(result).toBe(expectedResult); + }); + + it("should propagate error if model.chat throws an error", async () => { + const message = "Test message"; + const completionOptions: LLMFullCompletionOptions = {}; + + testLLM.chat = jest.fn().mockRejectedValue(new Error("Chat error")); + + await expect( + ChatDescriber.describe(testLLM, completionOptions, message), + ).rejects.toThrow("Chat error"); + }); + }); +}); diff --git a/core/util/chatDescriber.ts b/core/util/chatDescriber.ts index 70b7a27b7..e4fce3ecd 100644 --- a/core/util/chatDescriber.ts +++ b/core/util/chatDescriber.ts @@ -2,7 +2,7 @@ import { ILLM, LLMFullCompletionOptions } from ".."; import { removeQuotesAndEscapes, removeCodeBlocksAndTrim } from "."; -import type { IMessenger } from "./messenger"; +import type { IMessenger } from "../protocol/messenger"; import type { FromCoreProtocol, ToCoreProtocol } from "../protocol"; export class ChatDescriber { diff --git a/core/util/dedent.test.ts b/core/util/dedent.test.ts deleted file mode 100644 index 95908ab4a..000000000 --- a/core/util/dedent.test.ts +++ /dev/null @@ -1,155 +0,0 @@ -import { dedent } from "./index"; - -describe("dedent function", () => { - it("should remove common leading whitespace from all lines", () => { - const result = dedent` - Hello - World - ! - `; - expect(result).toBe("Hello\n World\n !"); - }); - - it("should handle strings with no indentation", () => { - const result = dedent`Hello -World -!`; - expect(result).toBe("Hello\nWorld\n!"); - }); - - it("should handle strings with mixed indentation", () => { - const result = dedent` - Hello - World - ! - `; - expect(result).toBe(" Hello\nWorld\n !"); - }); - - it("should remove leading and trailing empty lines", () => { - const result = dedent` - - Hello - World - - `; - expect(result).toBe("Hello\nWorld"); - }); - - it("should handle empty strings", () => { - const result = dedent``; - expect(result).toBe(""); - }); - - it("should handle strings with only whitespace", () => { - const result = dedent` - - `; - expect(result).toBe(""); - }); - - it.skip("should handle strings with tabs", () => { - const result = dedent` - \tHello - \t\tWorld - \t\t\t! -`; - expect(result).toBe("\tHello\n\t\tWorld\n\t\t\t!"); - }); - - it("should handle interpolated values", () => { - const world = "World"; - const result = dedent` - Hello ${world} - How are you? - `; - expect(result).toBe("Hello World\n How are you?"); - }); - - it("should handle multiple interpolated values", () => { - const greeting = "Hello"; - const name = "Alice"; - const question = "How are you?"; - const result = dedent` - ${greeting} ${name} - ${question} - `; - expect(result).toBe("Hello Alice\n How are you?"); - }); - - it("should handle interpolated values with different indentation", () => { - const value1 = "foo"; - const value2 = "bar"; - const result = dedent` - ${value1} - ${value2} - `; - expect(result).toBe("foo\n bar"); - }); - - it("should handle a single line with indentation", () => { - const result = dedent` Hello World!`; - expect(result).toBe("Hello World!"); - }); - - it("should handle a string with only one non-empty line", () => { - const result = dedent` - - Hello World! - - `; - expect(result).toBe("Hello World!"); - }); - - it("should handle a string with Unicode characters", () => { - const result = dedent` - こんにちは - 世界 - `; - expect(result).toBe("こんにちは\n 世界"); - }); - - it("should handle a string with emoji", () => { - const result = dedent` - 🌍 - 🌎 - 🌏 - `; - expect(result).toBe("🌍\n 🌎\n 🌏"); - }); - - it.skip("should handle a string with CRLF line endings", () => { - const result = dedent` - Hello\r - World\r - `; - expect(result).toBe("Hello\r\n World"); - }); - - it("should not count empty lines in the minimum indentation", () => { - const result = dedent` - Hello - - World - `; - - expect(result).toBe("Hello\n\nWorld"); - }); - - it("should work with templated strings", () => { - const language = "typescript"; - const code = "console.log('hello');\nconsole.log('world');"; - - const result = dedent` - This is the prefix of the file: - \`\`\`${language} - ${code} - \`\`\``; - - expect(result).toBe(`\ -This is the prefix of the file: -\`\`\`${language} -${code} -\`\`\``); - }); -}); diff --git a/core/util/extractMinimalStackTraceInfo.test.ts b/core/util/extractMinimalStackTraceInfo.test.ts new file mode 100644 index 000000000..f8c3a682a --- /dev/null +++ b/core/util/extractMinimalStackTraceInfo.test.ts @@ -0,0 +1,83 @@ +// Generated by continue + +import { extractMinimalStackTraceInfo } from "./extractMinimalStackTraceInfo"; + +describe("extractMinimalStackTraceInfo", () => { + it("should return an empty string when stack is not a string or an empty string", () => { + expect(extractMinimalStackTraceInfo(undefined)).toBe(""); + expect(extractMinimalStackTraceInfo(null)).toBe(""); + expect(extractMinimalStackTraceInfo(1234)).toBe(""); + expect(extractMinimalStackTraceInfo({})).toBe(""); + expect(extractMinimalStackTraceInfo([])).toBe(""); + expect(extractMinimalStackTraceInfo(true)).toBe(""); + expect(extractMinimalStackTraceInfo("")).toBe(""); + }); + + it("should extract minimal stack trace info from a valid stack trace", () => { + const stack = `Error: Something went wrong + at FunctionOne (/Users/user/project/file1.ts:10:15) + at FunctionTwo (/Users/user/project/file2.ts:20:25) + at FunctionThree (/Users/user/project/file3.ts:30:35) + at node_modules/some_module/index.js:40:45 + at FunctionFour (/Users/user/project/file4.ts:50:55) + at processTicksAndRejections (node:internal/process/task_queues:96:5) + `; + const expected = "FunctionOne, FunctionTwo, FunctionThree, FunctionFour"; + expect(extractMinimalStackTraceInfo(stack)).toBe(expected); + }); + + it("should return an empty string if no matching lines are found", () => { + const stack = `Error: Something went wrong + at node_modules/some_module/index.js:40:45 + at processTicksAndRejections (node:internal/process/task_queues:96:5) + `; + expect(extractMinimalStackTraceInfo(stack)).toBe(""); + }); + + it("should handle stack traces without 'at ' at the beginning of lines", () => { + const stack = `Error: Something went wrong + in FunctionOne (/Users/user/project/file1.ts:10:15) + in FunctionTwo (/Users/user/project/file2.ts:20:25) + `; + expect(extractMinimalStackTraceInfo(stack)).toBe(""); + }); + + it("should handle stack traces with varying whitespace", () => { + const stack = `Error: Something went wrong +at FunctionOne (/Users/user/project/file1.ts:10:15) + at FunctionTwo(/Users/user/project/file2.ts:20:25) + at FunctionThree (/Users/user/project/file3.ts:30:35) + `; + const expected = "FunctionOne, FunctionTwo(), FunctionThree"; + expect(extractMinimalStackTraceInfo(stack)).toBe(expected); + }); + + it("should correctly handle function names with spaces and special characters", () => { + const stack = `Error: Something went wrong + at Object.Function One (/Users/user/project/file1.ts:10:15) + at Module. (/Users/user/project/file2.ts:20:25) + at Function_Two (/Users/user/project/file3.ts:30:35) + `; + const expected = "Object.Function One, Module., Function_Two"; + expect(extractMinimalStackTraceInfo(stack)).toBe(expected); + }); + + it("should handle stack traces with anonymous functions", () => { + const stack = `Error: Something went wrong + at /Users/user/project/file1.ts:10:15 + at /Users/user/project/file2.ts:20:25 + at node_modules/some_module/index.js:40:45 + `; + expect(extractMinimalStackTraceInfo(stack)).toBe(""); + }); + + it("should handle lines without parentheses", () => { + const stack = `Error: Something went wrong + at FunctionOne + at FunctionTwo + at FunctionThree (/Users/user/project/file3.ts:30:35) + `; + const expected = "FunctionOne, FunctionTwo, FunctionThree"; + expect(extractMinimalStackTraceInfo(stack)).toBe(expected); + }); +}); diff --git a/core/util/extractMinimalStackTraceInfo.ts b/core/util/extractMinimalStackTraceInfo.ts index 51fcde91a..026c79aa2 100644 --- a/core/util/extractMinimalStackTraceInfo.ts +++ b/core/util/extractMinimalStackTraceInfo.ts @@ -5,12 +5,29 @@ * @returns A string containing the minimal stack trace information. */ export function extractMinimalStackTraceInfo(stack: unknown): string { - if (typeof stack !== "string") {return "";} - const lines = stack.split("\n"); + if (typeof stack !== "string") { + return ""; + } + const lines = stack + .trim() + .split("\n") + .map((line) => line.trim()); const minimalLines = lines.filter((line) => { - return line.trimStart().startsWith("at ") && !line.includes("node_modules"); + return ( + line.startsWith("at ") && + !line.includes("node_modules") && + !line.includes("node:internal") + ); }); return minimalLines - .map((line) => line.trimStart().replace("at ", "").split(" (").slice(0, 1)) + .map((line) => line.replace("at ", "").split(" (").slice(0, 1)) + .flatMap((parts) => + parts.map( + // to be safe, remove any lingering paths - anonymous function case + (part) => + part.replace(/(?:[A-Za-z]:[\\/]|[\\/])[^\n]*?:\d+:\d+/g, "").trim(), + ), + ) + .filter((part) => !!part) // remove empty string parts (anonymous functions case) .join(", "); } diff --git a/core/util/fetchFavicon.test.ts b/core/util/fetchFavicon.test.ts new file mode 100644 index 000000000..9f93dc2e2 --- /dev/null +++ b/core/util/fetchFavicon.test.ts @@ -0,0 +1,274 @@ +// Generated by continue + +import { + findFaviconPath, + getFaviconBase64, + fetchFavicon, +} from "./fetchFavicon"; + +describe("findFaviconPath", () => { + afterEach(() => { + jest.restoreAllMocks(); + }); + + it("should return the favicon URL when a favicon link is present", async () => { + const mockHtml = ` + + + + + + + `; + const mockResponse = { + ok: true, + text: jest.fn().mockResolvedValue(mockHtml), + }; + + global.fetch = jest.fn().mockResolvedValue(mockResponse); + + const url = new URL("https://example.com"); + const faviconPath = await findFaviconPath(url); + + expect(faviconPath).toBe("https://example.com/favicon.ico"); + expect(global.fetch).toHaveBeenCalledWith("https://example.com"); + }); + + it("should return undefined when no favicon link is present", async () => { + const mockHtml = ` + + + + + `; + const mockResponse = { + ok: true, + text: jest.fn().mockResolvedValue(mockHtml), + }; + + global.fetch = jest.fn().mockResolvedValue(mockResponse); + + const url = new URL("https://example.com"); + const faviconPath = await findFaviconPath(url); + + expect(faviconPath).toBeUndefined(); + expect(global.fetch).toHaveBeenCalledWith("https://example.com"); + }); + + it("should handle fetch errors gracefully and return undefined", async () => { + global.fetch = jest.fn().mockRejectedValue(new Error("Network error")); + + const url = new URL("https://example.com"); + const faviconPath = await findFaviconPath(url); + + expect(faviconPath).toBeUndefined(); + expect(global.fetch).toHaveBeenCalledWith("https://example.com"); + }); + + it("should handle non-OK responses and return undefined", async () => { + const mockResponse = { + ok: false, + status: 404, + }; + + global.fetch = jest.fn().mockResolvedValue(mockResponse); + + const url = new URL("https://example.com"); + const faviconPath = await findFaviconPath(url); + + expect(faviconPath).toBeUndefined(); + expect(global.fetch).toHaveBeenCalledWith("https://example.com"); + }); + + it("should handle relative favicon URLs", async () => { + const mockHtml = ` + + + + + + + `; + const mockResponse = { + ok: true, + text: jest.fn().mockResolvedValue(mockHtml), + }; + + global.fetch = jest.fn().mockResolvedValue(mockResponse); + + const url = new URL("https://example.com"); + const faviconPath = await findFaviconPath(url); + + expect(faviconPath).toBe("https://example.com/favicon.ico"); + expect(global.fetch).toHaveBeenCalledWith("https://example.com"); + }); +}); + +describe("getFaviconBase64", () => { + afterEach(() => { + jest.restoreAllMocks(); + }); + + it("should return base64 data URI of the favicon", async () => { + const iconData = "icon data"; + const arrayBuffer = new TextEncoder().encode(iconData).buffer; + const mockResponse = { + ok: true, + arrayBuffer: jest.fn().mockResolvedValue(arrayBuffer), + headers: { + get: jest.fn().mockReturnValue("image/png"), + }, + }; + + global.fetch = jest.fn().mockResolvedValue(mockResponse); + global.btoa = jest + .fn() + .mockImplementation((str) => + Buffer.from(str, "binary").toString("base64"), + ); + + const faviconUrl = "https://example.com/favicon.ico"; + const base64DataUri = await getFaviconBase64(faviconUrl); + + const expectedBase64 = Buffer.from(iconData).toString("base64"); + + expect(base64DataUri).toBe(`data:image/png;base64,${expectedBase64}`); + expect(global.fetch).toHaveBeenCalledWith(faviconUrl); + }); + + it("should handle fetch errors gracefully and return undefined", async () => { + global.fetch = jest.fn().mockRejectedValue(new Error("Network error")); + + const faviconUrl = "https://example.com/favicon.ico"; + const base64DataUri = await getFaviconBase64(faviconUrl); + + expect(base64DataUri).toBeUndefined(); + expect(global.fetch).toHaveBeenCalledWith(faviconUrl); + }); + + it("should handle non-OK responses and return undefined", async () => { + const mockResponse = { + ok: false, + status: 404, + }; + + global.fetch = jest.fn().mockResolvedValue(mockResponse); + + const faviconUrl = "https://example.com/favicon.ico"; + const base64DataUri = await getFaviconBase64(faviconUrl); + + expect(base64DataUri).toBeUndefined(); + expect(global.fetch).toHaveBeenCalledWith(faviconUrl); + }); + + it("should use default mime type if content-type header is missing", async () => { + const iconData = "icon data"; + const arrayBuffer = new TextEncoder().encode(iconData).buffer; + const mockResponse = { + ok: true, + arrayBuffer: jest.fn().mockResolvedValue(arrayBuffer), + headers: { + get: jest.fn().mockReturnValue(null), + }, + }; + + global.fetch = jest.fn().mockResolvedValue(mockResponse); + global.btoa = jest + .fn() + .mockImplementation((str) => + Buffer.from(str, "binary").toString("base64"), + ); + + const faviconUrl = "https://example.com/favicon.ico"; + const base64DataUri = await getFaviconBase64(faviconUrl); + + const expectedBase64 = Buffer.from(iconData).toString("base64"); + + expect(base64DataUri).toBe(`data:image/x-icon;base64,${expectedBase64}`); + expect(global.fetch).toHaveBeenCalledWith(faviconUrl); + }); +}); + +describe("fetchFavicon", () => { + afterEach(() => { + jest.restoreAllMocks(); + }); + + it("should return base64 data URI of the favicon when favicon is found", async () => { + const url = new URL("https://example.com"); + + // Mock fetch for homepage + const homepageHtml = ` + + + + + + + `; + const homepageResponse = { + ok: true, + text: jest.fn().mockResolvedValue(homepageHtml), + }; + + // Mock fetch for favicon + const iconData = "icon data"; + const arrayBuffer = new TextEncoder().encode(iconData).buffer; + const faviconResponse = { + ok: true, + arrayBuffer: jest.fn().mockResolvedValue(arrayBuffer), + headers: { + get: jest.fn().mockReturnValue("image/png"), + }, + }; + + const fetchMock = jest.fn(); + fetchMock.mockResolvedValueOnce(homepageResponse); // First fetch call + fetchMock.mockResolvedValueOnce(faviconResponse); // Second fetch call + + global.fetch = fetchMock; + global.btoa = jest + .fn() + .mockImplementation((str) => + Buffer.from(str, "binary").toString("base64"), + ); + + const result = await fetchFavicon(url); + + const expectedBase64 = Buffer.from(iconData).toString("base64"); + + expect(result).toBe(`data:image/png;base64,${expectedBase64}`); + expect(global.fetch).toHaveBeenCalledTimes(2); + expect(global.fetch).toHaveBeenCalledWith("https://example.com"); + expect(global.fetch).toHaveBeenCalledWith( + "https://example.com/favicon.ico", + ); + }); + + it("should return undefined when favicon is not found", async () => { + const url = new URL("https://example.com"); + + // Mock fetch for homepage + const homepageHtml = ` + + + + + `; + const homepageResponse = { + ok: true, + text: jest.fn().mockResolvedValue(homepageHtml), + }; + + const fetchMock = jest.fn(); + fetchMock.mockResolvedValueOnce(homepageResponse); // First fetch call + + global.fetch = fetchMock; + + const result = await fetchFavicon(url); + + expect(result).toBeUndefined(); + expect(global.fetch).toHaveBeenCalledTimes(1); + expect(global.fetch).toHaveBeenCalledWith("https://example.com"); + }); +}); diff --git a/core/util/fetchWithOptions.ts b/core/util/fetchWithOptions.ts deleted file mode 100644 index 1d2a8e94f..000000000 --- a/core/util/fetchWithOptions.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { globalAgent } from "https"; -import * as fs from "node:fs"; -import tls from "node:tls"; - -import * as followRedirects from "follow-redirects"; -import { HttpProxyAgent } from "http-proxy-agent"; -import { HttpsProxyAgent } from "https-proxy-agent"; -import fetch, { RequestInit, Response } from "node-fetch"; - - -import { RequestOptions } from "../index.js"; - -const { http, https } = (followRedirects as any).default; - -export function fetchwithRequestOptions( - url_: URL | string, - init?: RequestInit, - requestOptions?: RequestOptions, -): Promise { - let url = url_; - if (typeof url === "string") { - url = new URL(url); - } - - const TIMEOUT = 7200; // 7200 seconds = 2 hours - - let globalCerts: string[] = []; - if (process.env.IS_BINARY) { - if (Array.isArray(globalAgent.options.ca)) { - globalCerts = [...globalAgent.options.ca.map((cert) => cert.toString())]; - } else if (typeof globalAgent.options.ca !== "undefined") { - globalCerts.push(globalAgent.options.ca.toString()); - } - } - const ca = Array.from(new Set([...tls.rootCertificates, ...globalCerts])); - const customCerts = - typeof requestOptions?.caBundlePath === "string" - ? [requestOptions?.caBundlePath] - : requestOptions?.caBundlePath; - if (customCerts) { - ca.push( - ...customCerts.map((customCert) => fs.readFileSync(customCert, "utf8")), - ); - } - - const timeout = (requestOptions?.timeout ?? TIMEOUT) * 1000; // measured in ms - - const agentOptions: {[key: string]: any} = { - ca, - rejectUnauthorized: requestOptions?.verifySsl, - timeout, - sessionTimeout: timeout, - keepAlive: true, - keepAliveMsecs: timeout, - }; - - // Handle ClientCertificateOptions - if (requestOptions?.clientCertificate){ - agentOptions.cert = fs.readFileSync(requestOptions.clientCertificate.cert,"utf8"); - agentOptions.key = fs.readFileSync(requestOptions.clientCertificate.key,"utf8"); - if(requestOptions.clientCertificate.passphrase){ - agentOptions.passphrase = requestOptions.clientCertificate.passphrase; - } - } - - const proxy = requestOptions?.proxy; - - // Create agent - const protocol = url.protocol === "https:" ? https : http; - const agent = - proxy && !requestOptions?.noProxy?.includes(url.hostname) - ? protocol === https - ? new HttpsProxyAgent(proxy, agentOptions) - : new HttpProxyAgent(proxy, agentOptions) - : new protocol.Agent(agentOptions); - - let headers: { [key: string]: string } = {}; - for (const [key, value] of Object.entries(init?.headers || {})) { - headers[key] = value as string; - } - headers = { - ...headers, - ...requestOptions?.headers, - }; - - // Replace localhost with 127.0.0.1 - if (url.hostname === "localhost") { - url.hostname = "127.0.0.1"; - } - - // add extra body properties if provided - let updatedBody: string | undefined = undefined; - try { - if (requestOptions?.extraBodyProperties && typeof init?.body === "string") { - const parsedBody = JSON.parse(init.body); - updatedBody = JSON.stringify({ - ...parsedBody, - ...requestOptions.extraBodyProperties, - }); - } - } catch (e) { - console.log("Unable to parse HTTP request body: ", e); - } - - // fetch the request with the provided options - const resp = fetch(url, { - ...init, - body: updatedBody ?? init?.body, - headers: headers, - agent: agent, - }); - - return resp; -} diff --git a/core/util/generateRepoMap.test.ts b/core/util/generateRepoMap.test.ts new file mode 100644 index 000000000..d1d130d31 --- /dev/null +++ b/core/util/generateRepoMap.test.ts @@ -0,0 +1,214 @@ +// Generated by continue + +import generateRepoMap from "./generateRepoMap"; +import { testIde, testLLM } from "../test/fixtures"; +import { + setUpTestDir, + tearDownTestDir, + addToTestDir, + TEST_DIR, +} from "../test/testDir"; +import fs from "fs"; +import path from "path"; +import { getRepoMapFilePath } from "./paths"; +import { CodeSnippetsCodebaseIndex } from "../indexing/CodeSnippetsIndex"; + +describe.skip("generateRepoMap", () => { + beforeEach(() => { + setUpTestDir(); + }); + + afterEach(() => { + tearDownTestDir(); + jest.restoreAllMocks(); + }); + + it("should generate a repo map with signatures included", async () => { + // Arrange + // Create sample files in the test directory + addToTestDir([ + ["file1.js", "function foo() {}\nfunction bar() {}"], + ["subdir/file2.py", "def foo(): pass\ndef bar(): pass"], + ]); + + // Do not mock testIde.getWorkspaceDirs + + // Mock CodeSnippetsCodebaseIndex.getPathsAndSignatures + jest + .spyOn(CodeSnippetsCodebaseIndex, "getPathsAndSignatures") + .mockImplementation(async (dirs, offset, limit) => { + // Return test data + return { + groupedByPath: { + [path.join(TEST_DIR, "file1.js")]: [ + "function foo() {}", + "function bar() {}", + ], + [path.join(TEST_DIR, "subdir/file2.py")]: [ + "def foo():", + "def bar():", + ], + }, + hasMore: false, + }; + }); + + // Set testLLM properties + testLLM.contextLength = 2048; + testLLM.countTokens = jest.fn().mockReturnValue(10); + + // Act + const repoMapContent = await generateRepoMap(testLLM, testIde, { + includeSignatures: true, + }); + + // Assert + const expectedContent = + "Below is a repository map. \n" + + "For each file in the codebase, " + + "this map contains the name of the file, and the signature for any " + + "classes, methods, or functions in the file.\n\n" + + "file1.js:\n" + + "\tfunction foo() {}\n" + + "\t...\n" + + "\tfunction bar() {}\n\n" + + "subdir/file2.py:\n" + + "\tdef foo():\n" + + "\t...\n" + + "\tdef bar():\n\n"; + + expect(repoMapContent).toBe(expectedContent); + + // Also check that the repo map file was created at the correct path + const repoMapPath = getRepoMapFilePath(); + expect(fs.existsSync(repoMapPath)).toBe(true); + + const fileContent = fs.readFileSync(repoMapPath, "utf8"); + expect(fileContent).toBe(expectedContent); + }); + + it("should generate a repo map without signatures when includeSignatures is false", async () => { + // Arrange + // Create sample files in the test directory + addToTestDir([ + ["file1.js", "function foo() {}\nfunction bar() {}"], + ["subdir/file2.py", "def foo(): pass\ndef bar(): pass"], + ]); + + // Do not mock testIde.getWorkspaceDirs + + // Mock CodeSnippetsCodebaseIndex.getPathsAndSignatures + jest + .spyOn(CodeSnippetsCodebaseIndex, "getPathsAndSignatures") + .mockImplementation(async (dirs, offset, limit) => { + // Return test data + return { + groupedByPath: { + [path.join(TEST_DIR, "file1.js")]: [], + [path.join(TEST_DIR, "subdir/file2.py")]: [], + }, + hasMore: false, + }; + }); + + // Set testLLM properties + testLLM.contextLength = 2048; + testLLM.countTokens = jest.fn().mockReturnValue(10); + + // Act + const repoMapContent = await generateRepoMap(testLLM, testIde, { + includeSignatures: false, + }); + + // Assert + const expectedContent = + "Below is a repository map. \n" + + "For each file in the codebase, " + + "this map contains the name of the file, and the signature for any " + + "classes, methods, or functions in the file.\n\n" + + "file1.js\n" + + "subdir/file2.py\n"; + + expect(repoMapContent).toBe(expectedContent); + + // Also check that the repo map file was created at the correct path + const repoMapPath = getRepoMapFilePath(); + expect(fs.existsSync(repoMapPath)).toBe(true); + + const fileContent = fs.readFileSync(repoMapPath, "utf8"); + expect(fileContent).toBe(expectedContent); + }); + + it("should handle file read errors gracefully", async () => { + // Arrange + // Create sample files in the test directory + addToTestDir([ + ["file1.js", "function foo() {}\nfunction bar() {}"], + ["subdir/file2.py", "def foo(): pass\ndef bar(): pass"], + ]); + + // Do not mock testIde.getWorkspaceDirs + + // Mock CodeSnippetsCodebaseIndex.getPathsAndSignatures + jest + .spyOn(CodeSnippetsCodebaseIndex, "getPathsAndSignatures") + .mockImplementation(async (dirs, offset, limit) => { + // Return test data + return { + groupedByPath: { + [path.join(TEST_DIR, "file1.js")]: ["function foo() {}"], + [path.join(TEST_DIR, "subdir/file2.py")]: ["def foo():"], + }, + hasMore: false, + }; + }); + + // Mock fs.promises.readFile to throw an error when reading file1.js + jest + .spyOn(fs.promises, "readFile") + .mockImplementation((filePath, encoding) => { + if (filePath === path.join(TEST_DIR, "file1.js")) { + return Promise.reject(new Error("File not found")); + } + return fs.promises.readFile(filePath, encoding); + }); + + // Spy on console.error + const consoleErrorSpy = jest + .spyOn(console, "error") + .mockImplementation(() => {}); + + // Set testLLM properties + testLLM.contextLength = 2048; + testLLM.countTokens = jest.fn().mockReturnValue(10); + + // Act + const repoMapContent = await generateRepoMap(testLLM, testIde, { + includeSignatures: true, + }); + + // Assert + const expectedContent = + "Below is a repository map. \n" + + "For each file in the codebase, " + + "this map contains the name of the file, and the signature for any " + + "classes, methods, or functions in the file.\n\n" + + "subdir/file2.py:\n" + + "\tdef foo():\n\n" + + "file1.js\n"; // file1.js is added in writeRemainingPaths + + expect(repoMapContent).toBe(expectedContent); + + // Also check that an error was logged + expect(consoleErrorSpy).toHaveBeenCalledWith( + expect.stringContaining( + "Failed to read file:\n" + + ` Path: ${path.join(TEST_DIR, "file1.js")}\n` + + " Error: File not found", + ), + ); + + // Clean up mock + consoleErrorSpy.mockRestore(); + }); +}); diff --git a/core/util/generateRepoMap.ts b/core/util/generateRepoMap.ts index cfcfdaa8c..db1c1a213 100644 --- a/core/util/generateRepoMap.ts +++ b/core/util/generateRepoMap.ts @@ -187,11 +187,6 @@ class RepoMapGenerator { } private logRepoMapGeneration(): void { - console.debug( - `Generated repo map for ${this.repoMapDirs.join(", ")} at ${ - this.repoMapPath - }`, - ); if (this.contentTokens >= this.maxRepoMapTokens) { console.debug( "Full repo map was unable to be generated due to context window limitations", diff --git a/core/util/ideUtils.test.ts b/core/util/ideUtils.test.ts new file mode 100644 index 000000000..58cd7b7f4 --- /dev/null +++ b/core/util/ideUtils.test.ts @@ -0,0 +1,48 @@ +// Generated by continue + +import { resolveRelativePathInWorkspace } from "./ideUtils"; +import { testIde } from "../test/fixtures"; +import { IDE } from ".."; + +describe("resolveRelativePathInWorkspace", () => { + let mockIde: IDE; + + beforeEach(() => { + mockIde = testIde; + }); + + it("should return the full path if the path is already absolute", async () => { + const mockPath = "/absolute/path/to/file.txt"; + jest.spyOn(mockIde, "pathSep").mockResolvedValue("/"); + + const result = await resolveRelativePathInWorkspace(mockPath, mockIde); + expect(result).toBe(mockPath); + }); + + it("should resolve a relative path to a full path within workspace directories", async () => { + const relativePath = "relative/path/to/file.txt"; + const workspaces = ["/workspace/one", "/workspace/two"]; + const expectedFullPath = `/workspace/one/${relativePath}`; + + jest.spyOn(mockIde, "pathSep").mockResolvedValue("/"); + jest.spyOn(mockIde, "getWorkspaceDirs").mockResolvedValue(workspaces); + jest + .spyOn(mockIde, "fileExists") + .mockImplementation(async (path) => path === expectedFullPath); + + const result = await resolveRelativePathInWorkspace(relativePath, mockIde); + expect(result).toBe(expectedFullPath); + }); + + it("should return undefined if the relative path does not exist in any workspace directory", async () => { + const relativePath = "non/existent/path.txt"; + const workspaces = ["/workspace/one", "/workspace/two"]; + + jest.spyOn(mockIde, "pathSep").mockResolvedValue("/"); + jest.spyOn(mockIde, "getWorkspaceDirs").mockResolvedValue(workspaces); + jest.spyOn(mockIde, "fileExists").mockResolvedValue(false); + + const result = await resolveRelativePathInWorkspace(relativePath, mockIde); + expect(result).toBeUndefined(); + }); +}); diff --git a/core/util/incrementalParseJson.test.ts b/core/util/incrementalParseJson.test.ts new file mode 100644 index 000000000..7536b7977 --- /dev/null +++ b/core/util/incrementalParseJson.test.ts @@ -0,0 +1,89 @@ +// Generated by continue + +import { incrementalParseJson } from "./incrementalParseJson"; + +describe("incrementalParseJson", () => { + it("should return [true, parsedJson] for valid JSON object", () => { + const raw = '{"key": "value"}'; + const [isValid, parsed] = incrementalParseJson(raw); + expect(isValid).toBe(true); + expect(parsed).toEqual({ key: "value" }); + }); + + it("should return [true, parsedJson] for valid JSON array", () => { + const raw = "[1, 2, 3]"; + const [isValid, parsed] = incrementalParseJson(raw); + expect(isValid).toBe(true); + expect(parsed).toEqual([1, 2, 3]); + }); + + it("should return [false, partialParsedJson] for incomplete JSON object", () => { + const raw = '{"key": "value"'; + const [isValid, parsed] = incrementalParseJson(raw); + expect(isValid).toBe(false); + expect(parsed).toEqual({ key: "value" }); + }); + + it("should return [false, partialParsedJson] for incomplete JSON array", () => { + const raw = "[1, 2, 3"; + const [isValid, parsed] = incrementalParseJson(raw); + expect(isValid).toBe(false); + expect(parsed).toEqual([1, 2, 3]); + }); + + it("should return [false, {}] for completely invalid JSON", () => { + const raw = "Hello, World!"; + const [isValid, parsed] = incrementalParseJson(raw); + expect(isValid).toBe(false); + expect(parsed).toEqual({}); + }); + + it("should return [false, {}] for empty string", () => { + const raw = ""; + const [isValid, parsed] = incrementalParseJson(raw); + expect(isValid).toBe(false); + expect(parsed).toEqual({}); + }); + + it("should return [false, {}] for invalid JSON syntax", () => { + const raw = "{key: 'value'}"; + const [isValid, parsed] = incrementalParseJson(raw); + expect(isValid).toBe(false); + expect(parsed).toEqual({}); + }); + + it("should handle whitespace-only string", () => { + const raw = " "; + const [isValid, parsed] = incrementalParseJson(raw); + expect(isValid).toBe(false); + expect(parsed).toEqual({}); + }); + + it("should handle numeric string", () => { + const raw = "12345"; + const [isValid, parsed] = incrementalParseJson(raw); + expect(isValid).toBe(true); + expect(parsed).toEqual(12345); + }); + + it("should handle boolean true string", () => { + const raw = "true"; + const [isValid, parsed] = incrementalParseJson(raw); + expect(isValid).toBe(true); + expect(parsed).toEqual(true); + }); + + it("should handle boolean false string", () => { + const raw = "false"; + const [isValid, parsed] = incrementalParseJson(raw); + expect(isValid).toBe(true); + expect(parsed).toEqual(false); + }); + + it("should handle null string", () => { + const raw = "null"; + const [isValid, parsed] = incrementalParseJson(raw); + expect(isValid).toBe(true); + expect(parsed).toBeNull(); + }); +}); diff --git a/core/util/index.test.ts b/core/util/index.test.ts index 0d618069c..1c6b4a240 100644 --- a/core/util/index.test.ts +++ b/core/util/index.test.ts @@ -1,8 +1,19 @@ // File generated by Continue import { + dedent, dedentAndGetCommonWhitespace, deduplicateArray, getLastNPathParts, + copyOf, + getBasename, + getMarkdownLanguageTagForFile, + getRelativePath, + getUniqueFilePath, + groupByLastNPathParts, + removeCodeBlocksAndTrim, + removeQuotesAndEscapes, + shortestRelativePaths, + splitPath, } from "./"; describe("getLastNPathParts", () => { @@ -198,3 +209,492 @@ describe("dedentAndGetCommonWhitespace", () => { expect(output).toEqual([" line1\nline2\n line3", " "]); }); }); + +describe("dedent function", () => { + it("should remove common leading whitespace from all lines", () => { + const result = dedent` + Hello + World + ! + `; + expect(result).toBe("Hello\n World\n !"); + }); + + it("should handle strings with no indentation", () => { + const result = dedent`Hello +World +!`; + expect(result).toBe("Hello\nWorld\n!"); + }); + + it("should handle strings with mixed indentation", () => { + const result = dedent` + Hello + World + ! + `; + expect(result).toBe(" Hello\nWorld\n !"); + }); + + it("should remove leading and trailing empty lines", () => { + const result = dedent` + + Hello + World + + `; + expect(result).toBe("Hello\nWorld"); + }); + + it("should handle empty strings", () => { + const result = dedent``; + expect(result).toBe(""); + }); + + it("should handle strings with only whitespace", () => { + const result = dedent` + + `; + expect(result).toBe(""); + }); + + it("should handle interpolated values", () => { + const world = "World"; + const result = dedent` + Hello ${world} + How are you? + `; + expect(result).toBe("Hello World\n How are you?"); + }); + + it("should handle multiple interpolated values", () => { + const greeting = "Hello"; + const name = "Alice"; + const question = "How are you?"; + const result = dedent` + ${greeting} ${name} + ${question} + `; + expect(result).toBe("Hello Alice\n How are you?"); + }); + + it("should handle interpolated values with different indentation", () => { + const value1 = "foo"; + const value2 = "bar"; + const result = dedent` + ${value1} + ${value2} + `; + expect(result).toBe("foo\n bar"); + }); + + it("should handle a single line with indentation", () => { + const result = dedent` Hello World!`; + expect(result).toBe("Hello World!"); + }); + + it("should handle a string with only one non-empty line", () => { + const result = dedent` + + Hello World! + + `; + expect(result).toBe("Hello World!"); + }); + + it("should handle a string with Unicode characters", () => { + const result = dedent` + こんにちは + 世界 + `; + expect(result).toBe("こんにちは\n 世界"); + }); + + it("should handle a string with emoji", () => { + const result = dedent` + 🌍 + 🌎 + 🌏 + `; + expect(result).toBe("🌍\n 🌎\n 🌏"); + }); + + it.skip("should handle a string with CRLF line endings", () => { + const result = dedent` + Hello\r + World\r + `; + expect(result).toBe("Hello\r\n World"); + }); + + it.skip("should handle strings with tabs", () => { + const result = dedent` + \tHello + \t\tWorld + \t\t\t! + `; + expect(result).toBe("\tHello\n\t\tWorld\n\t\t\t!"); + }); + + it("should not count empty lines in the minimum indentation", () => { + const result = dedent` + Hello + + World + `; + + expect(result).toBe("Hello\n\nWorld"); + }); + + it("should work with templated strings", () => { + const language = "typescript"; + const code = "console.log('hello');\nconsole.log('world');"; + + const result = dedent` + This is the prefix of the file: + \`\`\`${language} + ${code} + \`\`\``; + + expect(result).toBe(`\ +This is the prefix of the file: +\`\`\`${language} +${code} +\`\`\``); + }); +}); + +describe("removeQuotesAndEscapes", () => { + it("should remove surrounding double quotes and unescape characters", () => { + const input = '"Hello \\"World\\""'; + const output = removeQuotesAndEscapes(input); + expect(output).toBe('Hello "World"'); + }); + + it("should remove surrounding single quotes and unescape characters", () => { + const input = "'It\\'s a test'"; + const output = removeQuotesAndEscapes(input); + expect(output).toBe("It's a test"); + }); + + it("should handle smart quotes and remove them", () => { + const input = "“Smart Quotes”"; + const output = removeQuotesAndEscapes(input); + expect(output).toBe("Smart Quotes"); + }); + + it("should remove backticks if present", () => { + const input = "`Some code snippet`"; + const output = removeQuotesAndEscapes(input); + expect(output).toBe("Some code snippet"); + }); + + it("should handle multiple layers of quotes", () => { + const input = "\"\"''``Nested``''\"\""; + const output = removeQuotesAndEscapes(input); + expect(output).toBe("Nested"); + }); + + it("should handle strings without quotes", () => { + const input = "No quotes here"; + const output = removeQuotesAndEscapes(input); + expect(output).toBe("No quotes here"); + }); + + it("should handle empty strings", () => { + const input = ""; + const output = removeQuotesAndEscapes(input); + expect(output).toBe(""); + }); + + it("should handle strings with only escape sequences", () => { + const input = "\\n\\t\\\\"; + const output = removeQuotesAndEscapes(input); + expect(output).toBe("\n\t\\"); + }); +}); + +describe("getBasename", () => { + it("should return the base name of a Unix-style path", () => { + const filepath = "/home/user/documents/file.txt"; + const output = getBasename(filepath); + expect(output).toBe("file.txt"); + }); + + it("should return the base name of a Windows-style path", () => { + const filepath = "C:\\Users\\User\\Documents\\file.txt"; + const output = getBasename(filepath); + expect(output).toBe("file.txt"); + }); + + it("should handle paths with mixed separators", () => { + const filepath = "C:/Users\\User/Documents/file.txt"; + const output = getBasename(filepath); + expect(output).toBe("file.txt"); + }); + + it("should return an empty string for empty input", () => { + const filepath = ""; + const output = getBasename(filepath); + expect(output).toBe(""); + }); +}); + +describe("groupByLastNPathParts", () => { + it("should group filepaths by their last N parts", () => { + const filepaths = [ + "/a/b/c/d/file1.txt", + "/x/y/z/file1.txt", + "/a/b/c/d/file2.txt", + ]; + const output = groupByLastNPathParts(filepaths, 2); + expect(output).toEqual({ + "d/file1.txt": ["/a/b/c/d/file1.txt"], + "z/file1.txt": ["/x/y/z/file1.txt"], + "d/file2.txt": ["/a/b/c/d/file2.txt"], + }); + }); + + it("should handle an empty array", () => { + const filepaths: string[] = []; + const output = groupByLastNPathParts(filepaths, 2); + expect(output).toEqual({}); + }); + + it("should handle N greater than path parts", () => { + const filepaths = ["/file.txt"]; + const output = groupByLastNPathParts(filepaths, 5); + expect(output).toEqual({ "/file.txt": ["/file.txt"] }); + }); +}); + +describe("getUniqueFilePath", () => { + it("should return a unique file path within the group", () => { + const item = "/a/b/c/file.txt"; + const itemGroups = { + "c/file.txt": ["/a/b/c/file.txt", "/x/y/c/file.txt"], + }; + const output = getUniqueFilePath(item, itemGroups); + expect(output).toBe("b/c/file.txt"); + }); + + it("should return the last two parts if unique", () => { + const item = "/a/b/c/file.txt"; + const itemGroups = { + "c/file.txt": ["/a/b/c/file.txt"], + }; + const output = getUniqueFilePath(item, itemGroups); + expect(output).toBe("c/file.txt"); + }); + + it("should handle when additional parts are needed to make it unique", () => { + const item = "/a/b/c/d/e/file.txt"; + const itemGroups = { + "e/file.txt": ["/a/b/c/d/e/file.txt", "/x/y/z/e/file.txt"], + }; + const output = getUniqueFilePath(item, itemGroups); + expect(output).toBe("d/e/file.txt"); + }); +}); + +describe("shortestRelativePaths", () => { + it("should return shortest unique paths", () => { + const paths = [ + "/a/b/c/file.txt", + "/a/b/d/file.txt", + "/a/b/d/file2.txt", + "/x/y/z/file.txt", + ]; + const output = shortestRelativePaths(paths); + expect(output).toEqual([ + "c/file.txt", + "d/file.txt", + "file2.txt", + "z/file.txt", + ]); + }); + + it("should handle empty array", () => { + const paths: string[] = []; + const output = shortestRelativePaths(paths); + expect(output).toEqual([]); + }); + + it("should handle paths with same base names", () => { + const paths = [ + "/a/b/c/d/file.txt", + "/a/b/c/e/file.txt", + "/a/b/f/g/h/file.txt", + ]; + const output = shortestRelativePaths(paths); + expect(output).toEqual(["d/file.txt", "e/file.txt", "h/file.txt"]); + }); + + it("should handle paths where entire path is needed", () => { + const paths = ["/a/b/c/file.txt", "/a/b/c/file.txt", "/a/b/c/file.txt"]; + const output = shortestRelativePaths(paths); + expect(output).toEqual(["file.txt", "file.txt", "file.txt"]); + }); +}); + +describe("splitPath", () => { + it("should split Unix-style paths", () => { + const path = "/a/b/c/d/e.txt"; + const output = splitPath(path); + expect(output).toEqual(["", "a", "b", "c", "d", "e.txt"]); + }); + + it("should split Windows-style paths", () => { + const path = "C:\\Users\\User\\Documents\\file.txt"; + const output = splitPath(path); + expect(output).toEqual(["C:", "Users", "User", "Documents", "file.txt"]); + }); + + it("should handle withRoot parameter", () => { + const path = "/a/b/c/d/e.txt"; + const withRoot = "/a/b"; + const output = splitPath(path, withRoot); + expect(output).toEqual(["b", "c", "d", "e.txt"]); + }); + + it("should handle empty path", () => { + const path = ""; + const output = splitPath(path); + expect(output).toEqual([""]); + }); + + it("should handle paths with multiple consecutive separators", () => { + const path = "/a//b/c/d/e.txt"; + const output = splitPath(path); + expect(output).toEqual(["", "a", "", "b", "c", "d", "e.txt"]); + }); +}); + +describe("getRelativePath", () => { + it("should return the relative path with respect to workspace directories", () => { + const filepath = "/workspace/project/src/file.ts"; + const workspaceDirs = ["/workspace/project"]; + const output = getRelativePath(filepath, workspaceDirs); + expect(output).toBe("src/file.ts"); + }); + + it("should return the filename if not in any workspace", () => { + const filepath = "/other/place/file.ts"; + const workspaceDirs = ["/workspace/project"]; + const output = getRelativePath(filepath, workspaceDirs); + expect(output).toBe("file.ts"); + }); + + it("should handle multiple workspace directories", () => { + const filepath = "/workspace2/project/src/file.ts"; + const workspaceDirs = ["/workspace/project", "/workspace2/project"]; + const output = getRelativePath(filepath, workspaceDirs); + expect(output).toBe("src/file.ts"); + }); + + it("should handle Windows-style paths", () => { + const filepath = "C:\\workspace\\project\\src\\file.ts"; + const workspaceDirs = ["C:\\workspace\\project"]; + const output = getRelativePath(filepath, workspaceDirs); + expect(output).toBe("src/file.ts"); + }); + + it("should handle paths with spaces or special characters", () => { + const filepath = "/workspace/project folder/src/file.ts"; + const workspaceDirs = ["/workspace/project folder"]; + const output = getRelativePath(filepath, workspaceDirs); + expect(output).toBe("src/file.ts"); + }); +}); + +describe("getMarkdownLanguageTagForFile", () => { + it("should return correct language tag for known extensions", () => { + expect(getMarkdownLanguageTagForFile("test.py")).toBe("python"); + expect(getMarkdownLanguageTagForFile("test.tsx")).toBe("tsx"); + expect(getMarkdownLanguageTagForFile("test.java")).toBe("java"); + expect(getMarkdownLanguageTagForFile("test.md")).toBe("markdown"); + expect(getMarkdownLanguageTagForFile("test.sh")).toBe("shell"); + expect(getMarkdownLanguageTagForFile("test.sql")).toBe("sql"); + }); + + it("should return the extension if not in the known list", () => { + expect(getMarkdownLanguageTagForFile("file.unknownext")).toBe("unknownext"); + }); + + it("should handle filenames without extension", () => { + expect(getMarkdownLanguageTagForFile("Makefile")).toBe("Makefile"); + }); + + it("should handle filenames with multiple dots", () => { + expect(getMarkdownLanguageTagForFile("archive.tar.gz")).toBe("gz"); + }); + + it("should handle edge case with empty string as filename", () => { + expect(getMarkdownLanguageTagForFile("")).toBe(""); + }); + + it("should correctly identify files with no extensions", () => { + expect(getMarkdownLanguageTagForFile("README")).toBe("README"); + }); +}); + +describe("copyOf", () => { + it("should create a deep copy of an object", () => { + const original = { a: 1, b: { c: 2 } }; + const copied = copyOf(original); + expect(copied).toEqual(original); + expect(copied).not.toBe(original); + expect(copied.b).not.toBe(original.b); + }); + + it("should handle arrays", () => { + const original = [1, 2, { a: 3 }]; + const copied = copyOf(original); + expect(copied).toEqual(original); + expect(copied).not.toBe(original); + expect(copied[2]).not.toBe(original[2]); + }); + + it("should return null for null input", () => { + expect(copyOf(null)).toBeNull(); + }); + + it("should return undefined for undefined input", () => { + expect(copyOf(undefined)).toBeUndefined(); + }); + + it("should handle objects with circular references gracefully", () => { + // This may not be feasible with JSON.stringify – consider alternative methods like a library for deep cloning. + const a: any = {}; + a.self = a; + expect(() => copyOf(a)).toThrow(); // Ideally, handle circular refs before calling JSON.stringify + }); +}); + +describe("removeCodeBlocksAndTrim", () => { + it("should remove code blocks from text", () => { + const text = + "Here is some text.\n```javascript\nconsole.log('Hello');\n```\nMore text."; + const output = removeCodeBlocksAndTrim(text); + expect(output).toBe("Here is some text.\n\nMore text."); + }); + + it("should remove multiple code blocks", () => { + const text = + "Text before.\n```code block 1```\nBetween code blocks.\n```code block 2```\nText after."; + const output = removeCodeBlocksAndTrim(text); + expect(output).toBe("Text before.\n\nBetween code blocks.\n\nText after."); + }); + + it("should handle text without code blocks", () => { + const text = "No code blocks here."; + const output = removeCodeBlocksAndTrim(text); + expect(output).toBe("No code blocks here."); + }); + + it("should trim whitespace from the result", () => { + const text = " \n```code```\n "; + const output = removeCodeBlocksAndTrim(text); + expect(output).toBe(""); + }); +}); diff --git a/core/util/index.ts b/core/util/index.ts index a5608a508..a2c8af5c5 100644 --- a/core/util/index.ts +++ b/core/util/index.ts @@ -1,20 +1,18 @@ -import { getLastNUriRelativePathParts } from "./uri"; - -export function removeQuotesAndEscapes(output: string): string { - output = output.trim(); +export function removeQuotesAndEscapes(input: string): string { + let output = input.trim(); // Replace smart quotes - output = output.replace("“", '"'); - output = output.replace("”", '"'); - output = output.replace("‘", "'"); - output = output.replace("’", "'"); + output = output.replaceAll("“", '"'); + output = output.replaceAll("”", '"'); + output = output.replaceAll("‘", "'"); + output = output.replaceAll("’", "'"); // Remove escapes - output = output.replace('\\"', '"'); - output = output.replace("\\'", "'"); - output = output.replace("\\n", "\n"); - output = output.replace("\\t", "\t"); - output = output.replace("\\\\", "\\"); + output = output.replaceAll('\\"', '"'); + output = output.replaceAll("\\'", "'"); + output = output.replaceAll("\\n", "\n"); + output = output.replaceAll("\\t", "\t"); + output = output.replaceAll("\\\\", "\\"); while ( (output.startsWith('"') && output.endsWith('"')) || (output.startsWith("'") && output.endsWith("'")) @@ -194,63 +192,37 @@ const SEP_REGEX = /[\\/]/; // } export function getMarkdownLanguageTagForFile(filepath: string): string { + const extToLangMap: { [key: string]: string } = { + py: "python", + js: "javascript", + jsx: "jsx", + tsx: "tsx", + ts: "typescript", + java: "java", + go: "go", + rb: "ruby", + rs: "rust", + c: "c", + cpp: "cpp", + cs: "csharp", + php: "php", + scala: "scala", + swift: "swift", + kt: "kotlin", + md: "markdown", + json: "json", + html: "html", + css: "css", + sh: "shell", + yaml: "yaml", + toml: "toml", + tex: "latex", + sql: "sql", + ps1: "powershell", + }; + const ext = filepath.split(".").pop(); - switch (ext) { - case "py": - return "python"; - case "js": - return "javascript"; - case "jsx": - return "jsx"; - case "tsx": - return "tsx"; - case "ts": - return "typescript"; - case "java": - return "java"; - case "go": - return "go"; - case "rb": - return "ruby"; - case "rs": - return "rust"; - case "c": - return "c"; - case "cpp": - return "cpp"; - case "cs": - return "csharp"; - case "php": - return "php"; - case "scala": - return "scala"; - case "swift": - return "swift"; - case "kt": - return "kotlin"; - case "md": - return "markdown"; - case "json": - return "json"; - case "html": - return "html"; - case "css": - return "css"; - case "sh": - return "shell"; - case "yaml": - return "yaml"; - case "toml": - return "toml"; - case "tex": - return "latex"; - case "sql": - return "sql"; - case "ps1": - return "powershell"; - default: - return ext ?? ""; - } + return ext ? (extToLangMap[ext] ?? ext) : ""; } export function copyOf(obj: any): any { @@ -259,6 +231,7 @@ export function copyOf(obj: any): any { } return JSON.parse(JSON.stringify(obj)); } +``; export function deduplicateArray( array: T[], diff --git a/core/util/messageContent.test.ts b/core/util/messageContent.test.ts new file mode 100644 index 000000000..130e7d533 --- /dev/null +++ b/core/util/messageContent.test.ts @@ -0,0 +1,74 @@ +import { stripImages, renderChatMessage, renderContextItems, normalizeToMessageParts } from "./messageContent.js"; +import { ChatMessage, ContextItem, MessageContent, MessagePart } from "../index.js"; + +describe("messageContent utility functions", () => { + describe("stripImages", () => { + it("should return the string as is if messageContent is a string", () => { + const content: MessageContent = "This is a test message."; + expect(stripImages(content)).toBe("This is a test message."); + }); + + it("should strip out image parts and join text parts of a message", () => { + const content: MessageContent = [ + { type: "text", text: "This is" }, + { type: "imageUrl", imageUrl: { url: "http://example.com/image1.png" } }, + { type: "text", text: "a test message." }, + ]; + expect(stripImages(content)).toBe("This is\na test message."); + }); + }); + + describe("renderChatMessage", () => { + it("should render user, assistant, or system messages with stripped image content", () => { + const message: ChatMessage = { + role: "assistant", + content: [ + { type: "text", text: "Hello," }, + { type: "imageUrl", imageUrl: { url: "http://example.com/image.png" } }, + { type: "text", text: "world!" }, + ], + }; + expect(renderChatMessage(message)).toBe("Hello,\nworld!"); + }); + + it("should render tool messages as is", () => { + const message: ChatMessage = { + role: "tool", + content: "Command output message", + toolCallId: "1", + }; + expect(renderChatMessage(message)).toBe("Command output message"); + }); + }); + + describe("renderContextItems", () => { + it("should concatenate the content of context items with two newlines", () => { + const items: ContextItem[] = [ + { content: "Context Item 1", name: "Item1", description: "Description1" }, + { content: "Context Item 2", name: "Item2", description: "Description2" }, + ]; + expect(renderContextItems(items)).toBe("Context Item 1\n\nContext Item 2"); + }); + }); + + describe("normalizeToMessageParts", () => { + it("should normalize user, assistant, or system messages to MessagePart array", () => { + const message: ChatMessage = { + role: "user", + content: "This is a test message.", + }; + const expected: MessagePart[] = [{ type: "text", text: "This is a test message." }]; + expect(normalizeToMessageParts(message)).toEqual(expected); + }); + + it("should normalize tool messages to MessagePart array", () => { + const message: ChatMessage = { + role: "tool", + content: "Tool message content", + toolCallId: "1", + }; + const expected: MessagePart[] = [{ type: "text", text: "Tool message content" }]; + expect(normalizeToMessageParts(message)).toEqual(expected); + }); + }); +}); \ No newline at end of file diff --git a/core/util/messageContent.ts b/core/util/messageContent.ts index b42bb082a..b1c91ca17 100644 --- a/core/util/messageContent.ts +++ b/core/util/messageContent.ts @@ -3,7 +3,7 @@ import { ContextItem, MessageContent, MessagePart, -} from "../index.js"; +} from "../index"; export function stripImages(messageContent: MessageContent): string { if (typeof messageContent === "string") { diff --git a/core/util/paths.ts b/core/util/paths.ts index 48877ea4d..d6d2d3365 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -13,6 +13,10 @@ dotenv.config(); const CONTINUE_GLOBAL_DIR = process.env.CONTINUE_GLOBAL_DIR ?? path.join(os.homedir(), ".continue"); +// export const DEFAULT_CONFIG_TS_CONTENTS = `import { Config } from "./types"\n\nexport function modifyConfig(config: Config): Config { +// return config; +// }`; + export const DEFAULT_CONFIG_TS_CONTENTS = `export function modifyConfig(config: Config): Config { return config; }`; diff --git a/core/util/ranges.test.ts b/core/util/ranges.test.ts index d9d12c07a..84d1c8d54 100644 --- a/core/util/ranges.test.ts +++ b/core/util/ranges.test.ts @@ -1,8 +1,8 @@ // This file is generated by Continue import { - intersection, getRangeInString, + intersection, maxPosition, minPosition, union, @@ -80,8 +80,7 @@ describe("union", () => { }); }); - // TODO - test.skip("should handle edge case where start and end lines are the same", () => { + test("should handle edge case where start and end lines are the same", () => { rangeA = { start: { line: 1, character: 0 }, end: { line: 1, character: 5 }, diff --git a/core/util/ranges.ts b/core/util/ranges.ts index 3fb5b609e..a9bf5e972 100644 --- a/core/util/ranges.ts +++ b/core/util/ranges.ts @@ -58,17 +58,27 @@ export function intersection(a: Range, b: Range): Range | null { } export function union(a: Range, b: Range): Range { - const startLine = Math.min(a.start.line, b.start.line); - const endLine = Math.max(a.end.line, b.end.line); + let start: Position; + if (a.start.line === b.start.line) { + start = { + line: a.start.line, + character: Math.min(a.start.character, b.start.character), + }; + } else if (a.start.line < b.start.line) start = a.start; + else start = b.start; - const startCharacter = - startLine === a.start.line ? a.start.character : b.start.character; - const endCharacter = - endLine === a.end.line ? a.end.character : b.end.character; + let end: Position; + if (a.end.line === b.end.line) { + end = { + line: a.end.line, + character: Math.max(a.end.character, b.end.character), + }; + } else if (a.end.line > b.end.line) end = a.end; + else end = b.end; return { - start: { line: startLine, character: startCharacter }, - end: { line: endLine, character: endCharacter }, + start, + end, }; } diff --git a/core/util/treeSitter.ts b/core/util/treeSitter.ts index daa12827d..2a67b9102 100644 --- a/core/util/treeSitter.ts +++ b/core/util/treeSitter.ts @@ -279,6 +279,7 @@ export async function getSymbolsForFile( line: node.endPosition.row + 1, }, }, + content: node.text, }); } } diff --git a/core/util/tts.ts b/core/util/tts.ts index 1fd41607c..aace86bf9 100644 --- a/core/util/tts.ts +++ b/core/util/tts.ts @@ -3,7 +3,7 @@ import os from "node:os"; import { removeCodeBlocksAndTrim } from "."; -import type { IMessenger } from "./messenger"; +import type { IMessenger } from "../protocol/messenger"; import type { FromCoreProtocol, ToCoreProtocol } from "../protocol"; // The amount of time before a process is declared diff --git a/core/util/withExponentialBackoff.test.ts b/core/util/withExponentialBackoff.test.ts new file mode 100644 index 000000000..5049073c7 --- /dev/null +++ b/core/util/withExponentialBackoff.test.ts @@ -0,0 +1,142 @@ +// Generated by continue + +import { + withExponentialBackoff, + APIError, + RETRY_AFTER_HEADER, +} from "./withExponentialBackoff"; + +describe.skip("withExponentialBackoff", () => { + it("should return result when apiCall succeeds on first attempt", async () => { + // Arrange + const apiCall = jest.fn().mockResolvedValue("Success"); + + // Act + const result = await withExponentialBackoff(apiCall); + + // Assert + expect(result).toBe("Success"); + expect(apiCall).toHaveBeenCalledTimes(1); + }); + + it("should throw error when apiCall fails with non-429 error", async () => { + // Arrange + const error = new Error("Some error"); + const apiCall = jest.fn().mockRejectedValue(error); + + // Act & Assert + await expect(withExponentialBackoff(apiCall)).rejects.toThrow("Some error"); + expect(apiCall).toHaveBeenCalledTimes(1); + }); + + it("should retry when apiCall fails with 429 and no Retry-After header", async () => { + // Arrange + const apiCall = jest.fn(); + + const firstError: APIError = new Error("Rate limit"); + firstError.response = { + status: 429, + headers: { + get: () => null, // No Retry-After header + }, + } as unknown as Response; + + // First call fails with 429, second call succeeds + apiCall.mockRejectedValueOnce(firstError).mockResolvedValueOnce("Success"); + + // Act + const result = await withExponentialBackoff( + apiCall, + 5, + 0.01, // initialDelaySeconds + ); + + // Assert + expect(result).toBe("Success"); + expect(apiCall).toHaveBeenCalledTimes(2); + }); + + it("should retry when apiCall fails with 429 and Retry-After header", async () => { + // Arrange + const apiCall = jest.fn(); + + const firstError: APIError = new Error("Rate limit"); + firstError.response = { + status: 429, + headers: { + get: (headerName: string) => { + if (headerName === RETRY_AFTER_HEADER) { + return "0.02"; + } + return null; + }, + }, + } as unknown as Response; + + // First call fails with 429, second call succeeds + apiCall.mockRejectedValueOnce(firstError).mockResolvedValueOnce("Success"); + + jest.useFakeTimers(); + + const promise = withExponentialBackoff(apiCall, 5, 0.01); + + // Advance timers to cover the delay + await jest.advanceTimersByTimeAsync(20); + + const result = await promise; + + // Assert + expect(result).toBe("Success"); + expect(apiCall).toHaveBeenCalledTimes(2); + + jest.useRealTimers(); + }); + + it("should throw error after maxTries reached", async () => { + // Arrange + const apiCall = jest.fn(); + + const error: APIError = new Error("Rate limit"); + error.response = { + status: 429, + headers: { + get: () => null, + }, + } as unknown as Response; + + apiCall.mockRejectedValue(error); + + const maxTries = 3; + const initialDelaySeconds = 0.01; + + // Act & Assert + await expect( + withExponentialBackoff(apiCall, maxTries, initialDelaySeconds), + ).rejects.toThrow("Failed to make API call after max tries"); + + expect(apiCall).toHaveBeenCalledTimes(maxTries); + }); + + it("should not call if maxTries is 0", async () => { + const apiCall = jest.fn(); + + const error: APIError = new Error("Rate limit"); + error.response = { + status: 429, + headers: { + get: () => null, + }, + } as unknown as Response; + + apiCall.mockRejectedValue(error); + + const maxTries = 0; + const initialDelaySeconds = 0.01; + + await expect( + withExponentialBackoff(apiCall, maxTries, initialDelaySeconds), + ).rejects.toThrow("Failed to make API call after max tries"); + + expect(apiCall).toHaveBeenCalledTimes(0); + }); +}); diff --git a/core/util/withExponentialBackoff.ts b/core/util/withExponentialBackoff.ts index 84b301b26..d0cef31e5 100644 --- a/core/util/withExponentialBackoff.ts +++ b/core/util/withExponentialBackoff.ts @@ -1,4 +1,4 @@ -interface APIError extends Error { +export interface APIError extends Error { response?: Response; } @@ -6,18 +6,15 @@ export const RETRY_AFTER_HEADER = "Retry-After"; const withExponentialBackoff = async ( apiCall: () => Promise, - maxRetries = 5, + maxTries = 5, initialDelaySeconds = 1, ) => { - for (let attempt = 0; attempt < maxRetries; attempt++) { + for (let attempt = 0; attempt < maxTries; attempt++) { try { const result = await apiCall(); return result; } catch (error: any) { - if ( - (error as APIError).response?.status === 429 && - attempt < maxRetries - 1 - ) { + if ((error as APIError).response?.status === 429) { const retryAfter = (error as APIError).response?.headers.get( RETRY_AFTER_HEADER, ); @@ -35,7 +32,7 @@ const withExponentialBackoff = async ( } } } - throw new Error("Failed to make API call after multiple retries"); + throw new Error(`Failed to make API call after ${maxTries} retries`); }; export { withExponentialBackoff }; diff --git a/docs/docs/actions/how-to-customize.md b/docs/docs/actions/how-to-customize.md index 01cf2d064..81d33967b 100644 --- a/docs/docs/actions/how-to-customize.md +++ b/docs/docs/actions/how-to-customize.md @@ -33,9 +33,12 @@ export function modifyConfig(config: Config): Config { name: "commit", description: "Write a commit message", run: async function* (sdk) { - const diff = await sdk.ide.getDiff(); + // 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, }, @@ -47,7 +50,6 @@ export function modifyConfig(config: Config): Config { return config; } ``` - diff --git a/docs/docs/customize/deep-dives/configuration.md b/docs/docs/customize/deep-dives/configuration.md index 62f79952e..e2e2b91d1 100644 --- a/docs/docs/customize/deep-dives/configuration.md +++ b/docs/docs/customize/deep-dives/configuration.md @@ -50,9 +50,12 @@ export function modifyConfig(config: Config): Config { name: "commit", description: "Write a commit message", run: async function* (sdk) { - const diff = await sdk.ide.getDiff(); + // 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, }, diff --git a/docs/docs/customize/deep-dives/prompt-files.md b/docs/docs/customize/deep-dives/prompt-files.md index e69902a42..fd8a1ae94 100644 --- a/docs/docs/customize/deep-dives/prompt-files.md +++ b/docs/docs/customize/deep-dives/prompt-files.md @@ -51,7 +51,7 @@ Many [context provider](../context-providers.md) can be referenced by typing "@" - `@terminal` - The contents of the terminal - `@https://github.com/continuedev/continue` - The contents of a URL -- `@src/index.ts` - The contents of a file +- `@src/index.ts` - The contents of a file (VS Code only) ## Feedback diff --git a/docs/docs/customize/model-providers/more/scaleway.md b/docs/docs/customize/model-providers/more/scaleway.md new file mode 100644 index 000000000..411e95f3a --- /dev/null +++ b/docs/docs/customize/model-providers/more/scaleway.md @@ -0,0 +1,49 @@ +--- +title: Scaleway +--- + +:::info + +Scaleway Generative APIs give you instant access to leading AI models hosted in European data centers, ideal for developers requiring low latency, full data privacy, and compliance with EU AI Act. +You can generate your API key in [Scaleway's console](https://console.scaleway.com/generative-api/models). +Read the [quickstart documentation here](https://www.scaleway.com/en/docs/ai-data/generative-apis/quickstart/). + +::: + +## Chat model + +We recommend configuring **Qwen2.5-Coder-32B-Instruct** as your chat model. +[Click here](https://www.scaleway.com/en/docs/ai-data/generative-apis/reference-content/supported-models/) to see the list of available chat models. + +```json title="config.json" +{ + "models": [ + { + "title": "Qwen2.5-Coder-32B-Instruct", + "provider": "scaleway", + "model": "qwen2.5-coder-32b-instruct", + "apiKey": "[API_KEY]" + } + ] +} +``` + +## Autocomplete model + +Scaleway currently does not offer any autocomplete models. + +[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers. + +## Embeddings model + +We recommend configuring **BGE-Multilingual-Gemma2** as your embeddings model. + +```json title="config.json" +{ + "embeddingsProvider": { + "provider": "scaleway", + "model": "bge-multilingual-gemma2", + "apiKey": "[API_KEY]" + } +} +``` \ No newline at end of file diff --git a/docs/docs/customize/model-types/embeddings.md b/docs/docs/customize/model-types/embeddings.md index 882c5da79..137f6c260 100644 --- a/docs/docs/customize/model-types/embeddings.md +++ b/docs/docs/customize/model-types/embeddings.md @@ -19,7 +19,7 @@ The free trial supports embeddings (provider: `free-trial`) ## Recommended embedding models -If you have the ability to use any model, we recommend `voyage-code-2`, which is listed below along with the rest of the options for embeddings models. +If you have the ability to use any model, we recommend `voyage-code-3`, which is listed below along with the rest of the options for embeddings models. If you want to generate embeddings locally, we recommend using `nomic-embed-text` with [Ollama](../model-providers/top-level/ollama.md#embeddings-model). @@ -31,7 +31,7 @@ After obtaining an API key from [here](https://www.voyageai.com/), you can confi { "embeddingsProvider": { "provider": "voyage", - "model": "voyage-code-2", + "model": "voyage-code-3", "apiKey": "" } } 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 b3fc25c3a..dc450cdd4 100644 --- a/docs/docs/customize/tutorials/build-your-own-slash-command.md +++ b/docs/docs/customize/tutorials/build-your-own-slash-command.md @@ -44,9 +44,12 @@ export function modifyConfig(config: Config): Config { name: "commit", description: "Write a commit message", run: async function* (sdk) { - const diff = await sdk.ide.getDiff(true); + // 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, }, diff --git a/docs/docs/customize/tutorials/custom-code-rag.md b/docs/docs/customize/tutorials/custom-code-rag.md index acd778b91..b6f1cc251 100644 --- a/docs/docs/customize/tutorials/custom-code-rag.md +++ b/docs/docs/customize/tutorials/custom-code-rag.md @@ -4,7 +4,7 @@ While Continue comes with [@Codebase](../deep-dives/codebase.md) out of the box, ## Step 1: Choose an embeddings model -If possible, we recommend using [`voyage-code-2`](https://docs.voyageai.com/docs/embeddings), which will give the most accurate answers of any existing embeddings model for code. You can obtain an API key [here](https://dash.voyageai.com/api-keys). Because their API is [OpenAI-compatible](https://docs.voyageai.com/reference/embeddings-api), you can use any OpenAI client by swapping out the URL. +If possible, we recommend using [`voyage-code-3`](https://docs.voyageai.com/docs/embeddings), which will give the most accurate answers of any existing embeddings model for code. You can obtain an API key [here](https://dash.voyageai.com/api-keys). Because their API is [OpenAI-compatible](https://docs.voyageai.com/reference/embeddings-api), you can use any OpenAI client by swapping out the URL. ## Step 2: Choose a vector database @@ -16,7 +16,7 @@ There are a number of available vector databases, but because most vector databa Most embeddings models can only handle a limited amount of text at once. To get around this, we "chunk" our code into smaller pieces. -If you use `voyage-code-2`, it has a maximum context length of 16,000 tokens, which is enough to fit most files. This means that in the beginning you can get away with a more naive strategy of truncating files that exceed the limit. In order of easiest to most comprehensive, 3 chunking strategies you can use are: +If you use `voyage-code-3`, it has a maximum context length of 16,000 tokens, which is enough to fit most files. This means that in the beginning you can get away with a more naive strategy of truncating files that exceed the limit. In order of easiest to most comprehensive, 3 chunking strategies you can use are: 1. Truncate the file when it goes over the context length: in this case you will always have 1 chunk per file. 2. Split the file into chunks of a fixed length: starting at the top of the file, add lines you your current chunk until it reaches the limit, then start a new chunk. @@ -40,7 +40,7 @@ from lancedb.embeddings import get_registry db = lancedb.connect("/tmp/db") func = get_registry().get("openai").create( - name="voyage-code-2", + name="voyage-code-3", base_url="https://api.voyageai.com/v1/", api_key=os.environ["VOYAGE_API_KEY"], ) @@ -48,7 +48,7 @@ func = get_registry().get("openai").create( class CodeChunks(LanceModel): filename: str text: str = func.SourceField() - # 1536 is the embedding dimension of the `voyage-code-2` model. + # 1536 is the embedding dimension of the `voyage-code-3` model. vector: Vector(1536) = func.VectorField() table = db.create_table("code_chunks", schema=CodeChunks, mode="overwrite") diff --git a/docs/docs/getting-started/install.md b/docs/docs/getting-started/install.md index e894596fb..20aa52baa 100644 --- a/docs/docs/getting-started/install.md +++ b/docs/docs/getting-started/install.md @@ -18,7 +18,7 @@ If you have any problems, see the [troubleshooting guide](troubleshooting.md) or ## JetBrains -1. Open your JetBrains IDE and open **Settings** using cmd/ctrl + , +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 diff --git a/docs/docs/reference.md b/docs/docs/reference.md index df3f08e75..527820556 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -365,6 +365,7 @@ Customizable UI settings to control interface appearance and behavior. - `fontSize`: Specifies font size for UI elements. - `displayRawMarkdown`: If `true`, shows raw markdown in responses. - `showChatScrollbar`: If `true`, enables a scrollbar in the chat window. +- `codeWrap`: If `true`, enables text wrapping in code blocks. Example: @@ -373,7 +374,9 @@ Example: "ui": { "codeBlockToolbarPosition": "bottom", "fontSize": 14, - "displayRawMarkdown": false + "displayRawMarkdown": false, + "showChatScrollbar": false, + "codeWrap": false } } ``` 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 095d75918..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 @@ -33,9 +33,12 @@ export function modifyConfig(config: Config): Config { name: "commit", description: "Write a commit message", run: async function* (sdk) { - const diff = await sdk.ide.getDiff(); + // getDiff 函数接受一个布尔参数,该参数指示是否 + // 在 diff 中包含未暂存的更改。 + const diff = await sdk.ide.getDiff(false); // 传递 false 以排除未暂存的更改 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, }, 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-types/embeddings.md index eb73c3ad4..d5534b62a 100644 --- 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-types/embeddings.md @@ -11,7 +11,7 @@ sidebar_position: 3 ## 推荐的嵌入模型 -如果你有使用任何模型的能力,我们推荐 `voyage-code-2` ,它独立列在下面,和其他的嵌入模型选项一起。 +如果你有使用任何模型的能力,我们推荐 `voyage-code-3` ,它独立列在下面,和其他的嵌入模型选项一起。 如果你想本地生成嵌入,我们推荐通过 [Ollama](../model-providers/top-level/ollama.md#嵌入模型) 使用 `nomic-embed-text` 。 @@ -23,7 +23,7 @@ sidebar_position: 3 { "embeddingsProvider": { "provider": "voyage", - "model": "voyage-code-2", + "model": "voyage-code-3", "apiKey": "" } } diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/build-your-own-slash-command.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/build-your-own-slash-command.md index 755bb2b14..ccf367094 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/build-your-own-slash-command.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/build-your-own-slash-command.md @@ -44,9 +44,12 @@ export function modifyConfig(config: Config): Config { name: "commit", description: "Write a commit message", run: async function* (sdk) { - const diff = await sdk.ide.getDiff(); + // getDiff 函数接受一个布尔参数,该参数指示是否 + // 在 diff 中包含未暂存的更改。 + const diff = await sdk.ide.getDiff(false); // 传递 false 以排除未暂存的更改 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, }, diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/custom-code-rag.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/custom-code-rag.md index 118e7945d..311d20d34 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/custom-code-rag.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/custom-code-rag.md @@ -4,7 +4,7 @@ ## 步骤 1 :选择嵌入模型 -如果可能,我们推荐使用 [`voyage-code-2`](https://docs.voyageai.com/docs/embeddings) ,它将给出最准确的答案,关于任何已存的代码嵌入模型。你可以在 [这里](https://dash.voyageai.com/api-keys) 获取 API key 。因为他门的 API 是 [OpenAI-兼容的](https://docs.voyageai.com/reference/embeddings-api) ,你可以使用任何 OpenAI 客户端换出 URL 。 +如果可能,我们推荐使用 [`voyage-code-3`](https://docs.voyageai.com/docs/embeddings) ,它将给出最准确的答案,关于任何已存的代码嵌入模型。你可以在 [这里](https://dash.voyageai.com/api-keys) 获取 API key 。因为他门的 API 是 [OpenAI-兼容的](https://docs.voyageai.com/reference/embeddings-api) ,你可以使用任何 OpenAI 客户端换出 URL 。 ## 步骤 2 :选择向量模型 @@ -16,7 +16,7 @@ 大多数嵌入模型只能一次处理有限的文本数量。为了解决这个问题,我们 "分块" 我们的代码到较小的部分。 -如果你使用 `voyage-code-2` ,它可以有最大 16,000 token 上下文长度,足够容纳大多数文件。这意味着,在开始的时候,你可以使用更朴素的策略避免超过限制。为了最简单到最综合,你可以使用 3 分块策略: +如果你使用 `voyage-code-3` ,它可以有最大 16,000 token 上下文长度,足够容纳大多数文件。这意味着,在开始的时候,你可以使用更朴素的策略避免超过限制。为了最简单到最综合,你可以使用 3 分块策略: 1. 截断文件,当它超过上下文长度:在这种情况下,你总是每个文件有 1 个分块。 2. 拆分文件到一个固定长度的分块:从文件的最上面开始,添加你当前分块的行,直到它到达限制,然后开始一个新的分块。 @@ -42,7 +42,7 @@ from lancedb.embeddings import get_registry db = lancedb.connect("/tmp/db") func = get_registry().get("openai").create( - name="voyage-code-2", + name="voyage-code-3", base_url="https://api.voyageai.com/v1/", api_key=os.environ["VOYAGE_API_KEY"], ) @@ -50,7 +50,7 @@ func = get_registry().get("openai").create( class CodeChunks(LanceModel): filename: str text: str = func.SourceField() - # 1536 is the embedding dimension of the `voyage-code-2` model. + # 1536 is the embedding dimension of the `voyage-code-3` model. vector: Vector(1536) = func.VectorField() table = db.create_table("code_chunks", schema=CodeChunks, mode="overwrite") diff --git a/docs/package-lock.json b/docs/package-lock.json index c2485bdf7..9da26a803 100644 --- a/docs/package-lock.json +++ b/docs/package-lock.json @@ -10597,9 +10597,9 @@ } }, "node_modules/nanoid": { - "version": "3.3.7", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.7.tgz", - "integrity": "sha512-eSRppjcPIatRIMC1U6UngP8XFcz8MQWGQdt1MTBQ7NaAmvXDfvNxbvWV3x2y6CdEUciCSsDHDQZbhYaB8QEo2g==", + "version": "3.3.8", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.8.tgz", + "integrity": "sha512-WNLf5Sd8oZxOm+TzppcYk8gVOgP+l58xNy58D0nbUnOxOWRWvlcCV4kUF7ltmI6PsrLl/BgKEyS4mqsGChFN0w==", "funding": [ { "type": "github", diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinueActionPromote.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinueActionPromote.kt new file mode 100644 index 000000000..ae26033e5 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinueActionPromote.kt @@ -0,0 +1,25 @@ +package com.github.continuedev.continueintellijextension.actions + +import com.github.continuedev.continueintellijextension.autocomplete.AcceptAutocompleteAction +import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings +import com.intellij.openapi.actionSystem.ActionPromoter +import com.intellij.openapi.actionSystem.AnAction +import com.intellij.openapi.actionSystem.DataContext +import com.intellij.openapi.components.ServiceManager +import org.jetbrains.annotations.NotNull + +class ContinueActionPromote : ActionPromoter { + + override fun promote(@NotNull actions: List, @NotNull context: DataContext): List? { + + if (actions.none { it is AcceptAutocompleteAction }) { + return null + } else { + val settings = ServiceManager.getService(ContinueExtensionSettings::class.java) + if (!settings.continueState.showIDECompletionSideBySide) { + return null; + } + return actions.filterIsInstance() + } + } +} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt index 777df65ce..d48552375 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt @@ -98,8 +98,7 @@ class AutocompleteService(private val project: Project) { if (shouldRenderCompletion(finalTextToInsert, column, lineLength, editor)) { renderCompletion(editor, offset, finalTextToInsert) - pendingCompletion = pendingCompletion?.copy(text = finalTextToInsert) - + pendingCompletion = PendingCompletion(editor, offset, completionId, finalTextToInsert) // Hide auto-popup // AutoPopupController.getInstance(project).cancelAllRequests() } @@ -152,8 +151,8 @@ class AutocompleteService(private val project: Project) { return } if (isInjectedFile(editor)) return - // Don't render completions when code completion dropdown is visible - if (!autocompleteLookupListener.isLookupEmpty()) { + // Skip rendering completions if the code completion dropdown is already visible and the IDE completion side-by-side setting is disabled + if (shouldSkipRender(ServiceManager.getService(ContinueExtensionSettings::class.java))) { return } @@ -210,6 +209,10 @@ class AutocompleteService(private val project: Project) { } } + private fun shouldSkipRender(settings: ContinueExtensionSettings) = + !settings.continueState.showIDECompletionSideBySide && !autocompleteLookupListener.isLookupEmpty() + + private fun splitKeepingDelimiters(input: String, delimiterPattern: String = "\\s+"): List { val initialSplit = input.split("(?<=$delimiterPattern)|(?=$delimiterPattern)".toRegex()) .filter { it.isNotEmpty() } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt index 2cf51b5de..ce548e5f5 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt @@ -32,6 +32,7 @@ class ContinueSettingsComponent : DumbAware { val enableContinueTeamsBeta: JCheckBox = JCheckBox("Enable Continue for Teams Beta") val enableOSR: JCheckBox = JCheckBox("Enable Off-Screen Rendering") val displayEditorTooltip: JCheckBox = JCheckBox("Display Editor Tooltip") + val showIDECompletionSideBySide: JCheckBox = JCheckBox("Show IDE completions side-by-side") init { val constraints = GridBagConstraints() @@ -63,6 +64,8 @@ class ContinueSettingsComponent : DumbAware { constraints.gridy++ panel.add(displayEditorTooltip, constraints) constraints.gridy++ + panel.add(showIDECompletionSideBySide, constraints) + constraints.gridy++ // Add a "filler" component that takes up all remaining vertical space constraints.weighty = 1.0 @@ -94,6 +97,7 @@ open class ContinueExtensionSettings : PersistentStateComponent + messages.MyBundle diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/DiffStreamTest.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/DiffStreamTest.kt new file mode 100644 index 000000000..eecb0cc03 --- /dev/null +++ b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/DiffStreamTest.kt @@ -0,0 +1,25 @@ +package com.github.continuedev.continueintellijextension + +import com.github.continuedev.continueintellijextension.editor.DiffStreamHandler +import com.github.continuedev.continueintellijextension.editor.DiffStreamService +import com.intellij.openapi.components.service +import com.intellij.openapi.editor.impl.ImaginaryEditor +import com.intellij.testFramework.TestDataPath +import com.intellij.testFramework.fixtures.BasePlatformTestCase + +@TestDataPath("\$CONTENT_ROOT/src/test/testData") +class DiffStreamTest : BasePlatformTestCase() { + fun `test getAllInlaysForEditor`() { + myFixture.configureByText("index.ts", "console.log('Hello World!');") + val editor = ImaginaryEditor(myFixture.project, myFixture.editor.document) + + val diffStreamService = project.service() + val diffStreamHandler = DiffStreamHandler(project, editor, 0, 1, { -> }, { -> }) + + diffStreamService.register(diffStreamHandler, editor) + + diffStreamHandler.streamDiffLinesToEditor() + + assertEquals(editor.document.text, myFixture.file.text) + } +} \ No newline at end of file diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 36fe771da..c3b8336a5 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -1,7 +1,8 @@ { + "$schema": "https://json-schema.org/draft/2020-12/schema", "title": "config.json", - "$ref": "#/definitions/SerializedContinueConfig", - "definitions": { + "$ref": "#/$defs/SerializedContinueConfig", + "$defs": { "BaseCompletionOptions": { "title": "BaseCompletionOptions", "type": "object", @@ -154,7 +155,7 @@ "clientCertificate": { "title": "Client Certificate", "description": "Client certificate to use when making the HTTP request", - "$ref": "#/definitions/ClientCertificateOptions" + "$ref": "#/$defs/ClientCertificateOptions" } } }, @@ -208,7 +209,8 @@ "kindo", "moonshot", "siliconflow", - "function-network" + "function-network", + "scaleway" ], "markdownEnumDescriptions": [ "### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/openai)", @@ -248,7 +250,8 @@ "### Secure AI management software that helps enterprises adopt and manage AI across their workforce. To get started, obtain an API key from [the Kindo console](https://app.kindo.ai/settings/api), and see the [website](https://app.kindo.ai//)", "### Moonshot\nTo get started with Moonshot AI, obtain your API key from [Moonshot AI](https://platform.moonshot.cn/). Moonshot AI provides high-quality large language models with competitive pricing.\n> [Reference](https://platform.moonshot.cn/docs/api)", "### SiliconFlow\nTo get started with SiliconFlow, obtain your API key from [SiliconCloud](https://cloud.siliconflow.cn/account/ak). SiliconCloud provides cost-effective GenAI services based on excellent open source basic models.\n> [Models](https://siliconflow.cn/zh-cn/models)", - "### Function Network offers private, affordable user-owned AI\nTo get started with Function Network, obtain your API key from [Function Network](https://www.function.network/join-waitlist). Function Network provides a variety of models for chat, completion, and embeddings." + "### Function Network offers private, affordable user-owned AI\nTo get started with Function Network, obtain your API key from [Function Network](https://www.function.network/join-waitlist). Function Network provides a variety of models for chat, completion, and embeddings.", + "### Scaleway\n Generative APIs are serverless endpoints for the most popular AI models.\nHosted in European data centers and priced competitively per million tokens used, models served by Scaleway are ideal for users requiring low latency, full data privacy, and 100% compliance with EU AI Act. To get access to the Scaleway Generative APIs, read the [Quickstart guide](https://www.scaleway.com/en/docs/ai-data/generative-apis/quickstart/) and get a [valid API key](https://www.scaleway.com/en/docs/identity-and-access-management/iam/how-to/create-api-keys/)." ], "type": "string" }, @@ -386,7 +389,7 @@ }, "allOf": [ { - "$ref": "#/definitions/BaseCompletionOptions" + "$ref": "#/$defs/BaseCompletionOptions" } ] }, @@ -408,7 +411,7 @@ }, "allOf": [ { - "$ref": "#/definitions/RequestOptions" + "$ref": "#/$defs/RequestOptions" } ] }, @@ -476,7 +479,8 @@ "sambanova", "nebius", "xAI", - "kindo" + "kindo", + "scaleway" ] } }, @@ -1252,14 +1256,52 @@ "properties": { "model": { "enum": [ + "Qwen/QwQ-32B-Preview", "Qwen/Qwen2.5-Coder-32B-Instruct", "Qwen/Qwen2.5-Coder-7B-Instruct", - "Pro/Qwen/Qwen2.5-Coder-7B-Instruct" + "Pro/Qwen/Qwen2.5-Coder-7B-Instruct", + "Tencent/Hunyuan-A52B-Instruct", + "nvidia/Llama-3.1-Nemotron-70B-Instruct", + "Qwen/Qwen2-VL-72B-Instruct", + "TeleAI/TeleMM", + "deepseek-ai/DeepSeek-V2.5" ] } } } }, + { + "if": { + "properties": { + "provider": { + "enum": ["scaleway"] + } + }, + "required": ["provider"] + }, + "then": { + "properties": { + "model": { + "anyOf": [ + { + "enum": [ + "llama-3.1-8b-instruct", + "llama-3.1-70b-instruct", + "mistral-nemo-instruct-2407", + "qwen2.5-coder-32b-instruct", + "pixtral-12b-2409" + ] + }, + { + "type": "string" + } + ], + "markdownDescription": "Select a pre-defined option, or find the exact model string from Scaleway [here](https://www.scaleway.com/en/docs/ai-data/generative-apis/reference-content/supported-models/).", + "x-intellij-html-description": "Select a pre-defined option, or find the exact model string from Scaleway here." + } + } + } + }, { "if": { "properties": { @@ -2188,7 +2230,7 @@ }, "allOf": [ { - "$ref": "#/definitions/RequestOptions" + "$ref": "#/$defs/RequestOptions" } ] } @@ -2410,7 +2452,7 @@ ], "type": "array", "items": { - "$ref": "#/definitions/ModelDescription" + "$ref": "#/$defs/ModelDescription" } }, "systemMessage": { @@ -2432,7 +2474,7 @@ }, "allOf": [ { - "$ref": "#/definitions/BaseCompletionOptions" + "$ref": "#/$defs/BaseCompletionOptions" } ] }, @@ -2441,7 +2483,7 @@ "description": "Default request options for all fetch requests from models and context providers. These will be overriden by any model-specific request options.", "allOf": [ { - "$ref": "#/definitions/RequestOptions" + "$ref": "#/$defs/RequestOptions" } ] }, @@ -2452,7 +2494,7 @@ "default": [], "type": "array", "items": { - "$ref": "#/definitions/SlashCommand" + "$ref": "#/$defs/SlashCommand" } }, "customCommands": { @@ -2468,7 +2510,7 @@ ], "type": "array", "items": { - "$ref": "#/definitions/CustomCommand" + "$ref": "#/$defs/CustomCommand" } }, "contextProviders": { @@ -2478,7 +2520,7 @@ "default": [], "type": "array", "items": { - "$ref": "#/definitions/ContextProviderWithParams" + "$ref": "#/$defs/ContextProviderWithParams" } }, "userToken": { @@ -2527,7 +2569,8 @@ "watsonx", "lmstudio", "siliconflow", - "function-network" + "function-network", + "scaleway" ] }, "model": { @@ -2542,7 +2585,7 @@ "requestOptions": { "title": "Request Options", "description": "Request options to be used in any fetch requests made by the embeddings provider", - "$ref": "#/definitions/RequestOptions" + "$ref": "#/$defs/RequestOptions" }, "maxChunkSize": { "title": "Maximum Chunk Size", @@ -2561,7 +2604,7 @@ "region": { "title": "Region", "description": "The region where the model is hosted", - "$ref": "#/definitions/ModelDescription/properties/region" + "$ref": "#/$defs/ModelDescription/properties/region" }, "profile": { "title": "Profile", @@ -2675,7 +2718,8 @@ "rerank-english-v3.0", "rerank-multilingual-v3.0", "rerank-english-v2.0", - "rerank-multilingual-v2.0" + "rerank-multilingual-v2.0", + "rerank-v3.5" ] }, "apiBase": { @@ -2830,12 +2874,12 @@ }, "oneOf": [ { - "$ref": "#/definitions/ModelDescription" + "$ref": "#/$defs/ModelDescription" }, { "type": "array", "items": { - "$ref": "#/definitions/ModelDescription" + "$ref": "#/$defs/ModelDescription" } } ] @@ -2923,6 +2967,11 @@ "x-intellij-html-description": "If set to true, a scrollbar will be displayed in the chat window to navigate through messages.", "default": false, "type": "boolean" + }, + "codeWrap": { + "type": "boolean", + "description": "If set to true, code in pre blocks will wrap.", + "default": false } } }, @@ -2985,7 +3034,7 @@ "items": { "allOf": [ { - "$ref": "#/definitions/ContextProviderWithParams" + "$ref": "#/$defs/ContextProviderWithParams" }, { "properties": { diff --git a/extensions/vscode/e2e/TestUtils.ts b/extensions/vscode/e2e/TestUtils.ts index 05e4bc5d1..8b151e517 100644 --- a/extensions/vscode/e2e/TestUtils.ts +++ b/extensions/vscode/e2e/TestUtils.ts @@ -1,3 +1,4 @@ +import { expect } from "chai"; import { WebElement } from "vscode-extension-tester"; export class TestUtils { @@ -24,4 +25,38 @@ export class TestUtils { throw new Error(`Element not found after ${timeout}ms timeout`); } + + public static async expectNoElement( + locatorFn: () => Promise, + timeout: number = 1000, + interval: number = 200, + ): Promise { + const startTime = Date.now(); + let elementFound = false; + + while (Date.now() - startTime < timeout) { + try { + const element = await locatorFn(); + if (element) { + elementFound = true; + break; + } + } catch (e) { + // Continue if there's an error (element not found) + } + await new Promise((resolve) => setTimeout(resolve, interval)); + } + + expect(elementFound).to.be.false; + } + + public static generateTestMessagePair(id: number = 0): { + userMessage: string; + llmResponse: string; + } { + return { + userMessage: `TEST_USER_MESSAGE_${id}`, + llmResponse: `TEST_LLM_RESPONSE_${id}`, + }; + } } diff --git a/extensions/vscode/e2e/actions/GUI.actions.ts b/extensions/vscode/e2e/actions/GUI.actions.ts index 7a6e76c04..b4afcd1c9 100644 --- a/extensions/vscode/e2e/actions/GUI.actions.ts +++ b/extensions/vscode/e2e/actions/GUI.actions.ts @@ -1,4 +1,5 @@ import { + Key, WebDriver, WebElement, WebView, @@ -56,4 +57,21 @@ export class GUIActions { await dropdownOption.click(); }; + + public static async sendMessage({ + view, + message, + inputFieldIndex, + }: { + view: WebView; + message: string; + inputFieldIndex: number; + }) { + const editor = await GUISelectors.getMessageInputFieldAtIndex( + view, + inputFieldIndex, + ); + await editor.sendKeys(message); + await editor.sendKeys(Key.ENTER); + } } diff --git a/extensions/vscode/e2e/selectors/GUI.selectors.ts b/extensions/vscode/e2e/selectors/GUI.selectors.ts index b4c88aacb..c73b2c739 100644 --- a/extensions/vscode/e2e/selectors/GUI.selectors.ts +++ b/extensions/vscode/e2e/selectors/GUI.selectors.ts @@ -6,8 +6,16 @@ export class GUISelectors { return view.findWebElement(By.xpath("//*[contains(text(), 'Quickly')]")); } - public static getTipTapEditor(view: WebView) { - return view.findWebElement(By.className("tiptap")); + public static getMessageInputFields(view: WebView) { + return view.findWebElements(By.className("tiptap")); + } + + public static async getMessageInputFieldAtIndex( + view: WebView, + index: number, + ) { + const elements = await view.findWebElements(By.className("tiptap")); + return elements[index]; } public static getAllIframes(driver: WebDriver) { @@ -26,6 +34,19 @@ export class GUISelectors { return SelectorUtils.getElementByDataTestId(view, "model-select-button"); } + public static getNthHistoryTableRow(view: WebView, index: number) { + return SelectorUtils.getElementByDataTestId(view, `history-row-${index}`); + } + + public static getNthMessageDeleteButton(view: WebView, index: number) { + const adjustedIndex = 1 + index * 2; + + return SelectorUtils.getElementByDataTestId( + view, + `delete-button-${adjustedIndex}`, + ); + } + public static getModelDropdownOption(view: WebView, option: string) { return view.findWebElement( By.xpath(`//*[@role="listbox"]//*[contains(text(), "${option}")]`), @@ -37,4 +58,12 @@ export class GUISelectors { By.xpath(`//*[@class="thread-message"]//*[contains(text(), "${text}")]`), ); } + + public static getHistoryNavButton(view: WebView) { + return SelectorUtils.getElementByAriaLabel(view, "View History"); + } + + public static getNewSessionNavButton(view: WebView) { + return SelectorUtils.getElementByAriaLabel(view, "New Session"); + } } diff --git a/extensions/vscode/e2e/selectors/SelectorUtils.ts b/extensions/vscode/e2e/selectors/SelectorUtils.ts index 243e1bf44..7a7067b05 100644 --- a/extensions/vscode/e2e/selectors/SelectorUtils.ts +++ b/extensions/vscode/e2e/selectors/SelectorUtils.ts @@ -13,4 +13,17 @@ export class SelectorUtils { ): Promise { return view.findWebElement(By.css(`[data-testid='${testId}']`)); } + + /** + * Finds a web element by its aria-label attribute within a WebView. + * @param view - The WebView to search within. + * @param ariaLabel - The aria-label value to search for. + * @returns A promise that resolves to the WebElement found. + */ + public static getElementByAriaLabel( + view: WebView, + ariaLabel: string, + ): Promise { + return view.findWebElement(By.css(`[aria-label='${ariaLabel}']`)); + } } diff --git a/extensions/vscode/e2e/tests/GUI.test.ts b/extensions/vscode/e2e/tests/GUI.test.ts index 761964623..d954238c9 100644 --- a/extensions/vscode/e2e/tests/GUI.test.ts +++ b/extensions/vscode/e2e/tests/GUI.test.ts @@ -3,20 +3,26 @@ import { WebView, WebDriver, VSBrowser, + Key, } from "vscode-extension-tester"; import { expect } from "chai"; import { GUIActions } from "../actions/GUI.actions"; import { GUISelectors } from "../selectors/GUI.selectors"; import { TestUtils } from "../TestUtils"; +const DEFAULT_TIMEOUT = 30_000; + describe("GUI Test", () => { let view: WebView; let driver: WebDriver; before(async function () { - this.timeout(10000000); - + this.timeout(DEFAULT_TIMEOUT); await VSBrowser.instance.openResources("e2e/test-continue"); + }); + + beforeEach(async function () { + this.timeout(DEFAULT_TIMEOUT); await GUIActions.openGui(); @@ -24,35 +30,223 @@ describe("GUI Test", () => { driver = view.getDriver(); await GUIActions.switchToReactIframe(driver); + await GUIActions.selectModelFromDropdown(view, "TEST LLM"); + // await new Promise((res) => { - // setTimeout(res, 10000000); + // setTimeout(res, DEFAULT_TIMEOUT); // }); }); - after(async () => { + afterEach(async function () { + this.timeout(DEFAULT_TIMEOUT); + await view.switchBack(); await new EditorView().closeAllEditors(); }); - it("should display correct panel description", async () => { - const description = await GUISelectors.getDescription(view); + describe("Onboarding", () => { + it("should display correct panel description", async () => { + const description = await GUISelectors.getDescription(view); - expect(await description.getText()).has.string( - "Quickly get up and running using our API keys.", - ); - }).timeout(20_000); + expect(await description.getText()).has.string( + "Quickly get up and running using our API keys.", + ); + }).timeout(DEFAULT_TIMEOUT); + }); - it("should allow typing text in the editor", async () => { - await GUIActions.selectModelFromDropdown(view, "Mock"); - await GUIActions.selectModelFromDropdown(view, "TEST LLM"); + describe("Chat", () => { + it("Can submit message by pressing enter", async () => { + const [messageInput] = await GUISelectors.getMessageInputFields(view); + const messagePair = TestUtils.generateTestMessagePair(); + await messageInput.sendKeys(messagePair.userMessage); + await messageInput.sendKeys(Key.ENTER); + await TestUtils.waitForElement(() => + GUISelectors.getThreadMessageByText(view, messagePair.llmResponse), + ); + }); - const tiptap = await GUISelectors.getTipTapEditor(view); + it("Can submit message by button click", async () => { + const [messageInput] = await GUISelectors.getMessageInputFields(view); + const messagePair = TestUtils.generateTestMessagePair(); + await messageInput.sendKeys(messagePair.userMessage); + (await GUISelectors.getSubmitInputButton(view)).click(); + await TestUtils.waitForElement(() => + GUISelectors.getThreadMessageByText(view, messagePair.llmResponse), + ); + }); - await tiptap.sendKeys("How are you?"); - (await GUISelectors.getSubmitInputButton(view)).click(); + it.only("Can delete messages", async () => { + const { userMessage: userMessage0, llmResponse: llmResponse0 } = + TestUtils.generateTestMessagePair(0); + await GUIActions.sendMessage({ + view, + message: userMessage0, + inputFieldIndex: 0, + }); + await TestUtils.waitForElement(() => + GUISelectors.getThreadMessageByText(view, llmResponse0), + ); - await TestUtils.waitForElement(() => - GUISelectors.getThreadMessageByText(view, "I'm fine"), - ); - }).timeout(20_000); + const { userMessage: userMessage1, llmResponse: llmResponse1 } = + TestUtils.generateTestMessagePair(1); + await GUIActions.sendMessage({ + view, + message: userMessage1, + inputFieldIndex: 1, + }); + await TestUtils.waitForElement(() => + GUISelectors.getThreadMessageByText(view, llmResponse1), + ); + + const { userMessage: userMessage2, llmResponse: llmResponse2 } = + TestUtils.generateTestMessagePair(2); + await GUIActions.sendMessage({ + view, + message: userMessage2, + inputFieldIndex: 2, + }); + await TestUtils.waitForElement(() => + GUISelectors.getThreadMessageByText(view, llmResponse2), + ); + + GUISelectors.getThreadMessageByText(view, llmResponse1); + await (await GUISelectors.getNthMessageDeleteButton(view, 1)).click(); + await TestUtils.expectNoElement(() => + GUISelectors.getThreadMessageByText(view, llmResponse1), + ); + + GUISelectors.getThreadMessageByText(view, llmResponse0); + await (await GUISelectors.getNthMessageDeleteButton(view, 0)).click(); + await TestUtils.expectNoElement(() => + GUISelectors.getThreadMessageByText(view, llmResponse0), + ); + + GUISelectors.getThreadMessageByText(view, llmResponse2); + await (await GUISelectors.getNthMessageDeleteButton(view, 0)).click(); + await TestUtils.expectNoElement(() => + GUISelectors.getThreadMessageByText(view, llmResponse2), + ); + }).timeout(DEFAULT_TIMEOUT); + + it("Can edit messages", async () => { + const { userMessage: userMessage0, llmResponse: llmResponse0 } = + TestUtils.generateTestMessagePair(0); + await GUIActions.sendMessage({ + view, + message: userMessage0, + inputFieldIndex: 0, + }); + await TestUtils.waitForElement(() => + GUISelectors.getThreadMessageByText(view, llmResponse0), + ); + + const { userMessage: userMessage1, llmResponse: llmResponse1 } = + TestUtils.generateTestMessagePair(1); + await GUIActions.sendMessage({ + view, + message: userMessage1, + inputFieldIndex: 1, + }); + await TestUtils.waitForElement(() => + GUISelectors.getThreadMessageByText(view, llmResponse1), + ); + + const { userMessage: userMessage2, llmResponse: llmResponse2 } = + TestUtils.generateTestMessagePair(2); + await GUIActions.sendMessage({ + view, + message: userMessage2, + inputFieldIndex: 2, + }); + await TestUtils.waitForElement(() => + GUISelectors.getThreadMessageByText(view, llmResponse2), + ); + + const secondInputField = await GUISelectors.getMessageInputFieldAtIndex( + view, + 1, + ); + await secondInputField.clear(); + + const { userMessage: userMessage3, llmResponse: llmResponse3 } = + TestUtils.generateTestMessagePair(3); + + await GUIActions.sendMessage({ + view, + message: userMessage3, + inputFieldIndex: 1, + }); + await GUISelectors.getThreadMessageByText(view, llmResponse0); + + await TestUtils.waitForElement(() => + GUISelectors.getThreadMessageByText(view, llmResponse3), + ); + await Promise.all([ + TestUtils.expectNoElement(() => + GUISelectors.getThreadMessageByText(view, llmResponse1), + ), + TestUtils.expectNoElement(() => + GUISelectors.getThreadMessageByText(view, llmResponse2), + ), + ]); + }).timeout(DEFAULT_TIMEOUT); + }); + + describe("Chat Paths", () => { + it("chat → history → chat", async () => { + const messagePair1 = TestUtils.generateTestMessagePair(1); + await GUIActions.sendMessage({ + view, + message: messagePair1.userMessage, + inputFieldIndex: 0, + }); + await TestUtils.waitForElement(() => + GUISelectors.getThreadMessageByText(view, messagePair1.llmResponse), + ); + + const messagePair2 = TestUtils.generateTestMessagePair(2); + await GUIActions.sendMessage({ + view, + message: messagePair2.userMessage, + inputFieldIndex: 1, + }); + await TestUtils.waitForElement(() => + GUISelectors.getThreadMessageByText(view, messagePair2.llmResponse), + ); + + /** + * SWITCHING BACK AND FORTH + * We are switching back and forth here because the history is broken. + * It only updates once a another chat is opened, so we need to open a + * different chat first. + */ + await view.switchBack(); + await (await GUISelectors.getHistoryNavButton(view)).click(); + await GUIActions.switchToReactIframe(driver); + + await (await GUISelectors.getNthHistoryTableRow(view, 0)).click(); + + await view.switchBack(); + await (await GUISelectors.getHistoryNavButton(view)).click(); + /** + * END OF SWITCHING BACK AND FORTH + */ + + await GUIActions.switchToReactIframe(driver); + await (await GUISelectors.getNthHistoryTableRow(view, 0)).click(); + + await GUISelectors.getThreadMessageByText(view, messagePair1.llmResponse); + await GUISelectors.getThreadMessageByText(view, messagePair2.llmResponse); + + const messagePair3 = TestUtils.generateTestMessagePair(3); + await GUIActions.sendMessage({ + view, + message: messagePair3.userMessage, + inputFieldIndex: 2, + }); + await TestUtils.waitForElement(() => + GUISelectors.getThreadMessageByText(view, messagePair3.llmResponse), + ); + }).timeout(DEFAULT_TIMEOUT); + }); }); diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index ea5966c13..c3d015969 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,14 +1,15 @@ { "name": "continue", - "version": "0.9.240", + "version": "0.9.248", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.240", + "version": "0.9.248", "license": "Apache-2.0", "dependencies": { + "@continuedev/fetch": "^1.0.3", "@electron/rebuild": "^3.2.10", "@reduxjs/toolkit": "^1.9.3", "@types/node-fetch": "^2.6.11", @@ -76,6 +77,7 @@ "cargo-cp-artifact": "^0.1", "chai": "^4.5.0", "esbuild": "0.17.19", + "esbuild-visualizer": "^0.6.0", "eslint": "^8.28.0", "glob": "^8.0.3", "json-schema-to-typescript": "^12.0.0", @@ -101,7 +103,9 @@ "@aws-sdk/client-sagemaker-runtime": "^3.621.0", "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.13", + "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", + "@continuedev/openai-adapters": "^1.0.10", "@modelcontextprotocol/sdk": "^1.0.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", @@ -134,7 +138,7 @@ "node-html-markdown": "^1.3.0", "ollama": "^0.4.6", "onnxruntime-node": "1.14.0", - "openai": "^4.20.1", + "openai": "^4.76.0", "p-limit": "^6.1.0", "partial-json": "^0.1.7", "pg": "^8.11.3", @@ -678,6 +682,26 @@ "node": ">=14.21.3" } }, + "node_modules/@continuedev/config-types": { + "version": "1.0.13", + "resolved": "https://registry.npmjs.org/@continuedev/config-types/-/config-types-1.0.13.tgz", + "integrity": "sha512-5Qmy2x58uhW1GYknypFT/7iwxEJSbt8gMgfQReV7d6xjbJ09ISOTki3hIfCilKrTCo0gIY6pzKEfCoQkUTEi6Q==", + "dependencies": { + "zod": "^3.23.8" + } + }, + "node_modules/@continuedev/fetch": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.3.tgz", + "integrity": "sha512-cGNCUEVnDfC+3O/n1PV+oYhS5yZRLR1Q7Njg929kVbA8kRHe5a3VdKINfFzWdKprOU4wipsXSliciZHCpbJJ9g==", + "dependencies": { + "@continuedev/config-types": "^1.0.5", + "follow-redirects": "^1.15.6", + "http-proxy-agent": "^7.0.2", + "https-proxy-agent": "^7.0.5", + "node-fetch": "^3.3.2" + } + }, "node_modules/@electron/node-gyp": { "version": "10.2.0-electron.1", "resolved": "git+ssh://git@github.com/electron/node-gyp.git#06b29aafb7708acef8b3669835c8a7857ebc92d2", @@ -5327,6 +5351,23 @@ "@esbuild/win32-x64": "0.17.19" } }, + "node_modules/esbuild-visualizer": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/esbuild-visualizer/-/esbuild-visualizer-0.6.0.tgz", + "integrity": "sha512-oNK3JAhC7+re93VTtUdWJKTDVnA2qXPAjCAoaw9OxEFUXztszw3kcaK46u1U790T8FdUBAWv6F9Xt59P8nJCVA==", + "dev": true, + "dependencies": { + "open": "^8.4.0", + "picomatch": "^2.3.1", + "yargs": "^17.6.2" + }, + "bin": { + "esbuild-visualizer": "dist/bin/cli.js" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/escalade": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", @@ -14863,6 +14904,14 @@ "funding": { "url": "https://github.com/sponsors/sindresorhus" } + }, + "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" + } } } } diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 9cf7db2b1..755185f78 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "0.9.241", + "version": "0.9.242", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" @@ -602,6 +602,7 @@ "vscode:prepublish": "npm run esbuild-base -- --minify", "esbuild": "npm run esbuild-base -- --sourcemap", "esbuild-watch": "npm run esbuild-base -- --sourcemap --watch", + "esbuild:visualize": "esbuild-visualizer --metadata ./build/meta.json --filename ./build/stats.html --open", "tsc": "tsc -p ./", "tsc:check": "tsc -p ./ --noEmit", "tsc-watch": "tsc -watch -p ./", @@ -619,6 +620,7 @@ "build-debug:rust": "npm run build:rust --", "build-release:rust": "npm run build:rust -- --release", "e2e:compile": "tsc -p ./tsconfig.e2e.json", + "e2e:build": "npm --prefix ../../gui run build && npm run package", "e2e:create-storage": "mkdir -p ./e2e/storage", "e2e:get-chromedriver": "extest get-chromedriver --storage ./e2e/storage", "e2e:get-vscode": "extest get-vscode --storage ./e2e/storage", @@ -627,7 +629,7 @@ "e2e:install-vsix": "extest install-vsix -f ./e2e/vsix/continue.vsix --extensions_dir ./e2e/.test-extensions --storage ./e2e/storage", "e2e:test": "extest run-tests './e2e/_output/tests/*.test.js' --code_settings settings.json --extensions_dir ./e2e/.test-extensions --storage ./e2e/storage", "e2e:clean": "rm -rf ./e2e/_output", - "e2e:all": "npm run e2e:compile && npm run e2e:create-storage && npm run e2e:get-chromedriver && npm run e2e:get-vscode && npm run e2e:sign-vscode && npm run e2e:copy-vsix && npm run e2e:install-vsix && CONTINUE_GLOBAL_DIR=e2e/test-continue npm run e2e:test && npm run e2e:clean", + "e2e:all": "npm run e2e:build && npm run e2e:compile && npm run e2e:create-storage && npm run e2e:get-chromedriver && npm run e2e:get-vscode && npm run e2e:sign-vscode && npm run e2e:copy-vsix && npm run e2e:install-vsix && CONTINUE_GLOBAL_DIR=e2e/test-continue npm run e2e:test && npm run e2e:clean", "e2e:quick": "npm run e2e:compile && CONTINUE_GLOBAL_DIR=e2e/test-continue npm run e2e:test && npm run e2e:clean", "e2e:ci": "npm run e2e:compile && npm run e2e:create-storage && npm run e2e:get-chromedriver && npm run e2e:get-vscode && npm run e2e:copy-vsix && npm run e2e:install-vsix && CONTINUE_GLOBAL_DIR=e2e/test-continue npm run e2e:test" }, @@ -651,6 +653,7 @@ "cargo-cp-artifact": "^0.1", "chai": "^4.5.0", "esbuild": "0.17.19", + "esbuild-visualizer": "^0.6.0", "eslint": "^8.28.0", "glob": "^8.0.3", "json-schema-to-typescript": "^12.0.0", @@ -663,6 +666,7 @@ "vscode-extension-tester": "^8.10.0" }, "dependencies": { + "@continuedev/fetch": "^1.0.3", "@electron/rebuild": "^3.2.10", "@reduxjs/toolkit": "^1.9.3", "@types/node-fetch": "^2.6.11", diff --git a/extensions/vscode/scripts/esbuild.js b/extensions/vscode/scripts/esbuild.js index 7e367bfaa..bac602d79 100644 --- a/extensions/vscode/scripts/esbuild.js +++ b/extensions/vscode/scripts/esbuild.js @@ -20,6 +20,31 @@ const esbuildConfig = { inject: ["./scripts/importMetaUrl.js"], define: { "import.meta.url": "importMetaUrl" }, supported: { "dynamic-import": false }, + metafile: true, + plugins: [ + { + name: "on-end-plugin", + setup(build) { + build.onEnd((result) => { + if (result.errors.length > 0) { + console.error("Build failed with errors:", result.errors); + throw new Error(result.errors); + } else { + try { + const fs = require("fs"); + fs.writeFileSync( + "./build/meta.json", + JSON.stringify(result.metafile, null, 2), + ); + } catch (e) { + console.error("Failed to write esbuild meta file", e); + } + console.log("VS Code Extension esbuild complete"); // used verbatim in vscode tasks to detect completion + } + }); + }, + }, + ], }; (async () => { @@ -30,5 +55,4 @@ const esbuildConfig = { } else { await esbuild.build(esbuildConfig); } - console.log("VS Code Extension esbuild complete"); // Used in task endpattern to signal completion -})(); \ No newline at end of file +})(); diff --git a/extensions/vscode/scripts/package.js b/extensions/vscode/scripts/package.js index 17594333e..35ad7d24f 100644 --- a/extensions/vscode/scripts/package.js +++ b/extensions/vscode/scripts/package.js @@ -15,8 +15,8 @@ if (!fs.existsSync("build")) { const isPreRelease = args.includes("--pre-release"); let command = isPreRelease - ? "npx vsce package --out ./build patch --pre-release --no-dependencies" // --yarn" - : "npx vsce package --out ./build patch --no-dependencies"; // --yarn"; + ? "npx vsce package --out ./build --pre-release --no-dependencies" // --yarn" + : "npx vsce package --out ./build --no-dependencies"; // --yarn"; if (target) { command += ` --target ${target}`; diff --git a/extensions/vscode/scripts/utils.js b/extensions/vscode/scripts/utils.js index 7d62fefa4..550d0246c 100644 --- a/extensions/vscode/scripts/utils.js +++ b/extensions/vscode/scripts/utils.js @@ -13,7 +13,7 @@ const continueDir = path.join(__dirname, "..", "..", ".."); function copyConfigSchema() { // Modify and copy for .continuerc.json const schema = JSON.parse(fs.readFileSync("config_schema.json", "utf8")); - schema.definitions.SerializedContinueConfig.properties.mergeBehavior = { + schema.$defs.SerializedContinueConfig.properties.mergeBehavior = { type: "string", enum: ["merge", "overwrite"], default: "merge", diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index f23f6dff2..3706cf79a 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -455,13 +455,16 @@ const getCommandsMap: ( hideGUI(); } else { void sidebar.webviewProtocol?.request( - "focusContinueInput", + "focusContinueInputWithNewSession", undefined, ); } } else { focusGUI(); - sidebar.webviewProtocol?.request("focusContinueInput", undefined); + sidebar.webviewProtocol?.request( + "focusContinueInputWithNewSession", + undefined, + ); void addHighlightedCodeToContext(sidebar.webviewProtocol); } }, diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 7d3368a76..de4a36d02 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -5,7 +5,7 @@ import { ConfigHandler } from "core/config/ConfigHandler"; import { controlPlaneEnv, EXTENSION_NAME } from "core/control-plane/env"; import { Core } from "core/core"; import { FromCoreProtocol, ToCoreProtocol } from "core/protocol"; -import { InProcessMessenger } from "core/util/messenger"; +import { InProcessMessenger } from "core/protocol/messenger"; import { getConfigJsonPath, getConfigTsPath } from "core/util/paths"; import { v4 as uuidv4 } from "uuid"; import * as vscode from "vscode"; diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 5133788ce..3f201f016 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -17,7 +17,7 @@ import { WEBVIEW_TO_CORE_PASS_THROUGH, } from "core/protocol/passThrough"; import { getBasename } from "core/util"; -import { InProcessMessenger, Message } from "core/util/messenger"; +import { InProcessMessenger, Message } from "core/protocol/messenger"; import * as vscode from "vscode"; import { stripImages } from "core/util/messageContent"; diff --git a/extensions/vscode/src/quickEdit/ContextProvidersQuickPick.ts b/extensions/vscode/src/quickEdit/ContextProvidersQuickPick.ts index 02521c2ae..1296a3466 100644 --- a/extensions/vscode/src/quickEdit/ContextProvidersQuickPick.ts +++ b/extensions/vscode/src/quickEdit/ContextProvidersQuickPick.ts @@ -1,5 +1,5 @@ +import { fetchwithRequestOptions } from "@continuedev/fetch"; import { ContinueConfig, IDE } from "core"; -import { fetchwithRequestOptions } from "core/util/fetchWithOptions"; import { QuickPickItem, window } from "vscode"; export async function getContextProviderItems({ diff --git a/extensions/vscode/src/webviewProtocol.ts b/extensions/vscode/src/webviewProtocol.ts index 17b72af8b..1fc383fae 100644 --- a/extensions/vscode/src/webviewProtocol.ts +++ b/extensions/vscode/src/webviewProtocol.ts @@ -4,12 +4,12 @@ import path from "path"; import { FromWebviewProtocol, ToWebviewProtocol } from "core/protocol"; import { WebviewMessengerResult } from "core/protocol/util"; import { extractMinimalStackTraceInfo } from "core/util/extractMinimalStackTraceInfo"; -import { Message } from "core/util/messenger"; +import { Message } from "core/protocol/messenger"; import { Telemetry } from "core/util/posthog"; import { v4 as uuidv4 } from "uuid"; import * as vscode from "vscode"; -import { IMessenger } from "../../../core/util/messenger"; +import { IMessenger } from "../../../core/protocol/messenger"; import { showFreeTrialLoginMessage } from "./util/messages"; import { getExtensionUri } from "./util/vscode"; @@ -33,7 +33,8 @@ export async function showTutorial() { } export class VsCodeWebviewProtocol - implements IMessenger { + implements IMessenger +{ listeners = new Map< keyof FromWebviewProtocol, ((message: Message) => any)[] @@ -127,7 +128,7 @@ export class VsCodeWebviewProtocol message = message.split("\n").filter((l: string) => l !== "")[1]; try { message = JSON.parse(message).message; - } catch { } + } catch {} if (message.includes("exceeded")) { message += " To keep using Continue, you can set up a local model or use your own API key."; @@ -181,7 +182,7 @@ export class VsCodeWebviewProtocol }); } - constructor(private readonly reloadConfig: () => void) { } + constructor(private readonly reloadConfig: () => void) {} invoke( messageType: T, data: FromWebviewProtocol[T][0], diff --git a/extensions/vscode/vsc-extension-quickstart.md b/extensions/vscode/vsc-extension-quickstart.md index 04a57fc6a..a77988101 100644 --- a/extensions/vscode/vsc-extension-quickstart.md +++ b/extensions/vscode/vsc-extension-quickstart.md @@ -1,42 +1,13 @@ -# Welcome to your VS Code Extension - -## What's in the folder - -* This folder contains all of the files necessary for your extension. -* `package.json` - this is the manifest file in which you declare your extension and command. - * The sample plugin registers a command and defines its title and command name. With this information VS Code can show the command in the command palette. It doesn’t yet need to load the plugin. -* `src/extension.ts` - this is the main file where you will provide the implementation of your command. - * The file exports one function, `activate`, which is called the very first time your extension is activated (in this case by executing the command). Inside the `activate` function we call `registerCommand`. - * We pass the function containing the implementation of the command as the second parameter to `registerCommand`. +# Welcome to the Continue Visual Studio Code Extension ## Get up and running straight away -* Press `F5` to open a new window with your extension loaded. -* Run your command from the command palette by pressing (`Ctrl+Shift+P` or `Cmd+Shift+P` on Mac) and typing `Hello World`. -* Set breakpoints in your code inside `src/extension.ts` to debug your extension. -* Find output from your extension in the debug console. +- Open the root of the continue repository in visual studio code +- Press `F5` to open a new window with your extension loaded. +- The continue in the launched vs code instance uses `extensions/.continue-debug` as configuration folder +- Find output from your extension in the debug console. ## Make changes -* You can relaunch the extension from the debug toolbar after changing code in `src/extension.ts`. -* You can also reload (`Ctrl+R` or `Cmd+R` on Mac) the VS Code window with your extension to load your changes. - -## Explore the API - -* You can open the full set of our API when you open the file `node_modules/@types/vscode/index.d.ts`. - -## Run tests - -* Open the debug viewlet (`Ctrl+Shift+D` or `Cmd+Shift+D` on Mac) and from the launch configuration dropdown pick `Extension Tests`. -* Press `F5` to run the tests in a new window with your extension loaded. -* See the output of the test result in the debug console. -* Make changes to `src/test/suite/extension.test.ts` or create new test files inside the `test/suite` folder. - * The provided test runner will only consider files matching the name pattern `**.test.ts`. - * You can create folders inside the `test` folder to structure your tests any way you want. - -## Go further - -* [Follow UX guidelines](https://code.visualstudio.com/api/ux-guidelines/overview) to create extensions that seamlessly integrate with VS Code's native interface and patterns. - * Reduce the extension size and improve the startup time by [bundling your extension](https://code.visualstudio.com/api/working-with-extensions/bundling-extension). - * [Publish your extension](https://code.visualstudio.com/api/working-with-extensions/publishing-extension) on the VS Code extension marketplace. - * Automate builds by setting up [Continuous Integration](https://code.visualstudio.com/api/working-with-extensions/continuous-integration). +- You can relaunch the extension from the debug toolbar after changing code. +- You can also reload (`Ctrl+R` or `Cmd+R` on Mac) the VS Code window with your extension to load your changes. diff --git a/gui/package-lock.json b/gui/package-lock.json index 91410e6df..ac5e3c351 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -9,7 +9,6 @@ "dependencies": { "@headlessui/react": "^1.7.17", "@heroicons/react": "^2.0.18", - "@monaco-editor/react": "^4.6.0", "@reduxjs/toolkit": "^2.3.0", "@tiptap/core": "^2.3.2", "@tiptap/extension-document": "^2.3.2", @@ -107,7 +106,9 @@ "@aws-sdk/client-sagemaker-runtime": "^3.621.0", "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.13", + "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", + "@continuedev/openai-adapters": "^1.0.10", "@modelcontextprotocol/sdk": "^1.0.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", @@ -140,7 +141,7 @@ "node-html-markdown": "^1.3.0", "ollama": "^0.4.6", "onnxruntime-node": "1.14.0", - "openai": "^4.20.1", + "openai": "^4.76.0", "p-limit": "^6.1.0", "partial-json": "^0.1.7", "pg": "^8.11.3", @@ -1336,30 +1337,6 @@ "node": "^12.20.0 || ^14.13.1 || >=16.0.0" } }, - "node_modules/@monaco-editor/loader": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@monaco-editor/loader/-/loader-1.4.0.tgz", - "integrity": "sha512-00ioBig0x642hytVspPl7DbQyaSWRaolYie/UFNjoTdvoKPzo6xrXLhTk9ixgIKcLH5b5vDOjVNiGyY+uDCUlg==", - "dependencies": { - "state-local": "^1.0.6" - }, - "peerDependencies": { - "monaco-editor": ">= 0.21.0 < 1" - } - }, - "node_modules/@monaco-editor/react": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/@monaco-editor/react/-/react-4.6.0.tgz", - "integrity": "sha512-RFkU9/i7cN2bsq/iTkurMWOEErmYcY6JiQI3Jn+WeR/FGISH8JbHERjpS9oRuSOPvDMJI0Z8nJeKkbOs9sBYQw==", - "dependencies": { - "@monaco-editor/loader": "^1.4.0" - }, - "peerDependencies": { - "monaco-editor": ">= 0.25.0 < 1", - "react": "^16.8.0 || ^17.0.0 || ^18.0.0", - "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0" - } - }, "node_modules/@napi-rs/nice": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/@napi-rs/nice/-/nice-1.0.1.tgz", @@ -8871,12 +8848,6 @@ "resolved": "https://registry.npmjs.org/minisearch/-/minisearch-7.1.0.tgz", "integrity": "sha512-tv7c/uefWdEhcu6hvrfTihflgeEi2tN6VV7HJnCjK6VxM75QQJh4t9FwJCsA2EsRS8LCnu3W87CuGPWMocOLCA==" }, - "node_modules/monaco-editor": { - "version": "0.52.0", - "resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.52.0.tgz", - "integrity": "sha512-OeWhNpABLCeTqubfqLMXGsqf6OmPU6pHM85kF3dhy6kq5hnhuVS1p3VrEW/XhWHc71P2tHyS5JFySD8mgs1crw==", - "peer": true - }, "node_modules/mrmime": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/mrmime/-/mrmime-2.0.0.tgz", @@ -11435,11 +11406,6 @@ "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", "dev": true }, - "node_modules/state-local": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/state-local/-/state-local-1.0.7.tgz", - "integrity": "sha512-HTEHMNieakEnoe33shBYcZ7NX83ACUjCu8c40iOGEZsngj9zRnkqS9j1pqQPXwobB0ZcVTk27REb7COQ0UR59w==" - }, "node_modules/std-env": { "version": "3.7.0", "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.7.0.tgz", diff --git a/gui/package.json b/gui/package.json index b5e16103d..ba889ca39 100644 --- a/gui/package.json +++ b/gui/package.json @@ -17,7 +17,6 @@ "dependencies": { "@headlessui/react": "^1.7.17", "@heroicons/react": "^2.0.18", - "@monaco-editor/react": "^4.6.0", "@reduxjs/toolkit": "^2.3.0", "@tiptap/core": "^2.3.2", "@tiptap/extension-document": "^2.3.2", diff --git a/gui/public/logos/anthropic.png b/gui/public/logos/anthropic.png index 9adf1b71b..76b245f3b 100644 Binary files a/gui/public/logos/anthropic.png and b/gui/public/logos/anthropic.png differ diff --git a/gui/public/logos/azure.png b/gui/public/logos/azure.png index c24fcbe8c..3158c7d3c 100644 Binary files a/gui/public/logos/azure.png and b/gui/public/logos/azure.png differ diff --git a/gui/public/logos/cohere.png b/gui/public/logos/cohere.png index 3da0b8373..6fd546855 100644 Binary files a/gui/public/logos/cohere.png and b/gui/public/logos/cohere.png differ diff --git a/gui/public/logos/deepseek.png b/gui/public/logos/deepseek.png index 5b98a9078..2ccca71db 100644 Binary files a/gui/public/logos/deepseek.png and b/gui/public/logos/deepseek.png differ diff --git a/gui/public/logos/fireworks.png b/gui/public/logos/fireworks.png index aecb2a27b..d7b811e83 100644 Binary files a/gui/public/logos/fireworks.png and b/gui/public/logos/fireworks.png differ diff --git a/gui/public/logos/flowiseai.png b/gui/public/logos/flowiseai.png deleted file mode 100644 index 027198c2a..000000000 Binary files a/gui/public/logos/flowiseai.png and /dev/null differ diff --git a/gui/public/logos/gemini.png b/gui/public/logos/gemini.png index 8496a4b08..ba998db89 100644 Binary files a/gui/public/logos/gemini.png and b/gui/public/logos/gemini.png differ diff --git a/gui/public/logos/google-palm.png b/gui/public/logos/google-palm.png deleted file mode 100644 index 0f9dc3451..000000000 Binary files a/gui/public/logos/google-palm.png and /dev/null differ diff --git a/gui/public/logos/groq.png b/gui/public/logos/groq.png index 7cefaad26..638e8bd36 100644 Binary files a/gui/public/logos/groq.png and b/gui/public/logos/groq.png differ diff --git a/gui/public/logos/hf.png b/gui/public/logos/hf.png deleted file mode 100644 index 49e2841dd..000000000 Binary files a/gui/public/logos/hf.png and /dev/null differ diff --git a/gui/public/logos/hunyuan.png b/gui/public/logos/hunyuan.png new file mode 100644 index 000000000..ca6ac0a7d Binary files /dev/null and b/gui/public/logos/hunyuan.png differ diff --git a/gui/public/logos/ibmold.png b/gui/public/logos/ibmold.png deleted file mode 100644 index be88ec2ed..000000000 Binary files a/gui/public/logos/ibmold.png and /dev/null differ diff --git a/gui/public/logos/lmstudio.png b/gui/public/logos/lmstudio.png index b2b73591f..d4286733b 100644 Binary files a/gui/public/logos/lmstudio.png and b/gui/public/logos/lmstudio.png differ diff --git a/gui/public/logos/meta.png b/gui/public/logos/meta.png index 84a15698e..4dcb7b9d1 100644 Binary files a/gui/public/logos/meta.png and b/gui/public/logos/meta.png differ diff --git a/gui/public/logos/mistral.png b/gui/public/logos/mistral.png index 0f535f84e..071a2dc37 100644 Binary files a/gui/public/logos/mistral.png and b/gui/public/logos/mistral.png differ diff --git a/gui/public/logos/moonshot.png b/gui/public/logos/moonshot.png index f51df62eb..c2d1d812c 100644 Binary files a/gui/public/logos/moonshot.png and b/gui/public/logos/moonshot.png differ diff --git a/gui/public/logos/msty.png b/gui/public/logos/msty.png deleted file mode 100644 index 8e1b2f3e4..000000000 Binary files a/gui/public/logos/msty.png and /dev/null differ diff --git a/gui/public/logos/nvidia.png b/gui/public/logos/nvidia.png new file mode 100644 index 000000000..ed84888a0 Binary files /dev/null and b/gui/public/logos/nvidia.png differ diff --git a/gui/public/logos/ollama.png b/gui/public/logos/ollama.png index 56ef23f4a..1f7a4ddd4 100644 Binary files a/gui/public/logos/ollama.png and b/gui/public/logos/ollama.png differ diff --git a/gui/public/logos/openai.png b/gui/public/logos/openai.png index e24b90113..2948f669b 100644 Binary files a/gui/public/logos/openai.png and b/gui/public/logos/openai.png differ diff --git a/gui/public/logos/qwen.png b/gui/public/logos/qwen.png index 4f5a292bc..83f5bf490 100644 Binary files a/gui/public/logos/qwen.png and b/gui/public/logos/qwen.png differ diff --git a/gui/public/logos/replicate.png b/gui/public/logos/replicate.png index f71504f59..32433380f 100644 Binary files a/gui/public/logos/replicate.png and b/gui/public/logos/replicate.png differ diff --git a/gui/public/logos/together.png b/gui/public/logos/together.png index e989afdde..0d983a594 100644 Binary files a/gui/public/logos/together.png and b/gui/public/logos/together.png differ diff --git a/gui/public/logos/vertexai.png b/gui/public/logos/vertexai.png index 1744c1f07..335802425 100644 Binary files a/gui/public/logos/vertexai.png and b/gui/public/logos/vertexai.png differ diff --git a/gui/public/logos/xAI.png b/gui/public/logos/xAI.png index 95bdec71a..17ef5f556 100644 Binary files a/gui/public/logos/xAI.png and b/gui/public/logos/xAI.png differ diff --git a/gui/src/App.tsx b/gui/src/App.tsx index 244d811b5..c9f01ad7a 100644 --- a/gui/src/App.tsx +++ b/gui/src/App.tsx @@ -9,7 +9,6 @@ import ErrorPage from "./pages/error"; import Chat from "./pages/gui"; import History from "./pages/history"; import MigrationPage from "./pages/migration"; -import MonacoPage from "./pages/monaco"; import MorePage from "./pages/More"; import Stats from "./pages/stats"; import { ROUTES } from "./util/navigation"; @@ -53,10 +52,6 @@ const router = createMemoryRouter([ path: ROUTES.CONFIG_ERROR, element: , }, - { - path: "/monaco", - element: , - }, { path: "/migration", element: , @@ -70,9 +65,7 @@ const router = createMemoryRouter([ TODO - look into a more redux-esque way to do this */ function SetupListeners() { - const dispatch = useDispatch(); - - useSetup(dispatch); + useSetup(); return <>; } diff --git a/gui/src/components/History/HistoryTableRow.tsx b/gui/src/components/History/HistoryTableRow.tsx index a19e2e062..7f80819c7 100644 --- a/gui/src/components/History/HistoryTableRow.tsx +++ b/gui/src/components/History/HistoryTableRow.tsx @@ -1,27 +1,31 @@ import { PencilSquareIcon, TrashIcon } from "@heroicons/react/24/outline"; import { SessionMetadata } from "core"; -import React, { useState } from "react"; -import { useDispatch } from "react-redux"; +import React, { useContext, useEffect, useState } from "react"; import { useNavigate } from "react-router-dom"; import { Input } from ".."; -import useHistory from "../../hooks/useHistory"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { useAppDispatch, useAppSelector } from "../../redux/hooks"; +import { + deleteSession, + getSession, + loadSession, + updateSession, +} from "../../redux/thunks/session"; import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; -import { useAppSelector } from "../../redux/hooks"; -import { getLastNPathParts } from "core/util/uri"; +import { getLastNUriRelativePathParts } from "core/util/uri"; export function HistoryTableRow({ sessionMetadata, date, - onDelete, - onEdit, + index, }: { sessionMetadata: SessionMetadata; date: Date; - onDelete: (sessionId: string) => void; - onEdit: (session: SessionMetadata) => void; + index: number; }) { - const dispatch = useDispatch(); + const dispatch = useAppDispatch(); const navigate = useNavigate(); + const ideMessenger = useContext(IdeMessengerContext); const [hovered, setHovered] = useState(false); const [editing, setEditing] = useState(false); @@ -30,30 +34,37 @@ export function HistoryTableRow({ ); const currentSessionId = useAppSelector((state) => state.session.id); - const { saveSession, deleteSession, loadSession, getSession, updateSession } = - useHistory(dispatch); + useEffect(() => { + setSessionTitleEditValue(sessionMetadata.title); + }, [sessionMetadata]); const handleKeyUp = async (e: React.KeyboardEvent) => { if (e.key === "Enter") { if (sessionTitleEditValue !== sessionMetadata.title) { - const sessionData = await getSession(sessionMetadata.sessionId); - sessionData.title = sessionTitleEditValue; - await updateSession(sessionData); - onEdit({ - ...sessionMetadata, - title: sessionTitleEditValue, - }); + // imperfect solution of loading session just to update it + // but fine for now, pretty low latency + const currentSession = await getSession( + ideMessenger, + sessionMetadata.sessionId, + ); + await dispatch( + updateSession({ + ...currentSession, + title: sessionTitleEditValue, + }), + ); } setEditing(false); } else if (e.key === "Escape") { - setEditing(false); setSessionTitleEditValue(sessionMetadata.title); + setEditing(false); } }; return ( setHovered(true)} onMouseLeave={() => setHovered(false)} @@ -61,12 +72,14 @@ export function HistoryTableRow({
{ - // Save current session if (sessionMetadata.sessionId !== currentSessionId) { - await saveSession(); - await loadSession(sessionMetadata.sessionId); + await dispatch( + loadSession({ + sessionId: sessionMetadata.sessionId, + saveCurrentSession: true, + }), + ); } - navigate("/"); }} > @@ -85,13 +98,17 @@ export function HistoryTableRow({
) : ( - {JSON.stringify(sessionMetadata.title).slice(1, -1)} + {sessionMetadata.title} )}
- {getLastNPathParts(sessionMetadata.workspaceDirectory || "", 1)} + {getLastNUriRelativePathParts( + window.workspacePaths ?? [], + sessionMetadata.workspaceDirectory || "", + 1, + )} {/* Uncomment to show the date */} {/* @@ -122,8 +139,7 @@ export function HistoryTableRow({ text="Delete" onClick={async (e) => { e.stopPropagation(); - await deleteSession(sessionMetadata.sessionId); - onDelete(sessionMetadata.sessionId); + await dispatch(deleteSession(sessionMetadata.sessionId)); }} > diff --git a/gui/src/components/History/index.tsx b/gui/src/components/History/index.tsx index b872addd4..9c6bc054e 100644 --- a/gui/src/components/History/index.tsx +++ b/gui/src/components/History/index.tsx @@ -1,12 +1,11 @@ import { SessionMetadata } from "core"; import MiniSearch from "minisearch"; import React, { Fragment, useEffect, useMemo, useRef, useState } from "react"; -import { useDispatch } from "react-redux"; -import useHistory from "../../hooks/useHistory"; import { getFontSize, getMetaKeyLabel } from "../../util"; import { HistoryTableRow } from "./HistoryTableRow"; import { XMarkIcon } from "@heroicons/react/24/solid"; +import { useAppSelector } from "../../redux/hooks"; const parseDate = (date: string): Date => { let dateObj = new Date(date); @@ -20,15 +19,12 @@ const HEADER_CLASS = "flex user-select-none pt-2 pb-3 opacity-75 text-center font-bold items-center justify-center sticky h-6"; export function History() { - const [sessions, setSessions] = useState([]); - const searchInputRef = React.useRef(null); - const dispatch = useDispatch(); - const { getHistory, lastSessionId } = useHistory(dispatch); - const [searchTerm, setSearchTerm] = useState(""); + const sessionTitle = useAppSelector((state) => state.session.title); + const minisearch = useRef( new MiniSearch({ fields: ["title"], @@ -36,47 +32,24 @@ export function History() { }), ).current; + const allSessionMetadata = useAppSelector( + (state) => state.session.allSessionMetadata, + ); + useEffect(() => { - const fetchSessions = async () => { - const sessions = await getHistory(); - setSessions(sessions); - - try { - // Consider adding just last session to existing instead of clearing/adding all - minisearch.removeAll(); - minisearch.addAll( - sessions.map((session) => ({ - title: session.title, - sessionId: session.sessionId, - id: session.sessionId, - })), - ); - } catch (e) { - console.log("error adding sessions to minisearch", e); - } - }; - fetchSessions(); - }, [lastSessionId]); - - const deleteSessionInUI = async (sessionId: string) => { - setSessions((prev) => - prev.filter((session) => session.sessionId !== sessionId), - ); - minisearch.discard(sessionId); - }; - - const updateSessionInUI = async (session: SessionMetadata) => { - setSessions((prev) => - prev.map((sess) => - sess.sessionId === session.sessionId ? session : sess, - ), - ); - minisearch.replace({ - title: session.title, - sessionId: session.sessionId, - id: session.sessionId, - }); - }; + try { + minisearch.removeAll(); + minisearch.addAll( + allSessionMetadata.map((session) => ({ + title: session.title, + sessionId: session.sessionId, + id: session.sessionId, + })), + ); + } catch (e) { + console.log("error adding sessions to minisearch", e); + } + }, [allSessionMetadata]); const filteredAndSortedSessions: SessionMetadata[] = useMemo(() => { const sessionIds = minisearch @@ -85,7 +58,7 @@ export function History() { }) .map((result) => result.id); - return sessions + return allSessionMetadata .filter((session) => { return searchTerm === "" || sessionIds.includes(session.sessionId); }) @@ -94,7 +67,7 @@ export function History() { parseDate(b.dateCreated).getTime() - parseDate(a.dateCreated).getTime(), ); - }, [sessions, searchTerm, minisearch]); + }, [allSessionMetadata, searchTerm, minisearch]); const yesterday = new Date(Date.now() - 1000 * 60 * 60 * 24); const lastWeek = new Date(Date.now() - 1000 * 60 * 60 * 24 * 7); @@ -170,8 +143,7 @@ export function History() { ); diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index 038655ec0..b183e24e4 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -2,7 +2,6 @@ import { useEffect, useMemo } from "react"; import { Outlet, useLocation, useNavigate } from "react-router-dom"; import styled from "styled-components"; import { CustomScrollbarDiv, defaultBorderRadius } from "."; -import { LastSessionProvider } from "../context/LastSessionContext"; import { useWebviewListener } from "../hooks/useWebviewListener"; import { useAppDispatch, useAppSelector } from "../redux/hooks"; import { setEditStatus, focusEdit } from "../redux/slices/editModeState"; @@ -22,8 +21,8 @@ import { isNewUserOnboarding, useOnboardingCard } from "./OnboardingCard"; import PostHogPageView from "./PosthogPageView"; import AccountDialog from "./AccountDialog"; import { AuthProvider } from "../context/Auth"; -import useHistory from "../hooks/useHistory"; import { exitEditMode } from "../redux/thunks"; +import { loadLastSession, saveCurrentSession } from "../redux/thunks/session"; const LayoutTopDiv = styled(CustomScrollbarDiv)` height: 100%; @@ -55,7 +54,6 @@ const Layout = () => { const dispatch = useAppDispatch(); const onboardingCard = useOnboardingCard(); const { pathname } = useLocation(); - const { saveSession, loadLastSession } = useHistory(dispatch); const configError = useAppSelector((state) => state.config.configError); @@ -67,6 +65,8 @@ const Layout = () => { const showDialog = useAppSelector((state) => state.ui.showDialog); + const isStreaming = useAppSelector((state) => state.session.isStreaming); + useWebviewListener( "openDialogMessage", async (message) => { @@ -157,7 +157,11 @@ const Layout = () => { useWebviewListener( "focusEdit", async () => { - await saveSession(false); + await dispatch( + saveCurrentSession({ + openNewSession: false, + }), + ); dispatch(newSession()); dispatch(focusEdit()); dispatch(setMode("edit")); @@ -168,8 +172,11 @@ const Layout = () => { useWebviewListener( "focusEditWithoutClear", async () => { - await saveSession(false); - dispatch(newSession()); + await dispatch( + saveCurrentSession({ + openNewSession: true, + }), + ); dispatch(focusEdit()); dispatch(setMode("edit")); }, @@ -193,10 +200,11 @@ const Layout = () => { ); useWebviewListener("exitEditMode", async () => { - loadLastSession().catch((e) => - console.error(`Failed to load last session: ${e}`), + dispatch( + loadLastSession({ + saveCurrentSession: false, + }), ); - dispatch(exitEditMode()); }); @@ -231,53 +239,51 @@ const Layout = () => { return ( - - -
+
+ { + dispatch(setShowDialog(false)); }} - > - { - dispatch(setShowDialog(false)); - }} - onClose={() => { - dispatch(setShowDialog(false)); - }} - message={dialogMessage} - /> - - - - - - {hasFatalErrors && pathname !== ROUTES.CONFIG_ERROR && ( -
navigate(ROUTES.CONFIG_ERROR)} - > - Error!{" "} - - Could not load config.json - -
Learn More
-
- )} -
- -
-
{ + dispatch(setShowDialog(false)); + }} + message={dialogMessage} /> - - + + + + + + {hasFatalErrors && pathname !== ROUTES.CONFIG_ERROR && ( +
navigate(ROUTES.CONFIG_ERROR)} + > + Error!{" "} + + Could not load config.json + +
Learn More
+
+ )} +
+ +
+
+ ); }; diff --git a/gui/src/components/OnboardingCard/hooks/useOnboardingCard.ts b/gui/src/components/OnboardingCard/hooks/useOnboardingCard.ts index d653012f0..ac6078818 100644 --- a/gui/src/components/OnboardingCard/hooks/useOnboardingCard.ts +++ b/gui/src/components/OnboardingCard/hooks/useOnboardingCard.ts @@ -1,11 +1,11 @@ import { useDispatch } from "react-redux"; import { useNavigate } from "react-router-dom"; import { TabTitle } from "../components/OnboardingCardTabs"; -import useHistory from "../../../hooks/useHistory"; import { setOnboardingCard } from "../../../redux/slices/uiSlice"; import { OnboardingCardState } from ".."; import { getLocalStorage, setLocalStorage } from "../../../util/localStorage"; -import { useAppSelector } from "../../../redux/hooks"; +import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; +import { saveCurrentSession } from "../../../redux/thunks/session"; export interface UseOnboardingCard { show: OnboardingCardState["show"]; @@ -17,8 +17,7 @@ export interface UseOnboardingCard { export function useOnboardingCard(): UseOnboardingCard { const navigate = useNavigate(); - const dispatch = useDispatch(); - const { saveSession } = useHistory(dispatch); + const dispatch = useAppDispatch(); const onboardingCard = useAppSelector((state) => state.ui.onboardingCard); @@ -37,11 +36,15 @@ export function useOnboardingCard(): UseOnboardingCard { show = onboardingStatus !== "Completed" && !hasDismissedOnboardingCard; } - function open(tab: TabTitle) { + async function open(tab: TabTitle) { navigate("/"); // Used to clear the chat panel before showing onboarding card - saveSession(); + dispatch( + saveCurrentSession({ + openNewSession: true, + }), + ); dispatch(setOnboardingCard({ show: true, activeTab: tab })); } diff --git a/gui/src/components/StepContainer/EditActions.tsx b/gui/src/components/StepContainer/EditActions.tsx index 4c4f89a75..bd1f1f5d9 100644 --- a/gui/src/components/StepContainer/EditActions.tsx +++ b/gui/src/components/StepContainer/EditActions.tsx @@ -5,8 +5,8 @@ import FeedbackButtons from "./FeedbackButtons"; import { renderChatMessage } from "core/util/messageContent"; import { CopyIconButton } from "../gui/CopyIconButton"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; -import useHistory from "../../hooks/useHistory"; import { exitEditMode } from "../../redux/thunks/exitEditMode"; +import { loadLastSession } from "../../redux/thunks/session"; export interface EditActionsProps { index: number; @@ -18,7 +18,6 @@ export default function EditActions({ index, item }: EditActionsProps) { // (store: RootState) => store.state.curCheckpointIndex, // ); const dispatch = useAppDispatch(); - const { loadLastSession } = useHistory(dispatch); const isStreaming = useAppSelector((state) => state.session.isStreaming); @@ -58,12 +57,13 @@ export default function EditActions({ index, item }: EditActionsProps) { {hasPendingApplies && ( { + onAcceptOrReject={async (outcome) => { if (outcome === "acceptDiff") { - loadLastSession().catch((e) => - console.error(`Failed to load last session: ${e}`), + await dispatch( + loadLastSession({ + saveCurrentSession: false, + }), ); - dispatch(exitEditMode()); } }} diff --git a/gui/src/components/StepContainer/ResponseActions.tsx b/gui/src/components/StepContainer/ResponseActions.tsx index 958595aee..bda0d4a6c 100644 --- a/gui/src/components/StepContainer/ResponseActions.tsx +++ b/gui/src/components/StepContainer/ResponseActions.tsx @@ -46,6 +46,7 @@ export default function ResponseActions({ )}
*/} -

+

{ + e.stopPropagation(); + ideMessenger.post("openUrl", details.docsLink); + }} + > {details.docsLink}

)}
-
+
{ + e.stopPropagation(); + }} + > , + , tooltipPortalDiv, ) ); diff --git a/gui/src/components/indexing/DocsIndexingStatus.tsx b/gui/src/components/indexing/DocsIndexingStatus.tsx index 03a941c80..31604874f 100644 --- a/gui/src/components/indexing/DocsIndexingStatus.tsx +++ b/gui/src/components/indexing/DocsIndexingStatus.tsx @@ -1,16 +1,18 @@ import { IndexingStatus, SiteIndexingConfig } from "core"; -import { useContext, useMemo } from "react"; -import { useDispatch } from "react-redux"; +import { useContext, useMemo, useState } from "react"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { ArrowPathIcon, ArrowTopRightOnSquareIcon, CheckCircleIcon, PauseCircleIcon, + TrashIcon, XMarkIcon, } from "@heroicons/react/24/outline"; -import { useAppSelector } from "../../redux/hooks"; +import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { updateIndexingStatus } from "../../redux/slices/indexingSlice"; +import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; +import ConfirmationDialog from "../dialogs/ConfirmationDialog"; interface IndexingStatusViewerProps { docConfig: SiteIndexingConfig; @@ -21,14 +23,13 @@ const STATUS_TO_ICON: Record = { paused: PauseCircleIcon, complete: CheckCircleIcon, aborted: null, - deleted: null, pending: null, - failed: XMarkIcon, // Since we show an erorr message below + failed: XMarkIcon, // Since we show an error message below }; function DocsIndexingStatus({ docConfig }: IndexingStatusViewerProps) { const ideMessenger = useContext(IdeMessengerContext); - const dispatch = useDispatch(); + const dispatch = useAppDispatch(); const status = useAppSelector( (store) => store.indexing.indexing.statuses[docConfig.startUrl], @@ -53,6 +54,26 @@ function DocsIndexingStatus({ docConfig }: IndexingStatusViewerProps) { } }; + const [hasDeleted, setHasDeleted] = useState(false); // simple alternative to optimistic redux update + const onDelete = () => { + // optimistic update + dispatch( + setDialogMessage( + { + ideMessenger.post("context/removeDocs", { + startUrl: docConfig.startUrl, + }); + setHasDeleted(true); + }} + />, + ), + ); + dispatch(setShowDialog(true)); + }; + const progressPercentage = useMemo(() => { if (!status) { return 0; @@ -62,6 +83,8 @@ function DocsIndexingStatus({ docConfig }: IndexingStatusViewerProps) { const Icon = STATUS_TO_ICON[status?.status]; + if (hasDeleted) return null; + return (
{/* {`${status.type} - ${status.id} - ${status.status} - ${status.progress} - ${status.description} - ${status.icon}`} */} @@ -100,6 +123,12 @@ function DocsIndexingStatus({ docConfig }: IndexingStatusViewerProps) { }`} > ) : null} + {status?.status !== "indexing" ? ( + + ) : null}
)}
@@ -125,7 +154,6 @@ function DocsIndexingStatus({ docConfig }: IndexingStatusViewerProps) { failed: reIndex, aborted: reIndex, paused: () => {}, - deleted: () => {}, pending: () => {}, }[status?.status] } @@ -137,7 +165,6 @@ function DocsIndexingStatus({ docConfig }: IndexingStatusViewerProps) { failed: "Click to retry", aborted: "Click to index", paused: "", - deleted: "", pending: "", }[status?.status] } diff --git a/gui/src/components/indexing/DocsIndexingStatuses.tsx b/gui/src/components/indexing/DocsIndexingStatuses.tsx index a54ffd2a5..76feb21e0 100644 --- a/gui/src/components/indexing/DocsIndexingStatuses.tsx +++ b/gui/src/components/indexing/DocsIndexingStatuses.tsx @@ -10,16 +10,6 @@ function DocsIndexingStatuses() { const config = useAppSelector((store) => store.config.config); const configDocs = config.docs ?? []; - // const indexingStatuses = useSelector( - // (store: RootState) => store.indexing.indexing.statuses, - // ); - // const docsStatuses = useMemo(() => { - // const docs = Object.values(indexingStatuses).filter( - // (status) => status.type === "docs" && status.status !== "deleted", - // ); - // return docs; - // }, [indexingStatuses]); - return (
@@ -38,9 +28,23 @@ function DocsIndexingStatuses() { ) : null}
- Manage your documentation sources + {configDocs.length + ? "Manage your documentation sources" + : "No docs yet"}
+
+ {configDocs.length === 0 && ( + { + dispatch(setShowDialog(true)); + dispatch(setDialogMessage()); + }} + > + Add Docs + + )} +
{configDocs.map((doc) => { return ; })} diff --git a/gui/src/components/indexing/utils.ts b/gui/src/components/indexing/utils.ts deleted file mode 100644 index 768384a52..000000000 --- a/gui/src/components/indexing/utils.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { - ArrowPathIcon, - CheckCircleIcon, - PauseCircleIcon, -} from "@heroicons/react/24/outline"; -import { IndexingStatus } from "core"; - -export const STATUS_TO_ICON: Record = { - indexing: ArrowPathIcon, - paused: PauseCircleIcon, - complete: CheckCircleIcon, - aborted: null, - deleted: null, - pending: null, - failed: null, // XMarkIcon, // Since we show an error message below -}; diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index 7625ca0d6..bd3420e45 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -3,12 +3,10 @@ import { ContextItemWithId, InputModifiers } from "core"; import { useDispatch } from "react-redux"; import styled, { keyframes } from "styled-components"; import { defaultBorderRadius, vscBackground } from ".."; -import { useWebviewListener } from "../../hooks/useWebviewListener"; import { selectSlashCommandComboBoxInputs } from "../../redux/selectors"; import ContextItemsPeek from "./ContextItemsPeek"; import TipTapEditor from "./TipTapEditor"; import { useAppSelector } from "../../redux/hooks"; -import { newSession, setMessageAtIndex } from "../../redux/slices/sessionSlice"; import { ToolbarOptions } from "./InputToolbar"; import { useMemo } from "react"; @@ -76,8 +74,6 @@ const GradientBorder = styled.div<{ `; function ContinueInputBox(props: ContinueInputBoxProps) { - const dispatch = useDispatch(); - const isStreaming = useAppSelector((state) => state.session.isStreaming); const availableSlashCommands = useAppSelector( selectSlashCommandComboBoxInputs, @@ -93,7 +89,7 @@ function ContinueInputBox(props: ContinueInputBoxProps) { const filteredSlashCommands = props.isEditMode ? [] : availableSlashCommands; const filteredContextProviders = useMemo(() => { if (!props.isEditMode) { - availableContextProviders; + return availableContextProviders ?? []; } return ( @@ -125,22 +121,6 @@ function ContinueInputBox(props: ContinueInputBoxProps) { hideTools: !useTools, }; - useWebviewListener( - "newSessionWithPrompt", - async (data) => { - if (props.isMainInput) { - dispatch(newSession()); - dispatch( - setMessageAtIndex({ - message: { role: "user", content: data.prompt }, - index: 0, - }), - ); - } - }, - [props.isMainInput], - ); - return (
diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index f83c27d1e..d80d0e50c 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -27,7 +27,7 @@ import { selectIsInEditMode, } from "../../redux/slices/sessionSlice"; import { exitEditMode } from "../../redux/thunks"; -import useHistory from "../../hooks/useHistory"; +import { loadLastSession } from "../../redux/thunks/session"; const StyledDiv = styled.div<{ isHidden?: boolean }>` padding-top: 4px; @@ -89,7 +89,6 @@ function InputToolbar(props: InputToolbarProps) { const useActiveFile = useAppSelector(selectUseActiveFile); const isInEditMode = useAppSelector(selectIsInEditMode); const hasCodeToEdit = useAppSelector(selectHasCodeToEdit); - const { loadLastSession } = useHistory(dispatch); const isEditModeAndNoCodeToEdit = isInEditMode && !hasCodeToEdit; const isEnterDisabled = props.disabled || isEditModeAndNoCodeToEdit; const shouldRenderToolsButton = @@ -193,11 +192,12 @@ function InputToolbar(props: InputToolbarProps) { {isInEditMode && ( { - loadLastSession().catch((e) => - console.error(`Failed to load last session: ${e}`), + onClick={async (e) => { + await dispatch( + loadLastSession({ + saveCurrentSession: false, + }), ); - dispatch(exitEditMode()); }} > diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 5b68489c1..b39cf4bb8 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -36,7 +36,6 @@ import { } from ".."; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useSubmenuContextProviders } from "../../context/SubmenuContextProviders"; -import useHistory from "../../hooks/useHistory"; import { useInputHistory } from "../../hooks/useInputHistory"; import useIsOSREnabled from "../../hooks/useIsOSREnabled"; import useUpdatingRef from "../../hooks/useUpdatingRef"; @@ -69,9 +68,15 @@ import { clearCodeToEdit, selectHasCodeToEdit, selectIsInEditMode, + setMainEditorContentTrigger, } from "../../redux/slices/sessionSlice"; import { exitEditMode } from "../../redux/thunks"; -import { getBasename, getRelativePath } from "core/util/uri"; +import { getUriPathBasename, getRelativePath } from "core/util/uri"; +import { + loadLastSession, + loadSession, + saveCurrentSession, +} from "../../redux/thunks/session"; const InputBoxDiv = styled.div<{ border?: string }>` resize: none; @@ -186,8 +191,6 @@ function TipTapEditor(props: TipTapEditorProps) { const useActiveFile = useAppSelector(selectUseActiveFile); - const { saveSession, loadSession, loadLastSession } = useHistory(dispatch); - const posthog = usePostHog(); const inSubmenuRef = useRef(undefined); @@ -256,7 +259,6 @@ function TipTapEditor(props: TipTapEditorProps) { const isInEditModeRef = useUpdatingRef(isInEditMode); const hasCodeToEdit = useAppSelector(selectHasCodeToEdit); const isEditModeAndNoCodeToEdit = isInEditMode && !hasCodeToEdit; - async function handleImageFile( file: File, ): Promise<[HTMLImageElement, string] | undefined> { @@ -301,10 +303,6 @@ function TipTapEditor(props: TipTapEditorProps) { return undefined; } - const mainEditorContent = useAppSelector( - (store) => store.session.mainEditorContent, - ); - const { prevRef, nextRef, addRef } = useInputHistory(props.historyKey); const editor: Editor = useEditor({ @@ -382,7 +380,7 @@ function TipTapEditor(props: TipTapEditorProps) { onEnterRef.current({ useCodebase: false, - noContext: useActiveFile, + noContext: !!useActiveFile, }); return true; @@ -424,12 +422,14 @@ function TipTapEditor(props: TipTapEditorProps) { if (inDropdownRef.current || !isInEditModeRef.current) { return false; } - - loadLastSession().catch((e) => - console.error(`Failed to load last session: ${e}`), - ); - - dispatch(exitEditMode()); + (async () => { + await dispatch( + loadLastSession({ + saveCurrentSession: false, + }), + ); + dispatch(exitEditMode()); + })(); return true; }, @@ -539,7 +539,7 @@ function TipTapEditor(props: TipTapEditorProps) { style: `font-size: ${getFontSize()}px;`, }, }, - content: props.editorState || mainEditorContent || "", + content: props.editorState, editable: !isStreaming || props.isMainInput, }); @@ -660,6 +660,18 @@ function TipTapEditor(props: TipTapEditorProps) { } }, [props.isMainInput, isStreaming, editor]); + // This allows anywhere in the app to set the content of the main input + const mainInputContentTrigger = useAppSelector( + (store) => store.session.mainEditorContentTrigger, + ); + useEffect(() => { + if (!props.isMainInput || !mainInputContentTrigger) { + return; + } + editor.commands.setContent(mainInputContentTrigger); + dispatch(setMainEditorContentTrigger(undefined)); + }, [editor, props.isMainInput, mainInputContentTrigger]); + // IDE event listeners useWebviewListener( "userInput", @@ -687,14 +699,18 @@ function TipTapEditor(props: TipTapEditorProps) { dispatch(clearCodeToEdit()); if (historyLength > 0) { - await saveSession(); + await dispatch( + saveCurrentSession({ + openNewSession: false, + }), + ); } setTimeout(() => { editor?.commands.blur(); editor?.commands.focus("end"); }, 20); }, - [historyLength, saveSession, editor, props.isMainInput], + [historyLength, editor, props.isMainInput], ); useWebviewListener( @@ -716,12 +732,16 @@ function TipTapEditor(props: TipTapEditorProps) { if (!props.isMainInput) { return; } - await saveSession(); + await dispatch( + saveCurrentSession({ + openNewSession: true, + }), + ); setTimeout(() => { editor?.commands.focus("end"); }, 20); }, - [editor, props.isMainInput, saveSession], + [editor, props.isMainInput], ); useWebviewListener( @@ -733,10 +753,10 @@ function TipTapEditor(props: TipTapEditorProps) { const rif: RangeInFile & { contents: string } = data.rangeInFileWithContents; - const basename = getBasename(rif.filepath); + const basename = getUriPathBasename(rif.filepath); const relativePath = getRelativePath( rif.filepath, - await ideMessenger.ide.getWorkspaceDirs(), + window.workspacePaths ?? [], ); const rangeStr = `(${rif.range.start.line + 1}-${ rif.range.end.line + 1 @@ -842,12 +862,17 @@ function TipTapEditor(props: TipTapEditorProps) { useWebviewListener( "focusContinueSessionId", async (data) => { - if (!props.isMainInput) { + if (!props.isMainInput || !data.sessionId) { return; } - loadSession(data.sessionId); + await dispatch( + loadSession({ + sessionId: data.sessionId, + saveCurrentSession: true, + }), + ); }, - [loadSession, props.isMainInput], + [props.isMainInput], ); const [showDragOverMsg, setShowDragOverMsg] = useState(false); diff --git a/gui/src/components/markdown/FilenameLink.tsx b/gui/src/components/markdown/FilenameLink.tsx index aed1d1c9b..f1013b42f 100644 --- a/gui/src/components/markdown/FilenameLink.tsx +++ b/gui/src/components/markdown/FilenameLink.tsx @@ -2,7 +2,9 @@ import { RangeInFile } from "core"; import { useContext } from "react"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import FileIcon from "../FileIcon"; -import { getBasename } from "core/util/uri"; +import { getUriPathBasename } from "core/util/uri"; +import { ToolTip } from "../gui/Tooltip"; +import { v4 as uuidv4 } from "uuid"; interface FilenameLinkProps { rif: RangeInFile; @@ -19,16 +21,24 @@ function FilenameLink({ rif }: FilenameLinkProps) { }); } + const id = uuidv4(); + return ( - - - - {getBasename(rif.filepath)} + <> + + + + {getUriPathBasename(rif.filepath)} + - + + {rif.filepath} + + ); } diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index 46a52a97a..3dcfcc869 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -1,6 +1,6 @@ import { SymbolWithRange } from "core"; import { ctxItemToRifWithContents } from "core/commands/util"; -import { memo, useEffect, useRef } from "react"; +import { memo, useEffect, useMemo, useRef } from "react"; import { useRemark } from "react-remark"; import rehypeHighlight, { Options } from "rehype-highlight"; import rehypeKatex from "rehype-katex"; @@ -26,11 +26,15 @@ import { SyntaxHighlightedPre } from "./SyntaxHighlightedPre"; import { patchNestedMarkdown } from "./utils/patchNestedMarkdown"; import { useAppSelector } from "../../redux/hooks"; import { fixDoubleDollarNewLineLatex } from "./utils/fixDoubleDollarLatex"; +import { selectUIConfig } from "../../redux/slices/configSlice"; + const StyledMarkdown = styled.div<{ fontSize?: number; + whiteSpace: string; }>` pre { + white-space: ${(props) => props.whiteSpace}; background-color: ${vscEditorBackground}; border-radius: ${defaultBorderRadius}; @@ -160,20 +164,35 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( // The refs are a workaround because rehype options are stored on initiation // So they won't use the most up-to-date state values // So in this case we just put them in refs - const contextItems = useAppSelector( - (state) => state.session.history[props.itemIndex - 1]?.contextItems, - ); - const contextItemsRef = useUpdatingRef(contextItems); - const symbols = useAppSelector((state) => state.session.symbols); + // Grab context items that are this one or further back + const history = useAppSelector((state) => state.session.history); + const previousFileContextItems = useMemo(() => { + const index = props.itemIndex; + if (index === undefined) { + return []; + } + const previousItems = history.flatMap((item, i) => + i <= index ? item.contextItems : [], + ); + return previousItems.filter( + (item) => item.uri?.type === "file" && item?.uri?.value, + ); + }, [props.itemIndex, history]); + const previousFileContextItemsRef = useUpdatingRef(previousFileContextItems); - const symbolsRef = useRef([]); - useEffect(() => { - // Note, before I was only looking for symbols that matched - // Context item files on current history item - // but in practice global symbols for session makes way more sense - symbolsRef.current = Object.values(symbols).flat(); - }, [symbols]); + // Extract global symbols for files matching previous context items + const allSymbols = useAppSelector((state) => state.session.symbols); + const previousFileContextItemSymbols = useMemo(() => { + const uniqueUris = new Set( + previousFileContextItems.map((item) => item.uri!.value!), + ); + return Object.entries(allSymbols) + .filter((e) => uniqueUris.has(e[0])) + .map((f) => f[1]) + .flat(); + }, [allSymbols, previousFileContextItems]); + const symbolsRef = useUpdatingRef(previousFileContextItemSymbols); const [reactContent, setMarkdownSource] = useRemark({ remarkPlugins: [ @@ -265,18 +284,17 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( code: ({ node, ...codeProps }) => { const content = getCodeChildrenContent(codeProps.children); - if (content && contextItemsRef.current) { - const ctxItem = contextItemsRef.current.find( - (ctxItem) => - ctxItem.uri?.value.includes(content) && - ctxItem.uri.type === "file", + if (content && previousFileContextItemsRef.current) { + // Insert file links for matching previous context items + const ctxItem = previousFileContextItemsRef.current.find((item) => + item.uri!.value!.includes(content), ); - if (ctxItem) { const rif = ctxItemToRifWithContents(ctxItem); return ; } + // Insert symbols for exact matches const exactSymbol = symbolsRef.current.find( (s) => s.name === content, ); @@ -284,7 +302,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( return ; } - // PARTIAL - this is the case where the llm returns e.g. `subtract(number)` instead of `subtract` + // Partial matches - this is the case where the llm returns e.g. `subtract(number)` instead of `subtract` const partialSymbol = symbolsRef.current.find((s) => content.startsWith(s.name), ); @@ -303,10 +321,12 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( // some patches to source markdown are applied here: fixDoubleDollarNewLineLatex(patchNestedMarkdown(props.source ?? "")), ); - }, [props.source]); + }, [props.source, allSymbols]); + const uiConfig = useAppSelector(selectUIConfig); + const codeWrapState = uiConfig?.codeWrap ? "pre-wrap" : "pre"; return ( - {reactContent} + {reactContent} ); }); diff --git a/gui/src/components/markdown/SymbolLink.tsx b/gui/src/components/markdown/SymbolLink.tsx index 45d54ba8f..c1ffa7b05 100644 --- a/gui/src/components/markdown/SymbolLink.tsx +++ b/gui/src/components/markdown/SymbolLink.tsx @@ -1,6 +1,8 @@ import { SymbolWithRange } from "core"; -import { useContext } from "react"; +import { useContext, useMemo } from "react"; +import { v4 as uuidv4 } from "uuid"; import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { ToolTip } from "../gui/Tooltip"; interface SymbolLinkProps { symbol: SymbolWithRange; @@ -18,15 +20,38 @@ function SymbolLink({ symbol, content }: SymbolLinkProps) { }); } + const processedContent = useMemo(() => { + let content = symbol.content; + // TODO Normalize indentation + // let lines = symbol.content.split("\n"); + // if (lines.length > 1) { + // const firstLineIndentation = lines[0].match(/^\s*/)?.[0].length || 0; + // content = lines + // .map((line) => line.slice(firstLineIndentation)) + // .join("\n"); + // } + + // Truncate + return content.length > 200 ? content.slice(0, 196) + "\n..." : content; + }, [symbol]); + + const id = uuidv4(); return ( - - - {content} - - + <> + + + {content} + + + +
{processedContent ?? symbol.filepath}
+
+ ); } diff --git a/gui/src/components/markdown/monaco.css b/gui/src/components/markdown/monaco.css deleted file mode 100644 index 1e53f45fe..000000000 --- a/gui/src/components/markdown/monaco.css +++ /dev/null @@ -1,3 +0,0 @@ -.monaco-editor .margin { - padding-top: 4px; -} diff --git a/gui/src/context/IdeMessenger.ts b/gui/src/context/IdeMessenger.ts index fbbfc21b1..8b47fbf9b 100644 --- a/gui/src/context/IdeMessenger.ts +++ b/gui/src/context/IdeMessenger.ts @@ -1,8 +1,8 @@ import { ChatMessage, IDE, LLMFullCompletionOptions, PromptLog } from "core"; import type { FromWebviewProtocol, ToWebviewProtocol } from "core/protocol"; import { WebviewMessengerResult } from "core/protocol/util"; -import { MessageIde } from "core/util/messageIde"; -import { Message } from "core/util/messenger"; +import { MessageIde } from "core/protocol/messenger/messageIde"; +import { Message } from "core/protocol/messenger"; import { createContext } from "react"; import { v4 as uuidv4 } from "uuid"; import "vscode-webview"; @@ -184,25 +184,32 @@ export class IdeMessenger implements IIdeMessenger { }; window.addEventListener("message", handler); - cancelToken?.addEventListener("abort", () => { + const handleAbort = () => { this.post("abort", undefined, messageId); - }); + }; + cancelToken?.addEventListener("abort", handleAbort); + + try { + while (!done) { + if (buffer.length > index) { + const chunks = buffer.slice(index); + index = buffer.length; + yield chunks; + } + await new Promise((resolve) => setTimeout(resolve, 50)); + } - while (!done) { if (buffer.length > index) { const chunks = buffer.slice(index); - index = buffer.length; yield chunks; } - await new Promise((resolve) => setTimeout(resolve, 50)); - } - if (buffer.length > index) { - const chunks = buffer.slice(index); - yield chunks; + return returnVal; + } catch (e) { + throw e; + } finally { + cancelToken?.removeEventListener("abort", handleAbort); } - - return returnVal; } async *llmStreamChat( diff --git a/gui/src/context/LastSessionContext.tsx b/gui/src/context/LastSessionContext.tsx deleted file mode 100644 index d3b555dc6..000000000 --- a/gui/src/context/LastSessionContext.tsx +++ /dev/null @@ -1,23 +0,0 @@ -import React, { createContext, useState } from "react"; - -export const LastSessionContext = createContext<{ - lastSessionId: string | undefined; - setLastSessionId: (id: string | undefined) => void; -}>({ - lastSessionId: undefined, - setLastSessionId: () => {}, -}); - -export const LastSessionProvider: React.FC<{ - children: React.ReactNode; -}> = ({ children }) => { - const [lastSessionId, setLastSessionId] = useState(); - - return ( - - {children} - - ); -}; - -export const useLastSessionContext = () => React.useContext(LastSessionContext); diff --git a/gui/src/editorInset/EditorInset.tsx b/gui/src/editorInset/EditorInset.tsx index c06661971..9f7393e20 100644 --- a/gui/src/editorInset/EditorInset.tsx +++ b/gui/src/editorInset/EditorInset.tsx @@ -17,7 +17,6 @@ const EditorInsetDiv = styled.div` `; function EditorInset() { - const dispatch = useDispatch(); const availableSlashCommands = useAppSelector( selectSlashCommandComboBoxInputs, ); @@ -25,7 +24,7 @@ function EditorInset() { (store) => store.config.config.contextProviders, ); - useSetup(dispatch); + useSetup(); const elementRef = useRef(null); diff --git a/gui/src/hooks/useHistory.tsx b/gui/src/hooks/useHistory.tsx deleted file mode 100644 index 63252d8f1..000000000 --- a/gui/src/hooks/useHistory.tsx +++ /dev/null @@ -1,164 +0,0 @@ -import { Dispatch } from "@reduxjs/toolkit"; -import { Session, SessionMetadata } from "core"; -import { NEW_SESSION_TITLE } from "core/util/constants"; -import { renderChatMessage } from "core/util/messageContent"; -import { useCallback, useContext } from "react"; -import { IdeMessengerContext } from "../context/IdeMessenger"; -import { useLastSessionContext } from "../context/LastSessionContext"; -import { useAppSelector } from "../redux/hooks"; -import { newSession, updateSessionTitle } from "../redux/slices/sessionSlice"; -import { getLocalStorage, setLocalStorage } from "../util/localStorage"; - -const MAX_TITLE_LENGTH = 100; - -function truncateText(text: string, maxLength: number) { - if (text.length > maxLength) { - return text.slice(0, maxLength - 3) + "..."; - } - return text; -} - -function useHistory(dispatch: Dispatch) { - const sessionId = useAppSelector((store) => store.session.id); - const config = useAppSelector((store) => store.config.config); - const history = useAppSelector((store) => store.session.history); - const title = useAppSelector((store) => store.session.title); - const ideMessenger = useContext(IdeMessengerContext); - const { lastSessionId, setLastSessionId } = useLastSessionContext(); - const selectedModelTitle = useAppSelector( - (store) => store.config.defaultModelTitle, - ); - - const updateLastSessionId = useCallback((sessionId: string) => { - setLastSessionId(sessionId); - setLocalStorage("lastSessionId", sessionId); - }, []); - - async function getHistory( - offset?: number, - limit?: number, - ): Promise { - const result = await ideMessenger.request("history/list", { - offset, - limit, - }); - return result.status === "success" ? result.content : []; - } - - async function getChatTitle(message?: string): Promise { - if (!selectedModelTitle) { - console.error("Failed to get chat title"); - return; - } - const result = await ideMessenger.request("chatDescriber/describe", { - text: message, - selectedModelTitle, - }); - return result.status === "success" ? result.content : undefined; - } - - async function saveSession(openNewSession: boolean = true) { - if (history.length === 0) return; - - if (openNewSession) { - dispatch(newSession()); - updateLastSessionId(sessionId); - } - - let currentTitle = title; - if (config?.ui?.getChatTitles && currentTitle === NEW_SESSION_TITLE) { - try { - // Check if we have first assistant response - let assistantResponse = history - ?.filter((h) => h.message.role === "assistant")[0] - ?.message?.content?.toString(); - - if (assistantResponse) { - currentTitle = await getChatTitle(assistantResponse); - } - } catch (e) { - throw new Error("Unable to get chat title"); - } - } - - // Fallback if we get an error above or if the user has not set getChatTitles - let newTitle = - currentTitle === NEW_SESSION_TITLE - ? truncateText( - renderChatMessage(history[0].message) - .split("\n") - .filter((l) => l.trim() !== "") - .slice(-1)[0] || "", - MAX_TITLE_LENGTH, - ) - : currentTitle?.length > 0 - ? currentTitle - : (await getSession(sessionId)).title; // to ensure titles are synced with updates from history page. - - const session: Session = { - sessionId, - title: newTitle, - workspaceDirectory: window.workspacePaths?.[0] || "", - history, - }; - - await ideMessenger.request("history/save", session); - - if (!openNewSession) { - dispatch(updateSessionTitle(newTitle)); - } - } - - async function getSession(id: string): Promise { - const result = await ideMessenger.request("history/load", { id }); - if (result.status === "error") { - throw new Error(result.error); - } - return result.content; - } - - async function updateSession(session: Session) { - return await ideMessenger.request("history/save", session); - } - - async function deleteSession(id: string) { - return await ideMessenger.request("history/delete", { id }); - } - - async function loadSession(id: string): Promise { - updateLastSessionId(sessionId); - const result = await ideMessenger.request("history/load", { id }); - if (result.status === "error") { - throw new Error(result.error); - } - - const sessionContent = result.content; - dispatch(newSession(sessionContent)); - return sessionContent; - } - - async function loadLastSession(): Promise { - const lastSessionId = getLocalStorage("lastSessionId"); - if (lastSessionId) { - return await loadSession(lastSessionId); - } - } - - function getLastSessionId(): string | undefined { - return getLocalStorage("lastSessionId"); - } - - return { - getHistory, - saveSession, - deleteSession, - loadSession, - loadLastSession, - getLastSessionId, - updateSession, - getSession, - lastSessionId, - }; -} - -export default useHistory; diff --git a/gui/src/hooks/useNavigationListener.tsx b/gui/src/hooks/useNavigationListener.tsx index 503b4a997..3c09dc2d0 100644 --- a/gui/src/hooks/useNavigationListener.tsx +++ b/gui/src/hooks/useNavigationListener.tsx @@ -5,7 +5,6 @@ import { useWebviewListener } from "./useWebviewListener"; const openGUITypes: (keyof ToWebviewProtocol)[] = [ "highlightedCode", - "newSessionWithPrompt", "focusContinueInput", "focusContinueInputWithoutClear", "newSession", diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index b828824a8..0e97965bb 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -6,14 +6,9 @@ import { AppDispatch } from "../redux/store"; import { streamResponseThunk } from "../redux/thunks/streamResponse"; import { isJetBrains } from "../util"; import { setLocalStorage } from "../util/localStorage"; -import { updateFileSymbolsFromContextItems } from "../util/symbols"; import { useWebviewListener } from "./useWebviewListener"; -import { useAppSelector } from "../redux/hooks"; -import { - selectDefaultModel, - setConfig, - setConfigError, -} from "../redux/slices/configSlice"; +import { useAppDispatch, useAppSelector } from "../redux/hooks"; +import { setConfig, setConfigError } from "../redux/slices/configSlice"; import { updateIndexingStatus } from "../redux/slices/indexingSlice"; import { updateDocsSuggestions } from "../redux/slices/miscSlice"; import { @@ -23,14 +18,17 @@ import { } from "../redux/slices/sessionSlice"; import { setTTSActive } from "../redux/slices/uiSlice"; import useUpdatingRef from "./useUpdatingRef"; +import { updateFileSymbolsFromHistory } from "../redux/thunks/updateFileSymbols"; +import { refreshSessionMetadata } from "../redux/thunks/session"; -function useSetup(dispatch: AppDispatch) { +function useSetup() { + const dispatch = useAppDispatch(); const ideMessenger = useContext(IdeMessengerContext); const history = useAppSelector((store) => store.session.history); const defaultModelTitle = useAppSelector( (store) => store.config.defaultModelTitle, ); - const defaultModelTitleRef = useUpdatingRef(defaultModelTitle); + const hasLoadedConfig = useRef(false); const loadConfig = useCallback( async (initial: boolean) => { @@ -66,6 +64,8 @@ function useSetup(dispatch: AppDispatch) { // Init to run on initial config load ideMessenger.post("docs/getSuggestedDocs", undefined); ideMessenger.post("docs/initStatuses", undefined); + dispatch(updateFileSymbolsFromHistory()) + dispatch(refreshSessionMetadata({})); // This triggers sending pending status to the GUI for relevant docs indexes clearInterval(interval); @@ -87,18 +87,11 @@ function useSetup(dispatch: AppDispatch) { // Load symbols for chat on any session change const sessionId = useAppSelector((state) => state.session.id); - const sessionIdRef = useRef(""); - useEffect(() => { - if (sessionIdRef.current !== sessionId) { - updateFileSymbolsFromContextItems( - history.flatMap((item) => item.contextItems), - ideMessenger, - dispatch, - ); + if (sessionId) { + dispatch(updateFileSymbolsFromHistory()); } - sessionIdRef.current = sessionId; - }, [sessionId, history, ideMessenger, dispatch]); + }, [sessionId]); // ON LOAD useEffect(() => { diff --git a/gui/src/hooks/useWebviewListener.ts b/gui/src/hooks/useWebviewListener.ts index 91d37ecb7..568084a2d 100644 --- a/gui/src/hooks/useWebviewListener.ts +++ b/gui/src/hooks/useWebviewListener.ts @@ -1,5 +1,5 @@ import type { ToWebviewProtocol } from "core/protocol/index.js"; -import { Message } from "core/util/messenger"; +import { Message } from "core/protocol/messenger"; import { useContext, useEffect } from "react"; import { IdeMessengerContext } from "../context/IdeMessenger"; diff --git a/gui/src/pages/AddNewModel/configs/models.ts b/gui/src/pages/AddNewModel/configs/models.ts index e9eecaf49..a4f996ebe 100644 --- a/gui/src/pages/AddNewModel/configs/models.ts +++ b/gui/src/pages/AddNewModel/configs/models.ts @@ -1,4 +1,4 @@ -import { ILLM, ModelProvider } from "core"; +import { ILLM } from "core"; import { ModelProviderTags } from "../../../components/modelSelection/utils"; import { InputDescriptor } from "./providers"; @@ -26,7 +26,7 @@ export interface ModelPackage { [key: string]: any; }; dimensions?: PackageDimension[]; - providerOptions?: ModelProvider[]; + providerOptions?: string[]; isOpenSource: boolean; } @@ -1175,26 +1175,13 @@ export const models: { [key: string]: ModelPackage } = { }, isOpenSource: true, }, - Qwen25Coder_7b: { - title: "Qwen 2.5 Coder 7b", + QwenQwQ_32b_preview: { + title: "Qwen QwQ 32b Preview", description: - "Qwen 2.5 is an auto-regressive language model that uses an optimized transformer architecture.", + "QwQ-32B-Preview is Qwen's latest experimental research model, focusing on improving AI reasoning capabilities.", params: { - title: "Qwen 2.5 Coder 7b", - model: "Qwen/Qwen2.5-Coder-7B-Instruct", - contextLength: 32_000, - }, - icon: "qwen.png", - providerOptions: ["siliconflow"], - isOpenSource: true, - }, - Qwen25Coder_7b_pro: { - title: "Qwen 2.5 Coder 7b pro", - description: - "Qwen 2.5 is an auto-regressive language model that uses an optimized transformer architecture.", - params: { - title: "Qwen 2.5 Coder 7b pro", - model: "Pro/Qwen/Qwen2.5-Coder-7B-Instruct", + title: "Qwen QwQ 32b Preview", + model: "Qwen/QwQ-32B-Preview", contextLength: 32_000, }, icon: "qwen.png", @@ -1214,6 +1201,32 @@ export const models: { [key: string]: ModelPackage } = { providerOptions: ["siliconflow"], isOpenSource: true, }, + Hunyuan_a52b: { + title: "Hunyuan A52B", + description: + "Hunyuan-Large is the industry's largest open source Transformer architecture MoE model.", + params: { + title: "Hunyuan A52B", + model: "Tencent/Hunyuan-A52B-Instruct", + contextLength: 32_000, + }, + icon: "hunyuan.png", + providerOptions: ["siliconflow"], + isOpenSource: true, + }, + Llama31Nemotron_70b: { + title: "Llama Nemotron 70B Instruct", + description: + "Llama-3.1-Nemotron-70B-Instruct is a large language model customized by NVIDIA, designed to improve the helpfulness of responses generated by LLM to user queries.", + params: { + title: "Llama Nemotron 70B Instruct", + model: "nvidia/Llama-3.1-Nemotron-70B-Instruct", + contextLength: 32_000, + }, + icon: "nvidia.png", + providerOptions: ["siliconflow"], + isOpenSource: true, + }, AUTODETECT: { title: "Autodetect", description: diff --git a/gui/src/pages/AddNewModel/configs/providers.ts b/gui/src/pages/AddNewModel/configs/providers.ts index 4c56dd8a6..ed22bcbcd 100644 --- a/gui/src/pages/AddNewModel/configs/providers.ts +++ b/gui/src/pages/AddNewModel/configs/providers.ts @@ -1,4 +1,3 @@ -import { ModelProvider } from "core"; import { HTMLInputTypeAttribute } from "react"; import { ModelProviderTags } from "../../../components/modelSelection/utils"; import { FREE_TRIAL_LIMIT_REQUESTS } from "../../../util/freeTrial"; @@ -24,7 +23,7 @@ export interface InputDescriptor { export interface ProviderInfo { title: string; icon?: string; - provider: ModelProvider; + provider: string; description: string; longDescription?: string; tags?: ModelProviderTags[]; @@ -50,7 +49,7 @@ export const apiBaseInput: InputDescriptor = { required: false, }; -export const providers: Partial> = { +export const providers: Partial> = { openai: { title: "OpenAI", provider: "openai", @@ -826,9 +825,10 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo }, ], packages: [ - models.Qwen25Coder_7b, - models.Qwen25Coder_7b_pro, + models.QwenQwQ_32b_preview, models.Qwen25Coder_32b, + models.Hunyuan_a52b, + models.Llama31Nemotron_70b, ], apiKeyUrl: "https://cloud.siliconflow.cn/account/ak", }, diff --git a/gui/src/pages/More/IndexingProgress/IndexingProgressErrorText.tsx b/gui/src/pages/More/IndexingProgress/IndexingProgressErrorText.tsx index ada887cf3..4cfea672c 100644 --- a/gui/src/pages/More/IndexingProgress/IndexingProgressErrorText.tsx +++ b/gui/src/pages/More/IndexingProgress/IndexingProgressErrorText.tsx @@ -1,8 +1,7 @@ -import { IndexingProgressUpdate } from "core"; -import TransformersJsEmbeddingsProvider from "core/indexing/embeddings/TransformersJsEmbeddingsProvider"; -import { isJetBrains } from "../../../util"; import { XCircleIcon } from "@heroicons/react/24/outline"; +import { IndexingProgressUpdate } from "core"; import { useAppSelector } from "../../../redux/hooks"; +import { isJetBrains } from "../../../util"; export interface IndexingProgressErrorTextProps { update: IndexingProgressUpdate; @@ -14,9 +13,7 @@ function IndexingProgressErrorText({ update }: IndexingProgressErrorTextProps) { ); const showJbError = - (isJetBrains() && - embeddingsProvider === TransformersJsEmbeddingsProvider.model) || - true; + (isJetBrains() && embeddingsProvider === "all-MiniLM-L6-v2") || true; if (showJbError) { return ( diff --git a/gui/src/pages/More/More.tsx b/gui/src/pages/More/More.tsx index 347220084..ea7ed37fd 100644 --- a/gui/src/pages/More/More.tsx +++ b/gui/src/pages/More/More.tsx @@ -1,29 +1,26 @@ import { - ArrowLeftIcon, ArrowTopRightOnSquareIcon, DocumentArrowUpIcon, TableCellsIcon, } from "@heroicons/react/24/outline"; import { useContext } from "react"; import { useNavigate } from "react-router-dom"; -import { vscBackground } from "../../components"; import KeyboardShortcuts from "./KeyboardShortcuts"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useNavigationListener } from "../../hooks/useNavigationListener"; -import { useDispatch } from "react-redux"; import { setOnboardingCard } from "../../redux/slices/uiSlice"; -import useHistory from "../../hooks/useHistory"; import MoreHelpRow from "./MoreHelpRow"; import IndexingProgress from "./IndexingProgress"; import DocsIndexingStatuses from "../../components/indexing/DocsIndexingStatuses"; import PageHeader from "../../components/PageHeader"; +import { useAppDispatch } from "../../redux/hooks"; +import { saveCurrentSession } from "../../redux/thunks/session"; function MorePage() { useNavigationListener(); - const dispatch = useDispatch(); + const dispatch = useAppDispatch(); const navigate = useNavigate(); const ideMessenger = useContext(IdeMessengerContext); - const { saveSession } = useHistory(dispatch); return (
@@ -87,10 +84,14 @@ function MorePage() { title="Quickstart" description="Reopen the quickstart and tutorial file" Icon={DocumentArrowUpIcon} - onClick={() => { + onClick={async () => { navigate("/"); // Used to clear the chat panel before showing onboarding card - saveSession(); + await dispatch( + saveCurrentSession({ + openNewSession: true, + }), + ); dispatch(setOnboardingCard({ show: true, activeTab: "Best" })); ideMessenger.post("showTutorial", undefined); }} diff --git a/gui/src/pages/error.tsx b/gui/src/pages/error.tsx index d7e10f51a..0014a580e 100644 --- a/gui/src/pages/error.tsx +++ b/gui/src/pages/error.tsx @@ -48,7 +48,6 @@ const ErrorPage: React.FC = () => { localStorage.removeItem("inputHistory_chat"); // localStorage.removeItem("showTutorialCard"); // localStorage.removeItem("onboardingStatus"); - // localStorage.removeItem("lastSessionId"); navigate("/"); }} > diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 851a6f13b..ea514b833 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -37,7 +37,6 @@ import PageHeader from "../../components/PageHeader"; import StepContainer from "../../components/StepContainer"; import AcceptRejectAllButtons from "../../components/StepContainer/AcceptRejectAllButtons"; import { IdeMessengerContext } from "../../context/IdeMessenger"; -import useHistory from "../../hooks/useHistory"; import { useTutorialCard } from "../../hooks/useTutorialCard"; import { useWebviewListener } from "../../hooks/useWebviewListener"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; @@ -72,6 +71,10 @@ import ConfigErrorIndicator from "./ConfigError"; import { ToolCallDiv } from "./ToolCallDiv"; import { ToolCallButtons } from "./ToolCallDiv/ToolCallButtonsDiv"; import ToolOutput from "./ToolCallDiv/ToolOutput"; +import { + loadLastSession, + saveCurrentSession, +} from "../../redux/thunks/session"; const StopButton = styled.div` background-color: ${vscBackground}; @@ -149,8 +152,6 @@ export function Chat() { const showChatScrollbar = useAppSelector( (state) => state.config.config.ui?.showChatScrollbar, ); - const { saveSession, getLastSessionId, loadLastSession } = - useHistory(dispatch); const codeToEdit = useAppSelector((state) => state.session.codeToEdit); const toolCallState = useSelector( selectCurrentToolCall, @@ -166,7 +167,7 @@ export function Chat() { const isSingleRangeEditOrInsertion = useAppSelector( selectIsSingleRangeEditOrInsertion, ); - + const lastSessionId = useAppSelector((state) => state.session.lastSessionId); const snapToBottom = useCallback(() => { if (!stepsDivRef.current) return; const elem = stepsDivRef.current; @@ -259,8 +260,6 @@ export function Chat() { return; } - editor.commands.clearContent(true); - const promptPreamble = isInEditMode ? getMultifileEditPrompt(codeToEdit) : undefined; @@ -269,6 +268,8 @@ export function Chat() { streamResponseThunk({ editorState, modifiers, promptPreamble, index }), ); + editor.commands.clearContent(true); + // Increment localstorage counter for popup const currentCount = getLocalStorage("mainTextEntryCounter"); if (currentCount) { @@ -320,11 +321,16 @@ export function Chat() { useWebviewListener( "newSession", async () => { - saveSession(); + await dispatch( + saveCurrentSession({ + openNewSession: true, + }), + ); + // unwrapResult(response) // errors if session creation failed mainTextInputRef.current?.focus?.(); dispatch(exitEditMode()); }, - [saveSession], + [mainTextInputRef], ); const isLastUserInput = useCallback( @@ -343,14 +349,9 @@ export function Chat() { {isInEditMode && ( { - loadLastSession().catch((e) => - console.error(`Failed to load last session: ${e}`), - ); - - if (isInEditMode) { - dispatch(exitEditMode()); - } + onClick={async () => { + await dispatch(loadLastSession({ saveCurrentSession: false })); + dispatch(exitEditMode()); }} /> )} @@ -497,14 +498,16 @@ export function Chat() { >
- {history.length === 0 && getLastSessionId() && !isInEditMode && ( + {history.length === 0 && lastSessionId && !isInEditMode && (
- loadLastSession().catch((e) => - console.error(`Failed to load last session: ${e}`), - ) - } + onClick={async () => { + await dispatch( + loadLastSession({ + saveCurrentSession: true, + }), + ); + }} className="flex items-center gap-2" > @@ -519,12 +522,13 @@ export function Chat() { {hasPendingApplies && isSingleRangeEditOrInsertion && ( { + onAcceptOrReject={async (outcome) => { if (outcome === "acceptDiff") { - loadLastSession().catch((e) => - console.error(`Failed to load last session: ${e}`), + await dispatch( + loadLastSession({ + saveCurrentSession: false, + }), ); - dispatch(exitEditMode()); } }} diff --git a/gui/src/pages/monaco.tsx b/gui/src/pages/monaco.tsx deleted file mode 100644 index c0cfbd8ec..000000000 --- a/gui/src/pages/monaco.tsx +++ /dev/null @@ -1,107 +0,0 @@ -import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline"; -import { DiffEditor } from "@monaco-editor/react"; -import React, { useContext, useEffect } from "react"; -import { v4 } from "uuid"; -import { vscInputBackground } from "../components"; -import HeaderButtonWithToolTip from "../components/gui/HeaderButtonWithToolTip"; -import { IdeMessengerContext } from "../context/IdeMessenger"; - -interface EditorFrameProps { - filename: string; -} - -function EditorFrame(props: EditorFrameProps) { - const [contents, setContents] = React.useState( - "function sum(a, b) {return a + b;}", - ); - - const ideMessenger = useContext(IdeMessengerContext); - - useEffect(() => { - const messageId = v4(); - const eventListener = (event: any) => { - if ( - event.data.messageId === messageId && - event.data.type === "readRangeInFile" - ) { - setContents(event.data.contents); - } - }; - window.addEventListener("message", eventListener); - - ideMessenger.post("readFile", { filepath: props.filename }); - - return () => window.removeEventListener("message", eventListener); - }, []); - - return ( -
-
- { - ideMessenger.post("showFile", { - filepath: props.filename, - }); - }} - > - {props.filename.split("/").pop()} - -
- {}}> - - - {}}> - - -
-
- {/* */} - -
- ); -} - -const FILENAMES = [ - "/Users/natesesti/Desktop/continue/gui/src/hooks/CustomPostHogProvider.tsx", - "/Users/natesesti/Desktop/continue/gui/src/hooks/CustomPostHogProvider.tsx", - "/Users/natesesti/Desktop/continue/gui/src/hooks/CustomPostHogProvider.tsx", -]; - -function MonacoPage() { - return ( -
-

Multi-File Edit

- {FILENAMES.map((filename) => { - return ; - })} -
- ); -} - -export default MonacoPage; diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index d64852f2f..6e3e38884 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -17,6 +17,7 @@ import { MessageModes, PromptLog, Session, + SessionMetadata, ToolCall, } from "core"; import { NEW_SESSION_TITLE } from "core/util/constants"; @@ -35,6 +36,8 @@ type ChatHistoryItemWithMessageId = ChatHistoryItem & { }; type SessionState = { + lastSessionId?: string; + allSessionMetadata: SessionMetadata[]; history: ChatHistoryItemWithMessageId[]; isStreaming: boolean; title: string; @@ -43,7 +46,8 @@ type SessionState = { streamAborter: AbortController; codeToEdit: CodeToEdit[]; curCheckpointIndex: number; - mainEditorContent?: JSONContent; + currentMainEditorContent?: JSONContent; + mainEditorContentTrigger?: JSONContent | undefined; symbols: FileSymbolMap; mode: MessageModes; codeBlockApplyStates: { @@ -71,21 +75,8 @@ function isCodeToEditEqual(a: CodeToEdit, b: CodeToEdit) { return !("range" in a) && !("range" in b); } -function getBaseHistoryItem(): ChatHistoryItemWithMessageId { - return { - message: { - id: uuidv4(), - role: "assistant", - content: "", - }, - contextItems: [], - isGatheringContext: false, - checkpoint: {}, - isBeforeCheckpoint: false, - }; -} - const initialState: SessionState = { + allSessionMetadata: [], history: [], isStreaming: false, title: NEW_SESSION_TITLE, @@ -100,6 +91,7 @@ const initialState: SessionState = { states: [], curIndex: 0, }, + lastSessionId: undefined, }; export const sessionSlice = createSlice({ @@ -130,16 +122,22 @@ export const sessionSlice = createSlice({ if (state.history.length < 2) { return; } - const lastMessage = state.history[state.history.length - 1]; // Only clear in the case of an empty message if (!lastMessage.message.content.length) { - state.mainEditorContent = + state.mainEditorContentTrigger = state.history[state.history.length - 2].editorState; state.history = state.history.slice(0, -2); } }, + // Trigger value picked up by editor with isMainInput to set its content + setMainEditorContentTrigger: ( + state, + action: PayloadAction, + ) => { + state.mainEditorContentTrigger = action.payload; + }, updateFileSymbols: (state, action: PayloadAction) => { state.symbols = { ...state.symbols, @@ -159,99 +157,91 @@ export const sessionSlice = createSlice({ state.history[index].contextItems = contextItems; } }, - resubmitAtIndex: ( + submitEditorAndInitAtIndex: ( state, { payload, }: PayloadAction<{ - index: number; + index?: number; editorState: JSONContent; }>, ) => { - const historyItem = state.history[payload.index]; - const lastHistoryItem = state.history[payload.index - 1]; + const { index, editorState } = payload; - if (!historyItem) { - return; + if (typeof index === "number" && index < state.history.length) { + // Resubmission - update input message, truncate history after resubmit with new empty response message + if (index % 2 === 1) { + console.warn( + "Corrupted history: resubmitting at odd index, shouldn't happen", + ); + } + const historyItem = state.history[index]; + + historyItem.message.content = ""; // IMPORTANT - this is quickly updated by resolveEditorContent based on editor state prior to streaming + historyItem.editorState = payload.editorState; + + state.history = state.history.slice(0, index + 1).concat({ + message: { + id: uuidv4(), + role: "assistant", + content: "", // IMPORTANT - this is subsequently updated by response streaming + }, + contextItems: [], + }); + + state.curCheckpointIndex = Math.floor(index / 2); + } else { + // New input/response messages + state.history = state.history.concat([ + { + message: { + id: uuidv4(), + role: "user", + content: "", // IMPORTANT - this is quickly updated by resolveEditorContent based on editor state prior to streaming + }, + contextItems: [], + editorState, + }, + { + message: { + id: uuidv4(), + role: "assistant", + content: "", // IMPORTANT - this is subsequently updated by response streaming + }, + contextItems: [], + }, + ]); + + state.curCheckpointIndex = Math.floor((state.history.length - 1) / 2); // TODO this feels really fragile } - historyItem.message.content = ""; - historyItem.editorState = payload.editorState; - - // Cut off history after the resubmitted message - state.history = state.history - .slice(0, payload.index + 1) - .concat(getBaseHistoryItem()); - state.isStreaming = true; }, deleteMessage: (state, action: PayloadAction) => { // Deletes the current assistant message and the previous user message state.history.splice(action.payload - 1, 2); }, - initNewActiveMessage: ( + updateHistoryItemAtIndex: ( state, { payload, }: PayloadAction<{ - editorState: JSONContent; - }>, - ) => { - const baseHistoryItem = getBaseHistoryItem(); - - state.history.push({ - ...baseHistoryItem, - message: { ...baseHistoryItem.message, id: uuidv4(), role: "user" }, - editorState: payload.editorState, - }); - - state.history.push({ - ...baseHistoryItem, - message: { - ...baseHistoryItem.message, - id: uuidv4(), - role: "assistant", - }, - editorState: payload.editorState, - }); - - state.isStreaming = true; - state.curCheckpointIndex = state.curCheckpointIndex + 1; - }, - setMessageAtIndex: ( - state, - { - payload, - }: PayloadAction<{ - message: ChatMessage; index: number; - contextItems?: ContextItemWithId[]; + updates: Partial; }>, ) => { - if (payload.index >= state.history.length) { - const baseHistoryItem = getBaseHistoryItem(); - - state.history.push({ - ...baseHistoryItem, - message: { ...baseHistoryItem.message, ...payload.message }, - editorState: { - type: "doc", - content: renderChatMessage(payload.message) - .split("\n") - .map((line) => ({ - type: "paragraph", - content: line === "" ? [] : [{ type: "text", text: line }], - })), - }, - }); + const { index, updates } = payload; + if (!state.history[index]) { + console.error( + `attempting to update history item at nonexistent index ${index}`, + updates, + ); + return; } - - state.history[payload.index].message = { - ...payload.message, - id: uuidv4(), + state.history[index] = { + ...state.history[index], + ...updates, }; - - state.history[payload.index].contextItems = payload.contextItems || []; }, addContextItemsAtIndex: ( state, @@ -299,12 +289,13 @@ export const sessionSlice = createSlice({ message.role === "assistant" && message.toolCalls?.length)) ) { - const baseHistoryItem = getBaseHistoryItem(); - // Create a new message const historyItem: ChatHistoryItemWithMessageId = { - ...baseHistoryItem, - message: { ...baseHistoryItem.message, ...message }, + message: { + ...message, + id: uuidv4(), + }, + contextItems: [], }; if (message.role === "assistant" && message.toolCalls) { @@ -359,6 +350,8 @@ export const sessionSlice = createSlice({ } }, newSession: (state, { payload }: PayloadAction) => { + state.lastSessionId = state.id; + state.streamAborter.abort(); state.streamAborter = new AbortController(); @@ -372,14 +365,58 @@ export const sessionSlice = createSlice({ state.curCheckpointIndex = 0; } else { state.history = []; - state.title = "New Session"; + state.title = NEW_SESSION_TITLE; state.id = uuidv4(); state.curCheckpointIndex = 0; } }, + updateSessionTitle: (state, { payload }: PayloadAction) => { state.title = payload; }, + setAllSessionMetadata: ( + state, + { payload }: PayloadAction, + ) => { + state.allSessionMetadata = payload; + }, + ////////////////////////////////////////////////////////////////////////////////// + // These are for optimistic session metadata updates, especially for History page + addSessionMetadata: ( + state, + { payload }: PayloadAction, + ) => { + state.allSessionMetadata = [...state.allSessionMetadata, payload]; + }, + updateSessionMetadata: ( + state, + { + payload, + }: PayloadAction< + { + sessionId: string; + } & Partial + >, + ) => { + state.allSessionMetadata = state.allSessionMetadata.map((session) => + session.sessionId === payload.sessionId + ? { + ...session, + ...payload, + } + : session, + ); + if (payload.title && payload.sessionId === state.id) { + state.title = payload.title; + } + }, + deleteSessionMetadata: (state, { payload }: PayloadAction) => { + // Note, should not be allowed to delete current session from chat session + state.allSessionMetadata = state.allSessionMetadata.filter( + (session) => session.sessionId !== payload, + ); + }, + ////////////////////////////////////////////////////////////////////////////////// addHighlightedCode: ( state, { @@ -582,13 +619,13 @@ export const { streamUpdate, newSession, updateSessionTitle, - resubmitAtIndex, addHighlightedCode, addPromptCompletionPair, setActive, - initNewActiveMessage, - setMessageAtIndex, + submitEditorAndInitAtIndex, + updateHistoryItemAtIndex, clearLastEmptyResponse, + setMainEditorContentTrigger, setSelectedProfileId, deleteMessage, setIsGatheringContext, @@ -606,6 +643,10 @@ export const { setToolGenerated, setToolCallOutput, setMode, + setAllSessionMetadata, + addSessionMetadata, + updateSessionMetadata, + deleteSessionMetadata, } = sessionSlice.actions; export const { diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index 779909a47..5ddf55ee6 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -31,9 +31,10 @@ const rootReducer = combineReducers({ }); const saveSubsetFilters = [ - createFilter("session", ["history", "sessionId", "defaultModelTitle"]), + createFilter("session", ["history", "sessionId"]), // Don't persist any of the edit state for now createFilter("editModeState", []), + createFilter("config", ["defaultModelTitle"]), ]; const migrations: MigrationManifest = { diff --git a/gui/src/redux/thunks/gatherContext.ts b/gui/src/redux/thunks/gatherContext.ts index b232732e7..d1eb556d6 100644 --- a/gui/src/redux/thunks/gatherContext.ts +++ b/gui/src/redux/thunks/gatherContext.ts @@ -9,11 +9,11 @@ import { import resolveEditorContent, { hasSlashCommandOrContextProvider, } from "../../components/mainInput/resolveInput"; -import { updateFileSymbolsFromContextItems } from "../../util/symbols"; import { ThunkApiType } from "../store"; import { selectDefaultModel } from "../slices/configSlice"; import { setIsGatheringContext } from "../slices/sessionSlice"; -import { getBasename, getRelativePath } from "core/util/uri"; +import { getRelativePath, getUriPathBasename } from "core/util/uri"; +import { updateFileSymbolsFromNewContextItems } from "./updateFileSymbols"; export const gatherContext = createAsyncThunk< { @@ -85,7 +85,7 @@ export const gatherContext = createAsyncThunk< currentFile.path, await extra.ideMessenger.ide.getWorkspaceDirs(), )}\n${currentFileContents}\n\`\`\``, - name: `Active file: ${getBasename(currentFile.path)}`, + name: `Active file: ${getUriPathBasename(currentFile.path)}`, description: currentFile.path, id: { itemId: currentFile.path, @@ -100,11 +100,7 @@ export const gatherContext = createAsyncThunk< } } - await updateFileSymbolsFromContextItems( - selectedContextItems, - extra.ideMessenger, - dispatch, - ); + dispatch(updateFileSymbolsFromNewContextItems(selectedContextItems)); if (promptPreamble) { if (typeof content === "string") { diff --git a/gui/src/redux/thunks/handleErrors.ts b/gui/src/redux/thunks/handleErrors.ts deleted file mode 100644 index b0beef06f..000000000 --- a/gui/src/redux/thunks/handleErrors.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { createAsyncThunk } from "@reduxjs/toolkit"; -import { setInactive } from "../slices/sessionSlice"; -import { ThunkApiType } from "../store"; - -export const handleErrors = createAsyncThunk< - void, - () => Promise, - ThunkApiType ->("chat/handleErrors", async (runStream, { dispatch, extra }) => { - try { - await runStream(); - } catch (e: any) { - console.debug("Error streaming response: ", e); - } finally { - dispatch(setInactive()); - // triggerSave(!save); TODO - } -}); diff --git a/gui/src/redux/thunks/index.ts b/gui/src/redux/thunks/index.ts index c35189de3..31f0fa0cc 100644 --- a/gui/src/redux/thunks/index.ts +++ b/gui/src/redux/thunks/index.ts @@ -1,6 +1,6 @@ export { exitEditMode } from "./exitEditMode"; export { gatherContext } from "./gatherContext"; -export { handleErrors } from "./handleErrors"; +export { streamThunkWrapper } from "./streamThunkWrapper"; export { resetStateForNewMessage } from "./resetStateForNewMessage"; export { streamNormalInput } from "./streamNormalInput"; export { streamResponseThunk } from "./streamResponse"; diff --git a/gui/src/redux/thunks/session.ts b/gui/src/redux/thunks/session.ts new file mode 100644 index 000000000..f0553f4bb --- /dev/null +++ b/gui/src/redux/thunks/session.ts @@ -0,0 +1,217 @@ +import { createAsyncThunk, Dispatch, unwrapResult } from "@reduxjs/toolkit"; +import { ChatMessage, Session, SessionMetadata } from "core"; +import { NEW_SESSION_TITLE } from "core/util/constants"; +import { renderChatMessage } from "core/util/messageContent"; +import { ThunkApiType } from "../store"; +import { + deleteSessionMetadata, + newSession, + setAllSessionMetadata, + updateSessionMetadata, +} from "../slices/sessionSlice"; +import { IIdeMessenger } from "../../context/IdeMessenger"; + +const MAX_TITLE_LENGTH = 100; + +// Async session functions live in thunks (because of IDE messaging mostly) +// see sessionSlice for sync redux session functions + +export async function getSession( + ideMessenger: IIdeMessenger, + id: string, +): Promise { + const result = await ideMessenger.request("history/load", { id }); + if (result.status === "error") { + throw new Error(result.error); + } + return result.content; +} + +export const refreshSessionMetadata = createAsyncThunk< + SessionMetadata[], + { + offset?: number; + limit?: number; + }, + ThunkApiType +>("session/refreshMetadata", async ({ offset, limit }, { dispatch, extra }) => { + const result = await extra.ideMessenger.request("history/list", { + limit, + offset, + }); + if (result.status === "error") { + throw new Error(result.error); + } + dispatch(setAllSessionMetadata(result.content)); + return result.content; +}); + +export const deleteSession = createAsyncThunk( + "session/delete", + async (id, { getState, dispatch, extra }) => { + dispatch(deleteSessionMetadata(id)); // optimistic + const state = getState(); + if (id === state.session.id) { + await dispatch( + loadLastSession({ + saveCurrentSession: false, + }), + ); + } + const result = await extra.ideMessenger.request("history/delete", { id }); + if (result.status === "error") { + throw new Error(result.error); + } + dispatch(refreshSessionMetadata({})); + }, +); + +export const updateSession = createAsyncThunk( + "session/update", + async (session, { extra, dispatch }) => { + dispatch( + updateSessionMetadata({ + sessionId: session.sessionId, + title: session.title, + }), + ); // optimistic session metadata update + await extra.ideMessenger.request("history/save", session); + await dispatch(refreshSessionMetadata({})); + }, +); + +/* + this is only used for the custom focusContinueSessionId command at the moment +*/ +export const loadSession = createAsyncThunk< + void, + { + sessionId: string; + saveCurrentSession: boolean; + }, + ThunkApiType +>( + "session/load", + async ({ sessionId, saveCurrentSession: save }, { extra, dispatch }) => { + if (save) { + const result = await dispatch( + saveCurrentSession({ + openNewSession: false, + }), + ); + unwrapResult(result); + } + const session = await getSession(extra.ideMessenger, sessionId); + dispatch(newSession(session)); + }, +); + +export const loadLastSession = createAsyncThunk< + void, + { + saveCurrentSession: boolean; + }, + ThunkApiType +>( + "session/loadLast", + async ({ saveCurrentSession }, { extra, dispatch, getState }) => { + const state = getState(); + + if (state.session.id && saveCurrentSession) { + } + const lastSessionId = getState().session.lastSessionId; + + if (!lastSessionId) { + dispatch(newSession()); + return; + } + + const session = await getSession(extra.ideMessenger, lastSessionId); + dispatch(newSession(session)); + }, +); + +function getChatTitleFromMessage(message: ChatMessage) { + const text = + renderChatMessage(message) + .split("\n") + .filter((l) => l.trim() !== "") + .slice(-1)[0] || ""; + + // Truncate + if (text.length > MAX_TITLE_LENGTH) { + return text.slice(0, MAX_TITLE_LENGTH - 3) + "..."; + } + return text; +} + +export const saveCurrentSession = createAsyncThunk< + void, + { openNewSession: boolean }, + ThunkApiType +>( + "session/saveCurrent", + async ({ openNewSession }, { dispatch, extra, getState }) => { + const state = getState(); + if (state.session.history.length === 0) { + return; + } + + if (openNewSession) { + dispatch(newSession()); + } + + // New session has already been dispatched + // Now save previous session and update chat title if relevant + let title = state.session.title; + if (title === NEW_SESSION_TITLE) { + if ( + state.config.config?.ui?.getChatTitles && + state.config.defaultModelTitle + ) { + let assistantResponse = state.session.history + ?.filter((h) => h.message.role === "assistant")[0] + ?.message?.content?.toString(); + + if (assistantResponse) { + const result = await extra.ideMessenger.request( + "chatDescriber/describe", + { + text: assistantResponse, + selectedModelTitle: state.config.defaultModelTitle, + }, + ); + if (result.status === "success" && result.content) { + title = result.content; + } + } + } + // Fallbacks if above doesn't work out or getChatTitles = false + if (title === NEW_SESSION_TITLE) { + title = getChatTitleFromMessage(history[0].message); + } + } + // More fallbacks in case of no title + if (!title.length) { + const metadata = getState().session.allSessionMetadata.find( + (m) => m.sessionId === state.session.id, + ); + if (metadata?.title) { + title = metadata.title; + } + } + if (!title.length) { + title = NEW_SESSION_TITLE; + } + + const session: Session = { + sessionId: state.session.id, + title, + workspaceDirectory: window.workspacePaths?.[0] || "", + history: state.session.history, + }; + + const result = await dispatch(updateSession(session)); + unwrapResult(result); + }, +); diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index 5a22a36b5..aec7bb38e 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -5,7 +5,6 @@ import { selectDefaultModel } from "../slices/configSlice"; import { abortStream, addPromptCompletionPair, - clearLastEmptyResponse, setToolGenerated, streamUpdate, } from "../slices/sessionSlice"; @@ -17,70 +16,65 @@ export const streamNormalInput = createAsyncThunk< ChatMessage[], ThunkApiType >("chat/streamNormalInput", async (messages, { dispatch, extra, getState }) => { - try { - // Gather state - const state = getState(); - const defaultModel = selectDefaultModel(state); - const toolSettings = state.ui.toolSettings; - const streamAborter = state.session.streamAborter; - const useTools = state.ui.useTools; + // Gather state + const state = getState(); + const defaultModel = selectDefaultModel(state); + const toolSettings = state.ui.toolSettings; + const streamAborter = state.session.streamAborter; + const useTools = state.ui.useTools; - if (!defaultModel) { - throw new Error("Default model not defined"); + if (!defaultModel) { + throw new Error("Default model not defined"); + } + + // Send request + const gen = extra.ideMessenger.llmStreamChat( + defaultModel.title, + streamAborter.signal, + messages, + { + tools: useTools + ? Object.keys(toolSettings) + .filter((tool) => toolSettings[tool] !== "disabled") + .map((toolName) => + state.config.config.tools.find( + (tool) => tool.function.name === toolName, + ), + ) + .filter(Boolean) + : undefined, + }, + ); + + // Stream response + let next = await gen.next(); + while (!next.done) { + if (!getState().session.isStreaming) { + dispatch(abortStream()); + break; } - // Send request - const gen = extra.ideMessenger.llmStreamChat( - defaultModel.title, - streamAborter.signal, - messages, - { - tools: useTools - ? Object.keys(toolSettings) - .filter((tool) => toolSettings[tool] !== "disabled") - .map((toolName) => - state.config.config.tools.find( - (tool) => tool.function.name === toolName, - ), - ) - .filter(Boolean) - : undefined, - }, - ); + const updates = next.value as ChatMessage[]; + dispatch(streamUpdate(updates)); + next = await gen.next(); + } - // Stream response - let next = await gen.next(); - while (!next.done) { - if (!getState().session.isStreaming) { - dispatch(abortStream()); - break; - } + // Attach prompt log + let returnVal = next.value as PromptLog; + if (returnVal) { + dispatch(addPromptCompletionPair([returnVal])); + } - const updates = next.value as ChatMessage[]; - dispatch(streamUpdate(updates)); - next = await gen.next(); + // If it's a tool call that is automatically accepted, we should call it + const toolCallState = selectCurrentToolCall(getState()); + if (toolCallState) { + dispatch(setToolGenerated()); + + if ( + toolSettings[toolCallState.toolCall.function.name] === + "allowedWithoutPermission" + ) { + await dispatch(callTool()); } - - // Attach prompt log - let returnVal = next.value as PromptLog; - if (returnVal) { - dispatch(addPromptCompletionPair([returnVal])); - } - - // If it's a tool call that is automatically accepted, we should call it - const toolCallState = selectCurrentToolCall(getState()); - if (toolCallState) { - dispatch(setToolGenerated()); - - if ( - toolSettings[toolCallState.toolCall.function.name] === - "allowedWithoutPermission" - ) { - await dispatch(callTool()); - } - } - } catch (e) { - // If there's an error, we should clear the response so there aren't two input boxes - dispatch(clearLastEmptyResponse()); } }); diff --git a/gui/src/redux/thunks/streamResponse.ts b/gui/src/redux/thunks/streamResponse.ts index 1ee3d65d5..1411828d3 100644 --- a/gui/src/redux/thunks/streamResponse.ts +++ b/gui/src/redux/thunks/streamResponse.ts @@ -1,28 +1,21 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; import { JSONContent } from "@tiptap/core"; -import { - ChatHistoryItem, - ChatMessage, - InputModifiers, - MessageContent, - SlashCommandDescription, -} from "core"; +import { InputModifiers, MessageContent, SlashCommandDescription } from "core"; import { constructMessages } from "core/llm/constructMessages"; import { renderChatMessage } from "core/util/messageContent"; import posthog from "posthog-js"; import { - initNewActiveMessage, - resubmitAtIndex, - setCurCheckpointIndex, - setMessageAtIndex, + submitEditorAndInitAtIndex, + updateHistoryItemAtIndex, } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; import { gatherContext } from "./gatherContext"; -import { handleErrors } from "./handleErrors"; +import { streamThunkWrapper } from "./streamThunkWrapper"; import { resetStateForNewMessage } from "./resetStateForNewMessage"; import { streamNormalInput } from "./streamNormalInput"; import { streamSlashCommand } from "./streamSlashCommand"; import { selectDefaultModel } from "../slices/configSlice"; +import { v4 as uuidv4 } from "uuid"; const getSlashCommandForInput = ( input: MessageContent, @@ -66,24 +59,15 @@ export const streamResponseThunk = createAsyncThunk< { dispatch, extra, getState }, ) => { await dispatch( - handleErrors(async () => { + streamThunkWrapper(async () => { const state = getState(); const defaultModel = selectDefaultModel(state); const slashCommands = state.config.config.slashCommands || []; const inputIndex = index ?? state.session.history.length; - if (typeof index === "number") { - dispatch(resubmitAtIndex({ index, editorState })); - } else { - dispatch(initNewActiveMessage({ editorState })); - } - + dispatch(submitEditorAndInitAtIndex({ index, editorState })); resetStateForNewMessage(); - if (index) { - dispatch(setCurCheckpointIndex(Math.floor(index / 2))); - } - const result = await dispatch( gatherContext({ editorState, @@ -94,22 +78,17 @@ export const streamResponseThunk = createAsyncThunk< const unwrapped = unwrapResult(result); const { selectedContextItems, selectedCode, content } = unwrapped; - // Add the message to the history - const message: ChatMessage = { - role: "user", - content, - }; - const historyItem: ChatHistoryItem = { - message, - contextItems: selectedContextItems, - editorState, - }; - dispatch( - setMessageAtIndex({ - message, + updateHistoryItemAtIndex({ index: inputIndex, - contextItems: selectedContextItems, + updates: { + message: { + role: "user", + content, + id: uuidv4(), + }, + contextItems: selectedContextItems, + }, }), ); @@ -127,7 +106,7 @@ export const streamResponseThunk = createAsyncThunk< let commandAndInput = getSlashCommandForInput(content, slashCommands); if (!commandAndInput) { - await dispatch(streamNormalInput(messages)); + unwrapResult(await dispatch(streamNormalInput(messages))); } else { const [slashCommand, commandInput] = commandAndInput; let updatedContextItems = []; diff --git a/gui/src/redux/thunks/streamResponseAfterToolCall.ts b/gui/src/redux/thunks/streamResponseAfterToolCall.ts index 52b15c13f..39ba0a24a 100644 --- a/gui/src/redux/thunks/streamResponseAfterToolCall.ts +++ b/gui/src/redux/thunks/streamResponseAfterToolCall.ts @@ -1,4 +1,4 @@ -import { createAsyncThunk } from "@reduxjs/toolkit"; +import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; import { ChatMessage, ContextItem } from "core"; import { constructMessages } from "core/llm/constructMessages"; import { renderContextItems } from "core/util/messageContent"; @@ -9,7 +9,7 @@ import { streamUpdate, } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; -import { handleErrors } from "./handleErrors"; +import { streamThunkWrapper } from "./streamThunkWrapper"; import { resetStateForNewMessage } from "./resetStateForNewMessage"; import { streamNormalInput } from "./streamNormalInput"; @@ -24,7 +24,7 @@ export const streamResponseAfterToolCall = createAsyncThunk< "chat/streamAfterToolCall", async ({ toolCallId, toolOutput }, { dispatch, getState }) => { await dispatch( - handleErrors(async () => { + streamThunkWrapper(async () => { const state = getState(); const initialHistory = state.session.history; const defaultModel = selectDefaultModel(state); @@ -60,7 +60,7 @@ export const streamResponseAfterToolCall = createAsyncThunk< [...updatedHistory], defaultModel.model, ); - await dispatch(streamNormalInput(messages)); + unwrapResult(await dispatch(streamNormalInput(messages))); }), ); }, diff --git a/gui/src/redux/thunks/streamThunkWrapper.ts b/gui/src/redux/thunks/streamThunkWrapper.ts new file mode 100644 index 000000000..7b9000be8 --- /dev/null +++ b/gui/src/redux/thunks/streamThunkWrapper.ts @@ -0,0 +1,25 @@ +import { createAsyncThunk } from "@reduxjs/toolkit"; +import { clearLastEmptyResponse, setInactive } from "../slices/sessionSlice"; +import { ThunkApiType } from "../store"; +import { saveCurrentSession } from "./session"; + +export const streamThunkWrapper = createAsyncThunk< + void, + () => Promise, + ThunkApiType +>("chat/streamWrapper", async (runStream, { dispatch, extra }) => { + try { + await runStream(); + } catch (e: any) { + // NOTE - streaming errors are shown as ide toasts in core, don't show duplicate here + console.debug("Error streaming response: ", e); + dispatch(clearLastEmptyResponse()); + } finally { + dispatch(setInactive()); + await dispatch( + saveCurrentSession({ + openNewSession: false, + }), + ); + } +}); diff --git a/gui/src/redux/thunks/updateFileSymbols.ts b/gui/src/redux/thunks/updateFileSymbols.ts new file mode 100644 index 000000000..199fbc1b1 --- /dev/null +++ b/gui/src/redux/thunks/updateFileSymbols.ts @@ -0,0 +1,92 @@ +import { createAsyncThunk } from "@reduxjs/toolkit"; +import { ThunkApiType } from "../store"; +import { updateFileSymbols } from "../slices/sessionSlice"; +import { ContextItemWithId } from "core"; + +/* + Get file symbols for given context items + Overwrite symbols for existing file matches +*/ +export const updateFileSymbolsFromNewContextItems = createAsyncThunk< + void, + ContextItemWithId[], + ThunkApiType +>( + "symbols/updateFromContextItems", + async (contextItems, { dispatch, extra, getState }) => { + try { + // Get unique file uris from context items + const uniqueUris = Array.from( + new Set( + contextItems + .filter((item) => item.uri?.type === "file" && item?.uri?.value) + .map((item) => item.uri!.value), + ), + ); + + // Update symbols for those files + if (uniqueUris.length > 0) { + const result = await extra.ideMessenger.request( + "context/getSymbolsForFiles", + { uris: uniqueUris }, + ); + if (result.status === "error") { + throw new Error(result.error); + } + dispatch(updateFileSymbols(result.content)); + } + } catch (e) { + console.error( + "Error updating file symbols from context items", + e, + contextItems, + ); + } + }, +); + +/* + - Update file symbols for all context items in history + - That don't already have symbols +*/ +export const updateFileSymbolsFromHistory = createAsyncThunk< + void, + undefined, + ThunkApiType +>("symbols/updateFromHistory", async (_, { dispatch, extra, getState }) => { + try { + const state = getState(); + + // Get unique context item file uris from all history + const contextItems = state.session.history.flatMap( + (item) => item.contextItems, + ); + const uniqueUris = new Set( + contextItems + .filter((item) => item.uri?.type === "file" && item?.uri?.value) + .map((item) => item.uri!.value), + ); + + // Remove if already in symbols + Object.keys(state.session.symbols).forEach((key) => { + uniqueUris.delete(key); + }); + + const uriArray = Array.from(uniqueUris); + + // And then update symbols for those files + if (uriArray.length > 0) { + const result = await extra.ideMessenger.request( + "context/getSymbolsForFiles", + { uris: uriArray }, + ); + if (result.status === "error") { + throw new Error(result.error); + } + dispatch(updateFileSymbols(result.content)); + } + } catch (e) { + // Catch all - don't want file symbols to break the chat experience for now + console.error("Error updating file symbols from context items", e); + } +}); diff --git a/gui/src/util/localStorage.ts b/gui/src/util/localStorage.ts index 1f3fa7a61..f457e3544 100644 --- a/gui/src/util/localStorage.ts +++ b/gui/src/util/localStorage.ts @@ -8,7 +8,6 @@ type LocalStorageTypes = { ide: "vscode" | "jetbrains"; ftc: number; fontSize: number; - lastSessionId: string | undefined; [key: `inputHistory_${string}`]: JSONContent[]; extensionVersion: string; showTutorialCard: boolean; diff --git a/gui/src/util/symbols.ts b/gui/src/util/symbols.ts deleted file mode 100644 index a79e3eb2f..000000000 --- a/gui/src/util/symbols.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { ContextItemWithId } from "core"; -import { IIdeMessenger } from "../context/IdeMessenger"; -import { updateFileSymbols } from "../redux/slices/sessionSlice"; -import { Dispatch } from "@reduxjs/toolkit"; - -export async function updateFileSymbolsFromContextItems( - contextItems: ContextItemWithId[], - ideMessenger: IIdeMessenger, - dispatch: Dispatch, -) { - // Given a list of context items, - // Get unique file uris - try { - const contextUris = Array.from( - new Set( - contextItems - .filter((item) => item.uri?.type === "file" && item?.uri?.value) - .map((item) => item.uri!.value), - ), - ); - // And then update symbols for those files - if (contextUris.length > 0) { - const symbolsResult = await ideMessenger.request( - "context/getSymbolsForFiles", - { uris: contextUris }, - ); - if (symbolsResult.status === "success") { - dispatch(updateFileSymbols(symbolsResult.content)); - } - } - } catch (e) { - // Catch all - don't want file symbols to break the chat experience for now - console.error("Error updating file symbols from context items", e); - } -} diff --git a/package-lock.json b/package-lock.json index c147efa72..c588ac878 100644 --- a/package-lock.json +++ b/package-lock.json @@ -6,6 +6,7 @@ "": { "devDependencies": { "@typescript-eslint/parser": "^7.8.0", + "concurrently": "^9.1.0", "eslint-plugin-import": "^2.29.1", "prettier": "^3.3.3", "prettier-plugin-tailwindcss": "^0.6.8" @@ -359,7 +360,6 @@ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true, - "peer": true, "engines": { "node": ">=8" } @@ -369,7 +369,6 @@ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, - "peer": true, "dependencies": { "color-convert": "^2.0.1" }, @@ -586,7 +585,6 @@ "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", "dev": true, - "peer": true, "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" @@ -598,12 +596,25 @@ "url": "https://github.com/chalk/chalk?sponsor=1" } }, + "node_modules/cliui": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", + "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", + "dev": true, + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, "node_modules/color-convert": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", "dev": true, - "peer": true, "dependencies": { "color-name": "~1.1.4" }, @@ -615,8 +626,7 @@ "version": "1.1.4", "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "dev": true, - "peer": true + "dev": true }, "node_modules/concat-map": { "version": "0.0.1", @@ -624,6 +634,46 @@ "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", "dev": true }, + "node_modules/concurrently": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/concurrently/-/concurrently-9.1.0.tgz", + "integrity": "sha512-VxkzwMAn4LP7WyMnJNbHN5mKV9L2IbyDjpzemKr99sXNR3GqRNMMHdm7prV1ws9wg7ETj6WUkNOigZVsptwbgg==", + "dev": true, + "dependencies": { + "chalk": "^4.1.2", + "lodash": "^4.17.21", + "rxjs": "^7.8.1", + "shell-quote": "^1.8.1", + "supports-color": "^8.1.1", + "tree-kill": "^1.2.2", + "yargs": "^17.7.2" + }, + "bin": { + "conc": "dist/bin/concurrently.js", + "concurrently": "dist/bin/concurrently.js" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/open-cli-tools/concurrently?sponsor=1" + } + }, + "node_modules/concurrently/node_modules/supports-color": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", + "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", + "dev": true, + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, "node_modules/cross-spawn": { "version": "7.0.3", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", @@ -773,6 +823,12 @@ "node": ">=6.0.0" } }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true + }, "node_modules/es-abstract": { "version": "1.23.3", "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.23.3.tgz", @@ -906,6 +962,15 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "engines": { + "node": ">=6" + } + }, "node_modules/escape-string-regexp": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", @@ -1397,6 +1462,15 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "dev": true, + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, "node_modules/get-intrinsic": { "version": "1.2.4", "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.4.tgz", @@ -1577,7 +1651,6 @@ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", "dev": true, - "peer": true, "engines": { "node": ">=8" } @@ -1824,6 +1897,15 @@ "node": ">=0.10.0" } }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true, + "engines": { + "node": ">=8" + } + }, "node_modules/is-glob": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", @@ -2069,6 +2151,12 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", + "dev": true + }, "node_modules/lodash.merge": { "version": "4.6.2", "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", @@ -2513,6 +2601,15 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/resolve": { "version": "1.22.8", "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.8.tgz", @@ -2590,6 +2687,15 @@ "queue-microtask": "^1.2.2" } }, + "node_modules/rxjs": { + "version": "7.8.1", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.1.tgz", + "integrity": "sha512-AA3TVj+0A2iuIoQkWEK/tqFjBq2j+6PO6Y0zJcvzLAFhEFIO3HL0vls9hWLncZbAAbK0mar7oZ4V079I/qPMxg==", + "dev": true, + "dependencies": { + "tslib": "^2.1.0" + } + }, "node_modules/safe-array-concat": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/safe-array-concat/-/safe-array-concat-1.1.2.tgz", @@ -2692,6 +2798,18 @@ "node": ">=8" } }, + "node_modules/shell-quote": { + "version": "1.8.2", + "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.2.tgz", + "integrity": "sha512-AzqKpGKjrj7EM6rKVQEPpB288oCfnrEIuyoT9cyF4nmGa7V8Zk6f7RRqYisX8X9m+Q7bd632aZW4ky7EhbQztA==", + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/side-channel": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.6.tgz", @@ -2719,6 +2837,20 @@ "node": ">=8" } }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/string.prototype.trim": { "version": "1.2.9", "resolved": "https://registry.npmjs.org/string.prototype.trim/-/string.prototype.trim-1.2.9.tgz", @@ -2773,7 +2905,6 @@ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", "dev": true, - "peer": true, "dependencies": { "ansi-regex": "^5.0.1" }, @@ -2808,7 +2939,6 @@ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, - "peer": true, "dependencies": { "has-flag": "^4.0.0" }, @@ -2847,6 +2977,15 @@ "node": ">=8.0" } }, + "node_modules/tree-kill": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz", + "integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==", + "dev": true, + "bin": { + "tree-kill": "cli.js" + } + }, "node_modules/ts-api-utils": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-1.3.0.tgz", @@ -2871,6 +3010,12 @@ "strip-bom": "^3.0.0" } }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "dev": true + }, "node_modules/type-check": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", @@ -3070,6 +3215,23 @@ "node": ">=0.10.0" } }, + "node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, "node_modules/wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", @@ -3077,6 +3239,42 @@ "dev": true, "peer": true }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "dev": true, + "engines": { + "node": ">=10" + } + }, + "node_modules/yargs": { + "version": "17.7.2", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", + "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", + "dev": true, + "dependencies": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/yargs-parser": { + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", + "dev": true, + "engines": { + "node": ">=12" + } + }, "node_modules/yocto-queue": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", diff --git a/package.json b/package.json index 3009e5d12..c093fccd9 100644 --- a/package.json +++ b/package.json @@ -1,4 +1,11 @@ { + "scripts": { + "tsc:watch": "npx concurrently -n gui,vscode,core,binary -c cyan,magenta,yellow,green \"npm run tsc:watch:gui\" \"npm run tsc:watch:vscode\" \"npm run tsc:watch:core\" \"npm run tsc:watch:binary\"", + "tsc:watch:gui": "tsc --project gui/tsconfig.json --watch --noEmit --pretty", + "tsc:watch:vscode": "tsc --project extensions/vscode/tsconfig.json --watch --noEmit --pretty", + "tsc:watch:core": "tsc --project core/tsconfig.json --watch --noEmit --pretty", + "tsc:watch:binary": "tsc --project binary/tsconfig.json --watch --noEmit --pretty" + }, "devDependencies": { "@typescript-eslint/parser": "^7.8.0", "eslint-plugin-import": "^2.29.1", diff --git a/packages/config-types/src/index.ts b/packages/config-types/src/index.ts index 2170a116b..45b508c69 100644 --- a/packages/config-types/src/index.ts +++ b/packages/config-types/src/index.ts @@ -125,6 +125,7 @@ export const uiOptionsSchema = z.object({ fontSize: z.number().optional(), displayRawMarkdown: z.boolean().optional(), showChatScrollbar: z.boolean().optional(), + codeWrap: z.boolean().optional(), }); export type UiOptions = z.infer; diff --git a/packages/fetch/package-lock.json b/packages/fetch/package-lock.json index b7f80cb7d..9c923a4ad 100644 --- a/packages/fetch/package-lock.json +++ b/packages/fetch/package-lock.json @@ -1,12 +1,12 @@ { "name": "@continuedev/fetch", - "version": "1.0.2", + "version": "1.0.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/fetch", - "version": "1.0.2", + "version": "1.0.4", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.5", diff --git a/packages/fetch/package.json b/packages/fetch/package.json index 17223fc3f..6a7097284 100644 --- a/packages/fetch/package.json +++ b/packages/fetch/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/fetch", - "version": "1.0.3", + "version": "1.0.4", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/packages/fetch/src/fetch.ts b/packages/fetch/src/fetch.ts index 8e9ffc833..01fc631db 100644 --- a/packages/fetch/src/fetch.ts +++ b/packages/fetch/src/fetch.ts @@ -1,12 +1,13 @@ -import { RequestOptions } from "@continuedev/config-types/src/index.js"; -import * as followRedirects from "follow-redirects"; -import { HttpProxyAgent } from "http-proxy-agent"; import { globalAgent } from "https"; -import { HttpsProxyAgent } from "https-proxy-agent"; -import fetch, { RequestInit, Response } from "node-fetch"; import * as fs from "node:fs"; import tls from "node:tls"; +import { RequestOptions } from "@continuedev/config-types"; +import * as followRedirects from "follow-redirects"; +import { HttpProxyAgent } from "http-proxy-agent"; +import { HttpsProxyAgent } from "https-proxy-agent"; +import fetch, { RequestInit, Response } from "node-fetch"; + const { http, https } = (followRedirects as any).default; export function fetchwithRequestOptions( diff --git a/packages/llm-info/README.md b/packages/llm-info/README.md index 068a1d24a..8be4214bf 100644 --- a/packages/llm-info/README.md +++ b/packages/llm-info/README.md @@ -1,3 +1,32 @@ # @continuedev/llm-info -A lightweight package providing information about various Large Language Models (LLMs). +A lightweight package providing information about various Large Language Models (LLMs), including embedding, reranking, and other models. + +Whereas @continuedev/openai-adapters is responsible for translation between API types, @continuedev/llm-info is concerned with + +- Templates +- Capabilities (e.g. tools, images, streaming, predicted outputs, etc.) +- Model aliases + +and openai-adapters might depend on llm-info for some of these things. + +### Goal + +We know we are done when the steps required to add support for a new model in Continue are exactly + +1. editing a single LlmInfo object, and +2. adding it to the supporting ModelProviders. + +### Code structure + +The two primary types are LlmInfo and ModelProvider + +Models are defined on their own in the `models` directory. They can be grouped however makes sense. + +Providers are defined in the `providers` directory, with all models that they support in their `models` attribute. It's important that models are tied to providers, because the model might have slightly different attributes (e.g. context length) per provider. Define as much as possible in the base object, and then spread to update for the specific providers as needed. + +### Where to use llm-info + +- Replace autodetect.ts +- See usage in `BaseLLM` constructor, and finish the job of using llm-info everywhere relevant. +- Replace `gui/pages/AddNewModel/configs/[providers/models].ts` diff --git a/packages/llm-info/src/providers/voyage.ts b/packages/llm-info/src/providers/voyage.ts index 9bc5f6250..dc89305d4 100644 --- a/packages/llm-info/src/providers/voyage.ts +++ b/packages/llm-info/src/providers/voyage.ts @@ -6,6 +6,11 @@ export const Voyage: ModelProvider = { model: "voyage-code-2", displayName: "Voyage Code 2", contextLength: 8096, + }, + { + model: "voyage-code-3", + displayName: "Voyage Code 3", + contextLength: 8096, recommendedFor: ["embed"], }, { diff --git a/packages/llm-info/src/types.ts b/packages/llm-info/src/types.ts index 0440b6a4b..d96234a35 100644 --- a/packages/llm-info/src/types.ts +++ b/packages/llm-info/src/types.ts @@ -11,14 +11,20 @@ export interface Parameter { defaultValue?: any; } +export enum ChatTemplate { + None = "none", + // TODO +} + export interface LlmInfo { model: string; - provider: string; + // providers: string[]; // TODO: uncomment and deal with the consequences displayName?: string; description?: string; contextLength?: number; maxCompletionTokens?: number; regex?: RegExp; + chatTemplate?: ChatTemplate; /** If not set, assumes "text" only */ mediaTypes?: MediaType[]; @@ -52,12 +58,17 @@ export interface ApiProviderInfo { handlesTemplating: boolean; } -export type ModelProviderCapability = "stream" | "fim" | "image"; +export type ModelProviderCapability = + | "stream" + | "fim" + | "image" + | "template_chat" + | "tools"; export interface ModelProvider { id: string; displayName: string; - // capabilities: ModelProviderCapability[]; + // capabilities: ModelProviderCapability[]; // TODO: uncomment and deal with the consequences models: Omit[]; /** Any additional parameters required to configure the model diff --git a/packages/openai-adapters/README.md b/packages/openai-adapters/README.md new file mode 100644 index 000000000..3eb6de50a --- /dev/null +++ b/packages/openai-adapters/README.md @@ -0,0 +1,66 @@ +# OpenAI Adapters + +OpenAI adapters convert an OpenAI-compatible request to a request for another API and back. + +They are purely a translation layer, and are not concerned with: + +- Templates +- Whether a model supports tools, images, etc. +- Dynamically changing API base for model +- Keeping track of system message (it will always be the first message with a systemMesage) +- Keeping a private variable with anything that is already passed through the OpenAI request body +- Appending "/" to the apiBase (but this is TODO) +- Batching embeddings (yes, it requires some knowledge of max batch size, but it's more important to maintain 1 req = 1 req) +- Using streamChat for streamComplete and vice-versa if one isn't defined + +They are concerned with: + +- Converting model aliases +- Cache behavior +- max stop words +- use legacy completions endpoint? +- anything else that couldn't possibly be guess by the client since it won't know the endpoint behind the proxy + +## Supported APIs + +- [x] Anthropic +- [ ] AskSage +- [x] Azure +- [ ] Bedrock +- [ ] Bedrock Import +- [x] Cerebras +- [ ] Cloudflare +- [x] Cohere +- [x] DeepInfra +- [x] Deepseek +- [ ] Flowise +- [x] Function Network +- [x] Gemini +- [x] Groq +- [ ] HuggingFace Inference API +- [ ] HuggingFace TGI +- [x] Kindo +- [x] LMStudio +- [x] LlamaCpp +- [x] Llamafile +- [x] Msty +- [x] Mistral +- [x] Nvidia +- [x] Nebius +- [x] OpenRouter +- [x] OpenAI +- [ ] !Ollama +- [ ] Replicate +- [ ] SageMaker +- [x] SambaNova +- [x] Scaleway +- [ ] Silicon Flow +- [x] TextGen Web UI +- [x] Together +- [x] Vllm +- [ ] Vertex AI +- [x] Voyage AI +- [ ] WatsonX +- [x] xAI +- [x] Fireworks +- [x] Moonshot diff --git a/packages/openai-adapters/package-lock.json b/packages/openai-adapters/package-lock.json index af8cd0800..21e830ab2 100644 --- a/packages/openai-adapters/package-lock.json +++ b/packages/openai-adapters/package-lock.json @@ -1,19 +1,20 @@ { "name": "@continuedev/openai-adapters", - "version": "1.0.8", + "version": "1.0.9", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/openai-adapters", - "version": "1.0.8", + "version": "1.0.9", "license": "Apache-2.0", "dependencies": { "@azure/openai": "^1.0.0-beta.12", "@continuedev/config-types": "^1.0.5", "@continuedev/fetch": "^1.0.3", "node-fetch": "^3.3.2", - "openai": "^4.67.0" + "openai": "^4.76.0", + "zod": "^3.23.8" }, "devDependencies": { "@types/follow-redirects": "^1.14.4", @@ -3581,9 +3582,9 @@ } }, "node_modules/openai": { - "version": "4.67.0", - "resolved": "https://registry.npmjs.org/openai/-/openai-4.67.0.tgz", - "integrity": "sha512-jdsPSEdZbUNVtvEFE/eeL4FjKavyVMJJEdGMZk9vExglqUrblEcFxi3LK2WhskhrYKAU1MgJAI+dK9pDcA5z5w==", + "version": "4.76.0", + "resolved": "https://registry.npmjs.org/openai/-/openai-4.76.0.tgz", + "integrity": "sha512-QBGIetjX1C9xDp5XGa/3mPnfKI9BgAe2xHQX6PmO98wuW9qQaurBaumcYptQWc9LHZZq7cH/Y1Rjnsr6uUDdVw==", "dependencies": { "@types/node": "^18.11.18", "@types/node-fetch": "^2.6.4", diff --git a/packages/openai-adapters/package.json b/packages/openai-adapters/package.json index 5a4fe374d..a3d0bf7d0 100644 --- a/packages/openai-adapters/package.json +++ b/packages/openai-adapters/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/openai-adapters", - "version": "1.0.9", + "version": "1.0.10", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", @@ -16,7 +16,8 @@ "@continuedev/config-types": "^1.0.5", "@continuedev/fetch": "^1.0.3", "node-fetch": "^3.3.2", - "openai": "^4.67.0" + "openai": "^4.76.0", + "zod": "^3.23.8" }, "devDependencies": { "@types/follow-redirects": "^1.14.4", diff --git a/packages/openai-adapters/src/apis/Anthropic.ts b/packages/openai-adapters/src/apis/Anthropic.ts index 7df75dfae..926a36323 100644 --- a/packages/openai-adapters/src/apis/Anthropic.ts +++ b/packages/openai-adapters/src/apis/Anthropic.ts @@ -1,6 +1,5 @@ import { streamSse } from "@continuedev/fetch"; -import fetch from "node-fetch"; -import { OpenAI } from "openai/index.mjs"; +import { OpenAI } from "openai/index"; import { ChatCompletion, ChatCompletionChunk, @@ -9,9 +8,10 @@ import { Completion, CompletionCreateParamsNonStreaming, CompletionCreateParamsStreaming, -} from "openai/resources/index.mjs"; +} from "openai/resources/index"; import { ChatCompletionCreateParams } from "openai/src/resources/index.js"; -import { LlmApiConfig } from "../index.js"; +import { AnthropicConfig } from "../types.js"; +import { customFetch } from "../util.js"; import { BaseLlmApi, CreateRerankResponse, @@ -22,7 +22,7 @@ import { export class AnthropicApi implements BaseLlmApi { apiBase: string = "https://api.anthropic.com/v1/"; - constructor(protected config: LlmApiConfig) { + constructor(protected config: AnthropicConfig) { this.apiBase = config.apiBase ?? this.apiBase; if (!this.apiBase.endsWith("/")) { this.apiBase += "/"; @@ -87,17 +87,22 @@ export class AnthropicApi implements BaseLlmApi { async chatCompletionNonStream( body: ChatCompletionCreateParamsNonStreaming, + signal: AbortSignal, ): Promise { - const response = await fetch(new URL("messages", this.apiBase), { - method: "POST", - headers: { - "Content-Type": "application/json", - Accept: "application/json", - "anthropic-version": "2023-06-01", - "x-api-key": this.config.apiKey, + const response = await customFetch(this.config.requestOptions)( + new URL("messages", this.apiBase), + { + method: "POST", + headers: { + "Content-Type": "application/json", + Accept: "application/json", + "anthropic-version": "2023-06-01", + "x-api-key": this.config.apiKey, + }, + body: JSON.stringify(this._convertBody(body)), + signal, }, - body: JSON.stringify(this._convertBody(body)), - }); + ); const completion = (await response.json()) as any; return { @@ -127,18 +132,23 @@ export class AnthropicApi implements BaseLlmApi { } async *chatCompletionStream( body: ChatCompletionCreateParamsStreaming, + signal: AbortSignal, ): AsyncGenerator { body.messages; - const response = await fetch(new URL("messages", this.apiBase), { - method: "POST", - headers: { - "Content-Type": "application/json", - Accept: "application/json", - "anthropic-version": "2023-06-01", - "x-api-key": this.config.apiKey, + const response = await customFetch(this.config.requestOptions)( + new URL("messages", this.apiBase), + { + method: "POST", + headers: { + "Content-Type": "application/json", + Accept: "application/json", + "anthropic-version": "2023-06-01", + "x-api-key": this.config.apiKey, + }, + body: JSON.stringify(this._convertBody(body)), + signal, }, - body: JSON.stringify(this._convertBody(body)), - }); + ); for await (const value of streamSse(response as any)) { if (value.delta?.text) { @@ -165,16 +175,19 @@ export class AnthropicApi implements BaseLlmApi { } async completionNonStream( body: CompletionCreateParamsNonStreaming, + signal: AbortSignal, ): Promise { throw new Error("Method not implemented."); } async *completionStream( body: CompletionCreateParamsStreaming, + signal: AbortSignal, ): AsyncGenerator { throw new Error("Method not implemented."); } async *fimStream( body: FimCreateParamsStreaming, + signal: AbortSignal, ): AsyncGenerator { throw new Error("Method not implemented."); } @@ -188,4 +201,8 @@ export class AnthropicApi implements BaseLlmApi { async rerank(body: RerankCreateParams): Promise { throw new Error("Method not implemented."); } + + list(): Promise { + throw new Error("Method not implemented."); + } } diff --git a/packages/openai-adapters/src/apis/AzureOpenAI.ts b/packages/openai-adapters/src/apis/AzureOpenAI.ts index aabd9cf94..2b02af69d 100644 --- a/packages/openai-adapters/src/apis/AzureOpenAI.ts +++ b/packages/openai-adapters/src/apis/AzureOpenAI.ts @@ -13,8 +13,10 @@ import { ChatCompletionCreateParamsStreaming, CreateEmbeddingResponse, EmbeddingCreateParams, + Model, } from "openai/resources/index.js"; -import { LlmApiConfig } from "../index.js"; +import { AzureConfig } from "../types.js"; +import { embedding } from "../util.js"; import { BaseLlmApi, CreateRerankResponse, @@ -32,7 +34,7 @@ const MS_TOKEN = 30; export class AzureOpenAIApi implements BaseLlmApi { private client: OpenAIClient; - constructor(private config: LlmApiConfig) { + constructor(private config: AzureConfig) { let proxyOptions; const PROXY = HTTPS_PROXY ?? HTTP_PROXY; if (PROXY) { @@ -60,6 +62,7 @@ export class AzureOpenAIApi implements BaseLlmApi { body: | ChatCompletionCreateParamsStreaming | ChatCompletionCreateParamsNonStreaming, + signal: AbortSignal, ) { return { maxTokens: body.max_tokens ?? undefined, @@ -69,16 +72,18 @@ export class AzureOpenAIApi implements BaseLlmApi { presencePenalty: body.presence_penalty ?? undefined, stop: typeof body.stop === "string" ? [body.stop] : (body.stop ?? undefined), + abortSignal: signal, }; } async chatCompletionNonStream( body: ChatCompletionCreateParamsNonStreaming, + signal: AbortSignal, ): Promise { const completion = await this.client.getChatCompletions( body.model, body.messages, - this._bodyToOptions(body), + this._bodyToOptions(body, signal), ); return { ...completion, @@ -106,11 +111,12 @@ export class AzureOpenAIApi implements BaseLlmApi { } async *chatCompletionStream( body: ChatCompletionCreateParamsStreaming, + signal: AbortSignal, ): AsyncGenerator { const events = await this.client.streamChatCompletions( body.model, body.messages, - this._bodyToOptions(body), + this._bodyToOptions(body, signal), ); const eventBuffer: ChatCompletionChunk[] = []; @@ -167,6 +173,7 @@ export class AzureOpenAIApi implements BaseLlmApi { } async completionNonStream( body: CompletionCreateParamsNonStreaming, + signal: AbortSignal, ): Promise { const { prompt, logprobs, ...restOfBody } = body; const messages = [ @@ -175,10 +182,13 @@ export class AzureOpenAIApi implements BaseLlmApi { content: prompt as any, }, ]; - const resp = await this.chatCompletionNonStream({ - messages, - ...restOfBody, - }); + const resp = await this.chatCompletionNonStream( + { + messages, + ...restOfBody, + }, + signal, + ); return { ...resp, object: "text_completion", @@ -192,6 +202,7 @@ export class AzureOpenAIApi implements BaseLlmApi { } async *completionStream( body: CompletionCreateParamsStreaming, + signal: AbortSignal, ): AsyncGenerator { const { prompt, logprobs, ...restOfBody } = body; const messages = [ @@ -200,13 +211,21 @@ export class AzureOpenAIApi implements BaseLlmApi { content: prompt as any, }, ]; - for await (const event of this.chatCompletionStream({ - messages, - ...restOfBody, - })) { + for await (const event of this.chatCompletionStream( + { + messages, + ...restOfBody, + }, + signal, + )) { yield { ...event, object: "text_completion", + usage: { + completion_tokens: event.usage?.completion_tokens ?? 0, + prompt_tokens: event.usage?.prompt_tokens ?? 0, + total_tokens: event.usage?.total_tokens ?? 0, + }, choices: event.choices.map((choice) => ({ ...choice, text: choice.delta.content ?? "", @@ -231,18 +250,14 @@ export class AzureOpenAIApi implements BaseLlmApi { model: body.model, }); - const output = { - data: response.data.map((item) => ({ - ...item, - object: "embedding" as const, - })), + const output = embedding({ + data: response.data.map((item) => item.embedding), model: body.model, - object: "list" as const, usage: { prompt_tokens: response.usage.promptTokens, total_tokens: response.usage.totalTokens, }, - }; + }); return output; } @@ -250,4 +265,8 @@ export class AzureOpenAIApi implements BaseLlmApi { async rerank(body: RerankCreateParams): Promise { throw new Error("Azure OpenAI does not support reranking."); } + + list(): Promise { + throw new Error("Method not implemented."); + } } diff --git a/packages/openai-adapters/src/apis/Cohere.ts b/packages/openai-adapters/src/apis/Cohere.ts index f97dea327..416fd0a09 100644 --- a/packages/openai-adapters/src/apis/Cohere.ts +++ b/packages/openai-adapters/src/apis/Cohere.ts @@ -1,6 +1,5 @@ import { streamJSON } from "@continuedev/fetch"; -import fetch from "node-fetch"; -import { OpenAI } from "openai/index.mjs"; +import { OpenAI } from "openai/index"; import { ChatCompletion, ChatCompletionChunk, @@ -12,8 +11,10 @@ import { CompletionCreateParamsStreaming, CreateEmbeddingResponse, EmbeddingCreateParams, -} from "openai/resources/index.mjs"; -import { LlmApiConfig } from "../index.js"; + Model, +} from "openai/resources/index"; +import { CohereConfig } from "../types.js"; +import { chatCompletion, customFetch, embedding } from "../util.js"; import { BaseLlmApi, CreateRerankResponse, @@ -26,11 +27,8 @@ export class CohereApi implements BaseLlmApi { static maxStopSequences = 5; - constructor(protected config: LlmApiConfig) { + constructor(protected config: CohereConfig) { this.apiBase = config.apiBase ?? this.apiBase; - if (!this.apiBase.endsWith("/")) { - this.apiBase += "/"; - } } private _convertMessages( @@ -62,58 +60,55 @@ export class CohereApi implements BaseLlmApi { async chatCompletionNonStream( body: ChatCompletionCreateParamsNonStreaming, + signal: AbortSignal, ): Promise { const headers = { "Content-Type": "application/json", Authorization: `Bearer ${this.config.apiKey}`, }; - const resp = await fetch(new URL("chat", this.apiBase), { - method: "POST", - headers, - body: JSON.stringify(this._convertBody(body)), - }); + const resp = await customFetch(this.config.requestOptions)( + new URL("chat", this.apiBase), + { + method: "POST", + headers, + body: JSON.stringify(this._convertBody(body)), + signal, + }, + ); const data = (await resp.json()) as any; const { input_tokens, output_tokens } = data.meta.tokens; - return { - id: data.id, - object: "chat.completion", + return chatCompletion({ model: body.model, - created: Date.now(), + id: data.id, + content: data.text, usage: { total_tokens: input_tokens + output_tokens, completion_tokens: output_tokens, prompt_tokens: input_tokens, }, - choices: [ - { - logprobs: null, - finish_reason: "stop", - message: { - role: "assistant", - content: data.text, - refusal: null, - }, - index: 0, - }, - ], - }; + }); } async *chatCompletionStream( body: ChatCompletionCreateParamsStreaming, + signal: AbortSignal, ): AsyncGenerator { const headers = { "Content-Type": "application/json", Authorization: `Bearer ${this.config.apiKey}`, }; - const resp = await fetch(new URL("chat", this.apiBase), { - method: "POST", - headers, - body: JSON.stringify(this._convertBody(body)), - }); + const resp = await customFetch(this.config.requestOptions)( + new URL("chat", this.apiBase), + { + method: "POST", + headers, + body: JSON.stringify(this._convertBody(body)), + signal, + }, + ); for await (const value of streamJSON(resp as any)) { if (value.event_type === "text-generation") { @@ -155,7 +150,7 @@ export class CohereApi implements BaseLlmApi { } async rerank(body: RerankCreateParams): Promise { const endpoint = new URL("rerank", this.apiBase); - const response = await fetch(endpoint, { + const response = await customFetch(this.config.requestOptions)(endpoint, { method: "POST", body: JSON.stringify(body), headers: { @@ -182,7 +177,7 @@ export class CohereApi implements BaseLlmApi { async embed(body: EmbeddingCreateParams): Promise { const url = new URL("/embed", this.apiBase); const texts = typeof body.input === "string" ? [body.input] : body.input; - const response = await fetch(url, { + const response = await customFetch(this.config.requestOptions)(url, { method: "POST", headers: { "Content-Type": "application/json", @@ -196,18 +191,17 @@ export class CohereApi implements BaseLlmApi { }); const data = (await response.json()) as any; - return { - object: "list", + return embedding({ model: body.model, usage: { total_tokens: 0, prompt_tokens: 0, }, - data: data.embeddings.map((embedding: any, index: number) => ({ - object: "embedding", - index, - embedding, - })), - }; + data: data.embeddings.map((embedding: any) => embedding), + }); + } + + list(): Promise { + throw new Error("Method not implemented."); } } diff --git a/packages/openai-adapters/src/apis/DeepSeek.ts b/packages/openai-adapters/src/apis/DeepSeek.ts index 5ff6e41d5..cd2c70dbd 100644 --- a/packages/openai-adapters/src/apis/DeepSeek.ts +++ b/packages/openai-adapters/src/apis/DeepSeek.ts @@ -1,20 +1,25 @@ import { streamSse } from "@continuedev/fetch"; -import fetch from "node-fetch"; -import { ChatCompletionChunk } from "openai/resources/index.mjs"; -import { LlmApiConfig } from "../index.js"; +import { ChatCompletionChunk, Model } from "openai/resources/index"; +import { DeepseekConfig } from "../types.js"; +import { chatChunk, customFetch } from "../util.js"; import { OpenAIApi } from "./OpenAI.js"; import { FimCreateParamsStreaming } from "./base.js"; export class DeepSeekApi extends OpenAIApi { - constructor(config: LlmApiConfig) { - super(config); - this.apiBase = "https://api.deepseek.com/"; + apiBase: string = "https://api.deepseek.com/"; + constructor(config: DeepseekConfig) { + super({ + ...config, + provider: "openai", + }); } + async *fimStream( body: FimCreateParamsStreaming, + signal: AbortSignal, ): AsyncGenerator { const endpoint = new URL("beta/completions", this.apiBase); - const resp = await fetch(endpoint, { + const resp = await customFetch(this.config.requestOptions)(endpoint, { method: "POST", body: JSON.stringify({ model: body.model, @@ -33,25 +38,18 @@ export class DeepSeekApi extends OpenAIApi { Accept: "application/json", Authorization: `Bearer ${this.config.apiKey}`, }, + signal, }); for await (const chunk of streamSse(resp as any)) { - yield { - choices: [ - { - delta: { - content: chunk.choices[0].text, - role: "assistant", - }, - finish_reason: chunk.finish_reason, - index: 0, - logprobs: null, - }, - ], - created: Date.now(), - id: "", + yield chatChunk({ + content: chunk.choices[0].text, + finish_reason: chunk.finish_reason, model: body.model, - object: "chat.completion.chunk", - }; + }); } } + + list(): Promise { + throw new Error("Method not implemented."); + } } diff --git a/packages/openai-adapters/src/apis/Gemini.ts b/packages/openai-adapters/src/apis/Gemini.ts index c4f1948b9..716d8d582 100644 --- a/packages/openai-adapters/src/apis/Gemini.ts +++ b/packages/openai-adapters/src/apis/Gemini.ts @@ -1,6 +1,5 @@ import { streamResponse } from "@continuedev/fetch"; -import fetch from "node-fetch"; -import { OpenAI } from "openai/index.mjs"; +import { OpenAI } from "openai/index"; import { ChatCompletion, ChatCompletionChunk, @@ -12,8 +11,11 @@ import { CompletionCreateParamsStreaming, CreateEmbeddingResponse, EmbeddingCreateParams, -} from "openai/resources/index.mjs"; -import { LlmApiConfig } from "../index.js"; + Model, +} from "openai/resources/index"; + +import { GeminiConfig } from "../types.js"; +import { customFetch, embedding } from "../util.js"; import { BaseLlmApi, CreateRerankResponse, @@ -26,11 +28,8 @@ export class GeminiApi implements BaseLlmApi { static maxStopSequences = 5; - constructor(protected config: LlmApiConfig) { + constructor(protected config: GeminiConfig) { this.apiBase = config.apiBase ?? this.apiBase; - if (!this.apiBase.endsWith("/")) { - this.apiBase += "/"; - } } private _convertMessages( @@ -45,16 +44,22 @@ export class GeminiApi implements BaseLlmApi { private _oaiPartToGeminiPart( part: OpenAI.Chat.Completions.ChatCompletionContentPart, ) { - return part.type === "text" - ? { + switch (part.type) { + case "text": + return { text: part.text, - } - : { + }; + case "input_audio": + throw new Error("Unsupported part type: input_audio"); + case "image_url": + default: + return { inlineData: { mimeType: "image/jpeg", data: part.image_url?.url.split(",")[1], }, }; + } } private _convertBody(oaiBody: ChatCompletionCreateParams, url: string) { @@ -110,12 +115,16 @@ export class GeminiApi implements BaseLlmApi { async chatCompletionNonStream( body: ChatCompletionCreateParamsNonStreaming, + signal: AbortSignal, ): Promise { let completion = ""; - for await (const chunk of this.chatCompletionStream({ - ...body, - stream: true, - })) { + for await (const chunk of this.chatCompletionStream( + { + ...body, + stream: true, + }, + signal, + )) { completion += chunk.choices[0].delta.content; } return { @@ -141,14 +150,16 @@ export class GeminiApi implements BaseLlmApi { async *chatCompletionStream( body: ChatCompletionCreateParamsStreaming, + signal: AbortSignal, ): AsyncGenerator { const apiURL = new URL( `models/${body.model}:streamGenerateContent?key=${this.config.apiKey}`, this.apiBase, ).toString(); - const resp = await fetch(apiURL, { + const resp = await customFetch(this.config.requestOptions)(apiURL, { method: "POST", body: JSON.stringify(this._convertBody(body, apiURL)), + signal, }); let buffer = ""; @@ -232,7 +243,7 @@ export class GeminiApi implements BaseLlmApi { async embed(body: EmbeddingCreateParams): Promise { const inputs = Array.isArray(body.input) ? body.input : [body.input]; - const response = await fetch( + const response = await customFetch(this.config.requestOptions)( new URL(`${body.model}:batchEmbedContents`, this.apiBase), { method: "POST", @@ -255,18 +266,17 @@ export class GeminiApi implements BaseLlmApi { ); const data = (await response.json()) as any; - return { - object: "list", + return embedding({ model: body.model, usage: { - total_tokens: 0, - prompt_tokens: 0, + total_tokens: data.total_tokens, + prompt_tokens: data.prompt_tokens, }, - data: data.embeddings.map((embedding: any, index: number) => ({ - object: "embedding", - index, - embedding: embedding.values, - })), - }; + data: data.batchEmbedContents.map((embedding: any) => embedding.values), + }); + } + + list(): Promise { + throw new Error("Method not implemented."); } } diff --git a/packages/openai-adapters/src/apis/Jina.ts b/packages/openai-adapters/src/apis/Jina.ts index 7d5e2a40a..fb449e1d5 100644 --- a/packages/openai-adapters/src/apis/Jina.ts +++ b/packages/openai-adapters/src/apis/Jina.ts @@ -1,5 +1,4 @@ -import fetch from "node-fetch"; -import { OpenAI } from "openai/index.mjs"; +import { OpenAI } from "openai/index"; import { ChatCompletion, ChatCompletionChunk, @@ -8,8 +7,10 @@ import { Completion, CompletionCreateParamsNonStreaming, CompletionCreateParamsStreaming, -} from "openai/resources/index.mjs"; -import { LlmApiConfig } from "../index.js"; + Model, +} from "openai/resources/index"; +import { JinaConfig } from "../types.js"; +import { customFetch, rerank } from "../util.js"; import { BaseLlmApi, CreateRerankResponse, @@ -20,11 +21,8 @@ import { export class JinaApi implements BaseLlmApi { apiBase: string = "https://api.jina.ai/v1/"; - constructor(protected config: LlmApiConfig) { + constructor(protected config: JinaConfig) { this.apiBase = config.apiBase ?? this.apiBase; - if (!this.apiBase.endsWith("/")) { - this.apiBase += "/"; - } } async chatCompletionNonStream( @@ -61,7 +59,7 @@ export class JinaApi implements BaseLlmApi { async rerank(body: RerankCreateParams): Promise { const endpoint = new URL("rerank", this.apiBase); - const response = await fetch(endpoint, { + const response = await customFetch(this.config.requestOptions)(endpoint, { method: "POST", body: JSON.stringify(body), headers: { @@ -72,16 +70,17 @@ export class JinaApi implements BaseLlmApi { }, }); const data = (await response.json()) as any; - return { - object: "list", - data: data.results.map((result: any) => ({ - index: result.index, - relevance_score: result.relevance_score, - })), + + return rerank({ model: body.model, usage: { total_tokens: 0, }, - }; + data: data.results.map((result: any) => result.relevance_score), + }); + } + + list(): Promise { + throw new Error("Method not implemented."); } } diff --git a/packages/openai-adapters/src/apis/Moonshot.ts b/packages/openai-adapters/src/apis/Moonshot.ts index eb11124f0..fd65c64fd 100644 --- a/packages/openai-adapters/src/apis/Moonshot.ts +++ b/packages/openai-adapters/src/apis/Moonshot.ts @@ -1,21 +1,25 @@ import { streamSse } from "@continuedev/fetch"; -import fetch from "node-fetch"; -import { ChatCompletionChunk } from "openai/resources/index.mjs"; -import { LlmApiConfig } from "../index.js"; +import { ChatCompletionChunk, Model } from "openai/resources/index"; +import { MoonshotConfig } from "../types.js"; +import { chatChunk, customFetch } from "../util.js"; import { OpenAIApi } from "./OpenAI.js"; import { FimCreateParamsStreaming } from "./base.js"; export class MoonshotApi extends OpenAIApi { - constructor(config: LlmApiConfig) { - super(config); - this.apiBase = "https://api.moonshot.cn/"; + apiBase: string = "https://api.moonshot.cn/"; + constructor(config: MoonshotConfig) { + super({ + ...config, + provider: "openai", + }); } async *fimStream( body: FimCreateParamsStreaming, + signal: AbortSignal, ): AsyncGenerator { const endpoint = new URL("v1/chat/completions", this.apiBase); - const resp = await fetch(endpoint, { + const resp = await customFetch(this.config.requestOptions)(endpoint, { method: "POST", body: JSON.stringify({ model: body.model, @@ -38,26 +42,18 @@ export class MoonshotApi extends OpenAIApi { Accept: "application/json", Authorization: `Bearer ${this.config.apiKey}`, }, + signal, }); for await (const chunk of streamSse(resp as any)) { - yield { - choices: [ - { - delta: { - content: chunk.choices[0].delta.content, - role: "assistant", - }, - finish_reason: chunk.finish_reason, - index: 0, - logprobs: null, - }, - ], - created: Date.now(), - id: "", + yield chatChunk({ + content: chunk.choices[0].delta.content, + finish_reason: chunk.finish_reason, model: body.model, - object: "chat.completion.chunk", - }; + }); } } + list(): Promise { + throw new Error("Method not implemented."); + } } diff --git a/packages/openai-adapters/src/apis/OpenAI.ts b/packages/openai-adapters/src/apis/OpenAI.ts index c05cc749c..db52a6758 100644 --- a/packages/openai-adapters/src/apis/OpenAI.ts +++ b/packages/openai-adapters/src/apis/OpenAI.ts @@ -1,6 +1,6 @@ import { streamSse } from "@continuedev/fetch"; import fetch from "node-fetch"; -import { OpenAI } from "openai/index.mjs"; +import { OpenAI } from "openai/index"; import { ChatCompletion, ChatCompletionChunk, @@ -9,8 +9,11 @@ import { Completion, CompletionCreateParamsNonStreaming, CompletionCreateParamsStreaming, -} from "openai/resources/index.mjs"; -import { LlmApiConfig } from "../index.js"; + Model, +} from "openai/resources/index"; +import { z } from "zod"; +import { OpenAIConfigSchema } from "../types.js"; +import { maybeCustomFetch } from "../util.js"; import { BaseLlmApi, CreateRerankResponse, @@ -22,47 +25,54 @@ export class OpenAIApi implements BaseLlmApi { openai: OpenAI; apiBase: string = "https://api.openai.com/v1/"; - constructor(protected config: LlmApiConfig) { + constructor(protected config: z.infer) { this.apiBase = config.apiBase ?? this.apiBase; - if (!this.apiBase.endsWith("/")) { - this.apiBase += "/"; - } this.openai = new OpenAI({ apiKey: config.apiKey, baseURL: this.apiBase, + fetch: maybeCustomFetch(config.requestOptions), }); } async chatCompletionNonStream( body: ChatCompletionCreateParamsNonStreaming, + signal: AbortSignal, ): Promise { - const response = await this.openai.chat.completions.create(body); + const response = await this.openai.chat.completions.create(body, { + signal, + }); return response; } async *chatCompletionStream( body: ChatCompletionCreateParamsStreaming, + signal: AbortSignal, ): AsyncGenerator { - const response = await this.openai.chat.completions.create(body); + const response = await this.openai.chat.completions.create(body, { + signal, + }); for await (const result of response) { yield result; } } async completionNonStream( body: CompletionCreateParamsNonStreaming, + signal: AbortSignal, ): Promise { - const response = await this.openai.completions.create(body); + const response = await this.openai.completions.create(body, { signal }); return response; } async *completionStream( body: CompletionCreateParamsStreaming, + signal: AbortSignal, ): AsyncGenerator { - const response = await this.openai.completions.create(body); + const response = await this.openai.completions.create(body, { signal }); for await (const result of response) { yield result; } } async *fimStream( body: FimCreateParamsStreaming, + signal: AbortSignal, ): AsyncGenerator { const endpoint = new URL("fim/completions", this.apiBase); const resp = await fetch(endpoint, { @@ -86,6 +96,7 @@ export class OpenAIApi implements BaseLlmApi { "x-api-key": this.config.apiKey ?? "", Authorization: `Bearer ${this.config.apiKey}`, }, + signal, }); for await (const chunk of streamSse(resp as any)) { if (chunk.choices && chunk.choices.length > 0) { @@ -116,4 +127,8 @@ export class OpenAIApi implements BaseLlmApi { const data = await response.json(); return data as any; } + + async list(): Promise { + return (await this.openai.models.list()).data; + } } diff --git a/packages/openai-adapters/src/apis/base.ts b/packages/openai-adapters/src/apis/base.ts index ee812b8e4..5079aedef 100644 --- a/packages/openai-adapters/src/apis/base.ts +++ b/packages/openai-adapters/src/apis/base.ts @@ -8,7 +8,8 @@ import { CompletionCreateParamsStreaming, CreateEmbeddingResponse, EmbeddingCreateParams, -} from "openai/resources/index.mjs"; + Model, +} from "openai/resources/index"; export interface FimCreateParamsStreaming extends CompletionCreateParamsStreaming { @@ -40,26 +41,31 @@ export interface BaseLlmApi { // Chat, no stream chatCompletionNonStream( body: ChatCompletionCreateParamsNonStreaming, + signal: AbortSignal, ): Promise; // Chat, stream chatCompletionStream( body: ChatCompletionCreateParamsStreaming, + signal: AbortSignal, ): AsyncGenerator; // Completion, no stream completionNonStream( body: CompletionCreateParamsNonStreaming, + signal: AbortSignal, ): Promise; // Completion, stream completionStream( body: CompletionCreateParamsStreaming, + signal: AbortSignal, ): AsyncGenerator; // FIM, stream fimStream( body: FimCreateParamsStreaming, + signal: AbortSignal, ): AsyncGenerator; // Embeddings @@ -67,4 +73,7 @@ export interface BaseLlmApi { // Reranking rerank(body: RerankCreateParams): Promise; + + // List Models + list(): Promise; } diff --git a/packages/openai-adapters/src/index.ts b/packages/openai-adapters/src/index.ts index 4856a7b11..fa02153fa 100644 --- a/packages/openai-adapters/src/index.ts +++ b/packages/openai-adapters/src/index.ts @@ -1,4 +1,5 @@ import dotenv from "dotenv"; +import { z } from "zod"; import { AnthropicApi } from "./apis/Anthropic.js"; import { AzureOpenAIApi } from "./apis/AzureOpenAI.js"; import { BaseLlmApi } from "./apis/base.js"; @@ -8,32 +9,26 @@ import { GeminiApi } from "./apis/Gemini.js"; import { JinaApi } from "./apis/Jina.js"; import { MoonshotApi } from "./apis/Moonshot.js"; import { OpenAIApi } from "./apis/OpenAI.js"; +import { LLMConfig, OpenAIConfigSchema } from "./types.js"; dotenv.config(); -export interface LlmApiConfig { - provider: string; - model: string; - apiKey: string; - apiBase?: string; +function openAICompatible( + apiBase: string, + config: z.infer, +): OpenAIApi { + return new OpenAIApi({ + ...config, + apiBase: config.apiBase ?? apiBase, + }); } -export function constructLlmApi(config: LlmApiConfig): BaseLlmApi { +export function constructLlmApi(config: LLMConfig): BaseLlmApi | undefined { switch (config.provider) { case "openai": return new OpenAIApi(config); - case "mistral": - return new OpenAIApi({ - ...config, - apiBase: "https://api.mistral.ai/v1/", - }); case "azure": return new AzureOpenAIApi(config); - case "voyage": - return new OpenAIApi({ - ...config, - apiBase: "https://api.voyageai.com/v1/", - }); case "cohere": return new CohereApi(config); case "anthropic": @@ -42,47 +37,53 @@ export function constructLlmApi(config: LlmApiConfig): BaseLlmApi { return new GeminiApi(config); case "jina": return new JinaApi(config); - case "deepinfra": - return new OpenAIApi({ - ...config, - apiBase: "https://api.deepinfra.com/v1/openai/", - }); case "deepseek": return new DeepSeekApi(config); case "moonshot": return new MoonshotApi(config); + case "x-ai": + return openAICompatible("https://api.x.ai/v1/", config); + case "voyage": + return openAICompatible("https://api.voyageai.com/v1/", config); + case "mistral": + return openAICompatible("https://api.mistral.ai/v1/", config); + case "deepinfra": + return openAICompatible("https://api.deepinfra.com/v1/openai/", config); + case "vllm": + return openAICompatible("http://localhost:8000/v1/", config); case "groq": - return new OpenAIApi({ - ...config, - apiBase: "https://api.groq.com/openai/v1/", - }); - case "nvidia": - return new OpenAIApi({ - ...config, - apiBase: "https://integrate.api.nvidia.com/v1/", - }); - case "fireworks": - return new OpenAIApi({ - ...config, - apiBase: "https://api.fireworks.ai/inference/v1", - }); - case "together": - return new OpenAIApi({ - ...config, - apiBase: "https://api.together.xyz/v1/", - }); + return openAICompatible("https://api.groq.com/openai/v1/", config); case "sambanova": - return new OpenAIApi({ - ...config, - apiBase: "https://api.sambanova.ai/v1/", - }); + return openAICompatible("https://api.sambanova.ai/v1/", config); + case "text-gen-webui": + return openAICompatible("http://127.0.0.1:5000/v1/", config); + case "openrouter": + return openAICompatible("https://openrouter.ai/api/v1/", config); + case "cerebras": + return openAICompatible("https://api.cerebras.ai/v1/", config); + case "kindo": + return openAICompatible("https://llm.kindo.ai/v1/", config); + case "msty": + return openAICompatible("http://localhost:10000", config); + case "nvidia": + return openAICompatible("https://integrate.api.nvidia.com/v1/", config); + case "scaleway": + return openAICompatible("https://api.scaleway.ai/v1/", config); + case "fireworks": + return openAICompatible("https://api.fireworks.ai/inference/v1/", config); + case "together": + return openAICompatible("https://api.together.xyz/v1/", config); case "nebius": - return new OpenAIApi({ - ...config, - apiBase: "https://api.studio.nebius.ai/v1/", - }); + return openAICompatible("https://api.studio.nebius.ai/v1/", config); + case "function-network": + return openAICompatible("https://api.function.network/v1/", config); + case "llama.cpp": + case "llamafile": + return openAICompatible("http://localhost:8000/", config); + case "lmstudio": + return openAICompatible("http://localhost:1234/", config); default: - throw new Error(`Unsupported LLM API format: ${config.provider}`); + return undefined; } } @@ -96,4 +97,6 @@ export { type CompletionCreateParams, type CompletionCreateParamsNonStreaming, type CompletionCreateParamsStreaming, -} from "openai/resources/index.mjs"; +} from "openai/resources/index"; + +export type { BaseLlmApi } from "./apis/base.js"; diff --git a/packages/openai-adapters/src/test/util.ts b/packages/openai-adapters/src/test/util.ts new file mode 100644 index 000000000..e69de29bb diff --git a/packages/openai-adapters/src/types.ts b/packages/openai-adapters/src/types.ts new file mode 100644 index 000000000..fbb21e2e0 --- /dev/null +++ b/packages/openai-adapters/src/types.ts @@ -0,0 +1,109 @@ +import * as z from "zod"; + +export const ClientCertificateOptionsSchema = z.object({ + cert: z.string(), + key: z.string(), + passphrase: z.string().optional(), +}); + +export const RequestOptionsSchema = z.object({ + timeout: z.number().optional(), + verifySsl: z.boolean().optional(), + caBundlePath: z.union([z.string(), z.array(z.string())]).optional(), + proxy: z.string().optional(), + headers: z.record(z.string()).optional(), + extraBodyProperties: z.record(z.unknown()).optional(), + noProxy: z.array(z.string()).optional(), + clientCertificate: z.lazy(() => ClientCertificateOptionsSchema).optional(), +}); + +// Base config objects +export const BaseConfig = z.object({ + provider: z.string(), + requestOptions: RequestOptionsSchema.optional(), +}); + +export const BasePlusConfig = BaseConfig.extend({ + apiBase: z.string().optional(), + apiKey: z.string().optional(), +}); + +// OpenAI and compatible +export const OpenAIConfigSchema = BasePlusConfig.extend({ + provider: z.union([ + z.literal("openai"), + z.literal("mistral"), + z.literal("voyage"), + z.literal("deepinfra"), + z.literal("groq"), + z.literal("nvidia"), + z.literal("fireworks"), + z.literal("together"), + z.literal("sambanova"), + z.literal("nebius"), + z.literal("function-network"), + z.literal("llama.cpp"), + z.literal("llamafile"), + z.literal("lmstudio"), + z.literal("cerebras"), + z.literal("kindo"), + z.literal("msty"), + z.literal("openrouter"), + z.literal("sambanova"), + z.literal("text-gen-webui"), + z.literal("vllm"), + z.literal("x-ai"), + ]), +}); +export type OpenAIConfig = z.infer; + +export const MoonshotConfigSchema = OpenAIConfigSchema.extend({ + provider: z.literal("moonshot"), +}); +export type MoonshotConfig = z.infer; + +export const DeepseekConfigSchema = OpenAIConfigSchema.extend({ + provider: z.literal("deepseek"), +}); +export type DeepseekConfig = z.infer; + +// Other APIs +export const CohereConfigSchema = OpenAIConfigSchema.extend({ + provider: z.literal("cohere"), +}); +export type CohereConfig = z.infer; + +export const AzureConfigSchema = OpenAIConfigSchema.extend({ + provider: z.literal("azure"), +}); +export type AzureConfig = z.infer; + +export const GeminiConfigSchema = OpenAIConfigSchema.extend({ + provider: z.literal("gemini"), + apiKey: z.string(), +}); +export type GeminiConfig = z.infer; + +export const AnthropicConfigSchema = OpenAIConfigSchema.extend({ + provider: z.literal("anthropic"), + apiKey: z.string(), +}); +export type AnthropicConfig = z.infer; + +export const JinaConfigSchema = OpenAIConfigSchema.extend({ + provider: z.literal("jina"), +}); +export type JinaConfig = z.infer; + +// Discriminated union +export const LLMConfigSchema = z.discriminatedUnion("provider", [ + OpenAIConfigSchema, + MoonshotConfigSchema, + DeepseekConfigSchema, + CohereConfigSchema, + AzureConfigSchema, + GeminiConfigSchema, + AnthropicConfigSchema, + JinaConfigSchema, +]); +export type LLMConfig = z.infer; diff --git a/packages/openai-adapters/src/util.ts b/packages/openai-adapters/src/util.ts new file mode 100644 index 000000000..afdc1cb11 --- /dev/null +++ b/packages/openai-adapters/src/util.ts @@ -0,0 +1,125 @@ +import { RequestOptions } from "@continuedev/config-types"; +import { fetchwithRequestOptions } from "@continuedev/fetch"; +import fetch from "node-fetch"; +import { + ChatCompletionChunk, + CompletionUsage, + CreateEmbeddingResponse, + Model, +} from "openai/resources/index"; +import { ChatCompletion } from "openai/src/resources/index.js"; +import { CreateRerankResponse } from "./apis/base.js"; + +export function chatChunk(options: { + content: string | null | undefined; + model: string; + finish_reason?: ChatCompletionChunk.Choice["finish_reason"]; + id?: string | null; + usage?: CompletionUsage; +}): ChatCompletionChunk { + return { + choices: [ + { + delta: { + content: options.content, + role: "assistant", + }, + finish_reason: options.finish_reason ?? "stop", + index: 0, + logprobs: null, + }, + ], + usage: options.usage, + created: Date.now(), + id: options.id ?? "", + model: options.model, + object: "chat.completion.chunk", + }; +} + +export function chatCompletion(options: { + content: string | null | undefined; + model: string; + finish_reason?: ChatCompletion.Choice["finish_reason"]; + id?: string | null; + usage?: CompletionUsage; + index?: number | null; +}): ChatCompletion { + return { + choices: [ + { + finish_reason: options.finish_reason ?? "stop", + index: options.index ?? 0, + logprobs: null, + message: { + content: options.content ?? null, + role: "assistant", + refusal: null, + }, + }, + ], + usage: options.usage, + created: Date.now(), + id: options.id ?? "", + model: options.model, + object: "chat.completion", + }; +} + +export function embedding(options: { + data: number[][]; + model: string; + usage?: CreateEmbeddingResponse.Usage; +}): CreateEmbeddingResponse { + return { + data: options.data.map((embedding, i) => ({ + index: i, + embedding: embedding, + object: "embedding" as const, + })), + model: options.model, + object: "list" as const, + usage: options.usage ?? { + prompt_tokens: 0, + total_tokens: 0, + }, + }; +} + +export function rerank(options: { + model: string; + data: number[]; + usage?: CreateRerankResponse["usage"]; +}): CreateRerankResponse { + return { + data: options.data.map((score, index) => ({ + index, + relevance_score: score, + })), + model: options.model, + object: "list" as const, + usage: options.usage ?? { + total_tokens: 0, + }, + }; +} + +export function model(options: { id: string; owned_by?: string }): Model { + return { + id: options.id, + object: "model", + created: Date.now(), + owned_by: options.owned_by ?? "organization-owner", + }; +} + +export function maybeCustomFetch(requestOptions: RequestOptions | undefined) { + return requestOptions + ? (url: any, init: any) => + fetchwithRequestOptions(url, init, requestOptions) + : undefined; +} + +export function customFetch(requestOptions: RequestOptions | undefined) { + return maybeCustomFetch(requestOptions) ?? fetch; +} diff --git a/packages/openai-adapters/test/main.test.ts b/packages/openai-adapters/test/main.test.ts index efe8cc7c5..4a9117cab 100644 --- a/packages/openai-adapters/test/main.test.ts +++ b/packages/openai-adapters/test/main.test.ts @@ -279,6 +279,12 @@ const COMPLETION_TESTS: ({ chatOnly?: boolean } & LlmApiConfig)[] = [ apiKey: process.env.NEBIUS_API_KEY!, chatOnly: true, }, + { + provider: "scaleway", + model: "llama3.1-8b", + apiKey: process.env.SCALEWAY_API_KEY!, + chatOnly: true, + }, ]; const FIM_TESTS: LlmApiConfig[] = [ @@ -303,7 +309,7 @@ const EMBEDDINGS_TESTS: LlmApiConfig[] = [ }, { provider: "openai", - model: "voyage-code-2", + model: "voyage-code-3", apiKey: process.env.VOYAGE_API_KEY!, apiBase: "https://api.voyageai.com/v1/", }, @@ -322,6 +328,11 @@ const EMBEDDINGS_TESTS: LlmApiConfig[] = [ model: "BAAI/bge-en-icl", apiKey: process.env.NEBIUS_API_KEY!, }, + { + provider: "scaleway", + model: "bge-multilingual-gemma2", + apiKey: process.env.SCALEWAY_API_KEY!, + }, ]; const RERANK_TESTS: LlmApiConfig[] = [