merge main
This commit is contained in:
commit
a88915ec71
304 changed files with 7723 additions and 4214 deletions
41
.continue/prompts/core-unit-test.prompt
Normal file
41
.continue/prompts/core-unit-test.prompt
Normal file
|
|
@ -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)
|
||||
|
|
@ -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
|
||||
10
.github/auto_assign.yml
vendored
Normal file
10
.github/auto_assign.yml
vendored
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
# Reference: https://github.com/marketplace/actions/auto-assign-action
|
||||
addAssignees: true
|
||||
|
||||
assignees:
|
||||
- sestinj
|
||||
- Patrick-Erichsen
|
||||
- tomasz-stefaniak
|
||||
- RomneyDa
|
||||
|
||||
numberOfAssignees: 2
|
||||
10
.github/workflows/auto-assign-pr.yaml
vendored
Normal file
10
.github/workflows/auto-assign-pr.yaml
vendored
Normal file
|
|
@ -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
|
||||
254
.github/workflows/pr_checks.yaml
vendored
254
.github/workflows/pr_checks.yaml
vendored
|
|
@ -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: |
|
||||
|
|
|
|||
5
.gitignore
vendored
5
.gitignore
vendored
|
|
@ -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
|
||||
*.vsix
|
||||
34
.vscode/tasks.json
vendored
34
.vscode/tasks.json
vendored
|
|
@ -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"
|
||||
]
|
||||
},
|
||||
|
|
|
|||
4
binary/package-lock.json
generated
4
binary/package-lock.json
generated
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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) {
|
||||
|
|
|
|||
|
|
@ -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";
|
||||
|
|
|
|||
|
|
@ -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";
|
||||
|
||||
|
|
|
|||
|
|
@ -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";
|
||||
|
|
|
|||
|
|
@ -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));
|
||||
|
|
|
|||
|
|
@ -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. */
|
||||
|
|
|
|||
3
core/.gitignore
vendored
3
core/.gitignore
vendored
|
|
@ -3,6 +3,5 @@ target
|
|||
**/.DS_Store
|
||||
npm-debug.log*
|
||||
.env
|
||||
.continue-test
|
||||
testDir
|
||||
test/.continue-test
|
||||
coverage
|
||||
|
|
@ -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 === "") {
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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`,
|
||||
},
|
||||
|
||||
{
|
||||
|
|
|
|||
149
core/commands/util.test.ts
Normal file
149
core/commands/util.test.ts
Normal file
|
|
@ -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);
|
||||
});
|
||||
});
|
||||
|
|
@ -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,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -846,6 +846,7 @@ declare global {
|
|||
codeBlockToolbarPosition?: "top" | "bottom";
|
||||
fontSize?: number;
|
||||
displayRawMarkdown?: boolean;
|
||||
codeWrap?: boolean;
|
||||
}
|
||||
|
||||
interface ContextMenuConfig {
|
||||
|
|
|
|||
17
core/context/allRerankers.ts
Normal file
17
core/context/allRerankers.ts
Normal file
|
|
@ -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,
|
||||
};
|
||||
|
|
@ -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<number[]> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
|
@ -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<number[]> {
|
||||
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()();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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<number[]> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
|
@ -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<number[]> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
|
@ -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,
|
||||
};
|
||||
|
|
@ -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<number[]> {
|
||||
let apiBase = this.params.apiBase ?? HuggingFaceTEIReranker.defaultOptions.apiBase;
|
||||
if (!apiBase.endsWith("/")) {
|
||||
apiBase += "/";
|
||||
}
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
"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);
|
||||
}
|
||||
}
|
||||
|
|
@ -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,
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -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";
|
||||
|
|
|
|||
|
|
@ -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) => {
|
||||
|
|
|
|||
117
core/context/retrieval/utils.test.ts
Normal file
117
core/context/retrieval/utils.test.ts
Normal file
|
|
@ -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,
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
12
core/core.ts
12
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<ToCoreProtocol, FromCoreProtocol>
|
||||
|
|
@ -372,7 +373,6 @@ export class Core {
|
|||
msg: Message<ToCoreProtocol["llm/streamChat"][0]>,
|
||||
) {
|
||||
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) => {
|
||||
|
|
|
|||
|
|
@ -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" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
200
core/diff/util.test.ts
Normal file
200
core/diff/util.test.ts
Normal file
|
|
@ -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<string> {
|
||||
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<ChatMessage> {
|
||||
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<string> {
|
||||
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);
|
||||
});
|
||||
});
|
||||
109
core/edit/lazy/findInAst.test.ts
Normal file
109
core/edit/lazy/findInAst.test.ts
Normal file
|
|
@ -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<Parser.SyntaxNode> = {
|
||||
type,
|
||||
children,
|
||||
childCount: children.length,
|
||||
child: (index: number) => {
|
||||
return children[index] || null;
|
||||
},
|
||||
};
|
||||
return node as Parser.SyntaxNode;
|
||||
}
|
||||
|
|
@ -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;
|
||||
|
|
|
|||
77
core/edit/streamDiffLines.test.ts
Normal file
77
core/edit/streamDiffLines.test.ts
Normal file
|
|
@ -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<DiffLine> {
|
||||
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");
|
||||
});
|
||||
});
|
||||
|
|
@ -30,7 +30,7 @@ function constructPrompt(
|
|||
});
|
||||
}
|
||||
|
||||
async function* addIndentation(
|
||||
export async function* addIndentation(
|
||||
diffLineGenerator: AsyncGenerator<DiffLine>,
|
||||
indentation: string,
|
||||
): AsyncGenerator<DiffLine> {
|
||||
|
|
@ -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,
|
||||
});
|
||||
|
||||
|
|
|
|||
237
core/index.d.ts
vendored
237
core/index.d.ts
vendored
|
|
@ -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<ChatMessage>;
|
||||
|
||||
embed(chunks: string[]): Promise<number[][]>;
|
||||
|
||||
rerank(query: string, chunks: Chunk[]): Promise<number[]>;
|
||||
|
||||
countTokens(text: string): number;
|
||||
|
||||
supportsImages(): boolean;
|
||||
|
|
@ -175,8 +176,8 @@ export type FetchFunction = (url: string | URL, init?: any) => Promise<any>;
|
|||
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<string, SymbolWithRange[]>;
|
||||
|
|
@ -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<number[][]>;
|
||||
}
|
||||
|
||||
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<number[]>;
|
||||
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<TabAutocompleteOptions>;
|
||||
ui?: ContinueUIConfig;
|
||||
reranker?: Reranker;
|
||||
reranker?: ILLM;
|
||||
experimental?: ExperimentalConfig;
|
||||
analytics?: AnalyticsConfig;
|
||||
docs?: SiteIndexingConfig[];
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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<string, ItemWithChunks>;
|
|||
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<string>,
|
||||
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",
|
||||
};
|
||||
}
|
||||
|
|
|
|||
49
core/indexing/allEmbeddingsProviders.ts
Normal file
49
core/indexing/allEmbeddingsProviders.ts
Normal file
|
|
@ -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,
|
||||
};
|
||||
87
core/indexing/chunk/basic.test.ts
Normal file
87
core/indexing/chunk/basic.test.ts
Normal file
|
|
@ -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);
|
||||
});
|
||||
});
|
||||
|
|
@ -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,
|
||||
},
|
||||
}));
|
||||
|
||||
|
|
@ -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<EmbeddingsProvider> {
|
||||
async getEmbeddingsProvider(isPreIndexedDoc: boolean = false): Promise<ILLM> {
|
||||
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");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
283
core/indexing/docs/suggestions/suggestions.test.ts
Normal file
283
core/indexing/docs/suggestions/suggestions.test.ts
Normal file
|
|
@ -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<typeof fetch>;
|
||||
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<typeof fetch>;
|
||||
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<typeof fetch>;
|
||||
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<typeof fetch>;
|
||||
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<typeof fetch>;
|
||||
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",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -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<number[][]>;
|
||||
|
||||
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;
|
||||
|
|
@ -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<EmbedOptions> = {
|
||||
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<number[][]> {
|
||||
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;
|
||||
|
|
@ -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<EmbedOptions> | 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<Response>(() =>
|
||||
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;
|
||||
|
|
@ -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;
|
||||
|
|
@ -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<EmbedOptions> | undefined = {
|
||||
model: "sentence-transformers/all-MiniLM-L6-v2",
|
||||
};
|
||||
|
||||
async embed(chunks: string[]) {
|
||||
const fetchWithBackoff = () =>
|
||||
withExponentialBackoff<Response>(() =>
|
||||
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;
|
||||
|
|
@ -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<EmbedOptions> | 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<Response>(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;
|
||||
|
|
@ -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<EmbedOptions> | 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<Response>(() =>
|
||||
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;
|
||||
|
|
@ -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<Response>(() =>
|
||||
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;
|
||||
|
|
@ -1,14 +0,0 @@
|
|||
import { EmbeddingsProviderName, EmbedOptions } from "../..";
|
||||
|
||||
import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider";
|
||||
|
||||
class LMStudioEmbeddingsProvider extends OpenAIEmbeddingsProvider {
|
||||
static providerName: EmbeddingsProviderName = "lmstudio";
|
||||
|
||||
static defaultOptions: Partial<EmbedOptions> | undefined = {
|
||||
apiBase: "http://localhost:1234/v1",
|
||||
model: "nomic-ai/nomic-embed-text-v1.5-GGUF",
|
||||
};
|
||||
}
|
||||
|
||||
export default LMStudioEmbeddingsProvider;
|
||||
|
|
@ -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<EmbedOptions> | undefined = {
|
||||
apiBase: "https://api.mistral.ai/v1/",
|
||||
model: "mistral-embed",
|
||||
};
|
||||
}
|
||||
|
||||
export default MistralEmbeddingsProvider;
|
||||
|
|
@ -1,14 +0,0 @@
|
|||
import { EmbeddingsProviderName, EmbedOptions } from "../..";
|
||||
|
||||
import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider";
|
||||
|
||||
class NebiusEmbeddingsProvider extends OpenAIEmbeddingsProvider {
|
||||
static providerName: EmbeddingsProviderName = "nebius";
|
||||
|
||||
static defaultOptions: Partial<EmbedOptions> | undefined = {
|
||||
apiBase: "https://api.studio.nebius.ai/v1/",
|
||||
model: "BAAI/bge-en-icl",
|
||||
};
|
||||
}
|
||||
|
||||
export default NebiusEmbeddingsProvider;
|
||||
|
|
@ -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<EmbedOptions> | 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<Response>(() =>
|
||||
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;
|
||||
|
|
@ -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<number[][]>(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;
|
||||
|
|
@ -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<EmbedOptions> | 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<Response>(() =>
|
||||
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;
|
||||
|
|
@ -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<EmbedOptions> | 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;
|
||||
|
|
@ -1,14 +0,0 @@
|
|||
import { EmbeddingsProviderName, EmbedOptions } from "../..";
|
||||
|
||||
import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider";
|
||||
|
||||
class SiliconFlowEmbeddingsProvider extends OpenAIEmbeddingsProvider {
|
||||
static providerName: EmbeddingsProviderName = "siliconflow";
|
||||
|
||||
static defaultOptions: Partial<EmbedOptions> | undefined = {
|
||||
apiBase: "https://api.siliconflow.cn/v1/",
|
||||
model: "BAAI/bge-m3",
|
||||
};
|
||||
}
|
||||
|
||||
export default SiliconFlowEmbeddingsProvider;
|
||||
|
|
@ -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<EmbedOptions> | 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<Response>(() =>
|
||||
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;
|
||||
|
|
@ -1,14 +0,0 @@
|
|||
import { EmbeddingsProviderName, EmbedOptions } from "../..";
|
||||
|
||||
import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider";
|
||||
|
||||
class VoyageEmbeddingsProvider extends OpenAIEmbeddingsProvider {
|
||||
static providerName: EmbeddingsProviderName = "voyage";
|
||||
|
||||
static defaultOptions: Partial<EmbedOptions> | undefined = {
|
||||
apiBase: "https://api.voyageai.com/v1/",
|
||||
model: "voyage-code-2",
|
||||
};
|
||||
}
|
||||
|
||||
export default VoyageEmbeddingsProvider;
|
||||
|
|
@ -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<EmbedOptions> | 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<number[][]>(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;
|
||||
|
|
@ -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,
|
||||
};
|
||||
|
|
@ -19,8 +19,14 @@ export default {
|
|||
__dirname: path.dirname(fileURLToPath(import.meta.url)),
|
||||
__filename: path.resolve(fileURLToPath(import.meta.url)),
|
||||
},
|
||||
|
||||
globalSetup: "<rootDir>/jest.global-setup.ts",
|
||||
setupFilesAfterEnv: ["<rootDir>/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: "<rootDir>/test/jest.global-setup.ts",
|
||||
setupFilesAfterEnv: ["<rootDir>/test/jest.setup-after-env.ts"],
|
||||
maxWorkers: 1, // equivalent to CLI --runInBand
|
||||
};
|
||||
|
|
|
|||
|
|
@ -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 (
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
109
core/llm/countTokens.test.ts
Normal file
109
core/llm/countTokens.test.ts
Normal file
|
|
@ -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);
|
||||
});
|
||||
});
|
||||
|
|
@ -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<LLMOptions> = {
|
||||
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);
|
||||
|
|
|
|||
|
|
@ -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<LLMOptions> | 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<string[]> {
|
||||
|
|
@ -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<number[][]> {
|
||||
const batches = this.getBatchedChunks(chunks);
|
||||
|
||||
return (
|
||||
await Promise.all(
|
||||
batches.map(async (batch) => {
|
||||
if (batch.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const embeddings = await withExponentialBackoff<number[][]>(
|
||||
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<number[]> {
|
||||
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<number[][]> {
|
||||
throw new Error(
|
||||
`Embedding is not supported for provider type ${this.providerName}`,
|
||||
);
|
||||
}
|
||||
|
||||
countTokens(text: string): number {
|
||||
return countTokens(text, this.model);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<LLMOptions> = {
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
contextLength: 200_000,
|
||||
|
|
|
|||
|
|
@ -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<LLMOptions> = {
|
||||
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<string> {
|
||||
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<string> {
|
||||
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<ChatMessage> {
|
||||
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;
|
||||
export default Asksage;
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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<LLMOptions> = {
|
||||
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<number[][]> {
|
||||
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<number[]> {
|
||||
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;
|
||||
|
|
|
|||
|
|
@ -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<LLMOptions> = {
|
||||
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(
|
||||
|
|
|
|||
|
|
@ -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<LLMOptions> = {
|
||||
apiBase: "https://api.cerebras.ai/v1/",
|
||||
};
|
||||
|
|
|
|||
|
|
@ -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 = {
|
||||
|
|
|
|||
|
|
@ -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<LLMOptions> = {
|
||||
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<number[][]> {
|
||||
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<number[]> {
|
||||
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;
|
||||
|
|
|
|||
|
|
@ -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";
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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<LLMOptions> = {
|
||||
apiBase: "https://api.deepinfra.com/v1/openai/",
|
||||
};
|
||||
maxStopWords: number | undefined = 16;
|
||||
|
||||
protected async _embed(chunks: string[]): Promise<number[][]> {
|
||||
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;
|
||||
|
|
|
|||
|
|
@ -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<LLMOptions> = {
|
||||
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;
|
||||
|
|
|
|||
|
|
@ -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<LLMOptions> = {
|
||||
apiBase: "https://api.fireworks.ai/inference/v1",
|
||||
};
|
||||
|
|
|
|||
|
|
@ -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<IFlowiseProviderLLMOptions> = {
|
||||
apiBase: "http://localhost:3000",
|
||||
};
|
||||
|
|
|
|||
|
|
@ -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<LLMOptions> | 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<number[][]> {
|
||||
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<number[]> {
|
||||
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;
|
||||
|
|
|
|||
|
|
@ -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<LLMOptions> = {
|
||||
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<number[][]> {
|
||||
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;
|
||||
|
|
|
|||
|
|
@ -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<LLMOptions> = {
|
||||
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<number[][]> {
|
||||
// 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;
|
||||
|
|
|
|||
|
|
@ -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<LLMOptions> = {
|
||||
apiBase: "https://api.groq.com/openai/v1/",
|
||||
};
|
||||
|
|
|
|||
|
|
@ -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() {
|
||||
|
|
|
|||
|
|
@ -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<EmbedOptions> | undefined = {
|
||||
static defaultOptions: Partial<LLMOptions> | 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<number[][]> {
|
||||
const resp = await withExponentialBackoff<Response>(() =>
|
||||
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<TEIInfoResponse> {
|
||||
const resp = await withExponentialBackoff<Response>(() =>
|
||||
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<number[]> {
|
||||
const headers: Record<string, string> = {
|
||||
"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 {
|
||||
|
|
@ -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<LLMOptions> = {
|
||||
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,
|
||||
},
|
||||
);
|
||||
|
||||
|
|
|
|||
|
|
@ -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<LLMOptions> = {
|
||||
apiBase: "https://llm.kindo.ai/v1",
|
||||
requestOptions: {
|
||||
headers: {
|
||||
"kindo-token-transaction-type": "CONTINUE"
|
||||
}
|
||||
}
|
||||
};
|
||||
static providerName = "kindo";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://llm.kindo.ai/v1",
|
||||
requestOptions: {
|
||||
headers: {
|
||||
"kindo-token-transaction-type": "CONTINUE",
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export default Kindo;
|
||||
export default Kindo;
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue