Merge branch 'main' into chore/update-groq-models

This commit is contained in:
Dallin Romney 2025-01-27 15:21:06 -08:00 • committed by GitHub
commit 4e184df99d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
219 changed files with 7670 additions and 3672 deletions

View file

@ -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

View file

@ -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:

View file

@ -5,6 +5,7 @@ on:
branches:
- main
paths:
- "extensions/intellij/**"
- "extensions/vscode/**"
- "core/**"
- "gui/**"
@ -274,6 +275,11 @@ 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
@ -370,7 +376,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,
@ -384,6 +390,7 @@ jobs:
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
- uses: actions/setup-node@v4
@ -432,8 +439,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
@ -546,7 +552,7 @@ jobs:
with:
url: http://127.0.0.1:8082
max-attempts: 15
retry-delay: 5s
retry-delay: 30s
- name: Run tests
run: |
@ -572,6 +578,4 @@ jobs:
with:
name: jb-failure-report
path: |
${{ github.workspace }}/extensions/intellij/build/reports
${{ github.workspace }}/extensions/intellij/build/reports

3
.vscode/launch.json vendored
View file

@ -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"
}

View file

@ -42,5 +42,6 @@
"extensions/.continue-debug": true
// "sync/**": true
},
"eslint.workingDirectories": ["./core"]
"eslint.workingDirectories": ["./core"],
"typescript.tsdk": "node_modules/typescript/lib"
}

View file

@ -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).

View file

@ -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" : "";

View file

@ -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",

View file

@ -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);

View file

@ -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],

View file

@ -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.

View file

@ -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;

View file

@ -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 () => {

View file

@ -1,3 +1,5 @@
import * as fs from "node:fs";
import {
ControlPlaneClient,
ControlPlaneSessionInfo,
@ -12,20 +14,24 @@ 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 { ConfigResult, ConfigYaml, 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 +62,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 +83,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}${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: ConfigYaml | 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 +172,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 +294,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);

View file

@ -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,

View file

@ -33,7 +33,6 @@ import {
} from "../commands/index.js";
import { AllRerankers } from "../context/allRerankers";
import { MCPManagerSingleton } from "../context/mcp";
import CodebaseContextProvider from "../context/providers/CodebaseContextProvider";
import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider";
import CustomContextProviderClass from "../context/providers/CustomContextProvider";
import FileContextProvider from "../context/providers/FileContextProvider";
@ -63,6 +62,7 @@ import {
getEsbuildBinaryPath,
} from "../util/paths";
import { ConfigResult, ConfigValidationError } from "@continuedev/config-yaml";
import {
defaultContextProvidersJetBrains,
defaultContextProvidersVsCode,
@ -70,14 +70,10 @@ import {
defaultSlashCommandsVscode,
} from "./default";
import { getSystemPromptDotFile } from "./getSystemPromptDotFile";
import { isSupportedLanceDbCpuTarget } from "./util";
import { ConfigValidationError, validateConfig } from "./validation.js";
export interface ConfigResult<T> {
config: T | undefined;
errors: ConfigValidationError[] | undefined;
configLoadInterrupted: boolean;
}
// import { isSupportedLanceDbCpuTarget } from "./util";
import { useHub } from "../control-plane/env";
import { localPathToUri } from "../util/pathToUri";
import { validateConfig } from "./validation.js";
function resolveSerializedConfig(filepath: string): SerializedContinueConfig {
let content = fs.readFileSync(filepath, "utf8");
@ -139,11 +135,14 @@ function loadSerializedConfig(
config.allowAnonymousTelemetry = true;
}
if (config.ui?.getChatTitles === undefined) {
config.ui = {
...config.ui,
getChatTitles: true,
};
// Deprecated getChatTitles property should be accounted for
// This is noted in docs
if (
config.ui &&
"getChatTitles" in config.ui &&
config.ui.getChatTitles === false
) {
config.disableSessionTitles = true;
}
if (ideSettings.remoteConfigServerUrl) {
@ -176,9 +175,10 @@ function loadSerializedConfig(
? [...defaultSlashCommandsVscode]
: [...defaultSlashCommandsJetBrains];
if (!isSupportedLanceDbCpuTarget(ide)) {
config.disableIndexing = true;
}
// Temporarily disabling this check until we can verify the commands are accuarate
// if (!isSupportedLanceDbCpuTarget(ide)) {
// config.disableIndexing = true;
// }
return { config, errors, configLoadInterrupted: false };
}
@ -229,12 +229,19 @@ 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;
}
const getCodebaseProvider = async (params: any) => {
const { default: CodebaseContextProvider } = await import(
"../context/providers/CodebaseContextProvider"
);
return new CodebaseContextProvider(params);
};
/** Only difference between intermediate and final configs is the `models` array */
async function intermediateToFinalConfig(
config: Config,
@ -394,9 +401,14 @@ async function intermediateToFinalConfig(
| ContextProviderWithParams
| undefined
)?.params || {};
const DEFAULT_CONTEXT_PROVIDERS = [
new FileContextProvider({}),
new CodebaseContextProvider(codebaseContextParams),
// Add codebase provider if indexing is enabled
...(!config.disableIndexing
? [await getCodebaseProvider(codebaseContextParams)]
: []),
// Add prompt files provider if enabled
...(loadPromptFiles ? [new PromptFilesContextProvider({})] : []),
];
@ -535,9 +547,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) => ({
@ -570,6 +583,7 @@ function finalToBrowserConfig(
experimental: final.experimental,
docs: final.docs,
tools: final.tools,
usePlatform: await useHub(ide.getIdeSettings()),
};
}
@ -804,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,

View file

@ -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,
);

View file

@ -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;
}

View file

@ -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 {}

View file

@ -0,0 +1,79 @@
import { ConfigYaml } 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<ConfigYaml>,
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 {}
}

View file

@ -1,5 +1,10 @@
import fs from "fs";
import {
ConfigResult,
ConfigValidationError,
ConfigYaml,
} from "@continuedev/config-yaml";
import {
ContinueConfig,
ContinueRcJson,
@ -9,15 +14,15 @@ 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 { Telemetry } from "../../util/posthog";
import { TTS } from "../../util/tts";
import { ConfigResult, loadFullConfigNode } from "../load";
import { ConfigValidationError } from "../validation";
import { loadFullConfigNode } from "../load";
import { loadContinueConfigFromYaml } from "../yaml/loadYaml";
import { PlatformConfigMetadata } from "./PlatformProfileLoader";
export default async function doLoadConfig(
ide: IDE,
@ -25,6 +30,8 @@ export default async function doLoadConfig(
controlPlaneClient: ControlPlaneClient,
writeLog: (message: string) => Promise<void>,
overrideConfigJson: SerializedContinueConfig | undefined,
overrideConfigYaml: ConfigYaml | undefined,
platformConfigMetadata: PlatformConfigMetadata | undefined,
workspaceId?: string,
): Promise<ConfigResult<ContinueConfig>> {
const workspaceConfigs = await getWorkspaceConfigs(ide);
@ -39,7 +46,7 @@ export default async function doLoadConfig(
let errors: ConfigValidationError[] | undefined;
let configLoadInterrupted = false;
if (fs.existsSync(configYamlPath)) {
if (fs.existsSync(configYamlPath) || overrideConfigYaml) {
const result = await loadContinueConfigFromYaml(
ide,
workspaceConfigs.map((c) => JSON.stringify(c)),
@ -48,8 +55,9 @@ export default async function doLoadConfig(
uniqueId,
writeLog,
workOsAccessToken,
undefined,
// overrideConfigYaml, TODO
overrideConfigYaml,
platformConfigMetadata,
controlPlaneClient,
);
newConfig = result.config;
errors = result.errors;
@ -91,9 +99,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 += "/";

View file

@ -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;
@ -955,7 +947,6 @@ declare global {
fontSize?: number;
displayRawMarkdown?: boolean;
showChatScrollbar?: boolean;
getChatTitles?: boolean;
codeWrap?: boolean;
}

View file

@ -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.

View 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,
);
}

View file

@ -8,6 +8,7 @@ export function convertConfigJsonToConfigYaml(
): ConfigYaml {
return {
name: "Local Config",
version: "1.0.0",
models: [
...configJson.models.map(
(model): ModelConfig => ({

View file

@ -5,10 +5,12 @@ export const defaultConfigYaml: ConfigYaml = {
models: [],
context: [],
name: "Local Config",
version: "1.0.0",
};
export const defaultConfigYamlJetBrains: ConfigYaml = {
models: [],
context: [],
name: "Local Config",
version: "1.0.0",
};

View file

@ -1,15 +1,11 @@
import fs from "node:fs";
import path from "path";
import {
extendConfig,
fillTemplateVariables,
ConfigResult,
ConfigYaml,
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,51 @@ 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";
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: ConfigYaml | undefined,
ide: IDE,
controlPlaneClient: ControlPlaneClient,
): Promise<ConfigResult<ConfigYaml>> {
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,
};
@ -119,17 +92,36 @@ async function configYamlToContinueConfig(
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 +138,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 +152,8 @@ async function configYamlToContinueConfig(
uniqueId,
ideSettings,
writeLog,
platformConfigMetadata,
continueConfig.systemMessage,
);
continueConfig.tabAutocompleteModels?.push(...llms);
}
@ -181,18 +179,33 @@ async function configYamlToContinueConfig(
// TODO: Split into model roles.
// Context
continueConfig.contextProviders = config.context
// Context providers
const codebaseContextParams: IContextProvider[] =
(config.context || []).find((cp) => cp.uses === "codebase")?.with || {};
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;
if (!cls) {
console.warn(`Unknown context provider ${context.uses}`);
if (!DEFAULT_CONTEXT_PROVIDERS_TITLES.includes(context.uses)) {
console.warn(`Unknown context provider ${context.uses}`);
}
return undefined;
}
const instance: IContextProvider = new cls(context.with ?? {});
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 +296,22 @@ export async function loadContinueConfigFromYaml(
uniqueId: string,
writeLog: (log: string) => Promise<void>,
workOsAccessToken: string | undefined,
overrideConfigYaml: string | undefined,
overrideConfigYaml: ConfigYaml | 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(configYamlPath, "utf-8")
: "";
const configYamlResult = await loadConfigYaml(
workspaceConfigs,
ideSettings,
ideType,
overrideConfigYaml ?? rawYaml,
rawYaml,
overrideConfigYaml,
ide,
controlPlaneClient,
);
if (!configYamlResult.config || configYamlResult.configLoadInterrupted) {
@ -310,6 +329,7 @@ export async function loadContinueConfigFromYaml(
uniqueId,
writeLog,
workOsAccessToken,
platformConfigMetadata,
);
const systemPromptDotFile = await getSystemPromptDotFile(ide);

View file

@ -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 {

View file

@ -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";

View file

@ -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",

View file

@ -24,6 +24,8 @@ class DocsContextProvider extends BaseContextProvider {
constructor(options: any) {
super(options);
const docsService = DocsService.getSingleton();
docsService?.setGithubToken(this.options?.githubToken);
}
private async _rerankChunks(
@ -173,6 +175,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,

View file

@ -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),
}),
},
];

View file

@ -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) {

View file

@ -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",

View file

@ -1,9 +1,16 @@
import { ConfigJson } from "@continuedev/config-types";
import { ConfigYaml } from "@continuedev/config-yaml/dist/schemas/index.js";
import fetch, { RequestInit, Response } from "node-fetch";
import { ModelDescription } from "../index.js";
import { IdeSettings, ModelDescription } from "../index.js";
import { controlPlaneEnv } from "./env.js";
import {
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<ConfigYaml>;
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 {};
}
}
}

View file

@ -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";
}

View file

@ -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,
});
});
@ -285,6 +297,11 @@ export class Core {
addContextProvider(msg.data);
});
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 +395,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 +412,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 +448,7 @@ export class Core {
const chunk = next.value;
yield { content: chunk };
yield chunk;
next = await gen.next();
}
@ -448,7 +465,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 +479,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 +502,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 +570,7 @@ export class Core {
abortedMessageIds: Set<string>,
msg: Message<ToCoreProtocol["command/run"][0]>,
messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>,
) {
): AsyncGenerator<string> {
const {
input,
history,
@ -613,7 +635,7 @@ export class Core {
break;
}
if (content) {
yield { content };
yield content;
}
}
} catch (e) {
@ -621,7 +643,6 @@ export class Core {
} finally {
clearInterval(checkActiveInterval);
}
yield { done: true, content: "" };
}
on("command/run", (msg) =>
runNodeJsSlashCommand(
@ -652,7 +673,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 +688,8 @@ export class Core {
abortedMessageIds.delete(msg.messageId);
break;
}
yield { content: diffLine };
yield diffLine;
}
return { done: true };
}
on("streamDiffLines", (msg) =>
@ -854,7 +873,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 };
});

52
core/index.d.ts vendored
View file

@ -223,16 +223,10 @@ export interface ContextSubmenuItemWithProvider extends ContextSubmenuItem {
export interface SiteIndexingConfig {
title: string;
startUrl: string;
rootUrl?: string;
maxDepth?: number;
faviconUrl?: string;
}
export interface SiteIndexingConfig {
startUrl: string;
rootUrl?: string;
title: string;
maxDepth?: number;
useLocalCrawling?: boolean;
rootUrl?: string; // Currently only used by preindexed docs
}
export interface IContextProvider {
@ -306,11 +300,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[];
@ -460,6 +460,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,6 +583,7 @@ export interface IdeSettings {
remoteConfigSyncPeriod: number;
userToken: string;
enableControlServerBeta: boolean;
continueTestEnvironment: "none" | "production" | "test" | "local";
pauseCodebaseIndexOnStart: boolean;
enableDebugLogs: boolean;
}
@ -683,6 +685,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 +827,7 @@ export interface SlashCommandDescription {
export interface CustomCommand {
name: string;
prompt: string;
description: string;
description?: string;
}
export interface Prediction {
@ -854,6 +861,13 @@ export interface Tool {
uri?: string;
}
interface ToolChoice {
type: "function";
function: {
name: string;
};
}
export interface BaseCompletionOptions {
temperature?: number;
topP?: number;
@ -871,6 +885,7 @@ export interface BaseCompletionOptions {
stream?: boolean;
prediction?: Prediction;
tools?: Tool[];
toolChoice?: ToolChoice;
}
export interface ModelCapability {
@ -882,6 +897,7 @@ export interface ModelDescription {
provider: string;
model: string;
apiKey?: string;
apiKeyLocation?: string;
apiBase?: string;
contextLength?: number;
maxStopWords?: number;
@ -971,7 +987,6 @@ export interface ContinueUIConfig {
fontSize?: number;
displayRawMarkdown?: boolean;
showChatScrollbar?: boolean;
getChatTitles?: boolean;
codeWrap?: boolean;
}
@ -1198,6 +1213,7 @@ export interface BrowserSerializedContinueConfig {
analytics?: AnalyticsConfig;
docs?: SiteIndexingConfig[];
tools: Tool[];
usePlatform: boolean;
}
// DOCS SUGGESTIONS AND PACKAGE INFO
@ -1235,9 +1251,9 @@ export type PackageDocsResult = {
} & (
| { error: string; details?: never }
| { details: PackageDetailsSuccess; error?: never }
);
);
export interface TerminalOptions {
reuseTerminal?: boolean,
terminalName?: string,
reuseTerminal?: boolean;
terminalName?: string;
}

View file

@ -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);
});

View file

@ -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);
});
});

View file

@ -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,
};

View file

@ -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];

View file

@ -25,9 +25,13 @@ 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 { ConfigResult } from "@continuedev/config-yaml";
import { runLanceMigrations, runSqliteMigrations } from "./migrations";
import {
downloadFromS3,
@ -73,8 +77,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 +94,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 +106,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 +202,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 +222,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 +243,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 +275,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;
}
@ -365,16 +370,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 +384,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 +394,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 +430,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 +517,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 +544,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 +610,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 +635,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,19 +681,18 @@ 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);
}
// This is split into its own function so that it can be recursive
@ -666,15 +701,13 @@ export default class DocsService {
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,18 +722,14 @@ 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);
}
if (isPreIndexedDoc) {
void Telemetry.capture("docs_pre_indexed_doc_used", {
doc: preIndexedDoc["title"],
});
await this.fetchAndAddPreIndexedDocEmbeddings(
preIndexedDocs[startUrl]!["title"],
);
return await this.retrieveChunks(startUrl, vector, nRetrieve, true, true);
}
return docs.map((doc) => ({
@ -802,13 +831,10 @@ 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 {
@ -828,7 +854,10 @@ export default class DocsService {
});
}
} else {
newDocs.push(doc);
const currentStatus = this.statuses.get(doc.startUrl);
if (currentStatus?.status !== "failed") {
newDocs.push(doc);
}
}
}
@ -892,10 +921,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 +931,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 +971,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 +1005,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 +1080,7 @@ export default class DocsService {
}
}
async deleteIndexes(startUrl: string) {
private async deleteIndexes(startUrl: string) {
await this.deleteEmbeddingsFromLance(startUrl);
await this.deleteMetadataFromSqlite(startUrl);
}

View file

@ -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}`);
}
}

View file

@ -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 });

View file

@ -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,
);
}
}
}

View file

@ -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();

View 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,
);
});
});

View 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 };

View file

@ -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 ?? "" };
}
}

View 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",
];

View file

@ -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;

View file

@ -25,6 +25,7 @@ import { logDevData } from "../util/devdata.js";
import { DevDataSqliteDb } from "../util/devdataSqlite.js";
import mergeJson from "../util/merge.js";
import { renderChatMessage } from "../util/messageContent.js";
import { isOllamaInstalled } from "../util/ollamaHelper.js";
import { Telemetry } from "../util/posthog.js";
import { withExponentialBackoff } from "../util/withExponentialBackoff.js";
@ -55,7 +56,6 @@ import {
toCompleteBody,
toFimBody,
} from "./openaiTypeConverters.js";
import { isOllamaInstalled } from "../util/ollamaHelper.js";
export abstract class BaseLLM implements ILLM {
static providerName: string;
@ -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;
@ -415,10 +417,9 @@ export abstract class BaseLLM implements ILLM {
e.code === "ECONNREFUSED" &&
e.message.includes("http://127.0.0.1:11434")
) {
const message = (await isOllamaInstalled()) ?
"Unable to connect to local Ollama instance. Ollama may not be running." :
"Unable to connect to local Ollama instance. Ollama may not be installed or may not running."
;
const message = (await isOllamaInstalled())
? "Unable to connect to local Ollama instance. Ollama may not be running."
: "Unable to connect to local Ollama instance. Ollama may not be installed or may not running.";
throw new Error(message);
}
}
@ -693,13 +694,28 @@ export abstract class BaseLLM implements ILLM {
return body;
}
private _modifyCompletionOptions(
completionOptions: CompletionOptions,
): CompletionOptions {
// As of 01/14/25 streaming is currently not available with o1
// See these threads:
// - https://github.com/continuedev/continue/issues/3698
// - https://community.openai.com/t/streaming-support-for-o1-o1-2024-12-17-resulting-in-400-unsupported-value/1085043
if (completionOptions.model === "o1") {
completionOptions.stream = false;
}
return completionOptions;
}
async *streamChat(
_messages: ChatMessage[],
signal: AbortSignal,
options: LLMFullCompletionOptions = {},
): AsyncGenerator<ChatMessage, PromptLog> {
const { completionOptions, log, raw } =
this._parseCompletionOptions(options);
let { completionOptions, log } = this._parseCompletionOptions(options);
completionOptions = this._modifyCompletionOptions(completionOptions);
const messages = this._compileChatMessages(completionOptions, _messages);

View file

@ -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,12 +20,23 @@ const COMPLETION_OPTIONS: Partial<CompletionOptions> = {
// maxTokens: 5,
};
function testLLM(llm: BaseLLM) {
function testLLM(
llm: BaseLLM,
{
skip,
testFim,
testToolCall,
}: { skip?: boolean; testFim?: boolean; testToolCall?: boolean },
) {
if (skip) {
return;
}
beforeAll(() => {
llm.completionOptions = { ...llm.completionOptions, ...COMPLETION_OPTIONS };
});
describe(llm.providerName, () => {
describe(llm.providerName + "/" + llm.model, () => {
test("Stream Chat works", async () => {
let total = "";
for await (const chunk of llm.streamChat(
@ -54,62 +69,119 @@ function testLLM(llm: BaseLLM) {
expect(completion.length).toBeGreaterThan(0);
return;
});
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;
});
}
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");
});
}
});
}
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 },
);
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" })
// );
});

View file

@ -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;

View file

@ -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,8 +19,8 @@ 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
@ -25,7 +30,7 @@ class Asksage extends BaseLLM {
"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 +55,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(""),
};
}

View file

@ -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 {

View file

@ -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,129 @@ 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;
}
}
fn.parameters = {
type: tool.function.parameters.type.toUpperCase(),
...tool.function.parameters,
};
}
functions.push(fn);
}
});
if (functions.length) {
body.tools = [
{
functionDeclarations: functions,
},
];
}
}
}
const response = await this.fetch(apiURL, {
method: "POST",
body: JSON.stringify(body),
@ -192,24 +293,68 @@ 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[] = [];
for (const part of content.parts) {
if ("text" in part) {
supportedParts.push({ type: "text", text: part.text });
} else if ("inlineData" in part) {
// TODO does this image url conversion actually work?
supportedParts.push({
type: "imageUrl",
imageUrl: {
url: `data:image/jpeg;base64,${part.inlineData.data}`,
},
});
} else if ("functionCall" in part) {
// Handle function call
toolCalls.push({
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) {
// TODO hypothetically order could be off here
// Where function response is in the middle of something
yield {
role: "tool",
content: part.functionResponse.response.output as string,
toolCallId: part.functionResponse.name,
};
} else {
console.warn("Unsupported gemini part type received", part);
}
}
if (supportedParts.length || toolCalls.length) {
// Incrementally stream the content to make it smoother
yield {
role: "assistant",
content: supportedParts.length ? supportedParts : "",
...(toolCalls.length ? { toolCalls } : {}),
};
}
} else {
// Handle the case where the expected data structure is not found
console.warn("Unexpected response format:", data);

View file

@ -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;
}

View file

@ -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) {

View file

@ -113,6 +113,10 @@ class OpenAI extends BaseLLM {
};
}
protected extraBodyProperties(): Record<string, any> {
return {};
}
protected getMaxStopWords(): number {
const url = new URL(this.apiBase!);
@ -150,6 +154,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
@ -241,6 +249,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 +291,7 @@ class OpenAI extends BaseLLM {
body: JSON.stringify({
...args,
stream: true,
...this.extraBodyProperties(),
}),
signal,
});
@ -319,7 +333,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 +375,7 @@ class OpenAI extends BaseLLM {
presence_penalty: options.presencePenalty,
stop: options.stop,
stream: true,
...this.extraBodyProperties(),
}),
headers: {
"Content-Type": "application/json",
@ -404,6 +422,7 @@ class OpenAI extends BaseLLM {
body: JSON.stringify({
input: chunks,
model: this.model,
...this.extraBodyProperties(),
}),
headers: {
Authorization: `Bearer ${this.apiKey}`,

View file

@ -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")) {

View file

@ -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,

View 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[];
}

View file

@ -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;

View file

@ -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) {

View file

@ -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
View file

@ -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.16",
"@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.16",
"resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.16.tgz",
"integrity": "sha512-r3dzTvL8aQ5RrzM+FX6fF+U12/crU4wpPXgDcDloSsxiOQfu3k/shLCbNzFPW57XhLUQAmUJYSZsJbIvYrNPNA==",
"dependencies": {
"@continuedev/config-types": "^1.0.14",
"yaml": "^2.6.1",
"zod": "^3.23.8"
}

View file

@ -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.16",
"@continuedev/fetch": "^1.0.4",
"@continuedev/llm-info": "^1.0.2",
"@continuedev/openai-adapters": "^1.0.10",

View file

@ -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) {

View file

@ -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,
@ -14,6 +12,7 @@ import type {
LLMFullCompletionOptions,
ModelDescription,
ModelRoles,
PromptLog,
RangeInFile,
SerializedContinueConfig,
Session,
@ -21,28 +20,8 @@ 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";
export type OnboardingModes =
| "Local"
@ -120,7 +99,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
historyIndex: number;
selectedCode: RangeInFile[];
},
ProtocolGeneratorType<string>,
AsyncGenerator<string>,
];
"llm/complete": [
{
@ -137,7 +116,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
completionOptions: LLMFullCompletionOptions;
title: string;
},
ProtocolGeneratorType<string>,
AsyncGenerator<string>,
];
"llm/streamChat": [
{
@ -145,7 +124,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
completionOptions: LLMFullCompletionOptions;
title: string;
},
ProtocolGeneratorType<ChatMessage>,
AsyncGenerator<ChatMessage, PromptLog>,
];
streamDiffLines: [
{
@ -156,7 +135,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
language: string | undefined;
modelTitle: string | undefined;
},
ProtocolGeneratorType<DiffLine>,
AsyncGenerator<DiffLine>,
];
"chatDescriber/describe": [
{
@ -212,4 +191,5 @@ export type ToCoreFromIdeOrWebviewProtocol = {
{ contextItems: ContextItem[] },
];
"clipboardCache/add": [{ content: string }, void];
"controlPlane/openUrl": [{ path: string }, void];
};

View file

@ -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];

View file

@ -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 });
}

View file

@ -58,6 +58,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"profiles/switch",
"didChangeSelectedProfile",
"tools/call",
"controlPlane/openUrl",
];
// Message types to pass through from core to webview
@ -66,6 +67,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.

View file

@ -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>;

View file

@ -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,

View file

@ -11,6 +11,7 @@ export const ideSettingsPromise = testIde.getIdeSettings();
export const testControlPlaneClient = new ControlPlaneClient(
Promise.resolve(undefined),
ideSettingsPromise,
);
export const testConfigHandler = new ConfigHandler(

View file

@ -13,7 +13,7 @@ export const searchWebTool: Tool = {
"Performs a web search, returning top results. This tool should only be called for questions that require external knowledge. Common programming questions do not require web search.",
parameters: {
type: "object",
required: ["query"],
required: ["repo_url"],
properties: {
repo_url: {
type: "string",

View file

@ -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,6 +53,7 @@ class FileSystemIde implements IDE {
remoteConfigSyncPeriod: 60,
userToken: "",
enableControlServerBeta: false,
continueTestEnvironment: "none",
pauseCodebaseIndexOnStart: false,
enableDebugLogs: false,
};

View file

@ -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];
}
}
}

View file

@ -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");
}

View file

@ -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());

View file

@ -301,11 +301,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 {

View file

@ -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"
}
]
```

View file

@ -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
}
}
]

View file

@ -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.
![Add documentation form](/img/docs-form.png)
### 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,20 +108,52 @@ 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.
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:
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`.
```json title="config.json"
{
"contextProviders": [
{
"name": "docs",
"params": {
"githubToken": "github_..."
}
}
]
}
```
### Local Crawling
By default, Continue crawls documentation sites using a specialized crawling service that provides the best experience for most users and documentation sites.
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 `useChromiumForDocsCrawling` feature in your `config.json`. This will download and install Chromium to `~/.continue/.utils`, and use it as the local crawler.
```json title="config.json"
"experimental": {
@ -100,8 +161,118 @@ If you want to crawl a site that is dynamically generated, or you get an error w
}
```
## FAQ
Further notes:
### How often is the indexed content updated?
- 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.
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`.
## 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
![More Page @docs indexes section](/img/docs-indexes.png)
You can also view the overall status of currently indexing docs from a hideable progress bar at the bottom of the chat page
![Documentation indexing peek](/img/docs-indexing-peek.png)
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
- Chromium enabled as a backup for private documentation
```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"
},
"experimental": {
"useChromiumForDocsCrawling": true
}
}
```

View file

@ -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"
}
]

View file

@ -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

View file

@ -64,7 +64,7 @@ To configure a remote instance of Ollama, add the `"apiBase"` property to your m
{
"title": "Llama3.1 8B",
"provider": "ollama",
"model": "llama3.1:8b"
"model": "llama3.1:8b",
"apiBase": "http://<my endpoint>:11434"
}
]

View file

@ -234,9 +234,10 @@ List of documentation sites to index.
- `title` (**required**): Title of the documentation site, displayed in dropdowns, etc.
- `startUrl` (**required**): Start page for crawling - usually root or intro page for docs
- `rootUrl`: Crawler will only index docs within this domain - pages that contain this URL
- `maxDepth`: Maximum depth for crawling. Default `3`
<!-- - `rootUrl`: Crawler will only index docs within this domain - pages that contain this URL -->
- `maxDepth`: Maximum link depth for crawling. Default `4`
- `favicon`: URL for site favicon (default is `/favicon.ico` from `startUrl`).
- `useLocalCrawling`: Skip the default crawler and only crawl using a local crawler.
Example
@ -245,22 +246,11 @@ Example
{
"title": "Continue",
"startUrl": "https://docs.continue.dev/intro",
"rootUrl": "https://docs.continue.dev",
"faviconUrl": "https://docs.continue.dev/favicon.ico",
}
]
```
### `analytics`
Configuration for analytics tracking.
**Properties:**
- `provider`: Analytics provider (`"posthog"` or `"logstash"`).
- `url`: URL for analytics data.
- `clientKey`: Client key for analytics.
### `slashCommands`
Custom commands initiated by typing "/" in the sidebar. Commands include predefined functionality or may be user-defined.
@ -355,6 +345,8 @@ Example
Prevents generating summary titles for each chat session when set to `true`.
Note that if the deprecated setting `ui.getChatTitles` is set to `false`, it will override this.
### `ui`
Customizable UI settings to control interface appearance and behavior.
@ -420,6 +412,7 @@ Several experimental config parameters are available, as described below:
- `fix`: Prompt for fixing code.
- `optimize`: Prompt for optimizing code.
- `useChromiumForDocsCrawling`: Use Chromium to crawl docs locally. Useful if the default Cheerio crawler fails on sites that require JavaScript rendering. Downloads and installs Chromium to `~/.continue/.utils`..
- `modelContextProtocolServers`: See [Model Context Protocol](/customize/context-providers#model-context-protocol)
Example
@ -441,7 +434,16 @@ Example
"fixGrammar": "Fix grammar in the above but allow for typos."
},
"readResponseTTS": false,
"useChromiumForDocsCrawling": true
"useChromiumForDocsCrawling": true,
"modelContextProtocolServers": [
{
"transport": {
"type": "stdio",
"command": "uvx",
"args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"]
}
}
]
}
}
```

347
docs/docs/yaml-migration.md Normal file
View file

@ -0,0 +1,347 @@
---
title: Config Migration to YAML
description: Reference for migrating from JSON to YAML Continue configuration.
keywords: [config, yaml, configuration, customize, customization, migration]
---
# Migrating Config to YAML
Continue's YAML configuration format provides more readable, maintainable, consistent configuration files, as well as new configuration options and removal of some old configuration options. YAML is the preferred format and will be used to integrate with future Continue products. Below is a brief guide for migration from `config.json` to `config.yaml`.
See also
- [Intro to YAML](https://yaml.org/)
- [JSON Continue Config Reference](/reference)
- [YAML Continue Config Reference](/yaml-reference)
## Create YAML file
Create a `config.yaml` file in your Continue Global Directory (`~/.continue` on Mac, `%USERPROFILE%\.continue`) alongside your current `config.json` file. If a `config.yaml` file is present, it will be loaded instead of `config.json`.
Give your configuration a `name` and a `version`:
```yaml title="config.yaml"
name: my-configuration
version: 0.0.1
```
### Models
Add all model configurations in `config.json`, including models in `models`, `tabAutocompleteModel`, `embeddingsProvider`, and `reranker`, to the `models` section of your new YAML config file. A new `roles` YAML field specifies which roles a model can be used for, with possible values `chat`, `autocomplete`, `embed`, `rerank`, `edit`, `apply`, `summarize`.
- `models` in config should have `roles: [chat]`
- `tabAutocompleteModel`(s) in config should have `roles: [autocomplete]`
- `embeddingsProvider` in config should have `roles: [embed]`
- `reranker` in config should have `roles: [rerank]`
- `experimental.modelRoles` is replaced by simply adding roles to the model
- `inlineEdit` -> e.g. `roles: [chat, edit]`
- `applyCodeBlock` -> e.g. `roles: [chat, apply]`
Model-level `requestOptions` remain, with minor changes. See [YAML Continue Config Reference](/yaml-reference#requestoptions)
Model-level `completionOptions` are replaced by `defaultCompletionOptions`, with minor changes. See [YAML Continue Config Reference](/yaml-reference#completionoptions)
<!-- TODO - API KEY -> apiKeySecret? -->
<!-- TODO - ollama autodetect supported? -->
**Before**
```json title="config.json"
{
"models": [
{
"title": "GPT-4",
"provider": "openai",
"model": "gpt-4",
"apiKey": "YOUR_API_KEY",
"completionOptions": {
"temperature": 0.5,
"maxTokens": 2000
}
},
{
"title": "Ollama",
"provider": "ollama",
"model": "AUTODETECT"
},
{
"title": "My Open AI Compatible Model",
"provider": "openai",
"apiBase": "http://3.3.3.3/v1",
"model": "my-openai-compatible-model",
"requestOptions": {
"headers": { "X-Auth-Token": "<API_KEY>" }
}
}
],
"tabAutocompleteModel": {
"title": "My Starcoder",
"provider": "ollama",
"model": "starcoder2:3b"
},
"embeddingsProvider": {
"provider": "openai",
"model": "text-embedding-ada-002",
"apiKey": "<API_KEY>",
"maxChunkSize": 256,
"maxBatchSize": 5
},
"reranker": {
"name": "voyage",
"params": {
"model": "rerank-2",
"apiKey": "<VOYAGE_API_KEY>"
}
}
}
```
**After**
```yaml title="config.yaml"
models:
- name: GPT-4
provider: openai
model: gpt-4
apiKey: <API_KEY>
defaultCompletionOptions:
temperature: 0.5
maxTokens: 2000
roles:
- chat
- edit
- name: My Voyage Reranker
provider: voyage
apiKey: <API_KEY>
roles:
- rerank
- name: My Starcoder
provider: ollama
model: starcoder2:3b
roles:
- autocomplete
- name: My Ada Embedder
provider: openai
apiKey: <API_KEY>
roles:
- embed
- name: Ollama Autodetect
provider: ollama
model: AUTODETECT
- name: My Open AI Compatible Model - Apply
provider: openai
model: my-openai-compatible-model
apiBase: http://3.3.3.3/v1
requestOptions:
headers:
X-Auth-Token: <API_KEY>
roles:
- chat
- apply
```
Note that the `repoMapFileSelection` experimental model role has been deprecated.
### Context Providers
The JSON `contextProviders` field is replaced by the YAML `context` array.
- JSON `name` maps to `uses`
- JSON `params` map to `with`
**Before**
```json title="config.json"
{
"contextProviders": [
{
"name": "docs"
},
{
"name": "codebase",
"params": {
"nRetrieve": 30,
"nFinal": 3
}
},
{
"name": "diff",
"params": {}
}
]
}
```
**After**
```yaml title="config.yaml"
context:
- uses: docs
- uses: codebase
with:
nRetrieve: 30
nFinal: 3
- uses: diff
```
### System Message
The `systemMessage` property has been replaced with a `rules` property that takes an array of strings.
**Before**
```json title="config.json"
{
"systemMessage": "Always give concise responses"
}
```
**After**
```yaml title="config.yaml"
rules:
- Always give concise responses
```
### Prompts
Rather than with `customCommands`, you can now use the `prompts` field to define custom prompts.
**Before**
```json title="config.json"
{
"customCommands": [
{
"name": "check",
"description": "Check for mistakes in my code",
"prompt": "{{{ input }}}\n\nPlease read the highlighted code and check for any mistakes. You should look for the following, and be extremely vigilant:\n- Syntax errors\n- Logic errors\n- Security vulnerabilities\n- Performance issues\n- Anything else that looks wrong\n\nOnce you find an error, please explain it as clearly as possible, but without using extra words. For example, instead of saying 'I think there is a syntax error on line 5', you should say 'Syntax error on line 5'. Give your answer as one bullet point per mistake found."
}
]
}
```
**After**
```yaml title="config.yaml"
prompts:
- name: check
description: Check for mistakes in my code
prompt: |
Please read the highlighted code and check for any mistakes. You should look for the following, and be extremely vigilant:
- Syntax errors
- Logic errors
- Security vulnerabilities
- Performance issues
- Anything else that looks wrong
Once you find an error, please explain it as clearly as possible, but without using extra words. For example, instead of saying 'I think there is a syntax error on line 5', you should say 'Syntax error on line 5'. Give your answer as one bullet point per mistake found.
```
### Documentation
Documentation is largely the same, but the `title` property has been replaced with `name`. The `startUrl`, `rootUrl`, and `faviconUrl` properties remain.
**Before**
```json title="config.json"
{
"docs": [
{
"startUrl": "https://docs.nestjs.com/",
"title": "nest.js"
},
{
"startUrl": "https://mysite.com/docs/",
"title": "My site"
}
]
}
```
**After**
```yaml title="config.yaml"
docs:
- name: nest.js
startUrl: https://docs.nestjs.com/
- name: My site
startUrl: https://mysite.com/docs/
```
### MCP Servers
<!-- TODO this is definitely wrong -->
**Properties:**
- `name` (**required**): The name of the MCP server.
- `command` (**required**): The command used to start the server.
- `args`: An optional array of arguments for the command.
- `env`: An optional map of environment variables for the server process.
**Before**
```json title="config.json"
{
"experimental": {
"modelContextProtocolServers": [
{
"transport": {
"type": "stdio",
"command": "uvx",
"args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"],
"env": {
"KEY": "<VALUE>"
}
}
}
]
}
}
```
**After**
```yaml title="config.yaml"
mcpServers:
- name: My MCP Server
command: uvx
args:
- mcp-server-sqlite
- --db-path
- /Users/NAME/test.db
env:
KEY: <VALUE>
```
---
## Deprecated configuration options
The following top-level fields from `config.json` have been deprecated. Most UI-related and user-specific options will move into a settings page in the UI
- Slash commands (JSON `slashCommands`)
- top-level `requestOptions`
- top-level `completionOptions`
- `tabAutocompleteOptions`
- `analytics`
- `customCommands`
- `disableSessionTitles`
- `experimental`
- `allowAnonymousTelemetry` (moved to user/IDE level)
- `ui` (moved to user/IDE level)
- `userToken`
- `disableIndexing` (moved to user/IDE level)
## New Configuration options
The YAML configuration format offers new configuration options not available in the JSON format. See the [YAML Config Reference](/yaml-reference) for more information.

321
docs/docs/yaml-reference.md Normal file
View file

@ -0,0 +1,321 @@
---
title: Config YAML Reference
description: Reference for the Continue configuration YAML file
keywords: [config, yaml, configuration, customize, customization]
---
# Config YAML Reference
<!-- TODO - data and packages sections -->
Continue can be configured using a YAML file `config.yaml` which for local configuration can be placed in your global `.continue` folder (`~/.continue` on Mac, `%USERPROFILE%\.continue`)
Below are details for each property that can be set in `config.yaml`.
:::info
Config YAML does not work alongside `config.json` - it replaces it. View the **[Migration Guide](/yaml-migration)**. `config.yaml` currently only works in VS Code pre-release.
:::
**All properties at all levels are optional unless explicitly marked as required.**
## Properties
The top-level properties in the `config.yaml` configuration file are:
- [`name`](#name) (**required**)
<!-- - [`packages`](#packages) -->
- [`version`](#version) (**required**)
- [`models`](#models)
- [`context`](#context)
- [`rules`](#rules)
- [`prompts`](#prompts)
- [`docs`](#docs)
<!-- - [`data`](#data) -->
<!-- - [`tools`](#tools) -->
- [`mcpServers`](#mcpservers)
---
### `name`
The `name` property specifies the name of your project or configuration.
```yaml title="config.yaml"
name: MyProject
```
### `version`
The `version` property specifies the version of your project or configuration.
---
### `models`
The `models` section defines the language models used in your configuration. Models are used for functionalities such as chat, editing, and summarizing.
**Properties:**
- `name` (**required**): A unique name to identify the model within your configuration.
- `provider` (**required**): The provider of the model (e.g., `openai`, `ollama`).
- `model` (**required**): The specific model name (e.g., `gpt-4`, `starcoder`).
- `roles`: An array specifying the roles this model can fulfill, such as `chat`, `autocomplete`, `embed`, `rerank`, `edit`, `apply`, `summarize`.
- `defaultCompletionOptions`: Default completion options for model settings.
**Properties:**
- `contextLength`: Maximum context length of the model, typically in tokens.
- `maxTokens`: Maximum number of tokens to generate in a completion.
- `temperature`: Controls the randomness of the completion. Values range from `0.0` (deterministic) to `1.0` (random).
- `topP`: The cumulative probability for nucleus sampling.
- `topK`: Maximum number of tokens considered at each step.
- `stop`: An array of stop tokens that will terminate the completion.
- `n`: Number of completions to generate.
- `requestOptions`: HTTP request options specific to the model.
**Properties:**
- `timeout`: Timeout for each request to the language model.
- `verifySsl`: Whether to verify SSL certificates for requests.
- `caBundlePath`: Path to a custom CA bundle for HTTP requests.
- `proxy`: Proxy URL for HTTP requests.
- `headers`: Custom headers for HTTP requests.
- `extraBodyProperties`: Additional properties to merge with the HTTP request body.
- `noProxy`: List of hostnames that should bypass the specified proxy.
- `clientCertificate`: Client certificate for HTTP requests.
- `cert`: Path to the client certificate file.
- `key`: Path to the client certificate key file.
- `passphrase`: Optional passphrase for the client certificate key file.
#### Example:
```yaml title="config.yaml"
models:
- name: GPT-4o
provider: openai
model: gpt-4o
roles:
- chat
- edit
- apply
defaultCompletionOptions:
temperature: 0.7
maxTokens: 1500
- name: Codestral
provider: mistral
model: codestral-latest
roles:
- autocomplete
```
---
### `context`
The `context` section defines context providers, which supply additional information or context to the language models. Each context provider can be configured with specific parameters.
More information about usage/params for each context provider can be found [here](/customize/context-providers)
**Properties:**
- `uses` (**required**): The identifier or name of the context provider (e.g., `code`, `docs`, `web`).
- `with`: Optional parameters to configure the context provider's behavior.
**Example:**
```yaml title="config.yaml"
context:
- uses: files
- uses: code
- uses: codebase
with:
nFinal: 10
- uses: docs
- uses: diff
- uses: folder
- uses: terminal
```
---
### `rules`
List of rules that the LLM should follow. These are inserted into the system message for all chat requests.
Example
```yaml title="config.yaml"
rules:
- Always annotate Python functions with their parameter and return types
- Always write Google style docstrings for functions and classes
```
---
### `prompts`
A list of custom prompts that can be invoked from the chat window. Each prompt has a name, description, and the actual prompt text.
```yaml title="config.yaml"
prompts:
- name: check
description: Check for mistakes in my code
prompt: |
Please read the highlighted code and check for any mistakes. You should look for the following, and be extremely vigilant:
- Syntax errors
- Logic errors
- Security vulnerabilities
```
---
### `docs`
List of documentation sites to index.
**Properties:**
- `name` (**required**): Name of the documentation site, displayed in dropdowns, etc.
- `startUrl` (**required**): Start page for crawling - usually root or intro page for docs
<!-- - `rootUrl`: Crawler will only index docs within this domain - pages that contain this URL -->
- `favicon`: URL for site favicon (default is `/favicon.ico` from `startUrl`).
- `maxDepth`: M
- `useLocalCrawling`: Force use of local crawling
Example
```yaml title="config.yaml"
docs:
- name: Continue
startUrl: https://docs.continue.dev/intro
favicon: https://docs.continue.dev/favicon.ico
```
---
<!-- ### `tools`
The `tools` section specifies external tools or APIs that can be used within your configuration.
**Properties:**
- `url` (**required**): The URL of the tool's API or endpoint.
- `apiKey`: An optional API key required by the tool.
**Example:**
```yaml title="config.yaml"
tools:
- url: https://api.exampletool.com/tool1
apiKey: YOUR_API_KEY
```
--- -->
### `mcpServers`
<!-- TODO is this correct? -->
The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports any MCP server with the MCP context provider.
**Properties:**
- `name` (**required**): The name of the MCP server.
- `command` (**required**): The command used to start the server.
- `args`: An optional array of arguments for the command.
- `env`: An optional map of environment variables for the server process.
**Example:**
```yaml title="config.yaml"
mcpServers:
- name: My MCP Server
command: uvx
args:
- mcp-server-sqlite
- --db-path
- /Users/NAME/test.db
```
<!-- ### `data`
The `data` section specifies data providers used in your configuration. Data providers supply data or resources for use in various operations.
**Properties:**
- `provider` (**required**): The name of the data provider.
**Example:**
```yaml title="config.yaml"
data:
- provider: embeddings
```
--- -->
---
## Complete YAML Config Example
Putting it all together, here's a complete example of a `config.yaml` configuration file:
```yaml title="config.yaml"
name: MyProject
version: 0.0.1
models:
- name: GPT-4
provider: openai
model: gpt-4
roles:
- chat
- edit
defaultCompletionOptions:
temperature: 0.5
maxTokens: 2000
requestOptions:
headers:
Authorization: Bearer YOUR_OPENAI_API_KEY
- name: Ollama Starcoder
provider: ollama
model: starcoder
roles:
- autocomplete
defaultCompletionOptions:
temperature: 0.3
stop:
- "\n"
rules:
- Give concise responses
- Always assume TypeScript rather than JavaScript
prompts:
- name: test
description: Unit test a function
prompt: |
Please write a complete suite of unit tests for this function. You should use the Jest testing framework. The tests should cover all possible edge cases and should be as thorough as possible. You should also include a description of each test case.
context:
- uses: diff
- uses: file
- uses: codebase
- uses: code
- uses: docs
with:
startUrl: https://docs.example.com/introduction
maxDepth: 3
mcpServers:
- name: DevServer
command: npm
args:
- run
- dev
env:
PORT: "3000"
```

View file

@ -13,7 +13,6 @@ const config = {
experimental_faster: true,
},
title: "Continue",
tagline:
"the open-source library for accelerating software development with language models",

View file

@ -58,7 +58,6 @@ toc_max_heading_level: 5
{
"title": "Continue",
"startUrl": "https://docs.continue.dev/intro",
"rootUrl": "https://docs.continue.dev",
"faviconUrl": "https://docs.continue.dev/favicon.ico",
}
]
@ -66,7 +65,7 @@ toc_max_heading_level: 5
- `title`: 文档网站的名称,用来在 UI 中进行识别。
- `startUrl`: 索引进程开始的 URL 。
- `rootUrl`: 文档网站的基本 URL ,用来确定哪个页面索引。
<!-- - `rootUrl`: 文档网站的基本 URL ,用来确定哪个页面索引。 -->
- `faviconUrl`: 网站 favicon 的 URL ,用来在 UI 中进行视觉识别。
## 使用 `useChromiumForDocsCrawling` 爬取动态生成的网站

View file

@ -233,8 +233,8 @@ List of documentation sites to index.
- `title` (**required**): Title of the documentation site, displayed in dropdowns, etc.
- `startUrl` (**required**): Start page for crawling - usually root or intro page for docs
- `rootUrl`: Crawler will only index docs within this domain - pages that contain this URL
- `maxDepth`: Maximum depth for crawling. Default `3`
<!-- - `rootUrl`: Crawler will only index docs within this domain - pages that contain this URL -->
- `maxDepth`: Maximum link depth for crawling. Default `4`
- `favicon`: URL for site favicon (default is `/favicon.ico` from `startUrl`).
Example
@ -244,7 +244,6 @@ Example
{
"title": "Continue",
"startUrl": "https://docs.continue.dev/intro",
"rootUrl": "https://docs.continue.dev",
"faviconUrl": "https://docs.continue.dev/favicon.ico",
}
]

2702
docs/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -16,10 +16,10 @@
"write-heading-ids": "docusaurus write-heading-ids"
},
"dependencies": {
"@docusaurus/core": "^3.6.3",
"@docusaurus/faster": "^3.6.3",
"@docusaurus/plugin-client-redirects": "^3.6.3",
"@docusaurus/preset-classic": "^3.6.3",
"@docusaurus/core": "^3.7.0",
"@docusaurus/faster": "^3.7.0",
"@docusaurus/plugin-client-redirects": "^3.7.0",
"@docusaurus/preset-classic": "^3.7.0",
"@mdx-js/react": "^3.0.0",
"clsx": "^2.1.0",
"prism-react-renderer": "^2.3.1",
@ -27,7 +27,7 @@
"react-dom": "^18.2.0"
},
"devDependencies": {
"@docusaurus/module-type-aliases": "^3.6.3",
"@docusaurus/module-type-aliases": "^3.7.0",
"nodemon": "^3.1.4"
},
"browserslist": {

View file

@ -138,6 +138,16 @@ const sidebars = {
label: "Reference",
href: "/reference",
},
// {
// type: "link",
// label: "YAML Reference",
// href: "/yaml-reference",
// },
// {
// type: "link",
// label: "YAML Migration",
// href: "/yaml-migration",
// },
],
};

BIN
docs/static/img/docs-form.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

BIN
docs/static/img/docs-indexes.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Some files were not shown because too many files have changed in this diff Show more