Merge branch 'preview' into dev

This commit is contained in:
Nate Sesti 2024-08-07 10:37:45 -04:00
commit e2a4a2cf09
21 changed files with 406 additions and 151 deletions

19
.vscode/launch.json vendored
View file

@ -139,5 +139,24 @@
"NODE_OPTIONS": "--experimental-vm-modules"
}
}
// {
// "name": "[openai-adapters] Jest Test Debugger, Current Open File",
// "type": "node",
// "request": "launch",
// "runtimeArgs": [
// "--inspect-brk",
// "${workspaceRoot}/packages/openai-adapters/node_modules/jest/bin/jest.js",
// "--runInBand",
// "--config",
// "${workspaceRoot}/packages/openai-adapters/jest.config.mjs",
// "${relativeFile}"
// ],
// "cwd": "${workspaceRoot}/packages/openai-adapters",
// "console": "integratedTerminal",
// "internalConsoleOptions": "neverOpen",
// "env": {
// "NODE_OPTIONS": "--experimental-vm-modules"
// }
// }
]
}

View file

@ -36,6 +36,7 @@ import CustomLLMClass from "../llm/llms/CustomLLM.js";
import FreeTrial from "../llm/llms/FreeTrial.js";
import { llmFromDescription } from "../llm/llms/index.js";
import { execSync } from "child_process";
import CodebaseContextProvider from "../context/providers/CodebaseContextProvider.js";
import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider.js";
import { fetchwithRequestOptions } from "../util/fetchWithOptions.js";
@ -61,7 +62,7 @@ import {
getPromptFiles,
slashCommandFromPromptFile,
} from "./promptFile.js";
import { execSync } from "child_process";
function resolveSerializedConfig(filepath: string): SerializedContinueConfig {
let content = fs.readFileSync(filepath, "utf8");
const config = JSONC.parse(content) as unknown as SerializedContinueConfig;

View file

@ -1,3 +1,4 @@
import { BaseContextProvider } from "../";
import {
Chunk,
ContextItem,
@ -9,7 +10,6 @@ import {
import DocsService from "../../indexing/docs/DocsService";
import preIndexedDocs from "../../indexing/docs/preIndexedDocs";
import { Telemetry } from "../../util/posthog";
import { BaseContextProvider } from "../";
class DocsContextProvider extends BaseContextProvider {
static nRetrieve = 30;
@ -108,9 +108,8 @@ class DocsContextProvider extends BaseContextProvider {
});
}
const embeddingsProvider = await docsService.getEmbeddingsProvider(
!!preIndexedDoc,
);
const embeddingsProvider =
await docsService.getEmbeddingsProvider(!!preIndexedDoc);
const [vector] = await embeddingsProvider.embed([extras.fullInput]);

View file

@ -1,3 +1,8 @@
import { open, type Database } from "sqlite";
import sqlite3 from "sqlite3";
import lancedb, { Connection } from "vectordb";
import { ConfigHandler } from "../../config/ConfigHandler.js";
import DocsContextProvider from "../../context/providers/DocsContextProvider.js";
import {
Chunk,
ContinueConfig,
@ -6,13 +11,19 @@ import {
IndexingProgressUpdate,
SiteIndexingConfig,
} from "../../index.js";
import { FromCoreProtocol, ToCoreProtocol } from "../../protocol/index.js";
import { GlobalContext } from "../../util/GlobalContext.js";
import { IMessenger } from "../../util/messenger.js";
import {
editConfigJson,
getDocsSqlitePath,
getLanceDbPath,
} from "../../util/paths.js";
import { Telemetry } from "../../util/posthog.js";
import TransformersJsEmbeddingsProvider from "../embeddings/TransformersJsEmbeddingsProvider.js";
import { Article, chunkArticle, pageToArticle } from "./article.js";
import { crawlPage } from "./crawl.js";
import { runLanceMigrations, runSqliteMigrations } from "./migrations.js";
import {
downloadFromS3,
getS3Filename,
@ -20,17 +31,6 @@ import {
SiteIndexingResults,
} from "./preIndexed.js";
import preIndexedDocs from "./preIndexedDocs.js";
import TransformersJsEmbeddingsProvider from "../embeddings/TransformersJsEmbeddingsProvider.js";
import { ConfigHandler } from "../../config/ConfigHandler.js";
import lancedb, { Connection } from "vectordb";
import { GlobalContext } from "../../util/GlobalContext.js";
import DocsContextProvider from "../../context/providers/DocsContextProvider.js";
import { open, type Database } from "sqlite";
import sqlite3 from "sqlite3";
import { Telemetry } from "../../util/posthog.js";
import { runSqliteMigrations, runLanceMigrations } from "./migrations.js";
import { IMessenger } from "../../util/messenger.js";
import { ToCoreProtocol, FromCoreProtocol } from "../../protocol/index.js";
// Purposefully lowercase because lancedb converts
export interface LanceDbDocsRow {
@ -522,9 +522,8 @@ export default class DocsService {
private async getLanceTableNameFromEmbeddingsProvider(
isPreIndexedDoc: boolean,
) {
const embeddingsProvider = await this.getEmbeddingsProvider(
isPreIndexedDoc,
);
const embeddingsProvider =
await this.getEmbeddingsProvider(isPreIndexedDoc);
const embeddingsProviderId = this.removeInvalidLanceTableNameChars(
embeddingsProvider.id,
);

View file

@ -1,6 +1,6 @@
import ignore, { Ignore } from "ignore";
import path from "node:path";
import { FileType, IDE } from "../index.d.js";
import ignore, { Ignore } from "ignore";
import {
DEFAULT_IGNORE_DIRS,
DEFAULT_IGNORE_FILETYPES,
@ -105,17 +105,18 @@ class DFSWalker {
if (ignoreFilesInDir.length === 0) {
return parentIgnore;
}
const patterns = ignoreFilesInDir.map(c => {
return c.split(/\r?\n/)
.map((l) => l.trim())
.filter((l) => !/^#|^$/.test(l));
}).flat();
const patterns = ignoreFilesInDir
.map((c) => {
return c
.split(/\r?\n/)
.map((l) => l.trim())
.filter((l) => !/^#|^$/.test(l));
})
.flat();
return ignore().add(parentIgnore).add(patterns);
}
private async loadIgnoreFiles(
entries: WalkableEntry[],
): Promise<string[]> {
private async loadIgnoreFiles(entries: WalkableEntry[]): Promise<string[]> {
const ignoreEntries = entries.filter((w) => this.isIgnoreFile(w.entry));
const promises = ignoreEntries.map(async (w) => {
return await this.ide.readFile(w.absPath);
@ -128,10 +129,7 @@ class DFSWalker {
return this.ignoreFileNames.has(p);
}
private shouldInclude(
walkableEntry: WalkableEntry,
ignore: Ignore,
) {
private shouldInclude(walkableEntry: WalkableEntry, ignore: Ignore) {
if (this.entryIsSymlink(walkableEntry.entry)) {
// If called from the root, a symlink either links to a real file in this repository,
// and therefore will be walked OR it linksto something outside of the repository and

View file

@ -1,99 +1,108 @@
import {
BedrockRuntimeClient,
ConverseStreamCommand,
} from "@aws-sdk/client-bedrock-runtime";
import { fromIni } from "@aws-sdk/credential-providers";
import {
ChatMessage,
CompletionOptions,
LLMOptions,
MessageContent,
ModelProvider,
} from "../../index.js";
import { stripImages } from "../images.js";
import { BaseLLM } from "../index.js";
class Bedrock extends BaseLLM {
private static PROFILE_NAME: string = "bedrock";
static providerName: ModelProvider = "bedrock";
static defaultOptions: Partial<LLMOptions> = {
region: "us-east-1",
model: "anthropic.claude-3-sonnet-20240229-v1:0",
contextLength: 200_000,
};
constructor(options: LLMOptions) {
super(options);
if (!options.apiBase) {
this.apiBase = `https://bedrock-runtime.${options.region}.amazonaws.com`;
}
BedrockRuntimeClient,
ConverseStreamCommand,
} from "@aws-sdk/client-bedrock-runtime";
import { fromIni } from "@aws-sdk/credential-providers";
import {
ChatMessage,
CompletionOptions,
LLMOptions,
MessageContent,
ModelProvider,
} from "../../index.js";
import { stripImages } from "../images.js";
import { BaseLLM } from "../index.js";
class Bedrock extends BaseLLM {
private static PROFILE_NAME: string = "bedrock";
static providerName: ModelProvider = "bedrock";
static defaultOptions: Partial<LLMOptions> = {
region: "us-east-1",
model: "anthropic.claude-3-sonnet-20240229-v1:0",
contextLength: 200_000,
};
constructor(options: LLMOptions) {
super(options);
if (!options.apiBase) {
this.apiBase = `https://bedrock-runtime.${options.region}.amazonaws.com`;
}
protected async *_streamComplete(
prompt: string,
options: CompletionOptions,
): AsyncGenerator<string> {
const messages = [{ role: "user" as const, content: prompt }];
for await (const update of this._streamChat(messages, options)) {
yield stripImages(update.content);
}
}
protected async *_streamComplete(
prompt: string,
options: CompletionOptions,
): AsyncGenerator<string> {
const messages = [{ role: "user" as const, content: prompt }];
for await (const update of this._streamChat(messages, options)) {
yield stripImages(update.content);
}
protected async *_streamChat(
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const credentials = await this._getCredentials();
const client = new BedrockRuntimeClient({
region: this.region,
credentials: {
accessKeyId: credentials.accessKeyId,
secretAccessKey: credentials.secretAccessKey,
sessionToken: credentials.sessionToken || "",
},
});
const input = this._generateConverseInput(messages, options);
const command = new ConverseStreamCommand(input);
const response = await client.send(command);
if (response.stream) {
for await (const chunk of response.stream) {
if (chunk.contentBlockDelta?.delta?.text) {
yield { role: "assistant", content: chunk.contentBlockDelta.delta.text };
}
}
protected async *_streamChat(
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const credentials = await this._getCredentials();
const client = new BedrockRuntimeClient({
region: this.region,
credentials: {
accessKeyId: credentials.accessKeyId,
secretAccessKey: credentials.secretAccessKey,
sessionToken: credentials.sessionToken || "",
},
});
const input = this._generateConverseInput(messages, options);
const command = new ConverseStreamCommand(input);
const response = await client.send(command);
if (response.stream) {
for await (const chunk of response.stream) {
if (chunk.contentBlockDelta?.delta?.text) {
yield {
role: "assistant",
content: chunk.contentBlockDelta.delta.text,
};
}
}
}
private _generateConverseInput(messages: ChatMessage[], options: CompletionOptions): any {
const convertedMessages = this._convertMessages(messages);
return {
modelId: options.model,
messages: convertedMessages,
system: this.systemMessage ? [{ text: this.systemMessage }] : undefined,
inferenceConfig: {
maxTokens: options.maxTokens,
temperature: options.temperature,
topP: options.topP,
stopSequences: options.stop?.filter((stop) => stop.trim() !== ""),
},
};
}
private _convertMessages(messages: ChatMessage[]): any[] {
return messages.filter((message)=>message.role!=="system").map((message) => ({
}
private _generateConverseInput(
messages: ChatMessage[],
options: CompletionOptions,
): any {
const convertedMessages = this._convertMessages(messages);
return {
modelId: options.model,
messages: convertedMessages,
system: this.systemMessage ? [{ text: this.systemMessage }] : undefined,
inferenceConfig: {
maxTokens: options.maxTokens,
temperature: options.temperature,
topP: options.topP,
stopSequences: options.stop?.filter((stop) => stop.trim() !== ""),
},
};
}
private _convertMessages(messages: ChatMessage[]): any[] {
return messages
.filter((message) => message.role !== "system")
.map((message) => ({
role: message.role,
content: this._convertMessageContent(message.content),
}));
}
private _convertMessageContent(messageContent: MessageContent): any[] {
if (typeof messageContent === "string") {
return [{ text: messageContent }];
}
private _convertMessageContent(messageContent: MessageContent): any[] {
if (typeof messageContent === "string") {
return [{ text: messageContent }];
}
return messageContent.map((part) => {
return messageContent
.map((part) => {
if (part.type === "text") {
return { text: part.text };
}
@ -108,21 +117,22 @@ import {
};
}
return null;
}).filter(Boolean);
}
private async _getCredentials() {
try {
return await fromIni({
profile: Bedrock.PROFILE_NAME,
})();
} catch (e) {
console.warn(
`AWS profile with name ${Bedrock.PROFILE_NAME} not found in ~/.aws/credentials, using default profile`,
);
return await fromIni()();
}
})
.filter(Boolean);
}
private async _getCredentials() {
try {
return await fromIni({
profile: Bedrock.PROFILE_NAME,
})();
} catch (e) {
console.warn(
`AWS profile with name ${Bedrock.PROFILE_NAME} not found in ~/.aws/credentials, using default profile`,
);
return await fromIni()();
}
}
export default Bedrock;
}
export default Bedrock;

View file

@ -104,13 +104,13 @@ class OpenAI extends BaseLLM {
this.maxStopWords !== undefined
? options.stop?.slice(0, this.maxStopWords)
: url.host === "api.deepseek.com"
? options.stop?.slice(0, 16)
: url.port === "1337" ||
url.host === "api.openai.com" ||
url.host === "api.groq.com" ||
this.apiType === "azure"
? options.stop?.slice(0, 4)
: options.stop,
? options.stop?.slice(0, 16)
: url.port === "1337" ||
url.host === "api.openai.com" ||
url.host === "api.groq.com" ||
this.apiType === "azure"
? options.stop?.slice(0, 4)
: options.stop,
};
return finalOptions;
@ -139,7 +139,7 @@ class OpenAI extends BaseLLM {
return completion;
}
private _getEndpoint(
protected _getEndpoint(
endpoint: "chat/completions" | "completions" | "models",
) {
if (this.apiType === "azure") {

30
core/llm/llms/Vllm.ts Normal file
View file

@ -0,0 +1,30 @@
import { LLMOptions, ModelProvider } from "../../index.js";
import OpenAI from "./OpenAI.js";
class Vllm extends OpenAI {
constructor(options: LLMOptions) {
super(options);
this._setupCompletionOptions();
}
private _setupCompletionOptions() {
this.fetch(this._getEndpoint("models"), {
method: "GET",
headers: this._getHeaders(),
}).then(async (response) => {
if (response.status !== 200) {
console.warn(
"Error calling vLLM /models endpoint: ",
await response.text(),
);
return;
}
const json = await response.json();
const data = json.data;
this.model = data.id;
this.contextLength = Number.parseInt(data.max_model_len);
});
}
}
export default Vllm;

View file

@ -5,9 +5,11 @@ import {
LLMOptions,
ModelDescription,
} from "../..";
import { renderTemplatedString } from "../../promptFiles/renderTemplatedString";
import { DEFAULT_MAX_TOKENS } from "../constants";
import { BaseLLM } from "../index";
import Anthropic from "./Anthropic";
import Azure from "./Azure";
import Bedrock from "./Bedrock";
import Cloudflare from "./Cloudflare";
import Cohere from "./Cohere";
@ -25,16 +27,14 @@ import LlamaCpp from "./LlamaCpp";
import Llamafile from "./Llamafile";
import Mistral from "./Mistral";
import Msty from "./Msty";
import Azure from "./Azure";
import Ollama from "./Ollama";
import OpenAI from "./OpenAI";
import Replicate from "./Replicate";
import SageMaker from "./SageMaker";
import TextGenWebUI from "./TextGenWebUI";
import Together from "./Together";
import ContinueProxy from "./stubs/ContinueProxy";
import WatsonX from "./WatsonX";
import SageMaker from "./SageMaker";
import { renderTemplatedString } from "../../promptFiles/renderTemplatedString";
import ContinueProxy from "./stubs/ContinueProxy";
const LLMs = [
Anthropic,

View file

@ -12,6 +12,7 @@ OpenAI compatible servers
- [LocalAI](https://localai.io/basics/getting_started/)
- [llama-cpp-python](https://github.com/abetlen/llama-cpp-python#web-server)
- [TensorRT-LLM](https://github.com/NVIDIA/trt-llm-as-openai-windows?tab=readme-ov-file#examples)
- [vLLM](https://docs.vllm.ai/en/latest/serving/openai_compatible_server.html) [^1]
OpenAI compatible APIs
@ -40,4 +41,7 @@ To force usage of `chat/completions` instead of `completions` endpoint you can s
"useLegacyCompletionsEndpoint": false
```
[^1]: Use the [Vllm Model Provider](./vllm.md) instead.
[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/OpenAI.ts)

View file

@ -0,0 +1,22 @@
# vLLM
Run the OpenAI-compatible server by vLLM using `vllm serve`. See their [server documentation](https://docs.vllm.ai/en/latest/serving/openai_compatible_server.html) and the [engine arguments documentation](https://docs.vllm.ai/en/latest/models/engine_args.html).
```shell
vllm serve NousResearch/Meta-Llama-3-8B-Instruct --max-model-len 1024
```
The continue implementation uses [OpenAI](./openai.md) under the hood and automatically selects the available model. You only need to set the `apiBase` like this:
```json title="~/.continue/config.json"
{
"models": [
{
"title": "My vLLM OpenAI-compatible server",
"apiBase": "http://localhost:8000/v1"
}
]
}
```
[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Vllm.ts)

View file

@ -49,7 +49,7 @@ _You can also use other commercial chat models by adding them to your `config.js
## Autocomplete
You likely want to use a model that is 1-15B parameters for autocomplete.
You likely want to use a model that is 1-15B parameters for autocomplete. You can read more about it [here](../features/tab-autocomplete.md#tab-autocomplete-beta)
### Commercial LLMs

View file

@ -1489,6 +1489,46 @@
}
},
"allOf": [
{
"if": {
"properties": {
"name": {
"enum": ["docs"]
}
}
},
"then": {
"properties": {
"params": {
"properties": {
"sites": {
"type": "array",
"items": {
"type": "object",
"properties": {
"title": {
"type": "string"
},
"startUrl": {
"type": "string"
},
"rootUrl": {
"type": "string"
},
"maxDepth": {
"type": "integer"
}
},
"required": ["title", "startUrl"]
}
}
},
"required": ["sites"]
}
},
"required": ["params"]
}
},
{
"if": {
"properties": {

View file

@ -1489,6 +1489,46 @@
}
},
"allOf": [
{
"if": {
"properties": {
"name": {
"enum": ["docs"]
}
}
},
"then": {
"properties": {
"params": {
"properties": {
"sites": {
"type": "array",
"items": {
"type": "object",
"properties": {
"title": {
"type": "string"
},
"startUrl": {
"type": "string"
},
"rootUrl": {
"type": "string"
},
"maxDepth": {
"type": "integer"
}
},
"required": ["title", "startUrl"]
}
}
},
"required": ["sites"]
}
},
"required": ["params"]
}
},
{
"if": {
"properties": {

View file

@ -1489,6 +1489,46 @@
}
},
"allOf": [
{
"if": {
"properties": {
"name": {
"enum": ["docs"]
}
}
},
"then": {
"properties": {
"params": {
"properties": {
"sites": {
"type": "array",
"items": {
"type": "object",
"properties": {
"title": {
"type": "string"
},
"startUrl": {
"type": "string"
},
"rootUrl": {
"type": "string"
},
"maxDepth": {
"type": "integer"
}
},
"required": ["title", "startUrl"]
}
}
},
"required": ["sites"]
}
},
"required": ["params"]
}
},
{
"if": {
"properties": {

View file

@ -1646,6 +1646,55 @@
}
},
"allOf": [
{
"if": {
"properties": {
"name": {
"enum": [
"docs"
]
}
}
},
"then": {
"properties": {
"params": {
"properties": {
"sites": {
"type": "array",
"items": {
"type": "object",
"properties": {
"title": {
"type": "string"
},
"startUrl": {
"type": "string"
},
"rootUrl": {
"type": "string"
},
"maxDepth": {
"type": "integer"
}
},
"required": [
"title",
"startUrl"
]
}
}
},
"required": [
"sites"
]
}
},
"required": [
"params"
]
}
},
{
"if": {
"properties": {

View file

@ -259,6 +259,9 @@ export class VsCodeExtension {
const indexer = await this.core.codebaseIndexerPromise;
indexer.refreshFile(filepath);
}
// Reindex the workspaces
this.core.invoke("index/forceReIndex", undefined);
});
// When GitHub sign-in status changes, reload config

View file

@ -1,12 +1,12 @@
import { ContinueConfig, QuickActionConfig } from "core";
import { Telemetry } from "core/util/posthog";
import * as vscode from "vscode";
import { QuickEditShowParams } from "../../../quickEdit/QuickEditQuickPick";
import {
CONTINUE_WORKSPACE_KEY,
getContinueWorkspaceConfig,
} from "../../../util/workspaceConfig";
import { isTutorialFile } from "./TutorialCodeLensProvider";
import { Telemetry } from "core/util/posthog";
import { QuickEditShowParams } from "../../../quickEdit/QuickEditQuickPick";
export const ENABLE_QUICK_ACTIONS_KEY = "enableQuickActions";

View file

@ -1,6 +1,6 @@
import { ContinueConfig, IDE } from "core";
import { QuickPickItem, window } from "vscode";
import { fetchwithRequestOptions } from "core/util/fetchWithOptions";
import { QuickPickItem, window } from "vscode";
export async function getContextProviderItems({
contextProviders,

View file

@ -1,3 +1,4 @@
import { ChevronDownIcon, ChevronUpIcon } from "@heroicons/react/24/outline";
import { SiteIndexingConfig } from "core";
import { usePostHog } from "posthog-js/react";
import { useContext, useLayoutEffect, useRef, useState } from "react";
@ -5,7 +6,6 @@ import { useDispatch } from "react-redux";
import { Button, HelperText, Input, lightGray } from "..";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { setShowDialog } from "../../redux/slices/uiStateSlice";
import { ChevronDownIcon, ChevronUpIcon } from "@heroicons/react/24/outline";
const DEFAULT_MAX_DEPTH = 3;

View file

@ -1,6 +1,7 @@
import {
ArrowPathIcon,
BarsArrowDownIcon,
CubeIcon,
HandThumbDownIcon,
HandThumbUpIcon,
TrashIcon,