diff --git a/.changes/extensions/vscode/v0.8.2.md b/.changes/extensions/vscode/v0.8.2.md new file mode 100644 index 000000000..40ada41a6 --- /dev/null +++ b/.changes/extensions/vscode/v0.8.2.md @@ -0,0 +1,8 @@ +## v0.8.2 - 2024-01-23 +### Added +* Add codellama and gemini to free trial, using new server +* Local codebase syncing and embeddings using LanceDB +* Improved VS Code theme matching +### Changed +* Updates to packaging to download native modules for current platform (lancedb, sqlite, onnxruntime, tree-sitter wasms) +* Context providers now run from the extension side (in Node.js instead of browser javascript) diff --git a/.changes/unreleased/Added-20240111-194246.yaml b/.changes/unreleased/Added-20240111-194246.yaml deleted file mode 100644 index e5d80f8f1..000000000 --- a/.changes/unreleased/Added-20240111-194246.yaml +++ /dev/null @@ -1,4 +0,0 @@ -project: extensions/vscode -kind: Added -body: Add codellama and gemini to free trial, using new server -time: 2024-01-11T19:42:46.155127-08:00 diff --git a/.changes/unreleased/Added-20240124-222904.yaml b/.changes/unreleased/Added-20240124-222904.yaml new file mode 100644 index 000000000..b2fe1ca0f --- /dev/null +++ b/.changes/unreleased/Added-20240124-222904.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Image support +time: 2024-01-24T22:29:04.193864-08:00 diff --git a/.changes/unreleased/Added-20240129-210550.yaml b/.changes/unreleased/Added-20240129-210550.yaml new file mode 100644 index 000000000..bcadeee63 --- /dev/null +++ b/.changes/unreleased/Added-20240129-210550.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Full-text search index for retrieval +time: 2024-01-29T21:05:50.216548-08:00 diff --git a/.changes/unreleased/Added-20240130-123143.yaml b/.changes/unreleased/Added-20240130-123143.yaml new file mode 100644 index 000000000..419c65e6b --- /dev/null +++ b/.changes/unreleased/Added-20240130-123143.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Docs context provider +time: 2024-01-30T12:31:43.521306-08:00 diff --git a/.changes/unreleased/Added-20240130-130332.yaml b/.changes/unreleased/Added-20240130-130332.yaml new file mode 100644 index 000000000..75bd1ca2e --- /dev/null +++ b/.changes/unreleased/Added-20240130-130332.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: CodeLlama-70b support +time: 2024-01-30T13:03:32.287428-08:00 diff --git a/.changes/unreleased/Fixed-20240130-130315.yaml b/.changes/unreleased/Fixed-20240130-130315.yaml new file mode 100644 index 000000000..ddc4186b8 --- /dev/null +++ b/.changes/unreleased/Fixed-20240130-130315.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Fixed +body: Fixed proxy setting in config.json +time: 2024-01-30T13:03:15.8294-08:00 diff --git a/.changie.yaml b/.changie.yaml index 1a7be016e..de6d6890d 100644 --- a/.changie.yaml +++ b/.changie.yaml @@ -26,10 +26,6 @@ newlines: envPrefix: CHANGIE_ projects: - - label: server - key: server - changelog: server/CHANGELOG.md - - label: extensions/intellij key: extensions/intellij changelog: extensions/intellij/CHANGELOG.md diff --git a/.continueignore b/.continueignore index 4f17aba35..1086d8297 100644 --- a/.continueignore +++ b/.continueignore @@ -1,2 +1,3 @@ **/*.run.xml -archive/**/* \ No newline at end of file +archive/**/* +extensions/vscode/models/**/* \ No newline at end of file diff --git a/.gitignore b/.gitignore index c993dc808..f8d2c8a18 100644 --- a/.gitignore +++ b/.gitignore @@ -149,4 +149,7 @@ codeql **/**/build continue_server.build -continue_server.dist \ No newline at end of file +continue_server.dist + +Icon +Icon? \ No newline at end of file diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 767734ec5..758820fa5 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -102,8 +102,9 @@ { "label": "install-all-dependencies", "type": "shell", + "windows": { "command": "./install-dependencies.ps1" }, "command": "./install-dependencies.sh", - "problemMatcher": [] // Empty so users are not promted to select progress reporting + "problemMatcher": [] // Empty so users are not prompted to select progress reporting }, // // Start the React App for debugging with Vite diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1ec49117d..036e5734b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -11,6 +11,7 @@ - [Environment Setup](#environment-setup) - [Writing Slash Commands](#writing-slash-commands) - [Writing Context Providers](#writing-context-providers) + - [Adding an LLM Provider](#adding-an-llm-provider) - [Adding Models](#adding-models) - [📐 Continue Architecture](#-continue-architecture) - [Continue VS Code Extension](#continue-vs-code-extension) @@ -56,7 +57,7 @@ Continue is continuously improving, but a feature isn't complete until it is ref VS Code is assumed for development as Continue is primarily a VS Code tool at the moment. Most of the setup and running is automated through VS Code tasks and launch configurations. -Pre-requisite: you will need `cargo` the rust package manager installed ([get it on rust-lang.org](https://www.rust-lang.org/tools/install)). + 1. Clone and open in VS Code the Continue repo `https://github.com/continuedev/continue` @@ -82,11 +83,47 @@ Continue uses [Prettier](https://marketplace.visualstudio.com/items?itemName=esb ### Writing Slash Commands -A Step can be used as a custom slash command, or called otherwise in a `Policy`. See the [steps README](./server/continuedev/plugins/steps/README.md) to learn how to write a Step. +The slash command interface, defined in [core/index.d.ts](./core/index.d.ts), requires you to define a `name` (the text that will be typed to invoke the command), a `description` (the text that will be shown in the slash command menu), and a `run` function that will be called when the command is invoked. The `run` function is an async generator that yields the content to be displayed in the chat. The `run` function is passed a `ContinueSDK` object that can be used to interact with the IDE, call the LLM, and see the chat history, among a few other utilities. + +```ts +export interface SlashCommand { + name: string; + description: string; + params?: { [key: string]: any }; + run: (sdk: ContinueSDK) => AsyncGenerator; +} +``` + +There are many example of slash commands in [core/commands/slash](./core/commands/slash) that we recommend borrowing from. Once you've created your new `SlashCommand` in this folder, also be sure to complete the following: + +- Add your command to the array in [core/commands/slash/index.ts](./core/commands/slash/index.ts) +- Add your command to the list in [`config_schema.json`](./extensions/vscode/config_schema.json). This makes sure that Intellisense shows users what commands are available for your provider when they are editing `config.json`. If there are any parameters that your command accepts, you should also follow existing examples in adding them to the JSON Schema. ### Writing Context Providers -A `ContextProvider` is a Continue plugin that lets type '@' to quickly select documents as context for the language model. The simplest way to create a `ContextProvider` is to implement the `provide_context_items` method. You can find a great example of this in [GitHubIssuesContextProvider](./server/continuedev/plugins/context_providers/github.py), which allows you to search GitHub Issues in a repo. +A `ContextProvider` is a Continue plugin that lets type '@' to quickly select documents as context for the language model. The `IContextProvider` interface is defined in [`core/index.d.ts`](./core/index.d.ts), but all built-in context providers extend [`BaseContextProvider`](./core/context/index.ts). + +Before defining your context provider, determine which "type" you want to create. The `"query"` type will show a small text input when selected, giving the user the chance to enter something like a Google search query for the [`GoogleContextProvider`](./core/context/providers/GoogleContextProvider.ts). The `"submenu"` type will open up a submenu of items that can be searched through and selected. Examples are the [`GitHubIssuesContextProvider`](./core/context/providers/GitHubIssuesContextProvider.ts) and the [`DocsContextProvider`](./core/context/providers/DocsContextProvider.ts). The `"normal"` type will just immediately add the context item. Examples include the [`DiffContextProvider`](./core/context/providers/DiffContextProvider.ts) and the [`OpenFilesContextProvider`](./core/context/providers/OpenFilesContextProvider.ts). + +After you've written your context provider, make sure to complete the following: + +- Add it to the array of context providers in [core/context/providers/index.ts](./core/context/providers/index.ts) +- Add it to the `ContextProviderName` type in [core/index.d.ts](./core/index.d.ts) +- Add it to the list in [`config_schema.json`](./extensions/vscode/config_schema.json). If there are any parameters that your context provider accepts, you should also follow existing examples in adding them to the JSON Schema. + +### Adding an LLM Provider + +Continue has support for more than a dozen different LLM "providers", making it easy to use models running on OpenAI, Ollama, Together, LM Studio, and more. You can find all of the existing providers [here](https://github.com/continuedev/continue/tree/main/core/llm/llms), and if you see one missing, you can add it with the following steps: + +1. Create a new file in the `core/llm/llms` directory. The name of the file should be the name of the provider, and it should export a class that extends `BaseLLM`. This class should contain the following minimal implementation. We recommend viewing pre-existing providers for more details. The [LlamaCpp Provider](./core/llm/llms/LlamaCpp.ts) is a good simple example. + +- `providerName` - the identifier for your provider +- At least one of `_streamComplete` or `_streamChat` - This is the function that makes the request to the API and returns the streamed response. You only need to implement one because Continue can automatically convert between "chat" and "raw completion". + +2. Add your provider to the `LLMs` array in [core/llm/llms/index.ts](./core/llm/llms/index.ts). +3. If your provider supports images, add it to the `PROVIDER_SUPPORTS_IMAGES` array in [core/llm/index.ts](./core/llm/index.ts). +4. Add the necessary JSON Schema types to [`config_schema.json`](./extensions/vscode/config_schema.json). This makes sure that Intellisense shows users what options are available for your provider when they are editing `config.json`. +5. Add a documentation page for your provider in [`docs/docs/reference/Model Providers`](./docs/docs/reference/Model%20Providers). This should show an example of configuring your provider in `config.json` and explain what options are available. ### Adding Models diff --git a/README.md b/README.md index d300749e0..6eba72e42 100644 --- a/README.md +++ b/README.md @@ -11,13 +11,13 @@
- + - + - +

@@ -66,4 +66,4 @@ Check out the [contribution ideas board](https://github.com/orgs/continuedev/pro ## License -[Apache 2.0 © 2023 Continue Dev, Inc.](./LICENSE) \ No newline at end of file +[Apache 2.0 © 2023 Continue Dev, Inc.](./LICENSE) diff --git a/core/commands/slash/cmd.ts b/core/commands/slash/cmd.ts index 44c27357d..9afc4a61c 100644 --- a/core/commands/slash/cmd.ts +++ b/core/commands/slash/cmd.ts @@ -1,19 +1,40 @@ import { SlashCommand } from "../.."; +import { streamLines } from "../../diff/util"; import { removeQuotesAndEscapes } from "../../util"; const GenerateTerminalCommand: SlashCommand = { name: "cmd", description: "Generate a shell command", run: async function* ({ ide, llm, input }) { - let cmd = - await llm.complete(`The user has made a request to run a shell command. Their description of what it should do is: + const gen = + llm.streamComplete(`The user has made a request to run a shell command. Their description of what it should do is: "${input}" -Please write a shell command that will do what the user requested. Your output should consist of only the command itself, without any explanation or example output. Do not use any newlines. Only output the command that when inserted into the terminal will do precisely what was requested.`); - cmd = removeQuotesAndEscapes(cmd.trim()) - .replace("\n", "") - .replace("\r", ""); +Please write a shell command that will do what the user requested. Your output should consist of only the command itself, without any explanation or example output. Do not use any newlines. Only output the command that when inserted into the terminal will do precisely what was requested. Here is the command:`); + + const lines = streamLines(gen); + let cmd = ""; + for await (const line of lines) { + console.log(line); + if (line.startsWith("```") && line.endsWith("```")) { + cmd = line.split(" ").slice(1).join(" ").slice(0, -3); + break; + } + + if ( + line.startsWith(">") || + line.startsWith("``") || + line.startsWith("\\begin{") || + line.trim() === "" + ) { + continue; + } + + cmd = removeQuotesAndEscapes(line.trim()); + break; + } + await ide.runCommand(cmd); yield `Generated shell command: ${cmd}`; }, diff --git a/core/commands/slash/draftIssue.ts b/core/commands/slash/draftIssue.ts index 9f7b573ed..2250151da 100644 --- a/core/commands/slash/draftIssue.ts +++ b/core/commands/slash/draftIssue.ts @@ -29,12 +29,13 @@ const DraftIssueCommand: SlashCommand = { yield "This command requires a repository URL to be set in the config file."; return; } - const title = await llm.complete( + let title = await llm.complete( `Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `, { maxTokens: 20 } ); - yield removeQuotesAndEscapes(title) + "\n\n"; + title = removeQuotesAndEscapes(title.trim()) + "\n\n"; + yield title; let body = ""; const messages: ChatMessage[] = [ diff --git a/core/commands/slash/edit.ts b/core/commands/slash/edit.ts index b28f72511..e20cc922b 100644 --- a/core/commands/slash/edit.ts +++ b/core/commands/slash/edit.ts @@ -206,10 +206,15 @@ const EditSlashCommand: SlashCommand = { name: "edit", description: "Edit selected code", run: async function* ({ ide, llm, input, history, contextItems, params }) { - const contextItemToEdit = contextItems.find( + let contextItemToEdit = contextItems.find( (item: ContextItemWithId) => item.editing && item.id.providerTitle === "code" ); + if (!contextItemToEdit) { + contextItemToEdit = contextItems.find( + (item: ContextItemWithId) => item.id.providerTitle === "code" + ); + } if (!contextItemToEdit) { yield "Select (highlight and press `cmd+shift+M` (MacOS) / `ctrl+shift+M` (Windows)) the code that you want to edit first"; diff --git a/core/commands/util.ts b/core/commands/util.ts index 17e0151f0..e9ec5943d 100644 --- a/core/commands/util.ts +++ b/core/commands/util.ts @@ -15,10 +15,10 @@ export function contextItemToRangeInFileWithContents( const lines = item.name.split("(")[1].split(")")[0].split("-"); const rif: RangeInFileWithContents = { - filepath: item.description, + filepath: item.description.split(" (")[0], range: { start: { - line: parseInt(lines[0]) - 1, + line: parseInt(lines[0]), character: 0, }, end: { diff --git a/core/config/default.ts b/core/config/default.ts index a61d1cdb1..037c7d15b 100644 --- a/core/config/default.ts +++ b/core/config/default.ts @@ -8,20 +8,20 @@ const defaultConfig: SerializedContinueConfig = { model: "gpt-4", }, { - title: "GPT-3.5-Turbo (Free Trial)", + title: "GPT-4 Vision (Free Trial)", provider: "free-trial", - model: "gpt-3.5-turbo", - }, - { - title: "Phind CodeLlama (Free Trial)", - provider: "free-trial", - model: "phind-codellama-34b", + model: "gpt-4-vision-preview", }, { title: "Gemini Pro (Free Trial)", provider: "free-trial", model: "gemini-pro", }, + { + title: "Codellama 70b (Free Trial)", + provider: "free-trial", + model: "codellama-70b", + }, ], slashCommands: [ { diff --git a/core/context/providers/CodebaseContextProvider.ts b/core/context/providers/CodebaseContextProvider.ts index c79d8cc60..5c31fcc67 100644 --- a/core/context/providers/CodebaseContextProvider.ts +++ b/core/context/providers/CodebaseContextProvider.ts @@ -4,7 +4,6 @@ import { ContextProviderDescription, ContextProviderExtras, } from "../.."; -import { retrieveContextItemsFromEmbeddings } from "../retrieval"; class CodebaseContextProvider extends BaseContextProvider { static description: ContextProviderDescription = { @@ -18,6 +17,7 @@ class CodebaseContextProvider extends BaseContextProvider { query: string, extras: ContextProviderExtras ): Promise { + const { retrieveContextItemsFromEmbeddings } = await import("../retrieval"); return retrieveContextItemsFromEmbeddings(extras, this.options, undefined); } async load(): Promise {} diff --git a/core/context/providers/DocsContextProvider.ts b/core/context/providers/DocsContextProvider.ts index 3875dd3a0..803628f0c 100644 --- a/core/context/providers/DocsContextProvider.ts +++ b/core/context/providers/DocsContextProvider.ts @@ -36,13 +36,15 @@ class DocsContextProvider extends BaseContextProvider { return [ ...chunks .map((chunk) => ({ - name: chunk.filepath - .split("/") - .slice(1) - .join("/") - .split("/tree/main/") - .slice(1) - .join("/"), // chunk.otherMetadata?.title || chunk.filepath, + name: chunk.filepath.includes("/tree/main") // For display of GitHub files + ? chunk.filepath + .split("/") + .slice(1) + .join("/") + .split("/tree/main/") + .slice(1) + .join("/") + : chunk.otherMetadata?.title || chunk.filepath, description: new URL(chunk.filepath, query).toString(), content: chunk.content, })) diff --git a/core/context/providers/FileTreeContextProvider.ts b/core/context/providers/FileTreeContextProvider.ts index 5b6c91150..6e8fe39f4 100644 --- a/core/context/providers/FileTreeContextProvider.ts +++ b/core/context/providers/FileTreeContextProvider.ts @@ -75,9 +75,9 @@ class FileTreeContextProvider extends BaseContextProvider { } currentTree.files.push(parts.pop()!); - - trees.push(formatFileTree(subDirTree)); } + + trees.push(formatFileTree(subDirTree)); } return [ diff --git a/core/context/providers/FolderContextProvider.ts b/core/context/providers/FolderContextProvider.ts index 10ad971d5..81955cb1e 100644 --- a/core/context/providers/FolderContextProvider.ts +++ b/core/context/providers/FolderContextProvider.ts @@ -7,7 +7,6 @@ import { LoadSubmenuItemsArgs, } from "../.."; import { getBasename, getLastNPathParts } from "../../util"; -import { retrieveContextItemsFromEmbeddings } from "../retrieval"; class FolderContextProvider extends BaseContextProvider { static description: ContextProviderDescription = { @@ -21,6 +20,7 @@ class FolderContextProvider extends BaseContextProvider { query: string, extras: ContextProviderExtras ): Promise { + const { retrieveContextItemsFromEmbeddings } = await import("../retrieval"); return retrieveContextItemsFromEmbeddings(extras, this.options, query); } async loadSubmenuItems( diff --git a/core/context/retrieval.ts b/core/context/retrieval.ts index 3a405691f..4ffc583cc 100644 --- a/core/context/retrieval.ts +++ b/core/context/retrieval.ts @@ -1,10 +1,8 @@ -import { - Chunk, - ContextItem, - ContextProviderExtras, - ILLM, - ModelProvider, -} from ".."; +import { Chunk, ContextItem, ContextProviderExtras, ILLM } from ".."; +import { FullTextSearchCodebaseIndex } from "../indexing/FullTextSearch"; +import { ChunkCodebaseIndex } from "../indexing/chunk/ChunkCodebaseIndex"; +import { IndexTag } from "../indexing/types"; +import { llmCanGenerateInParallel } from "../llm"; import { getBasename } from "../util"; const RERANK_PROMPT = ( @@ -47,28 +45,6 @@ ${document} Relevant: `; -const PARALLEL_PROVIDERS: ModelProvider[] = [ - "anthropic", - "bedrock", - "deepinfra", - "gemini", - "google-palm", - "huggingface-inference-api", - "huggingface-tgi", - "mistral", - "free-trial", - "replicate", - "together", -]; - -function llmCanGenerateInParallel(llm: ILLM): boolean { - if (llm.providerName === "openai") { - return llm.model.includes("gpt"); - } - - return PARALLEL_PROVIDERS.includes(llm.providerName); -} - async function scoreChunk( chunk: Chunk, llm: ILLM, @@ -133,24 +109,66 @@ export async function retrieveContextItemsFromEmbeddings( return []; } - const nRetrieve = options?.nRetrieve || 20; - const nFinal = options?.nFinal || 8; + const nFinal = options?.nFinal || 10; const useReranking = llmCanGenerateInParallel(extras.llm) && (options?.useReranking === undefined ? false : options?.useReranking); + const nRetrieve = useReranking === false ? nFinal : options?.nRetrieve || 20; - // Similarity search - let results = await extras.ide.retrieveChunks( + const ftsIndex = new FullTextSearchCodebaseIndex(); + const workspaceDirs = await extras.ide.getWorkspaceDirs(); + const branches = await Promise.all( + workspaceDirs.map((dir) => extras.ide.getBranch(dir)) + ); + const tags: IndexTag[] = workspaceDirs.map((directory, i) => ({ + directory, + branch: branches[i], + artifactId: ChunkCodebaseIndex.artifactId, + })); + + let ftsResults = await ftsIndex.retrieve( + tags, + extras.fullInput.trim().split(" ").join(" OR "), + nRetrieve / 2, + filterDirectory, + undefined + ); + + let vecResults = await extras.ide.retrieveChunks( extras.fullInput, - useReranking === false ? nFinal : nRetrieve, + nRetrieve, filterDirectory ); + // Now combine these (de-duplicate) and re-rank + let results = [...ftsResults]; + for (const vecResult of vecResults) { + if (results.length >= nRetrieve) { + break; + } + if ( + !ftsResults.find( + (r) => + r.filepath === vecResult.filepath && + r.startLine === vecResult.startLine && + r.endLine === vecResult.endLine + ) + ) { + results.push(vecResult); + } + } + // Re-ranking if (useReranking) { results = await rerank(results, extras.llm, extras.fullInput, nFinal); } + if (results.length === 0) { + throw new Error( + "Warning: No results found for @codebase context provider." + ); + } + return [ ...results.map((r) => { const name = `${getBasename(r.filepath)} (${r.startLine}-${r.endLine})`; diff --git a/core/ide/filesystem.ts b/core/ide/filesystem.ts index 2635a05cb..ad79c7e1f 100644 --- a/core/ide/filesystem.ts +++ b/core/ide/filesystem.ts @@ -28,6 +28,13 @@ class FileSystemIde implements IDE { getTerminalContents(): Promise { return Promise.resolve(""); } + showLines( + filepath: string, + startLine: number, + endLine: number + ): Promise { + return Promise.resolve(); + } listWorkspaceContents(): Promise { return new Promise((resolve, reject) => { fs.readdir("/tmp/continue", (err, files) => { @@ -94,6 +101,10 @@ class FileSystemIde implements IDE { return Promise.resolve(); } + getBranch(dir: string): Promise { + return Promise.resolve(""); + } + async verticalDiffUpdate( filepath: string, startLine: number, diff --git a/core/ide/index.ts b/core/ide/index.ts index 66e865775..02c808634 100644 --- a/core/ide/index.ts +++ b/core/ide/index.ts @@ -30,6 +30,14 @@ export class ExtensionIde implements IDE { return await r("getWorkspaceDirs"); } + async showLines( + filepath: string, + startLine: number, + endLine: number + ): Promise { + return await r("showLines", { filepath, startLine, endLine }); + } + async listFolders(): Promise { return await r("listFolders"); } @@ -112,6 +120,10 @@ export class ExtensionIde implements IDE { return r("sendChunkForFile", { chunk, embedding, tags }); } + async getBranch(dir: string): Promise { + return r("getBranch", { dir }); + } + retrieveChunks( text: string, n: number, diff --git a/core/index.d.ts b/core/index.d.ts index 93b413902..20763fc93 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -300,6 +300,11 @@ export interface IDE { runCommand(command: string): Promise; saveFile(filepath: string): Promise; readFile(filepath: string): Promise; + showLines( + filepath: string, + startLine: number, + endLine: number + ): Promise; showDiff( filepath: string, newContents: string, @@ -316,6 +321,7 @@ export interface IDE { getSearchResults(query: string): Promise; subprocess(command: string): Promise<[string, string]>; getProblems(filepath?: string | undefined): Promise; + getBranch(dir: string): Promise; // Embeddings /** @@ -397,7 +403,9 @@ type TemplateType = | "openchat" | "deepseek" | "xwin-coder" - | "neural-chat"; + | "neural-chat" + | "codellama-70b" + | "llava"; type ModelProvider = | "openai" @@ -426,7 +434,8 @@ export type ModelName = | "gpt-4" | "gpt-3.5-turbo-0613" | "gpt-4-32k" - | "gpt-4-1106-preview" + | "gpt-4-0125-preview" + | "gpt-4-vision-preview" // Open Source | "mistral-7b" | "mistral-8x7b" @@ -435,6 +444,7 @@ export type ModelName = | "codellama-7b" | "codellama-13b" | "codellama-34b" + | "codellama-70b" | "phi2" | "phind-codellama-34b" | "wizardcoder-7b" diff --git a/core/indexing/FullTextSearch.ts b/core/indexing/FullTextSearch.ts new file mode 100644 index 000000000..c7720bbf5 --- /dev/null +++ b/core/indexing/FullTextSearch.ts @@ -0,0 +1,135 @@ +import { Chunk, IndexingProgressUpdate } from ".."; +import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex"; +import { + CodebaseIndex, + IndexResultType, + IndexTag, + MarkCompleteCallback, + RefreshIndexResults, +} from "./types"; + +export class FullTextSearchCodebaseIndex implements CodebaseIndex { + artifactId: string = "sqliteFts"; + + private async _createTables(db: DatabaseConnection) { + await db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS fts USING fts5( + path, + content, + tokenize = 'trigram' + )`); + + await db.exec(`CREATE TABLE IF NOT EXISTS fts_metadata ( + id INTEGER PRIMARY KEY, + path TEXT NOT NULL, + cacheKey TEXT NOT NULL, + chunkId INTEGER NOT NULL, + FOREIGN KEY (chunkId) REFERENCES chunks (id), + FOREIGN KEY (id) REFERENCES fts (rowid) + )`); + } + + async *update( + tag: IndexTag, + results: RefreshIndexResults, + markComplete: MarkCompleteCallback + ): AsyncGenerator { + const db = await SqliteDb.get(); + await this._createTables(db); + + for (let i = 0; i < results.compute.length; i++) { + const item = results.compute[i]; + + // Insert chunks + const chunks = await db.all( + `SELECT * FROM chunks WHERE path = ? AND cacheKey = ?`, + [item.path, item.cacheKey] + ); + + for (let chunk of chunks) { + const { lastID } = await db.run( + `INSERT INTO fts (path, content) VALUES (?, ?)`, + [item.path, chunk.content] + ); + await db.run( + `INSERT INTO fts_metadata (id, path, cacheKey, chunkId) VALUES (?, ?, ?, ?)`, + [lastID, item.path, item.cacheKey, chunk.id] + ); + } + + yield { + progress: i / results.compute.length, + desc: `Indexing ${item.path}`, + }; + markComplete([item], IndexResultType.Compute); + } + + // Add tag + for (const item of results.addTag) { + markComplete([item], IndexResultType.AddTag); + } + + // Remove tag + for (const item of results.removeTag) { + markComplete([item], IndexResultType.RemoveTag); + } + + // Delete + for (const item of results.del) { + const { lastID } = await db.run( + `DELETE FROM fts_metadata WHERE path = ? AND cacheKey = ?`, + [item.path, item.cacheKey] + ); + await db.run(`DELETE FROM fts WHERE rowid = ?`, [lastID]); + + markComplete([item], IndexResultType.Delete); + } + } + + async retrieve( + tags: IndexTag[], + text: string, + n: number, + directory: string | undefined, + filterPaths: string[] | undefined + ): Promise { + const db = await SqliteDb.get(); + const tagStrings = tags.map(tagToString); + + const results = await db.all( + `SELECT fts_metadata.chunkId, fts_metadata.path, fts.content, rank + FROM fts + JOIN fts_metadata ON fts.rowid = fts_metadata.id + JOIN chunk_tags ON fts_metadata.chunkId = chunk_tags.chunkId + WHERE fts MATCH '${text.replace( + /\?/g, + "" + )}' AND chunk_tags.tag IN (${tagStrings.map(() => "?").join(",")}) + ${ + filterPaths + ? `AND fts_metadata.path IN (${filterPaths + .map(() => "?") + .join(",")})` + : "" + } + ORDER BY rank + LIMIT ?`, + [...tagStrings, ...(filterPaths || []), n] + ); + + const chunks = await db.all( + `SELECT * FROM chunks WHERE id IN (${results.map(() => "?").join(",")})`, + results.map((result) => result.chunkId) + ); + + return chunks.map((chunk) => { + return { + filepath: chunk.path, + index: chunk.index, + startLine: chunk.startLine, + endLine: chunk.endLine, + content: chunk.content, + digest: chunk.cacheKey, + }; + }); + } +} diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index feafc3a3a..792c01fd4 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -6,7 +6,7 @@ import { MAX_CHUNK_SIZE } from "../llm/constants"; import { getBasename } from "../util"; import { getLanceDbPath } from "../util/paths"; import { chunkDocument } from "./chunk/chunk"; -import { DatabaseConnection, SqliteDb } from "./refreshIndex"; +import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex"; import { CodebaseIndex, IndexResultType, @@ -15,10 +15,6 @@ import { RefreshIndexResults, } from "./types"; -export function tagToString(tag: IndexTag): string { - return `${tag.directory}::${tag.branch}::${tag.artifactId}`; -} - // LanceDB converts to lowercase, so names must all be lowercase interface LanceDbRow { uuid: string; @@ -283,7 +279,7 @@ export class LanceDbIndex implements CodebaseIndex { } allResults = allResults - .sort((a, b) => b._distance - a._distance) + .sort((a, b) => a._distance - b._distance) .slice(0, n); const sqliteDb = await SqliteDb.get(); diff --git a/core/indexing/chunk/ChunkCodebaseIndex.ts b/core/indexing/chunk/ChunkCodebaseIndex.ts new file mode 100644 index 000000000..477328365 --- /dev/null +++ b/core/indexing/chunk/ChunkCodebaseIndex.ts @@ -0,0 +1,127 @@ +import { IndexingProgressUpdate } from "../.."; +import { MAX_CHUNK_SIZE } from "../../llm/constants"; +import { getBasename } from "../../util"; +import { DatabaseConnection, SqliteDb, tagToString } from "../refreshIndex"; +import { + CodebaseIndex, + IndexResultType, + IndexTag, + MarkCompleteCallback, + RefreshIndexResults, +} from "../types"; +import { chunkDocument } from "./chunk"; + +export class ChunkCodebaseIndex implements CodebaseIndex { + static artifactId: string = "chunks"; + artifactId: string = ChunkCodebaseIndex.artifactId; + + readFile: (filepath: string) => Promise; + constructor(readFile: (filepath: string) => Promise) { + this.readFile = readFile; + } + + private async _createTables(db: DatabaseConnection) { + await db.exec(`CREATE TABLE IF NOT EXISTS chunks ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + cacheKey TEXT NOT NULL, + path TEXT NOT NULL, + idx INTEGER NOT NULL, + startLine INTEGER NOT NULL, + endLine INTEGER NOT NULL, + content TEXT NOT NULL + )`); + + await db.exec(`CREATE TABLE IF NOT EXISTS chunk_tags ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + tag TEXT NOT NULL, + chunkId INTEGER NOT NULL, + FOREIGN KEY (chunkId) REFERENCES chunks (id) + )`); + } + + async *update( + tag: IndexTag, + results: RefreshIndexResults, + markComplete: MarkCompleteCallback + ): AsyncGenerator { + const db = await SqliteDb.get(); + await this._createTables(db); + const tagString = tagToString(tag); + + // Compute chunks for new files + const contents = await Promise.all( + results.compute.map(({ path }) => this.readFile(path)) + ); + for (let i = 0; i < results.compute.length; i++) { + const item = results.compute[i]; + + // Insert chunks + for await (let chunk of chunkDocument( + item.path, + contents[i], + MAX_CHUNK_SIZE, + item.cacheKey + )) { + const { lastID } = await db.run( + `INSERT INTO chunks (cacheKey, path, idx, startLine, endLine, content) VALUES (?, ?, ?, ?, ?, ?)`, + [ + chunk.digest, + chunk.filepath, + chunk.index, + chunk.startLine, + chunk.endLine, + chunk.content, + ] + ); + + await db.run(`INSERT INTO chunk_tags (chunkId, tag) VALUES (?, ?)`, [ + lastID, + tagString, + ]); + } + + yield { + progress: i / results.compute.length, + desc: `Chunking ${getBasename(item.path)}`, + }; + markComplete([item], IndexResultType.Compute); + } + + // Add tag + for (const item of results.addTag) { + const chunksWithPath = await db.all( + `SELECT * FROM chunks WHERE cacheKey = ?`, + [item.cacheKey] + ); + + for (const chunk of chunksWithPath) { + await db.run(`INSERT INTO chunk_tags (chunkId, tag) VALUES (?, ?)`, [ + chunk.id, + tagString, + ]); + } + + markComplete([item], IndexResultType.AddTag); + } + + // Remove tag + for (const item of results.removeTag) { + await db.run(`DELETE FROM chunk_tags WHERE tag = ?`, [tagString]); + markComplete([item], IndexResultType.RemoveTag); + } + + // Delete + for (const item of results.del) { + const deleted = await db.run(`DELETE FROM chunks WHERE cacheKey = ?`, [ + item.cacheKey, + ]); + + // Delete from chunk_tags + await db.run(`DELETE FROM chunk_tags WHERE chunkId = ?`, [ + deleted.lastID, + ]); + + markComplete([item], IndexResultType.Delete); + } + } +} diff --git a/core/indexing/chunk/markdown.ts b/core/indexing/chunk/markdown.ts index 0ca92158c..0e0901cf0 100644 --- a/core/indexing/chunk/markdown.ts +++ b/core/indexing/chunk/markdown.ts @@ -58,14 +58,29 @@ export async function* markdownChunker( hLevel: number ): AsyncGenerator { if (countTokens(content, "gpt-4") <= maxChunkSize) { + const header = findHeader(content.split("\n")); yield { content, startLine: 0, endLine: content.split("\n").length, + otherMetadata: { + fragment: cleanFragment(header), + title: cleanHeader(header), + }, }; return; } else if (hLevel > 4) { - yield* basicChunker(content, maxChunkSize); + const header = findHeader(content.split("\n")); + + for (const chunk of basicChunker(content, maxChunkSize)) { + yield { + ...chunk, + otherMetadata: { + fragment: cleanFragment(header), + title: cleanHeader(header), + }, + }; + } return; } diff --git a/core/indexing/docs/crawl.ts b/core/indexing/docs/crawl.ts index 13b86c807..0152005f2 100644 --- a/core/indexing/docs/crawl.ts +++ b/core/indexing/docs/crawl.ts @@ -43,11 +43,16 @@ function shouldFilterPath(pathname: string, baseUrl: URL): boolean { return false; } -async function crawlLinks(path: string, baseUrl: URL, visited: Set) { +async function* crawlLinks( + path: string, + baseUrl: URL, + visited: Set +): AsyncGenerator { if (visited.has(path) || shouldFilterPath(path, baseUrl)) { return; } visited.add(path); + yield visited.size; const response = await fetch(new URL(path, baseUrl)); const text = await response.text(); @@ -71,8 +76,12 @@ async function crawlLinks(path: string, baseUrl: URL, visited: Set) { }); await Promise.all( - children.map((child) => crawlLinks(child, baseUrl, visited)) + children.map(async (child) => { + for await (const _ of crawlLinks(child, baseUrl, visited)) { + } + }) ); + yield visited.size; } async function crawlGithubRepo(baseUrl: URL) { @@ -116,25 +125,44 @@ async function crawlGithubRepo(baseUrl: URL) { return paths; } -export async function crawlSubpages(baseUrl: URL) { +export async function* crawlSubpages( + baseUrl: URL +): AsyncGenerator { // Special case for GitHub repos if (baseUrl.hostname === "github.com") { return crawlGithubRepo(baseUrl); } // First, check if the parent of the path redirects to the same page - const parentUrl = new URL(baseUrl); - parentUrl.pathname = parentUrl.pathname.split("/").slice(0, -1).join("/"); - const response = await fetch(parentUrl); - - let useParent = response.url === baseUrl.toString(); + if (baseUrl.pathname.endsWith("/")) { + baseUrl.pathname = baseUrl.pathname.slice(0, -1); + } + let realBaseUrl = new URL(baseUrl); + while (true) { + let parentUrl = new URL(realBaseUrl); + parentUrl.pathname = parentUrl.pathname.split("/").slice(0, -1).join("/"); + if ( + parentUrl.pathname === realBaseUrl.pathname || + parentUrl.pathname === "" + ) { + break; + } + const response = await fetch(parentUrl); + const redirected = response.url.toString() === baseUrl.toString() + "/"; + if (!redirected) { + break; + } + realBaseUrl = parentUrl; + } const visited = new Set(); - await crawlLinks( - (useParent ? parentUrl.pathname : baseUrl.pathname) || "/", - baseUrl, + for await (const count of crawlLinks( + realBaseUrl.pathname || "/", + realBaseUrl, visited - ); + )) { + yield count; + } return [...visited]; } diff --git a/core/indexing/docs/db.ts b/core/indexing/docs/db.ts index 760fc0f87..21a23d827 100644 --- a/core/indexing/docs/db.ts +++ b/core/indexing/docs/db.ts @@ -22,7 +22,7 @@ async function createDocsTable(db: Database) { db.exec(`CREATE TABLE IF NOT EXISTS docs ( id INTEGER PRIMARY KEY AUTOINCREMENT, title STRING NOT NULL, - baseUrl STRING NOT NULL + baseUrl STRING NOT NULL UNIQUE )`); } diff --git a/core/indexing/docs/index.ts b/core/indexing/docs/index.ts index 7b147dcdd..5c2ade9ac 100644 --- a/core/indexing/docs/index.ts +++ b/core/indexing/docs/index.ts @@ -16,7 +16,7 @@ export async function* indexDocs( embeddingsProvider: EmbeddingsProvider ): AsyncGenerator { const existingDocs = await listDocs(); - if (existingDocs.find((doc) => doc.title === title)) { + if (existingDocs.find((doc) => doc.baseUrl === baseUrl.toString())) { yield { progress: 1, desc: "Already indexed", @@ -29,8 +29,23 @@ export async function* indexDocs( desc: "Finding subpages", }; - let subpaths = await crawlSubpages(baseUrl); - console.log("Found subpaths", subpaths); + const subpathGenerator = crawlSubpages(baseUrl); + let { value, done } = await subpathGenerator.next(); + while (true) { + if (done) { + break; + } + yield { + progress: 0, + desc: `Finding subpages (${value})`, + }; + const next = await subpathGenerator.next(); + value = next.value; + done = next.done; + } + + let subpaths = value as string[]; + const chunks: Chunk[] = []; const embeddings: number[][] = []; @@ -53,7 +68,7 @@ export async function* indexDocs( for (let i = 0; i < subpaths.length; i++) { const subpath = subpaths[i]; yield { - progress: 1 / (subpaths.length + 1), + progress: Math.max(1, Math.floor(100 / (subpaths.length + 1))), desc: `${subpath}`, }; @@ -75,6 +90,7 @@ export async function* indexDocs( (chunk.otherMetadata?.fragment ? `#${chunk.otherMetadata.fragment}` : ""), + otherMetadata: chunk.otherMetadata, index, digest: subpath, }); diff --git a/core/indexing/embeddings/OpenAIEmbeddingsProvider.ts b/core/indexing/embeddings/OpenAIEmbeddingsProvider.ts index cb9a4cb43..0b6f4fb22 100644 --- a/core/indexing/embeddings/OpenAIEmbeddingsProvider.ts +++ b/core/indexing/embeddings/OpenAIEmbeddingsProvider.ts @@ -4,7 +4,7 @@ import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider"; class OpenAIEmbeddingsProvider extends BaseEmbeddingsProvider { static defaultOptions: Partial | undefined = { apiBase: "https://api.openai.com", - model: "text-embedding-ada-002", + model: "text-embedding-3-large", }; get id(): string { @@ -16,13 +16,10 @@ class OpenAIEmbeddingsProvider extends BaseEmbeddingsProvider { if (apiBase?.endsWith("/")) { apiBase = apiBase.slice(0, -1); } - if (apiBase?.endsWith("/v1")) { - apiBase = apiBase.slice(0, -3); - } return await Promise.all( chunks.map(async (chunk) => { - const resp = await fetch(`${apiBase}/v1/embeddings`, { + const resp = await fetch(`${apiBase}/embeddings`, { method: "POST", body: JSON.stringify({ input: chunk, diff --git a/core/indexing/refreshIndex.ts b/core/indexing/refreshIndex.ts index 94ee72a9f..a37ae0077 100644 --- a/core/indexing/refreshIndex.ts +++ b/core/indexing/refreshIndex.ts @@ -15,6 +15,10 @@ import { export type DatabaseConnection = Database; +export function tagToString(tag: IndexTag): string { + return `${tag.directory}::${tag.branch}::${tag.artifactId}`; +} + export class SqliteDb { static db: DatabaseConnection | null = null; diff --git a/core/llm/constants.ts b/core/llm/constants.ts index c64626e01..0a05c8886 100644 --- a/core/llm/constants.ts +++ b/core/llm/constants.ts @@ -17,6 +17,8 @@ const CONTEXT_LENGTH_FOR_MODEL: { [name: string]: number } = { "gpt-35-turbo": 4096, "gpt-4-32k": 32_768, "gpt-4-1106-preview": 128_000, + "gpt-4-vision": 128_000, + "gpt-4-0125-preview": 128_000, }; const TOKEN_BUFFER_FOR_SAFETY = 350; diff --git a/core/llm/index.ts b/core/llm/index.ts index 792b46349..cb4c04447 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -6,10 +6,12 @@ import { LLMFullCompletionOptions, LLMOptions, LLMReturnValue, + ModelName, ModelProvider, RequestOptions, TemplateType, } from ".."; +import mergeJson from "../util/merge"; import { CONTEXT_LENGTH_FOR_MODEL, DEFAULT_ARGS, @@ -24,8 +26,10 @@ import { import { anthropicTemplateMessages, chatmlTemplateMessages, + codeLlama70bTemplateMessages, deepseekTemplateMessages, llama2TemplateMessages, + llavaTemplateMessages, neuralChatTemplateMessages, openchatTemplateMessages, phi2TemplateMessages, @@ -36,6 +40,7 @@ import { } from "./templates/chat"; import { alpacaEditPrompt, + codeLlama70bEditPrompt, codellamaEditPrompt, deepseekEditPrompt, mistralEditPrompt, @@ -47,14 +52,21 @@ import { xWinCoderEditPrompt, zephyrEditPrompt, } from "./templates/edit"; +import CompletionOptionsForModels from "./templates/options"; const PROVIDER_HANDLES_TEMPLATING: ModelProvider[] = [ "lmstudio", "openai", "ollama", + "together", ]; -const PROVIDER_SUPPORTS_IMAGES: ModelProvider[] = ["openai", "ollama"]; +const PROVIDER_SUPPORTS_IMAGES: ModelProvider[] = [ + "openai", + "ollama", + "google-palm", + "free-trial", +]; export function modelSupportsImages( provider: ModelProvider, @@ -63,19 +75,53 @@ export function modelSupportsImages( if (!PROVIDER_SUPPORTS_IMAGES.includes(provider)) { return false; } + if (model.includes("llava")) { return true; } + if (["gpt-4-vision-preview"].includes(model)) { return true; } + if ( + model === "gemini-ultra" && + (provider === "google-palm" || provider === "free-trial") + ) { + return true; + } + return false; } +const PARALLEL_PROVIDERS: ModelProvider[] = [ + "anthropic", + "bedrock", + "deepinfra", + "gemini", + "google-palm", + "huggingface-inference-api", + "huggingface-tgi", + "mistral", + "free-trial", + "replicate", + "together", +]; + +export function llmCanGenerateInParallel(llm: ILLM): boolean { + if (llm.providerName === "openai") { + return llm.model.includes("gpt"); + } + + return PARALLEL_PROVIDERS.includes(llm.providerName); +} function autodetectTemplateType(model: string): TemplateType | undefined { const lower = model.toLowerCase(); + if (lower.includes("codellama") && lower.includes("70b")) { + return "codellama-70b"; + } + if ( lower.includes("gpt") || lower.includes("chat-bison") || @@ -85,6 +131,10 @@ function autodetectTemplateType(model: string): TemplateType | undefined { return undefined; } + if (lower.includes("llava")) { + return "llava"; + } + if (lower.includes("xwin")) { return "xwin-coder"; } @@ -163,6 +213,8 @@ function autodetectTemplateFunction( openchat: openchatTemplateMessages, "xwin-coder": xWinCoderTemplateMessages, "neural-chat": neuralChatTemplateMessages, + llava: llavaTemplateMessages, + "codellama-70b": codeLlama70bTemplateMessages, none: null, }; @@ -203,6 +255,8 @@ function autodetectPromptTemplates( editTemplate = xWinCoderEditPrompt; } else if (templateType === "neural-chat") { editTemplate = neuralChatEditPrompt; + } else if (templateType === "codellama-70b") { + editTemplate = codeLlama70bEditPrompt; } else if (templateType) { editTemplate = simplestEditPrompt; } @@ -273,6 +327,12 @@ export abstract class BaseLLM implements ILLM { model: options.model || "gpt-4", maxTokens: options.completionOptions?.maxTokens || DEFAULT_MAX_TOKENS, }; + if (CompletionOptionsForModels[options.model as ModelName]) { + this.completionOptions = mergeJson( + this.completionOptions, + CompletionOptionsForModels[options.model as ModelName] || {} + ); + } this.requestOptions = options.requestOptions; this.promptTemplates = { ...autodetectPromptTemplates(options.model, templateType), @@ -355,11 +415,11 @@ export abstract class BaseLLM implements ILLM { .map(([key, value]) => `${key}: ${value}`) .join("\n"); return `Settings: - ${settings} +${settings} - ############################################ +############################################ - ${prompt}`; +${prompt}`; } private _logTokensGenerated(model: string, completion: string) { @@ -404,10 +464,10 @@ export abstract class BaseLLM implements ILLM { delete options.log; delete options.raw; - const completionOptions: CompletionOptions = { - ...this.completionOptions, - ...options, - }; + const completionOptions: CompletionOptions = mergeJson( + this.completionOptions, + options + ); return { completionOptions, log, raw }; } @@ -455,6 +515,10 @@ export abstract class BaseLLM implements ILLM { this._logTokensGenerated(completionOptions.model, completion); + if (log && this.writeLog) { + await this.writeLog(`Completion:\n\n${completion}\n\n`); + } + return { prompt, completion }; } @@ -485,6 +549,10 @@ export abstract class BaseLLM implements ILLM { const completion = await this._complete(prompt, completionOptions); this._logTokensGenerated(completionOptions.model, completion); + if (log && this.writeLog) { + await this.writeLog(`Completion:\n\n${completion}\n\n`); + } + return completion; } @@ -543,6 +611,10 @@ export abstract class BaseLLM implements ILLM { } this._logTokensGenerated(completionOptions.model, completion); + if (log && this.writeLog) { + await this.writeLog(`Completion:\n\n${completion}\n\n`); + } + return { prompt, completion }; } diff --git a/core/llm/llms/FreeTrial.ts b/core/llm/llms/FreeTrial.ts index 27ce0b040..e8400830b 100644 --- a/core/llm/llms/FreeTrial.ts +++ b/core/llm/llms/FreeTrial.ts @@ -3,7 +3,7 @@ import { ChatMessage, CompletionOptions, ModelProvider } from "../.."; import { streamResponse } from "../stream"; // const SERVER_URL = "http://localhost:3000"; -const SERVER_URL = "https://node-proxy-server-l6vsfbzhba-uw.a.run.app"; +const SERVER_URL = "https://node-proxy-server-blue-l6vsfbzhba-uw.a.run.app"; class FreeTrial extends BaseLLM { static providerName: ModelProvider = "free-trial"; @@ -47,6 +47,24 @@ class FreeTrial extends BaseLLM { } } + protected _convertMessage(message: ChatMessage) { + if (typeof message.content === "string") { + return message; + } + + const parts = message.content.map((part) => { + return { + type: part.type, + text: part.text, + image_url: { ...part.imageUrl, detail: "low" }, + }; + }); + return { + ...message, + content: parts, + }; + } + protected async *_streamChat( messages: ChatMessage[], options: CompletionOptions @@ -57,7 +75,7 @@ class FreeTrial extends BaseLLM { method: "POST", headers: this._getHeaders(), body: JSON.stringify({ - messages, + messages: messages.map(this._convertMessage), ...args, }), }); diff --git a/core/llm/llms/GooglePalm.ts b/core/llm/llms/GooglePalm.ts index 93a81943e..8a6d13f84 100644 --- a/core/llm/llms/GooglePalm.ts +++ b/core/llm/llms/GooglePalm.ts @@ -3,6 +3,7 @@ import { ChatMessage, CompletionOptions, LLMOptions, + MessagePart, ModelProvider, } from "../.."; import { stripImages } from "../countTokens"; @@ -42,6 +43,19 @@ class GooglePalm extends BaseLLM { } } + private _continuePartToGeminiPart(part: MessagePart) { + return part.type === "text" + ? { + text: part.text, + } + : { + inlineData: { + mimeType: "image/jpeg", + data: part.imageUrl?.url.split(",")[1], + }, + }; + } + private async *streamChatGemini( messages: ChatMessage[], options: CompletionOptions @@ -51,7 +65,10 @@ class GooglePalm extends BaseLLM { contents: messages.map((msg) => { return { role: msg.role === "assistant" ? "model" : "user", - parts: [{ text: msg.content }], + parts: + typeof msg.content === "string" + ? [{ text: msg.content }] + : msg.content.map(this._continuePartToGeminiPart), }; }), }; diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index 57817c049..0d454fb59 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -67,6 +67,7 @@ class Ollama extends BaseLLM { "codellama-7b": "codellama:7b", "codellama-13b": "codellama:13b", "codellama-34b": "codellama:34b", + "codellama-70b": "codellama:70b", "phi-2": "phi:2.7b", "phind-codellama-34b": "phind-codellama:34b-v2", "wizardcoder-7b": "wizardcoder:7b-python", @@ -103,6 +104,7 @@ class Ollama extends BaseLLM { const finalOptions: any = { model: this._getModel(), raw: true, + keep_alive: 60 * 30, // 30 minutes options: { temperature: options.temperature, top_p: options.topP, diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 2e4681d46..b0c357765 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -24,7 +24,7 @@ const NON_CHAT_MODELS = [ class OpenAI extends BaseLLM { static providerName: ModelProvider = "openai"; static defaultOptions: Partial = { - apiBase: "https://api.openai.com", + apiBase: "https://api.openai.com/v1", }; protected _convertMessage(message: ChatMessage) { @@ -87,9 +87,7 @@ class OpenAI extends BaseLLM { if (url.endsWith("/")) { url = url.slice(0, -1); } - if (!url.endsWith("/v1") && !url.includes("api.perplexity.ai")) { - url += "/v1"; - } + return url + "/completions"; } } @@ -110,6 +108,10 @@ class OpenAI extends BaseLLM { prompt: string, options: CompletionOptions ): AsyncGenerator { + const args: any = this._convertArgs(options, []); + args.prompt = prompt; + delete args.messages; + const response = await this.fetch(this._getCompletionUrl(), { method: "POST", headers: { @@ -118,16 +120,7 @@ class OpenAI extends BaseLLM { "api-key": this.apiKey || "", // For Azure }, body: JSON.stringify({ - ...{ - prompt, - model: options.model, - max_tokens: options.maxTokens, - temperature: options.temperature, - top_p: options.topP, - frequency_penalty: options.frequencyPenalty, - presence_penalty: options.presencePenalty, - stop: options.stop, - }, + ...args, stream: true, }), }); @@ -153,10 +146,6 @@ class OpenAI extends BaseLLM { url = url.slice(0, -1); } - if (!url.includes("/v1") && !url.includes("api.perplexity.ai")) { - // includes instead of endsWith becuase DeepInfra uses /v1/openai/chat/completions - url += "/v1"; - } return url + "/chat/completions"; } } @@ -178,6 +167,15 @@ class OpenAI extends BaseLLM { return; } + let body = { + ...this._convertArgs(options, messages), + stream: true, + }; + // Empty messages cause an error in LM Studio + body.messages = body.messages.map((m) => ({ + ...m, + content: m.content === "" ? " " : m.content, + })) as any; const response = await this.fetch(this._getChatUrl(), { method: "POST", headers: { @@ -185,10 +183,7 @@ class OpenAI extends BaseLLM { Authorization: `Bearer ${this.apiKey}`, "api-key": this.apiKey || "", // For Azure }, - body: JSON.stringify({ - ...this._convertArgs(options, messages), - stream: true, - }), + body: JSON.stringify(body), }); for await (const value of streamSse(response)) { diff --git a/core/llm/llms/Together.ts b/core/llm/llms/Together.ts index 5976b9575..d93be974c 100644 --- a/core/llm/llms/Together.ts +++ b/core/llm/llms/Together.ts @@ -1,17 +1,23 @@ -import { BaseLLM } from ".."; -import { CompletionOptions, LLMOptions, ModelProvider } from "../.."; -import { streamSse } from "../stream"; +import { + ChatMessage, + CompletionOptions, + LLMOptions, + ModelProvider, +} from "../.."; -class Together extends BaseLLM { +import OpenAI from "./OpenAI"; + +class Together extends OpenAI { static providerName: ModelProvider = "together"; static defaultOptions: Partial = { - apiBase: "https://api.together.xyz", + apiBase: "https://api.together.xyz/v1", }; private static MODEL_IDS: { [name: string]: string } = { "codellama-7b": "togethercomputer/CodeLlama-7b-Instruct", "codellama-13b": "togethercomputer/CodeLlama-13b-Instruct", "codellama-34b": "togethercomputer/CodeLlama-34b-Instruct", + "codellama-70b": "codellama/CodeLlama-70b-Instruct-hf", "llama2-7b": "togethercomputer/llama-2-7b-chat", "llama2-13b": "togethercomputer/llama-2-13b-chat", "llama2-70b": "togethercomputer/llama-2-70b-chat", @@ -24,17 +30,9 @@ class Together extends BaseLLM { return Together.MODEL_IDS[model] || this.model; } - private _convertArgs(options: CompletionOptions, prompt: string) { - const finalOptions = { - prompt, - model: this._getModelName(options.model), - temperature: options.temperature, - top_p: options.topP, - top_k: options.topK, - max_tokens: options.maxTokens, - repetition_penalty: options.frequencyPenalty, - }; - + protected _convertArgs(options: any, messages: ChatMessage[]) { + const finalOptions = super._convertArgs(options, messages); + finalOptions.model = this._getModelName(options.model); return finalOptions; } @@ -42,22 +40,8 @@ class Together extends BaseLLM { prompt: string, options: CompletionOptions ): AsyncGenerator { - const response = await this.fetch(`${this.apiBase}/inference`, { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${this.apiKey}`, - }, - body: JSON.stringify({ - ...this._convertArgs(options, prompt), - stream_tokens: true, - }), - }); - - for await (const value of streamSse(response)) { - if (value.choices) { - yield value.choices[0].text; - } + for await (const chunk of this._legacystreamComplete(prompt, options)) { + yield chunk; } } } diff --git a/core/llm/templates/chat.ts b/core/llm/templates/chat.ts index d360bad18..bb0945042 100644 --- a/core/llm/templates/chat.ts +++ b/core/llm/templates/chat.ts @@ -69,6 +69,26 @@ function anthropicTemplateMessages(messages: ChatMessage[]): string { return prompt; } +function llavaTemplateMessages(msgs: ChatMessage[]): string { + `A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions. +USER: {prompt} +ASSISTANT:`; + + let prompt = + "A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions."; + + for (const msg of msgs) { + prompt += msg.role === "user" ? "USER: " : "ASSISTANT: "; + prompt += msg.content; + + prompt += "\n"; + } + + prompt += "ASSISTANT: "; + + return prompt; +} + function zephyrTemplateMessages(msgs: ChatMessage[]): string { let prompt = ""; @@ -244,11 +264,29 @@ function neuralChatTemplateMessages(msgs: ChatMessage[]): string { return prompt; } +/** +'Source: system\n\n System prompt Source: user\n\n First user query Source: assistant\n\n Model response to first query Source: user\n\n Second user query Source: assistant\nDestination: user\n\n ' + */ +function codeLlama70bTemplateMessages(msgs: ChatMessage[]): string { + let prompt = ""; + + for (const msg of msgs) { + prompt += `Source: ${msg.role}\n\n ${stripImages(msg.content).trim()}`; + prompt += " "; + } + + prompt += "Source: assistant\nDestination: user\n\n"; + + return prompt; +} + export { anthropicTemplateMessages, chatmlTemplateMessages, + codeLlama70bTemplateMessages, deepseekTemplateMessages, llama2TemplateMessages, + llavaTemplateMessages, neuralChatTemplateMessages, openchatTemplateMessages, phi2TemplateMessages, diff --git a/core/llm/templates/edit.ts b/core/llm/templates/edit.ts index 5a49f3158..0471ba4d1 100644 --- a/core/llm/templates/edit.ts +++ b/core/llm/templates/edit.ts @@ -138,18 +138,25 @@ Sure! Here's the code you requested: \`\`\`{{{language}}} `; +const codeLlama70bEditPrompt = `Source: system\n\n You are an expert programmer and write code on the first attempt without any errors or fillers. Source: user\n\n Rewrite the code to satisfy this request: "{{{userInput}}}" + +\`\`\`{{{language}}} +{{{codeToEdit}}} +\`\`\` Source: assistant\nDestination: user\n\n `; + export { alpacaEditPrompt, + codeLlama70bEditPrompt, codellamaEditPrompt, codellamaInfillEditPrompt, deepseekEditPrompt, gptEditPrompt, mistralEditPrompt, + neuralChatEditPrompt, openchatEditPrompt, phindEditPrompt, simplestEditPrompt, simplifiedEditPrompt, xWinCoderEditPrompt, zephyrEditPrompt, - neuralChatEditPrompt, }; diff --git a/core/llm/templates/options.ts b/core/llm/templates/options.ts new file mode 100644 index 000000000..1ebb02ba2 --- /dev/null +++ b/core/llm/templates/options.ts @@ -0,0 +1,11 @@ +import { CompletionOptions, ModelName } from "../.."; + +const CompletionOptionsForModels: { + [key in ModelName]?: Partial; +} = { + "codellama-70b": { + stop: ["Source: assistant"], + }, +}; + +export default CompletionOptionsForModels; diff --git a/core/util/index.ts b/core/util/index.ts index a6f90b6d4..de330f772 100644 --- a/core/util/index.ts +++ b/core/util/index.ts @@ -16,13 +16,17 @@ export function removeQuotesAndEscapes(output: string): string { output = output.replace("\\n", "\n"); output = output.replace("\\t", "\t"); output = output.replace("\\\\", "\\"); - if ( + while ( (output.startsWith('"') && output.endsWith('"')) || (output.startsWith("'") && output.endsWith("'")) ) { output = output.slice(1, -1); } + while (output.startsWith("`") && output.endsWith("`")) { + output = output.slice(1, -1); + } + return output; } @@ -131,6 +135,10 @@ export function getMarkdownLanguageTagForFile(filepath: string): string { return "python"; case "js": return "javascript"; + case "jsx": + return "jsx"; + case "tsx": + return "tsx"; case "ts": return "typescript"; case "java": diff --git a/core/util/merge.ts b/core/util/merge.ts new file mode 100644 index 000000000..c5a0af85f --- /dev/null +++ b/core/util/merge.ts @@ -0,0 +1,36 @@ +type JsonObject = { [key: string]: any }; + +export function mergeJson(first: JsonObject, second: JsonObject): any { + try { + for (var key in second) { + let secondValue = second[key]; + + if (!(key in first)) { + // New value + first[key] = secondValue; + continue; + } + + const firstValue = first[key]; + if (Array.isArray(secondValue)) { + // Array + first[key] = [...firstValue, ...secondValue]; + } else if (typeof secondValue === "object") { + // Object + first[key] = mergeJson(firstValue, secondValue); + } else { + // Other (boolean, number, string) + first[key] = secondValue; + } + } + return first; + } catch (e) { + console.error("Error merging JSON", e, first, second); + return { + ...first, + ...second, + }; + } +} + +export default mergeJson; diff --git a/docs/docs/customization/context-providers.md b/docs/docs/customization/context-providers.md index 5d710f1c3..692035656 100644 --- a/docs/docs/customization/context-providers.md +++ b/docs/docs/customization/context-providers.md @@ -32,6 +32,14 @@ Type '@terminal' to reference the contents of your IDE's terminal. { "name": "terminal" } ``` +### Documentation + +Type `@docs` to index and retrieve snippets from any documentation site. You can add any site by selecting "Add Docs" in the dropdown, then entering the root URL of the documentation site and a title to remember it by. After the site has been indexed, you can type `@docs`, select your documentation from the dropdown, and Continue will use similarity search to automatically find important sections when answering your question. + +```json +{ "name": "docs" } +``` + ### Open Files Type '@open' to reference the contents of all of your open files. Set `onlyPinned` to `true` to only reference pinned files. @@ -129,7 +137,11 @@ interface CustomContextProvider { } ``` -As an example, let's say you have a set of internal documents that have been indexed in a vector database. You've set up a simple REST API that allows internal users to query and get back relevant snippets. This context provider will send the query to this server and return the results from the vector database. +As an example, let's say you have a set of internal documents that have been indexed in a vector database. You've set up a simple REST API that allows internal users to query and get back relevant snippets. This context provider will send the query to this server and return the results from the vector database. The return type of `getContextItems` _must_ be an array of objects that have all of the following properties: + +- `name`: The name of the context item, which will be displayed as a title +- `description`: A longer description of the context item +- `content`: The actual content of the context item, which will be fed to the LLM as context ```typescript title="~/.continue/config.ts" const RagContextProvider: CustomContextProvider = { @@ -172,6 +184,83 @@ export function modifyConfig(config: Config): Config { No modification in `config.json` is necessary. +### Custom Context Providers with Submenu or Query + +There are 3 types of context providers: "normal", "query", and "submenu". The "normal" type is the default, and is what we've seen so far. + +The **"query"** type is used when you want to display a text box to the user, and then use the contents of that text box to generate the context items. Built-in examples include ["search"](#exact-search) and ["google"](#google). This text is what gets passed to the "query" argument in `getContextItems`. To implement a "query" context provider, simply set `"type": "query"` in your custom context provider object. + +The **"submenu"** type is used when you want to display a list of searchable items in the dropdown. Built-in examples include ["issue"](#github-issues) and ["folder"](#folders). To implement a "submenu" context provider, set `"type": "submenu"` and implement the `loadSubmenuItems` and `getContextItems` functions. Here is an example that shows a list of all README files in the current workspace: + +```typescript title="~/.continue/config.ts" +const ReadMeContextProvider: CustomContextProvider = { + title: "readme", + displayTitle: "README", + description: "Reference README.md files in your workspace", + type: "submenu", + + getContextItems: async ( + query: string, + extras: ContextProviderExtras + ): Promise => { + // 'query' is the filepath of the README selected from the dropdown + const content = await extras.ide.readFile(query); + return [ + { + name: getFolder(query), + description: getFolderAndBasename(query), + content, + }, + ]; + }, + + loadSubmenuItems: async ( + args: LoadSubmenuItemsArgs + ): Promise => { + // Filter all workspace files for READMEs + const allFiles = await args.ide.listWorkspaceContents(); + const readmes = allFiles.filter((filepath) => + filepath.endsWith("README.md") + ); + + // Return the items that will be shown in the dropdown + return readmes.map((filepath) => { + return { + id: filepath, + title: getFolder(filepath), + description: getFolderAndBasename(filepath), + }; + }); + }, +}; + +export function modifyConfig(config: Config): Config { + if (!config.contextProviders) { + config.contextProviders = []; + } + config.contextProviders.push(ReadMeContextProvider); + return config; +} + +function getFolder(path: string): string { + return path.split(/[\/\\]/g).slice(-2)[0]; +} + +function getFolderAndBasename(path: string): string { + return path + .split(/[\/\\]/g) + .slice(-2) + .join("/"); +} +``` + +The flow of information in the above example is as follows: + +1. The user types `@readme` and selects it from the dropdown, now displaying the submenu where they can search for any item returned by `loadSubmenuItems`. +2. The user selects one of the READMEs in the submenu, enters the rest of their input, and presses enter. +3. The `id` of the chosen `ContextSubmenuItem` is passed to `getContextItems` as the `query` argument. In this case it is the filepath of the README. +4. The `getContextItems` function can then use the `query` to retrieve the full contents of the README and format the content before returning the context item which will be included in the prompt. + ### Importing outside modules > Context providers run in a NodeJS environment, but for the time being the `modifyConfig` function will be called both from NodeJS _and_ the browser. This means that if you are importing packages requiring NodeJS, you should dynamically import them inside of the context provider (e.g. `const moduleA = await import('./moduleA');`). @@ -185,9 +274,11 @@ Continue will use [esbuild](https://esbuild.github.io/) to bundle your `config.t - `title`: An identifier for the context provider - `displayTitle` (optional): The title displayed in the dropdown - `description` (optional): The longer description displayed in the dropdown when hovered +- `type` (optional): The type of context provider. Options are "normal", "query", and "submenu". Defaults to "normal". - `getContextItems`: A function that returns the documents to include in the prompt. It should return a list of `ContextItem`s, and is given access to the following arguments: - `extras.fullInput`: A string representing the user's full input to the text box. This can be used for example to generate an embedding to compare against a set of other embedded documents - `extras.embeddingsProvider`: The embeddings provider has an `embed` function that will convert text (such as `fullInput`) to an embedding - `extras.llm`: The current default LLM, which you can use to make completion requests - `extras.ide`: An instance of the `IDE` class, which lets you gather various sources of information from the IDE, including the contents of the terminal, the list of open files, or any warnings in the currently open file. - `query`: (not currently used) A string representing the query +- `loadSubmenuItems` (optional): A function that returns a list of `ContextSubmenuItem`s to display in a submenu. It is given access to an `IDE`, the same that is passed to `getContextItems`. diff --git a/docs/docs/model-setup/overview.md b/docs/docs/model-setup/overview.md index b1daabc6a..20800f418 100644 --- a/docs/docs/model-setup/overview.md +++ b/docs/docs/model-setup/overview.md @@ -9,12 +9,12 @@ Once you're ready to use your own API key or a different model / provider, press If you are unsure what model or provider to use, here is a rule of thumb: - Use GPT-4 via OpenAI if you want the best possible model overall right now -- Use X via Together if you want the best open-source model right now -- Use X via Ollama if you want to run a model locally on Mac or Linux -- Use X via LM Studio if you want to run a model locally on Windows +- Use Phind CodeLlama or Mixtral 8x7B via Together if you want the best open-source model right now +- Use CodeLlama via Ollama if you want to run a model locally on Mac or Linux +- Use CodeLlama via LM Studio if you want to run a model locally on Windows Learn more: - [Select a provider](select-provider.md) - [Select a model](select-model.md) -- [Configuration](configuration.md) +- [Configuration](configuration.md) \ No newline at end of file diff --git a/docs/docs/model-setup/select-model.md b/docs/docs/model-setup/select-model.md index db3ae9787..6e461aae5 100644 --- a/docs/docs/model-setup/select-model.md +++ b/docs/docs/model-setup/select-model.md @@ -17,6 +17,7 @@ The default models available in the GUI: - [Code Llama-Instruct-7B](https://github.com/continuedev/what-llm-to-use/blob/main/README.md#1-code-llama) - [Code Llama-Instruct-13B](https://github.com/continuedev/what-llm-to-use/blob/main/README.md#1-code-llama) - [Code Llama-Instruct-34B](https://github.com/continuedev/what-llm-to-use/blob/main/README.md#1-code-llama) +- [Code Llama-Instruct-70B](https://github.com/continuedev/what-llm-to-use/blob/main/README.md#1-code-llama) - [WizardCoder-7B](https://github.com/continuedev/what-llm-to-use/blob/main/README.md#2-wizardcoder) - [WizardCoder-13B](https://github.com/continuedev/what-llm-to-use/blob/main/README.md#2-wizardcoder) - [WizardCoder-34B](https://github.com/continuedev/what-llm-to-use/blob/main/README.md#2-wizardcoder) diff --git a/docs/docs/reference/config.mdx b/docs/docs/reference/config.mdx index 8bad8f814..608072369 100644 --- a/docs/docs/reference/config.mdx +++ b/docs/docs/reference/config.mdx @@ -3,7 +3,7 @@ import JSONSchemaViewer from "@theme/JSONSchemaViewer"; # Configuration Options -The following shows the JSON Schema definition for `config.json`: +The following shows the JSON Schema definition for `config.json`. You can also define a partial `config.json` object in a file called `.continuerc.json` at the root of your workspace. This will be [applied on top of](https://github.com/continuedev/continue/blob/74c1eb5e25c517c575f72d26227d31d5d2ea18ed/extensions/vscode/src/ideProtocol.ts#L165-L173) any configuration from `config.json`. - Currently, the codebase retrieval feature is available as the "codebase" and "folder" context providers. You can use them by typing `@codebase` or `@folder` in the input box, and then asking a question. The contents of the input box will be compared with the embeddings from the rest of the codebase (or folder) to determine relevant files. - +Here are use cases where it is not useful: + +- When you need the LLM to see _literally every_ file in your codebase + - "Find everywhere where the `foo` function is called" + - "Review our codebase and find any spelling mistakes" +- Refactoring + - "Add a new parameter to the `bar` function and update usages" ## Configuration @@ -121,3 +136,5 @@ export function modifyConfig(config: Config): Config { ## Customizing which files are indexed Continue respects `.gitignore` files in order to determine which files should not be indexed. If you'd like to exclude additional files, you can add them to a `.continueignore` file, which follows the exact same rules as `.gitignore`. + +If you want to see exactly what files Continue has indexed, the metadata is stored in `~/.continue/index/index.sqlite`. You can use a tool like [DB Browser for SQLite](https://sqlitebrowser.org/) to view the `tags_catalog` table within this file. diff --git a/docs/static/schemas/config.json b/docs/static/schemas/config.json index d9af7c9fd..fc893cb5f 100644 --- a/docs/static/schemas/config.json +++ b/docs/static/schemas/config.json @@ -172,7 +172,8 @@ "deepseek", "openchat", "xwin-coder", - "neural-chat" + "neural-chat", + "codellama-70b" ], "type": "string" }, @@ -334,7 +335,7 @@ "gpt-4", "gpt-3.5-turbo-0613", "gpt-4-32k", - "gpt-4-1106-preview" + "gpt-4-0125-preview" ] } } @@ -386,7 +387,8 @@ "gpt-4", "phind-codellama-34b", "gemini-pro", - "mistral-medium" + "gpt-4-vision-preview", + "codellama-70b" ] } } @@ -417,7 +419,8 @@ "gpt-4", "gpt-3.5-turbo-0613", "gpt-4-32k", - "gpt-4-1106-preview", + "gpt-4-0125-preview", + "gpt-4-vision-preview", "mistral-7b", "mistral-8x7b", "llama2-7b", @@ -425,6 +428,7 @@ "codellama-7b", "codellama-13b", "codellama-34b", + "codellama-70b", "phind-codellama-34b", "wizardcoder-7b", "wizardcoder-13b", @@ -502,6 +506,7 @@ "codellama-7b", "codellama-13b", "codellama-34b", + "codellama-70b", "phind-codellama-34b" ] }, @@ -557,6 +562,7 @@ "codellama-7b", "codellama-13b", "codellama-34b", + "codellama-70b", "phind-codellama-34b", "wizardcoder-7b", "wizardcoder-13b", @@ -596,6 +602,7 @@ "codellama-7b", "codellama-13b", "codellama-34b", + "codellama-70b", "phi-2", "phind-codellama-34b", "wizardcoder-7b", @@ -762,7 +769,8 @@ "gpt-4", "gpt-3.5-turbo-0613", "gpt-4-32k", - "gpt-4-1106-preview", + "gpt-4-0125-preview", + "gpt-4-vision-preview", "mistral-7b", "mistral-8x7b", "llama2-7b", @@ -770,6 +778,7 @@ "codellama-7b", "codellama-13b", "codellama-34b", + "codellama-70b", "phind-codellama-34b", "wizardcoder-7b", "wizardcoder-13b", @@ -959,7 +968,9 @@ "codebase", "problems", "folder", - "issue" + "issue", + "docs", + "tree" ], "markdownEnumDescriptions": [ "Reference the contents of the current changes as given by `git diff`", @@ -972,7 +983,9 @@ "Reference all linting errors and warnings in the currently open file", "Include important files from a folder in the prompt, as determined by similarity search", "Reference GitHub issues from a repository", - "Retrieve important pages from a documentation website, as determined by similarity search" + "Retrieve important pages from a documentation website, as determined by similarity search", + "Index and retrieve the contents of any documentation site, using embeddings to find important snippets", + "Display a file tree of the current workspace" ], "type": "string" }, diff --git a/extensions/intellij/src/main/resources/webview/index.html b/extensions/intellij/src/main/resources/webview/index.html index 5f6818c14..5f2db045f 100644 --- a/extensions/intellij/src/main/resources/webview/index.html +++ b/extensions/intellij/src/main/resources/webview/index.html @@ -1,4 +1,4 @@ - + @@ -7,17 +7,6 @@ Continue - - - - -
diff --git a/extensions/vscode/CHANGELOG.md b/extensions/vscode/CHANGELOG.md index 887ab8b46..fabc24168 100644 --- a/extensions/vscode/CHANGELOG.md +++ b/extensions/vscode/CHANGELOG.md @@ -8,7 +8,21 @@ and is generated by [Changie](https://github.com/miniscruff/changie). Pre-release Changes ### Added +* Image support +* Full-text search index for retrieval +* Docs context provider +* CodeLlama-70b support +### Fixed +* Fixed proxy setting in config.json + +## v0.8.2 - 2024-01-23 +### Added * Add codellama and gemini to free trial, using new server +* Local codebase syncing and embeddings using LanceDB +* Improved VS Code theme matching +### Changed +* Updates to packaging to download native modules for current platform (lancedb, sqlite, onnxruntime, tree-sitter wasms) +* Context providers now run from the extension side (in Node.js instead of browser javascript) ## v0.8.1 - 2024-01-08 diff --git a/extensions/vscode/CONTRIBUTING.md b/extensions/vscode/CONTRIBUTING.md index e88a18983..ddeca6bcb 100644 --- a/extensions/vscode/CONTRIBUTING.md +++ b/extensions/vscode/CONTRIBUTING.md @@ -4,7 +4,6 @@ This is the Continue VS Code Extension. Its primary jobs are 1. Implement the IDE side of the Continue IDE protocol, allowing a Continue server to interact natively in an IDE. This happens in `src/continueIdeClient.ts`. 2. Open the Continue React app in a side panel. The React app's source code lives in the `gui` directory. The panel is opened by the `continue.openContinueGUI` command, as defined in `src/commands.ts`. -3. Run a Continue server in the background, which connects to both the IDE protocol and the React app. The server is launched in `src/activation/environmentSetup.ts` by calling Python code that lives in `server/` (unless extension settings define a server URL other than localhost:65432, in which case the extension will just connect to that). # How to run the extension @@ -12,7 +11,7 @@ See [Environment Setup](../CONTRIBUTING.md#environment-setup) # How to run and debug tests -After following the setup in [Environment Setup](../CONTRIBUTING.md#environment-setup) you can run `npm run test` in the command line or the `Server + Tests (VSCode)` launch configuration in VS Code to debug tests + server. +After following the setup in [Environment Setup](../CONTRIBUTING.md#environment-setup) you can run the `Extension (VSCode)` launch configuration in VS Code. ## Notes diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index d9af7c9fd..fc893cb5f 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -172,7 +172,8 @@ "deepseek", "openchat", "xwin-coder", - "neural-chat" + "neural-chat", + "codellama-70b" ], "type": "string" }, @@ -334,7 +335,7 @@ "gpt-4", "gpt-3.5-turbo-0613", "gpt-4-32k", - "gpt-4-1106-preview" + "gpt-4-0125-preview" ] } } @@ -386,7 +387,8 @@ "gpt-4", "phind-codellama-34b", "gemini-pro", - "mistral-medium" + "gpt-4-vision-preview", + "codellama-70b" ] } } @@ -417,7 +419,8 @@ "gpt-4", "gpt-3.5-turbo-0613", "gpt-4-32k", - "gpt-4-1106-preview", + "gpt-4-0125-preview", + "gpt-4-vision-preview", "mistral-7b", "mistral-8x7b", "llama2-7b", @@ -425,6 +428,7 @@ "codellama-7b", "codellama-13b", "codellama-34b", + "codellama-70b", "phind-codellama-34b", "wizardcoder-7b", "wizardcoder-13b", @@ -502,6 +506,7 @@ "codellama-7b", "codellama-13b", "codellama-34b", + "codellama-70b", "phind-codellama-34b" ] }, @@ -557,6 +562,7 @@ "codellama-7b", "codellama-13b", "codellama-34b", + "codellama-70b", "phind-codellama-34b", "wizardcoder-7b", "wizardcoder-13b", @@ -596,6 +602,7 @@ "codellama-7b", "codellama-13b", "codellama-34b", + "codellama-70b", "phi-2", "phind-codellama-34b", "wizardcoder-7b", @@ -762,7 +769,8 @@ "gpt-4", "gpt-3.5-turbo-0613", "gpt-4-32k", - "gpt-4-1106-preview", + "gpt-4-0125-preview", + "gpt-4-vision-preview", "mistral-7b", "mistral-8x7b", "llama2-7b", @@ -770,6 +778,7 @@ "codellama-7b", "codellama-13b", "codellama-34b", + "codellama-70b", "phind-codellama-34b", "wizardcoder-7b", "wizardcoder-13b", @@ -959,7 +968,9 @@ "codebase", "problems", "folder", - "issue" + "issue", + "docs", + "tree" ], "markdownEnumDescriptions": [ "Reference the contents of the current changes as given by `git diff`", @@ -972,7 +983,9 @@ "Reference all linting errors and warnings in the currently open file", "Include important files from a folder in the prompt, as determined by similarity search", "Reference GitHub issues from a repository", - "Retrieve important pages from a documentation website, as determined by similarity search" + "Retrieve important pages from a documentation website, as determined by similarity search", + "Index and retrieve the contents of any documentation site, using embeddings to find important snippets", + "Display a file tree of the current workspace" ], "type": "string" }, diff --git a/extensions/vscode/media/Lexend/Lexend-VariableFont_wght.ttf b/extensions/vscode/media/Lexend/Lexend-VariableFont_wght.ttf deleted file mode 100644 index b294dc840..000000000 Binary files a/extensions/vscode/media/Lexend/Lexend-VariableFont_wght.ttf and /dev/null differ diff --git a/extensions/vscode/media/Lexend/OFL.txt b/extensions/vscode/media/Lexend/OFL.txt deleted file mode 100644 index 6b6792485..000000000 --- a/extensions/vscode/media/Lexend/OFL.txt +++ /dev/null @@ -1,93 +0,0 @@ -Copyright 2018 The Lexend Project Authors (https://github.com/googlefonts/lexend), with Reserved Font Name “RevReading Lexend”. - -This Font Software is licensed under the SIL Open Font License, Version 1.1. -This license is copied below, and is also available with a FAQ at: -http://scripts.sil.org/OFL - - ------------------------------------------------------------ -SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 ------------------------------------------------------------ - -PREAMBLE -The goals of the Open Font License (OFL) are to stimulate worldwide -development of collaborative font projects, to support the font creation -efforts of academic and linguistic communities, and to provide a free and -open framework in which fonts may be shared and improved in partnership -with others. - -The OFL allows the licensed fonts to be used, studied, modified and -redistributed freely as long as they are not sold by themselves. The -fonts, including any derivative works, can be bundled, embedded, -redistributed and/or sold with any software provided that any reserved -names are not used by derivative works. The fonts and derivatives, -however, cannot be released under any other type of license. The -requirement for fonts to remain under this license does not apply -to any document created using the fonts or their derivatives. - -DEFINITIONS -"Font Software" refers to the set of files released by the Copyright -Holder(s) under this license and clearly marked as such. This may -include source files, build scripts and documentation. - -"Reserved Font Name" refers to any names specified as such after the -copyright statement(s). - -"Original Version" refers to the collection of Font Software components as -distributed by the Copyright Holder(s). - -"Modified Version" refers to any derivative made by adding to, deleting, -or substituting -- in part or in whole -- any of the components of the -Original Version, by changing formats or by porting the Font Software to a -new environment. - -"Author" refers to any designer, engineer, programmer, technical -writer or other person who contributed to the Font Software. - -PERMISSION & CONDITIONS -Permission is hereby granted, free of charge, to any person obtaining -a copy of the Font Software, to use, study, copy, merge, embed, modify, -redistribute, and sell modified and unmodified copies of the Font -Software, subject to the following conditions: - -1) Neither the Font Software nor any of its individual components, -in Original or Modified Versions, may be sold by itself. - -2) Original or Modified Versions of the Font Software may be bundled, -redistributed and/or sold with any software, provided that each copy -contains the above copyright notice and this license. These can be -included either as stand-alone text files, human-readable headers or -in the appropriate machine-readable metadata fields within text or -binary files as long as those fields can be easily viewed by the user. - -3) No Modified Version of the Font Software may use the Reserved Font -Name(s) unless explicit written permission is granted by the corresponding -Copyright Holder. This restriction only applies to the primary font name as -presented to the users. - -4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font -Software shall not be used to promote, endorse or advertise any -Modified Version, except to acknowledge the contribution(s) of the -Copyright Holder(s) and the Author(s) or with their explicit written -permission. - -5) The Font Software, modified or unmodified, in part or in whole, -must be distributed entirely under this license, and must not be -distributed under any other license. The requirement for fonts to -remain under this license does not apply to any document created -using the Font Software. - -TERMINATION -This license becomes null and void if any of the above conditions are -not met. - -DISCLAIMER -THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT -OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE -COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL -DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM -OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/extensions/vscode/media/Lexend/README.txt b/extensions/vscode/media/Lexend/README.txt deleted file mode 100644 index f2966dfed..000000000 --- a/extensions/vscode/media/Lexend/README.txt +++ /dev/null @@ -1,71 +0,0 @@ -Lexend Variable Font -==================== - -This download contains Lexend as both a variable font and static fonts. - -Lexend is a variable font with this axis: - wght - -This means all the styles are contained in a single file: - Lexend-VariableFont_wght.ttf - -If your app fully supports variable fonts, you can now pick intermediate styles -that aren’t available as static fonts. Not all apps support variable fonts, and -in those cases you can use the static font files for Lexend: - static/Lexend-Thin.ttf - static/Lexend-ExtraLight.ttf - static/Lexend-Light.ttf - static/Lexend-Regular.ttf - static/Lexend-Medium.ttf - static/Lexend-SemiBold.ttf - static/Lexend-Bold.ttf - static/Lexend-ExtraBold.ttf - static/Lexend-Black.ttf - -Get started ------------ - -1. Install the font files you want to use - -2. Use your app's font picker to view the font family and all the -available styles - -Learn more about variable fonts -------------------------------- - - https://developers.google.com/web/fundamentals/design-and-ux/typography/variable-fonts - https://variablefonts.typenetwork.com - https://medium.com/variable-fonts - -In desktop apps - - https://theblog.adobe.com/can-variable-fonts-illustrator-cc - https://helpx.adobe.com/nz/photoshop/using/fonts.html#variable_fonts - -Online - - https://developers.google.com/fonts/docs/getting_started - https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Fonts/Variable_Fonts_Guide - https://developer.microsoft.com/en-us/microsoft-edge/testdrive/demos/variable-fonts - -Installing fonts - - MacOS: https://support.apple.com/en-us/HT201749 - Linux: https://www.google.com/search?q=how+to+install+a+font+on+gnu%2Blinux - Windows: https://support.microsoft.com/en-us/help/314960/how-to-install-or-remove-a-font-in-windows - -Android Apps - - https://developers.google.com/fonts/docs/android - https://developer.android.com/guide/topics/ui/look-and-feel/downloadable-fonts - -License -------- -Please read the full license text (OFL.txt) to understand the permissions, -restrictions and requirements for usage, redistribution, and modification. - -You can use them in your products & projects – print or digital, -commercial or otherwise. - -This isn't legal advice, please consider consulting a lawyer and see the full -license for all details. diff --git a/extensions/vscode/media/Lexend/static/Lexend-Black.ttf b/extensions/vscode/media/Lexend/static/Lexend-Black.ttf deleted file mode 100644 index 2fea087c2..000000000 Binary files a/extensions/vscode/media/Lexend/static/Lexend-Black.ttf and /dev/null differ diff --git a/extensions/vscode/media/Lexend/static/Lexend-Bold.ttf b/extensions/vscode/media/Lexend/static/Lexend-Bold.ttf deleted file mode 100644 index 95884f6e5..000000000 Binary files a/extensions/vscode/media/Lexend/static/Lexend-Bold.ttf and /dev/null differ diff --git a/extensions/vscode/media/Lexend/static/Lexend-ExtraBold.ttf b/extensions/vscode/media/Lexend/static/Lexend-ExtraBold.ttf deleted file mode 100644 index 02f84ed31..000000000 Binary files a/extensions/vscode/media/Lexend/static/Lexend-ExtraBold.ttf and /dev/null differ diff --git a/extensions/vscode/media/Lexend/static/Lexend-ExtraLight.ttf b/extensions/vscode/media/Lexend/static/Lexend-ExtraLight.ttf deleted file mode 100644 index 20e7068d0..000000000 Binary files a/extensions/vscode/media/Lexend/static/Lexend-ExtraLight.ttf and /dev/null differ diff --git a/extensions/vscode/media/Lexend/static/Lexend-Light.ttf b/extensions/vscode/media/Lexend/static/Lexend-Light.ttf deleted file mode 100644 index fb6d097ce..000000000 Binary files a/extensions/vscode/media/Lexend/static/Lexend-Light.ttf and /dev/null differ diff --git a/extensions/vscode/media/Lexend/static/Lexend-Medium.ttf b/extensions/vscode/media/Lexend/static/Lexend-Medium.ttf deleted file mode 100644 index d91a86735..000000000 Binary files a/extensions/vscode/media/Lexend/static/Lexend-Medium.ttf and /dev/null differ diff --git a/extensions/vscode/media/Lexend/static/Lexend-Regular.ttf b/extensions/vscode/media/Lexend/static/Lexend-Regular.ttf deleted file mode 100644 index b423d3ab7..000000000 Binary files a/extensions/vscode/media/Lexend/static/Lexend-Regular.ttf and /dev/null differ diff --git a/extensions/vscode/media/Lexend/static/Lexend-SemiBold.ttf b/extensions/vscode/media/Lexend/static/Lexend-SemiBold.ttf deleted file mode 100644 index 9dcb82141..000000000 Binary files a/extensions/vscode/media/Lexend/static/Lexend-SemiBold.ttf and /dev/null differ diff --git a/extensions/vscode/media/Lexend/static/Lexend-Thin.ttf b/extensions/vscode/media/Lexend/static/Lexend-Thin.ttf deleted file mode 100644 index 0d7df8813..000000000 Binary files a/extensions/vscode/media/Lexend/static/Lexend-Thin.ttf and /dev/null differ diff --git a/extensions/vscode/media/readme.gif b/extensions/vscode/media/readme.gif index 1fdeefb71..a8ba308a1 100644 Binary files a/extensions/vscode/media/readme.gif and b/extensions/vscode/media/readme.gif differ diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 5648153d6..9c32d567b 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.29", + "version": "0.9.42", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.29", + "version": "0.9.42", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 5187d1c7a..c0dc1710d 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -1,7 +1,7 @@ { "name": "continue", "icon": "media/icon.png", - "version": "0.9.29", + "version": "0.9.42", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" @@ -73,90 +73,108 @@ { "command": "continue.acceptDiff", "category": "Continue", - "title": "Accept Diff" + "title": "Accept Diff", + "group": "Continue" }, { "command": "continue.rejectDiff", "category": "Continue", - "title": "Reject Diff" + "title": "Reject Diff", + "group": "Continue", + "icon": "$(stop)" }, { "command": "continue.quickEdit", "category": "Continue", - "title": "Quick Edit" + "title": "Quick Edit", + "group": "Continue" }, { "command": "continue.toggleAuxiliaryBar", "category": "Continue", - "title": "Toggle Right Sidebar" + "title": "Toggle Right Sidebar", + "group": "Continue" }, { "command": "continue.focusContinueInput", "category": "Continue", - "title": "Add Highlighted Code to Context" + "title": "Add Highlighted Code to Context", + "group": "Continue" }, { "command": "continue.focusContinueInputWithoutClear", "category": "Continue", - "title": "Add Highlighted Code to Context" + "title": "Add Highlighted Code to Context", + "group": "Continue" }, { "command": "continue.debugTerminal", "category": "Continue", - "title": "Debug Terminal" + "title": "Debug Terminal", + "group": "Continue" }, { "command": "continue.toggleFullScreen", "category": "Continue", "title": "Toggle Full Screen", - "icon": "$(fullscreen)" + "icon": "$(fullscreen)", + "group": "Continue" }, { "command": "continue.shareSession", "category": "Continue", - "title": "Share Session" + "title": "Share Session", + "group": "Continue" }, { "command": "continue.selectFilesAsContext", "category": "Continue", - "title": "Continue: Select Files as Context" + "title": "Continue: Select Files as Context", + "group": "Continue" }, { "command": "continue.newSession", "category": "Continue", "title": "New Session", - "icon": "$(add)" + "icon": "$(add)", + "group": "Continue" }, { "command": "continue.viewHistory", "category": "Continue", "title": "View History", - "icon": "$(history)" + "icon": "$(history)", + "group": "Continue" }, { "command": "continue.writeCommentsForCode", "category": "Continue", - "title": "Write Comments for this Code" + "title": "Write Comments for this Code", + "group": "Continue" }, { "command": "continue.writeDocstringForCode", "category": "Continue", - "title": "Write a Docstring for this Code" + "title": "Write a Docstring for this Code", + "group": "Continue" }, { "command": "continue.fixCode", "category": "Continue", - "title": "Fix this Code" + "title": "Fix this Code", + "group": "Continue" }, { "command": "continue.optimizeCode", "category": "Continue", - "title": "Optimize this Code" + "title": "Optimize this Code", + "group": "Continue" }, { "command": "continue.fixGrammar", "category": "Continue", - "title": "Fix Grammar / Spelling" + "title": "Fix Grammar / Spelling", + "group": "Continue" } ], "keybindings": [ @@ -209,6 +227,29 @@ } ], "menus": { + "commandPalette": [ + { + "command": "continue.quickEdit" + }, + { + "command": "continue.toggleAuxiliaryBar" + }, + { + "command": "continue.focusContinueInput" + }, + { + "command": "continue.focusContinueInputWithoutClear" + }, + { + "command": "continue.debugTerminal" + }, + { + "command": "continue.toggleFullScreen" + }, + { + "command": "continue.newSession" + } + ], "webview/context": [ { "command": "continue.shareSession", @@ -218,7 +259,14 @@ "editor/context": [ { "submenu": "continue.continueSubMenu", - "group": "1_debug@1" + "group": "0_acontinue" + } + ], + "editor/title/run": [ + { + "command": "continue.rejectDiff", + "group": "Continue", + "when": "continue.streamingDiff" } ], "continue.continueSubMenu": [ diff --git a/extensions/vscode/scripts/prepackage.js b/extensions/vscode/scripts/prepackage.js index 754c61dec..cace676bc 100644 --- a/extensions/vscode/scripts/prepackage.js +++ b/extensions/vscode/scripts/prepackage.js @@ -124,6 +124,7 @@ if (args[2] === "--target") { target = `${os}-${arch}`; console.log("Detected target: ", target); } + fs.mkdirSync("bin", { recursive: true }); // onnxruntime-node await new Promise((resolve, reject) => { diff --git a/extensions/vscode/src/activation/activate.ts b/extensions/vscode/src/activation/activate.ts index d351601c6..b4c267452 100644 --- a/extensions/vscode/src/activation/activate.ts +++ b/extensions/vscode/src/activation/activate.ts @@ -17,14 +17,27 @@ export let extensionContext: vscode.ExtensionContext | undefined = undefined; export let ideProtocolClient: IdeProtocolClient; export let windowId: string = v4(); -async function openTutorial(context: vscode.ExtensionContext) { +export async function showTutorial() { + const tutorialPath = path.join( + getExtensionUri().fsPath, + "continue_tutorial.py" + ); + // Ensure keyboard shortcuts match OS + if (process.platform !== "darwin") { + let tutorialContent = fs.readFileSync(tutorialPath, "utf8"); + tutorialContent = tutorialContent.replace("⌘", "^"); + fs.writeFileSync(tutorialPath, tutorialContent); + } + + const doc = await vscode.workspace.openTextDocument( + vscode.Uri.file(tutorialPath) + ); + await vscode.window.showTextDocument(doc); +} + +async function openTutorialFirstTime(context: vscode.ExtensionContext) { if (context.globalState.get("continue.tutorialShown") !== true) { - const doc = await vscode.workspace.openTextDocument( - vscode.Uri.file( - path.join(getExtensionUri().fsPath, "continue_tutorial.py") - ) - ); - await vscode.window.showTextDocument(doc); + await showTutorial(); context.globalState.update("continue.tutorialShown", true); } } @@ -69,7 +82,7 @@ export async function activateExtension(context: vscode.ExtensionContext) { registerAllCodeLensProviders(context); registerAllCommands(context); registerQuickFixProvider(); - await openTutorial(context); + await openTutorialFirstTime(context); setupInlineTips(context); showRefactorMigrationMessage(); @@ -132,6 +145,8 @@ export async function activateExtension(context: vscode.ExtensionContext) { fontColor: "#fff", }; themeJson.fileNames[".continueignore"] = "_f_continue"; + themeJson.fileNames[".continuerc.json"] = "_f_continue"; + themeJson.fileNames["config.json"] = "_f_continue"; fs.writeFileSync(themePath, JSON.stringify(themeJson)); found = true; break; diff --git a/extensions/vscode/src/activation/inlineTips.ts b/extensions/vscode/src/activation/inlineTips.ts index 9f78b8c3e..34ed41bd7 100644 --- a/extensions/vscode/src/activation/inlineTips.ts +++ b/extensions/vscode/src/activation/inlineTips.ts @@ -13,6 +13,11 @@ const inlineTipDecoration = vscode.window.createTextEditorDecorationType({ function handleSelectionChange(e: vscode.TextEditorSelectionChangeEvent) { const selection = e.selections[0]; const editor = e.textEditor; + + if (editor.document.uri.toString().startsWith("output:")) { + return; + } + if ( selection.isEmpty || vscode.workspace @@ -69,6 +74,10 @@ export function setupInlineTips(context: vscode.ExtensionContext) { context.subscriptions.push( vscode.window.onDidChangeActiveTextEditor((editor) => { if (editor?.document.getText() === "") { + if (editor.document.uri.toString().startsWith("output:")) { + return; + } + editor.setDecorations(emptyFileTooltipDecoration, [ { range: new vscode.Range( @@ -83,6 +92,9 @@ export function setupInlineTips(context: vscode.ExtensionContext) { context.subscriptions.push( vscode.workspace.onDidChangeTextDocument((e) => { + if (e.document.uri.toString().startsWith("vscode://inline-chat")) { + return; + } if (e.document.getText() === "") { vscode.window.visibleTextEditors.forEach((editor) => { editor.setDecorations(emptyFileTooltipDecoration, [ diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 871ab27f4..d2896f4d7 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -190,7 +190,7 @@ const commandsMap: { [command: string]: (...args: any) => any } = { await vscode.window.showTextDocument(uri); }, "continue.debugTerminal": async () => { - const terminalContents = await ideProtocolClient.getTerminalContents(2); + const terminalContents = await ideProtocolClient.getTerminalContents(1); vscode.commands.executeCommand("continue.continueGUIView.focus"); debugPanelWebview?.postMessage({ type: "userInput", diff --git a/extensions/vscode/src/continueIdeClient.ts b/extensions/vscode/src/continueIdeClient.ts index 650665aff..38cb966cc 100644 --- a/extensions/vscode/src/continueIdeClient.ts +++ b/extensions/vscode/src/continueIdeClient.ts @@ -233,9 +233,9 @@ class IdeProtocolClient { panel.webview.html = getSidebarContent(panel, "/monaco", edits); } - openFile(filepath: string) { + openFile(filepath: string, range?: vscode.Range) { // vscode has a builtin open/get open files - openEditorAndRevealRange(filepath, undefined, vscode.ViewColumn.One); + return openEditorAndRevealRange(filepath, range, vscode.ViewColumn.One); } async fileExists(filepath: string): Promise { @@ -354,7 +354,20 @@ class IdeProtocolClient { } const allFiles: string[] = []; - for await (const file of traverseDirectory(directory, [])) { + const gitRoot = await this.getGitRoot(directory); + let onlyThisDirectory = undefined; + if (gitRoot) { + onlyThisDirectory = directory.slice(gitRoot.length).split(path.sep); + if (onlyThisDirectory[0] === "") { + onlyThisDirectory.shift(); + } + } + for await (const file of traverseDirectory( + gitRoot || directory, + [], + true, + onlyThisDirectory + )) { allFiles.push(file); } return allFiles; @@ -455,6 +468,11 @@ class IdeProtocolClient { return repo; } + async getGitRoot(forDirectory: string): Promise { + const repo = await this.getRepo(vscode.Uri.file(forDirectory)); + return repo?.rootUri?.fsPath; + } + async getBranch(forDirectory: vscode.Uri) { let repo = await this.getRepo(forDirectory); if (repo?.state?.HEAD?.name === undefined) { diff --git a/extensions/vscode/src/debugPanel.ts b/extensions/vscode/src/debugPanel.ts index 620478a13..57cdcf064 100644 --- a/extensions/vscode/src/debugPanel.ts +++ b/extensions/vscode/src/debugPanel.ts @@ -2,12 +2,19 @@ import { ContextItemId, DiffLine, FileEdit, ModelDescription } from "core"; import { indexDocs } from "core/indexing/docs"; import TransformersJsEmbeddingsProvider from "core/indexing/embeddings/TransformersJsEmbeddingsProvider"; import { editConfigJson, getConfigJsonPath } from "core/util/paths"; +import * as fs from "fs"; import { readFileSync, writeFileSync } from "fs"; +import * as path from "path"; import * as io from "socket.io-client"; import { v4 as uuidv4 } from "uuid"; import * as vscode from "vscode"; -import { ideProtocolClient, windowId } from "./activation/activate"; +import { + ideProtocolClient, + showTutorial, + windowId, +} from "./activation/activate"; import { getContinueServerUrl } from "./bridge"; +import { streamEdit } from "./diff/verticalPerLine/manager"; import historyManager from "./history"; import { VsCodeIde } from "./ideProtocol"; import { configHandler, llmFromTitle } from "./loadConfig"; @@ -214,25 +221,6 @@ export function getSidebarContent( }); break; } - case "showLines": { - ideProtocolClient.highlightCode( - { - filepath: data.filepath, - range: { - start: { - line: data.start, - character: 0, - }, - end: { - line: data.end, - character: 0, - }, - }, - }, - "#00ff0022" - ); - break; - } case "toggleDevTools": { vscode.commands.executeCommand("workbench.action.toggleDevTools"); vscode.commands.executeCommand("continue.viewLogs"); @@ -431,6 +419,11 @@ export function getSidebarContent( respond(await ide.getProblems(data.message.filepath)); break; } + case "getBranch": { + const { dir } = data.message; + respond(await ide.getBranch(dir)); + break; + } case "getOpenFiles": { respond(await ide.getOpenFiles()); break; @@ -439,6 +432,11 @@ export function getSidebarContent( respond(await ide.getPinnedFiles()); break; } + case "showLines": { + const { filepath, startLine, endLine } = data.message; + respond(await ide.showLines(filepath, startLine, endLine)); + break; + } // Other case "errorPopup": { vscode.window @@ -694,7 +692,7 @@ export function getSidebarContent( embeddingsProvider )) { progress.report({ - increment: update.progress * 100, + increment: update.progress, message: update.desc, }); } @@ -702,26 +700,104 @@ export function getSidebarContent( vscode.window.showInformationMessage( `🎉 Successfully indexed ${title}` ); + + debugPanelWebview?.postMessage({ + type: "refreshSubmenuItems", + }); } ); break; } + case "applyToCurrentFile": { + // Select the entire current file + const editor = vscode.window.activeTextEditor; + if (!editor) { + vscode.window.showErrorMessage( + "No active editor to apply edits to" + ); + break; + } + const document = editor.document; + const start = new vscode.Position(0, 0); + const end = new vscode.Position( + document.lineCount - 1, + document.lineAt(document.lineCount - 1).text.length + ); + editor.selection = new vscode.Selection(start, end); + + streamEdit( + `The following code was suggested as an edit:\n\`\`\`\n${data.text}\n\`\`\`\nPlease apply it to the previous code.` + ); + break; + } + case "showTutorial": { + showTutorial(); + break; + } } - } catch (e) { + } catch (e: any) { + let message = `Continue error: ${e.message}`; + if (e.cause) { + if (e.cause.name === "ConnectTimeoutError") { + message = `Connection timed out. If you expect it to take a long time to connect, you can increase the timeout in config.json by setting "requestOptions": { "timeout": 10000 }. You can find the full config reference here: https://continue.dev/docs/reference/config`; + } else if (e.cause.code === "ECONNREFUSED") { + message = `Connection was refused. This likely means that there is no server running at the specified URL. If you are running your own server you may need to set the "apiBase" parameter in config.json. For example, you can set up an OpenAI-compatible server like here: https://continue.dev/docs/reference/Model%20Providers/openai#openai-compatible-servers--apis`; + } else { + message = `The request failed with "${e.cause.name}": ${e.cause.message}. If you're having trouble setting up Continue, please see the troubleshooting guide for help.`; + } + } + vscode.window - .showErrorMessage( - `Error handling message from Continue side panel: ${e}`, - "Show Logs" - ) + .showErrorMessage(message, "Show Logs", "Troubleshooting") .then((selection) => { if (selection === "Show Logs") { vscode.commands.executeCommand("workbench.action.toggleDevTools"); + } else if (selection === "Troubleshooting") { + vscode.env.openExternal( + vscode.Uri.parse("https://continue.dev/docs/troubleshooting") + ); } }); respond({ done: true, data: {} }); } }); + let currentTheme = undefined; + let colorThemeName = "dark-plus"; + const tokenColorMap: any = {}; + try { + // Pass color theme to webview for syntax highlighting + const colorTheme = vscode.workspace + .getConfiguration("workbench") + .get("colorTheme"); + + for (let i = vscode.extensions.all.length - 1; i >= 0; i--) { + if (currentTheme) { + break; + } + const extension = vscode.extensions.all[i]; + if (extension.packageJSON?.contributes?.themes?.length > 0) { + for (const theme of extension.packageJSON.contributes.themes) { + if (theme.label === colorTheme) { + const themePath = path.join(extension.extensionPath, theme.path); + currentTheme = fs.readFileSync(themePath).toString(); + break; + } + } + } + } + + // Strip comments from theme + currentTheme = currentTheme + ?.split("\n") + .filter((line) => { + return !line.trim().startsWith("//"); + }) + .join("\n"); + } catch (e) { + console.log("Error adding .continueignore file icon: ", e); + } + return ` @@ -730,11 +806,6 @@ export function getSidebarContent( - - - - - Continue @@ -747,6 +818,8 @@ export function getSidebarContent( + +