Merge branch 'main' into start-ollama-chat
This commit is contained in:
commit
c5d007a7d1
266 changed files with 8517 additions and 2435 deletions
18
.github/workflows/jetbrains-release.yaml
vendored
18
.github/workflows/jetbrains-release.yaml
vendored
|
|
@ -6,7 +6,13 @@ name: JetBrains Release
|
|||
|
||||
on:
|
||||
release:
|
||||
types: [prereleased]
|
||||
types: [ prereleased ]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
publish_build:
|
||||
description: 'Whether or not to publish the built extension to the JetBrains marketplace'
|
||||
required: true
|
||||
default: false
|
||||
|
||||
defaults:
|
||||
run:
|
||||
|
|
@ -34,7 +40,7 @@ jobs:
|
|||
# Prepare and publish the plugin to JetBrains Marketplace repository
|
||||
build:
|
||||
needs: check_release_name
|
||||
if: needs.check_release_name.outputs.should_run == 'true'
|
||||
if: needs.check_release_name.outputs.should_run == 'true' || github.event_name == 'workflow_dispatch'
|
||||
name: Build Plugin
|
||||
runs-on: macos-latest
|
||||
permissions:
|
||||
|
|
@ -175,6 +181,7 @@ jobs:
|
|||
|
||||
# Publish the plugin to JetBrains Marketplace
|
||||
- name: Publish EAP Plugin
|
||||
if: github.event_name == 'release' || github.event.inputs.publish_build == 'true'
|
||||
env:
|
||||
PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }}
|
||||
CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }}
|
||||
|
|
@ -184,6 +191,7 @@ jobs:
|
|||
run: ./gradlew publishPlugin
|
||||
|
||||
- name: Publish Stable Plugin
|
||||
if: github.event_name == 'release' || github.event.inputs.publish_build == 'true'
|
||||
env:
|
||||
PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }}
|
||||
CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }}
|
||||
|
|
@ -337,7 +345,7 @@ jobs:
|
|||
# Run tests and upload a code coverage report
|
||||
test:
|
||||
name: Test
|
||||
needs: [build]
|
||||
needs: [ build ]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
# Check out current repository
|
||||
|
|
@ -379,7 +387,7 @@ jobs:
|
|||
inspectCode:
|
||||
if: false
|
||||
name: Inspect code
|
||||
needs: [build]
|
||||
needs: [ build ]
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
|
|
@ -414,7 +422,7 @@ jobs:
|
|||
verify:
|
||||
if: false
|
||||
name: Verify plugin
|
||||
needs: [build]
|
||||
needs: [ build ]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
# Free GitHub Actions Environment Disk Space
|
||||
|
|
|
|||
10
.github/workflows/main.yaml
vendored
10
.github/workflows/main.yaml
vendored
|
|
@ -4,6 +4,13 @@ on:
|
|||
release:
|
||||
types: [released]
|
||||
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
publish_build:
|
||||
description: "Whether or not to publish the built extension to the VS Code marketplace"
|
||||
required: true
|
||||
default: false
|
||||
|
||||
jobs:
|
||||
check_release_name:
|
||||
runs-on: ubuntu-latest
|
||||
|
|
@ -21,7 +28,7 @@ jobs:
|
|||
|
||||
build:
|
||||
needs: check_release_name
|
||||
if: needs.check_release_name.outputs.should_run == 'true'
|
||||
if: needs.check_release_name.outputs.should_run == 'true' || github.event_name == 'workflow_dispatch'
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
|
|
@ -201,6 +208,7 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
needs:
|
||||
- build
|
||||
if: github.event.inputs.publish_build == 'true'
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
|
|
|
|||
130
.github/workflows/pr_checks.yaml
vendored
130
.github/workflows/pr_checks.yaml
vendored
|
|
@ -1,10 +1,11 @@
|
|||
name: PR checks
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
pull_request_target:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- "extensions/intellij/**"
|
||||
- "extensions/vscode/**"
|
||||
- "core/**"
|
||||
- "gui/**"
|
||||
|
|
@ -21,10 +22,22 @@ on:
|
|||
- ".github/workflows/**"
|
||||
|
||||
jobs:
|
||||
validate-pr:
|
||||
runs-on: ubuntu-latest
|
||||
environment: tests-requiring-secrets
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
install-root:
|
||||
needs: validate-pr
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
# This is important - it switches from the base repo to the fork
|
||||
repository: ${{ github.event.pull_request.head.repo.full_name }}
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
|
|
@ -44,6 +57,10 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
repository: ${{ github.event.pull_request.head.repo.full_name }}
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
|
|
@ -69,8 +86,13 @@ jobs:
|
|||
core-checks:
|
||||
needs: install-core
|
||||
runs-on: ubuntu-latest
|
||||
environment: tests-requiring-secrets
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
repository: ${{ github.event.pull_request.head.repo.full_name }}
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
|
|
@ -96,10 +118,14 @@ jobs:
|
|||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
|
||||
install-gui:
|
||||
needs: [ install-root, install-core ]
|
||||
needs: [install-root, install-core]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
repository: ${{ github.event.pull_request.head.repo.full_name }}
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
|
|
@ -131,6 +157,10 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
repository: ${{ github.event.pull_request.head.repo.full_name }}
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
|
|
@ -157,10 +187,14 @@ jobs:
|
|||
npx tsc --noEmit
|
||||
|
||||
binary-checks:
|
||||
needs: [ install-root, install-core ]
|
||||
needs: [install-root, install-core]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
repository: ${{ github.event.pull_request.head.repo.full_name }}
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
|
|
@ -193,10 +227,14 @@ jobs:
|
|||
npx tsc --noEmit
|
||||
|
||||
install-vscode:
|
||||
needs: [ install-root, install-core ]
|
||||
needs: [install-root, install-core]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
repository: ${{ github.event.pull_request.head.repo.full_name }}
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
|
|
@ -230,6 +268,10 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
repository: ${{ github.event.pull_request.head.repo.full_name }}
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
|
|
@ -261,6 +303,10 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
repository: ${{ github.event.pull_request.head.repo.full_name }}
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
|
|
@ -274,14 +320,22 @@ jobs:
|
|||
run: |
|
||||
cd core
|
||||
npm test
|
||||
env:
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
|
||||
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
|
||||
|
||||
vscode-get-test-file-matrix:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [ install-root, install-vscode ]
|
||||
needs: [install-root, install-vscode]
|
||||
outputs:
|
||||
test_file_matrix: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
repository: ${{ github.event.pull_request.head.repo.full_name }}
|
||||
|
||||
- name: Cache node modules
|
||||
uses: actions/cache@v3
|
||||
|
|
@ -306,9 +360,13 @@ jobs:
|
|||
|
||||
vscode-package-extension:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [ install-vscode, install-core ]
|
||||
needs: [install-vscode, install-core]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
repository: ${{ github.event.pull_request.head.repo.full_name }}
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
|
|
@ -338,9 +396,13 @@ jobs:
|
|||
|
||||
vscode-download-e2e-dependencies:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [ install-vscode, install-core ]
|
||||
needs: [install-vscode, install-core]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
repository: ${{ github.event.pull_request.head.repo.full_name }}
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
|
|
@ -370,7 +432,7 @@ jobs:
|
|||
path: extensions/vscode/e2e/storage
|
||||
|
||||
vscode-e2e-tests:
|
||||
name: ${{ matrix.test_file }}"
|
||||
name: ${{ matrix.test_file }} (${{ matrix.command }})
|
||||
needs:
|
||||
[
|
||||
vscode-download-e2e-dependencies,
|
||||
|
|
@ -380,12 +442,19 @@ jobs:
|
|||
install-core,
|
||||
]
|
||||
runs-on: ubuntu-latest
|
||||
# Tests requiring secrets need approval from maintainers
|
||||
environment: tests-requiring-secrets
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
test_file: ${{ fromJson(needs.vscode-get-test-file-matrix.outputs.test_file_matrix) }}
|
||||
command: ["e2e:ci:run", "e2e:ci:run-yaml"]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
repository: ${{ github.event.pull_request.head.repo.full_name }}
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
|
|
@ -432,8 +501,7 @@ jobs:
|
|||
- name: Run e2e tests
|
||||
run: |
|
||||
cd extensions/vscode
|
||||
TEST_FILE="${{ matrix.test_file }}" npm run e2e:ci:run
|
||||
|
||||
TEST_FILE="${{ matrix.test_file }}" npm run ${{ matrix.command }}
|
||||
env:
|
||||
DISPLAY: :99
|
||||
|
||||
|
|
@ -445,10 +513,14 @@ jobs:
|
|||
path: extensions/vscode/e2e/storage/screenshots
|
||||
|
||||
gui-tests:
|
||||
needs: [ install-gui, install-core ]
|
||||
needs: [install-gui, install-core]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
repository: ${{ github.event.pull_request.head.repo.full_name }}
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
|
|
@ -476,10 +548,13 @@ jobs:
|
|||
npm test
|
||||
|
||||
jetbrains-tests:
|
||||
needs: [ install-root, core-checks ]
|
||||
needs: [install-root, core-checks]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
repository: ${{ github.event.pull_request.head.repo.full_name }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
|
|
@ -546,7 +621,7 @@ jobs:
|
|||
with:
|
||||
url: http://127.0.0.1:8082
|
||||
max-attempts: 15
|
||||
retry-delay: 5s
|
||||
retry-delay: 30s
|
||||
|
||||
- name: Run tests
|
||||
run: |
|
||||
|
|
@ -574,4 +649,33 @@ jobs:
|
|||
path: |
|
||||
${{ github.workspace }}/extensions/intellij/build/reports
|
||||
|
||||
# GitHub does not have a way of requiring that all checks pass (you must manually select each job)
|
||||
# This action at least lets us manage the list of required tests via source control
|
||||
# so that creators of new jobs can add them to this list
|
||||
require-all-checks-to-pass:
|
||||
if: always()
|
||||
runs-on: ubuntu-latest
|
||||
needs:
|
||||
- install-root
|
||||
- install-core
|
||||
- core-checks
|
||||
- install-gui
|
||||
- gui-checks
|
||||
- binary-checks
|
||||
- install-vscode
|
||||
- vscode-checks
|
||||
- core-tests
|
||||
- vscode-get-test-file-matrix
|
||||
- vscode-package-extension
|
||||
- vscode-download-e2e-dependencies
|
||||
- vscode-e2e-tests
|
||||
- gui-tests
|
||||
- jetbrains-tests
|
||||
|
||||
steps:
|
||||
- name: Decide whether the needed jobs succeeded or failed
|
||||
uses: re-actors/alls-green@release/v1
|
||||
with:
|
||||
allowed-failures:
|
||||
allowed-skips:
|
||||
jobs: ${{ toJSON(needs) }}
|
||||
|
|
|
|||
3
.vscode/launch.json
vendored
3
.vscode/launch.json
vendored
|
|
@ -20,10 +20,10 @@
|
|||
"outFiles": ["${workspaceFolder}/extensions/vscode/out/extension.js"],
|
||||
"preLaunchTask": "vscode-extension:build",
|
||||
"env": {
|
||||
// "CONTROL_PLANE_ENV": "local",
|
||||
"CONTINUE_GLOBAL_DIR": "${workspaceFolder}/extensions/.continue-debug"
|
||||
// "staging" for the preview deployment "CONTINUE_GLOBAL_DIR": "${workspaceFolder}/extensions/.continue-debug"
|
||||
// "local" for entirely local development of control plane/proxy
|
||||
// "CONTROL_PLANE_ENV": "staging"
|
||||
}
|
||||
},
|
||||
{
|
||||
|
|
@ -38,6 +38,7 @@
|
|||
"internalConsoleOptions": "openOnSessionStart",
|
||||
"cwd": "${workspaceFolder}/binary",
|
||||
"env": {
|
||||
// "CONTROL_PLANE_ENV": "test",
|
||||
"CONTINUE_DEVELOPMENT": "true",
|
||||
"CONTINUE_GLOBAL_DIR": "${workspaceFolder}/extensions/.continue-debug"
|
||||
}
|
||||
|
|
|
|||
3
.vscode/settings.json
vendored
3
.vscode/settings.json
vendored
|
|
@ -42,5 +42,6 @@
|
|||
"extensions/.continue-debug": true
|
||||
// "sync/**": true
|
||||
},
|
||||
"eslint.workingDirectories": ["./core"]
|
||||
"eslint.workingDirectories": ["./core"],
|
||||
"typescript.tsdk": "node_modules/typescript/lib"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -49,7 +49,7 @@ If you find a bug, please [create an issue](https://github.com/continuedev/conti
|
|||
|
||||
## ✨ Suggest Enhancements
|
||||
|
||||
Continue is quickly adding features, and we'd love to hear which are the most important to you. The best ways to suggest an enhancement are
|
||||
Continue is quickly adding features, and we'd love to hear which are the most important to you. The best ways to suggest an enhancement are:
|
||||
|
||||
- Create an issue
|
||||
|
||||
|
|
@ -192,7 +192,7 @@ Continue has support for more than a dozen different LLM "providers", making it
|
|||
|
||||
1. Create a new file in the `core/llm/llms` directory. The name of the file should be the name of the provider, and it should export a class that extends `BaseLLM`. This class should contain the following minimal implementation. We recommend viewing pre-existing providers for more details. The [LlamaCpp Provider](./core/llm/llms/LlamaCpp.ts) is a good simple example.
|
||||
|
||||
- `providerName` - the identifier for your provider
|
||||
- `providerName` - the identifier for your provider.
|
||||
- At least one of `_streamComplete` or `_streamChat` - This is the function that makes the request to the API and returns the streamed response. You only need to implement one because Continue can automatically convert between "chat" and "raw completion".
|
||||
|
||||
2. Add your provider to the `LLMs` array in [core/llm/llms/index.ts](./core/llm/llms/index.ts).
|
||||
|
|
|
|||
|
|
@ -118,6 +118,22 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
|
|||
}
|
||||
|
||||
(async () => {
|
||||
// Informs of where to look for node_sqlite3.node https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found
|
||||
// This is only needed for our `pkg` command at build time
|
||||
fs.writeFileSync(
|
||||
"out/package.json",
|
||||
JSON.stringify(
|
||||
{
|
||||
name: "binary",
|
||||
version: "1.0.0",
|
||||
author: "Continue Dev, Inc",
|
||||
license: "Apache-2.0",
|
||||
},
|
||||
undefined,
|
||||
2,
|
||||
),
|
||||
);
|
||||
|
||||
console.log("[info] Downloading prebuilt lancedb...");
|
||||
for (const target of targets) {
|
||||
if (targetToLanceDb[target]) {
|
||||
|
|
@ -263,9 +279,12 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
|
|||
|
||||
// Informs the `continue-binary` of where to look for node_sqlite3.node
|
||||
// https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found
|
||||
fs.writeFileSync(`${targetDir}/package.json`, "");
|
||||
// fs.writeFileSync(`${targetDir}/package.json`, "");
|
||||
}
|
||||
|
||||
// Cleanup - this is needed when running locally
|
||||
fs.rmSync("out/package.json");
|
||||
|
||||
const pathsToVerify = [];
|
||||
for (const target of targets) {
|
||||
const exe = target.startsWith("win") ? ".exe" : "";
|
||||
|
|
|
|||
2
binary/package-lock.json
generated
2
binary/package-lock.json
generated
|
|
@ -48,7 +48,7 @@
|
|||
"@aws-sdk/client-sagemaker-runtime": "^3.621.0",
|
||||
"@aws-sdk/credential-providers": "^3.620.1",
|
||||
"@continuedev/config-types": "^1.0.13",
|
||||
"@continuedev/config-yaml": "^1.0.0",
|
||||
"@continuedev/config-yaml": "^1.0.16",
|
||||
"@continuedev/fetch": "^1.0.4",
|
||||
"@continuedev/llm-info": "^1.0.2",
|
||||
"@continuedev/openai-adapters": "^1.0.10",
|
||||
|
|
|
|||
|
|
@ -33,14 +33,46 @@ class IPCMessengerBase<
|
|||
response &&
|
||||
typeof response[Symbol.asyncIterator] === "function"
|
||||
) {
|
||||
for await (const update of response) {
|
||||
this.send(msg.messageType, update, msg.messageId);
|
||||
let next = await response.next();
|
||||
while (!next.done) {
|
||||
this.send(
|
||||
msg.messageType,
|
||||
{
|
||||
done: false,
|
||||
content: next.value,
|
||||
status: "success",
|
||||
},
|
||||
msg.messageId,
|
||||
);
|
||||
next = await response.next();
|
||||
}
|
||||
this.send(msg.messageType, { done: true }, msg.messageId);
|
||||
this.send(
|
||||
msg.messageType,
|
||||
{
|
||||
done: true,
|
||||
content: next.value,
|
||||
status: "success",
|
||||
},
|
||||
msg.messageId,
|
||||
);
|
||||
} else {
|
||||
this.send(msg.messageType, response, msg.messageId);
|
||||
this.send(
|
||||
msg.messageType,
|
||||
{
|
||||
done: true,
|
||||
content: response,
|
||||
status: "success",
|
||||
},
|
||||
msg.messageId,
|
||||
);
|
||||
}
|
||||
} catch (e: any) {
|
||||
this.send(
|
||||
msg.messageType,
|
||||
{ done: true, error: e.message, status: "error" },
|
||||
msg.messageId,
|
||||
);
|
||||
|
||||
console.warn(`Error running handler for "${msg.messageType}": `, e);
|
||||
this._onErrorHandlers.forEach((handler) => {
|
||||
handler(e);
|
||||
|
|
@ -62,6 +94,7 @@ class IPCMessengerBase<
|
|||
}
|
||||
|
||||
private _unfinishedLine: string | undefined = undefined;
|
||||
|
||||
protected _handleData(data: Buffer) {
|
||||
const d = data.toString();
|
||||
const lines = d.split(/\r\n/).filter((line) => line.trim() !== "");
|
||||
|
|
@ -169,6 +202,7 @@ export class IpcMessenger<
|
|||
process.exit(1);
|
||||
});
|
||||
}
|
||||
|
||||
_sendMsg(msg: Message) {
|
||||
const d = JSON.stringify(msg);
|
||||
// console.log("[info] Sending message: ", d);
|
||||
|
|
|
|||
|
|
@ -69,14 +69,46 @@ export class TcpMessenger<
|
|||
response &&
|
||||
typeof response[Symbol.asyncIterator] === "function"
|
||||
) {
|
||||
for await (const update of response) {
|
||||
this.send(msg.messageType, update, msg.messageId);
|
||||
let next = await response.next();
|
||||
while (!next.done) {
|
||||
this.send(
|
||||
msg.messageType,
|
||||
{
|
||||
done: false,
|
||||
content: next.value,
|
||||
status: "success",
|
||||
},
|
||||
msg.messageId,
|
||||
);
|
||||
next = await response.next();
|
||||
}
|
||||
this.send(msg.messageType, { done: true }, msg.messageId);
|
||||
this.send(
|
||||
msg.messageType,
|
||||
{
|
||||
done: true,
|
||||
content: next.value,
|
||||
status: "success",
|
||||
},
|
||||
msg.messageId,
|
||||
);
|
||||
} else {
|
||||
this.send(msg.messageType, response || {}, msg.messageId);
|
||||
this.send(
|
||||
msg.messageType,
|
||||
{
|
||||
done: true,
|
||||
content: response,
|
||||
status: "success",
|
||||
},
|
||||
msg.messageId,
|
||||
);
|
||||
}
|
||||
} catch (e: any) {
|
||||
this.send(
|
||||
msg.messageType,
|
||||
{ done: true, error: e.message, status: "error" },
|
||||
msg.messageId,
|
||||
);
|
||||
|
||||
console.warn(`Error running handler for "${msg.messageType}": `, e);
|
||||
this._onErrorHandlers.forEach((handler) => {
|
||||
handler(e);
|
||||
|
|
@ -98,6 +130,7 @@ export class TcpMessenger<
|
|||
}
|
||||
|
||||
private _unfinishedLine: string | undefined = undefined;
|
||||
|
||||
private _handleData(data: Buffer) {
|
||||
const d = data.toString();
|
||||
const lines = d.split(/\r\n/).filter((line) => line.trim() !== "");
|
||||
|
|
@ -151,6 +184,7 @@ export class TcpMessenger<
|
|||
data,
|
||||
});
|
||||
}
|
||||
|
||||
request<T extends keyof FromProtocol>(
|
||||
messageType: T,
|
||||
data: FromProtocol[T][0],
|
||||
|
|
|
|||
|
|
@ -1,158 +0,0 @@
|
|||
# Tab Autocomplete (beta)
|
||||
|
||||
Continue now provides support for tab autocomplete in [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains IDEs](https://plugins.jetbrains.com/plugin/22707-continue/edit). We will be greatly improving the experience over the next few releases, and it is always helpful to hear feedback. If you have any problems or suggestions, please let us know in our [Discord](https://discord.gg/vapESyrFmJ).
|
||||
|
||||
## Setting up with Ollama (default)
|
||||
|
||||
We recommend setting up tab-autocomplete with a local Ollama instance. To do this, first download the latest version of Ollama from [here](https://ollama.ai). Then, run the following command to download our recommended model:
|
||||
|
||||
```bash
|
||||
ollama run qwen2.5-coder:1.5b-base
|
||||
```
|
||||
|
||||
Once it has been downloaded, you should begin to see completions in VS Code.
|
||||
|
||||
## Setting up with LM Studio
|
||||
|
||||
You can also set up tab-autocomplete with a local LM Studio instance by following these steps:
|
||||
|
||||
1. Download the latest version of LM Studio from [here](https://lmstudio.ai/)
|
||||
2. Download a model (e.g. search for `Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF` and choose one of the options there)
|
||||
3. Go to the server section (button is on the left), select your model from the dropdown at the top, and click "Start Server"
|
||||
4. Go to the "My Models" section (button is on the left), find your selected model, and copy the name the path (example: `Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF/qwen2.5-coder-1.5b-instruct-q4_k_m.gguf`); this will be used as the "model" attribute in Continue
|
||||
5. Go to Continue and modify the configurations for a [custom model](#setting-up-a-custom-model)
|
||||
6. Set the "provider" to `lmstudio` and the "model" to the path copied earlier
|
||||
|
||||
Example:
|
||||
|
||||
```json title="config.json"
|
||||
{
|
||||
"tabAutocompleteModel": {
|
||||
"title": "Qwen2.5-Coder 1.5b",
|
||||
"model": "Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF",
|
||||
"provider": "lmstudio"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Setting up a custom model
|
||||
|
||||
All of the configuration options available for chat models are available to use for tab-autocomplete. For example, if you wanted to use a remote vLLM instance you would edit your `config.json` like this (note that it is not inside the models array), filling in the correct model name and vLLM endpoint:
|
||||
|
||||
```json title="config.json"
|
||||
{
|
||||
"tabAutocompleteModel": {
|
||||
"title": "Tab Autocomplete Model",
|
||||
"provider": "openai",
|
||||
"model": "<MODEL_NAME>",
|
||||
"apiBase": "<VLLM_ENDPOINT_URL>"
|
||||
},
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
As another example, say you want to use a different model, `deepseek-coder:6.7b-base`, with Ollama:
|
||||
|
||||
```json title="config.json"
|
||||
{
|
||||
"tabAutocompleteModel": {
|
||||
"title": "Tab Autocomplete Model",
|
||||
"provider": "ollama",
|
||||
"model": "deepseek-coder:6.7b-base"
|
||||
},
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
If you aren't yet familiar with the available options, you can learn more in our [overview](../setup/overview.md).
|
||||
|
||||
### What model should I use?
|
||||
|
||||
If you are running the model locally, we recommend `qwen2.5-coder:1.5b`.
|
||||
|
||||
If you have a bit more compute, or are running a model in the cloud, you can upgrade to `qwen2.5-coder:7b`.
|
||||
|
||||
Regardless of what you are willing to spend, we do not recommend using GPT or Claude for autocomplete. Learn why [below](#i-want-better-completions-should-i-use-gpt-4).
|
||||
|
||||
## Configuration Options
|
||||
|
||||
The following can be configured in `config.json`:
|
||||
|
||||
### `tabAutocompleteModel`
|
||||
|
||||
This is just another object like the ones in the `"models"` array of `config.json`. You can choose and configure any model you would like, but we strongly suggest using a small model made for tab-autocomplete, such as `deepseek-1b`, `qwen2.5-coder:1.5b`, or `starcoder-3b`.
|
||||
|
||||
### `tabAutocompleteOptions`
|
||||
|
||||
This object allows you to customize the behavior of tab-autocomplete. The available options are:
|
||||
|
||||
- `useFileSuffix`: Determines whether to use the file suffix in the prompt. (Boolean)
|
||||
- `maxPromptTokens`: The maximum number of prompt tokens to use. A smaller number will yield faster completions, but less context. (Number)
|
||||
- `debounceDelay`: The delay in milliseconds before triggering autocomplete after a keystroke. (Number)
|
||||
- `maxSuffixPercentage`: The maximum percentage of the prompt that can be dedicated to the suffix. (Number)
|
||||
- `prefixPercentage`: The percentage of the input that should be dedicated to the prefix. (Number)
|
||||
- `template`: An optional template string to be used for autocomplete. It will be rendered with the Mustache templating language, and is passed the 'prefix' and 'suffix' variables. (String)
|
||||
- `multilineCompletions`: Whether to enable multiline completions ("always", "never", or "auto"). Defaults to "auto".
|
||||
|
||||
### Full example
|
||||
|
||||
```json title="config.json"
|
||||
{
|
||||
"tabAutocompleteModel": {
|
||||
"title": "Tab Autocomplete Model",
|
||||
"provider": "ollama",
|
||||
"model": "qwen2.5-coder:1.5b-base",
|
||||
"apiBase": "https://<my endpoint>"
|
||||
},
|
||||
"tabAutocompleteOptions": {
|
||||
"maxPromptTokens": 400,
|
||||
"prefixPercentage": 0.5
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### I want better completions, should I use GPT-4?
|
||||
|
||||
Perhaps surprisingly, the answer is no. The models that we suggest for autocomplete are trained with a highly specific prompt format, which allows them to respond to requests for completing code (see examples of these prompts [here](https://github.com/continuedev/continue/blob/main/core/autocomplete/templates.ts)). Some of the best commercial models like GPT-4 or Claude are not trained with this prompt format, which means that they won't generate useful completions. Luckily, a huge model is not required for great autocomplete. Most of the state-of-the-art autocomplete models are no more than 10b parameters, and increasing beyond this does not significantly improve performance.
|
||||
|
||||
### I'm not seeing any completions
|
||||
|
||||
Follow these steps to ensure that everything is set up correctly:
|
||||
|
||||
1. Make sure you have the "Enable Tab Autocomplete" setting checked (in VS Code, you can toggle by clicking the "Continue" button in the status bar).
|
||||
2. Make sure you have downloaded Ollama.
|
||||
3. Run `ollama run qwen2.5-coder:1.5b-base` to verify that the model is downloaded.
|
||||
4. Make sure that any other completion providers are disabled (e.g. Copilot), as they may interfere.
|
||||
5. If you are using another Ollama model for chat and your resources are limited, this will cause Ollama to constantly load and unload the models from memory, resulting in slow responses (or none at all) for both. A resolution for this could be using the same model for chat and autocomplete.
|
||||
6. Check the output of the logs to find any potential errors (cmd/ctrl+shift+p -> "Toggle Developer Tools" -> "Console" tab in VS Code, ~/.continue/logs/core.log in JetBrains).
|
||||
7. If you are still having issues, please let us know in our [Discord](https://discord.gg/vapESyrFmJ) and we'll help as soon as possible.
|
||||
|
||||
### Completions are slow
|
||||
|
||||
Depending on your hardware, you may want to try a smaller, faster model. If 3b isn't working for you we recommend trying `deepseek-coder:1.3b-base`.
|
||||
|
||||
### Completions don't know about my code
|
||||
|
||||
We are working on this! Right now Continue uses the Language Server Protocol to add definitions to the prompt, as well as using similarity search over recently edited files. We will be improving the accuracy of this system greatly over the next few weeks.
|
||||
|
||||
### Completions contain formatting errors
|
||||
|
||||
If you're seeing a common pattern of mistake that might be helpful to report, please share in Discord. We will do our best to fix it as soon as possible.
|
||||
|
||||
## How to turn off autocomplete
|
||||
|
||||
### VS Code
|
||||
|
||||
Click the "Continue" button in the status panel at the bottom right of the screen. The checkmark will become a "cancel" symbol and you will no longer see completions. You can click again to turn it back on.
|
||||
|
||||
Alternatively, open VS Code settings, search for "Continue" and uncheck the box for "Enable Tab Autocomplete".
|
||||
|
||||
### JetBrains
|
||||
|
||||
Open Settings -> Tools -> Continue and uncheck the box for "Enable Tab Autocomplete".
|
||||
|
||||
### Feedback
|
||||
|
||||
If you're turning off autocomplete, we'd love to hear how we can improve! Please let us know in our [Discord](https://discord.gg/vapESyrFmJ) or file an issue on GitHub.
|
||||
|
|
@ -76,7 +76,6 @@ export class StreamTransformPipeline {
|
|||
const timeoutValue = await Telemetry.getValueForFeatureFlag(
|
||||
PosthogFeatureFlag.AutocompleteTimeout,
|
||||
);
|
||||
// helper.options.showWhateverWeHaveAtXMs ?? DEFAULT_AUTOCOMPLETE_OPTS.showWhateverWeHaveAtXMs
|
||||
|
||||
lineGenerator = showWhateverWeHaveAtXMs(lineGenerator, timeoutValue!);
|
||||
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ export function slashFromCustomCommand(
|
|||
): SlashCommand {
|
||||
return {
|
||||
name: customCommand.name,
|
||||
description: customCommand.description,
|
||||
description: customCommand.description ?? "",
|
||||
run: async function* ({ input, llm, history, ide }) {
|
||||
// Remove slash command prefix from input
|
||||
let userInput = input;
|
||||
|
|
@ -37,16 +37,21 @@ export function slashFromCustomCommand(
|
|||
|
||||
if (
|
||||
Array.isArray(content) &&
|
||||
content.some((part) =>
|
||||
part.text?.startsWith(`/${customCommand.name}`),
|
||||
content.some(
|
||||
(part) =>
|
||||
"text" in part && part.text?.startsWith(`/${customCommand.name}`),
|
||||
)
|
||||
) {
|
||||
messages[i] = {
|
||||
...message,
|
||||
content: content.map((part) => {
|
||||
return part.text?.startsWith(`/${customCommand.name}`)
|
||||
? { ...part, text: promptUserInput }
|
||||
: part;
|
||||
if (
|
||||
"text" in part &&
|
||||
part.text.startsWith(`/${customCommand.name}`)
|
||||
) {
|
||||
return { type: "text", text: promptUserInput };
|
||||
}
|
||||
return part;
|
||||
}),
|
||||
};
|
||||
break;
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ describe.skip("Test the ConfigHandler and E2E config loading", () => {
|
|||
expect(profiles[0].id).toBe("local");
|
||||
|
||||
const currentProfile = testConfigHandler.currentProfile;
|
||||
expect(currentProfile.profileId).toBe("local");
|
||||
expect(currentProfile.profileDescription.id).toBe("local");
|
||||
});
|
||||
|
||||
test("should load the default config successfully", async () => {
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
import * as fs from "node:fs";
|
||||
|
||||
import {
|
||||
ControlPlaneClient,
|
||||
ControlPlaneSessionInfo,
|
||||
|
|
@ -12,20 +14,28 @@ import {
|
|||
} from "../index.js";
|
||||
import Ollama from "../llm/llms/Ollama.js";
|
||||
import { GlobalContext } from "../util/GlobalContext.js";
|
||||
import { getConfigJsonPath } from "../util/paths.js";
|
||||
import { getConfigJsonPath, getConfigYamlPath } from "../util/paths.js";
|
||||
|
||||
import { ConfigResult } from "./load.js";
|
||||
import {
|
||||
AssistantUnrolled,
|
||||
ConfigResult,
|
||||
FullSlug,
|
||||
} from "@continuedev/config-yaml";
|
||||
import * as YAML from "yaml";
|
||||
import { getControlPlaneEnv, useHub } from "../control-plane/env.js";
|
||||
import { localPathToUri } from "../util/pathToUri.js";
|
||||
import {
|
||||
LOCAL_ONBOARDING_CHAT_MODEL,
|
||||
ONBOARDING_LOCAL_MODEL_TITLE,
|
||||
} from "./onboarding.js";
|
||||
import ControlPlaneProfileLoader from "./profile/ControlPlaneProfileLoader.js";
|
||||
import LocalProfileLoader from "./profile/LocalProfileLoader.js";
|
||||
import PlatformProfileLoader from "./profile/PlatformProfileLoader.js";
|
||||
import {
|
||||
ProfileDescription,
|
||||
ProfileLifecycleManager,
|
||||
} from "./ProfileLifecycleManager.js";
|
||||
import { pathToFileURL } from "url";
|
||||
import { clientRenderHelper } from "./yaml/clientRender.js";
|
||||
|
||||
export type { ProfileDescription };
|
||||
|
||||
|
|
@ -56,8 +66,8 @@ export class ConfigHandler {
|
|||
controlPlaneClient,
|
||||
writeLog,
|
||||
);
|
||||
this.profiles = [new ProfileLifecycleManager(localProfileLoader)];
|
||||
this.selectedProfileId = localProfileLoader.profileId;
|
||||
this.profiles = [new ProfileLifecycleManager(localProfileLoader, this.ide)];
|
||||
this.selectedProfileId = localProfileLoader.description.id;
|
||||
|
||||
// Always load local profile immediately in case control plane doesn't load
|
||||
try {
|
||||
|
|
@ -77,47 +87,72 @@ export class ConfigHandler {
|
|||
|
||||
get currentProfile() {
|
||||
return (
|
||||
this.profiles.find((p) => p.profileId === this.selectedProfileId) ??
|
||||
this.fallbackProfile
|
||||
this.profiles.find(
|
||||
(p) => p.profileDescription.id === this.selectedProfileId,
|
||||
) ?? this.fallbackProfile
|
||||
);
|
||||
}
|
||||
|
||||
get inactiveProfiles() {
|
||||
return this.profiles.filter((p) => p.profileId !== this.selectedProfileId);
|
||||
return this.profiles.filter(
|
||||
(p) => p.profileDescription.id !== this.selectedProfileId,
|
||||
);
|
||||
}
|
||||
|
||||
async openConfigProfile(profileId?: string) {
|
||||
let openProfileId = profileId || this.selectedProfileId;
|
||||
if (openProfileId === "local") {
|
||||
await this.ide.openFile(pathToFileURL(getConfigJsonPath()).toString());
|
||||
const ideInfo = await this.ide.getIdeInfo();
|
||||
const configYamlPath = getConfigYamlPath(ideInfo.ideType);
|
||||
if (fs.existsSync(configYamlPath)) {
|
||||
await this.ide.openFile(localPathToUri(configYamlPath));
|
||||
} else {
|
||||
await this.ide.openFile(localPathToUri(getConfigJsonPath()));
|
||||
}
|
||||
} else {
|
||||
await this.ide.openUrl(
|
||||
"https://app.continue.dev/",
|
||||
// `https://app.continue.dev/workspaces/${openProfileId}/chat`,
|
||||
);
|
||||
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
|
||||
await this.ide.openUrl(`${env.APP_URL}platform/${openProfileId}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async fetchControlPlaneProfiles() {
|
||||
private async loadPlatformProfiles() {
|
||||
// Get the profiles and create their lifecycle managers
|
||||
this.controlPlaneClient
|
||||
.listWorkspaces()
|
||||
.then(async (workspaces) => {
|
||||
this.profiles = this.profiles.filter(
|
||||
(profile) => profile.profileId === "local",
|
||||
.listAssistants()
|
||||
.then(async (assistants) => {
|
||||
const hubProfiles = await Promise.all(
|
||||
assistants.map(async (assistant) => {
|
||||
let renderedConfig: AssistantUnrolled | undefined = undefined;
|
||||
if (assistant.configResult.config) {
|
||||
renderedConfig = await clientRenderHelper(
|
||||
YAML.stringify(assistant.configResult.config),
|
||||
this.ide,
|
||||
this.controlPlaneClient,
|
||||
);
|
||||
}
|
||||
|
||||
const profileLoader = new PlatformProfileLoader(
|
||||
{ ...assistant.configResult, config: renderedConfig },
|
||||
assistant.ownerSlug,
|
||||
assistant.packageSlug,
|
||||
assistant.configResult.config?.version ?? "latest",
|
||||
this.controlPlaneClient,
|
||||
this.ide,
|
||||
this.ideSettingsPromise,
|
||||
this.writeLog,
|
||||
this.reloadConfig.bind(this),
|
||||
);
|
||||
|
||||
return new ProfileLifecycleManager(profileLoader, this.ide);
|
||||
}),
|
||||
);
|
||||
workspaces.forEach((workspace) => {
|
||||
const profileLoader = new ControlPlaneProfileLoader(
|
||||
workspace.id,
|
||||
workspace.name,
|
||||
this.controlPlaneClient,
|
||||
this.ide,
|
||||
this.ideSettingsPromise,
|
||||
this.writeLog,
|
||||
this.reloadConfig.bind(this),
|
||||
);
|
||||
this.profiles.push(new ProfileLifecycleManager(profileLoader));
|
||||
});
|
||||
|
||||
this.profiles = [
|
||||
...this.profiles.filter(
|
||||
(profile) => profile.profileDescription.id === "local",
|
||||
),
|
||||
...hubProfiles,
|
||||
];
|
||||
|
||||
this.notifyProfileListeners(
|
||||
this.profiles.map((profile) => profile.profileDescription),
|
||||
|
|
@ -141,10 +176,103 @@ export class ConfigHandler {
|
|||
}
|
||||
})
|
||||
.catch((e) => {
|
||||
console.error(e);
|
||||
console.error("Failed to list assistants: ", e);
|
||||
});
|
||||
}
|
||||
|
||||
private platformProfilesRefreshInterval: NodeJS.Timeout | undefined;
|
||||
// We use this to keep track of whether we should reload the assistants
|
||||
private lastFullSlugsList: FullSlug[] = [];
|
||||
|
||||
private fullSlugsListsDiffer(a: FullSlug[], b: FullSlug[]): boolean {
|
||||
if (a.length !== b.length) {
|
||||
return true;
|
||||
}
|
||||
for (let i = 0; i < a.length; i++) {
|
||||
if (a[i].ownerSlug !== b[i].ownerSlug) {
|
||||
return true;
|
||||
}
|
||||
if (a[i].packageSlug !== b[i].packageSlug) {
|
||||
return true;
|
||||
}
|
||||
if (a[i].versionSlug !== b[i].versionSlug) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private async fetchControlPlaneProfiles() {
|
||||
if (await useHub(this.ideSettingsPromise)) {
|
||||
clearInterval(this.platformProfilesRefreshInterval);
|
||||
await this.loadPlatformProfiles();
|
||||
|
||||
// Every 5 seconds we ask the platform whether there are any assistant updates in the last 5 seconds
|
||||
// If so, we do the full (more expensive) reload
|
||||
this.platformProfilesRefreshInterval = setInterval(async () => {
|
||||
const newFullSlugsList =
|
||||
await this.controlPlaneClient.listAssistantFullSlugs();
|
||||
|
||||
if (newFullSlugsList) {
|
||||
const shouldReload = this.fullSlugsListsDiffer(
|
||||
newFullSlugsList,
|
||||
this.lastFullSlugsList,
|
||||
);
|
||||
if (shouldReload) {
|
||||
await this.loadPlatformProfiles();
|
||||
}
|
||||
this.lastFullSlugsList = newFullSlugsList;
|
||||
}
|
||||
}, PlatformProfileLoader.RELOAD_INTERVAL);
|
||||
} else {
|
||||
this.controlPlaneClient
|
||||
.listWorkspaces()
|
||||
.then(async (workspaces) => {
|
||||
this.profiles = this.profiles.filter(
|
||||
(profile) => profile.profileDescription.id === "local",
|
||||
);
|
||||
workspaces.forEach((workspace) => {
|
||||
const profileLoader = new ControlPlaneProfileLoader(
|
||||
workspace.id,
|
||||
workspace.name,
|
||||
this.controlPlaneClient,
|
||||
this.ide,
|
||||
this.ideSettingsPromise,
|
||||
this.writeLog,
|
||||
this.reloadConfig.bind(this),
|
||||
);
|
||||
this.profiles.push(
|
||||
new ProfileLifecycleManager(profileLoader, this.ide),
|
||||
);
|
||||
});
|
||||
|
||||
this.notifyProfileListeners(
|
||||
this.profiles.map((profile) => profile.profileDescription),
|
||||
);
|
||||
|
||||
// Check the last selected workspace, and reload if it isn't local
|
||||
const workspaceId = await this.getWorkspaceId();
|
||||
const lastSelectedWorkspaceIds =
|
||||
this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
|
||||
const selectedWorkspaceId = lastSelectedWorkspaceIds[workspaceId];
|
||||
if (selectedWorkspaceId) {
|
||||
this.selectedProfileId = selectedWorkspaceId;
|
||||
await this.loadConfig();
|
||||
} else {
|
||||
// Otherwise we stick with local profile, and record choice
|
||||
lastSelectedWorkspaceIds[workspaceId] = this.selectedProfileId;
|
||||
this.globalContext.update(
|
||||
"lastSelectedProfileForWorkspace",
|
||||
lastSelectedWorkspaceIds,
|
||||
);
|
||||
}
|
||||
})
|
||||
.catch((e) => {
|
||||
console.error(e);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async setSelectedProfile(profileId: string) {
|
||||
this.selectedProfileId = profileId;
|
||||
const result = await this.loadConfig();
|
||||
|
|
@ -170,11 +298,12 @@ export class ConfigHandler {
|
|||
void this.reloadConfig();
|
||||
}
|
||||
|
||||
updateControlPlaneSessionInfo(
|
||||
async updateControlPlaneSessionInfo(
|
||||
sessionInfo: ControlPlaneSessionInfo | undefined,
|
||||
) {
|
||||
this.controlPlaneClient = new ControlPlaneClient(
|
||||
Promise.resolve(sessionInfo),
|
||||
this.ideSettingsPromise,
|
||||
);
|
||||
this.fetchControlPlaneProfiles().catch((e) => {
|
||||
console.error("Failed to fetch control plane profiles: ", e);
|
||||
|
|
|
|||
|
|
@ -1,15 +1,24 @@
|
|||
import {
|
||||
ConfigResult,
|
||||
ConfigValidationError,
|
||||
FullSlug,
|
||||
} from "@continuedev/config-yaml";
|
||||
import {
|
||||
BrowserSerializedContinueConfig,
|
||||
ContinueConfig,
|
||||
IContextProvider,
|
||||
IDE,
|
||||
} from "../index.js";
|
||||
|
||||
import { ConfigResult, finalToBrowserConfig } from "./load.js";
|
||||
import { finalToBrowserConfig } from "./load.js";
|
||||
import { IProfileLoader } from "./profile/IProfileLoader.js";
|
||||
|
||||
export interface ProfileDescription {
|
||||
fullSlug: FullSlug;
|
||||
profileType: "control-plane" | "local" | "platform";
|
||||
title: string;
|
||||
id: string;
|
||||
errors: ConfigValidationError[] | undefined;
|
||||
}
|
||||
|
||||
export class ProfileLifecycleManager {
|
||||
|
|
@ -17,21 +26,13 @@ export class ProfileLifecycleManager {
|
|||
private savedBrowserConfigResult?: ConfigResult<BrowserSerializedContinueConfig>;
|
||||
private pendingConfigPromise?: Promise<ConfigResult<ContinueConfig>>;
|
||||
|
||||
constructor(private readonly profileLoader: IProfileLoader) {}
|
||||
|
||||
get profileId() {
|
||||
return this.profileLoader.profileId;
|
||||
}
|
||||
|
||||
get profileTitle() {
|
||||
return this.profileLoader.profileTitle;
|
||||
}
|
||||
constructor(
|
||||
private readonly profileLoader: IProfileLoader,
|
||||
private readonly ide: IDE,
|
||||
) {}
|
||||
|
||||
get profileDescription(): ProfileDescription {
|
||||
return {
|
||||
title: this.profileTitle,
|
||||
id: this.profileId,
|
||||
};
|
||||
return this.profileLoader.description;
|
||||
}
|
||||
|
||||
clearConfig() {
|
||||
|
|
@ -71,14 +72,10 @@ export class ProfileLifecycleManager {
|
|||
result.config.contextProviders = (
|
||||
result.config.contextProviders ?? []
|
||||
).concat(additionalContextProviders);
|
||||
|
||||
this.savedConfigResult = result;
|
||||
resolve(result);
|
||||
} else if (result.errors) {
|
||||
reject(
|
||||
`Error in config.json: ${result.errors.map((item) => item.message).join(" | ")}`,
|
||||
);
|
||||
}
|
||||
|
||||
this.savedConfigResult = result;
|
||||
resolve(result);
|
||||
});
|
||||
|
||||
// Wait for the config promise to resolve
|
||||
|
|
@ -100,7 +97,10 @@ export class ProfileLifecycleManager {
|
|||
config: undefined,
|
||||
};
|
||||
}
|
||||
const serializedConfig = finalToBrowserConfig(result.config);
|
||||
const serializedConfig = await finalToBrowserConfig(
|
||||
result.config,
|
||||
this.ide,
|
||||
);
|
||||
return {
|
||||
...result,
|
||||
config: serializedConfig,
|
||||
|
|
|
|||
|
|
@ -62,6 +62,7 @@ import {
|
|||
getEsbuildBinaryPath,
|
||||
} from "../util/paths";
|
||||
|
||||
import { ConfigResult, ConfigValidationError } from "@continuedev/config-yaml";
|
||||
import {
|
||||
defaultContextProvidersJetBrains,
|
||||
defaultContextProvidersVsCode,
|
||||
|
|
@ -69,16 +70,14 @@ import {
|
|||
defaultSlashCommandsVscode,
|
||||
} from "./default";
|
||||
import { getSystemPromptDotFile } from "./getSystemPromptDotFile";
|
||||
// import { isSupportedLanceDbCpuTarget } from "./util";
|
||||
import { ConfigValidationError, validateConfig } from "./validation.js";
|
||||
import { useHub } from "../control-plane/env";
|
||||
import { localPathToUri } from "../util/pathToUri";
|
||||
import { modifyContinueConfigWithSharedConfig } from "./sharedConfig";
|
||||
import { validateConfig } from "./validation.js";
|
||||
|
||||
export interface ConfigResult<T> {
|
||||
config: T | undefined;
|
||||
errors: ConfigValidationError[] | undefined;
|
||||
configLoadInterrupted: boolean;
|
||||
}
|
||||
|
||||
function resolveSerializedConfig(filepath: string): SerializedContinueConfig {
|
||||
export function resolveSerializedConfig(
|
||||
filepath: string,
|
||||
): SerializedContinueConfig {
|
||||
let content = fs.readFileSync(filepath, "utf8");
|
||||
const config = JSONC.parse(content) as unknown as SerializedContinueConfig;
|
||||
if (config.env && Array.isArray(config.env)) {
|
||||
|
|
@ -114,11 +113,10 @@ function loadSerializedConfig(
|
|||
overrideConfigJson: SerializedContinueConfig | undefined,
|
||||
ide: IDE,
|
||||
): ConfigResult<SerializedContinueConfig> {
|
||||
const configPath = getConfigJsonPath(ideType);
|
||||
let config: SerializedContinueConfig = overrideConfigJson!;
|
||||
if (!config) {
|
||||
try {
|
||||
config = resolveSerializedConfig(configPath);
|
||||
config = resolveSerializedConfig(getConfigJsonPath(ideType));
|
||||
} catch (e) {
|
||||
throw new Error(`Failed to parse config.json: ${e}`);
|
||||
}
|
||||
|
|
@ -138,13 +136,6 @@ function loadSerializedConfig(
|
|||
config.allowAnonymousTelemetry = true;
|
||||
}
|
||||
|
||||
if (config.ui?.getChatTitles === undefined) {
|
||||
config.ui = {
|
||||
...config.ui,
|
||||
getChatTitles: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (ideSettings.remoteConfigServerUrl) {
|
||||
try {
|
||||
const remoteConfigJson = resolveSerializedConfig(
|
||||
|
|
@ -229,7 +220,7 @@ function isModelDescription(
|
|||
return (llm as ModelDescription).title !== undefined;
|
||||
}
|
||||
|
||||
function isContextProviderWithParams(
|
||||
export function isContextProviderWithParams(
|
||||
contextProvider: CustomContextProvider | ContextProviderWithParams,
|
||||
): contextProvider is ContextProviderWithParams {
|
||||
return (contextProvider as ContextProviderWithParams).name !== undefined;
|
||||
|
|
@ -547,9 +538,10 @@ async function intermediateToFinalConfig(
|
|||
return { config: continueConfig, errors };
|
||||
}
|
||||
|
||||
function finalToBrowserConfig(
|
||||
async function finalToBrowserConfig(
|
||||
final: ContinueConfig,
|
||||
): BrowserSerializedContinueConfig {
|
||||
ide: IDE,
|
||||
): Promise<BrowserSerializedContinueConfig> {
|
||||
return {
|
||||
allowAnonymousTelemetry: final.allowAnonymousTelemetry,
|
||||
models: final.models.map((m) => ({
|
||||
|
|
@ -582,6 +574,8 @@ function finalToBrowserConfig(
|
|||
experimental: final.experimental,
|
||||
docs: final.docs,
|
||||
tools: final.tools,
|
||||
tabAutocompleteOptions: final.tabAutocompleteOptions,
|
||||
usePlatform: await useHub(ide.getIdeSettings()),
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -765,7 +759,7 @@ async function buildConfigTsandReadConfigJs(ide: IDE, ideType: IdeType) {
|
|||
return readConfigJs();
|
||||
}
|
||||
|
||||
async function loadFullConfigNode(
|
||||
async function loadContinueConfigFromJson(
|
||||
ide: IDE,
|
||||
workspaceConfigs: ContinueRcJson[],
|
||||
ideSettings: IdeSettings,
|
||||
|
|
@ -797,8 +791,16 @@ async function loadFullConfigNode(
|
|||
serialized.systemMessage = systemPromptDotFile;
|
||||
}
|
||||
|
||||
// Apply shared config
|
||||
// TODO: override several of these values with user/org shared config
|
||||
const sharedConfig = new GlobalContext().getSharedConfig();
|
||||
const withShared = modifyContinueConfigWithSharedConfig(
|
||||
serialized,
|
||||
sharedConfig,
|
||||
);
|
||||
|
||||
// Convert serialized to intermediate config
|
||||
let intermediate = await serializedToIntermediateConfig(serialized, ide);
|
||||
let intermediate = await serializedToIntermediateConfig(withShared, ide);
|
||||
|
||||
// Apply config.ts to modify intermediate config
|
||||
const configJsContents = await buildConfigTsandReadConfigJs(ide, ideType);
|
||||
|
|
@ -816,7 +818,7 @@ async function loadFullConfigNode(
|
|||
"Could not load config.ts as absolute path, retrying as file url ...",
|
||||
);
|
||||
try {
|
||||
module = await import(`file://${configJsPath}`);
|
||||
module = await import(localPathToUri(configJsPath));
|
||||
} catch (e) {
|
||||
throw new Error("Could not load config.ts as file url either", {
|
||||
cause: e,
|
||||
|
|
@ -875,6 +877,6 @@ async function loadFullConfigNode(
|
|||
export {
|
||||
finalToBrowserConfig,
|
||||
intermediateToFinalConfig,
|
||||
loadFullConfigNode,
|
||||
loadContinueConfigFromJson,
|
||||
type BrowserSerializedContinueConfig,
|
||||
};
|
||||
|
|
|
|||
212
core/config/migrateSharedConfig.ts
Normal file
212
core/config/migrateSharedConfig.ts
Normal file
|
|
@ -0,0 +1,212 @@
|
|||
import * as fs from "fs";
|
||||
|
||||
import * as JSONC from "comment-json";
|
||||
|
||||
import { IDE, SerializedContinueConfig } from "..";
|
||||
import { SharedConfigSchema } from "./sharedConfig";
|
||||
import { GlobalContext } from "../util/GlobalContext";
|
||||
import { editConfigJson } from "../util/paths";
|
||||
import { resolveSerializedConfig } from "./load";
|
||||
import { deduplicateArray } from "../util";
|
||||
|
||||
/*
|
||||
This migration function eliminates deprecated values from the json file
|
||||
And writes them to the shared config
|
||||
*/
|
||||
export function migrateJsonSharedConfig(filepath: string, ide: IDE): void {
|
||||
const globalContext = new GlobalContext();
|
||||
const currentSharedConfig = globalContext.getSharedConfig(); // for merging security concerns
|
||||
|
||||
try {
|
||||
let config = resolveSerializedConfig(filepath);
|
||||
const shareConfigUpdates: SharedConfigSchema = {};
|
||||
|
||||
let effected = false;
|
||||
|
||||
const { allowAnonymousTelemetry, ...withoutAllowTelemetry } = config;
|
||||
if (allowAnonymousTelemetry !== undefined) {
|
||||
if (currentSharedConfig.allowAnonymousTelemetry !== false) {
|
||||
// safe merge for security
|
||||
shareConfigUpdates.allowAnonymousTelemetry = allowAnonymousTelemetry;
|
||||
}
|
||||
config = withoutAllowTelemetry;
|
||||
effected = true;
|
||||
}
|
||||
|
||||
const { disableIndexing, ...withoutDisableIndexing } = config;
|
||||
if (disableIndexing !== undefined) {
|
||||
if (currentSharedConfig.disableIndexing !== true) {
|
||||
// safe merge for security
|
||||
shareConfigUpdates.disableIndexing = disableIndexing;
|
||||
}
|
||||
config = withoutDisableIndexing;
|
||||
effected = true;
|
||||
}
|
||||
|
||||
const { disableSessionTitles, ...withoutDisableSessionTitles } = config;
|
||||
if (config.disableSessionTitles !== undefined) {
|
||||
if (currentSharedConfig.disableSessionTitles !== true) {
|
||||
// safe merge for security
|
||||
shareConfigUpdates.disableSessionTitles = config.disableSessionTitles;
|
||||
}
|
||||
config = withoutDisableSessionTitles;
|
||||
effected = true;
|
||||
}
|
||||
|
||||
const { tabAutocompleteOptions, ...withoutAutocompleteOptions } = config;
|
||||
if (tabAutocompleteOptions !== undefined) {
|
||||
let migratedAutocomplete = { ...tabAutocompleteOptions };
|
||||
|
||||
const { useCache, ...withoutUseCache } = migratedAutocomplete;
|
||||
if (useCache !== undefined) {
|
||||
shareConfigUpdates.useAutocompleteCache = useCache;
|
||||
migratedAutocomplete = withoutUseCache;
|
||||
effected = true;
|
||||
}
|
||||
|
||||
const { multilineCompletions, ...withoutMultiline } =
|
||||
migratedAutocomplete;
|
||||
if (multilineCompletions !== undefined) {
|
||||
shareConfigUpdates.useAutocompleteMultilineCompletions =
|
||||
multilineCompletions;
|
||||
migratedAutocomplete = withoutMultiline;
|
||||
effected = true;
|
||||
}
|
||||
|
||||
const { disableInFiles, ...withoutDisableInFiles } = migratedAutocomplete;
|
||||
if (disableInFiles !== undefined) {
|
||||
if (currentSharedConfig.disableAutocompleteInFiles !== undefined) {
|
||||
// safe merge for security
|
||||
shareConfigUpdates.disableAutocompleteInFiles = deduplicateArray(
|
||||
[
|
||||
...currentSharedConfig.disableAutocompleteInFiles,
|
||||
...disableInFiles,
|
||||
],
|
||||
(a, b) => a === b,
|
||||
);
|
||||
} else {
|
||||
shareConfigUpdates.disableAutocompleteInFiles = disableInFiles;
|
||||
}
|
||||
shareConfigUpdates.disableAutocompleteInFiles = disableInFiles;
|
||||
migratedAutocomplete = withoutDisableInFiles;
|
||||
effected = true;
|
||||
}
|
||||
|
||||
if (Object.keys(migratedAutocomplete).length > 0) {
|
||||
config = {
|
||||
...withoutAutocompleteOptions,
|
||||
tabAutocompleteOptions: migratedAutocomplete,
|
||||
};
|
||||
} else {
|
||||
config = withoutAutocompleteOptions;
|
||||
}
|
||||
}
|
||||
|
||||
const { experimental, ...withoutExperimental } = config;
|
||||
if (experimental !== undefined) {
|
||||
let migratedExperimental = { ...experimental };
|
||||
|
||||
const { useChromiumForDocsCrawling, ...rest10 } = migratedExperimental;
|
||||
if (useChromiumForDocsCrawling !== undefined) {
|
||||
shareConfigUpdates.useChromiumForDocsCrawling =
|
||||
useChromiumForDocsCrawling;
|
||||
migratedExperimental = rest10;
|
||||
effected = true;
|
||||
}
|
||||
|
||||
const { promptPath, ...withoutPromptPath } = migratedExperimental;
|
||||
if (promptPath !== undefined) {
|
||||
shareConfigUpdates.promptPath = promptPath;
|
||||
migratedExperimental = withoutPromptPath;
|
||||
effected = true;
|
||||
}
|
||||
|
||||
const { readResponseTTS, ...withoutReadTTS } = migratedExperimental;
|
||||
if (readResponseTTS !== undefined) {
|
||||
shareConfigUpdates.readResponseTTS = readResponseTTS;
|
||||
migratedExperimental = withoutReadTTS;
|
||||
effected = true;
|
||||
}
|
||||
|
||||
if (Object.keys(migratedExperimental).length > 0) {
|
||||
config = {
|
||||
...withoutExperimental,
|
||||
experimental: migratedExperimental,
|
||||
};
|
||||
} else {
|
||||
config = withoutExperimental;
|
||||
}
|
||||
}
|
||||
|
||||
const { ui, ...withoutUI } = config;
|
||||
if (ui !== undefined) {
|
||||
let migratedUI = { ...ui };
|
||||
|
||||
const { codeBlockToolbarPosition, ...withoutToolbarPosition } =
|
||||
migratedUI;
|
||||
if (codeBlockToolbarPosition !== undefined) {
|
||||
shareConfigUpdates.codeBlockToolbarPosition = codeBlockToolbarPosition;
|
||||
migratedUI = withoutToolbarPosition;
|
||||
effected = true;
|
||||
}
|
||||
|
||||
const { fontSize, ...withoutFontSize } = migratedUI;
|
||||
if (fontSize !== undefined) {
|
||||
shareConfigUpdates.fontSize = fontSize;
|
||||
migratedUI = withoutFontSize;
|
||||
effected = true;
|
||||
}
|
||||
|
||||
const { codeWrap, ...withoutCodeWrap } = migratedUI;
|
||||
if (codeWrap !== undefined) {
|
||||
shareConfigUpdates.codeWrap = codeWrap;
|
||||
migratedUI = withoutCodeWrap;
|
||||
effected = true;
|
||||
}
|
||||
|
||||
const { displayRawMarkdown, ...withoutMD } = migratedUI;
|
||||
if (displayRawMarkdown !== undefined) {
|
||||
shareConfigUpdates.displayRawMarkdown = displayRawMarkdown;
|
||||
migratedUI = withoutMD;
|
||||
effected = true;
|
||||
}
|
||||
|
||||
const { showChatScrollbar, ...withoutShowChatScrollbar } = migratedUI;
|
||||
if (showChatScrollbar !== undefined) {
|
||||
shareConfigUpdates.showChatScrollbar = showChatScrollbar;
|
||||
migratedUI = withoutShowChatScrollbar;
|
||||
effected = true;
|
||||
}
|
||||
|
||||
// Ancient param to overwrite disableSessionTitles
|
||||
if ("getChatTitles" in migratedUI) {
|
||||
const { getChatTitles, ...withoutChatTitles } = migratedUI;
|
||||
if (getChatTitles === false) {
|
||||
shareConfigUpdates.disableSessionTitles = true;
|
||||
migratedUI = withoutChatTitles;
|
||||
effected = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (Object.keys(migratedUI).length > 0) {
|
||||
config = {
|
||||
...withoutUI,
|
||||
ui: migratedUI,
|
||||
};
|
||||
} else {
|
||||
config = withoutUI;
|
||||
}
|
||||
}
|
||||
|
||||
if (effected) {
|
||||
new GlobalContext().updateSharedConfig(shareConfigUpdates);
|
||||
editConfigJson(() => config);
|
||||
void ide.showToast(
|
||||
"warning",
|
||||
"Migrated deprecated Continue JSON settings. Edit in the Settings Page",
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
throw new Error(`Migration: Failed to parse config.json: ${e}`);
|
||||
}
|
||||
}
|
||||
|
|
@ -7,16 +7,16 @@ import {
|
|||
IdeSettings,
|
||||
SerializedContinueConfig,
|
||||
} from "../../index.js";
|
||||
import { ConfigResult } from "../load.js";
|
||||
|
||||
import { ConfigResult } from "@continuedev/config-yaml";
|
||||
import { ProfileDescription } from "../ProfileLifecycleManager.js";
|
||||
import doLoadConfig from "./doLoadConfig.js";
|
||||
import { IProfileLoader } from "./IProfileLoader.js";
|
||||
|
||||
export default class ControlPlaneProfileLoader implements IProfileLoader {
|
||||
private static RELOAD_INTERVAL = 1000 * 60 * 15; // every 15 minutes
|
||||
|
||||
readonly profileId: string;
|
||||
profileTitle: string;
|
||||
description: ProfileDescription;
|
||||
|
||||
workspaceSettings: ConfigJson | undefined;
|
||||
|
||||
|
|
@ -29,12 +29,23 @@ export default class ControlPlaneProfileLoader implements IProfileLoader {
|
|||
private writeLog: (message: string) => Promise<void>,
|
||||
private readonly onReload: () => void,
|
||||
) {
|
||||
this.profileId = workspaceId;
|
||||
this.profileTitle = workspaceTitle;
|
||||
this.description = {
|
||||
id: workspaceId,
|
||||
profileType: "control-plane",
|
||||
fullSlug: {
|
||||
ownerSlug: "",
|
||||
packageSlug: "",
|
||||
versionSlug: "",
|
||||
},
|
||||
title: workspaceTitle,
|
||||
errors: undefined,
|
||||
};
|
||||
|
||||
setInterval(async () => {
|
||||
this.workspaceSettings =
|
||||
await this.controlPlaneClient.getSettingsForWorkspace(this.profileId);
|
||||
await this.controlPlaneClient.getSettingsForWorkspace(
|
||||
this.description.id,
|
||||
);
|
||||
this.onReload();
|
||||
}, ControlPlaneProfileLoader.RELOAD_INTERVAL);
|
||||
}
|
||||
|
|
@ -43,7 +54,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader {
|
|||
const settings =
|
||||
this.workspaceSettings ??
|
||||
((await this.controlPlaneClient.getSettingsForWorkspace(
|
||||
this.profileId,
|
||||
this.description.id,
|
||||
)) as any);
|
||||
const serializedConfig: SerializedContinueConfig = settings;
|
||||
|
||||
|
|
@ -53,6 +64,8 @@ export default class ControlPlaneProfileLoader implements IProfileLoader {
|
|||
this.controlPlaneClient,
|
||||
this.writeLog,
|
||||
serializedConfig,
|
||||
undefined,
|
||||
undefined,
|
||||
this.workspaceId,
|
||||
);
|
||||
|
||||
|
|
|
|||
|
|
@ -1,12 +1,12 @@
|
|||
// ProfileHandlers manage the loading of a config, allowing us to abstract over different ways of getting to a ContinueConfig
|
||||
|
||||
import { ConfigResult } from "@continuedev/config-yaml";
|
||||
import { ContinueConfig } from "../../index.js";
|
||||
import { ConfigResult } from "../load.js";
|
||||
import { ProfileDescription } from "../ProfileLifecycleManager.js";
|
||||
|
||||
// After we have the ContinueConfig, the ConfigHandler takes care of everything else (loading models, lifecycle, etc.)
|
||||
export interface IProfileLoader {
|
||||
profileTitle: string;
|
||||
profileId: string;
|
||||
description: ProfileDescription;
|
||||
doLoadConfig(): Promise<ConfigResult<ContinueConfig>>;
|
||||
setIsActive(isActive: boolean): void;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,14 +1,24 @@
|
|||
import { ConfigResult } from "@continuedev/config-yaml";
|
||||
import { ControlPlaneClient } from "../../control-plane/client.js";
|
||||
import { ContinueConfig, IDE, IdeSettings } from "../../index.js";
|
||||
import { ConfigResult } from "../load.js";
|
||||
|
||||
import { ProfileDescription } from "../ProfileLifecycleManager.js";
|
||||
import doLoadConfig from "./doLoadConfig.js";
|
||||
import { IProfileLoader } from "./IProfileLoader.js";
|
||||
|
||||
export default class LocalProfileLoader implements IProfileLoader {
|
||||
static ID = "local";
|
||||
profileId = LocalProfileLoader.ID;
|
||||
profileTitle = "Local Config";
|
||||
description: ProfileDescription = {
|
||||
id: LocalProfileLoader.ID,
|
||||
profileType: "local",
|
||||
fullSlug: {
|
||||
ownerSlug: "",
|
||||
packageSlug: "",
|
||||
versionSlug: "",
|
||||
},
|
||||
title: "Local Config",
|
||||
errors: undefined,
|
||||
};
|
||||
|
||||
constructor(
|
||||
private ide: IDE,
|
||||
|
|
@ -18,13 +28,19 @@ export default class LocalProfileLoader implements IProfileLoader {
|
|||
) {}
|
||||
|
||||
async doLoadConfig(): Promise<ConfigResult<ContinueConfig>> {
|
||||
return doLoadConfig(
|
||||
const result = await doLoadConfig(
|
||||
this.ide,
|
||||
this.ideSettingsPromise,
|
||||
this.controlPlaneClient,
|
||||
this.writeLog,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
);
|
||||
|
||||
this.description.errors = result.errors;
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
setIsActive(isActive: boolean): void {}
|
||||
|
|
|
|||
79
core/config/profile/PlatformProfileLoader.ts
Normal file
79
core/config/profile/PlatformProfileLoader.ts
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
import { AssistantUnrolled } from "@continuedev/config-yaml/dist/schemas/index.js";
|
||||
|
||||
import { ControlPlaneClient } from "../../control-plane/client.js";
|
||||
import { ContinueConfig, IDE, IdeSettings } from "../../index.js";
|
||||
|
||||
import { ConfigResult } from "@continuedev/config-yaml";
|
||||
import { ProfileDescription } from "../ProfileLifecycleManager.js";
|
||||
import doLoadConfig from "./doLoadConfig.js";
|
||||
import { IProfileLoader } from "./IProfileLoader.js";
|
||||
|
||||
/**
|
||||
* Metadata about the package that is currently being loaded
|
||||
* If this is `undefined`, it's not a config from the platform,
|
||||
* could be local for example.
|
||||
*/
|
||||
export interface PlatformConfigMetadata {
|
||||
ownerSlug: string;
|
||||
packageSlug: string;
|
||||
}
|
||||
|
||||
export default class PlatformProfileLoader implements IProfileLoader {
|
||||
static RELOAD_INTERVAL = 1000 * 5; // 5 seconds
|
||||
|
||||
description: ProfileDescription;
|
||||
|
||||
constructor(
|
||||
private configResult: ConfigResult<AssistantUnrolled>,
|
||||
private readonly ownerSlug: string,
|
||||
private readonly packageSlug: string,
|
||||
versionSlug: string,
|
||||
private readonly controlPlaneClient: ControlPlaneClient,
|
||||
private readonly ide: IDE,
|
||||
private ideSettingsPromise: Promise<IdeSettings>,
|
||||
private writeLog: (message: string) => Promise<void>,
|
||||
private readonly onReload: () => void,
|
||||
) {
|
||||
this.description = {
|
||||
id: `${ownerSlug}/${packageSlug}`,
|
||||
profileType: "platform",
|
||||
fullSlug: {
|
||||
ownerSlug,
|
||||
packageSlug,
|
||||
versionSlug,
|
||||
},
|
||||
title: `${ownerSlug}/${packageSlug}@${versionSlug}`,
|
||||
errors: configResult.errors,
|
||||
};
|
||||
}
|
||||
|
||||
async doLoadConfig(): Promise<ConfigResult<ContinueConfig>> {
|
||||
if (this.configResult.errors?.length) {
|
||||
return {
|
||||
config: undefined,
|
||||
errors: this.configResult.errors,
|
||||
configLoadInterrupted: false,
|
||||
};
|
||||
}
|
||||
|
||||
const results = await doLoadConfig(
|
||||
this.ide,
|
||||
this.ideSettingsPromise,
|
||||
this.controlPlaneClient,
|
||||
this.writeLog,
|
||||
undefined,
|
||||
this.configResult.config,
|
||||
{
|
||||
ownerSlug: this.ownerSlug,
|
||||
packageSlug: this.packageSlug,
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
...results,
|
||||
errors: [], // Don't do config validation here, it happens in admin panel
|
||||
};
|
||||
}
|
||||
|
||||
setIsActive(isActive: boolean): void {}
|
||||
}
|
||||
|
|
@ -1,5 +1,10 @@
|
|||
import fs from "fs";
|
||||
|
||||
import {
|
||||
AssistantUnrolled,
|
||||
ConfigResult,
|
||||
ConfigValidationError,
|
||||
} from "@continuedev/config-yaml";
|
||||
import {
|
||||
ContinueConfig,
|
||||
ContinueRcJson,
|
||||
|
|
@ -9,15 +14,16 @@ import {
|
|||
} from "../../";
|
||||
import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js";
|
||||
import { ControlPlaneClient } from "../../control-plane/client.js";
|
||||
import { controlPlaneEnv } from "../../control-plane/env.js";
|
||||
import { getControlPlaneEnv } from "../../control-plane/env.js";
|
||||
import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js";
|
||||
import ContinueProxy from "../../llm/llms/stubs/ContinueProxy";
|
||||
import { getConfigYamlPath } from "../../util/paths";
|
||||
import { getConfigJsonPath, getConfigYamlPath } from "../../util/paths";
|
||||
import { Telemetry } from "../../util/posthog";
|
||||
import { TTS } from "../../util/tts";
|
||||
import { ConfigResult, loadFullConfigNode } from "../load";
|
||||
import { ConfigValidationError } from "../validation";
|
||||
import { loadContinueConfigFromJson } from "../load";
|
||||
import { loadContinueConfigFromYaml } from "../yaml/loadYaml";
|
||||
import { PlatformConfigMetadata } from "./PlatformProfileLoader";
|
||||
import { migrateJsonSharedConfig } from "../migrateSharedConfig";
|
||||
|
||||
export default async function doLoadConfig(
|
||||
ide: IDE,
|
||||
|
|
@ -25,6 +31,8 @@ export default async function doLoadConfig(
|
|||
controlPlaneClient: ControlPlaneClient,
|
||||
writeLog: (message: string) => Promise<void>,
|
||||
overrideConfigJson: SerializedContinueConfig | undefined,
|
||||
overrideConfigYaml: AssistantUnrolled | undefined,
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined,
|
||||
workspaceId?: string,
|
||||
): Promise<ConfigResult<ContinueConfig>> {
|
||||
const workspaceConfigs = await getWorkspaceConfigs(ide);
|
||||
|
|
@ -33,13 +41,20 @@ export default async function doLoadConfig(
|
|||
const ideSettings = await ideSettingsPromise;
|
||||
const workOsAccessToken = await controlPlaneClient.getAccessToken();
|
||||
|
||||
// Migrations for old config files
|
||||
// Removes
|
||||
const configJsonPath = getConfigJsonPath(ideInfo.ideType);
|
||||
if (fs.existsSync(configJsonPath)) {
|
||||
migrateJsonSharedConfig(configJsonPath, ide);
|
||||
}
|
||||
|
||||
const configYamlPath = getConfigYamlPath(ideInfo.ideType);
|
||||
|
||||
let newConfig: ContinueConfig | undefined;
|
||||
let errors: ConfigValidationError[] | undefined;
|
||||
let configLoadInterrupted = false;
|
||||
|
||||
if (fs.existsSync(configYamlPath)) {
|
||||
if (overrideConfigYaml || fs.existsSync(configYamlPath)) {
|
||||
const result = await loadContinueConfigFromYaml(
|
||||
ide,
|
||||
workspaceConfigs.map((c) => JSON.stringify(c)),
|
||||
|
|
@ -48,14 +63,15 @@ export default async function doLoadConfig(
|
|||
uniqueId,
|
||||
writeLog,
|
||||
workOsAccessToken,
|
||||
undefined,
|
||||
// overrideConfigYaml, TODO
|
||||
overrideConfigYaml,
|
||||
platformConfigMetadata,
|
||||
controlPlaneClient,
|
||||
);
|
||||
newConfig = result.config;
|
||||
errors = result.errors;
|
||||
configLoadInterrupted = result.configLoadInterrupted;
|
||||
} else {
|
||||
const result = await loadFullConfigNode(
|
||||
const result = await loadContinueConfigFromJson(
|
||||
ide,
|
||||
workspaceConfigs,
|
||||
ideSettings,
|
||||
|
|
@ -91,9 +107,11 @@ export default async function doLoadConfig(
|
|||
const controlPlane = (newConfig as any).controlPlane;
|
||||
const useOnPremProxy =
|
||||
controlPlane?.useContinueForTeamsProxy === false && controlPlane?.proxyUrl;
|
||||
|
||||
const env = await getControlPlaneEnv(ideSettingsPromise);
|
||||
let controlPlaneProxyUrl: string = useOnPremProxy
|
||||
? controlPlane?.proxyUrl
|
||||
: controlPlaneEnv.DEFAULT_CONTROL_PLANE_PROXY_URL;
|
||||
: env.DEFAULT_CONTROL_PLANE_PROXY_URL;
|
||||
|
||||
if (!controlPlaneProxyUrl.endsWith("/")) {
|
||||
controlPlaneProxyUrl += "/";
|
||||
|
|
|
|||
162
core/config/sharedConfig.ts
Normal file
162
core/config/sharedConfig.ts
Normal file
|
|
@ -0,0 +1,162 @@
|
|||
import z from "zod";
|
||||
import {
|
||||
BrowserSerializedContinueConfig,
|
||||
ContinueConfig,
|
||||
Config,
|
||||
SerializedContinueConfig,
|
||||
} from "..";
|
||||
|
||||
export const sharedConfigSchema = z
|
||||
.object({
|
||||
allowAnonymousTelemetry: z.boolean(),
|
||||
disableIndexing: z.boolean(),
|
||||
disableSessionTitles: z.boolean(),
|
||||
|
||||
// `experimental` in `ContinueConfig`
|
||||
useChromiumForDocsCrawling: z.boolean(),
|
||||
readResponseTTS: z.boolean(),
|
||||
promptPath: z.string(),
|
||||
|
||||
// `ui` in `ContinueConfig`
|
||||
codeBlockToolbarPosition: z.enum(["top", "bottom"]),
|
||||
fontSize: z.number(),
|
||||
codeWrap: z.boolean(),
|
||||
displayRawMarkdown: z.boolean(),
|
||||
showChatScrollbar: z.boolean(),
|
||||
|
||||
// `tabAutocompleteOptions` in `ContinueConfig`
|
||||
useAutocompleteCache: z.boolean(),
|
||||
useAutocompleteMultilineCompletions: z.enum(["always", "never", "auto"]),
|
||||
disableAutocompleteInFiles: z.array(z.string()),
|
||||
})
|
||||
.partial();
|
||||
|
||||
export type SharedConfigSchema = z.infer<typeof sharedConfigSchema>;
|
||||
|
||||
// For security in case of damaged config file, try to salvage any security-related values
|
||||
export function salvageSharedConfig(sharedConfig: object): SharedConfigSchema {
|
||||
const salvagedConfig: SharedConfigSchema = {};
|
||||
if ("allowAnonymousTelemetry" in sharedConfig) {
|
||||
const val = z.boolean().safeParse(sharedConfig.allowAnonymousTelemetry);
|
||||
if (val.success) {
|
||||
salvagedConfig.allowAnonymousTelemetry = val.data;
|
||||
}
|
||||
}
|
||||
if ("disableIndexing" in sharedConfig) {
|
||||
const val = z.boolean().safeParse(sharedConfig.disableIndexing);
|
||||
if (val.success) {
|
||||
salvagedConfig.disableIndexing = val.data;
|
||||
}
|
||||
}
|
||||
if ("disableSessionTitles" in sharedConfig) {
|
||||
const val = z.boolean().safeParse(sharedConfig.disableSessionTitles);
|
||||
if (val.success) {
|
||||
salvagedConfig.disableSessionTitles = val.data;
|
||||
}
|
||||
}
|
||||
if ("disableAutocompleteInFiles" in sharedConfig) {
|
||||
const val = sharedConfigSchema.shape.disableAutocompleteInFiles.safeParse(
|
||||
sharedConfig.disableAutocompleteInFiles,
|
||||
);
|
||||
if (val.success) {
|
||||
salvagedConfig.disableAutocompleteInFiles = val.data;
|
||||
}
|
||||
}
|
||||
return salvagedConfig;
|
||||
}
|
||||
|
||||
export function modifyContinueConfigWithSharedConfig<
|
||||
T extends
|
||||
| ContinueConfig
|
||||
| BrowserSerializedContinueConfig
|
||||
| Config
|
||||
| SerializedContinueConfig,
|
||||
>(continueConfig: T, sharedConfig: SharedConfigSchema): T {
|
||||
const configCopy = { ...continueConfig };
|
||||
configCopy.tabAutocompleteOptions = {
|
||||
...configCopy.tabAutocompleteOptions,
|
||||
};
|
||||
if (sharedConfig.useAutocompleteCache !== undefined) {
|
||||
configCopy.tabAutocompleteOptions.useCache =
|
||||
sharedConfig.useAutocompleteCache;
|
||||
}
|
||||
if (sharedConfig.useAutocompleteMultilineCompletions !== undefined) {
|
||||
configCopy.tabAutocompleteOptions.multilineCompletions =
|
||||
sharedConfig.useAutocompleteMultilineCompletions;
|
||||
}
|
||||
if (sharedConfig.disableAutocompleteInFiles !== undefined) {
|
||||
configCopy.tabAutocompleteOptions.disableInFiles =
|
||||
sharedConfig.disableAutocompleteInFiles;
|
||||
}
|
||||
|
||||
configCopy.ui = {
|
||||
...configCopy.ui,
|
||||
};
|
||||
if (sharedConfig.codeBlockToolbarPosition !== undefined) {
|
||||
configCopy.ui.codeBlockToolbarPosition =
|
||||
sharedConfig.codeBlockToolbarPosition;
|
||||
}
|
||||
if (sharedConfig.fontSize !== undefined) {
|
||||
configCopy.ui.fontSize = sharedConfig.fontSize;
|
||||
}
|
||||
if (sharedConfig.codeWrap !== undefined) {
|
||||
configCopy.ui.codeWrap = sharedConfig.codeWrap;
|
||||
}
|
||||
if (sharedConfig.displayRawMarkdown !== undefined) {
|
||||
configCopy.ui.displayRawMarkdown = sharedConfig.displayRawMarkdown;
|
||||
}
|
||||
if (sharedConfig.showChatScrollbar !== undefined) {
|
||||
configCopy.ui.showChatScrollbar = sharedConfig.showChatScrollbar;
|
||||
}
|
||||
|
||||
if (sharedConfig.allowAnonymousTelemetry !== undefined) {
|
||||
configCopy.allowAnonymousTelemetry = sharedConfig.allowAnonymousTelemetry;
|
||||
}
|
||||
if (sharedConfig.disableIndexing !== undefined) {
|
||||
configCopy.disableIndexing = sharedConfig.disableIndexing;
|
||||
}
|
||||
if (sharedConfig.disableSessionTitles !== undefined) {
|
||||
configCopy.disableSessionTitles = sharedConfig.disableSessionTitles;
|
||||
}
|
||||
|
||||
configCopy.experimental = {
|
||||
...configCopy.experimental,
|
||||
};
|
||||
if (sharedConfig.promptPath !== undefined) {
|
||||
configCopy.experimental.promptPath = sharedConfig.promptPath;
|
||||
}
|
||||
if (sharedConfig.useChromiumForDocsCrawling !== undefined) {
|
||||
configCopy.experimental.useChromiumForDocsCrawling =
|
||||
sharedConfig.useChromiumForDocsCrawling;
|
||||
}
|
||||
if (sharedConfig.readResponseTTS !== undefined) {
|
||||
configCopy.experimental.readResponseTTS = sharedConfig.readResponseTTS;
|
||||
}
|
||||
|
||||
return configCopy;
|
||||
}
|
||||
|
||||
// continueConfig.tabAutocompleteOptions = {
|
||||
// ...continueConfig.tabAutocompleteOptions,
|
||||
// useCache: sharedConfig.useAutocompleteCache,
|
||||
// disableInFiles: sharedConfig.disableAutocompleteInFiles,
|
||||
// multilineCompletions: sharedConfig.useAutocompleteMultilineCompletions,
|
||||
// };
|
||||
// continueConfig.ui = {
|
||||
// ...continueConfig.ui,
|
||||
// codeBlockToolbarPosition: sharedConfig.codeBlockToolbarPosition,
|
||||
// fontSize: sharedConfig.fontSize,
|
||||
// codeWrap: sharedConfig.codeWrap,
|
||||
// displayRawMarkdown: sharedConfig.displayRawMarkdown,
|
||||
// showChatScrollbar: sharedConfig.showChatScrollbar,
|
||||
// };
|
||||
// continueConfig.allowAnonymousTelemetry = sharedConfig.allowAnonymousTelemetry;
|
||||
// continueConfig.disableIndexing = sharedConfig.disableIndexing;
|
||||
// continueConfig.disableIndexing = sharedConfig.disableIndexing;
|
||||
// continueConfig.disableSessionTitles = sharedConfig.disableSessionTitles;
|
||||
// continueConfig.experimental = {
|
||||
// ...continueConfig.experimental,
|
||||
// useChromiumForDocsCrawling: sharedConfig.useChromiumForDocsCrawling,
|
||||
// readResponseTTS: sharedConfig.readResponseTTS,
|
||||
// promptPath: sharedConfig.promptPath,
|
||||
// };
|
||||
|
|
@ -220,18 +220,10 @@ declare global {
|
|||
export interface SiteIndexingConfig {
|
||||
title: string;
|
||||
startUrl: string;
|
||||
rootUrl?: string;
|
||||
maxDepth?: number;
|
||||
faviconUrl?: string;
|
||||
}
|
||||
|
||||
export interface SiteIndexingConfig {
|
||||
startUrl: string;
|
||||
rootUrl?: string;
|
||||
title: string;
|
||||
maxDepth?: number;
|
||||
}
|
||||
|
||||
export interface IContextProvider {
|
||||
get description(): ContextProviderDescription;
|
||||
|
||||
|
|
@ -580,7 +572,6 @@ declare global {
|
|||
userToken: string;
|
||||
enableControlServerBeta: boolean;
|
||||
pauseCodebaseIndexOnStart: boolean;
|
||||
enableDebugLogs: boolean;
|
||||
}
|
||||
|
||||
export interface IDE {
|
||||
|
|
@ -910,7 +901,6 @@ declare global {
|
|||
|
||||
export interface TabAutocompleteOptions {
|
||||
disable: boolean;
|
||||
useFileSuffix: boolean;
|
||||
maxPromptTokens: number;
|
||||
debounceDelay: number;
|
||||
maxSuffixPercentage: number;
|
||||
|
|
@ -955,7 +945,6 @@ declare global {
|
|||
fontSize?: number;
|
||||
displayRawMarkdown?: boolean;
|
||||
showChatScrollbar?: boolean;
|
||||
getChatTitles?: boolean;
|
||||
codeWrap?: boolean;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,11 +1,7 @@
|
|||
import { ConfigValidationError } from "@continuedev/config-yaml";
|
||||
import { ModelDescription, SerializedContinueConfig } from "../";
|
||||
import { Telemetry } from "../util/posthog";
|
||||
|
||||
export interface ConfigValidationError {
|
||||
fatal: boolean;
|
||||
message: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates a SerializedContinueConfig object to ensure all properties are correctly formed.
|
||||
* @param config The configuration object to validate.
|
||||
|
|
|
|||
40
core/config/yaml/clientRender.ts
Normal file
40
core/config/yaml/clientRender.ts
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
import {
|
||||
clientRender,
|
||||
PlatformClient,
|
||||
SecretStore,
|
||||
} from "@continuedev/config-yaml";
|
||||
|
||||
import { IDE } from "../..";
|
||||
import { ControlPlaneClient } from "../../control-plane/client";
|
||||
|
||||
export async function clientRenderHelper(
|
||||
unrolledAssistant: string,
|
||||
ide: IDE,
|
||||
controlPlaneClient: ControlPlaneClient,
|
||||
) {
|
||||
const ideSecretStore: SecretStore = {
|
||||
get: async function (secretName: string): Promise<string | undefined> {
|
||||
const results = await ide.readSecrets([secretName]);
|
||||
return results[secretName];
|
||||
},
|
||||
set: async function (
|
||||
secretName: string,
|
||||
secretValue: string,
|
||||
): Promise<void> {
|
||||
return await ide.writeSecrets({
|
||||
[secretName]: secretValue,
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
const platformClient: PlatformClient = {
|
||||
resolveFQSNs: controlPlaneClient.resolveFQSNs.bind(controlPlaneClient),
|
||||
};
|
||||
|
||||
const userId = await controlPlaneClient.userId;
|
||||
return await clientRender(
|
||||
unrolledAssistant,
|
||||
ideSecretStore,
|
||||
userId ? platformClient : undefined,
|
||||
);
|
||||
}
|
||||
|
|
@ -1,13 +1,14 @@
|
|||
import { ModelConfig } from "@continuedev/config-yaml";
|
||||
import { ConfigYaml } from "@continuedev/config-yaml/dist/schemas";
|
||||
import { AssistantUnrolled } from "@continuedev/config-yaml/dist/schemas";
|
||||
|
||||
import { SerializedContinueConfig } from "../..";
|
||||
|
||||
export function convertConfigJsonToConfigYaml(
|
||||
configJson: SerializedContinueConfig,
|
||||
): ConfigYaml {
|
||||
): AssistantUnrolled {
|
||||
return {
|
||||
name: "Local Config",
|
||||
version: "1.0.0",
|
||||
models: [
|
||||
...configJson.models.map(
|
||||
(model): ModelConfig => ({
|
||||
|
|
@ -23,8 +24,8 @@ export function convertConfigJsonToConfigYaml(
|
|||
// rerankModels
|
||||
],
|
||||
context: configJson.contextProviders?.map((provider) => ({
|
||||
uses: provider.name,
|
||||
with: provider.params,
|
||||
provider: provider.name,
|
||||
params: provider.params,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,14 +1,16 @@
|
|||
import { ConfigYaml } from "@continuedev/config-yaml/dist/schemas";
|
||||
import { AssistantUnrolled } from "@continuedev/config-yaml/dist/schemas";
|
||||
|
||||
// TODO
|
||||
export const defaultConfigYaml: ConfigYaml = {
|
||||
export const defaultConfigYaml: AssistantUnrolled = {
|
||||
models: [],
|
||||
context: [],
|
||||
name: "Local Config",
|
||||
version: "1.0.0",
|
||||
};
|
||||
|
||||
export const defaultConfigYamlJetBrains: ConfigYaml = {
|
||||
export const defaultConfigYamlJetBrains: AssistantUnrolled = {
|
||||
models: [],
|
||||
context: [],
|
||||
name: "Local Config",
|
||||
version: "1.0.0",
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,15 +1,11 @@
|
|||
import fs from "node:fs";
|
||||
import path from "path";
|
||||
|
||||
import {
|
||||
extendConfig,
|
||||
fillTemplateVariables,
|
||||
AssistantUnrolled,
|
||||
ConfigResult,
|
||||
validateConfigYaml,
|
||||
} from "@continuedev/config-yaml";
|
||||
import { ConfigYaml } from "@continuedev/config-yaml/dist/schemas";
|
||||
import { ValidationLevel } from "@continuedev/config-yaml/dist/validation";
|
||||
import { fetchwithRequestOptions } from "@continuedev/fetch";
|
||||
import * as YAML from "yaml";
|
||||
|
||||
import {
|
||||
BrowserSerializedContinueConfig,
|
||||
|
|
@ -22,74 +18,53 @@ import {
|
|||
} from "../..";
|
||||
import { AllRerankers } from "../../context/allRerankers";
|
||||
import { MCPManagerSingleton } from "../../context/mcp";
|
||||
import CodebaseContextProvider from "../../context/providers/CodebaseContextProvider";
|
||||
import FileContextProvider from "../../context/providers/FileContextProvider";
|
||||
import { contextProviderClassFromName } from "../../context/providers/index";
|
||||
import PromptFilesContextProvider from "../../context/providers/PromptFilesContextProvider";
|
||||
import { ControlPlaneClient } from "../../control-plane/client";
|
||||
import { allEmbeddingsProviders } from "../../indexing/allEmbeddingsProviders";
|
||||
import FreeTrial from "../../llm/llms/FreeTrial";
|
||||
import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider";
|
||||
import {
|
||||
getConfigYamlPath,
|
||||
getContinueDotEnv,
|
||||
readAllGlobalPromptFiles,
|
||||
} from "../../util/paths";
|
||||
import { getSystemPromptDotFile } from "../getSystemPromptDotFile";
|
||||
import { ConfigValidationError } from "../validation.js";
|
||||
|
||||
import { llmsFromModelConfig } from "./models";
|
||||
import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles";
|
||||
import { slashCommandFromPromptFileV1 } from "../../promptFiles/v1/slashCommandFromPromptFile";
|
||||
import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles";
|
||||
import { getConfigYamlPath } from "../../util/paths";
|
||||
import { getSystemPromptDotFile } from "../getSystemPromptDotFile";
|
||||
import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader";
|
||||
|
||||
export interface ConfigResult<T> {
|
||||
config: T | undefined;
|
||||
errors: ConfigValidationError[] | undefined;
|
||||
configLoadInterrupted: boolean;
|
||||
}
|
||||
import { slashFromCustomCommand } from "../../commands";
|
||||
import { allTools } from "../../tools";
|
||||
import { clientRenderHelper } from "./clientRender";
|
||||
import { llmsFromModelConfig } from "./models";
|
||||
import { GlobalContext } from "../../util/GlobalContext";
|
||||
import { modifyContinueConfigWithSharedConfig } from "../sharedConfig";
|
||||
|
||||
function renderTemplateVars(configYaml: string): string {
|
||||
const data: Record<string, string> = {};
|
||||
|
||||
// env.*
|
||||
const envVars = getContinueDotEnv();
|
||||
Object.entries(envVars).forEach(([key, value]) => {
|
||||
data[`env.${key}`] = value;
|
||||
});
|
||||
|
||||
// secrets.* not filled in
|
||||
|
||||
return fillTemplateVariables(configYaml, data);
|
||||
}
|
||||
|
||||
function loadConfigYaml(
|
||||
async function loadConfigYaml(
|
||||
workspaceConfigs: string[],
|
||||
ideSettings: IdeSettings,
|
||||
ideType: IdeType,
|
||||
rawYaml: string,
|
||||
): ConfigResult<ConfigYaml> {
|
||||
const renderedYaml = renderTemplateVars(rawYaml);
|
||||
let config = YAML.parse(renderedYaml) as ConfigYaml;
|
||||
overrideConfigYaml: AssistantUnrolled | undefined,
|
||||
ide: IDE,
|
||||
controlPlaneClient: ControlPlaneClient,
|
||||
): Promise<ConfigResult<AssistantUnrolled>> {
|
||||
let config =
|
||||
overrideConfigYaml ??
|
||||
(await clientRenderHelper(rawYaml, ide, controlPlaneClient));
|
||||
const errors = validateConfigYaml(config);
|
||||
|
||||
if (errors?.some((error) => error.level === ValidationLevel.Error)) {
|
||||
if (errors?.some((error) => error.fatal)) {
|
||||
return {
|
||||
errors: errors.map((error) => ({
|
||||
message: error.message,
|
||||
fatal: error.level === ValidationLevel.Error,
|
||||
})),
|
||||
errors,
|
||||
config: undefined,
|
||||
configLoadInterrupted: true,
|
||||
};
|
||||
}
|
||||
|
||||
for (const workspaceConfig of workspaceConfigs) {
|
||||
const rendered = renderTemplateVars(workspaceConfig);
|
||||
config = extendConfig(config, YAML.parse(rendered) as ConfigYaml);
|
||||
}
|
||||
|
||||
// Set defaults if undefined (this lets us keep config.json uncluttered for new users)
|
||||
return {
|
||||
config,
|
||||
errors: errors.map((error) => ({
|
||||
message: error.message,
|
||||
fatal: error.level === ValidationLevel.Error,
|
||||
fatal: error.fatal,
|
||||
})),
|
||||
configLoadInterrupted: false,
|
||||
};
|
||||
|
|
@ -113,23 +88,42 @@ async function slashCommandsFromV1PromptFiles(
|
|||
}
|
||||
|
||||
async function configYamlToContinueConfig(
|
||||
config: ConfigYaml,
|
||||
config: AssistantUnrolled,
|
||||
ide: IDE,
|
||||
ideSettings: IdeSettings,
|
||||
uniqueId: string,
|
||||
writeLog: (log: string) => Promise<void>,
|
||||
workOsAccessToken: string | undefined,
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined,
|
||||
allowFreeTrial: boolean = true,
|
||||
): Promise<ContinueConfig> {
|
||||
const continueConfig: ContinueConfig = {
|
||||
slashCommands: await slashCommandsFromV1PromptFiles(ide),
|
||||
slashCommands: [
|
||||
...(await slashCommandsFromV1PromptFiles(ide)),
|
||||
...(config.prompts?.map(slashFromCustomCommand) ?? []),
|
||||
],
|
||||
models: [],
|
||||
tabAutocompleteModels: [],
|
||||
tools: [],
|
||||
tools: allTools,
|
||||
systemMessage: config.rules?.join("\n"),
|
||||
embeddingsProvider: new TransformersJsEmbeddingsProvider(),
|
||||
experimental: {
|
||||
modelContextProtocolServers: [],
|
||||
modelContextProtocolServers: config.mcpServers?.map((mcpServer) => ({
|
||||
transport: {
|
||||
type: "stdio",
|
||||
command: mcpServer.command,
|
||||
args: mcpServer.args ?? [],
|
||||
env: mcpServer.env,
|
||||
},
|
||||
})),
|
||||
},
|
||||
docs: config.docs?.map((doc) => ({
|
||||
title: doc.name,
|
||||
startUrl: doc.startUrl,
|
||||
rootUrl: doc.rootUrl,
|
||||
faviconUrl: doc.faviconUrl,
|
||||
})),
|
||||
contextProviders: [],
|
||||
};
|
||||
|
||||
// Models
|
||||
|
|
@ -146,9 +140,13 @@ async function configYamlToContinueConfig(
|
|||
uniqueId,
|
||||
ideSettings,
|
||||
writeLog,
|
||||
platformConfigMetadata,
|
||||
continueConfig.systemMessage,
|
||||
);
|
||||
continueConfig.models.push(...llms);
|
||||
} else if (model.roles?.includes("autocomplete")) {
|
||||
}
|
||||
|
||||
if (model.roles?.includes("autocomplete")) {
|
||||
// Autocomplete models array
|
||||
const llms = await llmsFromModelConfig(
|
||||
model,
|
||||
|
|
@ -156,6 +154,8 @@ async function configYamlToContinueConfig(
|
|||
uniqueId,
|
||||
ideSettings,
|
||||
writeLog,
|
||||
platformConfigMetadata,
|
||||
continueConfig.systemMessage,
|
||||
);
|
||||
continueConfig.tabAutocompleteModels?.push(...llms);
|
||||
}
|
||||
|
|
@ -181,18 +181,34 @@ async function configYamlToContinueConfig(
|
|||
|
||||
// TODO: Split into model roles.
|
||||
|
||||
// Context
|
||||
continueConfig.contextProviders = config.context
|
||||
// Context providers
|
||||
const codebaseContextParams: IContextProvider[] =
|
||||
(config.context || []).find((cp) => cp.provider === "codebase")?.params ||
|
||||
{};
|
||||
const DEFAULT_CONTEXT_PROVIDERS = [
|
||||
new FileContextProvider({}),
|
||||
new CodebaseContextProvider(codebaseContextParams),
|
||||
new PromptFilesContextProvider({}),
|
||||
];
|
||||
|
||||
const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map(
|
||||
({ description: { title } }) => title,
|
||||
);
|
||||
|
||||
continueConfig.contextProviders = (config.context
|
||||
?.map((context) => {
|
||||
const cls = contextProviderClassFromName(context.uses) as any;
|
||||
const cls = contextProviderClassFromName(context.provider) as any;
|
||||
if (!cls) {
|
||||
console.warn(`Unknown context provider ${context.uses}`);
|
||||
if (!DEFAULT_CONTEXT_PROVIDERS_TITLES.includes(context.provider)) {
|
||||
console.warn(`Unknown context provider ${context.provider}`);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
const instance: IContextProvider = new cls(context.with ?? {});
|
||||
const instance: IContextProvider = new cls(context.params ?? {});
|
||||
return instance;
|
||||
})
|
||||
.filter((p) => !!p) as IContextProvider[];
|
||||
.filter((p) => !!p) ?? []) as IContextProvider[];
|
||||
continueConfig.contextProviders.push(...DEFAULT_CONTEXT_PROVIDERS);
|
||||
|
||||
// Embeddings Provider
|
||||
const embedConfig = config.models?.find((model) =>
|
||||
|
|
@ -283,16 +299,21 @@ export async function loadContinueConfigFromYaml(
|
|||
uniqueId: string,
|
||||
writeLog: (log: string) => Promise<void>,
|
||||
workOsAccessToken: string | undefined,
|
||||
overrideConfigYaml: string | undefined,
|
||||
overrideConfigYaml: AssistantUnrolled | undefined,
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined,
|
||||
controlPlaneClient: ControlPlaneClient,
|
||||
): Promise<ConfigResult<ContinueConfig>> {
|
||||
const configYamlPath = getConfigYamlPath(ideType);
|
||||
const rawYaml = fs.readFileSync(configYamlPath, "utf-8");
|
||||
const rawYaml =
|
||||
overrideConfigYaml === undefined
|
||||
? fs.readFileSync(getConfigYamlPath(ideType), "utf-8")
|
||||
: "";
|
||||
|
||||
const configYamlResult = await loadConfigYaml(
|
||||
workspaceConfigs,
|
||||
ideSettings,
|
||||
ideType,
|
||||
overrideConfigYaml ?? rawYaml,
|
||||
rawYaml,
|
||||
overrideConfigYaml,
|
||||
ide,
|
||||
controlPlaneClient,
|
||||
);
|
||||
|
||||
if (!configYamlResult.config || configYamlResult.configLoadInterrupted) {
|
||||
|
|
@ -310,6 +331,7 @@ export async function loadContinueConfigFromYaml(
|
|||
uniqueId,
|
||||
writeLog,
|
||||
workOsAccessToken,
|
||||
platformConfigMetadata,
|
||||
);
|
||||
|
||||
const systemPromptDotFile = await getSystemPromptDotFile(ide);
|
||||
|
|
@ -321,8 +343,16 @@ export async function loadContinueConfigFromYaml(
|
|||
}
|
||||
}
|
||||
|
||||
// Apply shared config
|
||||
// TODO: override several of these values with user/org shared config
|
||||
const sharedConfig = new GlobalContext().getSharedConfig();
|
||||
const withShared = modifyContinueConfigWithSharedConfig(
|
||||
continueConfig,
|
||||
sharedConfig,
|
||||
);
|
||||
|
||||
return {
|
||||
config: continueConfig,
|
||||
config: withShared,
|
||||
errors: configYamlResult.errors,
|
||||
configLoadInterrupted: false,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -3,21 +3,47 @@ import { ModelConfig } from "@continuedev/config-yaml";
|
|||
import { IDE, IdeSettings, LLMOptions } from "../..";
|
||||
import { BaseLLM } from "../../llm";
|
||||
import { LLMClasses } from "../../llm/llms";
|
||||
import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader";
|
||||
|
||||
const AUTODETECT = "AUTODETECT";
|
||||
|
||||
function getModelClass(
|
||||
model: ModelConfig,
|
||||
): (typeof LLMClasses)[number] | undefined {
|
||||
return LLMClasses.find((llm) => llm.providerName === model.provider);
|
||||
}
|
||||
|
||||
function getContinueProxyModelName(
|
||||
ownerSlug: string,
|
||||
packageSlug: string,
|
||||
model: ModelConfig,
|
||||
): string {
|
||||
return `${ownerSlug}/${packageSlug}/${model.provider}/${model.model}`;
|
||||
}
|
||||
|
||||
async function modelConfigToBaseLLM(
|
||||
model: ModelConfig,
|
||||
uniqueId: string,
|
||||
ideSettings: IdeSettings,
|
||||
writeLog: (log: string) => Promise<void>,
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined,
|
||||
systemMessage: string | undefined,
|
||||
): Promise<BaseLLM | undefined> {
|
||||
const cls = LLMClasses.find((llm) => llm.providerName === model.provider);
|
||||
const cls = getModelClass(model);
|
||||
|
||||
if (!cls) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const usingContinueProxy = model.provider === "continue-proxy";
|
||||
const modelName = usingContinueProxy
|
||||
? getContinueProxyModelName(
|
||||
platformConfigMetadata!.ownerSlug,
|
||||
platformConfigMetadata!.packageSlug,
|
||||
model,
|
||||
)
|
||||
: model.model;
|
||||
|
||||
let options: LLMOptions = {
|
||||
...model,
|
||||
completionOptions: {
|
||||
|
|
@ -30,6 +56,8 @@ async function modelConfigToBaseLLM(
|
|||
writeLog,
|
||||
uniqueId,
|
||||
title: model.name,
|
||||
model: modelName,
|
||||
systemMessage,
|
||||
};
|
||||
|
||||
const llm = new cls(options);
|
||||
|
|
@ -43,6 +71,8 @@ async function autodetectModels(
|
|||
uniqueId: string,
|
||||
ideSettings: IdeSettings,
|
||||
writeLog: (log: string) => Promise<void>,
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined,
|
||||
systemMessage: string | undefined,
|
||||
): Promise<BaseLLM[]> {
|
||||
try {
|
||||
const modelNames = await llm.listModels();
|
||||
|
|
@ -62,6 +92,8 @@ async function autodetectModels(
|
|||
uniqueId,
|
||||
ideSettings,
|
||||
writeLog,
|
||||
platformConfigMetadata,
|
||||
systemMessage,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
|
@ -78,12 +110,16 @@ export async function llmsFromModelConfig(
|
|||
uniqueId: string,
|
||||
ideSettings: IdeSettings,
|
||||
writeLog: (log: string) => Promise<void>,
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined,
|
||||
systemMessage: string | undefined,
|
||||
): Promise<BaseLLM[]> {
|
||||
const baseLlm = await modelConfigToBaseLLM(
|
||||
model,
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
writeLog,
|
||||
platformConfigMetadata,
|
||||
systemMessage,
|
||||
);
|
||||
if (!baseLlm) {
|
||||
return [];
|
||||
|
|
@ -97,6 +133,8 @@ export async function llmsFromModelConfig(
|
|||
uniqueId,
|
||||
ideSettings,
|
||||
writeLog,
|
||||
platformConfigMetadata,
|
||||
systemMessage,
|
||||
);
|
||||
return models;
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -4,9 +4,9 @@ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"
|
|||
import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js";
|
||||
import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
|
||||
|
||||
import { ConfigValidationError } from "@continuedev/config-yaml";
|
||||
import { ContinueConfig, MCPOptions, SlashCommand, Tool } from "../..";
|
||||
import { constructMcpSlashCommand } from "../../commands/slash/mcp";
|
||||
import { ConfigValidationError } from "../../config/validation";
|
||||
import { encodeMCPToolUri } from "../../tools/callTool";
|
||||
import MCPContextProvider from "../providers/MCPContextProvider";
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { controlPlaneEnv } from "../../control-plane/env.js";
|
||||
import { getControlPlaneEnv } from "../../control-plane/env.js";
|
||||
import {
|
||||
ContextItem,
|
||||
ContextProviderDescription,
|
||||
|
|
@ -35,11 +35,9 @@ class ContinueProxyContextProvider extends BaseContextProvider {
|
|||
async loadSubmenuItems(
|
||||
args: LoadSubmenuItemsArgs,
|
||||
): Promise<ContextSubmenuItem[]> {
|
||||
const env = await getControlPlaneEnv(args.ide.getIdeSettings());
|
||||
const response = await args.fetch(
|
||||
new URL(
|
||||
`/proxy/context/${this.options.id}/list`,
|
||||
controlPlaneEnv.CONTROL_PLANE_URL,
|
||||
),
|
||||
new URL(`/proxy/context/${this.options.id}/list`, env.CONTROL_PLANE_URL),
|
||||
{
|
||||
method: "GET",
|
||||
headers: {
|
||||
|
|
@ -56,10 +54,11 @@ class ContinueProxyContextProvider extends BaseContextProvider {
|
|||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const env = await getControlPlaneEnv(extras.ide.getIdeSettings());
|
||||
const response = await extras.fetch(
|
||||
new URL(
|
||||
`/proxy/context/${this.options.id}/retrieve`,
|
||||
controlPlaneEnv.CONTROL_PLANE_URL,
|
||||
env.CONTROL_PLANE_URL,
|
||||
),
|
||||
{
|
||||
method: "POST",
|
||||
|
|
|
|||
|
|
@ -20,10 +20,16 @@ class DocsContextProvider extends BaseContextProvider {
|
|||
displayTitle: "Docs",
|
||||
description: "Type to search docs",
|
||||
type: "submenu",
|
||||
// Todo: consider a different renderInline so that when multiple docs are referenced in one message,
|
||||
// Or the doc has an odd name unrelated to the content
|
||||
// The name of the doc itself doesn't skew the embedding results
|
||||
// renderInlineAs: "<docs-context-provider>",
|
||||
};
|
||||
|
||||
constructor(options: any) {
|
||||
super(options);
|
||||
const docsService = DocsService.getSingleton();
|
||||
docsService?.setGithubToken(this.options?.githubToken);
|
||||
}
|
||||
|
||||
private async _rerankChunks(
|
||||
|
|
@ -80,6 +86,7 @@ class DocsContextProvider extends BaseContextProvider {
|
|||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const nRetrieve = this.options?.nRetrieve ?? DocsContextProvider.nRetrieve;
|
||||
const useReranking = this.options?.useReranking ?? true;
|
||||
|
||||
// Get docs service
|
||||
|
|
@ -94,7 +101,7 @@ class DocsContextProvider extends BaseContextProvider {
|
|||
let chunks = await docsService.retrieveChunksFromQuery(
|
||||
extras.fullInput, // confusing: fullInput = the query, query = startUrl in this case
|
||||
query,
|
||||
this.options?.nRetrieve ?? DocsContextProvider.nRetrieve,
|
||||
nRetrieve,
|
||||
);
|
||||
if (!chunks?.length) {
|
||||
return [];
|
||||
|
|
@ -173,6 +180,10 @@ class DocsContextProvider extends BaseContextProvider {
|
|||
const canUsePreindexedDocs = await docsService.canUsePreindexedDocs();
|
||||
if (canUsePreindexedDocs) {
|
||||
for (const { startUrl, title } of Object.values(preIndexedDocs)) {
|
||||
// Skip if overridden in config
|
||||
if (docs.find((d) => d.startUrl === startUrl)) {
|
||||
continue;
|
||||
}
|
||||
submenuItemsMap.set(startUrl, {
|
||||
title,
|
||||
id: startUrl,
|
||||
|
|
|
|||
|
|
@ -41,7 +41,7 @@ class RepoMapContextProvider extends BaseContextProvider {
|
|||
// Doesn't ALWAYS depend on indexing, so not setting dependsOnIndexing = true, just checking for it
|
||||
includeSignatures: extras.config.disableIndexing
|
||||
? false
|
||||
: (this.options?.includeSignatures ?? false),
|
||||
: (this.options?.includeSignatures ?? true),
|
||||
}),
|
||||
},
|
||||
];
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ async function getContextProviderExtras(
|
|||
ide,
|
||||
ideSettingsPromise,
|
||||
async (text) => {},
|
||||
new ControlPlaneClient(Promise.resolve(undefined)),
|
||||
new ControlPlaneClient(Promise.resolve(undefined), ideSettingsPromise),
|
||||
);
|
||||
const { config } = await configHandler.loadConfig();
|
||||
if (!config) {
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ export interface IContinueServerClient {
|
|||
connected: boolean;
|
||||
url: URL | undefined;
|
||||
getUserToken(): string | undefined;
|
||||
getConfig(): Promise<{ configJson: string; configJs: string }>;
|
||||
getConfig(): Promise<{ configJson: string }>;
|
||||
getFromIndexCache<T extends ArtifactType>(
|
||||
keys: string[],
|
||||
artifactId: T,
|
||||
|
|
|
|||
|
|
@ -30,7 +30,7 @@ export class ContinueServerClient implements IContinueServerClient {
|
|||
return this.url !== undefined && this.userToken !== undefined;
|
||||
}
|
||||
|
||||
public async getConfig(): Promise<{ configJson: string; configJs: string }> {
|
||||
public async getConfig(): Promise<{ configJson: string }> {
|
||||
const userToken = await this.userToken;
|
||||
const response = await fetch(new URL("sync", this.url).href, {
|
||||
method: "GET",
|
||||
|
|
|
|||
|
|
@ -1,14 +1,16 @@
|
|||
import { v4 as uuidv4 } from "uuid";
|
||||
import { IdeSettings } from "../..";
|
||||
import { getControlPlaneEnv } from "../env";
|
||||
|
||||
const CLIENT_ID = "client_01J0FW6XN8N2XJAECF7NE0Y65J";
|
||||
// const CLIENT_ID = "client_01J0FW6XCPMJMQ3CG51RB4HBZQ"; // Staging
|
||||
|
||||
export async function getAuthUrlForTokenPage(): Promise<string> {
|
||||
export async function getAuthUrlForTokenPage(
|
||||
ideSettingsPromise: Promise<IdeSettings>,
|
||||
): Promise<string> {
|
||||
const env = await getControlPlaneEnv(ideSettingsPromise);
|
||||
const url = new URL("https://api.workos.com/user_management/authorize");
|
||||
const params = {
|
||||
response_type: "code",
|
||||
client_id: CLIENT_ID,
|
||||
redirect_uri: "https://app.continue.dev/tokens/callback",
|
||||
client_id: env.WORKOS_CLIENT_ID,
|
||||
redirect_uri: `${env.APP_URL}tokens/callback`,
|
||||
// redirect_uri: "http://localhost:3000/tokens/callback",
|
||||
state: uuidv4(),
|
||||
provider: "authkit",
|
||||
|
|
|
|||
|
|
@ -1,9 +1,16 @@
|
|||
import { ConfigJson } from "@continuedev/config-types";
|
||||
import fetch, { RequestInit, Response } from "node-fetch";
|
||||
|
||||
import { ModelDescription } from "../index.js";
|
||||
import { IdeSettings, ModelDescription } from "../index.js";
|
||||
|
||||
import { controlPlaneEnv } from "./env.js";
|
||||
import {
|
||||
AssistantUnrolled,
|
||||
ConfigResult,
|
||||
FQSN,
|
||||
FullSlug,
|
||||
SecretResult,
|
||||
} from "@continuedev/config-yaml";
|
||||
import { getControlPlaneEnv } from "./env.js";
|
||||
|
||||
export interface ControlPlaneSessionInfo {
|
||||
accessToken: string;
|
||||
|
|
@ -25,7 +32,6 @@ export const TRIAL_PROXY_URL =
|
|||
"https://proxy-server-blue-l6vsfbzhba-uw.a.run.app";
|
||||
|
||||
export class ControlPlaneClient {
|
||||
private static URL = controlPlaneEnv.CONTROL_PLANE_URL;
|
||||
private static ACCESS_TOKEN_VALID_FOR_MS = 1000 * 60 * 5; // 5 minutes
|
||||
|
||||
private lastAccessTokenRefresh = 0;
|
||||
|
|
@ -34,8 +40,22 @@ export class ControlPlaneClient {
|
|||
private readonly sessionInfoPromise: Promise<
|
||||
ControlPlaneSessionInfo | undefined
|
||||
>,
|
||||
private readonly ideSettingsPromise: Promise<IdeSettings>,
|
||||
) {}
|
||||
|
||||
async resolveFQSNs(fqsns: FQSN[]): Promise<(SecretResult | undefined)[]> {
|
||||
const userId = await this.userId;
|
||||
if (!userId) {
|
||||
throw new Error("No user id");
|
||||
}
|
||||
|
||||
const resp = await this.request("ide/sync-secrets", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ fqsns }),
|
||||
});
|
||||
return (await resp.json()) as any;
|
||||
}
|
||||
|
||||
get userId(): Promise<string | undefined> {
|
||||
return this.sessionInfoPromise.then(
|
||||
(sessionInfo) => sessionInfo?.account.id,
|
||||
|
|
@ -51,7 +71,9 @@ export class ControlPlaneClient {
|
|||
if (!accessToken) {
|
||||
throw new Error("No access token");
|
||||
}
|
||||
const url = new URL(path, ControlPlaneClient.URL).toString();
|
||||
|
||||
const env = await getControlPlaneEnv(this.ideSettingsPromise);
|
||||
const url = new URL(path, env.CONTROL_PLANE_URL).toString();
|
||||
const resp = await fetch(url, {
|
||||
...init,
|
||||
headers: {
|
||||
|
|
@ -85,6 +107,46 @@ export class ControlPlaneClient {
|
|||
}
|
||||
}
|
||||
|
||||
public async listAssistants(): Promise<
|
||||
{
|
||||
configResult: ConfigResult<AssistantUnrolled>;
|
||||
ownerSlug: string;
|
||||
packageSlug: string;
|
||||
iconUrl: string;
|
||||
}[]
|
||||
> {
|
||||
const userId = await this.userId;
|
||||
if (!userId) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const resp = await this.request("ide/list-assistants", {
|
||||
method: "GET",
|
||||
});
|
||||
return (await resp.json()) as any;
|
||||
} catch (e) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
public async listAssistantFullSlugs(): Promise<FullSlug[] | null> {
|
||||
const userId = await this.userId;
|
||||
if (!userId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const resp = await this.request("ide/list-assistant-full-slugs", {
|
||||
method: "GET",
|
||||
});
|
||||
const { fullSlugs } = (await resp.json()) as any;
|
||||
return fullSlugs;
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async getSettingsForWorkspace(workspaceId: string): Promise<ConfigJson> {
|
||||
const userId = await this.userId;
|
||||
if (!userId) {
|
||||
|
|
@ -96,4 +158,21 @@ export class ControlPlaneClient {
|
|||
});
|
||||
return ((await resp.json()) as any).settings;
|
||||
}
|
||||
|
||||
async syncSecrets(secretNames: string[]): Promise<Record<string, string>> {
|
||||
const userId = await this.userId;
|
||||
if (!userId) {
|
||||
throw new Error("No user id");
|
||||
}
|
||||
|
||||
try {
|
||||
const resp = await this.request("ide/sync-secrets", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ secretNames }),
|
||||
});
|
||||
return (await resp.json()) as any;
|
||||
} catch (e) {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,6 @@
|
|||
interface ControlPlaneEnv {
|
||||
import { IdeSettings } from "..";
|
||||
|
||||
export interface ControlPlaneEnv {
|
||||
DEFAULT_CONTROL_PLANE_PROXY_URL: string;
|
||||
CONTROL_PLANE_URL: string;
|
||||
AUTH_TYPE: string;
|
||||
|
|
@ -21,7 +23,15 @@ const PRODUCTION_ENV: ControlPlaneEnv = {
|
|||
"https://control-plane-api-service-i3dqylpbqa-uc.a.run.app/",
|
||||
AUTH_TYPE: WORKOS_ENV_ID_PRODUCTION,
|
||||
WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_PRODUCTION,
|
||||
APP_URL: "https://app.continue.dev",
|
||||
APP_URL: "https://app.continue.dev/",
|
||||
};
|
||||
|
||||
const PRODUCTION_HUB_ENV: ControlPlaneEnv = {
|
||||
DEFAULT_CONTROL_PLANE_PROXY_URL: "https://api.continue.dev/",
|
||||
CONTROL_PLANE_URL: "https://api.continue.dev/",
|
||||
AUTH_TYPE: WORKOS_ENV_ID_PRODUCTION,
|
||||
WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_PRODUCTION,
|
||||
APP_URL: "https://hub.continue.dev/",
|
||||
};
|
||||
|
||||
const STAGING_ENV: ControlPlaneEnv = {
|
||||
|
|
@ -31,7 +41,15 @@ const STAGING_ENV: ControlPlaneEnv = {
|
|||
"https://control-plane-api-service-537175798139.us-central1.run.app/",
|
||||
AUTH_TYPE: WORKOS_CLIENT_ID_STAGING,
|
||||
WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_STAGING,
|
||||
APP_URL: "https://app-preview.continue.dev",
|
||||
APP_URL: "https://app-preview.continue.dev/",
|
||||
};
|
||||
|
||||
const TEST_ENV: ControlPlaneEnv = {
|
||||
DEFAULT_CONTROL_PLANE_PROXY_URL: "https://api-test.continue.dev/",
|
||||
CONTROL_PLANE_URL: "https://api-test.continue.dev/",
|
||||
AUTH_TYPE: WORKOS_ENV_ID_STAGING,
|
||||
WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_STAGING,
|
||||
APP_URL: "https://app-test.continue.dev/",
|
||||
};
|
||||
|
||||
const LOCAL_ENV: ControlPlaneEnv = {
|
||||
|
|
@ -39,12 +57,42 @@ const LOCAL_ENV: ControlPlaneEnv = {
|
|||
CONTROL_PLANE_URL: "http://localhost:3001/",
|
||||
AUTH_TYPE: WORKOS_ENV_ID_STAGING,
|
||||
WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_STAGING,
|
||||
APP_URL: "http://localhost:3000",
|
||||
APP_URL: "http://localhost:3000/",
|
||||
};
|
||||
|
||||
export const controlPlaneEnv =
|
||||
process.env.CONTROL_PLANE_ENV === "local"
|
||||
export async function getControlPlaneEnv(
|
||||
ideSettingsPromise: Promise<IdeSettings>,
|
||||
): Promise<ControlPlaneEnv> {
|
||||
const ideSettings = await ideSettingsPromise;
|
||||
return getControlPlaneEnvSync(ideSettings.continueTestEnvironment);
|
||||
}
|
||||
|
||||
export function getControlPlaneEnvSync(
|
||||
ideTestEnvironment: IdeSettings["continueTestEnvironment"],
|
||||
): ControlPlaneEnv {
|
||||
const env =
|
||||
ideTestEnvironment === "production"
|
||||
? "hub"
|
||||
: ideTestEnvironment === "test"
|
||||
? "test"
|
||||
: ideTestEnvironment === "local"
|
||||
? "local"
|
||||
: process.env.CONTROL_PLANE_ENV;
|
||||
|
||||
return env === "local"
|
||||
? LOCAL_ENV
|
||||
: process.env.CONTROL_PLANE_ENV === "staging"
|
||||
: env === "staging"
|
||||
? STAGING_ENV
|
||||
: PRODUCTION_ENV;
|
||||
: env === "test"
|
||||
? TEST_ENV
|
||||
: env === "hub"
|
||||
? PRODUCTION_HUB_ENV
|
||||
: PRODUCTION_ENV;
|
||||
}
|
||||
|
||||
export async function useHub(
|
||||
ideSettingsPromise: Promise<IdeSettings>,
|
||||
): Promise<boolean> {
|
||||
const ideSettings = await ideSettingsPromise;
|
||||
return ideSettings.continueTestEnvironment !== "none";
|
||||
}
|
||||
|
|
|
|||
68
core/core.ts
68
core/core.ts
|
|
@ -43,8 +43,16 @@ import { Telemetry } from "./util/posthog";
|
|||
import { getSymbolsForManyFiles } from "./util/treeSitter";
|
||||
import { TTS } from "./util/tts";
|
||||
|
||||
import { type ContextItemId, type IDE, type IndexingProgressUpdate } from ".";
|
||||
import {
|
||||
ChatMessage,
|
||||
DiffLine,
|
||||
PromptLog,
|
||||
type ContextItemId,
|
||||
type IDE,
|
||||
type IndexingProgressUpdate,
|
||||
} from ".";
|
||||
|
||||
import { getControlPlaneEnv } from "./control-plane/env";
|
||||
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
|
||||
import type { IMessenger, Message } from "./protocol/messenger";
|
||||
|
||||
|
|
@ -103,9 +111,13 @@ export class Core {
|
|||
const ideSettingsPromise = messenger.request("getIdeSettings", undefined);
|
||||
const sessionInfoPromise = messenger.request("getControlPlaneSessionInfo", {
|
||||
silent: true,
|
||||
useOnboarding: false,
|
||||
});
|
||||
|
||||
this.controlPlaneClient = new ControlPlaneClient(sessionInfoPromise);
|
||||
this.controlPlaneClient = new ControlPlaneClient(
|
||||
sessionInfoPromise,
|
||||
ideSettingsPromise,
|
||||
);
|
||||
|
||||
this.configHandler = new ConfigHandler(
|
||||
this.ide,
|
||||
|
|
@ -124,7 +136,7 @@ export class Core {
|
|||
const serializedResult = await this.configHandler.getSerializedConfig();
|
||||
this.messenger.send("configUpdate", {
|
||||
result: serializedResult,
|
||||
profileId: this.configHandler.currentProfile.profileId,
|
||||
profileId: this.configHandler.currentProfile.profileDescription.id,
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -277,6 +289,7 @@ export class Core {
|
|||
on("config/ideSettingsUpdate", (msg) => {
|
||||
this.configHandler.updateIdeSettings(msg.data);
|
||||
});
|
||||
|
||||
on("config/listProfiles", (msg) => {
|
||||
return this.configHandler.listProfiles();
|
||||
});
|
||||
|
|
@ -285,6 +298,16 @@ export class Core {
|
|||
addContextProvider(msg.data);
|
||||
});
|
||||
|
||||
on("config/updateSharedConfig", async (msg) => {
|
||||
this.globalContext.updateSharedConfig(msg.data);
|
||||
await this.configHandler.reloadConfig();
|
||||
});
|
||||
|
||||
on("controlPlane/openUrl", async (msg) => {
|
||||
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
|
||||
await this.messenger.request("openUrl", `${env.APP_URL}${msg.data.path}`);
|
||||
});
|
||||
|
||||
// Context providers
|
||||
on("context/addDocs", async (msg) => {
|
||||
void this.docsService.indexAndAdd(msg.data);
|
||||
|
|
@ -378,7 +401,7 @@ export class Core {
|
|||
on("config/getSerializedProfileInfo", async (msg) => {
|
||||
return {
|
||||
result: await this.configHandler.getSerializedConfig(),
|
||||
profileId: this.configHandler.currentProfile.profileId,
|
||||
profileId: this.configHandler.currentProfile.profileDescription.id,
|
||||
};
|
||||
});
|
||||
|
||||
|
|
@ -395,7 +418,7 @@ export class Core {
|
|||
configHandler: ConfigHandler,
|
||||
abortedMessageIds: Set<string>,
|
||||
msg: Message<ToCoreProtocol["llm/streamChat"][0]>,
|
||||
) {
|
||||
): AsyncGenerator<ChatMessage, PromptLog> {
|
||||
const { config } = await configHandler.loadConfig();
|
||||
if (!config) {
|
||||
throw new Error("Config not loaded");
|
||||
|
|
@ -431,7 +454,7 @@ export class Core {
|
|||
|
||||
const chunk = next.value;
|
||||
|
||||
yield { content: chunk };
|
||||
yield chunk;
|
||||
next = await gen.next();
|
||||
}
|
||||
|
||||
|
|
@ -448,7 +471,11 @@ export class Core {
|
|||
true,
|
||||
);
|
||||
|
||||
return { done: true, content: next.value };
|
||||
if (!next.done) {
|
||||
throw new Error("Will never happen");
|
||||
}
|
||||
|
||||
return next.value;
|
||||
}
|
||||
|
||||
on("llm/streamChat", (msg) =>
|
||||
|
|
@ -458,9 +485,8 @@ export class Core {
|
|||
async function* llmStreamComplete(
|
||||
configHandler: ConfigHandler,
|
||||
abortedMessageIds: Set<string>,
|
||||
|
||||
msg: Message<ToCoreProtocol["llm/streamComplete"][0]>,
|
||||
) {
|
||||
): AsyncGenerator<string, PromptLog> {
|
||||
const model = await configHandler.llmFromTitle(msg.data.title);
|
||||
const gen = model.streamComplete(
|
||||
msg.data.prompt,
|
||||
|
|
@ -482,11 +508,13 @@ export class Core {
|
|||
});
|
||||
break;
|
||||
}
|
||||
yield { content: next.value };
|
||||
yield next.value;
|
||||
next = await gen.next();
|
||||
}
|
||||
|
||||
return { done: true, content: next.value };
|
||||
if (!next.done) {
|
||||
throw new Error("This will never happen");
|
||||
}
|
||||
return next.value;
|
||||
}
|
||||
|
||||
on("llm/streamComplete", (msg) =>
|
||||
|
|
@ -548,7 +576,7 @@ export class Core {
|
|||
abortedMessageIds: Set<string>,
|
||||
msg: Message<ToCoreProtocol["command/run"][0]>,
|
||||
messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>,
|
||||
) {
|
||||
): AsyncGenerator<string> {
|
||||
const {
|
||||
input,
|
||||
history,
|
||||
|
|
@ -613,7 +641,7 @@ export class Core {
|
|||
break;
|
||||
}
|
||||
if (content) {
|
||||
yield { content };
|
||||
yield content;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
|
|
@ -621,7 +649,6 @@ export class Core {
|
|||
} finally {
|
||||
clearInterval(checkActiveInterval);
|
||||
}
|
||||
yield { done: true, content: "" };
|
||||
}
|
||||
on("command/run", (msg) =>
|
||||
runNodeJsSlashCommand(
|
||||
|
|
@ -652,7 +679,7 @@ export class Core {
|
|||
configHandler: ConfigHandler,
|
||||
abortedMessageIds: Set<string>,
|
||||
msg: Message<ToCoreProtocol["streamDiffLines"][0]>,
|
||||
) {
|
||||
): AsyncGenerator<DiffLine> {
|
||||
const data = msg.data;
|
||||
const llm = await configHandler.llmFromTitle(msg.data.modelTitle);
|
||||
for await (const diffLine of streamDiffLines(
|
||||
|
|
@ -667,10 +694,8 @@ export class Core {
|
|||
abortedMessageIds.delete(msg.messageId);
|
||||
break;
|
||||
}
|
||||
yield { content: diffLine };
|
||||
yield diffLine;
|
||||
}
|
||||
|
||||
return { done: true };
|
||||
}
|
||||
|
||||
on("streamDiffLines", (msg) =>
|
||||
|
|
@ -844,6 +869,9 @@ export class Core {
|
|||
on("docs/initStatuses", async (msg) => {
|
||||
void this.docsService.initStatuses();
|
||||
});
|
||||
on("docs/getDetails", async (msg) => {
|
||||
return await this.docsService.getDetails(msg.data.startUrl);
|
||||
});
|
||||
//
|
||||
|
||||
on("didChangeSelectedProfile", (msg) => {
|
||||
|
|
@ -854,7 +882,7 @@ export class Core {
|
|||
this.configHandler.updateControlPlaneSessionInfo(msg.data.sessionInfo);
|
||||
});
|
||||
on("auth/getAuthUrl", async (msg) => {
|
||||
const url = await getAuthUrlForTokenPage();
|
||||
const url = await getAuthUrlForTokenPage(ideSettingsPromise);
|
||||
return { url };
|
||||
});
|
||||
|
||||
|
|
|
|||
65
core/index.d.ts
vendored
65
core/index.d.ts
vendored
|
|
@ -223,16 +223,18 @@ export interface ContextSubmenuItemWithProvider extends ContextSubmenuItem {
|
|||
export interface SiteIndexingConfig {
|
||||
title: string;
|
||||
startUrl: string;
|
||||
rootUrl?: string;
|
||||
maxDepth?: number;
|
||||
faviconUrl?: string;
|
||||
useLocalCrawling?: boolean;
|
||||
rootUrl?: string; // Currently only used by preindexed docs
|
||||
}
|
||||
|
||||
export interface SiteIndexingConfig {
|
||||
export interface DocsIndexingDetails {
|
||||
startUrl: string;
|
||||
rootUrl?: string;
|
||||
title: string;
|
||||
maxDepth?: number;
|
||||
config: SiteIndexingConfig;
|
||||
indexingStatus: IndexingStatus | undefined;
|
||||
chunks: Chunk[];
|
||||
isPreIndexedDoc: boolean;
|
||||
}
|
||||
|
||||
export interface IContextProvider {
|
||||
|
|
@ -306,11 +308,17 @@ export interface CompletionOptions extends BaseCompletionOptions {
|
|||
|
||||
export type ChatMessageRole = "user" | "assistant" | "system" | "tool";
|
||||
|
||||
export interface MessagePart {
|
||||
type: "text" | "imageUrl";
|
||||
text?: string;
|
||||
imageUrl?: { url: string };
|
||||
}
|
||||
export type TextMessagePart = {
|
||||
type: "text";
|
||||
text: string;
|
||||
};
|
||||
|
||||
export type ImageMessagePart = {
|
||||
type: "imageUrl";
|
||||
imageUrl: { url: string };
|
||||
};
|
||||
|
||||
export type MessagePart = TextMessagePart | ImageMessagePart;
|
||||
|
||||
export type MessageContent = string | MessagePart[];
|
||||
|
||||
|
|
@ -425,6 +433,13 @@ interface ToolCallState {
|
|||
output?: ContextItem[];
|
||||
}
|
||||
|
||||
interface Reasoning {
|
||||
active: boolean;
|
||||
text: string;
|
||||
startAt: number;
|
||||
endAt?: number;
|
||||
}
|
||||
|
||||
export interface ChatHistoryItem {
|
||||
message: ChatMessage;
|
||||
contextItems: ContextItemWithId[];
|
||||
|
|
@ -435,6 +450,7 @@ export interface ChatHistoryItem {
|
|||
isGatheringContext?: boolean;
|
||||
checkpoint?: Checkpoint;
|
||||
isBeforeCheckpoint?: boolean;
|
||||
reasoning?: Reasoning;
|
||||
}
|
||||
|
||||
export interface LLMFullCompletionOptions extends BaseCompletionOptions {
|
||||
|
|
@ -460,6 +476,7 @@ export interface LLMOptions {
|
|||
writeLog?: (str: string) => Promise<void>;
|
||||
llmRequestHook?: (model: string, prompt: string) => any;
|
||||
apiKey?: string;
|
||||
apiKeyLocation?: string;
|
||||
aiGatewaySlug?: string;
|
||||
apiBase?: string;
|
||||
cacheBehavior?: CacheBehavior;
|
||||
|
|
@ -582,8 +599,8 @@ export interface IdeSettings {
|
|||
remoteConfigSyncPeriod: number;
|
||||
userToken: string;
|
||||
enableControlServerBeta: boolean;
|
||||
continueTestEnvironment: "none" | "production" | "test" | "local";
|
||||
pauseCodebaseIndexOnStart: boolean;
|
||||
enableDebugLogs: boolean;
|
||||
}
|
||||
|
||||
export interface FileStats {
|
||||
|
|
@ -683,6 +700,11 @@ export interface IDE {
|
|||
|
||||
getGitHubAuthToken(args: GetGhTokenArgs): Promise<string | undefined>;
|
||||
|
||||
// Secret Storage
|
||||
readSecrets(keys: string[]): Promise<Record<string, string>>;
|
||||
|
||||
writeSecrets(secrets: { [key: string]: string }): Promise<void>;
|
||||
|
||||
// LSP
|
||||
gotoDefinition(location: Location): Promise<RangeInFile[]>;
|
||||
|
||||
|
|
@ -820,7 +842,7 @@ export interface SlashCommandDescription {
|
|||
export interface CustomCommand {
|
||||
name: string;
|
||||
prompt: string;
|
||||
description: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
export interface Prediction {
|
||||
|
|
@ -854,6 +876,13 @@ export interface Tool {
|
|||
uri?: string;
|
||||
}
|
||||
|
||||
interface ToolChoice {
|
||||
type: "function";
|
||||
function: {
|
||||
name: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface BaseCompletionOptions {
|
||||
temperature?: number;
|
||||
topP?: number;
|
||||
|
|
@ -871,6 +900,7 @@ export interface BaseCompletionOptions {
|
|||
stream?: boolean;
|
||||
prediction?: Prediction;
|
||||
tools?: Tool[];
|
||||
toolChoice?: ToolChoice;
|
||||
}
|
||||
|
||||
export interface ModelCapability {
|
||||
|
|
@ -882,6 +912,7 @@ export interface ModelDescription {
|
|||
provider: string;
|
||||
model: string;
|
||||
apiKey?: string;
|
||||
apiKeyLocation?: string;
|
||||
apiBase?: string;
|
||||
contextLength?: number;
|
||||
maxStopWords?: number;
|
||||
|
|
@ -925,7 +956,6 @@ export interface RerankerDescription {
|
|||
|
||||
export interface TabAutocompleteOptions {
|
||||
disable: boolean;
|
||||
useFileSuffix: boolean;
|
||||
maxPromptTokens: number;
|
||||
debounceDelay: number;
|
||||
maxSuffixPercentage: number;
|
||||
|
|
@ -971,7 +1001,6 @@ export interface ContinueUIConfig {
|
|||
fontSize?: number;
|
||||
displayRawMarkdown?: boolean;
|
||||
showChatScrollbar?: boolean;
|
||||
getChatTitles?: boolean;
|
||||
codeWrap?: boolean;
|
||||
}
|
||||
|
||||
|
|
@ -1198,6 +1227,8 @@ export interface BrowserSerializedContinueConfig {
|
|||
analytics?: AnalyticsConfig;
|
||||
docs?: SiteIndexingConfig[];
|
||||
tools: Tool[];
|
||||
usePlatform: boolean;
|
||||
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
|
||||
}
|
||||
|
||||
// DOCS SUGGESTIONS AND PACKAGE INFO
|
||||
|
|
@ -1235,9 +1266,9 @@ export type PackageDocsResult = {
|
|||
} & (
|
||||
| { error: string; details?: never }
|
||||
| { details: PackageDetailsSuccess; error?: never }
|
||||
);
|
||||
);
|
||||
|
||||
export interface TerminalOptions {
|
||||
reuseTerminal?: boolean,
|
||||
terminalName?: string,
|
||||
reuseTerminal?: boolean;
|
||||
terminalName?: string;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,12 +14,12 @@ import {
|
|||
} from "../test/testDir.js";
|
||||
import { getIndexSqlitePath } from "../util/paths.js";
|
||||
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { CodebaseIndexer, PauseToken } from "./CodebaseIndexer.js";
|
||||
import { getComputeDeleteAddRemove } from "./refreshIndex.js";
|
||||
import { TestCodebaseIndex } from "./TestCodebaseIndex.js";
|
||||
import { CodebaseIndex } from "./types.js";
|
||||
import { walkDir } from "./walkDir.js";
|
||||
import { localPathToUri } from "../util/pathToUri.js";
|
||||
|
||||
jest.useFakeTimers();
|
||||
|
||||
|
|
@ -159,7 +159,7 @@ describe("CodebaseIndexer", () => {
|
|||
|
||||
test("should have created index folder with all necessary files", async () => {
|
||||
const exists = await testIde.fileExists(
|
||||
pathToFileURL(getIndexSqlitePath()).toString(),
|
||||
localPathToUri(getIndexSqlitePath()),
|
||||
);
|
||||
expect(exists).toBe(true);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,142 +0,0 @@
|
|||
import os from "os";
|
||||
|
||||
import { jest } from "@jest/globals";
|
||||
|
||||
import { ContinueConfig } from "../..";
|
||||
import { testConfigHandler } from "../../test/fixtures";
|
||||
import FileSystemIde from "../../util/filesystem";
|
||||
|
||||
import DocsCrawler, { ChromiumInstaller, type PageData } from "./DocsCrawler";
|
||||
import preIndexedDocs from "./preIndexedDocs";
|
||||
|
||||
// Temporary workaround until we have better caching of Chromium
|
||||
// download between test runs
|
||||
const TIMEOUT_MS = 1_000_000_000;
|
||||
|
||||
// Overwrite the Chromium download path to `os.tmpdir()`
|
||||
// so that we don't delete the Chromium install between tests
|
||||
ChromiumInstaller.PCR_CONFIG = { downloadPath: os.tmpdir() };
|
||||
|
||||
// Skipped until we have a better way to cache Chromium installs
|
||||
// between tests and in CI
|
||||
describe.skip("DocsCrawler", () => {
|
||||
const NUM_PAGES_TO_CRAWL = 5;
|
||||
|
||||
let config: ContinueConfig;
|
||||
let mockIde: FileSystemIde;
|
||||
let chromiumInstaller;
|
||||
let docsCrawler: DocsCrawler;
|
||||
|
||||
beforeAll(async () => {
|
||||
const result = await testConfigHandler.loadConfig();
|
||||
config = result.config!;
|
||||
mockIde = new FileSystemIde(process.cwd());
|
||||
chromiumInstaller = new ChromiumInstaller(mockIde, config);
|
||||
docsCrawler = new DocsCrawler(mockIde, config);
|
||||
|
||||
// Make sure we have Chromium pulled down before beginning tests
|
||||
await chromiumInstaller.install();
|
||||
}, TIMEOUT_MS);
|
||||
|
||||
function crawlTest(
|
||||
urls: string[],
|
||||
numPagesToCrawl: number = NUM_PAGES_TO_CRAWL,
|
||||
) {
|
||||
const numUrlsToTest = 5;
|
||||
const randomUrls = urls
|
||||
.sort(() => 0.5 - Math.random())
|
||||
.slice(0, numUrlsToTest);
|
||||
|
||||
randomUrls.forEach((url) => {
|
||||
it(
|
||||
`Crawl test for ${url}`,
|
||||
async () => {
|
||||
const crawlResults: PageData[] = [];
|
||||
|
||||
for await (const page of docsCrawler.crawl(
|
||||
new URL(url),
|
||||
NUM_PAGES_TO_CRAWL,
|
||||
)) {
|
||||
crawlResults.push(page);
|
||||
}
|
||||
|
||||
expect(crawlResults.length).toBeGreaterThanOrEqual(numPagesToCrawl);
|
||||
},
|
||||
TIMEOUT_MS,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
describe("GitHub Crawler", () => {
|
||||
const repoUrl =
|
||||
"https://github.com/Patrick-Erichsen/test-github-repo-for-crawling";
|
||||
|
||||
let crawlResults: PageData[];
|
||||
|
||||
beforeAll(async () => {
|
||||
crawlResults = [];
|
||||
|
||||
for await (const page of docsCrawler.crawl(new URL(repoUrl))) {
|
||||
crawlResults.push(page);
|
||||
}
|
||||
}, TIMEOUT_MS);
|
||||
|
||||
test("finds expected markdown files", async () => {
|
||||
expect(crawlResults.some((page) => page.path.endsWith("README.md"))).toBe(
|
||||
true,
|
||||
);
|
||||
|
||||
expect(
|
||||
crawlResults.some((page) => page.path.endsWith("docs-depth-1.md")),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test("html includes the correct content", async () => {
|
||||
const doc = crawlResults.find((page) =>
|
||||
page.path.endsWith("docs-depth-1.md"),
|
||||
);
|
||||
|
||||
expect(doc?.content.includes("Test body")).toBe(true);
|
||||
expect(doc?.content.includes("Test H2 Header")).toBe(true);
|
||||
});
|
||||
|
||||
test("ignores non-markdown files, e.g. `test.js` at the root", async () => {
|
||||
expect(crawlResults.some((page) => page.path.endsWith("test.js"))).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Chromium Crawler", () => {
|
||||
let shouldUseChromiumSpy: any;
|
||||
|
||||
beforeAll(() => {
|
||||
shouldUseChromiumSpy = jest
|
||||
.spyOn(docsCrawler as any, "shouldUseChromium")
|
||||
.mockReturnValue(true);
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
shouldUseChromiumSpy.mockRestore();
|
||||
});
|
||||
|
||||
describe("Pre-indexed Docs", () => {
|
||||
crawlTest(Object.keys(preIndexedDocs));
|
||||
});
|
||||
|
||||
describe("Running list of common sites", () => {
|
||||
crawlTest([
|
||||
"https://docs.nestjs.com/",
|
||||
"https://go.dev/doc/",
|
||||
"https://clickhouse.com/docs",
|
||||
"https://www.tensorflow.org/api_docs",
|
||||
// "https://www.rust-lang.org/learn", TODO: This is failing
|
||||
"https://docs.anthropic.com/en/docs",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Cheerio Crawler", () => {
|
||||
crawlTest(["https://amplified.dev/"], 1);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,100 +0,0 @@
|
|||
import { URL } from "node:url";
|
||||
|
||||
// @ts-ignore
|
||||
// @prettier-ignore
|
||||
import { ContinueConfig, IDE } from "../..";
|
||||
|
||||
import CheerioCrawler from "./crawlers/CheerioCrawler";
|
||||
import { ChromiumCrawler, ChromiumInstaller } from "./crawlers/ChromiumCrawler";
|
||||
import { DefaultCrawler } from "./crawlers/DefaultCrawler";
|
||||
import GitHubCrawler from "./crawlers/GitHubCrawler";
|
||||
|
||||
export type PageData = {
|
||||
url: string;
|
||||
path: string;
|
||||
content: string;
|
||||
};
|
||||
|
||||
class DocsCrawler {
|
||||
private readonly MAX_REQUESTS_PER_CRAWL = 1000;
|
||||
private readonly GITHUB_HOST = "github.com";
|
||||
private readonly chromiumInstaller: ChromiumInstaller;
|
||||
|
||||
constructor(
|
||||
private readonly ide: IDE,
|
||||
private readonly config: ContinueConfig,
|
||||
) {
|
||||
this.chromiumInstaller = new ChromiumInstaller(this.ide, this.config);
|
||||
}
|
||||
|
||||
private shouldUseChromium() {
|
||||
return (
|
||||
this.config.experimental?.useChromiumForDocsCrawling &&
|
||||
this.chromiumInstaller.isInstalled()
|
||||
);
|
||||
}
|
||||
|
||||
async *crawl(
|
||||
startUrl: URL,
|
||||
maxRequestsPerCrawl: number = this.MAX_REQUESTS_PER_CRAWL,
|
||||
): AsyncGenerator<PageData, undefined, undefined> {
|
||||
if (startUrl.host === this.GITHUB_HOST) {
|
||||
yield* new GitHubCrawler(startUrl).crawl();
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const pageData = await new DefaultCrawler(startUrl).crawl();
|
||||
if (pageData.length > 0) {
|
||||
yield* pageData;
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Default crawler failed, trying backup: ", e);
|
||||
}
|
||||
|
||||
if (this.shouldUseChromium()) {
|
||||
yield* new ChromiumCrawler(startUrl, maxRequestsPerCrawl).crawl();
|
||||
} else {
|
||||
let didCrawlSinglePage = false;
|
||||
|
||||
for await (const pageData of new CheerioCrawler(
|
||||
startUrl,
|
||||
maxRequestsPerCrawl,
|
||||
).crawl()) {
|
||||
yield pageData;
|
||||
didCrawlSinglePage = true;
|
||||
}
|
||||
|
||||
// We assume that if we failed to crawl a single page,
|
||||
// it was due to an error that using Chromium can resolve
|
||||
const shouldProposeUseChromium =
|
||||
!didCrawlSinglePage &&
|
||||
this.chromiumInstaller.shouldProposeUseChromiumOnCrawlFailure();
|
||||
|
||||
if (shouldProposeUseChromium) {
|
||||
const didInstall =
|
||||
await this.chromiumInstaller.proposeAndAttemptInstall(
|
||||
startUrl.toString(),
|
||||
);
|
||||
|
||||
if (didInstall) {
|
||||
void this.ide.showToast(
|
||||
"info",
|
||||
`Successfully installed Chromium! Retrying crawl of: ${startUrl.toString()}`,
|
||||
);
|
||||
|
||||
yield* new ChromiumCrawler(startUrl, maxRequestsPerCrawl).crawl();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default DocsCrawler;
|
||||
export {
|
||||
CheerioCrawler,
|
||||
ChromiumCrawler,
|
||||
ChromiumInstaller,
|
||||
GitHubCrawler,
|
||||
};
|
||||
|
|
@ -4,7 +4,6 @@
|
|||
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";
|
||||
|
||||
|
|
@ -37,17 +36,19 @@ describe.skip("DocsService Integration Tests", () => {
|
|||
beforeEach(async () => {
|
||||
ide = new FileSystemIde(process.cwd());
|
||||
|
||||
const ideSettingsPromise = Promise.resolve({
|
||||
remoteConfigSyncPeriod: 60,
|
||||
userToken: "",
|
||||
enableControlServerBeta: false,
|
||||
continueTestEnvironment: "none" as const,
|
||||
pauseCodebaseIndexOnStart: false,
|
||||
ideSettings: {} as any,
|
||||
enableDebugLogs: false,
|
||||
remoteConfigServerUrl: "",
|
||||
});
|
||||
configHandler = new ConfigHandler(
|
||||
ide,
|
||||
Promise.resolve({
|
||||
remoteConfigSyncPeriod: 60,
|
||||
userToken: "",
|
||||
enableControlServerBeta: false,
|
||||
pauseCodebaseIndexOnStart: false,
|
||||
ideSettings: {} as any,
|
||||
enableDebugLogs: false,
|
||||
remoteConfigServerUrl: "",
|
||||
}),
|
||||
ideSettingsPromise,
|
||||
async () => {},
|
||||
new ControlPlaneClient(
|
||||
Promise.resolve({
|
||||
|
|
@ -57,6 +58,7 @@ describe.skip("DocsService Integration Tests", () => {
|
|||
label: "",
|
||||
},
|
||||
}),
|
||||
ideSettingsPromise,
|
||||
),
|
||||
);
|
||||
|
||||
|
|
@ -105,28 +107,28 @@ describe.skip("DocsService Integration Tests", () => {
|
|||
expect(retrievedChunks.length).toBe(0);
|
||||
});
|
||||
|
||||
test("Reindexes when changing embeddings provider", async () => {
|
||||
const originalEmbeddingsProvider =
|
||||
await docsService.getEmbeddingsProvider();
|
||||
// test("Reindexes when changing embeddings provider", async () => {
|
||||
// const originalEmbeddingsProvider =
|
||||
// await docsService.getEmbeddingsProvider();
|
||||
|
||||
// Change embeddings provider
|
||||
editConfigJson((config) => ({
|
||||
...config,
|
||||
embeddingsProvider: {
|
||||
provider: FreeTrial.providerName,
|
||||
},
|
||||
}));
|
||||
// // Change embeddings provider
|
||||
// editConfigJson((config) => ({
|
||||
// ...config,
|
||||
// embeddingsProvider: {
|
||||
// provider: FreeTrial.providerName,
|
||||
// },
|
||||
// }));
|
||||
|
||||
await getReloadedConfig();
|
||||
// await getReloadedConfig();
|
||||
|
||||
const newEmbeddingsProvider = await docsService.getEmbeddingsProvider();
|
||||
// const { provider, isPreindexed} = await docsService.getEmbeddingsProvider();
|
||||
|
||||
// Verify reindexing
|
||||
const [originalVector] = await originalEmbeddingsProvider.embed(["test"]);
|
||||
const [newMockVector] = await newEmbeddingsProvider.embed(["test"]);
|
||||
// // Verify reindexing
|
||||
// const [originalVector] = await originalEmbeddingsProvider.embed(["test"]);
|
||||
// const [newMockVector] = await provider.embed(["test"]);
|
||||
|
||||
expect(originalVector).not.toEqual(newMockVector);
|
||||
});
|
||||
// expect(originalVector).not.toEqual(newMockVector);
|
||||
// });
|
||||
|
||||
test("Handles pulling down and adding pre-indexed docs", async () => {
|
||||
const preIndexedDoc = Object.values(preIndexedDocs)[0];
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import lancedb, { Connection } from "vectordb";
|
|||
import {
|
||||
Chunk,
|
||||
ContinueConfig,
|
||||
DocsIndexingDetails,
|
||||
IDE,
|
||||
IdeInfo,
|
||||
ILLM,
|
||||
|
|
@ -25,9 +26,12 @@ import {
|
|||
} from "../../util/paths";
|
||||
import { Telemetry } from "../../util/posthog";
|
||||
|
||||
import { ConfigResult } from "../../config/load";
|
||||
import { Article, chunkArticle, pageToArticle } from "./article";
|
||||
import DocsCrawler from "./DocsCrawler";
|
||||
import {
|
||||
ArticleWithChunks,
|
||||
htmlPageToArticleWithChunks,
|
||||
markdownPageToArticleWithChunks,
|
||||
} from "./article";
|
||||
import DocsCrawler, { DocsCrawlerType, PageData } from "./crawlers/DocsCrawler";
|
||||
import { runLanceMigrations, runSqliteMigrations } from "./migrations";
|
||||
import {
|
||||
downloadFromS3,
|
||||
|
|
@ -36,6 +40,7 @@ import {
|
|||
SiteIndexingResults,
|
||||
} from "./preIndexed";
|
||||
import preIndexedDocs from "./preIndexedDocs";
|
||||
import { ConfigResult } from "@continuedev/config-yaml";
|
||||
|
||||
// Purposefully lowercase because lancedb converts
|
||||
export interface LanceDbDocsRow {
|
||||
|
|
@ -73,8 +78,6 @@ export type AddParams = {
|
|||
- delete
|
||||
- reindex all
|
||||
- add/index one
|
||||
- Currently a full reindex deletes all docs rather than storing PER embeddings provider
|
||||
- The last successful embeddings provider is stored in global context and updated AFTER an indexing process is successful
|
||||
*/
|
||||
export default class DocsService {
|
||||
static lanceTableName = "docs";
|
||||
|
|
@ -92,8 +95,8 @@ export default class DocsService {
|
|||
private config!: ContinueConfig;
|
||||
private sqliteDb?: Database;
|
||||
|
||||
private docsCrawler!: DocsCrawler;
|
||||
private ideInfoPromise: Promise<IdeInfo>;
|
||||
private githubToken?: string;
|
||||
|
||||
constructor(
|
||||
configHandler: ConfigHandler,
|
||||
|
|
@ -104,6 +107,10 @@ export default class DocsService {
|
|||
this.isInitialized = this.init(configHandler);
|
||||
}
|
||||
|
||||
setGithubToken(token: string) {
|
||||
this.githubToken = token;
|
||||
}
|
||||
|
||||
// Singleton pattern: only one service globally
|
||||
private static instance?: DocsService;
|
||||
static createSingleton(
|
||||
|
|
@ -196,6 +203,7 @@ export default class DocsService {
|
|||
}
|
||||
}
|
||||
|
||||
// Used to check periodically during indexing if should cancel indexing
|
||||
shouldCancel(startUrl: string, startedWithEmbedder: string) {
|
||||
// Check if aborted
|
||||
const isAborted = this.statuses.get(startUrl)?.status === "aborted";
|
||||
|
|
@ -215,21 +223,6 @@ export default class DocsService {
|
|||
return false;
|
||||
}
|
||||
|
||||
// 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",
|
||||
// });
|
||||
// }
|
||||
// }
|
||||
|
||||
// isPaused(startUrl: string) {
|
||||
// return this.statuses.get(startUrl)?.status === "paused";
|
||||
// }
|
||||
|
||||
/*
|
||||
* Currently, we generate and host embeddings for pre-indexed docs using transformers.
|
||||
* However, we don't ship transformers with the JetBrains extension.
|
||||
|
|
@ -251,14 +244,29 @@ export default class DocsService {
|
|||
return isPreIndexedDocsProvider && !canUsePreindexedDocs;
|
||||
}
|
||||
|
||||
async getEmbeddingsProvider(isPreIndexedDoc: boolean = false): Promise<ILLM> {
|
||||
const canUsePreindexedDocs = await this.canUsePreindexedDocs();
|
||||
// Determines if using preIndexed and returns proper embeddings provider
|
||||
async getEmbeddingsProvider(startUrl: string) {
|
||||
// Conditions for using a pre-indexed doc
|
||||
|
||||
if (canUsePreindexedDocs && isPreIndexedDoc) {
|
||||
return DocsService.preIndexedDocsEmbeddingsProvider;
|
||||
// Must be in pre indexed docs file
|
||||
const preIndexedDoc = preIndexedDocs[startUrl];
|
||||
if (preIndexedDoc) {
|
||||
// Most not be overriden by config
|
||||
if (!this.config?.docs?.find((doc) => doc.startUrl === startUrl)) {
|
||||
// Must be supported
|
||||
const canUsePreindexedDocs = await this.canUsePreindexedDocs();
|
||||
if (canUsePreindexedDocs) {
|
||||
return {
|
||||
provider: DocsService.preIndexedDocsEmbeddingsProvider,
|
||||
isPreindexed: true,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return this.config.embeddingsProvider;
|
||||
return {
|
||||
provider: this.config.embeddingsProvider,
|
||||
isPreindexed: false,
|
||||
};
|
||||
}
|
||||
|
||||
private async handleConfigUpdate({
|
||||
|
|
@ -268,8 +276,6 @@ export default class DocsService {
|
|||
const oldConfig = this.config;
|
||||
this.config = newConfig; // IMPORTANT - need to set up top, other methods below use this without passing it in
|
||||
|
||||
this.docsCrawler = new DocsCrawler(this.ide, newConfig);
|
||||
|
||||
if (this.config.disableIndexing) {
|
||||
return;
|
||||
}
|
||||
|
|
@ -322,7 +328,7 @@ export default class DocsService {
|
|||
}
|
||||
|
||||
// Returns true if startUrl has been indexed with current embeddingsProvider
|
||||
async hasMetadata(startUrl: string): Promise<Promise<boolean>> {
|
||||
async hasMetadata(startUrl: string): Promise<boolean> {
|
||||
const db = await this.getOrCreateSqliteDb();
|
||||
const title = await db.get(
|
||||
`SELECT title FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`,
|
||||
|
|
@ -365,16 +371,13 @@ export default class DocsService {
|
|||
console.warn("Attempting to add/index docs when indexing is disabled");
|
||||
return;
|
||||
}
|
||||
const { startUrl } = siteIndexingConfig;
|
||||
const { startUrl, useLocalCrawling, maxDepth } = siteIndexingConfig;
|
||||
|
||||
const canUsePreindexedDocs = await this.canUsePreindexedDocs();
|
||||
if (canUsePreindexedDocs) {
|
||||
const preIndexedDoc = preIndexedDocs[startUrl];
|
||||
const isPreIndexedDoc = !!preIndexedDoc;
|
||||
if (isPreIndexedDoc) {
|
||||
console.warn("Can not override pre-indexed start urls");
|
||||
return;
|
||||
}
|
||||
const { isPreindexed, provider } =
|
||||
await this.getEmbeddingsProvider(startUrl);
|
||||
if (isPreindexed) {
|
||||
console.warn("Attempted to indexAndAdd pre-indexed doc");
|
||||
return;
|
||||
}
|
||||
|
||||
// Queue - indexAndAdd is invoked circularly by config edits. This prevents duplicate runs
|
||||
|
|
@ -382,8 +385,7 @@ export default class DocsService {
|
|||
return;
|
||||
}
|
||||
|
||||
const embeddingsProvider = await this.getEmbeddingsProvider();
|
||||
const startedWithEmbedder = this.config.embeddingsProvider.embeddingId;
|
||||
const startedWithEmbedder = provider.embeddingId;
|
||||
const indexExists = await this.hasMetadata(startUrl);
|
||||
|
||||
// Build status update - most of it is fixed values
|
||||
|
|
@ -393,7 +395,7 @@ export default class DocsService {
|
|||
> = {
|
||||
type: "docs",
|
||||
id: siteIndexingConfig.startUrl,
|
||||
embeddingsProviderId: embeddingsProvider.embeddingId,
|
||||
embeddingsProviderId: provider.embeddingId,
|
||||
isReindexing: reIndex && indexExists,
|
||||
title: siteIndexingConfig.title,
|
||||
debugInfo: `max depth: ${siteIndexingConfig.maxDepth}`,
|
||||
|
|
@ -429,47 +431,81 @@ export default class DocsService {
|
|||
progress: 0,
|
||||
});
|
||||
|
||||
const articles: Article[] = [];
|
||||
// Crawl pages to get page data
|
||||
const pages: PageData[] = [];
|
||||
let processedPages = 0;
|
||||
let estimatedProgress = 0;
|
||||
let done = false;
|
||||
let usedCrawler: DocsCrawlerType | undefined = undefined;
|
||||
|
||||
// Crawl pages and retrieve info as articles
|
||||
for await (const page of this.docsCrawler.crawl(new URL(startUrl))) {
|
||||
estimatedProgress += 1 / 2 ** (processedPages + 1);
|
||||
const docsCrawler = new DocsCrawler(
|
||||
this.ide,
|
||||
this.config,
|
||||
maxDepth,
|
||||
undefined,
|
||||
useLocalCrawling,
|
||||
this.githubToken,
|
||||
);
|
||||
const crawlerGen = docsCrawler.crawl(new URL(startUrl));
|
||||
|
||||
// NOTE - during "indexing" phase, check if aborted before each status update
|
||||
if (this.shouldCancel(startUrl, startedWithEmbedder)) {
|
||||
return;
|
||||
while (!done) {
|
||||
const result = await crawlerGen.next();
|
||||
if (result.done) {
|
||||
done = true;
|
||||
usedCrawler = result.value;
|
||||
} else {
|
||||
const page = result.value;
|
||||
estimatedProgress += 1 / 2 ** (processedPages + 1);
|
||||
|
||||
// NOTE - during "indexing" phase, check if aborted before each status update
|
||||
if (this.shouldCancel(startUrl, startedWithEmbedder)) {
|
||||
return;
|
||||
}
|
||||
this.handleStatusUpdate({
|
||||
...fixedStatus,
|
||||
description: `Finding subpages (${page.path})`,
|
||||
status: "indexing",
|
||||
progress:
|
||||
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
|
||||
});
|
||||
|
||||
pages.push(page);
|
||||
|
||||
processedPages++;
|
||||
|
||||
// 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));
|
||||
}
|
||||
this.handleStatusUpdate({
|
||||
...fixedStatus,
|
||||
description: `Finding subpages (${page.path})`,
|
||||
status: "indexing",
|
||||
progress:
|
||||
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);
|
||||
if (!article) {
|
||||
continue;
|
||||
}
|
||||
articles.push(article);
|
||||
|
||||
processedPages++;
|
||||
|
||||
// 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", {
|
||||
count: processedPages,
|
||||
});
|
||||
|
||||
// Chunk pages based on which crawler was used
|
||||
const articles: ArticleWithChunks[] = [];
|
||||
const chunks: Chunk[] = [];
|
||||
const articleChunker =
|
||||
usedCrawler === "github"
|
||||
? markdownPageToArticleWithChunks
|
||||
: htmlPageToArticleWithChunks;
|
||||
for (const page of pages) {
|
||||
const articleWithChunks = await articleChunker(
|
||||
page,
|
||||
provider.maxEmbeddingChunkSize,
|
||||
);
|
||||
if (articleWithChunks) {
|
||||
articles.push(articleWithChunks);
|
||||
}
|
||||
const toWait = 20 * this.docsIndexingQueue.size + 10;
|
||||
await new Promise((resolve) => setTimeout(resolve, toWait));
|
||||
}
|
||||
|
||||
// const chunks: Chunk[] = [];
|
||||
const embeddings: number[][] = [];
|
||||
|
||||
// Create embeddings of retrieved articles
|
||||
|
|
@ -482,35 +518,26 @@ export default class DocsService {
|
|||
this.handleStatusUpdate({
|
||||
...fixedStatus,
|
||||
status: "indexing",
|
||||
description: `Creating Embeddings: ${article.subpath}`,
|
||||
description: `Creating Embeddings: ${article.article.subpath}`,
|
||||
progress: 0.5 + 0.3 * (i / articles.length), // 50% -> 80%
|
||||
});
|
||||
|
||||
try {
|
||||
const chunkedArticle = chunkArticle(
|
||||
article,
|
||||
embeddingsProvider.maxEmbeddingChunkSize,
|
||||
const subpathEmbeddings = await provider.embed(
|
||||
article.chunks.map((c) => c.content),
|
||||
);
|
||||
|
||||
const chunkedArticleContents = chunkedArticle.map(
|
||||
(chunk) => chunk.content,
|
||||
);
|
||||
|
||||
chunks.push(...chunkedArticle);
|
||||
|
||||
const subpathEmbeddings = await embeddingsProvider.embed(
|
||||
chunkedArticleContents,
|
||||
);
|
||||
|
||||
chunks.push(...article.chunks);
|
||||
embeddings.push(...subpathEmbeddings);
|
||||
const toWait = 100 * this.docsIndexingQueue.size + 50;
|
||||
await new Promise((resolve) => setTimeout(resolve, toWait));
|
||||
} catch (e) {
|
||||
console.warn("Error chunking article: ", e);
|
||||
console.warn("Error embedding article chunks: ", e);
|
||||
}
|
||||
}
|
||||
|
||||
if (embeddings.length === 0) {
|
||||
console.error(
|
||||
`No embeddings were created for site: ${siteIndexingConfig.startUrl}\n Num chunks: ${chunks.length}`,
|
||||
`No embeddings were created for site: ${startUrl}\n Num chunks: ${chunks.length}`,
|
||||
);
|
||||
|
||||
if (this.shouldCancel(startUrl, startedWithEmbedder)) {
|
||||
|
|
@ -518,7 +545,7 @@ export default class DocsService {
|
|||
}
|
||||
this.handleStatusUpdate({
|
||||
...fixedStatus,
|
||||
description: `No embeddings were created for site: ${siteIndexingConfig.startUrl}`,
|
||||
description: `No embeddings were created for site: ${startUrl}`,
|
||||
status: "failed",
|
||||
progress: 1,
|
||||
});
|
||||
|
|
@ -584,10 +611,19 @@ export default class DocsService {
|
|||
providers: ["docs"],
|
||||
});
|
||||
} catch (e) {
|
||||
let description = `Error getting docs from: ${siteIndexingConfig.startUrl}`;
|
||||
if (e instanceof Error) {
|
||||
if (
|
||||
e.message.includes("github.com") &&
|
||||
e.message.includes("rate limit")
|
||||
) {
|
||||
description = "Github rate limit exceeded";
|
||||
}
|
||||
}
|
||||
console.error("Error indexing docs", e);
|
||||
this.handleStatusUpdate({
|
||||
...fixedStatus,
|
||||
description: `Error getting docs from: ${siteIndexingConfig.startUrl}`,
|
||||
description,
|
||||
status: "failed",
|
||||
progress: 1,
|
||||
});
|
||||
|
|
@ -600,11 +636,12 @@ export default class DocsService {
|
|||
// And pre-indexed embeddings are supported
|
||||
// Fetch pre-indexed embeddings from S3, add to Lance, and then search those
|
||||
private async fetchAndAddPreIndexedDocEmbeddings(title: string) {
|
||||
const embeddingsProvider = await this.getEmbeddingsProvider(true);
|
||||
|
||||
const data = await downloadFromS3(
|
||||
S3Buckets.continueIndexedDocs,
|
||||
getS3Filename(embeddingsProvider.embeddingId, title),
|
||||
getS3Filename(
|
||||
DocsService.preIndexedDocsEmbeddingsProvider.embeddingId,
|
||||
title,
|
||||
),
|
||||
);
|
||||
|
||||
const siteEmbeddings = JSON.parse(data) as SiteIndexingResults;
|
||||
|
|
@ -645,36 +682,91 @@ export default class DocsService {
|
|||
return [];
|
||||
}
|
||||
|
||||
const preIndexedDoc = preIndexedDocs[startUrl];
|
||||
if (!!preIndexedDoc) {
|
||||
const { isPreindexed, provider } =
|
||||
await this.getEmbeddingsProvider(startUrl);
|
||||
|
||||
if (isPreindexed) {
|
||||
void Telemetry.capture("docs_pre_indexed_doc_used", {
|
||||
doc: preIndexedDoc["title"],
|
||||
doc: preIndexedDocs[startUrl]!["title"],
|
||||
});
|
||||
}
|
||||
|
||||
const embeddingsProvider =
|
||||
await this.getEmbeddingsProvider(!!preIndexedDoc);
|
||||
const [vector] = await provider.embed([query]);
|
||||
|
||||
const [vector] = await embeddingsProvider.embed([query]);
|
||||
|
||||
return await this.retrieveChunks(startUrl, vector, nRetrieve);
|
||||
return await this.retrieveChunks(startUrl, vector, nRetrieve, isPreindexed);
|
||||
}
|
||||
|
||||
private lanceDBRowToChunk(row: LanceDbDocsRow): Chunk {
|
||||
return {
|
||||
digest: row.path,
|
||||
filepath: row.path,
|
||||
startLine: row.startline,
|
||||
endLine: row.endline,
|
||||
index: 0,
|
||||
content: row.content,
|
||||
otherMetadata: {
|
||||
title: row.title,
|
||||
},
|
||||
};
|
||||
}
|
||||
async getDetails(startUrl: string): Promise<DocsIndexingDetails> {
|
||||
const db = await this.getOrCreateSqliteDb();
|
||||
|
||||
try {
|
||||
const { isPreindexed, provider } =
|
||||
await this.getEmbeddingsProvider(startUrl);
|
||||
const preIndexedDoc = preIndexedDocs[startUrl];
|
||||
const isPreIndexedDoc = !!preIndexedDoc;
|
||||
|
||||
const result = await db.get(
|
||||
`SELECT startUrl, title, favicon FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`,
|
||||
startUrl,
|
||||
provider.embeddingId,
|
||||
);
|
||||
|
||||
if (!result) {
|
||||
throw new Error(`${startUrl} not found in sqlite`);
|
||||
}
|
||||
const siteIndexingConfig: SiteIndexingConfig = {
|
||||
startUrl,
|
||||
faviconUrl: result.favicon,
|
||||
title: result.title,
|
||||
};
|
||||
|
||||
const table = await this.getOrCreateLanceTable({
|
||||
initializationVector: [],
|
||||
startUrl,
|
||||
});
|
||||
const rows = (await table
|
||||
.filter(`starturl = '${startUrl}'`)
|
||||
.limit(1000)
|
||||
.execute()) as LanceDbDocsRow[];
|
||||
|
||||
return {
|
||||
startUrl,
|
||||
config: siteIndexingConfig,
|
||||
indexingStatus: this.statuses.get(startUrl),
|
||||
chunks: rows.map(this.lanceDBRowToChunk),
|
||||
isPreIndexedDoc,
|
||||
};
|
||||
} catch (e) {
|
||||
console.warn("Error getting details", e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
// This is split into its own function so that it can be recursive
|
||||
// in the case of fetching preindexed docs from s3
|
||||
async retrieveChunks(
|
||||
startUrl: string,
|
||||
vector: number[],
|
||||
nRetrieve: number,
|
||||
isPreindexed: boolean,
|
||||
isRetry: boolean = false,
|
||||
): Promise<Chunk[]> {
|
||||
const preIndexedDoc = preIndexedDocs[startUrl];
|
||||
const isPreIndexedDoc = !!preIndexedDoc;
|
||||
|
||||
// Lance doesn't have an embeddingsprovider column, instead it includes it in the table name
|
||||
const table = await this.getOrCreateLanceTable({
|
||||
initializationVector: vector,
|
||||
isPreIndexedDoc,
|
||||
startUrl,
|
||||
});
|
||||
|
||||
let docs: LanceDbDocsRow[] = [];
|
||||
|
|
@ -689,31 +781,17 @@ export default class DocsService {
|
|||
}
|
||||
|
||||
// No docs are found for preindexed? try fetching once
|
||||
if (docs.length === 0 && isPreIndexedDoc) {
|
||||
if (docs.length === 0 && isPreindexed) {
|
||||
if (isRetry) {
|
||||
return [];
|
||||
}
|
||||
await this.fetchAndAddPreIndexedDocEmbeddings(preIndexedDoc.title);
|
||||
return await this.retrieveChunks(startUrl, vector, nRetrieve, true);
|
||||
await this.fetchAndAddPreIndexedDocEmbeddings(
|
||||
preIndexedDocs[startUrl]!["title"],
|
||||
);
|
||||
return await this.retrieveChunks(startUrl, vector, nRetrieve, true, true);
|
||||
}
|
||||
|
||||
if (isPreIndexedDoc) {
|
||||
void Telemetry.capture("docs_pre_indexed_doc_used", {
|
||||
doc: preIndexedDoc["title"],
|
||||
});
|
||||
}
|
||||
|
||||
return docs.map((doc) => ({
|
||||
digest: doc.path,
|
||||
filepath: doc.path,
|
||||
startLine: doc.startline,
|
||||
endLine: doc.endline,
|
||||
index: 0,
|
||||
content: doc.content,
|
||||
otherMetadata: {
|
||||
title: doc.title,
|
||||
},
|
||||
}));
|
||||
return docs.map(this.lanceDBRowToChunk);
|
||||
}
|
||||
|
||||
// SQLITE DB
|
||||
|
|
@ -769,7 +847,7 @@ export default class DocsService {
|
|||
private async syncDocs(
|
||||
oldConfig: ContinueConfig | undefined,
|
||||
newConfig: ContinueConfig,
|
||||
reindex: boolean,
|
||||
forceReindex: boolean,
|
||||
) {
|
||||
try {
|
||||
this.isSyncing = true;
|
||||
|
|
@ -802,33 +880,38 @@ export default class DocsService {
|
|||
const oldConfigDoc = oldConfigDocs.find(
|
||||
(d) => d.startUrl === doc.startUrl,
|
||||
);
|
||||
// const currentStatus = this.statuses.get(doc.startUrl);
|
||||
|
||||
if (
|
||||
// currentStatus?.status === "complete" &&
|
||||
oldConfigDoc &&
|
||||
(oldConfigDoc.maxDepth !== doc.maxDepth ||
|
||||
oldConfigDoc.title !== doc.title ||
|
||||
oldConfigDoc.faviconUrl !== doc.faviconUrl)
|
||||
!this.siteIndexingConfigsAreEqual(oldConfigDoc, doc)
|
||||
) {
|
||||
changedDocs.push(doc);
|
||||
} else {
|
||||
// if get's here, not changed, no update needed, mark as complete
|
||||
this.handleStatusUpdate({
|
||||
type: "docs",
|
||||
id: doc.startUrl,
|
||||
embeddingsProviderId: this.config.embeddingsProvider.embeddingId,
|
||||
isReindexing: false,
|
||||
title: doc.title,
|
||||
debugInfo: "Config sync: not changed",
|
||||
icon: doc.faviconUrl,
|
||||
url: doc.startUrl,
|
||||
progress: 1,
|
||||
description: "Complete",
|
||||
status: "complete",
|
||||
});
|
||||
if (forceReindex) {
|
||||
changedDocs.push(doc);
|
||||
} else {
|
||||
// if get's here, not changed, no update needed, mark as complete
|
||||
this.handleStatusUpdate({
|
||||
type: "docs",
|
||||
id: doc.startUrl,
|
||||
embeddingsProviderId:
|
||||
this.config.embeddingsProvider.embeddingId,
|
||||
isReindexing: false,
|
||||
title: doc.title,
|
||||
debugInfo: "Config sync: not changed",
|
||||
icon: doc.faviconUrl,
|
||||
url: doc.startUrl,
|
||||
progress: 1,
|
||||
description: "Complete",
|
||||
status: "complete",
|
||||
});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
newDocs.push(doc);
|
||||
const currentStatus = this.statuses.get(doc.startUrl);
|
||||
if (currentStatus?.status !== "failed") {
|
||||
newDocs.push(doc);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -892,10 +975,7 @@ export default class DocsService {
|
|||
return name.replace(/[^a-zA-Z0-9_.-]/g, "_");
|
||||
}
|
||||
|
||||
private async getLanceTableName(isPreIndexedDoc: boolean) {
|
||||
const embeddingsProvider =
|
||||
await this.getEmbeddingsProvider(isPreIndexedDoc);
|
||||
|
||||
private async getLanceTableName(embeddingsProvider: ILLM) {
|
||||
const tableName = this.sanitizeLanceTableName(
|
||||
`${DocsService.lanceTableName}${embeddingsProvider.embeddingId}`,
|
||||
);
|
||||
|
|
@ -905,15 +985,16 @@ export default class DocsService {
|
|||
|
||||
private async getOrCreateLanceTable({
|
||||
initializationVector,
|
||||
isPreIndexedDoc,
|
||||
startUrl,
|
||||
}: {
|
||||
initializationVector: number[];
|
||||
isPreIndexedDoc?: boolean;
|
||||
startUrl: string;
|
||||
}) {
|
||||
const conn = await lancedb.connect(getLanceDbPath());
|
||||
const tableNames = await conn.tableNames();
|
||||
const { provider } = await this.getEmbeddingsProvider(startUrl);
|
||||
const tableNameFromEmbeddingsProvider =
|
||||
await this.getLanceTableName(!!isPreIndexedDoc);
|
||||
await this.getLanceTableName(provider);
|
||||
|
||||
if (!tableNames.includes(tableNameFromEmbeddingsProvider)) {
|
||||
if (initializationVector) {
|
||||
|
|
@ -944,16 +1025,16 @@ export default class DocsService {
|
|||
embeddings,
|
||||
}: AddParams) {
|
||||
const sampleVector = embeddings[0];
|
||||
const isPreIndexedDoc = !!preIndexedDocs[siteIndexingConfig.startUrl];
|
||||
const { startUrl } = siteIndexingConfig;
|
||||
|
||||
const table = await this.getOrCreateLanceTable({
|
||||
isPreIndexedDoc,
|
||||
startUrl,
|
||||
initializationVector: sampleVector,
|
||||
});
|
||||
|
||||
const rows: LanceDbDocsRow[] = chunks.map((chunk, i) => ({
|
||||
vector: embeddings[i],
|
||||
starturl: siteIndexingConfig.startUrl,
|
||||
starturl: startUrl,
|
||||
title: chunk.otherMetadata?.title || siteIndexingConfig.title,
|
||||
content: chunk.content,
|
||||
path: chunk.filepath,
|
||||
|
|
@ -978,16 +1059,24 @@ export default class DocsService {
|
|||
);
|
||||
}
|
||||
|
||||
private siteIndexingConfigsAreEqual(
|
||||
config1: SiteIndexingConfig,
|
||||
config2: SiteIndexingConfig,
|
||||
) {
|
||||
return (
|
||||
config1.startUrl === config2.startUrl &&
|
||||
config1.faviconUrl === config2.faviconUrl &&
|
||||
config1.title === config2.title &&
|
||||
config1.maxDepth === config2.maxDepth &&
|
||||
config1.useLocalCrawling === config2.useLocalCrawling
|
||||
);
|
||||
}
|
||||
|
||||
private addToConfig(siteIndexingConfig: SiteIndexingConfig) {
|
||||
// Handles the case where a user has manually added the doc to config.json
|
||||
// so it already exists in the file
|
||||
const doesEquivalentDocExist = this.config.docs?.some(
|
||||
(doc) =>
|
||||
doc.startUrl === siteIndexingConfig.startUrl &&
|
||||
doc.faviconUrl === siteIndexingConfig.faviconUrl &&
|
||||
siteIndexingConfig.title === doc.title,
|
||||
// siteIndexingConfig.maxDepth === doc.maxDepth &&
|
||||
// doc.rootUrl === siteIndexingConfig.rootUrl,
|
||||
const doesEquivalentDocExist = this.config.docs?.some((doc) =>
|
||||
this.siteIndexingConfigsAreEqual(doc, siteIndexingConfig),
|
||||
);
|
||||
|
||||
if (!doesEquivalentDocExist) {
|
||||
|
|
@ -1045,7 +1134,7 @@ export default class DocsService {
|
|||
}
|
||||
}
|
||||
|
||||
async deleteIndexes(startUrl: string) {
|
||||
private async deleteIndexes(startUrl: string) {
|
||||
await this.deleteEmbeddingsFromLance(startUrl);
|
||||
await this.deleteMetadataFromSqlite(startUrl);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,9 +2,9 @@ import { Readability } from "@mozilla/readability";
|
|||
import { JSDOM } from "jsdom";
|
||||
|
||||
import { Chunk } from "../../";
|
||||
import { cleanFragment, cleanHeader } from "../chunk/markdown";
|
||||
import { cleanFragment, cleanHeader, markdownChunker } from "../chunk/markdown";
|
||||
|
||||
import { type PageData } from "./DocsCrawler";
|
||||
import { type PageData } from "./crawlers/DocsCrawler";
|
||||
|
||||
export type ArticleComponent = {
|
||||
title: string;
|
||||
|
|
@ -18,6 +18,11 @@ export type Article = {
|
|||
article_components: ArticleComponent[];
|
||||
};
|
||||
|
||||
export type ArticleWithChunks = {
|
||||
article: Article;
|
||||
chunks: Chunk[];
|
||||
};
|
||||
|
||||
function breakdownArticleComponent(
|
||||
url: string,
|
||||
article: ArticleComponent,
|
||||
|
|
@ -99,78 +104,100 @@ function breakdownArticleComponent(
|
|||
return chunks.filter((c) => c.content.trim().length > 20);
|
||||
}
|
||||
|
||||
export function chunkArticle(
|
||||
articleResult: Article,
|
||||
maxChunkSize: number,
|
||||
): Chunk[] {
|
||||
let chunks: Chunk[] = [];
|
||||
function chunkArticle(article: Article, maxChunkSize: number): Chunk[] {
|
||||
const chunks: Chunk[] = [];
|
||||
|
||||
for (const article of articleResult.article_components) {
|
||||
for (const component of article.article_components) {
|
||||
const articleChunks = breakdownArticleComponent(
|
||||
articleResult.url,
|
||||
article,
|
||||
articleResult.subpath,
|
||||
article.url,
|
||||
component,
|
||||
article.subpath,
|
||||
maxChunkSize,
|
||||
);
|
||||
chunks = [...chunks, ...articleChunks];
|
||||
chunks.push(...articleChunks);
|
||||
}
|
||||
|
||||
return chunks;
|
||||
}
|
||||
|
||||
function extractTitlesAndBodies(html: string): ArticleComponent[] {
|
||||
const dom = new JSDOM(html);
|
||||
const document = dom.window.document;
|
||||
|
||||
const titles = Array.from(document.querySelectorAll("h2"));
|
||||
const result = titles.map((titleElement) => {
|
||||
const title = titleElement.textContent || "";
|
||||
let body = "";
|
||||
let nextSibling = titleElement.nextElementSibling;
|
||||
|
||||
while (nextSibling && nextSibling.tagName !== "H2") {
|
||||
body += nextSibling.textContent || "";
|
||||
nextSibling = nextSibling.nextElementSibling;
|
||||
}
|
||||
|
||||
return { title, body };
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
export function stringToArticle(
|
||||
url: string,
|
||||
html: string,
|
||||
subpath: string,
|
||||
): Article | undefined {
|
||||
export async function htmlPageToArticleWithChunks(
|
||||
page: PageData,
|
||||
maxChunkSize: number,
|
||||
): Promise<ArticleWithChunks | undefined> {
|
||||
try {
|
||||
const html = page.content;
|
||||
const subpath = page.path;
|
||||
const url = page.url;
|
||||
|
||||
const dom = new JSDOM(html);
|
||||
const reader = new Readability(dom.window.document);
|
||||
const article = reader.parse();
|
||||
const readability = reader.parse();
|
||||
|
||||
if (!readability) {
|
||||
console.error("Docs indexing: Error getting readability for URL", url);
|
||||
|
||||
if (!article) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const article_components = extractTitlesAndBodies(article.content);
|
||||
const titles = Array.from(dom.window.document.querySelectorAll("h2"));
|
||||
const article_components = titles.map((titleElement) => {
|
||||
const title = titleElement.textContent || "";
|
||||
let body = "";
|
||||
let nextSibling = titleElement.nextElementSibling;
|
||||
|
||||
return {
|
||||
while (nextSibling && nextSibling.tagName !== "H2") {
|
||||
body += nextSibling.textContent || "";
|
||||
nextSibling = nextSibling.nextElementSibling;
|
||||
}
|
||||
|
||||
return { title, body };
|
||||
});
|
||||
|
||||
const article = {
|
||||
url,
|
||||
subpath,
|
||||
title: article.title,
|
||||
title: readability.title,
|
||||
article_components,
|
||||
};
|
||||
return {
|
||||
article,
|
||||
chunks: chunkArticle(article, maxChunkSize),
|
||||
};
|
||||
} catch (err) {
|
||||
console.error("Error converting URL to article components", err);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export function pageToArticle(page: PageData): Article | undefined {
|
||||
export async function markdownPageToArticleWithChunks(
|
||||
page: PageData,
|
||||
maxChunkSize: number,
|
||||
): Promise<ArticleWithChunks | undefined> {
|
||||
try {
|
||||
return stringToArticle(page.url, page.content, page.path);
|
||||
let index = 0;
|
||||
const chunks: Chunk[] = [];
|
||||
const chunker = markdownChunker(page.content, maxChunkSize, 1);
|
||||
for await (const chunk of chunker) {
|
||||
const fullUrl = new URL(page.url);
|
||||
fullUrl.hash = `#${cleanFragment(chunk.otherMetadata?.title)}`;
|
||||
|
||||
chunks.push({
|
||||
...chunk,
|
||||
index,
|
||||
filepath: fullUrl.toString(),
|
||||
digest: fullUrl.toString(),
|
||||
});
|
||||
index++;
|
||||
}
|
||||
return {
|
||||
article: {
|
||||
url: page.url,
|
||||
subpath: page.path,
|
||||
article_components: [], // TODO: markdown chunker just skips this for now since not used outside, only for html chunker
|
||||
title: chunks[0]?.otherMetadata?.title || page.path,
|
||||
},
|
||||
chunks,
|
||||
};
|
||||
} catch (err) {
|
||||
console.error("Error converting URL to article components", err);
|
||||
return undefined;
|
||||
console.error(`Docs indexing: failed to chunk markdown from ${page.url}`);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import { URL } from "node:url";
|
|||
|
||||
import * as cheerio from "cheerio";
|
||||
|
||||
import { PageData } from "../DocsCrawler";
|
||||
import { PageData } from "./DocsCrawler";
|
||||
|
||||
export default class CheerioCrawler {
|
||||
private readonly IGNORE_PATHS_ENDING_IN = [
|
||||
|
|
@ -21,23 +21,18 @@ export default class CheerioCrawler {
|
|||
constructor(
|
||||
private readonly startUrl: URL,
|
||||
private readonly maxRequestsPerCrawl: number,
|
||||
private readonly maxDepth: number,
|
||||
) {}
|
||||
|
||||
async *crawl(): AsyncGenerator<PageData> {
|
||||
yield* this.crawlPage(this.startUrl);
|
||||
}
|
||||
|
||||
private async *crawlPage(
|
||||
url: URL,
|
||||
maxDepth: number = 3,
|
||||
): AsyncGenerator<PageData> {
|
||||
let currentPageCount = 0;
|
||||
console.log(
|
||||
`[${
|
||||
(this.constructor as any).name
|
||||
}] Starting crawl from: ${url} - Max Depth: ${maxDepth}`,
|
||||
}] Starting crawl from: ${this.startUrl} - Max Depth: ${this.maxDepth}`,
|
||||
);
|
||||
|
||||
const { baseUrl, basePath } = this.splitUrl(url);
|
||||
const { baseUrl, basePath } = this.splitUrl(this.startUrl);
|
||||
|
||||
let paths: { path: string; depth: number }[] = [
|
||||
{ path: basePath, depth: 0 },
|
||||
|
|
@ -63,11 +58,16 @@ export default class CheerioCrawler {
|
|||
path,
|
||||
depth,
|
||||
} of results) {
|
||||
if (html !== "" && depth <= maxDepth) {
|
||||
yield { url: url.toString(), path, content: html };
|
||||
if (html !== "" && depth <= this.maxDepth) {
|
||||
yield { url: this.startUrl.toString(), path, content: html };
|
||||
currentPageCount++;
|
||||
if (currentPageCount >= this.maxRequestsPerCrawl) {
|
||||
console.log("Crawl completed - max requests reached");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (depth < maxDepth) {
|
||||
if (depth < this.maxDepth) {
|
||||
for (let link of linksArray) {
|
||||
if (!paths.some((p) => p.path === link)) {
|
||||
paths.push({ path: link, depth: depth + 1 });
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ import {
|
|||
getChromiumPath,
|
||||
getContinueUtilsPath,
|
||||
} from "../../../util/paths";
|
||||
import { PageData } from "../DocsCrawler";
|
||||
import { PageData } from "./DocsCrawler";
|
||||
|
||||
export class ChromiumCrawler {
|
||||
private readonly LINK_GROUP_SIZE = 2;
|
||||
|
|
@ -22,6 +22,7 @@ export class ChromiumCrawler {
|
|||
constructor(
|
||||
private readonly startUrl: URL,
|
||||
private readonly maxRequestsPerCrawl: number,
|
||||
private readonly maxDepth: number,
|
||||
) {}
|
||||
|
||||
static setUseChromiumForDocsCrawling(useChromiumForDocsCrawling: boolean) {
|
||||
|
|
@ -49,7 +50,7 @@ export class ChromiumCrawler {
|
|||
const page = await browser.newPage();
|
||||
|
||||
try {
|
||||
yield* this.crawlSitePages(page, this.startUrl);
|
||||
yield* this.crawlSitePages(page, this.startUrl, 0);
|
||||
} catch (e) {
|
||||
console.debug("Error getting links: ", e);
|
||||
console.debug(
|
||||
|
|
@ -97,6 +98,7 @@ export class ChromiumCrawler {
|
|||
private async *crawlSitePages(
|
||||
page: Page,
|
||||
curUrl: URL,
|
||||
depth: number,
|
||||
visitedLinks: Set<string> = new Set(),
|
||||
): AsyncGenerator<PageData> {
|
||||
const urlStr = curUrl.toString();
|
||||
|
|
@ -124,9 +126,17 @@ export class ChromiumCrawler {
|
|||
|
||||
for (const link of linkGroup) {
|
||||
enqueuedLinkCount++;
|
||||
console.log({ enqueuedLinkCount, url: this.startUrl.toString() });
|
||||
if (enqueuedLinkCount <= this.maxRequestsPerCrawl) {
|
||||
yield* this.crawlSitePages(page, new URL(link), visitedLinks);
|
||||
// console.log({ enqueuedLinkCount, url: this.startUrl.toString() });
|
||||
if (
|
||||
enqueuedLinkCount <= this.maxRequestsPerCrawl &&
|
||||
depth <= this.maxDepth
|
||||
) {
|
||||
yield* this.crawlSitePages(
|
||||
page,
|
||||
new URL(link),
|
||||
depth + 1,
|
||||
visitedLinks,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,10 +2,14 @@ import { URL } from "node:url";
|
|||
|
||||
import { getHeaders } from "../../../continueServer/stubs/headers";
|
||||
import { TRIAL_PROXY_URL } from "../../../control-plane/client";
|
||||
import { PageData } from "../DocsCrawler";
|
||||
import { PageData } from "./DocsCrawler";
|
||||
|
||||
export class DefaultCrawler {
|
||||
constructor(private readonly startUrl: URL) {}
|
||||
constructor(
|
||||
private readonly startUrl: URL,
|
||||
private readonly maxRequestsPerCrawl: number,
|
||||
private readonly maxDepth: number,
|
||||
) {}
|
||||
|
||||
async crawl(): Promise<PageData[]> {
|
||||
const resp = await fetch(new URL("crawl", TRIAL_PROXY_URL).toString(), {
|
||||
|
|
@ -14,7 +18,11 @@ export class DefaultCrawler {
|
|||
"Content-Type": "application/json",
|
||||
...(await getHeaders()),
|
||||
},
|
||||
body: JSON.stringify({ startUrl: this.startUrl.toString() }),
|
||||
body: JSON.stringify({
|
||||
startUrl: this.startUrl.toString(),
|
||||
maxDepth: this.maxDepth,
|
||||
limit: this.maxRequestsPerCrawl,
|
||||
}),
|
||||
});
|
||||
if (!resp.ok) {
|
||||
const text = await resp.text();
|
||||
|
|
|
|||
177
core/indexing/docs/crawlers/DocsCrawler.test.ts
Normal file
177
core/indexing/docs/crawlers/DocsCrawler.test.ts
Normal file
|
|
@ -0,0 +1,177 @@
|
|||
import os from "os";
|
||||
|
||||
import { ContinueConfig } from "../../..";
|
||||
import { testConfigHandler } from "../../../test/fixtures";
|
||||
import FileSystemIde from "../../../util/filesystem";
|
||||
|
||||
import DocsCrawler, {
|
||||
ChromiumInstaller,
|
||||
DocsCrawlerType,
|
||||
type PageData,
|
||||
} from "./DocsCrawler";
|
||||
import { commonDocsSites } from "./crawl-test-cases";
|
||||
|
||||
// Temporary workaround until we have better caching of Chromium
|
||||
// download between test runs
|
||||
const TIMEOUT_MS = 1_000_000_000;
|
||||
|
||||
// Overwrite the Chromium download path to `os.tmpdir()`
|
||||
// so that we don't delete the Chromium install between tests
|
||||
ChromiumInstaller.PCR_CONFIG = { downloadPath: os.tmpdir() };
|
||||
|
||||
describe("DocsCrawler", () => {
|
||||
let config: ContinueConfig;
|
||||
let mockIde: FileSystemIde;
|
||||
let chromiumInstaller: ChromiumInstaller;
|
||||
let docsCrawler: DocsCrawler;
|
||||
|
||||
beforeAll(async () => {
|
||||
const result = await testConfigHandler.loadConfig();
|
||||
config = result.config!;
|
||||
mockIde = new FileSystemIde(process.cwd());
|
||||
chromiumInstaller = new ChromiumInstaller(mockIde, config);
|
||||
docsCrawler = new DocsCrawler(mockIde, config);
|
||||
}, TIMEOUT_MS);
|
||||
|
||||
async function runCrawl(url: string) {
|
||||
const pages: PageData[] = [];
|
||||
const generator = docsCrawler.crawl(new URL(url));
|
||||
let done = false;
|
||||
let crawler: DocsCrawlerType = "default";
|
||||
while (!done) {
|
||||
const result = await generator.next();
|
||||
if (result.done) {
|
||||
done = true;
|
||||
crawler = result.value;
|
||||
} else {
|
||||
pages.push(result.value);
|
||||
}
|
||||
}
|
||||
return {
|
||||
pages,
|
||||
crawler,
|
||||
};
|
||||
}
|
||||
|
||||
describe("GitHub Crawler", () => {
|
||||
const repoUrl =
|
||||
"https://github.com/Patrick-Erichsen/test-github-repo-for-crawling";
|
||||
|
||||
let crawlResults: PageData[];
|
||||
let crawlerUsed: DocsCrawlerType;
|
||||
|
||||
beforeAll(async () => {
|
||||
docsCrawler = new DocsCrawler(mockIde, config, 5, 5, false);
|
||||
const { pages, crawler } = await runCrawl(repoUrl);
|
||||
crawlerUsed = crawler;
|
||||
crawlResults = pages;
|
||||
}, TIMEOUT_MS);
|
||||
|
||||
test(
|
||||
"finds expected markdown files",
|
||||
async () => {
|
||||
expect(
|
||||
crawlResults.some((page) => page.path.endsWith("README.md")),
|
||||
).toBe(true);
|
||||
|
||||
expect(
|
||||
crawlResults.some((page) => page.path.endsWith("docs-depth-1.md")),
|
||||
).toBe(true);
|
||||
},
|
||||
TIMEOUT_MS,
|
||||
);
|
||||
|
||||
test(
|
||||
"html includes the correct content",
|
||||
async () => {
|
||||
const doc = crawlResults.find((page) =>
|
||||
page.path.endsWith("docs-depth-1.md"),
|
||||
);
|
||||
|
||||
expect(doc?.content.includes("Test body")).toBe(true);
|
||||
expect(doc?.content.includes("Test H2 Header")).toBe(true);
|
||||
},
|
||||
TIMEOUT_MS,
|
||||
);
|
||||
|
||||
test(
|
||||
"ignores non-markdown files, e.g. `test.js` at the root",
|
||||
async () => {
|
||||
expect(crawlResults.some((page) => page.path.endsWith("test.js"))).toBe(
|
||||
false,
|
||||
);
|
||||
},
|
||||
TIMEOUT_MS,
|
||||
);
|
||||
});
|
||||
|
||||
// Skipped until we have a better way to cache Chromium installs
|
||||
// between tests and in CI
|
||||
// Run this periodically to make sure it's still working
|
||||
describe.skip("Chromium Crawler", () => {
|
||||
let shouldUseChromiumSpy: any;
|
||||
|
||||
beforeAll(async () => {
|
||||
docsCrawler = new DocsCrawler(mockIde, config, 5, 5, true);
|
||||
await chromiumInstaller.install();
|
||||
shouldUseChromiumSpy = jest
|
||||
.spyOn(docsCrawler as any, "shouldUseChromium")
|
||||
.mockReturnValue(true);
|
||||
}, TIMEOUT_MS);
|
||||
|
||||
afterAll(() => {
|
||||
shouldUseChromiumSpy.mockRestore();
|
||||
}, TIMEOUT_MS);
|
||||
|
||||
commonDocsSites.forEach((url) => {
|
||||
test(
|
||||
`Chromium crawler common site: ${url}`,
|
||||
async () => {
|
||||
const { pages, crawler } = await runCrawl(url);
|
||||
expect(pages.length).toBeGreaterThanOrEqual(1);
|
||||
expect(crawler).toEqual("chromium");
|
||||
},
|
||||
TIMEOUT_MS,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Default Crawler", () => {
|
||||
beforeAll(() => {
|
||||
docsCrawler = new DocsCrawler(mockIde, config, 2, 2, false);
|
||||
});
|
||||
|
||||
test(
|
||||
"works on static site",
|
||||
async () => {
|
||||
const { pages, crawler } = await runCrawl("https://amplified.dev/");
|
||||
expect(pages.length).toBeGreaterThanOrEqual(1);
|
||||
expect(crawler).toEqual("default");
|
||||
},
|
||||
TIMEOUT_MS,
|
||||
);
|
||||
|
||||
commonDocsSites.forEach((url) => {
|
||||
test(`Default crawler common site: ${url}`, async () => {
|
||||
const { pages, crawler } = await runCrawl(url);
|
||||
expect(pages.length).toBeGreaterThanOrEqual(1);
|
||||
expect(crawler).toEqual("default");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Cheerio Crawler", () => {
|
||||
beforeAll(() => {
|
||||
docsCrawler = new DocsCrawler(mockIde, config, 2, 2, true);
|
||||
});
|
||||
test(
|
||||
"works on static site",
|
||||
async () => {
|
||||
const { pages, crawler } = await runCrawl("https://amplified.dev/");
|
||||
expect(pages.length).toBeGreaterThanOrEqual(1);
|
||||
expect(crawler).toEqual("cheerio");
|
||||
},
|
||||
TIMEOUT_MS,
|
||||
);
|
||||
});
|
||||
});
|
||||
119
core/indexing/docs/crawlers/DocsCrawler.ts
Normal file
119
core/indexing/docs/crawlers/DocsCrawler.ts
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
import { URL } from "node:url";
|
||||
|
||||
import { ContinueConfig, IDE } from "../../..";
|
||||
|
||||
import CheerioCrawler from "./CheerioCrawler";
|
||||
import { ChromiumCrawler, ChromiumInstaller } from "./ChromiumCrawler";
|
||||
import { DefaultCrawler } from "./DefaultCrawler";
|
||||
import GitHubCrawler from "./GitHubCrawler";
|
||||
|
||||
export type PageData = {
|
||||
url: string;
|
||||
path: string;
|
||||
content: string;
|
||||
};
|
||||
|
||||
export type DocsCrawlerType = "default" | "cheerio" | "chromium" | "github";
|
||||
|
||||
class DocsCrawler {
|
||||
private readonly GITHUB_HOST = "github.com";
|
||||
private readonly chromiumInstaller: ChromiumInstaller;
|
||||
|
||||
constructor(
|
||||
private readonly ide: IDE,
|
||||
private readonly config: ContinueConfig,
|
||||
private readonly maxDepth: number = 4,
|
||||
private readonly maxRequestsPerCrawl: number = 1000,
|
||||
private readonly useLocalCrawling: boolean = false,
|
||||
private readonly githubToken: string | undefined = undefined,
|
||||
) {
|
||||
this.chromiumInstaller = new ChromiumInstaller(this.ide, this.config);
|
||||
}
|
||||
|
||||
private shouldUseChromium() {
|
||||
return (
|
||||
this.config.experimental?.useChromiumForDocsCrawling &&
|
||||
this.chromiumInstaller.isInstalled()
|
||||
);
|
||||
}
|
||||
|
||||
/*
|
||||
Returns the type of crawler used in the end
|
||||
*/
|
||||
async *crawl(
|
||||
startUrl: URL,
|
||||
): AsyncGenerator<PageData, DocsCrawlerType, undefined> {
|
||||
if (startUrl.host === this.GITHUB_HOST) {
|
||||
yield* new GitHubCrawler(startUrl, this.githubToken).crawl();
|
||||
return "github";
|
||||
}
|
||||
|
||||
if (!this.useLocalCrawling) {
|
||||
try {
|
||||
const pageData = await new DefaultCrawler(
|
||||
startUrl,
|
||||
this.maxRequestsPerCrawl,
|
||||
this.maxDepth,
|
||||
).crawl();
|
||||
if (pageData.length > 0) {
|
||||
yield* pageData;
|
||||
return "default";
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Default crawler failed, trying backup: ", e);
|
||||
}
|
||||
}
|
||||
|
||||
if (this.shouldUseChromium()) {
|
||||
yield* new ChromiumCrawler(
|
||||
startUrl,
|
||||
this.maxRequestsPerCrawl,
|
||||
this.maxDepth,
|
||||
).crawl();
|
||||
return "chromium";
|
||||
} else {
|
||||
let didCrawlSinglePage = false;
|
||||
|
||||
for await (const pageData of new CheerioCrawler(
|
||||
startUrl,
|
||||
this.maxRequestsPerCrawl,
|
||||
this.maxDepth,
|
||||
).crawl()) {
|
||||
yield pageData;
|
||||
didCrawlSinglePage = true;
|
||||
}
|
||||
|
||||
// We assume that if we failed to crawl a single page,
|
||||
// it was due to an error that using Chromium can resolve
|
||||
const shouldProposeUseChromium =
|
||||
!didCrawlSinglePage &&
|
||||
this.chromiumInstaller.shouldProposeUseChromiumOnCrawlFailure();
|
||||
|
||||
if (shouldProposeUseChromium) {
|
||||
const didInstall =
|
||||
await this.chromiumInstaller.proposeAndAttemptInstall(
|
||||
startUrl.toString(),
|
||||
);
|
||||
|
||||
if (didInstall) {
|
||||
void this.ide.showToast(
|
||||
"info",
|
||||
`Successfully installed Chromium! Retrying crawl of: ${startUrl.toString()}`,
|
||||
);
|
||||
|
||||
yield* new ChromiumCrawler(
|
||||
startUrl,
|
||||
this.maxRequestsPerCrawl,
|
||||
this.maxDepth,
|
||||
).crawl();
|
||||
return "chromium";
|
||||
}
|
||||
}
|
||||
|
||||
return "cheerio";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default DocsCrawler;
|
||||
export { CheerioCrawler, ChromiumCrawler, ChromiumInstaller, GitHubCrawler };
|
||||
|
|
@ -2,13 +2,19 @@ import { URL } from "node:url";
|
|||
|
||||
import { Octokit } from "@octokit/rest";
|
||||
|
||||
import { PageData } from "../DocsCrawler";
|
||||
import { PageData } from "./DocsCrawler";
|
||||
|
||||
class GitHubCrawler {
|
||||
private readonly markdownRegex = new RegExp(/\.(md|mdx)$/);
|
||||
private octokit = new Octokit({ auth: undefined });
|
||||
private octokit: Octokit;
|
||||
private FILES_TO_SKIP = [/TEMPLATE\.md$/, /template\.md$/];
|
||||
|
||||
constructor(private readonly startUrl: URL) {}
|
||||
constructor(
|
||||
private readonly startUrl: URL,
|
||||
private readonly githubToken: string | undefined,
|
||||
) {
|
||||
this.octokit = new Octokit({ auth: this.githubToken });
|
||||
}
|
||||
|
||||
async *crawl(): AsyncGenerator<PageData> {
|
||||
console.debug(
|
||||
|
|
@ -16,14 +22,20 @@ class GitHubCrawler {
|
|||
(this.constructor as any).name
|
||||
}] Crawling GitHub repo: ${this.startUrl.toString()}`,
|
||||
);
|
||||
const urlStr = this.startUrl.toString();
|
||||
const [_, owner, repo] = this.startUrl.pathname.split("/");
|
||||
const branch = await this.getGithubRepoDefaultBranch(owner, repo);
|
||||
|
||||
const paths = await this.getGitHubRepoPaths(owner, repo, branch);
|
||||
|
||||
for await (const path of paths) {
|
||||
if (this.FILES_TO_SKIP.some((skip) => skip.test(path))) {
|
||||
continue;
|
||||
}
|
||||
const content = await this.getGithubRepoFileContent(path, owner, repo);
|
||||
yield { path, url: urlStr, content: content ?? "" };
|
||||
|
||||
const fullUrl = new URL(this.startUrl.toString());
|
||||
fullUrl.pathname += `/tree/${branch}/${path}`;
|
||||
yield { path, url: fullUrl.toString(), content: content ?? "" };
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
64
core/indexing/docs/crawlers/crawl-test-cases.ts
Normal file
64
core/indexing/docs/crawlers/crawl-test-cases.ts
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
export const commonDocsRepos: string[] = [
|
||||
// "https://github.com/freeCodeCamp/freeCodeCamp",
|
||||
"https://github.com/996icu/996.ICU",
|
||||
// "https://github.com/vuejs/vue",
|
||||
// "https://github.com/tensorflow/tensorflow",
|
||||
"https://github.com/sindresorhus/awesome",
|
||||
"https://github.com/twbs/bootstrap",
|
||||
// "https://github.com/facebook/react",
|
||||
// "https://github.com/torvalds/linux",
|
||||
// "https://github.com/nodejs/node",
|
||||
// "https://github.com/microsoft/vscode",
|
||||
// "https://github.com/ohmyzsh/ohmyzsh",
|
||||
// "https://github.com/kamranahmedse/developer-roadmap",
|
||||
// "https://github.com/electron/electron",
|
||||
// "https://github.com/apache/spark",
|
||||
// "https://github.com/tensorflow/models",
|
||||
// "https://github.com/ansible/ansible",
|
||||
// "https://github.com/airbnb/javascript",
|
||||
// "https://github.com/torvalds/subsurface-for-dirk",
|
||||
// "https://github.com/scikit-learn/scikit-learn",
|
||||
// "https://github.com/denoland/deno",
|
||||
// "https://github.com/donnemartin/system-design-primer",
|
||||
// "https://github.com/reduxjs/redux",
|
||||
// "https://github.com/nvie/gitflow",
|
||||
// "https://github.com/pallets/flask",
|
||||
// "https://github.com/keras-team/keras",
|
||||
// "https://github.com/spring-projects/spring-boot",
|
||||
// "https://github.com/JetBrains/kotlin",
|
||||
// "https://github.com/saltstack/salt",
|
||||
// "https://github.com/apache/kafka",
|
||||
// "https://github.com/moby/moby",
|
||||
// "https://github.com/ansible/ansible-lint",
|
||||
// "https://github.com/angular/angular",
|
||||
// "https://github.com/microsoft/Terminal",
|
||||
// "https://github.com/EbookFoundation/free-programming-books",
|
||||
// "https://github.com/hashicorp/terraform",
|
||||
// "https://github.com/grafana/grafana",
|
||||
// "https://github.com/flutter/flutter",
|
||||
// "https://github.com/kubernetes/kubernetes",
|
||||
"https://github.com/jquery/jquery",
|
||||
// "https://github.com/laravel/laravel",
|
||||
// "https://github.com/mrdoob/three.js",
|
||||
// "https://github.com/prometheus/prometheus",
|
||||
// "https://github.com/nltk/nltk",
|
||||
// "https://github.com/facebook/react-native",
|
||||
// "https://github.com/jekyll/jekyll",
|
||||
// "https://github.com/wesbos/awesome-dev-podcasts",
|
||||
// "https://github.com/expressjs/express",
|
||||
// "https://github.com/elastic/elasticsearch",
|
||||
// "https://github.com/RocketChat/Rocket.Chat",
|
||||
// "https://github.com/open-source-labs/reactime",
|
||||
];
|
||||
|
||||
export const commonDocsSites = [
|
||||
"https://docs.nestjs.com/",
|
||||
"https://go.dev/doc/",
|
||||
"https://clickhouse.com/docs",
|
||||
];
|
||||
|
||||
export const failingDocsSites = [
|
||||
"https://www.tensorflow.org/api_docs",
|
||||
"https://docs.anthropic.com/en/docs",
|
||||
"https://www.rust-lang.org/learn",
|
||||
];
|
||||
|
|
@ -106,9 +106,12 @@ function countTokens(
|
|||
const encoding = encodingForModel(modelName);
|
||||
if (Array.isArray(content)) {
|
||||
return content.reduce((acc, part) => {
|
||||
return acc + part.type === "imageUrl"
|
||||
? countImageTokens(part)
|
||||
: encoding.encode(part.text ?? "", "all", []).length;
|
||||
return (
|
||||
acc +
|
||||
(part.type === "text"
|
||||
? encoding.encode(part.text ?? "", "all", []).length
|
||||
: countImageTokens(part))
|
||||
);
|
||||
}, 0);
|
||||
} else {
|
||||
return encoding.encode(content ?? "", "all", []).length;
|
||||
|
|
@ -335,7 +338,7 @@ function messageIsEmpty(message: ChatMessage): boolean {
|
|||
}
|
||||
if (Array.isArray(message.content)) {
|
||||
return message.content.every(
|
||||
(item) => !item.imageUrl && item.text?.trim() === "",
|
||||
(item) => item.type === "text" && item.text?.trim() === "",
|
||||
);
|
||||
}
|
||||
return false;
|
||||
|
|
@ -396,10 +399,10 @@ function compileChatMessages(
|
|||
|
||||
if (
|
||||
(systemMessage && systemMessage.trim() !== "") ||
|
||||
msgs?.[0].role === "system"
|
||||
msgs?.[0]?.role === "system"
|
||||
) {
|
||||
let content = "";
|
||||
if (msgs?.[0].role === "system") {
|
||||
if (msgs?.[0]?.role === "system") {
|
||||
content = renderChatMessage(msgs?.[0]);
|
||||
}
|
||||
if (systemMessage && systemMessage.trim() !== "") {
|
||||
|
|
|
|||
|
|
@ -117,6 +117,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
writeLog?: (str: string) => Promise<void>;
|
||||
llmRequestHook?: (model: string, prompt: string) => any;
|
||||
apiKey?: string;
|
||||
apiKeyLocation?: string;
|
||||
apiBase?: string;
|
||||
cacheBehavior?: CacheBehavior;
|
||||
capabilities?: ModelCapability;
|
||||
|
|
@ -194,6 +195,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
this.writeLog = options.writeLog;
|
||||
this.llmRequestHook = options.llmRequestHook;
|
||||
this.apiKey = options.apiKey;
|
||||
this.apiKeyLocation = options.apiKeyLocation;
|
||||
this.aiGatewaySlug = options.aiGatewaySlug;
|
||||
this.apiBase = options.apiBase;
|
||||
this.cacheBehavior = options.cacheBehavior;
|
||||
|
|
@ -458,9 +460,11 @@ export abstract class BaseLLM implements ILLM {
|
|||
`${toolCall.function?.name}(${toolCall.function?.arguments})`,
|
||||
)
|
||||
.join("\n");
|
||||
} else if ("content" in msg && Array.isArray(msg.content)) {
|
||||
const content = renderChatMessage(msg);
|
||||
msg.content = content;
|
||||
} else if ("content" in msg) {
|
||||
if (Array.isArray(msg.content)) {
|
||||
msg.content = renderChatMessage(msg);
|
||||
}
|
||||
contentToShow = msg.content;
|
||||
}
|
||||
|
||||
formatted += `<${msg.role}>\n${contentToShow}\n\n`;
|
||||
|
|
|
|||
|
|
@ -1,13 +1,17 @@
|
|||
import * as dotenv from "dotenv";
|
||||
|
||||
import { CompletionOptions } from "..";
|
||||
import { AssistantChatMessage, CompletionOptions } from "..";
|
||||
|
||||
import { BaseLLM } from ".";
|
||||
import Anthropic from "./llms/Anthropic";
|
||||
import Gemini from "./llms/Gemini";
|
||||
import Mistral from "./llms/Mistral";
|
||||
import OpenAI from "./llms/OpenAI";
|
||||
|
||||
dotenv.config();
|
||||
|
||||
const COMPLETION_OPTIONS: Partial<CompletionOptions> = {
|
||||
temperature: 0.5,
|
||||
// temperature: 0.5,
|
||||
topP: 1,
|
||||
topK: 40,
|
||||
presencePenalty: 0,
|
||||
|
|
@ -16,100 +20,197 @@ const COMPLETION_OPTIONS: Partial<CompletionOptions> = {
|
|||
// maxTokens: 5,
|
||||
};
|
||||
|
||||
function testLLM(llm: BaseLLM) {
|
||||
function testLLM(
|
||||
llm: BaseLLM,
|
||||
{
|
||||
skip,
|
||||
testFim,
|
||||
testToolCall,
|
||||
timeout,
|
||||
}: {
|
||||
skip?: boolean;
|
||||
testFim?: boolean;
|
||||
testToolCall?: boolean;
|
||||
timeout?: number;
|
||||
},
|
||||
) {
|
||||
if (skip) {
|
||||
return;
|
||||
}
|
||||
|
||||
beforeAll(() => {
|
||||
llm.completionOptions = { ...llm.completionOptions, ...COMPLETION_OPTIONS };
|
||||
});
|
||||
|
||||
describe(llm.providerName, () => {
|
||||
test("Stream Chat works", async () => {
|
||||
let total = "";
|
||||
for await (const chunk of llm.streamChat(
|
||||
[{ role: "user", content: "Hi" }],
|
||||
new AbortController().signal,
|
||||
)) {
|
||||
total += chunk.content;
|
||||
}
|
||||
describe(llm.providerName + "/" + llm.model, () => {
|
||||
test(
|
||||
"Stream Chat works",
|
||||
async () => {
|
||||
let total = "";
|
||||
for await (const chunk of llm.streamChat(
|
||||
[{ role: "user", content: "Hi" }],
|
||||
new AbortController().signal,
|
||||
)) {
|
||||
total += chunk.content;
|
||||
}
|
||||
|
||||
expect(total.length).toBeGreaterThan(0);
|
||||
return;
|
||||
});
|
||||
expect(total.length).toBeGreaterThan(0);
|
||||
return;
|
||||
},
|
||||
timeout,
|
||||
);
|
||||
|
||||
test("Stream Complete works", async () => {
|
||||
let total = "";
|
||||
for await (const chunk of llm.streamComplete(
|
||||
"Hi",
|
||||
new AbortController().signal,
|
||||
)) {
|
||||
total += chunk;
|
||||
}
|
||||
test(
|
||||
"Stream Complete works",
|
||||
async () => {
|
||||
let total = "";
|
||||
for await (const chunk of llm.streamComplete(
|
||||
"Hi",
|
||||
new AbortController().signal,
|
||||
)) {
|
||||
total += chunk;
|
||||
}
|
||||
|
||||
expect(total.length).toBeGreaterThan(0);
|
||||
return;
|
||||
});
|
||||
expect(total.length).toBeGreaterThan(0);
|
||||
return;
|
||||
},
|
||||
timeout,
|
||||
);
|
||||
|
||||
test("Complete works", async () => {
|
||||
const completion = await llm.complete("Hi", new AbortController().signal);
|
||||
test(
|
||||
"Complete works",
|
||||
async () => {
|
||||
const completion = await llm.complete(
|
||||
"Hi",
|
||||
new AbortController().signal,
|
||||
);
|
||||
|
||||
expect(completion.length).toBeGreaterThan(0);
|
||||
return;
|
||||
});
|
||||
expect(completion.length).toBeGreaterThan(0);
|
||||
return;
|
||||
},
|
||||
timeout,
|
||||
);
|
||||
|
||||
if (testFim) {
|
||||
test(
|
||||
"FIM works",
|
||||
async () => {
|
||||
let total = "";
|
||||
for await (const chunk of llm.streamFim(
|
||||
"Hi",
|
||||
"name is ChatGPT.",
|
||||
new AbortController().signal,
|
||||
)) {
|
||||
total += chunk;
|
||||
}
|
||||
|
||||
expect(total.length).toBeGreaterThan(0);
|
||||
return;
|
||||
},
|
||||
timeout,
|
||||
);
|
||||
}
|
||||
|
||||
if (testToolCall) {
|
||||
test(
|
||||
"Tool Call works",
|
||||
async () => {
|
||||
let args = "";
|
||||
let isFirstChunk = true;
|
||||
for await (const chunk of llm.streamChat(
|
||||
[{ role: "user", content: "Hi, my name is Nate." }],
|
||||
new AbortController().signal,
|
||||
{
|
||||
tools: [
|
||||
{
|
||||
displayTitle: "Say Hello",
|
||||
function: {
|
||||
name: "say_hello",
|
||||
description: "Say Hello",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {
|
||||
name: {
|
||||
type: "string",
|
||||
description: "The name of the person to greet",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
type: "function",
|
||||
wouldLikeTo: "Say hello",
|
||||
readonly: true,
|
||||
},
|
||||
],
|
||||
toolChoice: {
|
||||
type: "function",
|
||||
function: {
|
||||
name: "say_hello",
|
||||
},
|
||||
},
|
||||
},
|
||||
)) {
|
||||
const typedChunk = chunk as AssistantChatMessage;
|
||||
if (!typedChunk.toolCalls) {
|
||||
continue;
|
||||
}
|
||||
const toolCall = typedChunk.toolCalls[0];
|
||||
args += toolCall.function?.arguments ?? "";
|
||||
|
||||
expect(chunk.role).toBe("assistant");
|
||||
expect(chunk.content).toBe("");
|
||||
expect(typedChunk.toolCalls).toHaveLength(1);
|
||||
|
||||
if (isFirstChunk) {
|
||||
isFirstChunk = false;
|
||||
expect(toolCall.id).toBeDefined();
|
||||
expect(toolCall.function!.name).toBe("say_hello");
|
||||
}
|
||||
}
|
||||
|
||||
const parsedArgs = JSON.parse(args);
|
||||
expect(parsedArgs.name).toBe("Nate");
|
||||
},
|
||||
timeout,
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
describe.skip("LLM", () => {
|
||||
// testLLM(
|
||||
// new FreeTrial({
|
||||
// model: "gpt-3.5-turbo",
|
||||
// }),
|
||||
// );
|
||||
// testLLM(
|
||||
// new Anthropic({
|
||||
// model: "claude-2",
|
||||
// apiKey: process.env.ANTHROPIC_API_KEY,
|
||||
// }),
|
||||
// );
|
||||
describe("LLM", () => {
|
||||
testLLM(
|
||||
new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "gpt-3.5-turbo" }),
|
||||
new Anthropic({
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
apiKey: process.env.ANTHROPIC_API_KEY,
|
||||
}),
|
||||
{
|
||||
skip: false,
|
||||
testToolCall: true,
|
||||
},
|
||||
);
|
||||
testLLM(new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "gpt-4o" }), {
|
||||
skip: false,
|
||||
testToolCall: true,
|
||||
});
|
||||
testLLM(
|
||||
new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "o1-preview" }),
|
||||
{ skip: false, timeout: 20000 },
|
||||
);
|
||||
testLLM(new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "o1" }), {
|
||||
skip: false,
|
||||
});
|
||||
testLLM(
|
||||
new Gemini({
|
||||
model: "gemini-2.0-flash-exp",
|
||||
apiKey: process.env.GEMINI_API_KEY,
|
||||
}),
|
||||
{ skip: false },
|
||||
);
|
||||
testLLM(
|
||||
new Mistral({
|
||||
apiKey: process.env.MISTRAL_API_KEY,
|
||||
model: "codestral-latest",
|
||||
}),
|
||||
{ testFim: true, skip: false },
|
||||
);
|
||||
// TODO: Fix Replicate
|
||||
// testLLM(
|
||||
// new Replicate({
|
||||
// apiKey: process.env.REPLICATE_API_KEY,
|
||||
// model: "codellama-7b",
|
||||
// })
|
||||
// );
|
||||
// testLLM(new LMStudio({ model: "codellama-7b" }));
|
||||
// testLLM(new Ollama({ model: "codellama-7b" }));
|
||||
// testLLM(
|
||||
// new Together({
|
||||
// apiKey: process.env.TOGETHER_API_KEY,
|
||||
// model: "codellama-7b",
|
||||
// })
|
||||
// );
|
||||
// testLLM(new LlamaCpp({ model: "deepseek-7b" }));
|
||||
// testLLM(new Llamafile({ model: "mistral-7b" }));
|
||||
// TODO: Test these
|
||||
// testLLM(new TextGenWebUI({ model: "codellama-7b" }));
|
||||
// testLLM(new HuggingFaceTGI({ model: "codellama-7b" }));
|
||||
// testLLM(new HuggingFaceInferenceAPI({ model: "codellama-7b" }));
|
||||
// testLLM(
|
||||
// new Gemini({
|
||||
// model: "gemini-pro",
|
||||
// // model: "chat-bison-001",
|
||||
// apiKey: process.env.GOOGLE_PALM_API_KEY,
|
||||
// })
|
||||
// );
|
||||
// testLLM(
|
||||
// new Gemini({ model: "gemini-pro", apiKey: process.env.GOOGLE_PALM_API_KEY })
|
||||
// );
|
||||
// testLLM(
|
||||
// new Mistral({ apiKey: process.env.MISTRAL_API_KEY, model: "mistral-small" })
|
||||
// );
|
||||
// testLLM(
|
||||
// new Flowise({ apiKey: process.env.FLOWISE_API_KEY, model: "gpt-3.5-turbo" })
|
||||
// );
|
||||
// testLLM(
|
||||
// new Nebius({ apiKey: process.env.NEBIUS_API_KEY, model: "llama3.1-8b" })
|
||||
// );
|
||||
});
|
||||
|
|
|
|||
|
|
@ -30,6 +30,12 @@ class Anthropic extends BaseLLM {
|
|||
description: tool.function.description,
|
||||
input_schema: tool.function.parameters,
|
||||
})),
|
||||
tool_choice: options.toolChoice
|
||||
? {
|
||||
type: "tool",
|
||||
name: options.toolChoice.function.name,
|
||||
}
|
||||
: undefined,
|
||||
};
|
||||
|
||||
return finalOptions;
|
||||
|
|
|
|||
|
|
@ -1,4 +1,9 @@
|
|||
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
|
||||
import {
|
||||
ChatMessage,
|
||||
CompletionOptions,
|
||||
LLMOptions,
|
||||
TextMessagePart,
|
||||
} from "../../index.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
|
||||
class Asksage extends BaseLLM {
|
||||
|
|
@ -14,18 +19,19 @@ class Asksage extends BaseLLM {
|
|||
"gpt4-gov": "gpt4-gov", // Works
|
||||
"gpt-gov": "gpt-gov", // Works
|
||||
"gpt-4o": "gpt-4o", // Works
|
||||
"gpt-4o-mini": "gpt-4o-mini", // Works
|
||||
"gpt4": "gpt4", // Works
|
||||
"gpt-4o-mini": "gpt-4o-mini", // Works
|
||||
gpt4: "gpt4", // Works
|
||||
"gpt4-32k": "gpt4-32k",
|
||||
"gpt-o1": "gpt-o1", // Works
|
||||
"gpt-o1-mini": "gpt-o1-mini", // Works
|
||||
"gpt-o3-mini": "gpt-o3-mini", // Stub
|
||||
"gpt-3.5-turbo": "gpt35-16k", // Works
|
||||
"aws-bedrock-claude-35-sonnet-gov": "aws-bedrock-claude-35-sonnet-gov", // Works
|
||||
"claude-3-5-sonnet-latest": "claude-35-sonnet", // Works
|
||||
"claude-3-opus-20240229": "claude-3-opus", // Works
|
||||
"claude-3-sonnet-20240229": "claude-3-sonnet", // Works
|
||||
"grok-beta": "xai-grok",
|
||||
"groq-llama33": "groq-llama33",
|
||||
"groq-llama33": "groq-llama33",
|
||||
"groq-70b": "groq-70b",
|
||||
"mistral-large-latest": "mistral-large", // Works
|
||||
"llama3-70b": "llma3", // Works
|
||||
|
|
@ -50,7 +56,10 @@ class Asksage extends BaseLLM {
|
|||
message:
|
||||
typeof message.content === "string"
|
||||
? message.content
|
||||
: message.content.map((part) => part.text).join(""),
|
||||
: message.content
|
||||
.filter((part) => part.type === "text")
|
||||
.map((part) => (part as TextMessagePart).text)
|
||||
.join(""),
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -113,10 +113,18 @@ class FreeTrial extends BaseLLM {
|
|||
}
|
||||
|
||||
const parts = message.content.map((part) => {
|
||||
if (part.type === "imageUrl") {
|
||||
return {
|
||||
type: "image_url",
|
||||
image_url: {
|
||||
url: part.imageUrl.url,
|
||||
detail: "low",
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
type: part.type,
|
||||
type: "text",
|
||||
text: part.text,
|
||||
image_url: { ...part.imageUrl, detail: "low" },
|
||||
};
|
||||
});
|
||||
return {
|
||||
|
|
|
|||
|
|
@ -1,12 +1,23 @@
|
|||
import { r } from "tar";
|
||||
import {
|
||||
AssistantChatMessage,
|
||||
ChatMessage,
|
||||
CompletionOptions,
|
||||
LLMOptions,
|
||||
MessagePart,
|
||||
ToolCallDelta,
|
||||
} from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
import { streamResponse } from "../stream.js";
|
||||
import {
|
||||
GeminiChatContentPart,
|
||||
GeminiChatRequestBody,
|
||||
GeminiChatResponse,
|
||||
GeminiGenerationConfig,
|
||||
GeminiToolFunctionDeclaration,
|
||||
} from "./gemini-types.js";
|
||||
import { findLast } from "../../util/findLast.js";
|
||||
|
||||
class Gemini extends BaseLLM {
|
||||
static providerName = "gemini";
|
||||
|
|
@ -19,7 +30,7 @@ class Gemini extends BaseLLM {
|
|||
};
|
||||
|
||||
// Function to convert completion options to Gemini format
|
||||
public convertArgs(options: CompletionOptions) {
|
||||
public convertArgs(options: CompletionOptions): GeminiGenerationConfig {
|
||||
// should be public for use within VertexAI
|
||||
const finalOptions: any = {}; // Initialize an empty object
|
||||
|
||||
|
|
@ -42,7 +53,7 @@ class Gemini extends BaseLLM {
|
|||
.slice(0, this.maxStopWords ?? Gemini.defaultOptions.maxStopWords);
|
||||
}
|
||||
|
||||
return { generationConfig: finalOptions }; // Wrap options under 'generationConfig'
|
||||
return finalOptions;
|
||||
}
|
||||
|
||||
protected async *_streamComplete(
|
||||
|
|
@ -59,7 +70,7 @@ class Gemini extends BaseLLM {
|
|||
}
|
||||
}
|
||||
|
||||
public removeSystemMessage(messages: ChatMessage[]) {
|
||||
public removeSystemMessage(messages: ChatMessage[]): ChatMessage[] {
|
||||
// should be public for use within VertexAI
|
||||
const msgs = [...messages];
|
||||
|
||||
|
|
@ -92,8 +103,8 @@ class Gemini extends BaseLLM {
|
|||
? this.removeSystemMessage(messages)
|
||||
: messages;
|
||||
|
||||
if (options.model.includes("gemini")) {
|
||||
for await (const message of this.streamChatGemini(
|
||||
if (options.model.includes("bison")) {
|
||||
for await (const message of this.streamChatBison(
|
||||
convertedMsgs,
|
||||
signal,
|
||||
options,
|
||||
|
|
@ -101,7 +112,7 @@ class Gemini extends BaseLLM {
|
|||
yield message;
|
||||
}
|
||||
} else {
|
||||
for await (const message of this.streamChatBison(
|
||||
for await (const message of this.streamChatGemini(
|
||||
convertedMsgs,
|
||||
signal,
|
||||
options,
|
||||
|
|
@ -111,7 +122,7 @@ class Gemini extends BaseLLM {
|
|||
}
|
||||
}
|
||||
|
||||
continuePartToGeminiPart(part: MessagePart) {
|
||||
continuePartToGeminiPart(part: MessagePart): GeminiChatContentPart {
|
||||
return part.type === "text"
|
||||
? {
|
||||
text: part.text,
|
||||
|
|
@ -135,39 +146,165 @@ class Gemini extends BaseLLM {
|
|||
);
|
||||
// This feels hacky to repeat code from above function but was the quickest
|
||||
// way to ensure system message re-formatting isn't done if user has specified v1
|
||||
const apiBase =
|
||||
this.apiBase ||
|
||||
Gemini.defaultOptions?.apiBase ||
|
||||
"https://generativelanguage.googleapis.com/v1beta/"; // Determine if it's a v1 API call based on apiBase
|
||||
const apiBase = this.apiBase || Gemini.defaultOptions.apiBase!; // Determine if it's a v1 API call based on apiBase
|
||||
const isV1API = apiBase.includes("/v1/");
|
||||
|
||||
const contents = messages
|
||||
.map((msg) => {
|
||||
if (msg.role === "system" && !isV1API) {
|
||||
return null; // Don't include system message in contents
|
||||
}
|
||||
if (msg.role === "tool") {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
role: msg.role === "assistant" ? "model" : "user",
|
||||
parts:
|
||||
typeof msg.content === "string"
|
||||
? [{ text: msg.content }]
|
||||
: msg.content.map(this.continuePartToGeminiPart),
|
||||
};
|
||||
})
|
||||
.filter((c) => c !== null);
|
||||
// Convert chat messages to contents
|
||||
const body: GeminiChatRequestBody = {
|
||||
contents: messages
|
||||
.filter((msg) => !(msg.role === "system" && isV1API))
|
||||
.map((msg) => {
|
||||
if (msg.role === "tool") {
|
||||
let fn_name = "";
|
||||
const lastToolCallMessage = findLast(
|
||||
messages,
|
||||
(msg) => "toolCalls" in msg && msg.toolCalls?.[0]?.function?.name,
|
||||
) as AssistantChatMessage;
|
||||
if (lastToolCallMessage) {
|
||||
fn_name = lastToolCallMessage.toolCalls![0]!.function!.name!;
|
||||
}
|
||||
if (!fn_name) {
|
||||
console.warn(
|
||||
"Sending tool call response for unidentified tool call",
|
||||
);
|
||||
}
|
||||
return {
|
||||
role: "user",
|
||||
parts: [
|
||||
{
|
||||
functionResponse: {
|
||||
name: fn_name || "unknown",
|
||||
response: {
|
||||
output: msg.content, // "output" key is opinionated - not all functions will output objects
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
const assistantMsg = {
|
||||
role:
|
||||
msg.role === "assistant" ? ("model" as const) : ("user" as const),
|
||||
parts:
|
||||
typeof msg.content === "string"
|
||||
? [{ text: msg.content }]
|
||||
: msg.content.map(this.continuePartToGeminiPart),
|
||||
};
|
||||
if (msg.role === "assistant" && msg.toolCalls) {
|
||||
msg.toolCalls.forEach((toolCall) => {
|
||||
if (toolCall.function?.name && toolCall.function?.arguments) {
|
||||
assistantMsg.parts.push({
|
||||
functionCall: {
|
||||
name: toolCall.function.name,
|
||||
args: JSON.parse(toolCall.function.arguments),
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const body = {
|
||||
...this.convertArgs(options),
|
||||
contents,
|
||||
// if this.systemMessage is defined, reformat it for Gemini API
|
||||
...(this.systemMessage &&
|
||||
!isV1API && {
|
||||
systemInstruction: { parts: [{ text: this.systemMessage }] },
|
||||
return assistantMsg;
|
||||
}),
|
||||
};
|
||||
if (options) {
|
||||
body.generationConfig = this.convertArgs(options);
|
||||
}
|
||||
|
||||
// https://ai.google.dev/gemini-api/docs/api-versions
|
||||
if (!isV1API) {
|
||||
if (this.systemMessage) {
|
||||
body.systemInstruction = { parts: [{ text: this.systemMessage }] };
|
||||
}
|
||||
// Convert and add tools if present
|
||||
if (options.tools?.length) {
|
||||
// Choosing to map all tools to the functionDeclarations of one tool
|
||||
// Rather than map each tool to its own tool + functionDeclaration
|
||||
// Same difference
|
||||
const functions: GeminiToolFunctionDeclaration[] = [];
|
||||
options.tools.forEach((tool) => {
|
||||
if (tool.function.description && tool.function.name) {
|
||||
const fn: GeminiToolFunctionDeclaration = {
|
||||
description: tool.function.description,
|
||||
name: tool.function.name,
|
||||
};
|
||||
|
||||
if (
|
||||
tool.function.parameters &&
|
||||
"type" in tool.function.parameters
|
||||
// && typeof tool.function.parameters.type === "string"
|
||||
) {
|
||||
// const paramType = "TYPE_UNSPECIFIED"
|
||||
// | "STRING"
|
||||
// | "NUMBER"
|
||||
// | "INTEGER"
|
||||
// | "BOOLEAN"
|
||||
// | "ARRAY"
|
||||
// | "OBJECT"
|
||||
|
||||
if (tool.function.parameters.type === "object") {
|
||||
// Gemini can't take an empty object
|
||||
// So if empty object param is present just don't add parameters
|
||||
if (
|
||||
JSON.stringify(tool.function.parameters.properties) === "{}"
|
||||
) {
|
||||
functions.push(fn);
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Helper function to recursively clean JSON Schema objects
|
||||
const cleanJsonSchema = (schema: any): any => {
|
||||
if (!schema || typeof schema !== 'object') return schema;
|
||||
|
||||
if (Array.isArray(schema)) {
|
||||
return schema.map(cleanJsonSchema);
|
||||
}
|
||||
|
||||
const {
|
||||
$schema,
|
||||
additionalProperties,
|
||||
default: defaultValue,
|
||||
...rest
|
||||
} = schema;
|
||||
|
||||
// Recursively clean nested properties
|
||||
if (rest.properties) {
|
||||
rest.properties = Object.entries(rest.properties).reduce(
|
||||
(acc, [key, value]) => ({
|
||||
...acc,
|
||||
[key]: cleanJsonSchema(value),
|
||||
}),
|
||||
{}
|
||||
);
|
||||
}
|
||||
|
||||
// Clean items in arrays
|
||||
if (rest.items) {
|
||||
rest.items = cleanJsonSchema(rest.items);
|
||||
}
|
||||
|
||||
return rest;
|
||||
};
|
||||
|
||||
// Clean the parameters and convert type to uppercase
|
||||
const cleanedParams = cleanJsonSchema(tool.function.parameters);
|
||||
fn.parameters = {
|
||||
...cleanedParams,
|
||||
type: tool.function.parameters.type.toUpperCase(),
|
||||
};
|
||||
}
|
||||
functions.push(fn);
|
||||
}
|
||||
});
|
||||
if (functions.length) {
|
||||
body.tools = [
|
||||
{
|
||||
functionDeclarations: functions,
|
||||
},
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const response = await this.fetch(apiURL, {
|
||||
method: "POST",
|
||||
body: JSON.stringify(body),
|
||||
|
|
@ -192,24 +329,91 @@ class Gemini extends BaseLLM {
|
|||
let foundIncomplete = false;
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
const part = parts[i];
|
||||
let data;
|
||||
let data: GeminiChatResponse;
|
||||
try {
|
||||
data = JSON.parse(part);
|
||||
data = JSON.parse(part) as GeminiChatResponse;
|
||||
} catch (e) {
|
||||
foundIncomplete = true;
|
||||
continue; // yo!
|
||||
}
|
||||
if (data.error) {
|
||||
|
||||
if ("error" in data) {
|
||||
throw new Error(data.error.message);
|
||||
}
|
||||
|
||||
// Check for existence of each level before accessing the final 'text' property
|
||||
if (data?.candidates?.[0]?.content?.parts?.[0]?.text) {
|
||||
// Incrementally stream the content to make it smoother
|
||||
const content = data.candidates[0].content.parts[0].text;
|
||||
yield {
|
||||
role: "assistant",
|
||||
content,
|
||||
};
|
||||
const content = data?.candidates?.[0]?.content;
|
||||
if (content) {
|
||||
const supportedParts: MessagePart[] = [];
|
||||
const toolCalls: ToolCallDelta[] = [];
|
||||
|
||||
// Process all parts first to maintain order
|
||||
const processedParts: Array<{
|
||||
type: 'content' | 'tool' | 'toolCall',
|
||||
data: any
|
||||
}> = [];
|
||||
|
||||
for (const part of content.parts) {
|
||||
if ("text" in part) {
|
||||
supportedParts.push({ type: "text", text: part.text });
|
||||
} else if ("inlineData" in part) {
|
||||
supportedParts.push({
|
||||
type: "imageUrl",
|
||||
imageUrl: {
|
||||
url: `data:image/jpeg;base64,${part.inlineData.data}`,
|
||||
},
|
||||
});
|
||||
} else if ("functionCall" in part) {
|
||||
// Queue function call
|
||||
processedParts.push({
|
||||
type: 'toolCall',
|
||||
data: {
|
||||
type: "function",
|
||||
id: "", // Not supported by gemini
|
||||
function: {
|
||||
name: part.functionCall.name,
|
||||
arguments:
|
||||
typeof part.functionCall.args === "string"
|
||||
? part.functionCall.args
|
||||
: JSON.stringify(part.functionCall.args),
|
||||
},
|
||||
}
|
||||
});
|
||||
} else if ("functionResponse" in part) {
|
||||
// Queue function response
|
||||
processedParts.push({
|
||||
type: 'tool',
|
||||
data: {
|
||||
role: "tool",
|
||||
content: part.functionResponse.response.output as string,
|
||||
toolCallId: part.functionResponse.name,
|
||||
}
|
||||
});
|
||||
} else {
|
||||
console.warn("Unsupported gemini part type received", part);
|
||||
}
|
||||
}
|
||||
|
||||
// If we have supported content parts, yield them first
|
||||
if (supportedParts.length) {
|
||||
yield {
|
||||
role: "assistant",
|
||||
content: supportedParts,
|
||||
};
|
||||
}
|
||||
|
||||
// Then process tool calls and responses in order
|
||||
for (const part of processedParts) {
|
||||
if (part.type === 'toolCall') {
|
||||
yield {
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls: [part.data],
|
||||
};
|
||||
} else if (part.type === 'tool') {
|
||||
yield part.data;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Handle the case where the expected data structure is not found
|
||||
console.warn("Unexpected response format:", data);
|
||||
|
|
|
|||
|
|
@ -10,19 +10,16 @@ class Groq extends OpenAI {
|
|||
maxStopWords: number | undefined = 4;
|
||||
|
||||
private static modelConversion: { [key: string]: string } = {
|
||||
"llama2-70b": "llama2-70b-4096",
|
||||
"mistral-8x7b": "mixtral-8x7b-32768",
|
||||
gemma: "gemma-7b-it",
|
||||
gemma2: "gemma2-9b-it",
|
||||
"llama3-8b": "llama3-8b-8192",
|
||||
"llama3-70b": "llama3-70b-8192",
|
||||
"llama3.1-8b": "llama-3.1-8b-instant",
|
||||
"llama3.1-70b": "llama-3.1-70b-versatile",
|
||||
"llama3.1-405b": "llama-3.1-405b-reasoning",
|
||||
"llama3.2-1b": "llama-3.2-1b-preview",
|
||||
"llama3.2-3b": "llama-3.2-3b-preview",
|
||||
"llama3.2-11b": "llama-3.2-11b-vision-preview",
|
||||
"llama3.2-90b": "llama-3.2-90b-vision-preview",
|
||||
"llama3.3-70b": "llama-3.3-70b-versatile",
|
||||
};
|
||||
protected _convertModelName(model: string): string {
|
||||
return Groq.modelConversion[model] ?? model;
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
|
||||
type MockMessage = ChatMessage | "REPEAT_LAST_MSG";
|
||||
type MockMessage = ChatMessage | "REPEAT_LAST_MSG" | "REPEAT_SYSTEM_MSG";
|
||||
|
||||
class MockLLM extends BaseLLM {
|
||||
public completion: string = "Test Completion";
|
||||
|
|
@ -42,6 +42,13 @@ class MockLLM extends BaseLLM {
|
|||
content: messages[messages.length - 1].content,
|
||||
};
|
||||
break;
|
||||
case "REPEAT_SYSTEM_MSG":
|
||||
yield {
|
||||
role: "assistant",
|
||||
content:
|
||||
messages.find((m) => m.role === "system")?.content || "",
|
||||
};
|
||||
break;
|
||||
default:
|
||||
yield message;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { JSONSchema7Object, JSONSchema7Type } from "json-schema";
|
||||
import { JSONSchema7, JSONSchema7Object } from "json-schema";
|
||||
|
||||
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
|
|
@ -12,7 +12,7 @@ type OllamaChatMessage = {
|
|||
tool_calls?: {
|
||||
function: {
|
||||
name: string;
|
||||
arguments: Record<string, JSONSchema7Type>;
|
||||
arguments: JSONSchema7Object;
|
||||
};
|
||||
}[];
|
||||
};
|
||||
|
|
@ -119,7 +119,7 @@ interface OllamaTool {
|
|||
function: {
|
||||
name: string;
|
||||
description?: string;
|
||||
parameters?: JSONSchema7Object;
|
||||
parameters?: JSONSchema7;
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -273,10 +273,8 @@ class Ollama extends BaseLLM {
|
|||
content: "",
|
||||
};
|
||||
|
||||
if (typeof message.content === "string") {
|
||||
ollamaMessage.content = message.content;
|
||||
} else {
|
||||
ollamaMessage.content = renderChatMessage(message);
|
||||
ollamaMessage.content = renderChatMessage(message);
|
||||
if (Array.isArray(message.content)) {
|
||||
const images: string[] = [];
|
||||
message.content.forEach((part) => {
|
||||
if (part.type === "imageUrl" && part.imageUrl) {
|
||||
|
|
|
|||
|
|
@ -49,6 +49,7 @@ const CHAT_ONLY_MODELS = [
|
|||
"gpt-4o-mini",
|
||||
"o1-preview",
|
||||
"o1-mini",
|
||||
"o3-mini"
|
||||
];
|
||||
|
||||
const formatMessageForO1 = (messages: ChatCompletionMessageParam[]) => {
|
||||
|
|
@ -92,8 +93,8 @@ class OpenAI extends BaseLLM {
|
|||
return model;
|
||||
}
|
||||
|
||||
private isO1Model(model?: string): boolean {
|
||||
return !!model && model.startsWith("o1");
|
||||
private isO3orO1Model(model?: string): boolean {
|
||||
return !!model && (model.startsWith("o1") || model.startsWith("o3"));
|
||||
}
|
||||
|
||||
protected supportsPrediction(model: string): boolean {
|
||||
|
|
@ -113,6 +114,10 @@ class OpenAI extends BaseLLM {
|
|||
};
|
||||
}
|
||||
|
||||
protected extraBodyProperties(): Record<string, any> {
|
||||
return {};
|
||||
}
|
||||
|
||||
protected getMaxStopWords(): number {
|
||||
const url = new URL(this.apiBase!);
|
||||
|
||||
|
|
@ -140,8 +145,8 @@ class OpenAI extends BaseLLM {
|
|||
|
||||
finalOptions.stop = options.stop?.slice(0, this.getMaxStopWords());
|
||||
|
||||
// OpenAI o1-preview and o1-mini:
|
||||
if (this.isO1Model(options.model)) {
|
||||
// OpenAI o1-preview and o1-mini or o3-mini:
|
||||
if (this.isO3orO1Model(options.model)) {
|
||||
// a) use max_completion_tokens instead of max_tokens
|
||||
finalOptions.max_completion_tokens = options.maxTokens;
|
||||
finalOptions.max_tokens = undefined;
|
||||
|
|
@ -150,6 +155,10 @@ class OpenAI extends BaseLLM {
|
|||
finalOptions.messages = formatMessageForO1(finalOptions.messages);
|
||||
}
|
||||
|
||||
if (options.model === "o1") {
|
||||
finalOptions.stream = false;
|
||||
}
|
||||
|
||||
if (options.prediction && this.supportsPrediction(options.model)) {
|
||||
if (finalOptions.presence_penalty) {
|
||||
// prediction doesn't support > 0
|
||||
|
|
@ -231,8 +240,8 @@ class OpenAI extends BaseLLM {
|
|||
): ChatCompletionCreateParams {
|
||||
body.stop = body.stop?.slice(0, this.getMaxStopWords());
|
||||
|
||||
// OpenAI o1-preview and o1-mini:
|
||||
if (this.isO1Model(body.model)) {
|
||||
// OpenAI o1-preview and o1-mini or o3-mini:
|
||||
if (this.isO3orO1Model(body.model)) {
|
||||
// a) use max_completion_tokens instead of max_tokens
|
||||
body.max_completion_tokens = body.max_tokens;
|
||||
body.max_tokens = undefined;
|
||||
|
|
@ -241,6 +250,11 @@ class OpenAI extends BaseLLM {
|
|||
body.messages = formatMessageForO1(body.messages);
|
||||
}
|
||||
|
||||
if (body.model === "o1") {
|
||||
// o1 doesn't support streaming
|
||||
body.stream = false;
|
||||
}
|
||||
|
||||
if (body.prediction && this.supportsPrediction(body.model)) {
|
||||
if (body.presence_penalty) {
|
||||
// prediction doesn't support > 0
|
||||
|
|
@ -278,6 +292,7 @@ class OpenAI extends BaseLLM {
|
|||
body: JSON.stringify({
|
||||
...args,
|
||||
stream: true,
|
||||
...this.extraBodyProperties(),
|
||||
}),
|
||||
signal,
|
||||
});
|
||||
|
|
@ -319,7 +334,10 @@ class OpenAI extends BaseLLM {
|
|||
const response = await this.fetch(this._getEndpoint("chat/completions"), {
|
||||
method: "POST",
|
||||
headers: this._getHeaders(),
|
||||
body: JSON.stringify(body),
|
||||
body: JSON.stringify({
|
||||
...body,
|
||||
...this.extraBodyProperties(),
|
||||
}),
|
||||
signal,
|
||||
});
|
||||
|
||||
|
|
@ -358,6 +376,7 @@ class OpenAI extends BaseLLM {
|
|||
presence_penalty: options.presencePenalty,
|
||||
stop: options.stop,
|
||||
stream: true,
|
||||
...this.extraBodyProperties(),
|
||||
}),
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
|
|
@ -404,6 +423,7 @@ class OpenAI extends BaseLLM {
|
|||
body: JSON.stringify({
|
||||
input: chunks,
|
||||
model: this.model,
|
||||
...this.extraBodyProperties(),
|
||||
}),
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
|
|
|
|||
|
|
@ -124,7 +124,7 @@ class VertexAI extends BaseLLM {
|
|||
}
|
||||
|
||||
for await (const value of streamSse(response)) {
|
||||
if (value.type == "message_start") {
|
||||
if (value.type === "message_start") {
|
||||
console.log(value);
|
||||
}
|
||||
if (value.delta?.text) {
|
||||
|
|
@ -389,11 +389,11 @@ class VertexAI extends BaseLLM {
|
|||
const convertedMsgs = isV1API
|
||||
? this.geminiInstance.removeSystemMessage(messages)
|
||||
: messages;
|
||||
if (this.vertexProvider == "gemini") {
|
||||
if (this.vertexProvider === "gemini") {
|
||||
yield* this.streamChatGemini(convertedMsgs, options);
|
||||
} else if (this.vertexProvider == "mistral") {
|
||||
} else if (this.vertexProvider === "mistral") {
|
||||
yield* this.StreamChatMistral(messages, options);
|
||||
} else if (this.vertexProvider == "anthropic") {
|
||||
} else if (this.vertexProvider === "anthropic") {
|
||||
yield* this.StreamChatAnthropic(messages, options);
|
||||
} else {
|
||||
if (options.model.includes("bison")) {
|
||||
|
|
|
|||
|
|
@ -95,15 +95,16 @@ class WatsonX extends BaseLLM {
|
|||
}
|
||||
|
||||
const parts = message.content.map((part) => {
|
||||
const msg: any = {
|
||||
type: part.type,
|
||||
if (part.type === "imageUrl") {
|
||||
return {
|
||||
type: "image_url",
|
||||
image_url: { ...part.imageUrl, detail: "low" },
|
||||
};
|
||||
}
|
||||
return {
|
||||
type: "text",
|
||||
text: part.text,
|
||||
};
|
||||
if (part.type === "imageUrl") {
|
||||
msg.image_url = { ...part.imageUrl, detail: "low" };
|
||||
msg.type = "image_url";
|
||||
}
|
||||
return msg;
|
||||
});
|
||||
return {
|
||||
...message,
|
||||
|
|
|
|||
268
core/llm/llms/gemini-types.ts
Normal file
268
core/llm/llms/gemini-types.ts
Normal file
|
|
@ -0,0 +1,268 @@
|
|||
import { JSONSchema7Object } from "json-schema";
|
||||
|
||||
// https://ai.google.dev/api/generate-content
|
||||
export interface GeminiGenerationConfig {
|
||||
stopSequences?: string[];
|
||||
responseMimeType?: string;
|
||||
candidateCount?: number;
|
||||
maxOutputTokens?: number;
|
||||
temperature?: number;
|
||||
topP?: number;
|
||||
topK?: number;
|
||||
presencePenalty?: number;
|
||||
frequencyPenalty?: number;
|
||||
responseLogprobs?: boolean;
|
||||
logprobs?: number;
|
||||
// responseSchema?: object; // https://ai.google.dev/api/caching#Schema
|
||||
}
|
||||
|
||||
export interface GeminiFunctionSchema {
|
||||
type:
|
||||
| "TYPE_UNSPECIFIED"
|
||||
| "STRING"
|
||||
| "NUMBER"
|
||||
| "INTEGER"
|
||||
| "BOOLEAN"
|
||||
| "ARRAY"
|
||||
| "OBJECT";
|
||||
format?: string;
|
||||
description?: string;
|
||||
nullable?: boolean;
|
||||
enum?: string[];
|
||||
maxItems?: string;
|
||||
minItems?: string;
|
||||
properties?: Record<string, GeminiFunctionSchema>;
|
||||
required?: string[];
|
||||
items?: GeminiFunctionSchema;
|
||||
}
|
||||
|
||||
export type GeminiChatContentPart =
|
||||
| {
|
||||
text: string;
|
||||
}
|
||||
| {
|
||||
inlineData: {
|
||||
mimeType: string;
|
||||
data: string;
|
||||
};
|
||||
}
|
||||
| {
|
||||
functionCall: {
|
||||
name: string;
|
||||
args: JSONSchema7Object;
|
||||
};
|
||||
}
|
||||
| {
|
||||
functionResponse: {
|
||||
name: string;
|
||||
response: JSONSchema7Object;
|
||||
};
|
||||
}
|
||||
| {
|
||||
fileData: {
|
||||
fileUri: string;
|
||||
mimeType: string; // See possible values here: https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#filedata
|
||||
};
|
||||
}
|
||||
| {
|
||||
executableCode: {
|
||||
language: "PYTHON" | "LANGUAGE_UNSPECIFIED";
|
||||
code: string;
|
||||
};
|
||||
}
|
||||
| {
|
||||
codeExecutionResult: {
|
||||
outcome:
|
||||
| "OUTCOME_UNSPECIFIED"
|
||||
| "OUTCOME_OK"
|
||||
| "OUTCOME_FAILED"
|
||||
| "OUTCOME_DEADLINE_EXCEEDED";
|
||||
output: string;
|
||||
};
|
||||
};
|
||||
export interface GeminiChatContent {
|
||||
role?: "user" | "model";
|
||||
parts: GeminiChatContentPart[];
|
||||
}
|
||||
|
||||
export interface GeminiToolFunctionDeclaration {
|
||||
name: string;
|
||||
description: string;
|
||||
parameters?: GeminiFunctionSchema;
|
||||
}
|
||||
export interface GeminiTool {
|
||||
functionDeclarations?: GeminiToolFunctionDeclaration[];
|
||||
googleSearchRetrieval?: {
|
||||
dynamicRetrievalConfig: {
|
||||
mode?: "MODE_DYNAMIC" | "MODE_UNSPECIFIED";
|
||||
dynamicThreshold?: number;
|
||||
};
|
||||
};
|
||||
codeExecution?: {};
|
||||
}
|
||||
|
||||
export interface GeminiToolConfig {
|
||||
functionCallingConfig?: {
|
||||
mode?: "NONE" | "ANY" | "AUTO";
|
||||
allowedFunctionNames?: string[];
|
||||
};
|
||||
}
|
||||
|
||||
// https://ai.google.dev/api/generate-content#request-body
|
||||
export interface GeminiChatRequestBody {
|
||||
contents: GeminiChatContent[];
|
||||
tools?: GeminiTool[];
|
||||
toolConfig?: GeminiToolConfig;
|
||||
systemInstruction?: GeminiChatContent;
|
||||
generationConfig?: GeminiGenerationConfig;
|
||||
// cachedContent?: string;
|
||||
}
|
||||
|
||||
export interface GeminiChatResponseSuccess {
|
||||
candidates: Candidate[];
|
||||
promptFeedback: PromptFeedback;
|
||||
usageMetadata: UsageMetadata;
|
||||
}
|
||||
|
||||
export interface GeminiChatResponseError {
|
||||
error: {
|
||||
message: string;
|
||||
};
|
||||
}
|
||||
|
||||
export type GeminiChatResponse =
|
||||
| GeminiChatResponseError
|
||||
| GeminiChatResponseSuccess;
|
||||
|
||||
interface PromptFeedback {
|
||||
blockReason?: BlockReason;
|
||||
safetyRatings: SafetyRating[];
|
||||
}
|
||||
|
||||
enum BlockReason {
|
||||
BLOCK_REASON_UNSPECIFIED = "BLOCK_REASON_UNSPECIFIED",
|
||||
SAFETY = "SAFETY",
|
||||
OTHER = "OTHER",
|
||||
BLOCKLIST = "BLOCKLIST",
|
||||
PROHIBITED_CONTENT = "PROHIBITED_CONTENT",
|
||||
}
|
||||
|
||||
interface SafetyRating {
|
||||
harmCategory: HarmCategory;
|
||||
harmProbability: HarmProbability;
|
||||
blocked: boolean;
|
||||
}
|
||||
|
||||
enum HarmCategory {
|
||||
HARM_CATEGORY_UNSPECIFIED = "HARM_CATEGORY_UNSPECIFIED",
|
||||
HARM_CATEGORY_DEROGATORY = "HARM_CATEGORY_DEROGATORY",
|
||||
HARM_CATEGORY_TOXICITY = "HARM_CATEGORY_TOXICITY",
|
||||
HARM_CATEGORY_VIOLENCE = "HARM_CATEGORY_VIOLENCE",
|
||||
HARM_CATEGORY_SEXUAL = "HARM_CATEGORY_SEXUAL",
|
||||
HARM_CATEGORY_MEDICAL = "HARM_CATEGORY_MEDICAL",
|
||||
HARM_CATEGORY_DANGEROUS = "HARM_CATEGORY_DANGEROUS",
|
||||
HARM_CATEGORY_HARASSMENT = "HARM_CATEGORY_HARASSMENT",
|
||||
HARM_CATEGORY_HATE_SPEECH = "HARM_CATEGORY_HATE_SPEECH",
|
||||
HARM_CATEGORY_SEXUALLY_EXPLICIT = "HARM_CATEGORY_SEXUALLY_EXPLICIT",
|
||||
HARM_CATEGORY_DANGEROUS_CONTENT = "HARM_CATEGORY_DANGEROUS_CONTENT",
|
||||
HARM_CATEGORY_CIVIC_INTEGRITY = "HARM_CATEGORY_CIVIC_INTEGRITY",
|
||||
}
|
||||
|
||||
enum HarmProbability {
|
||||
HARM_PROBABILITY_UNSPECIFIED = "HARM_PROBABILITY_UNSPECIFIED",
|
||||
NEGLIGIBLE = "NEGLIGIBLE",
|
||||
LOW = "LOW",
|
||||
MEDIUM = "MEDIUM",
|
||||
HIGH = "HIGH",
|
||||
}
|
||||
|
||||
interface UsageMetadata {
|
||||
promptTokenCount: number;
|
||||
cachedContentTokenCount: number;
|
||||
candidatesTokenCount: number;
|
||||
totalTokenCount: number;
|
||||
}
|
||||
|
||||
interface Candidate {
|
||||
content: GeminiChatContent;
|
||||
finishReason: FinishReason;
|
||||
safetyRatings: SafetyRating[];
|
||||
tokenCount: number;
|
||||
groundingAttribution?: GroundingAttribution;
|
||||
groundingMetadata?: GroundingMetadata;
|
||||
avgLogprobs?: number;
|
||||
logprobs?: LogprobsResult;
|
||||
index: number;
|
||||
}
|
||||
|
||||
enum FinishReason {
|
||||
FINISH_REASON_UNSPECIFIED = "FINISH_REASON_UNSPECIFIED",
|
||||
STOP = "STOP",
|
||||
MAX_TOKENS = "MAX_TOKENS",
|
||||
SAFETY = "SAFETY",
|
||||
RECITATION = "RECITATION",
|
||||
LANGUAGE = "LANGUAGE",
|
||||
OTHER = "OTHER",
|
||||
BLOCKLIST = "BLOCKLIST",
|
||||
PROHIBITED_CONTENT = "PROHIBITED_CONTENT",
|
||||
SPII = "SPII",
|
||||
MALFORMED_FUNCTION_CALL = "MALFORMED_FUNCTION_CALL",
|
||||
}
|
||||
|
||||
interface GroundingAttribution {
|
||||
attributionSourceId: AttributionSourceId;
|
||||
groundingSourceContent: string;
|
||||
}
|
||||
|
||||
interface AttributionSourceId {
|
||||
groundingPassage?: GroundingPassageId;
|
||||
semanticRetrieverChunk?: SemanticRetrieverChunk;
|
||||
}
|
||||
|
||||
interface GroundingPassageId {
|
||||
passageId: string;
|
||||
partIndex: number;
|
||||
}
|
||||
|
||||
interface SemanticRetrieverChunk {
|
||||
source: string;
|
||||
chunk: string;
|
||||
}
|
||||
|
||||
interface GroundingMetadata {
|
||||
groundingSupport?: GroundingSupport[];
|
||||
webSearchQueries?: string[];
|
||||
searchEntryPoint?: SearchEntryPoint;
|
||||
retrievalMetadata?: RetrievalMetadata;
|
||||
}
|
||||
|
||||
interface SearchEntryPoint {
|
||||
renderedContent?: string;
|
||||
sdkBlob?: string;
|
||||
}
|
||||
|
||||
interface RetrievalMetadata {
|
||||
googleSearchDynamicRetrievalScore?: number;
|
||||
}
|
||||
|
||||
interface GroundingSupport {
|
||||
groundingChunkIndices: number[];
|
||||
confidenceScores: number[];
|
||||
segment: Segment;
|
||||
}
|
||||
|
||||
interface Segment {
|
||||
partIndex: number;
|
||||
startIndex: number;
|
||||
endIndex: number;
|
||||
text: string;
|
||||
}
|
||||
|
||||
interface LogprobsResult {
|
||||
topCandidates: TopCandidates[];
|
||||
chosenCandidates: Candidate[];
|
||||
}
|
||||
|
||||
interface TopCandidates {
|
||||
candidates: Candidate[];
|
||||
}
|
||||
|
|
@ -10,11 +10,31 @@ class ContinueProxy extends OpenAI {
|
|||
this.apiBase = new URL("openai/v1/", value.controlPlaneProxyUrl).toString();
|
||||
}
|
||||
|
||||
// The apiKey and apiBase are set to the values for the proxy,
|
||||
// but we need to keep track of the actual values that the proxy will use
|
||||
// to call whatever LLM API is chosen
|
||||
private actualApiBase?: string;
|
||||
|
||||
constructor(options: LLMOptions) {
|
||||
super(options);
|
||||
this.actualApiBase = options.apiBase;
|
||||
this.apiKeyLocation = options.apiKeyLocation;
|
||||
}
|
||||
|
||||
static providerName = "continue-proxy";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
useLegacyCompletionsEndpoint: false,
|
||||
};
|
||||
|
||||
protected extraBodyProperties(): Record<string, any> {
|
||||
return {
|
||||
continueProperties: {
|
||||
apiKeyLocation: this.apiKeyLocation,
|
||||
apiBase: this.actualApiBase,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
protected _getHeaders() {
|
||||
const headers: any = super._getHeaders();
|
||||
headers["x-continue-unique-id"] = Telemetry.uniqueId;
|
||||
|
|
|
|||
|
|
@ -1,13 +1,21 @@
|
|||
import { FimCreateParamsStreaming } from "@continuedev/openai-adapters/dist/apis/base";
|
||||
import {
|
||||
Chat,
|
||||
ChatCompletion,
|
||||
ChatCompletionAssistantMessageParam,
|
||||
ChatCompletionChunk,
|
||||
ChatCompletionCreateParams,
|
||||
ChatCompletionMessageParam,
|
||||
ChatCompletionUserMessageParam,
|
||||
CompletionCreateParams,
|
||||
} from "openai/resources/index";
|
||||
|
||||
import { ChatMessage, CompletionOptions } from "..";
|
||||
import {
|
||||
ChatMessage,
|
||||
CompletionOptions,
|
||||
MessageContent,
|
||||
TextMessagePart,
|
||||
} from "..";
|
||||
|
||||
export function toChatMessage(
|
||||
message: ChatMessage,
|
||||
|
|
@ -26,43 +34,55 @@ export function toChatMessage(
|
|||
};
|
||||
}
|
||||
|
||||
let msg: ChatCompletionMessageParam = {
|
||||
role: message.role,
|
||||
content:
|
||||
typeof message.content === "string"
|
||||
? message.content || " " // LM Studio (and other providers) don't accept empty content
|
||||
: !message.content.some((item) => item.type !== "text")
|
||||
? // If no multi-media is in the message, just send as text
|
||||
if (message.role === "assistant") {
|
||||
const msg: ChatCompletionAssistantMessageParam = {
|
||||
role: "assistant",
|
||||
content:
|
||||
typeof message.content === "string"
|
||||
? message.content || " " // LM Studio (and other providers) don't accept empty content
|
||||
: message.content
|
||||
.filter((part) => part.type === "text")
|
||||
.map((part) => part as TextMessagePart), // can remove with newer typescript version
|
||||
};
|
||||
|
||||
if (message.toolCalls) {
|
||||
msg.tool_calls = message.toolCalls.map((toolCall) => ({
|
||||
id: toolCall.id!,
|
||||
type: toolCall.type!,
|
||||
function: {
|
||||
name: toolCall.function?.name!,
|
||||
arguments: toolCall.function?.arguments!,
|
||||
},
|
||||
}));
|
||||
}
|
||||
return msg;
|
||||
} else {
|
||||
return {
|
||||
role: "user",
|
||||
content:
|
||||
typeof message.content === "string"
|
||||
? message.content || " " // LM Studio (and other providers) don't accept empty content
|
||||
: // If no multi-media is in the message, just send as text
|
||||
// for compatibility with OpenAI-"compatible" servers
|
||||
// that don't support multi-media format
|
||||
message.content.map((item) => item.text).join("") || " "
|
||||
: message.content.map((part) => {
|
||||
const msg: any = {
|
||||
type: part.type,
|
||||
text: part.text,
|
||||
};
|
||||
if (part.type === "imageUrl") {
|
||||
msg.image_url = { ...part.imageUrl, detail: "auto" };
|
||||
msg.type = "image_url";
|
||||
}
|
||||
return msg;
|
||||
}),
|
||||
};
|
||||
if (
|
||||
msg.role === "assistant" &&
|
||||
message.role === "assistant" &&
|
||||
message.toolCalls
|
||||
) {
|
||||
msg.tool_calls = message.toolCalls.map((toolCall) => ({
|
||||
id: toolCall.id!,
|
||||
type: toolCall.type!,
|
||||
function: {
|
||||
name: toolCall.function?.name!,
|
||||
arguments: toolCall.function?.arguments!,
|
||||
},
|
||||
}));
|
||||
message.content.some((item) => item.type !== "text")
|
||||
? message.content
|
||||
.map((item) => (item as TextMessagePart).text)
|
||||
.join("") || " "
|
||||
: message.content.map((part) => {
|
||||
if (part.type === "imageUrl") {
|
||||
return {
|
||||
type: "image_url" as const,
|
||||
image_url: {
|
||||
url: part.imageUrl.url,
|
||||
detail: "auto" as const,
|
||||
},
|
||||
};
|
||||
}
|
||||
return part;
|
||||
}),
|
||||
};
|
||||
}
|
||||
return msg;
|
||||
}
|
||||
|
||||
export function toChatBody(
|
||||
|
|
@ -80,6 +100,7 @@ export function toChatBody(
|
|||
stream: options.stream ?? true,
|
||||
stop: options.stop,
|
||||
prediction: options.prediction,
|
||||
tool_choice: options.toolChoice,
|
||||
};
|
||||
|
||||
if (options.tools?.length) {
|
||||
|
|
|
|||
|
|
@ -17,6 +17,10 @@ export const PROVIDER_TOOL_SUPPORT: Record<
|
|||
return true;
|
||||
}
|
||||
},
|
||||
gemini: (model) => {
|
||||
// All gemini models support function calling
|
||||
return model.toLowerCase().includes("gemini");
|
||||
},
|
||||
// https://ollama.com/search?c=tools
|
||||
ollama: (model) => {
|
||||
if (
|
||||
|
|
|
|||
15
core/package-lock.json
generated
15
core/package-lock.json
generated
|
|
@ -13,7 +13,7 @@
|
|||
"@aws-sdk/client-sagemaker-runtime": "^3.621.0",
|
||||
"@aws-sdk/credential-providers": "^3.620.1",
|
||||
"@continuedev/config-types": "^1.0.13",
|
||||
"@continuedev/config-yaml": "^1.0.0",
|
||||
"@continuedev/config-yaml": "^1.0.23",
|
||||
"@continuedev/fetch": "^1.0.4",
|
||||
"@continuedev/llm-info": "^1.0.2",
|
||||
"@continuedev/openai-adapters": "^1.0.10",
|
||||
|
|
@ -3030,18 +3030,19 @@
|
|||
}
|
||||
},
|
||||
"node_modules/@continuedev/config-types": {
|
||||
"version": "1.0.13",
|
||||
"resolved": "https://registry.npmjs.org/@continuedev/config-types/-/config-types-1.0.13.tgz",
|
||||
"integrity": "sha512-5Qmy2x58uhW1GYknypFT/7iwxEJSbt8gMgfQReV7d6xjbJ09ISOTki3hIfCilKrTCo0gIY6pzKEfCoQkUTEi6Q==",
|
||||
"version": "1.0.14",
|
||||
"resolved": "https://registry.npmjs.org/@continuedev/config-types/-/config-types-1.0.14.tgz",
|
||||
"integrity": "sha512-PVHyHPyRXd2QsaNgnCpiKYU3uHFTlyuQSkqE8OwrBmQqO6/TXUVIr/2EGtyIZGrml4Y+rGMSH40WU4/0t4SGpQ==",
|
||||
"dependencies": {
|
||||
"zod": "^3.23.8"
|
||||
}
|
||||
},
|
||||
"node_modules/@continuedev/config-yaml": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.0.tgz",
|
||||
"integrity": "sha512-NwagzzpnPLbMC3delzFSjWiFv5fp8ReFjdMQF0ko0Xg+U0Myja90k/J7JWGegF/SZMABxc/OJchElJFr58TwGA==",
|
||||
"version": "1.0.23",
|
||||
"resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.23.tgz",
|
||||
"integrity": "sha512-F2Hwc85iCwAHJuwJALOsmZIBeHdF+87mS0YT7dlC6QiE+zAhZKUHcLQ/nTt9bJuhyVyufpb9LApkp40UdGsaWw==",
|
||||
"dependencies": {
|
||||
"@continuedev/config-types": "^1.0.14",
|
||||
"yaml": "^2.6.1",
|
||||
"zod": "^3.23.8"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -46,7 +46,7 @@
|
|||
"@aws-sdk/client-sagemaker-runtime": "^3.621.0",
|
||||
"@aws-sdk/credential-providers": "^3.620.1",
|
||||
"@continuedev/config-types": "^1.0.13",
|
||||
"@continuedev/config-yaml": "^1.0.0",
|
||||
"@continuedev/config-yaml": "^1.0.23",
|
||||
"@continuedev/fetch": "^1.0.4",
|
||||
"@continuedev/llm-info": "^1.0.2",
|
||||
"@continuedev/openai-adapters": "^1.0.10",
|
||||
|
|
|
|||
|
|
@ -16,11 +16,11 @@ export async function getPromptFilesFromDir(
|
|||
return [];
|
||||
}
|
||||
|
||||
const paths = await walkDir(dir, ide, { ignoreFiles: [] });
|
||||
const promptFilePaths = paths.filter((p) => p.endsWith(".prompt"));
|
||||
const results = promptFilePaths.map(async (path) => {
|
||||
const content = await ide.readFile(path); // make a try catch
|
||||
return { path, content };
|
||||
const uris = await walkDir(dir, ide, { ignoreFiles: [] });
|
||||
const promptFilePaths = uris.filter((p) => p.endsWith(".prompt"));
|
||||
const results = promptFilePaths.map(async (uri) => {
|
||||
const content = await ide.readFile(uri); // make a try catch
|
||||
return { path: uri, content };
|
||||
});
|
||||
return Promise.all(results);
|
||||
} catch (e) {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,4 @@
|
|||
import { AutocompleteInput } from "../autocomplete/util/types";
|
||||
import { ProfileDescription } from "../config/ConfigHandler";
|
||||
|
||||
import { ConfigResult } from "@continuedev/config-yaml";
|
||||
import type {
|
||||
BrowserSerializedContinueConfig,
|
||||
ChatMessage,
|
||||
|
|
@ -9,11 +7,13 @@ import type {
|
|||
ContextProviderWithParams,
|
||||
ContextSubmenuItem,
|
||||
DiffLine,
|
||||
DocsIndexingDetails,
|
||||
FileSymbolMap,
|
||||
IdeSettings,
|
||||
LLMFullCompletionOptions,
|
||||
ModelDescription,
|
||||
ModelRoles,
|
||||
PromptLog,
|
||||
RangeInFile,
|
||||
SerializedContinueConfig,
|
||||
Session,
|
||||
|
|
@ -21,28 +21,9 @@ import type {
|
|||
SiteIndexingConfig,
|
||||
ToolCall,
|
||||
} from "../";
|
||||
import { ConfigResult } from "../config/load";
|
||||
|
||||
export type ProtocolGeneratorYield<T> = {
|
||||
done?: boolean;
|
||||
content: T;
|
||||
};
|
||||
export type ProtocolGeneratorType<Y> = AsyncGenerator<
|
||||
ProtocolGeneratorYield<Y>
|
||||
>;
|
||||
|
||||
export type AsyncGeneratorYieldType<T> =
|
||||
T extends AsyncGenerator<infer Y, any, any>
|
||||
? Y extends ProtocolGeneratorYield<infer PR>
|
||||
? PR
|
||||
: never
|
||||
: never;
|
||||
// export type AsyncGeneratorReturnType<T> =
|
||||
// T extends AsyncGenerator<any, infer R, any>
|
||||
// ? R extends ProtocolGeneratorYield<infer PR>
|
||||
// ? PR
|
||||
// : never
|
||||
// : never;
|
||||
import { AutocompleteInput } from "../autocomplete/util/types";
|
||||
import { ProfileDescription } from "../config/ConfigHandler";
|
||||
import { SharedConfigSchema } from "../config/sharedConfig";
|
||||
|
||||
export type OnboardingModes =
|
||||
| "Local"
|
||||
|
|
@ -91,6 +72,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
"config/reload": [undefined, ConfigResult<BrowserSerializedContinueConfig>];
|
||||
"config/listProfiles": [undefined, ProfileDescription[]];
|
||||
"config/openProfile": [{ profileId: string | undefined }, void];
|
||||
"config/updateSharedConfig": [SharedConfigSchema, void];
|
||||
"context/getContextItems": [
|
||||
{
|
||||
name: string;
|
||||
|
|
@ -120,7 +102,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
historyIndex: number;
|
||||
selectedCode: RangeInFile[];
|
||||
},
|
||||
ProtocolGeneratorType<string>,
|
||||
AsyncGenerator<string>,
|
||||
];
|
||||
"llm/complete": [
|
||||
{
|
||||
|
|
@ -137,7 +119,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
completionOptions: LLMFullCompletionOptions;
|
||||
title: string;
|
||||
},
|
||||
ProtocolGeneratorType<string>,
|
||||
AsyncGenerator<string>,
|
||||
];
|
||||
"llm/streamChat": [
|
||||
{
|
||||
|
|
@ -145,7 +127,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
completionOptions: LLMFullCompletionOptions;
|
||||
title: string;
|
||||
},
|
||||
ProtocolGeneratorType<ChatMessage>,
|
||||
AsyncGenerator<ChatMessage, PromptLog>,
|
||||
];
|
||||
streamDiffLines: [
|
||||
{
|
||||
|
|
@ -156,7 +138,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
language: string | undefined;
|
||||
modelTitle: string | undefined;
|
||||
},
|
||||
ProtocolGeneratorType<DiffLine>,
|
||||
AsyncGenerator<DiffLine>,
|
||||
];
|
||||
"chatDescriber/describe": [
|
||||
{
|
||||
|
|
@ -201,7 +183,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
"indexing/setPaused": [{ type: string; id: string; paused: boolean }, void];
|
||||
"docs/getSuggestedDocs": [undefined, void];
|
||||
"docs/initStatuses": [undefined, void];
|
||||
|
||||
"docs/getDetails": [{ startUrl: string }, DocsIndexingDetails];
|
||||
addAutocompleteModel: [{ model: ModelDescription }, void];
|
||||
|
||||
"profiles/switch": [{ id: string }, undefined];
|
||||
|
|
@ -212,4 +194,5 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
{ contextItems: ContextItem[] },
|
||||
];
|
||||
"clipboardCache/add": [{ content: string }, void];
|
||||
"controlPlane/openUrl": [{ path: string }, void];
|
||||
};
|
||||
|
|
|
|||
|
|
@ -13,8 +13,8 @@ import type {
|
|||
Problem,
|
||||
Range,
|
||||
RangeInFile,
|
||||
TerminalOptions,
|
||||
Thread,
|
||||
TerminalOptions
|
||||
} from "../";
|
||||
|
||||
export interface GetGhTokenArgs {
|
||||
|
|
@ -29,7 +29,7 @@ export type ToIdeFromWebviewOrCoreProtocol = {
|
|||
showVirtualFile: [{ name: string; content: string }, void];
|
||||
openFile: [{ path: string }, void];
|
||||
openUrl: [string, void];
|
||||
runCommand: [{ command: string, options?: TerminalOptions }, void];
|
||||
runCommand: [{ command: string; options?: TerminalOptions }, void];
|
||||
getSearchResults: [{ query: string }, string];
|
||||
subprocess: [{ command: string; cwd?: string }, [string, string]];
|
||||
saveFile: [{ filepath: string }, void];
|
||||
|
|
@ -72,6 +72,8 @@ export type ToIdeFromWebviewOrCoreProtocol = {
|
|||
isTelemetryEnabled: [undefined, boolean];
|
||||
getUniqueId: [undefined, string];
|
||||
getTags: [string, IndexTag[]];
|
||||
readSecrets: [{ keys: string[] }, Record<string, string>];
|
||||
writeSecrets: [{ secrets: Record<string, string> }, void];
|
||||
// end methods from IDE type
|
||||
|
||||
getIdeSettings: [undefined, IdeSettings];
|
||||
|
|
@ -92,7 +94,7 @@ export type ToIdeFromWebviewOrCoreProtocol = {
|
|||
|
||||
getGitHubAuthToken: [GetGhTokenArgs, string | undefined];
|
||||
getControlPlaneSessionInfo: [
|
||||
{ silent: boolean },
|
||||
{ silent: boolean; useOnboarding: boolean },
|
||||
ControlPlaneSessionInfo | undefined,
|
||||
];
|
||||
logoutOfControlPlane: [undefined, void];
|
||||
|
|
|
|||
|
|
@ -29,6 +29,14 @@ export class MessageIde implements IDE {
|
|||
) => void,
|
||||
) {}
|
||||
|
||||
async readSecrets(keys: string[]): Promise<Record<string, string>> {
|
||||
return this.request("readSecrets", { keys });
|
||||
}
|
||||
|
||||
async writeSecrets(secrets: { [key: string]: string }): Promise<void> {
|
||||
return this.request("writeSecrets", { secrets });
|
||||
}
|
||||
|
||||
fileExists(fileUri: string): Promise<boolean> {
|
||||
return this.request("fileExists", { filepath: fileUri });
|
||||
}
|
||||
|
|
@ -152,7 +160,7 @@ export class MessageIde implements IDE {
|
|||
await this.request("openUrl", url);
|
||||
}
|
||||
|
||||
async runCommand(command: string, options?: TerminalOptions): Promise<void> {
|
||||
async runCommand(command: string, options?: TerminalOptions): Promise<void> {
|
||||
await this.request("runCommand", { command, options });
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
|
|||
"config/deleteModel",
|
||||
"config/listProfiles",
|
||||
"config/openProfile",
|
||||
"config/updateSharedConfig",
|
||||
"context/getContextItems",
|
||||
"context/getSymbolsForFiles",
|
||||
"context/loadSubmenuItems",
|
||||
|
|
@ -52,12 +53,14 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
|
|||
"indexing/setPaused",
|
||||
"docs/getSuggestedDocs",
|
||||
"docs/initStatuses",
|
||||
"docs/getDetails",
|
||||
//
|
||||
"completeOnboarding",
|
||||
"addAutocompleteModel",
|
||||
"profiles/switch",
|
||||
"didChangeSelectedProfile",
|
||||
"tools/call",
|
||||
"controlPlane/openUrl",
|
||||
];
|
||||
|
||||
// Message types to pass through from core to webview
|
||||
|
|
@ -66,6 +69,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
|
|||
export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] =
|
||||
[
|
||||
"configUpdate",
|
||||
"configError",
|
||||
"getDefaultModelTitle",
|
||||
"indexProgress", // Codebase
|
||||
"indexing/statusUpdate", // Docs, etc.
|
||||
|
|
|
|||
|
|
@ -1,17 +1,53 @@
|
|||
import { FromWebviewProtocol } from ".";
|
||||
|
||||
interface ErrorWebviewMessengerResult {
|
||||
done: boolean;
|
||||
export interface ErrorWebviewMessage {
|
||||
status: "error";
|
||||
error: string;
|
||||
done: true;
|
||||
}
|
||||
|
||||
interface SuccessWebviewMessengerResult<T extends keyof FromWebviewProtocol> {
|
||||
done: boolean;
|
||||
export interface SuccessWebviewSingleMessage<T> {
|
||||
done: true;
|
||||
status: "success";
|
||||
content: FromWebviewProtocol[T][1];
|
||||
content: T;
|
||||
}
|
||||
|
||||
export type WebviewMessengerResult<T extends keyof FromWebviewProtocol> =
|
||||
| ErrorWebviewMessengerResult
|
||||
| SuccessWebviewMessengerResult<T>;
|
||||
export type WebviewSingleMessage<T> =
|
||||
| ErrorWebviewMessage
|
||||
| SuccessWebviewSingleMessage<T>;
|
||||
|
||||
export type WebviewSingleProtocolMessage<T extends keyof FromWebviewProtocol> =
|
||||
WebviewSingleMessage<FromWebviewProtocol[T][1]>;
|
||||
|
||||
// Generators
|
||||
export type GeneratorYieldType<T> =
|
||||
T extends AsyncGenerator<infer Yield, any, any> ? Yield : never;
|
||||
export type GeneratorReturnType<T> =
|
||||
T extends AsyncGenerator<any, infer Return, any> ? Return : never;
|
||||
|
||||
type SuccessWebviewGeneratorMessage<T, R> =
|
||||
| {
|
||||
status: "success";
|
||||
done: false;
|
||||
content: T;
|
||||
}
|
||||
| {
|
||||
status: "success";
|
||||
done: true;
|
||||
content: R;
|
||||
};
|
||||
|
||||
export type WebviewGeneratorMessage<T, R> =
|
||||
| SuccessWebviewGeneratorMessage<T, R>
|
||||
| ErrorWebviewMessage;
|
||||
|
||||
export type WebviewProtocolGeneratorMessage<
|
||||
T extends keyof FromWebviewProtocol,
|
||||
> = WebviewGeneratorMessage<
|
||||
GeneratorYieldType<FromWebviewProtocol[T][1]>,
|
||||
GeneratorReturnType<FromWebviewProtocol[T][1]>
|
||||
>;
|
||||
|
||||
export type WebviewMessage<T = unknown, R = unknown> =
|
||||
| WebviewSingleMessage<T>
|
||||
| WebviewGeneratorMessage<T, R>;
|
||||
|
|
|
|||
|
|
@ -1,11 +1,8 @@
|
|||
import { ConfigResult } from "../config/load.js";
|
||||
import { ConfigValidationError } from "../config/validation.js";
|
||||
|
||||
import { ConfigResult, ConfigValidationError } from "@continuedev/config-yaml";
|
||||
import type {
|
||||
BrowserSerializedContinueConfig,
|
||||
ContextItemWithId,
|
||||
ContextProviderName,
|
||||
ContextSubmenuItem,
|
||||
IndexingProgressUpdate,
|
||||
IndexingStatus,
|
||||
PackageDocsResult,
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ export const ideSettingsPromise = testIde.getIdeSettings();
|
|||
|
||||
export const testControlPlaneClient = new ControlPlaneClient(
|
||||
Promise.resolve(undefined),
|
||||
ideSettingsPromise,
|
||||
);
|
||||
|
||||
export const testConfigHandler = new ConfigHandler(
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ export const searchWebTool: Tool = {
|
|||
type: "object",
|
||||
required: ["query"],
|
||||
properties: {
|
||||
repo_url: {
|
||||
query: {
|
||||
type: "string",
|
||||
description: "The natural language search query",
|
||||
},
|
||||
|
|
|
|||
|
|
@ -1,5 +1,11 @@
|
|||
import fs from "node:fs";
|
||||
|
||||
import {
|
||||
salvageSharedConfig,
|
||||
sharedConfigSchema,
|
||||
SharedConfigSchema,
|
||||
} from "../config/sharedConfig";
|
||||
|
||||
import { getGlobalContextFilePath } from "./paths";
|
||||
|
||||
export type GlobalContextType = {
|
||||
|
|
@ -16,6 +22,7 @@ export type GlobalContextType = {
|
|||
hasAlreadyCreatedAPromptFile: boolean;
|
||||
showConfigUpdateToast: boolean;
|
||||
isSupportedLanceDbCpuTarget: boolean;
|
||||
sharedConfig: SharedConfigSchema;
|
||||
};
|
||||
|
||||
/**
|
||||
|
|
@ -26,9 +33,10 @@ export class GlobalContext {
|
|||
key: T,
|
||||
value: GlobalContextType[T],
|
||||
) {
|
||||
if (!fs.existsSync(getGlobalContextFilePath())) {
|
||||
const filepath = getGlobalContextFilePath();
|
||||
if (!fs.existsSync(filepath)) {
|
||||
fs.writeFileSync(
|
||||
getGlobalContextFilePath(),
|
||||
filepath,
|
||||
JSON.stringify(
|
||||
{
|
||||
[key]: value,
|
||||
|
|
@ -38,7 +46,7 @@ export class GlobalContext {
|
|||
),
|
||||
);
|
||||
} else {
|
||||
const data = fs.readFileSync(getGlobalContextFilePath(), "utf-8");
|
||||
const data = fs.readFileSync(filepath, "utf-8");
|
||||
|
||||
let parsed;
|
||||
try {
|
||||
|
|
@ -49,21 +57,19 @@ export class GlobalContext {
|
|||
}
|
||||
|
||||
parsed[key] = value;
|
||||
fs.writeFileSync(
|
||||
getGlobalContextFilePath(),
|
||||
JSON.stringify(parsed, null, 2),
|
||||
);
|
||||
fs.writeFileSync(filepath, JSON.stringify(parsed, null, 2));
|
||||
}
|
||||
}
|
||||
|
||||
get<T extends keyof GlobalContextType>(
|
||||
key: T,
|
||||
): GlobalContextType[T] | undefined {
|
||||
if (!fs.existsSync(getGlobalContextFilePath())) {
|
||||
const filepath = getGlobalContextFilePath();
|
||||
if (!fs.existsSync(filepath)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const data = fs.readFileSync(getGlobalContextFilePath(), "utf-8");
|
||||
const data = fs.readFileSync(filepath, "utf-8");
|
||||
try {
|
||||
const parsed = JSON.parse(data);
|
||||
return parsed[key];
|
||||
|
|
@ -72,4 +78,31 @@ export class GlobalContext {
|
|||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
getSharedConfig(): SharedConfigSchema {
|
||||
const sharedConfig = this.get("sharedConfig") ?? {};
|
||||
const result = sharedConfigSchema.safeParse(sharedConfig);
|
||||
if (result.success) {
|
||||
return result.data;
|
||||
} else {
|
||||
// in case of damaged shared config, repair it
|
||||
// Attempt to salvage any values that are security concerns
|
||||
console.error("Failed to load shared config, salvaging...", result.error);
|
||||
const salvagedConfig = salvageSharedConfig(sharedConfig);
|
||||
this.update("sharedConfig", salvagedConfig);
|
||||
return salvagedConfig;
|
||||
}
|
||||
}
|
||||
|
||||
updateSharedConfig(
|
||||
newValues: Partial<SharedConfigSchema>,
|
||||
): SharedConfigSchema {
|
||||
const currentSharedConfig = this.getSharedConfig();
|
||||
const updatedSharedConfig = {
|
||||
...currentSharedConfig,
|
||||
...newValues,
|
||||
};
|
||||
this.update("sharedConfig", updatedSharedConfig);
|
||||
return updatedSharedConfig;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,6 +21,13 @@ import { GetGhTokenArgs } from "../protocol/ide.js";
|
|||
|
||||
class FileSystemIde implements IDE {
|
||||
constructor(private readonly workspaceDir: string) {}
|
||||
|
||||
async readSecrets(keys: string[]): Promise<Record<string, string>> {
|
||||
return {};
|
||||
}
|
||||
|
||||
async writeSecrets(secrets: { [key: string]: string }): Promise<void> {}
|
||||
|
||||
showToast(
|
||||
type: ToastType,
|
||||
message: string,
|
||||
|
|
@ -46,8 +53,8 @@ class FileSystemIde implements IDE {
|
|||
remoteConfigSyncPeriod: 60,
|
||||
userToken: "",
|
||||
enableControlServerBeta: false,
|
||||
continueTestEnvironment: "none",
|
||||
pauseCodebaseIndexOnStart: false,
|
||||
enableDebugLogs: false,
|
||||
};
|
||||
}
|
||||
async getGitHubAuthToken(args: GetGhTokenArgs): Promise<string | undefined> {
|
||||
|
|
|
|||
|
|
@ -12,3 +12,14 @@ export function findLastIndex(
|
|||
}
|
||||
return lastIndex;
|
||||
}
|
||||
|
||||
export function findLast<T>(
|
||||
arr: T[],
|
||||
criterion: (item: T) => any,
|
||||
): T | undefined {
|
||||
for (let i = arr.length - 1; i >= 0; i--) {
|
||||
if (criterion(arr[i])) {
|
||||
return arr[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import {
|
|||
ContextItem,
|
||||
MessageContent,
|
||||
MessagePart,
|
||||
TextMessagePart,
|
||||
} from "../index";
|
||||
|
||||
export function stripImages(messageContent: MessageContent): string {
|
||||
|
|
@ -12,7 +13,7 @@ export function stripImages(messageContent: MessageContent): string {
|
|||
|
||||
return messageContent
|
||||
.filter((part) => part.type === "text")
|
||||
.map((part) => part.text)
|
||||
.map((part) => (part as TextMessagePart).text)
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@ import { TabAutocompleteOptions } from "../index.js";
|
|||
|
||||
export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = {
|
||||
disable: false,
|
||||
useFileSuffix: true,
|
||||
maxPromptTokens: 1024,
|
||||
prefixPercentage: 0.3,
|
||||
maxSuffixPercentage: 0.2,
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import * as URI from "uri-js";
|
|||
|
||||
// CAN ONLY BE USED IN CORE
|
||||
|
||||
// Converts a local path to a file:// URI
|
||||
// Converts a local path to a file:/// URI
|
||||
export function localPathToUri(path: string) {
|
||||
const url = pathToFileURL(path);
|
||||
return URI.normalize(url.toString());
|
||||
|
|
|
|||
|
|
@ -74,6 +74,10 @@ export function getGlobalContextFilePath(): string {
|
|||
return path.join(getIndexFolderPath(), "globalContext.json");
|
||||
}
|
||||
|
||||
export function getSharedConfigFilePath(): string {
|
||||
return path.join(getContinueGlobalPath(), "sharedConfig.json");
|
||||
}
|
||||
|
||||
export function getSessionFilePath(sessionId: string): string {
|
||||
return path.join(getSessionsFolderPath(), `${sessionId}.json`);
|
||||
}
|
||||
|
|
@ -301,11 +305,6 @@ export function getPathToRemoteConfig(remoteConfigServerUrl: string): string {
|
|||
return dir;
|
||||
}
|
||||
|
||||
export function internalBetaPathExists(): boolean {
|
||||
const sPath = path.join(getContinueGlobalPath(), ".internal_beta");
|
||||
return fs.existsSync(sPath);
|
||||
}
|
||||
|
||||
export function getConfigJsonPathForRemote(
|
||||
remoteConfigServerUrl: string,
|
||||
): string {
|
||||
|
|
|
|||
|
|
@ -50,6 +50,7 @@ export function modifyConfig(config: Config): Config {
|
|||
return config;
|
||||
}
|
||||
```
|
||||
|
||||
<!-- TODO: We need a config.ts reference -->
|
||||
<!-- For full `config.ts` reference, see [here](reference/config-ts.md). -->
|
||||
|
||||
|
|
@ -57,4 +58,4 @@ export function modifyConfig(config: Config): Config {
|
|||
|
||||
Currently the other action triggers are not open for configuration, but we plan to allow this via .prompt files in the future.
|
||||
|
||||
<!-- For any actions defined in a .prompt file, you can [configure a specific model](TODO). -->
|
||||
<!-- For any actions defined in a .prompt file, you can [configure a specific model](/). -->
|
||||
|
|
|
|||
|
|
@ -129,7 +129,8 @@ If your local machine can run an 8B parameter model, then we recommend running L
|
|||
{
|
||||
"title": "Llama 3.1 8B",
|
||||
"provider": "ollama",
|
||||
"model": "llama3.1:8b"
|
||||
"model": "llama3.1:8b",
|
||||
"apiBase": "http://localhost:11434"
|
||||
}
|
||||
]
|
||||
```
|
||||
|
|
@ -158,7 +159,8 @@ If your local machine can run a 16B parameter model, then we recommend running D
|
|||
{
|
||||
"title": "DeepSeek Coder 2 16B",
|
||||
"provider": "ollama",
|
||||
"model": "deepseek-coder-v2:16b"
|
||||
"model": "deepseek-coder-v2:16b",
|
||||
"apiBase": "http://localhost:11434"
|
||||
}
|
||||
]
|
||||
```
|
||||
|
|
|
|||
|
|
@ -261,9 +261,9 @@ Uses the top _n_ levels (defaulting to 3) of the call stack for that thread.
|
|||
|
||||
### `@Repository Map`
|
||||
|
||||
Reference the outline of your codebase.
|
||||
Reference the outline of your codebase. By default, signatures are included along with file in the repo map.
|
||||
|
||||
`includeSignatures` params can be used to include signatures for all files in the repo. Use with caution as will increase context size significantly. `includeSignatures` will not work if indexing is disabled.
|
||||
`includeSignatures` params can be set to false to exclude signatures. This could be necessary for large codebases and/or to reduce context size significantly. Signatures will not be included if indexing is disabled.
|
||||
|
||||
```json title="config.json"
|
||||
{
|
||||
|
|
@ -271,7 +271,7 @@ Reference the outline of your codebase.
|
|||
{
|
||||
"name": "repo-map",
|
||||
"params": {
|
||||
"includeSignatures": false
|
||||
"includeSignatures": false // default true
|
||||
}
|
||||
}
|
||||
]
|
||||
|
|
|
|||
|
|
@ -58,16 +58,15 @@ This is just another object like the ones in the `"models"` array of `config.jso
|
|||
|
||||
This object allows you to customize the behavior of tab-autocomplete. The available options are shown below, and you can find their default values [here](https://github.com/continuedev/continue/blob/fbeb2e4fe15d4b434a30a136f74b672485c852d9/core/util/parameters.ts).
|
||||
|
||||
- `disable`: Disable autocomplete (can also be done from IDE settings)
|
||||
- `disable`: Disable autocomplete (can also be done from IDE settings) (default: `false`)
|
||||
- `template`: An optional template string to be used for autocomplete. It will be rendered with the Mustache templating language, and is passed the 'prefix' and 'suffix' variables. (String)
|
||||
- `useFileSuffix`: Determines whether to use the file suffix in the prompt. (Boolean)
|
||||
- `maxPromptTokens`: The maximum number of prompt tokens to use. A smaller number will yield faster completions, but less context. (Number)
|
||||
- `prefixPercentage`: The percentage of the input that should be dedicated to the prefix. (Number)
|
||||
- `maxSuffixPercentage`: The maximum percentage of the prompt that can be dedicated to the suffix. (Number)
|
||||
- `debounceDelay`: The delay in milliseconds before triggering autocomplete after a keystroke. (Number)
|
||||
- `multilineCompletions`: Whether to enable multiline completions ("always", "never", or "auto"). Defaults to "auto".
|
||||
- `useCache`: Whether to cache and reuse completions when the prompt is the same as a previous one. May be useful to disable for testing purposes.
|
||||
- `disableInFiles`: A list of glob patterns for files in which you want to disable tab autocomplete.
|
||||
- `maxPromptTokens`: The maximum number of prompt tokens to use. A smaller number will yield faster completions, but less context. (Number) (default: `1024`)
|
||||
- `prefixPercentage`: The percentage of the input that should be dedicated to the prefix. (Number) (default: `0.3`)
|
||||
- `maxSuffixPercentage`: The maximum percentage of the prompt that can be dedicated to the suffix. (Number) (default: `0.2`)
|
||||
- `debounceDelay`: The delay in milliseconds before triggering autocomplete after a keystroke. (Number) (default: `350`)
|
||||
- `multilineCompletions`: Whether to enable multiline completions ("always", "never", or "auto"). Defaults to "auto". (default: `auto`)
|
||||
- `useCache`: Whether to cache and reuse completions when the prompt is the same as a previous one. May be useful to disable for testing purposes. (default: `true`)
|
||||
- `disableInFiles`: A list of glob patterns for files in which you want to disable tab autocomplete. (default: `[]`)
|
||||
|
||||
### Full example
|
||||
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ Continue can be deeply customized. User-level configuration is stored and can be
|
|||
- `~/.continue/config.json` (MacOS / Linux)
|
||||
- `%USERPROFILE%\.continue\config.json` (Windows)
|
||||
|
||||
To open `config.json`, you can click the "gear" icon in the bottom right corner of the Continue Chat sidebar. When editing this file, you can see the available options suggested as you type, or check the reference below.
|
||||
To open `config.json`, you can click the "gear" icon in the header of the Continue Chat sidebar to open the settings page, and then click `Open [your config location]` to open the file. When editing this file, you can see the available options suggested as you type, or check the reference below.
|
||||
|
||||
When you save `config.json`, Continue will automatically refresh to take into account your changes. `config.json` is automatically created the first time you use Continue. `config.json` is automatically generated if it doesn't exist.
|
||||
|
||||
|
|
|
|||
|
|
@ -1,18 +1,28 @@
|
|||
---
|
||||
description: Learn how to access and search your project's documentation directly within Continue
|
||||
keywords: [documentation, indexing, context provider, embeddings, docs]
|
||||
keywords:
|
||||
[
|
||||
documentation,
|
||||
indexing,
|
||||
context provider,
|
||||
embeddings,
|
||||
docs,
|
||||
embedder,
|
||||
embeddings provider,
|
||||
documentation,
|
||||
]
|
||||
toc_max_heading_level: 5
|
||||
---
|
||||
|
||||
# @Docs
|
||||
|
||||
The [`@Docs` context provider](customize/context-providers.md#docs) allows you to interact with your documentation directly within Continue. This feature enables you to index any static site or GitHub markdown pages, making it easier to access and utilize your documentation while coding.
|
||||
The [`@Docs` context provider](customize/context-providers.md#docs) allows you to efficiently reference locally-indexed documentation directly within Continue.
|
||||
|
||||
## Enabling the `@Docs` context provider
|
||||
|
||||
To enable the `@Docs` context provider, you need to add it to the list of context providers in your `config.json` file.
|
||||
To enable the `@Docs` context provider, add it to the list of context providers in your `config.json` file.
|
||||
|
||||
```json
|
||||
```json title="config.json"
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
|
|
@ -24,54 +34,73 @@ To enable the `@Docs` context provider, you need to add it to the list of contex
|
|||
|
||||
## How It Works
|
||||
|
||||
The `@Docs` context provider works by crawling specified documentation sites, generating embeddings, and storing them locally for you. This process allows for quick and efficient access to your documentation content.
|
||||
The `@Docs` context provider works by
|
||||
|
||||
1. We crawl the specified documentation site
|
||||
2. Generate embeddings for the content
|
||||
3. Store the embeddings locally on your machine
|
||||
4. Provide access to the indexed content through the `@Docs` context provider
|
||||
1. Crawling specified documentation sites
|
||||
2. Generating embeddings for the chunked content
|
||||
3. Storing the embeddings locally on your machine
|
||||
4. Embedding chat input to include similar documentation chunks as context
|
||||
|
||||
## Pre-indexed Documentation Sites
|
||||
|
||||
We offer a selection of pre-indexed documentation sites for popular frameworks and libraries. You can view the list of [available pre-indexed sites and request additions here](https://github.com/continuedev/continue/blob/main/core/indexing/docs/preIndexedDocs.ts).
|
||||
In VS Code, Continue offers a selection of pre-indexed documentation sites for popular frameworks and libraries. You can view the list of [available pre-indexed sites and request additions here](https://github.com/continuedev/continue/blob/main/core/indexing/docs/preIndexedDocs.ts).
|
||||
|
||||
Pre-indexed docs are only available in VS Code because the VS Code extension ships with the Transformers.js embedder built in, while Jetbrains currently does not. You can override a pre-indexed doc to index it with your own embeddings provider by adding it to your config (unique by `startUrl`). Otherwise, it will always use Transformers.js for queries.
|
||||
|
||||
## Indexing Your Own Documentation
|
||||
|
||||
### Through the `@Docs` Context Provider
|
||||
|
||||
To add a single documentation site, we recommend using the `@Docs` context provider.
|
||||
To add a single documentation site, we recommend using the **Add Documentation** Form within the GUI. This can be accessed
|
||||
|
||||
1. Type `@Docs` in the chat panel, hit enter
|
||||
2. Type "add" and select the "Add Docs" option
|
||||
3. Enter the required information into the dialog
|
||||
- from the `@Docs` context provider - type `@Docs` in the chat, hit `Enter`, and search for `Add Docs`
|
||||
- from the `More` page (three dots icon) in the `@docs indexes` section
|
||||
the `@Docs` context provider.
|
||||
|
||||
Indexing will begin upon submission.
|
||||
In the **Add Documentation** Form, enter a `Title` and `Start URL` for the site.
|
||||
|
||||
### Through `config.json`
|
||||
- `Title`: The name of the documentation site, used for identification in the UI
|
||||
- `Start URL`: The URL where the indexing process should begin.
|
||||
|
||||
To add multiple documentation sites, we recommend adding them in bulk to your `config.json` file. Indexing will kick off upon file save.
|
||||
Indexing will begin upon submission. Progress can be viewed in the form or later in the `@docs indexes` section of the `More` page.
|
||||
|
||||
The [configuration schema for docs](https://github.com/continuedev/continue/blob/v0.9.212-vscode/extensions/vscode/config_schema.json#L1943-L1973) is as follows:
|
||||
Documentation sources may be suggested based on package files in your repo. This currently works for Python `requirements.txt` files and Node.js (Javascript/Typescript) `package.json` files.
|
||||
|
||||
```json
|
||||
"docs": [
|
||||
- Packages with a valid documentation URL (with a `+` icon) can be clicked to immediately kick off indexing
|
||||
- Packages with partial information (with a pen icon) can be clicked to fill the form with the available information
|
||||
- Note that you can hover over the information icon to see where the package suggestion was found.
|
||||
|
||||

|
||||
|
||||
### Through global configuration
|
||||
|
||||
For bulk documentation site adds or edits, we recommend editing your global configuration file directly. Documentation sites are stored in an array within `docs` in your global configuration, as follows:
|
||||
|
||||
```json title="config.json"
|
||||
{
|
||||
"docs": [
|
||||
{
|
||||
"title": "Continue",
|
||||
"startUrl": "https://docs.continue.dev/intro",
|
||||
"rootUrl": "https://docs.continue.dev",
|
||||
"faviconUrl": "https://docs.continue.dev/favicon.ico",
|
||||
}
|
||||
]
|
||||
"title": "Nest.js",
|
||||
"startUrl": "https://docs.nestjs.com/",
|
||||
"faviconUrl": "https://docs.nestjs.com/favicon.ico"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
- `title`: The name of the documentation site, used for identification in the UI.
|
||||
- `startUrl`: The URL where the indexing process should begin.
|
||||
- `rootUrl`: The base URL of the documentation site, used to determine which pages to index.
|
||||
- `faviconUrl`: The URL of the site's favicon, used for visual identification in the UI.
|
||||
See [the config reference](../../reference) for all documentation site configuration options.
|
||||
|
||||
Indexing will re-sync upon saving the configuration file.
|
||||
|
||||
## Configuration
|
||||
|
||||
As with [@Codebase context provider configuration](https://docs.continue.dev/customize/deep-dives/codebase#configuration), you can adjust the behavior of the docs context provider with the `nRetrieve`, `nFinal`, and `useReranking`
|
||||
### Using Your Embeddings Provider
|
||||
|
||||
If you have set up an [embeddings provider](../model-types/embeddings.md), @docs will use your embeddings provider. Switching embeddings providers will trigger a re-index of all documentation sites in your configuration.
|
||||
|
||||
### Reranking
|
||||
|
||||
As with [@Codebase context provider configuration](./codebase#configuration), you can adjust the reranking behavior of the `@Docs` context provider with the `nRetrieve`, `nFinal`, and `useReranking`.
|
||||
|
||||
```json title="config.json"
|
||||
{
|
||||
|
|
@ -79,29 +108,163 @@ As with [@Codebase context provider configuration](https://docs.continue.dev/cus
|
|||
{
|
||||
"name": "docs",
|
||||
"params": {
|
||||
"nRetrieve": 25,
|
||||
"nFinal": 5,
|
||||
"useReranking": true
|
||||
"nRetrieve": 25, // The number of docs to retreive from the embeddings query
|
||||
"nFinal": 5, // The number of docs chunks to return IF reranking
|
||||
"useReranking": true // use reranking if a reranker is configured (defaults to true)
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Crawling dynamically generated sites with `useChromiumForDocsCrawling`
|
||||
### Github
|
||||
|
||||
By default, we use a lighter weight tool to crawl documentation sites that cannot render sites that are dynamically generated using JavaScript.
|
||||
|
||||
If you want to crawl a site that is dynamically generated, or you get an error while attempting to crawl a site, you can enable the experimental `useChromiumForDocsCrawling` feature in your `config.json`. This will download and install Chromium to `~/.continue/.utils`.
|
||||
The Github API rate limits public requests to 60 per hour. If you want to reliably index Github repos, you can add a github token to your config file:
|
||||
|
||||
```json title="config.json"
|
||||
"experimental": {
|
||||
"useChromiumForDocsCrawling": true
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "docs",
|
||||
"params": {
|
||||
"githubToken": "github_..."
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## FAQ
|
||||
### Local Crawling
|
||||
|
||||
### How often is the indexed content updated?
|
||||
By default, Continue crawls documentation sites using a specialized crawling service that provides the best experience for most users and documentation sites.
|
||||
|
||||
Currently we do not automatically re-index your docs. If you would like to force a re-index, you can use the following command: `Continue: Docs Force Re-Index`.
|
||||
If your documentation is private, you can skip the default crawler and use a local crawler instead by setting `useLocalCrawling` to `true`.
|
||||
|
||||
```json title="config.json"
|
||||
{
|
||||
"docs": [
|
||||
{
|
||||
"title": "My Private Docs",
|
||||
"startUrl": "http://10.2.1.2/docs",
|
||||
"faviconUrl": "http://10.2.1.2/docs/assets/favicon.ico",
|
||||
"useLocalCrawling": true
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
The default local crawler is a lightweight tool that cannot render sites that are dynamically generated using JavaScript. If your sites need to be rendered, you can enable the experimental `Use Chromium for Docs Crawling` feature from your [User Settings Page](../settings.md) This will download and install Chromium to `~/.continue/.utils`, and use it as the local crawler.
|
||||
|
||||
Further notes:
|
||||
|
||||
- If the site is only locally accessible, the default crawler will fail anyways and fall back to the local crawler. `useLocalCrawling` is especially useful if the URL itself is confidential.
|
||||
- For Github Repos this has no effect because only the Github Crawler will be used, and if the repo is private it can only be accessed with a priveleged Github token anyways.
|
||||
|
||||
## Managing your docs indexes
|
||||
|
||||
You can view indexing statuses and manage your documentation sites from the `@docs indexes` section of the `More` page (three dots)
|
||||
|
||||
- Continue does not automatically re-index your docs. Use `Click to re-index` to trigger a reindex for a specific source
|
||||
- While a site is indexing, click `Cancel indexing` to cancel the process
|
||||
- Failed indexing attempts will show an error status bar and icon
|
||||
- Delete a documentation site from your configuration using the trash icon
|
||||
|
||||

|
||||
|
||||
You can also view the overall status of currently indexing docs from a hideable progress bar at the bottom of the chat page
|
||||

|
||||
|
||||
You can also use the following IDE command to force a re-index of all docs: `Continue: Docs Force Re-Index`.
|
||||
|
||||
## Examples
|
||||
|
||||
### VS Code minimal setup
|
||||
|
||||
The following configuration example works out of the box for VS Code. This uses the built-in embeddings provider with no reranking. Pre-indexed docs will be accessible.
|
||||
|
||||
```json title="config.json"
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "docs",
|
||||
}
|
||||
],
|
||||
"docs": [
|
||||
{
|
||||
"title": "Nest.js",
|
||||
"startUrl": "https://docs.nestjs.com/",
|
||||
},
|
||||
],
|
||||
```
|
||||
|
||||
### Jetbrains minimal setup
|
||||
|
||||
Here is the equivalent minimal example for Jetbrains, which requires setting up an [embeddings provider](../model-types/embeddings.md). Pre-indexed docs will _not_ be accessible.
|
||||
|
||||
```json title="config.json"
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "docs",
|
||||
}
|
||||
],
|
||||
"docs": [
|
||||
{
|
||||
"title": "Nest.js",
|
||||
"startUrl": "https://docs.nestjs.com/",
|
||||
},
|
||||
],
|
||||
"embeddingsProvider": {
|
||||
"provider": "lmstudio",
|
||||
"model": "nomic-ai/nomic-embed-text-v1.5-GGUF"
|
||||
},
|
||||
```
|
||||
|
||||
### Full-power setup (VS Code or Jetbrains)
|
||||
|
||||
The following configuration example includes:
|
||||
|
||||
- Examples of both public and private documentation sources
|
||||
- A custom embeddings provider
|
||||
- A reranker model available, with reranking parameters customized
|
||||
- A Github token to enable Github crawling
|
||||
|
||||
```json title="config.json"
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "docs",
|
||||
"params": {
|
||||
"githubToken": "github_...",
|
||||
"nRetrieve": 25,
|
||||
"nFinal": 5,
|
||||
"useReranking": true
|
||||
}
|
||||
}
|
||||
],
|
||||
"docs": [
|
||||
{
|
||||
"title": "Nest.js",
|
||||
"startUrl": "https://docs.nestjs.com/"
|
||||
},
|
||||
{
|
||||
"title": "My Private Docs",
|
||||
"startUrl": "http://10.2.1.2/docs",
|
||||
"faviconUrl": "http://10.2.1.2/docs/assets/favicon.ico",
|
||||
"maxDepth": 4,
|
||||
"useLocalCrawling": true
|
||||
}
|
||||
],
|
||||
"reranker": {
|
||||
"name": "voyage",
|
||||
"params": {
|
||||
"model": "rerank-2",
|
||||
"apiKey": "<VOYAGE_API_KEY>"
|
||||
}
|
||||
},
|
||||
"embeddingsProvider": {
|
||||
"provider": "lmstudio",
|
||||
"model": "nomic-ai/nomic-embed-text-v1.5-GGUF"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This could also involve enabling Chromium as a backup for local documentation the [User Settings Page](../settings.md).
|
||||
|
|
|
|||
|
|
@ -60,6 +60,7 @@ The current Models available provided by Ask Sage are:
|
|||
| 8 | GPT-4-32K | Yes | ✅ |
|
||||
| 9 | GPT-o1 | Yes | ✅ |
|
||||
| 10 | GPT-o1-mini | Yes | ✅ |
|
||||
| 10 | GPT-o3-mini | Yes | ✅ |
|
||||
| 11 | GPT-3.5-turbo | Yes | ✅ |
|
||||
| 12 | Calude 3.5 Sonnet Gov | Yes | ✅ |
|
||||
| 13 | Calude 3 Opus | Yes | ✅ |
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ We recommend configuring **Llama3.1 8B** as your chat model.
|
|||
{
|
||||
"title": "Llama3.1 8B Instruct",
|
||||
"provider": "vllm",
|
||||
"model": "meta-llama/Meta-Llama-3.1-8B-Instruct"
|
||||
"model": "meta-llama/Meta-Llama-3.1-8B-Instruct",
|
||||
"apiBase": "http://<vllm chat endpoint>/v1"
|
||||
}
|
||||
]
|
||||
|
|
|
|||
|
|
@ -41,9 +41,9 @@ We recommend configuring **Claude 3.5 Sonnet** as your chat model.
|
|||
|
||||
## Autocomplete model
|
||||
|
||||
Bedrock currently does not offer any autocomplete models.
|
||||
Bedrock currently does not offer any autocomplete models. However, [Codestral from Mistral](https://mistral.ai/news/codestral-2501/) and [Point from Poolisde](https://aws.amazon.com/bedrock/poolside/) will be supported in the near future.
|
||||
|
||||
[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers.
|
||||
In the meantime, you can view a list of autocomplete model providers [here](../../model-types/autocomplete.md).
|
||||
|
||||
## Embeddings model
|
||||
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue