(broken) merge main

This commit is contained in:
Dallin Romney 2025-01-19 22:04:15 -08:00
commit bcb5cfd7b5
160 changed files with 4469 additions and 1543 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

2
.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"
}
},
{

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

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

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

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

@ -14,18 +14,21 @@ import Ollama from "../llm/llms/Ollama.js";
import { GlobalContext } from "../util/GlobalContext.js";
import { getConfigJsonPath } from "../util/paths.js";
import { ConfigResult } from "./load.js";
import { ConfigResult } from "@continuedev/config-yaml";
import { controlPlaneEnv } from "../control-plane/env.js";
import { usePlatform } from "../control-plane/flags.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 { localPathToUri } from "../util/pathToUri.js";
export type { ProfileDescription };
@ -57,7 +60,7 @@ export class ConfigHandler {
writeLog,
);
this.profiles = [new ProfileLifecycleManager(localProfileLoader)];
this.selectedProfileId = localProfileLoader.profileId;
this.selectedProfileId = localProfileLoader.description.id;
// Always load local profile immediately in case control plane doesn't load
try {
@ -77,39 +80,40 @@ 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());
await this.ide.openFile(localPathToUri(getConfigJsonPath()));
} else {
await this.ide.openUrl(
"https://app.continue.dev/",
// `https://app.continue.dev/workspaces/${openProfileId}/chat`,
);
await this.ide.openUrl(`${controlPlaneEnv.APP_URL}${openProfileId}`);
}
}
private async fetchControlPlaneProfiles() {
private async loadPlatformProfiles() {
// Get the profiles and create their lifecycle managers
this.controlPlaneClient
.listWorkspaces()
.then(async (workspaces) => {
.listAssistants()
.then(async (assistants) => {
this.profiles = this.profiles.filter(
(profile) => profile.profileId === "local",
(profile) => profile.profileDescription.id === "local",
);
workspaces.forEach((workspace) => {
const profileLoader = new ControlPlaneProfileLoader(
workspace.id,
workspace.name,
assistants.forEach((assistant) => {
const profileLoader = new PlatformProfileLoader(
assistant.configResult,
assistant.ownerSlug,
assistant.packageSlug,
this.controlPlaneClient,
this.ide,
this.ideSettingsPromise,
@ -141,10 +145,67 @@ export class ConfigHandler {
}
})
.catch((e) => {
console.error(e);
console.error("Failed to list assistants: ", e);
});
}
private platformProfilesRefreshInterval: NodeJS.Timeout | undefined;
private async fetchControlPlaneProfiles() {
if (usePlatform()) {
clearInterval(this.platformProfilesRefreshInterval);
await this.loadPlatformProfiles();
this.platformProfilesRefreshInterval = setInterval(
this.loadPlatformProfiles.bind(this),
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.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();

View file

@ -1,15 +1,17 @@
import { ConfigResult, ConfigValidationError } from "@continuedev/config-yaml";
import {
BrowserSerializedContinueConfig,
ContinueConfig,
IContextProvider,
} from "../index.js";
import { ConfigResult, finalToBrowserConfig } from "./load.js";
import { finalToBrowserConfig } from "./load.js";
import { IProfileLoader } from "./profile/IProfileLoader.js";
export interface ProfileDescription {
title: string;
id: string;
errors: ConfigValidationError[] | undefined;
}
export class ProfileLifecycleManager {
@ -19,19 +21,8 @@ export class ProfileLifecycleManager {
constructor(private readonly profileLoader: IProfileLoader) {}
get profileId() {
return this.profileLoader.profileId;
}
get profileTitle() {
return this.profileLoader.profileTitle;
}
get profileDescription(): ProfileDescription {
return {
title: this.profileTitle,
id: this.profileId,
};
return this.profileLoader.description;
}
clearConfig() {
@ -71,14 +62,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

View file

@ -62,6 +62,8 @@ import {
getEsbuildBinaryPath,
} from "../util/paths";
import { ConfigResult, ConfigValidationError } from "@continuedev/config-yaml";
import { usePlatform } from "../control-plane/flags";
import {
defaultContextProvidersJetBrains,
defaultContextProvidersVsCode,
@ -70,13 +72,8 @@ import {
} 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 { validateConfig } from "./validation.js";
import { localPathToUri } from "../util/pathToUri";
function resolveSerializedConfig(filepath: string): SerializedContinueConfig {
let content = fs.readFileSync(filepath, "utf8");
@ -229,7 +226,7 @@ function isModelDescription(
return (llm as ModelDescription).title !== undefined;
}
function isContextProviderWithParams(
export function isContextProviderWithParams(
contextProvider: CustomContextProvider | ContextProviderWithParams,
): contextProvider is ContextProviderWithParams {
return (contextProvider as ContextProviderWithParams).name !== undefined;
@ -582,6 +579,7 @@ function finalToBrowserConfig(
experimental: final.experimental,
docs: final.docs,
tools: final.tools,
usePlatform: usePlatform(),
};
}
@ -816,7 +814,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,17 @@ 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,
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 +48,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 +58,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,18 @@
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,
title: "Local Config",
errors: undefined,
};
constructor(
private ide: IDE,
@ -18,13 +22,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,90 @@
import { ClientConfigYaml } 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 * 60 * 15; // every 15 minutes
description: ProfileDescription;
constructor(
private configResult: ConfigResult<ClientConfigYaml>,
private readonly ownerSlug: string,
private readonly packageSlug: 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}`,
title: `${ownerSlug}/${packageSlug}`,
errors: configResult.errors,
};
setInterval(async () => {
const assistants = await this.controlPlaneClient.listAssistants();
const newConfigResult = assistants.find(
(assistant) =>
assistant.packageSlug === this.packageSlug &&
assistant.ownerSlug === this.ownerSlug,
)?.configResult;
if (!newConfigResult) {
return;
}
this.configResult = {
config: newConfigResult.config,
errors: newConfigResult.errors,
configLoadInterrupted: false,
};
this.onReload();
}, PlatformProfileLoader.RELOAD_INTERVAL);
}
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,7 @@
import fs from "fs";
import { ConfigResult, ConfigValidationError } from "@continuedev/config-yaml";
import { ClientConfigYaml } from "@continuedev/config-yaml/dist/schemas";
import {
ContinueConfig,
ContinueRcJson,
@ -15,9 +17,9 @@ 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 +27,8 @@ export default async function doLoadConfig(
controlPlaneClient: ControlPlaneClient,
writeLog: (message: string) => Promise<void>,
overrideConfigJson: SerializedContinueConfig | undefined,
overrideConfigYaml: ClientConfigYaml | undefined,
platformConfigMetadata: PlatformConfigMetadata | undefined,
workspaceId?: string,
): Promise<ConfigResult<ContinueConfig>> {
const workspaceConfigs = await getWorkspaceConfigs(ide);
@ -39,7 +43,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 +52,9 @@ export default async function doLoadConfig(
uniqueId,
writeLog,
workOsAccessToken,
undefined,
// overrideConfigYaml, TODO
overrideConfigYaml,
platformConfigMetadata,
controlPlaneClient,
);
newConfig = result.config;
errors = result.errors;

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;

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

@ -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,13 +1,12 @@
import fs from "node:fs";
import path from "path";
import {
extendConfig,
ConfigResult,
fillTemplateVariables,
resolveSecretsOnClient,
validateConfigYaml,
} from "@continuedev/config-yaml";
import { ConfigYaml } from "@continuedev/config-yaml/dist/schemas";
import { ValidationLevel } from "@continuedev/config-yaml/dist/validation";
import { ClientConfigYaml } from "@continuedev/config-yaml/dist/schemas";
import { fetchwithRequestOptions } from "@continuedev/fetch";
import * as YAML from "yaml";
@ -26,23 +25,17 @@ import { contextProviderClassFromName } from "../../context/providers/index";
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, getContinueDotEnv } 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 CodebaseContextProvider from "../../context/providers/CodebaseContextProvider";
import FileContextProvider from "../../context/providers/FileContextProvider";
import PromptFilesContextProvider from "../../context/providers/PromptFilesContextProvider";
import { ControlPlaneClient } from "../../control-plane/client";
import { llmsFromModelConfig } from "./models";
function renderTemplateVars(configYaml: string): string {
const data: Record<string, string> = {};
@ -60,36 +53,28 @@ function renderTemplateVars(configYaml: string): string {
function loadConfigYaml(
workspaceConfigs: string[],
ideSettings: IdeSettings,
ideType: IdeType,
rawYaml: string,
): ConfigResult<ConfigYaml> {
const renderedYaml = renderTemplateVars(rawYaml);
let config = YAML.parse(renderedYaml) as ConfigYaml;
overrideConfigYaml: ClientConfigYaml | undefined,
): ConfigResult<ClientConfigYaml> {
let config =
overrideConfigYaml ??
(YAML.parse(renderTemplateVars(rawYaml)) as ClientConfigYaml);
const errors = validateConfigYaml(config);
if (errors?.some((error) => error.level === ValidationLevel.Error)) {
if (errors?.some((error) => error.fatal)) {
return {
errors: errors.map((error) => ({
message: error.message,
fatal: error.level === ValidationLevel.Error,
})),
errors,
config: undefined,
configLoadInterrupted: true,
};
}
for (const workspaceConfig of workspaceConfigs) {
const rendered = renderTemplateVars(workspaceConfig);
config = extendConfig(config, YAML.parse(rendered) as ConfigYaml);
}
// Set defaults if undefined (this lets us keep config.json uncluttered for new users)
return {
config,
errors: errors.map((error) => ({
message: error.message,
fatal: error.level === ValidationLevel.Error,
fatal: error.fatal,
})),
configLoadInterrupted: false,
};
@ -113,12 +98,13 @@ async function slashCommandsFromV1PromptFiles(
}
async function configYamlToContinueConfig(
config: ConfigYaml,
config: ClientConfigYaml,
ide: IDE,
ideSettings: IdeSettings,
uniqueId: string,
writeLog: (log: string) => Promise<void>,
workOsAccessToken: string | undefined,
platformConfigMetadata: PlatformConfigMetadata | undefined,
allowFreeTrial: boolean = true,
): Promise<ContinueConfig> {
const continueConfig: ContinueConfig = {
@ -126,10 +112,24 @@ async function configYamlToContinueConfig(
models: [],
tabAutocompleteModels: [],
tools: [],
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,
})),
};
// Models
@ -146,9 +146,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 +160,8 @@ async function configYamlToContinueConfig(
uniqueId,
ideSettings,
writeLog,
platformConfigMetadata,
continueConfig.systemMessage,
);
continueConfig.tabAutocompleteModels?.push(...llms);
}
@ -181,18 +187,33 @@ async function configYamlToContinueConfig(
// TODO: Split into model roles.
// 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[];
continueConfig.contextProviders.push(...DEFAULT_CONTEXT_PROVIDERS);
// Embeddings Provider
const embedConfig = config.models?.find((model) =>
@ -283,16 +304,20 @@ export async function loadContinueConfigFromYaml(
uniqueId: string,
writeLog: (log: string) => Promise<void>,
workOsAccessToken: string | undefined,
overrideConfigYaml: string | undefined,
overrideConfigYaml: ClientConfigYaml | 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(
const configYamlResult = loadConfigYaml(
workspaceConfigs,
ideSettings,
ideType,
overrideConfigYaml ?? rawYaml,
rawYaml,
overrideConfigYaml,
);
if (!configYamlResult.config || configYamlResult.configLoadInterrupted) {
@ -303,13 +328,24 @@ export async function loadContinueConfigFromYaml(
};
}
const continueConfig = await configYamlToContinueConfig(
const configYaml = await resolveSecretsOnClient(
configYamlResult.config,
ide.readSecrets.bind(ide),
async (secretNames: string[]) => {
const secretValues = await controlPlaneClient.syncSecrets(secretNames);
await ide.writeSecrets(secretValues);
return secretValues;
},
);
const continueConfig = await configYamlToContinueConfig(
configYaml,
ide,
ideSettings,
uniqueId,
writeLog,
workOsAccessToken,
platformConfigMetadata,
);
const systemPromptDotFile = await getSystemPromptDotFile(ide);

View file

@ -3,21 +3,59 @@ import { ModelConfig } from "@continuedev/config-yaml";
import { IDE, IdeSettings, LLMOptions } from "../..";
import { BaseLLM } from "../../llm";
import { LLMClasses } from "../../llm/llms";
import ContinueProxy from "../../llm/llms/stubs/ContinueProxy";
import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader";
const AUTODETECT = "AUTODETECT";
function useContinueProxy(
model: ModelConfig,
platformConfigMetadata: PlatformConfigMetadata | undefined,
): boolean {
return !!platformConfigMetadata && model.apiKeySecret !== undefined;
}
function getModelClass(
model: ModelConfig,
platformConfigMetadata: PlatformConfigMetadata | undefined,
): (typeof LLMClasses)[number] | undefined {
if (useContinueProxy(model, platformConfigMetadata)) {
return ContinueProxy;
}
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, platformConfigMetadata);
if (!cls) {
return undefined;
}
const usingContinueProxy = useContinueProxy(model, platformConfigMetadata);
const modelName = usingContinueProxy
? getContinueProxyModelName(
platformConfigMetadata!.ownerSlug,
platformConfigMetadata!.packageSlug,
model,
)
: model.model;
let options: LLMOptions = {
...model,
completionOptions: {
@ -30,6 +68,8 @@ async function modelConfigToBaseLLM(
writeLog,
uniqueId,
title: model.name,
model: modelName,
systemMessage,
};
const llm = new cls(options);
@ -43,6 +83,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 +104,8 @@ async function autodetectModels(
uniqueId,
ideSettings,
writeLog,
platformConfigMetadata,
systemMessage,
);
}),
);
@ -78,12 +122,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 +145,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

@ -28,6 +28,8 @@ class DocsContextProvider extends BaseContextProvider {
constructor(options: any) {
super(options);
const docsService = DocsService.getSingleton();
docsService?.setGithubToken(this.options?.githubToken);
}
private async _rerankChunks(
@ -178,6 +180,10 @@ class DocsContextProvider extends BaseContextProvider {
const canUsePreindexedDocs = await docsService.canUsePreindexedDocs();
if (canUsePreindexedDocs) {
for (const { startUrl, title } of Object.values(preIndexedDocs)) {
// Skip if overridden in config
if (docs.find((d) => d.startUrl === startUrl)) {
continue;
}
submenuItemsMap.set(startUrl, {
title,
id: startUrl,

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

@ -1,5 +1,7 @@
import { v4 as uuidv4 } from "uuid";
import { controlPlaneEnv } from "../env";
const CLIENT_ID = "client_01J0FW6XN8N2XJAECF7NE0Y65J";
// const CLIENT_ID = "client_01J0FW6XCPMJMQ3CG51RB4HBZQ"; // Staging
@ -8,7 +10,7 @@ export async function getAuthUrlForTokenPage(): Promise<string> {
const params = {
response_type: "code",
client_id: CLIENT_ID,
redirect_uri: "https://app.continue.dev/tokens/callback",
redirect_uri: `${controlPlaneEnv.APP_URL}tokens/callback`,
// redirect_uri: "http://localhost:3000/tokens/callback",
state: uuidv4(),
provider: "authkit",

View file

@ -1,8 +1,10 @@
import { ConfigJson } from "@continuedev/config-types";
import { ClientConfigYaml } from "@continuedev/config-yaml/dist/schemas/index.js";
import fetch, { RequestInit, Response } from "node-fetch";
import { ModelDescription } from "../index.js";
import { ConfigResult } from "@continuedev/config-yaml";
import { controlPlaneEnv } from "./env.js";
export interface ControlPlaneSessionInfo {
@ -85,6 +87,29 @@ export class ControlPlaneClient {
}
}
public async listAssistants(): Promise<
{
configResult: ConfigResult<ClientConfigYaml>;
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 [];
}
}
async getSettingsForWorkspace(workspaceId: string): Promise<ConfigJson> {
const userId = await this.userId;
if (!userId) {
@ -96,4 +121,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,3 +1,6 @@
import { readUsePlatform } from "../util/paths";
import { usePlatform } from "./flags";
interface ControlPlaneEnv {
DEFAULT_CONTROL_PLANE_PROXY_URL: string;
CONTROL_PLANE_URL: string;
@ -21,7 +24,7 @@ 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 STAGING_ENV: ControlPlaneEnv = {
@ -31,7 +34,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 +50,20 @@ 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"
function getControlPlaneEnv(): ControlPlaneEnv {
const usePlatformFileEnv = readUsePlatform();
const env = usePlatformFileEnv || process.env.CONTROL_PLANE_ENV;
return env === "local"
? LOCAL_ENV
: process.env.CONTROL_PLANE_ENV === "staging"
: env === "staging"
? STAGING_ENV
: PRODUCTION_ENV;
: env === "test" || usePlatform()
? TEST_ENV
: PRODUCTION_ENV;
}
export const controlPlaneEnv = getControlPlaneEnv();

View file

@ -0,0 +1,13 @@
import { readUsePlatform, usePlatformPathExists } from "../util/paths";
export function usePlatform(): boolean {
return usePlatformPathExists();
}
export function getEnvFromUsePlatformFile(): string | undefined {
const contents = readUsePlatform();
if (contents && contents.trim().length > 0) {
return contents.trim();
}
return undefined;
}

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 { usePlatform } from "./control-plane/flags";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
import type { IMessenger, Message } from "./protocol/messenger";
@ -103,6 +111,7 @@ export class Core {
const ideSettingsPromise = messenger.request("getIdeSettings", undefined);
const sessionInfoPromise = messenger.request("getControlPlaneSessionInfo", {
silent: true,
useOnboarding: usePlatform(),
});
this.controlPlaneClient = new ControlPlaneClient(sessionInfoPromise);
@ -124,7 +133,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,
});
});
@ -378,7 +387,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 +404,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 +440,7 @@ export class Core {
const chunk = next.value;
yield { content: chunk };
yield chunk;
next = await gen.next();
}
@ -448,7 +457,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 +471,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 +494,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 +562,7 @@ export class Core {
abortedMessageIds: Set<string>,
msg: Message<ToCoreProtocol["command/run"][0]>,
messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>,
) {
): AsyncGenerator<string> {
const {
input,
history,
@ -613,7 +627,7 @@ export class Core {
break;
}
if (content) {
yield { content };
yield content;
}
}
} catch (e) {
@ -621,7 +635,6 @@ export class Core {
} finally {
clearInterval(checkActiveInterval);
}
yield { done: true, content: "" };
}
on("command/run", (msg) =>
runNodeJsSlashCommand(
@ -652,7 +665,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 +680,8 @@ export class Core {
abortedMessageIds.delete(msg.messageId);
break;
}
yield { content: diffLine };
yield diffLine;
}
return { done: true };
}
on("streamDiffLines", (msg) =>

48
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 DocsIndexingDetails {
@ -314,11 +308,17 @@ export interface CompletionOptions extends BaseCompletionOptions {
export type ChatMessageRole = "user" | "assistant" | "system" | "tool";
export interface MessagePart {
type: "text" | "imageUrl";
text?: string;
imageUrl?: { url: string };
}
export type TextMessagePart = {
type: "text";
text: string;
};
export type ImageMessagePart = {
type: "imageUrl";
imageUrl: { url: string };
};
export type MessagePart = TextMessagePart | ImageMessagePart;
export type MessageContent = string | MessagePart[];
@ -468,6 +468,7 @@ export interface LLMOptions {
writeLog?: (str: string) => Promise<void>;
llmRequestHook?: (model: string, prompt: string) => any;
apiKey?: string;
apiKeySecret?: string;
aiGatewaySlug?: string;
apiBase?: string;
cacheBehavior?: CacheBehavior;
@ -691,6 +692,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[]>;
@ -862,6 +868,13 @@ export interface Tool {
uri?: string;
}
interface ToolChoice {
type: "function";
function: {
name: string;
};
}
export interface BaseCompletionOptions {
temperature?: number;
topP?: number;
@ -879,6 +892,7 @@ export interface BaseCompletionOptions {
stream?: boolean;
prediction?: Prediction;
tools?: Tool[];
toolChoice?: ToolChoice;
}
export interface ModelCapability {
@ -890,6 +904,7 @@ export interface ModelDescription {
provider: string;
model: string;
apiKey?: string;
apiKeySecret?: string;
apiBase?: string;
contextLength?: number;
maxStopWords?: number;
@ -1206,6 +1221,7 @@ export interface BrowserSerializedContinueConfig {
analytics?: AnalyticsConfig;
docs?: SiteIndexingConfig[];
tools: Tool[];
usePlatform: boolean;
}
// DOCS SUGGESTIONS AND PACKAGE INFO
@ -1243,9 +1259,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

@ -105,28 +105,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

@ -26,9 +26,12 @@ import {
} from "../../util/paths";
import { Telemetry } from "../../util/posthog";
import { ConfigResult } from "../../config/load";
import { Article, chunkArticle, pageToArticle } from "./article";
import DocsCrawler from "./DocsCrawler";
import {
ArticleWithChunks,
htmlPageToArticleWithChunks,
markdownPageToArticleWithChunks,
} from "./article";
import DocsCrawler, { DocsCrawlerType, PageData } from "./crawlers/DocsCrawler";
import { runLanceMigrations, runSqliteMigrations } from "./migrations";
import {
downloadFromS3,
@ -37,6 +40,7 @@ import {
SiteIndexingResults,
} from "./preIndexed";
import preIndexedDocs from "./preIndexedDocs";
import { ConfigResult } from "@continuedev/config-types";
// Purposefully lowercase because lancedb converts
export interface LanceDbDocsRow {
@ -74,8 +78,6 @@ export type AddParams = {
- delete
- reindex all
- add/index one
- Currently a full reindex deletes all docs rather than storing PER embeddings provider
- The last successful embeddings provider is stored in global context and updated AFTER an indexing process is successful
*/
export default class DocsService {
static lanceTableName = "docs";
@ -93,8 +95,8 @@ export default class DocsService {
private config!: ContinueConfig;
private sqliteDb?: Database;
private docsCrawler!: DocsCrawler;
private ideInfoPromise: Promise<IdeInfo>;
private githubToken?: string;
constructor(
configHandler: ConfigHandler,
@ -105,6 +107,10 @@ export default class DocsService {
this.isInitialized = this.init(configHandler);
}
setGithubToken(token: string) {
this.githubToken = token;
}
// Singleton pattern: only one service globally
private static instance?: DocsService;
static createSingleton(
@ -197,6 +203,7 @@ export default class DocsService {
}
}
// Used to check periodically during indexing if should cancel indexing
shouldCancel(startUrl: string, startedWithEmbedder: string) {
// Check if aborted
const isAborted = this.statuses.get(startUrl)?.status === "aborted";
@ -216,21 +223,6 @@ export default class DocsService {
return false;
}
// NOTE Pausing not supported for docs yet
// setPaused(startUrl: string, pause: boolean) {
// const status = this.statuses.get(startUrl);
// if (status) {
// this.handleStatusUpdate({
// ...status,
// status: pause ? "paused" : "indexing",
// });
// }
// }
// isPaused(startUrl: string) {
// return this.statuses.get(startUrl)?.status === "paused";
// }
/*
* Currently, we generate and host embeddings for pre-indexed docs using transformers.
* However, we don't ship transformers with the JetBrains extension.
@ -252,14 +244,29 @@ export default class DocsService {
return isPreIndexedDocsProvider && !canUsePreindexedDocs;
}
async getEmbeddingsProvider(isPreIndexedDoc: boolean = false): Promise<ILLM> {
const canUsePreindexedDocs = await this.canUsePreindexedDocs();
// Determines if using preIndexed and returns proper embeddings provider
async getEmbeddingsProvider(startUrl: string) {
// Conditions for using a pre-indexed doc
if (canUsePreindexedDocs && isPreIndexedDoc) {
return DocsService.preIndexedDocsEmbeddingsProvider;
// Must be in pre indexed docs file
const preIndexedDoc = preIndexedDocs[startUrl];
if (preIndexedDoc) {
// Most not be overriden by config
if (!this.config?.docs?.find((doc) => doc.startUrl === startUrl)) {
// Must be supported
const canUsePreindexedDocs = await this.canUsePreindexedDocs();
if (canUsePreindexedDocs) {
return {
provider: DocsService.preIndexedDocsEmbeddingsProvider,
isPreindexed: true,
};
}
}
}
return this.config.embeddingsProvider;
return {
provider: this.config.embeddingsProvider,
isPreindexed: false,
};
}
private async handleConfigUpdate({
@ -269,8 +276,6 @@ export default class DocsService {
const oldConfig = this.config;
this.config = newConfig; // IMPORTANT - need to set up top, other methods below use this without passing it in
this.docsCrawler = new DocsCrawler(this.ide, newConfig);
if (this.config.disableIndexing) {
return;
}
@ -366,16 +371,13 @@ export default class DocsService {
console.warn("Attempting to add/index docs when indexing is disabled");
return;
}
const { startUrl } = siteIndexingConfig;
const { startUrl, useLocalCrawling, maxDepth } = siteIndexingConfig;
const canUsePreindexedDocs = await this.canUsePreindexedDocs();
if (canUsePreindexedDocs) {
const preIndexedDoc = preIndexedDocs[startUrl];
const isPreIndexedDoc = !!preIndexedDoc;
if (isPreIndexedDoc) {
console.warn("Can not override pre-indexed start urls");
return;
}
const { isPreindexed, provider } =
await this.getEmbeddingsProvider(startUrl);
if (isPreindexed) {
console.warn("Attempted to indexAndAdd pre-indexed doc");
return;
}
// Queue - indexAndAdd is invoked circularly by config edits. This prevents duplicate runs
@ -383,8 +385,7 @@ export default class DocsService {
return;
}
const embeddingsProvider = await this.getEmbeddingsProvider();
const startedWithEmbedder = this.config.embeddingsProvider.embeddingId;
const startedWithEmbedder = provider.embeddingId;
const indexExists = await this.hasMetadata(startUrl);
// Build status update - most of it is fixed values
@ -394,7 +395,7 @@ export default class DocsService {
> = {
type: "docs",
id: siteIndexingConfig.startUrl,
embeddingsProviderId: embeddingsProvider.embeddingId,
embeddingsProviderId: provider.embeddingId,
isReindexing: reIndex && indexExists,
title: siteIndexingConfig.title,
debugInfo: `max depth: ${siteIndexingConfig.maxDepth}`,
@ -430,47 +431,81 @@ export default class DocsService {
progress: 0,
});
const articles: Article[] = [];
// Crawl pages to get page data
const pages: PageData[] = [];
let processedPages = 0;
let estimatedProgress = 0;
let done = false;
let usedCrawler: DocsCrawlerType | undefined = undefined;
// Crawl pages and retrieve info as articles
for await (const page of this.docsCrawler.crawl(new URL(startUrl))) {
estimatedProgress += 1 / 2 ** (processedPages + 1);
const docsCrawler = new DocsCrawler(
this.ide,
this.config,
maxDepth,
undefined,
useLocalCrawling,
this.githubToken,
);
const crawlerGen = docsCrawler.crawl(new URL(startUrl));
// NOTE - during "indexing" phase, check if aborted before each status update
if (this.shouldCancel(startUrl, startedWithEmbedder)) {
return;
while (!done) {
const result = await crawlerGen.next();
if (result.done) {
done = true;
usedCrawler = result.value;
} else {
const page = result.value;
estimatedProgress += 1 / 2 ** (processedPages + 1);
// NOTE - during "indexing" phase, check if aborted before each status update
if (this.shouldCancel(startUrl, startedWithEmbedder)) {
return;
}
this.handleStatusUpdate({
...fixedStatus,
description: `Finding subpages (${page.path})`,
status: "indexing",
progress:
0.15 * estimatedProgress +
Math.min(0.35, (0.35 * processedPages) / 500),
// For the first 50%, 15% is sum of series 1/(2^n) and the other 35% is based on number of files/ 500 max
});
pages.push(page);
processedPages++;
// Locks down GUI if no sleeping
// Wait proportional to how many docs are indexing
const toWait = 100 * this.docsIndexingQueue.size + 50;
await new Promise((resolve) => setTimeout(resolve, toWait));
}
this.handleStatusUpdate({
...fixedStatus,
description: `Finding subpages (${page.path})`,
status: "indexing",
progress:
0.15 * estimatedProgress +
Math.min(0.35, (0.35 * processedPages) / 500),
// For the first 50%, 15% is sum of series 1/(2^n) and the other 35% is based on number of files/ 500 max
});
const article = pageToArticle(page);
if (!article) {
continue;
}
articles.push(article);
processedPages++;
// Locks down GUI if no sleeping
// Wait proportional to how many docs are indexing
const toWait = 100 * this.docsIndexingQueue.size + 50;
await new Promise((resolve) => setTimeout(resolve, toWait));
}
void Telemetry.capture("docs_pages_crawled", {
count: processedPages,
});
// Chunk pages based on which crawler was used
const articles: ArticleWithChunks[] = [];
const chunks: Chunk[] = [];
const articleChunker =
usedCrawler === "github"
? markdownPageToArticleWithChunks
: htmlPageToArticleWithChunks;
for (const page of pages) {
const articleWithChunks = await articleChunker(
page,
provider.maxEmbeddingChunkSize,
);
if (articleWithChunks) {
articles.push(articleWithChunks);
}
const toWait = 20 * this.docsIndexingQueue.size + 10;
await new Promise((resolve) => setTimeout(resolve, toWait));
}
// const chunks: Chunk[] = [];
const embeddings: number[][] = [];
// Create embeddings of retrieved articles
@ -483,35 +518,26 @@ export default class DocsService {
this.handleStatusUpdate({
...fixedStatus,
status: "indexing",
description: `Creating Embeddings: ${article.subpath}`,
description: `Creating Embeddings: ${article.article.subpath}`,
progress: 0.5 + 0.3 * (i / articles.length), // 50% -> 80%
});
try {
const chunkedArticle = chunkArticle(
article,
embeddingsProvider.maxEmbeddingChunkSize,
const subpathEmbeddings = await provider.embed(
article.chunks.map((c) => c.content),
);
const chunkedArticleContents = chunkedArticle.map(
(chunk) => chunk.content,
);
chunks.push(...chunkedArticle);
const subpathEmbeddings = await embeddingsProvider.embed(
chunkedArticleContents,
);
chunks.push(...article.chunks);
embeddings.push(...subpathEmbeddings);
const toWait = 100 * this.docsIndexingQueue.size + 50;
await new Promise((resolve) => setTimeout(resolve, toWait));
} catch (e) {
console.warn("Error chunking article: ", e);
console.warn("Error embedding article chunks: ", e);
}
}
if (embeddings.length === 0) {
console.error(
`No embeddings were created for site: ${siteIndexingConfig.startUrl}\n Num chunks: ${chunks.length}`,
`No embeddings were created for site: ${startUrl}\n Num chunks: ${chunks.length}`,
);
if (this.shouldCancel(startUrl, startedWithEmbedder)) {
@ -519,7 +545,7 @@ export default class DocsService {
}
this.handleStatusUpdate({
...fixedStatus,
description: `No embeddings were created for site: ${siteIndexingConfig.startUrl}`,
description: `No embeddings were created for site: ${startUrl}`,
status: "failed",
progress: 1,
});
@ -585,10 +611,19 @@ export default class DocsService {
providers: ["docs"],
});
} catch (e) {
let description = `Error getting docs from: ${siteIndexingConfig.startUrl}`;
if (e instanceof Error) {
if (
e.message.includes("github.com") &&
e.message.includes("rate limit")
) {
description = "Github rate limit exceeded";
}
}
console.error("Error indexing docs", e);
this.handleStatusUpdate({
...fixedStatus,
description: `Error getting docs from: ${siteIndexingConfig.startUrl}`,
description,
status: "failed",
progress: 1,
});
@ -601,11 +636,12 @@ export default class DocsService {
// And pre-indexed embeddings are supported
// Fetch pre-indexed embeddings from S3, add to Lance, and then search those
private async fetchAndAddPreIndexedDocEmbeddings(title: string) {
const embeddingsProvider = await this.getEmbeddingsProvider(true);
const data = await downloadFromS3(
S3Buckets.continueIndexedDocs,
getS3Filename(embeddingsProvider.embeddingId, title),
getS3Filename(
DocsService.preIndexedDocsEmbeddingsProvider.embeddingId,
title,
),
);
const siteEmbeddings = JSON.parse(data) as SiteIndexingResults;
@ -646,19 +682,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);
}
private lanceDBRowToChunk(row: LanceDbDocsRow): Chunk {
@ -678,15 +713,15 @@ export default class DocsService {
const db = await this.getOrCreateSqliteDb();
try {
const { isPreindexed, provider } = await this.getEmbeddingsProvider(startUrl);
const preIndexedDoc = preIndexedDocs[startUrl];
const isPreIndexedDoc = !!preIndexedDoc;
const embeddingsProvider =
await this.getEmbeddingsProvider(isPreIndexedDoc);
const result = await db.get(
`SELECT startUrl, title, favicon FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`,
startUrl,
embeddingsProvider.embeddingId,
provider.embeddingId,
);
if (!result) {
@ -700,7 +735,7 @@ export default class DocsService {
const table = await this.getOrCreateLanceTable({
initializationVector: [],
isPreIndexedDoc,
startUrl,
});
const rows = (await table
.filter(`starturl = '${startUrl}'`)
@ -725,15 +760,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[] = [];
@ -748,18 +781,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(this.lanceDBRowToChunk);
@ -851,13 +880,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 {
@ -882,7 +908,10 @@ export default class DocsService {
}
}
} else {
newDocs.push(doc);
const currentStatus = this.statuses.get(doc.startUrl);
if (currentStatus?.status !== "failed") {
newDocs.push(doc);
}
}
}
@ -946,10 +975,7 @@ export default class DocsService {
return name.replace(/[^a-zA-Z0-9_.-]/g, "_");
}
private async getLanceTableName(isPreIndexedDoc: boolean) {
const embeddingsProvider =
await this.getEmbeddingsProvider(isPreIndexedDoc);
private async getLanceTableName(embeddingsProvider: ILLM) {
const tableName = this.sanitizeLanceTableName(
`${DocsService.lanceTableName}${embeddingsProvider.embeddingId}`,
);
@ -959,15 +985,16 @@ export default class DocsService {
private async getOrCreateLanceTable({
initializationVector,
isPreIndexedDoc,
startUrl,
}: {
initializationVector: number[];
isPreIndexedDoc?: boolean;
startUrl: string;
}) {
const conn = await lancedb.connect(getLanceDbPath());
const tableNames = await conn.tableNames();
const { provider } = await this.getEmbeddingsProvider(startUrl);
const tableNameFromEmbeddingsProvider =
await this.getLanceTableName(!!isPreIndexedDoc);
await this.getLanceTableName(provider);
if (!tableNames.includes(tableNameFromEmbeddingsProvider)) {
if (initializationVector) {
@ -998,16 +1025,16 @@ export default class DocsService {
embeddings,
}: AddParams) {
const sampleVector = embeddings[0];
const isPreIndexedDoc = !!preIndexedDocs[siteIndexingConfig.startUrl];
const { startUrl } = siteIndexingConfig;
const table = await this.getOrCreateLanceTable({
isPreIndexedDoc,
startUrl,
initializationVector: sampleVector,
});
const rows: LanceDbDocsRow[] = chunks.map((chunk, i) => ({
vector: embeddings[i],
starturl: siteIndexingConfig.startUrl,
starturl: startUrl,
title: chunk.otherMetadata?.title || siteIndexingConfig.title,
content: chunk.content,
path: chunk.filepath,
@ -1032,16 +1059,24 @@ export default class DocsService {
);
}
private siteIndexingConfigsAreEqual(
config1: SiteIndexingConfig,
config2: SiteIndexingConfig,
) {
return (
config1.startUrl === config2.startUrl &&
config1.faviconUrl === config2.faviconUrl &&
config1.title === config2.title &&
config1.maxDepth === config2.maxDepth &&
config1.useLocalCrawling === config2.useLocalCrawling
);
}
private addToConfig(siteIndexingConfig: SiteIndexingConfig) {
// Handles the case where a user has manually added the doc to config.json
// so it already exists in the file
const doesEquivalentDocExist = this.config.docs?.some(
(doc) =>
doc.startUrl === siteIndexingConfig.startUrl &&
doc.faviconUrl === siteIndexingConfig.faviconUrl &&
siteIndexingConfig.title === doc.title,
// siteIndexingConfig.maxDepth === doc.maxDepth &&
// doc.rootUrl === siteIndexingConfig.rootUrl,
const doesEquivalentDocExist = this.config.docs?.some((doc) =>
this.siteIndexingConfigsAreEqual(doc, siteIndexingConfig),
);
if (!doesEquivalentDocExist) {
@ -1099,7 +1134,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

@ -1,13 +1,11 @@
import { URL } from "node:url";
// @ts-ignore
// @prettier-ignore
import { ContinueConfig, IDE } from "../..";
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";
import CheerioCrawler from "./CheerioCrawler";
import { ChromiumCrawler, ChromiumInstaller } from "./ChromiumCrawler";
import { DefaultCrawler } from "./DefaultCrawler";
import GitHubCrawler from "./GitHubCrawler";
export type PageData = {
url: string;
@ -15,14 +13,19 @@ export type PageData = {
content: string;
};
export type DocsCrawlerType = "default" | "cheerio" | "chromium" | "github";
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,
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);
}
@ -34,33 +37,47 @@ class DocsCrawler {
);
}
/*
Returns the type of crawler used in the end
*/
async *crawl(
startUrl: URL,
maxRequestsPerCrawl: number = this.MAX_REQUESTS_PER_CRAWL,
): AsyncGenerator<PageData, undefined, undefined> {
): AsyncGenerator<PageData, DocsCrawlerType, undefined> {
if (startUrl.host === this.GITHUB_HOST) {
yield* new GitHubCrawler(startUrl).crawl();
return;
yield* new GitHubCrawler(startUrl, this.githubToken).crawl();
return "github";
}
try {
const pageData = await new DefaultCrawler(startUrl).crawl();
if (pageData.length > 0) {
yield* pageData;
return;
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);
}
} catch (e) {
console.error("Default crawler failed, trying backup: ", e);
}
if (this.shouldUseChromium()) {
yield* new ChromiumCrawler(startUrl, maxRequestsPerCrawl).crawl();
yield* new ChromiumCrawler(
startUrl,
this.maxRequestsPerCrawl,
this.maxDepth,
).crawl();
return "chromium";
} else {
let didCrawlSinglePage = false;
for await (const pageData of new CheerioCrawler(
startUrl,
maxRequestsPerCrawl,
this.maxRequestsPerCrawl,
this.maxDepth,
).crawl()) {
yield pageData;
didCrawlSinglePage = true;
@ -84,9 +101,16 @@ class DocsCrawler {
`Successfully installed Chromium! Retrying crawl of: ${startUrl.toString()}`,
);
yield* new ChromiumCrawler(startUrl, maxRequestsPerCrawl).crawl();
yield* new ChromiumCrawler(
startUrl,
this.maxRequestsPerCrawl,
this.maxDepth,
).crawl();
return "chromium";
}
}
return "cheerio";
}
}
}

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;
apiKeySecret?: 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.apiKeySecret = options.apiKeySecret;
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,33 @@ 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;
private actualApiKey?: string;
constructor(options: LLMOptions) {
super(options);
this.actualApiBase = options.apiBase;
this.actualApiKey = options.apiKey;
}
static providerName = "continue-proxy";
static defaultOptions: Partial<LLMOptions> = {
useLegacyCompletionsEndpoint: false,
};
protected extraBodyProperties(): Record<string, any> {
return {
continueProperties: {
apiKey: this.actualApiKey,
apiBase: this.actualApiBase,
apiKeySecret: this.apiKeySecret,
},
};
}
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.11",
"@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.11",
"resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.11.tgz",
"integrity": "sha512-E3RBQfNEPBGBmlnAbCXgeAasDzTjo4ON/HH0hr5g292i+WdAN3i/omjQ6Iusx00L1Fz7klZGJePZ3GVQKOGEUg==",
"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.11",
"@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,
@ -15,6 +13,7 @@ import type {
LLMFullCompletionOptions,
ModelDescription,
ModelRoles,
PromptLog,
RangeInFile,
SerializedContinueConfig,
Session,
@ -22,28 +21,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"
@ -121,7 +100,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
historyIndex: number;
selectedCode: RangeInFile[];
},
ProtocolGeneratorType<string>,
AsyncGenerator<string>,
];
"llm/complete": [
{
@ -138,7 +117,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
completionOptions: LLMFullCompletionOptions;
title: string;
},
ProtocolGeneratorType<string>,
AsyncGenerator<string>,
];
"llm/streamChat": [
{
@ -146,7 +125,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
completionOptions: LLMFullCompletionOptions;
title: string;
},
ProtocolGeneratorType<ChatMessage>,
AsyncGenerator<ChatMessage, PromptLog>,
];
streamDiffLines: [
{
@ -157,7 +136,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
language: string | undefined;
modelTitle: string | undefined;
},
ProtocolGeneratorType<DiffLine>,
AsyncGenerator<DiffLine>,
];
"chatDescriber/describe": [
{

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

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

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

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,18 @@ export function getPathToRemoteConfig(remoteConfigServerUrl: string): string {
return dir;
}
export function internalBetaPathExists(): boolean {
const sPath = path.join(getContinueGlobalPath(), ".internal_beta");
export function usePlatformPathExists(): boolean {
const sPath = path.join(getContinueGlobalPath(), ".use_platform");
return fs.existsSync(sPath);
}
export function readUsePlatform(): string | undefined {
const sPath = path.join(getContinueGlobalPath(), ".use_platform");
if (fs.existsSync(sPath)) {
return fs.readFileSync(sPath, "utf8");
}
}
export function getConfigJsonPathForRemote(
remoteConfigServerUrl: string,
): string {

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

@ -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,7 +246,6 @@ Example
{
"title": "Continue",
"startUrl": "https://docs.continue.dev/intro",
"rootUrl": "https://docs.continue.dev",
"faviconUrl": "https://docs.continue.dev/favicon.ico",
}
]

View file

@ -14,7 +14,7 @@ See also
- [JSON Continue Config Reference](/reference)
- [YAML Continue Config Reference](/yaml-reference)
### 1. Create YAML file
## 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`.
@ -25,14 +25,14 @@ name: my-configuration
version: 0.0.1
```
### 2. Map Models
### 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`
- `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]`
@ -103,46 +103,56 @@ models:
- name: GPT-4
provider: openai
model: gpt-4
apiKey: <API_KEY>
defaultCompletionOptions:
temperature: 0.5
maxTokens: 2000'
roles: [chat, edit]
apiKey: <API_KEY>
maxTokens: 2000
roles:
- chat
- edit
- name: My Voyage Reranker
provider: voyage
roles: rerank
apiKey: <API_KEY>
roles:
- rerank
- name: My Starcoder
provider: ollama
model: starcoder2:3b
roles: autocomplete
roles:
- autocomplete
- name: My Ada Embedder
provider: openai
roles: embed
apiKey: <API_KEY>
roles:
- embed
- name: Ollama Autodetect
provider: ollama
model: AUTODETECT
- name: My Open AI Compatible Model - Apply
provider: openai
apiBase: http://3.3.3.3/v1
model: my-openai-compatible-model
apiBase: http://3.3.3.3/v1
requestOptions:
headers:
X-Auth-Token: <API_KEY>
roles: [chat, apply]
roles:
- chat
- apply
```
Note that the `repoMapFileSelection` experimental model role has been deprecated.
### 3. Map Context Providers
### Context Providers
The JSON `contextProviders` and `docs` fields are replaced by the YAML `context` array.
The JSON `contextProviders` field is replaced by the YAML `context` array.
- JSON `name` maps to `uses`
- JSON `params` map to `with`
- Use multiple `docs` entries rather than the array of docs in the JSON format
<!-- TODO is this docs not correct ?^ -->
**Before**
@ -150,10 +160,7 @@ The JSON `contextProviders` and `docs` fields are replaced by the YAML `context`
{
"contextProviders": [
{
"name": "docs",
"params": {
"startUrl": "https://docs.continue.dev/intro"
}
"name": "docs"
},
{
"name": "codebase",
@ -166,7 +173,86 @@ The JSON `contextProviders` and `docs` fields are replaced by the YAML `context`
"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/",
@ -183,23 +269,15 @@ The JSON `contextProviders` and `docs` fields are replaced by the YAML `context`
**After**
```yaml title="config.yaml"
context:
- uses: docs
with:
startUrl: https://docs.nestjs.com/
title: nest.js
- uses: docs
with:
startUrl: https://mysite.com/docs/
title: My Site
- uses: codebase
with:
nRetrieve: 30
nFinal: 3
- uses: diff
docs:
- name: nest.js
startUrl: https://docs.nestjs.com/
- name: My site
startUrl: https://mysite.com/docs/
```
## Map MCP Servers
### MCP Servers
<!-- TODO this is definitely wrong -->
@ -220,7 +298,10 @@ context:
"transport": {
"type": "stdio",
"command": "uvx",
"args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"]
"args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"],
"env": {
"KEY": "<VALUE>"
}
}
}
]
@ -238,13 +319,15 @@ mcpServers:
- 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
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`
@ -257,7 +340,6 @@ The following top-level fields from `config.json` have been deprecated
- `allowAnonymousTelemetry` (moved to user/IDE level)
- `ui` (moved to user/IDE level)
- `userToken`
- `systemMessage`
- `disableIndexing` (moved to user/IDE level)
## New Configuration options

View file

@ -28,6 +28,7 @@ The top-level properties in the `config.yaml` configuration file are:
- [`models`](#models)
- [`context`](#context)
- [`rules`](#rules)
- [`prompts`](#prompts)
- [`docs`](#docs)
<!-- - [`data`](#data) -->
<!-- - [`tools`](#tools) -->
@ -153,6 +154,23 @@ rules:
---
### `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.
@ -161,8 +179,10 @@ List of documentation sites to index.
- `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
<!-- - `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
@ -170,15 +190,12 @@ Example
docs:
- name: Continue
startUrl: https://docs.continue.dev/intro
rootUrl: https://docs.continue.dev
favicon: https://docs.continue.dev/favicon.ico
```
---
### `tools`
<!-- TODO how does this actually work -->
<!-- ### `tools`
The `tools` section specifies external tools or APIs that can be used within your configuration.
@ -195,7 +212,7 @@ tools:
apiKey: YOUR_API_KEY
```
---
--- -->
### `mcpServers`
@ -247,6 +264,7 @@ Putting it all together, here's a complete example of a `config.yaml` configurat
```yaml title="config.yaml"
name: MyProject
version: 0.0.1
models:
- name: GPT-4
@ -261,6 +279,7 @@ models:
requestOptions:
headers:
Authorization: Bearer YOUR_OPENAI_API_KEY
- name: Ollama Starcoder
provider: ollama
model: starcoder
@ -271,18 +290,26 @@ models:
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
rootUrl: https://docs.example.com
maxDepth: 3
tools:
- url: https://api.exampletool.com
apiKey: YOUR_TOOL_API_KEY
mcpServers:
- name: DevServer
command: npm

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

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

BIN
docs/static/img/docs-indexing-peek.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

View file

@ -5,7 +5,7 @@
<option name="SCRIPT_PATH" value="" />
<option name="SCRIPT_OPTIONS" value="" />
<option name="INDEPENDENT_SCRIPT_WORKING_DIRECTORY" value="true" />
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$/../../binary" />
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$/binary" />
<option name="INDEPENDENT_INTERPRETER_PATH" value="true" />
<option name="INTERPRETER_PATH" value="" />
<option name="INTERPRETER_OPTIONS" value="" />

View file

@ -5,7 +5,7 @@
<option name="SCRIPT_PATH" value="" />
<option name="SCRIPT_OPTIONS" value="" />
<option name="INDEPENDENT_SCRIPT_WORKING_DIRECTORY" value="true" />
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$/../../gui" />
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$/gui" />
<option name="INDEPENDENT_INTERPRETER_PATH" value="true" />
<option name="INTERPRETER_PATH" value="/bin/zsh" />
<option name="INTERPRETER_OPTIONS" value="" />

View file

@ -152,6 +152,8 @@ This will generate a .zip file in `./build/distributions` with the version defin
The e2e tests are written using [intellij-ui-test-robot](`https://github.com/JetBrains/intellij-ui-test-robot`). The
README for this project has a lot of helpful info on how to use the library.
Note that these tests fully take control of your mouse while executing.
#### Setup
If you are on macOS, you'll need to give IntelliJ permission to control your computer in order to run the e2e tests.
@ -174,7 +176,18 @@ to run.
#### Identifying selectors
While the `runIdeForUiTests` task is runnung, you can visit the following URL
While the `runIdeForUiTests` task is running, you can visit the following URL
to view the UI hierarchy of the running IDE:
http://127.0.0.1:8082/
http://127.0.0.1:8082/
#### Rebuilding the extension
To rebuild the extension with the latest source code, run the following:
```sh
./gradlew buildPlugin
```
This will update the contents of the extension that is loaded into the test IDE from
`build/idea-sandbox/plugins-uiTest/continue-intellij-extension`

View file

@ -47,6 +47,22 @@ dependencies {
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.9.2")
testImplementation("com.squareup.okhttp3:logging-interceptor:4.12.0")
implementation("com.automation-remarks:video-recorder-junit5:2.0")
// Exclude vulnerable Log4j from all dependencies
configurations.all {
resolutionStrategy {
eachDependency {
if (requested.group == "log4j" && requested.name == "log4j") {
useTarget("org.slf4j:log4j-over-slf4j:1.7.36")
}
}
}
}
// Add Log4j 2.x explicitly
implementation("org.apache.logging.log4j:log4j-core:2.20.0")
implementation("org.apache.logging.log4j:log4j-api:2.20.0")
}
// Set the JVM language level used to build the project. Use Java 11 for 2020.3+, and Java 17 for
@ -105,13 +121,10 @@ tasks {
wrapper { gradleVersion = properties("gradleVersion").get() }
patchPluginXml {
version = properties("pluginVersion")
sinceBuild = properties("pluginSinceBuild")
untilBuild = properties("pluginUntilBuild")
// Extract the <!-- Plugin description --> section from README.md and provide for the plugin's
// manifest
pluginDescription =
version.set(properties("pluginVersion"))
sinceBuild.set(properties("pluginSinceBuild"))
untilBuild.set(properties("pluginUntilBuild"))
pluginDescription.set(
providers.fileContents(layout.projectDirectory.file("README.md")).asText.map {
val start = "<!-- Plugin description -->"
val end = "<!-- Plugin description end -->"
@ -125,6 +138,7 @@ tasks {
subList(indexOf(start) + 1, indexOf(end)).joinToString("\n").let(::markdownToHTML)
}
}
)
}
// Configure UI tests plugin
@ -149,9 +163,9 @@ tasks {
// This is to ensure we load the GUI with OSR enabled. We have logic that
// renders with OSR disabled below a particular IDE version.
// See ContinueExtensionSettingsService.kt for more info.
intellij {
version.set("2024.1")
}
// intellij {
// version.set("2024.1")
// }
}
signPlugin {

View file

@ -53,6 +53,7 @@ class MessageTypes {
// Note: If updating these values, make a corresponding update in
// core/protocol/passThrough.ts
val PASS_THROUGH_TO_WEBVIEW = listOf(
"configError",
"configUpdate",
"getDefaultModelTitle",
"indexProgress", // Codebase

View file

@ -58,10 +58,10 @@ class CoreMessengerManager(
private fun setupCoreMessenger(continueCorePath: String) {
coreMessenger = CoreMessenger(project, continueCorePath, ideProtocolClient, coroutineScope)
coreMessenger?.request("config/getSerializedProfileInfo", null, null) { resp ->
val data = resp as? Map<String, Any>
val profileInfo = data?.get("config") as? Map<String, Any>
val allowAnonymousTelemetry = profileInfo?.get("allowAnonymousTelemetry") as? Boolean
coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response ->
val result = (response as Map<String, Any>)["result"] as Map<String, Any>
val config = result["config"] as Map<String, Any>
val allowAnonymousTelemetry = config?.get("allowAnonymousTelemetry") as? Boolean
val telemetryService = service<TelemetryService>()
if (allowAnonymousTelemetry == true || allowAnonymousTelemetry == null) {
telemetryService.setup(getMachineUniqueID())

View file

@ -439,7 +439,8 @@ class IdeProtocolClient(
null,
null
) { response ->
val config = (response as Map<String, Any>)["config"] as Map<String, Any>
val result = (response as Map<String, Any>)["result"] as Map<String, Any>
val config = result["config"] as Map<String, Any>
val applyCodeBlockModel = getModelByRole(config, "applyCodeBlock")
if (applyCodeBlockModel != null) {

View file

@ -128,11 +128,14 @@ fun openInlineEdit(project: Project?, editor: Editor) {
// Get list of model titles
val continuePluginService = project.service<ContinuePluginService>()
val modelTitles = mutableListOf<String>()
continuePluginService.coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response ->
val config = response as Map<String, Any>
val models = (config["config"] as Map<String, Any>)["models"] as List<Map<String, Any>>
val result = (response as Map<String, Any>)["result"] as Map<String, Any>
val config = result["config"] as Map<String, Any>
val models = config["models"] as List<Map<String, Any>>
modelTitles.addAll(models.map { it["title"] as String })
}
val maxWaitTime = 200
val startTime = System.currentTimeMillis()
while (modelTitles.isEmpty() && System.currentTimeMillis() - startTime < maxWaitTime) {
@ -427,7 +430,7 @@ class CustomPanel(
}
selectedIndex =
if(itemCount == 0) -1 else continueSettingsService.continueState.lastSelectedInlineEditModel?.let {
if (itemCount == 0) -1 else continueSettingsService.continueState.lastSelectedInlineEditModel?.let {
if (modelTitles.isEmpty()) -1
else {
val index = modelTitles.indexOf(it)

View file

@ -34,7 +34,7 @@ class Autocomplete {
@AfterEach
fun closeProject(remoteRobot: RemoteRobot) = CommonSteps(remoteRobot).closeProject()
// @Test
@Test
@Video
fun displayCompletion(remoteRobot: RemoteRobot): Unit = with(remoteRobot) {
welcomeFrame {
@ -50,7 +50,7 @@ class Autocomplete {
// Our "continue_tutorial.java.ft" tab loads first, but then "Main.java" takes focus.
waitFor(ofSeconds(20)) {
findAll<ComponentFixture>(
byXpath("//div[@accessiblename='Main.java' and @class='EditorTabLabel']")
byXpath("//div[@accessiblename='Main.java' and @class='SingleHeightLabel']")
).isNotEmpty()
}
@ -64,7 +64,7 @@ class Autocomplete {
enterText(" ")
}
waitFor(ofSeconds(10)) {
waitFor(ofSeconds(20)) {
editor.hasText("TEST_LLM_RESPONSE_0")
}
}

View file

@ -39,7 +39,7 @@ class GUI {
@AfterEach
fun closeProject(remoteRobot: RemoteRobot) = CommonSteps(remoteRobot).closeProject()
// @Test
// @Test
@Video
fun highlightCode(remoteRobot: RemoteRobot): Unit = with(remoteRobot) {
welcomeFrame {
@ -57,7 +57,7 @@ class GUI {
// while the `continue_tutorial.java` is loading.
waitFor(ofSeconds(20)) {
findAll<ComponentFixture>(
byXpath("//div[@accessiblename='Main.java' and @class='EditorTabLabel']")
byXpath("//div[@accessiblename='Main.java' and @class='SingleHeightLabel']")
).isNotEmpty()
}

View file

@ -35,7 +35,7 @@ class Onboarding {
fun closeProject(remoteRobot: RemoteRobot) = CommonSteps(remoteRobot).closeProject()
// @Test
// @Test
@Video
fun onboarding(remoteRobot: RemoteRobot): Unit = with(remoteRobot) {
welcomeFrame {
@ -53,7 +53,7 @@ class Onboarding {
// So we need to wait for that to occur, and then focus on "continue_tutorial.java.ft"
waitFor(ofSeconds(20)) {
findAll<ComponentFixture>(
byXpath("//div[@accessiblename='Main.java' and @class='EditorTabLabel']")
byXpath("//div[@accessiblename='Main.java' and @class='SingleHeightLabel']")
).isNotEmpty()
}

View file

@ -23,4 +23,6 @@ e2e/.test-extensions
e2e/storage
e2e/vsix
e2e/test-continue/*
!e2e/test-continue/config.json
!e2e/test-continue/config.json
e2e/test-continue-yaml/*
!e2e/test-continue-yaml/config.yaml

View file

@ -2389,7 +2389,7 @@
"if": {
"properties": {
"name": {
"enum": ["codebase", "folder", "docs"]
"enum": ["codebase", "folder"]
}
}
},
@ -2420,6 +2420,46 @@
}
}
},
{
"if": {
"properties": {
"name": {
"enum": ["docs"]
}
}
},
"then": {
"properties": {
"params": {
"properties": {
"nRetrieve": {
"title": "N Retrieve",
"description": "Number of docs results to initially retrieve from vector database",
"default": 50,
"type": "integer"
},
"nFinal": {
"title": "N Final",
"description": "Final number of docs results to include after re-ranking",
"default": 10,
"type": "integer"
},
"useReranking": {
"title": "Use Reranking",
"description": "Whether to use re-ranking, which will allow initial selection of nRetrieve results, then will use an LLM to select the top nFinal results. Disabling re-ranking will give faster, but less accurate, results.",
"default": true,
"type": "boolean"
},
"githubToken": {
"type": "string",
"title": "Github Token",
"description": "Include to crawl Github repositories for documentation"
}
}
}
}
}
},
{
"if": {
"properties": {
@ -2563,17 +2603,17 @@
"type": "string",
"description": "The starting URL for indexing the documentation"
},
"rootUrl": {
"type": "string",
"description": "The root URL of the documentation site"
},
"maxDepth": {
"type": "integer",
"description": "The maximum depth to crawl the documentation site"
"description": "The maximum link depth when crawling the documentation site"
},
"faviconUrl": {
"type": "string",
"description": "The URL path to a favicon for the site - by default, it will be `/favicon.ico` path from the Start URL"
},
"useLocalCrawling": {
"type": "boolean",
"description": "Only use local crawling for this documentation site"
}
},
"required": ["title", "startUrl"]

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