From 1da38e226d44d12e42e0f1a88d3f9351e21e916a Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Tue, 9 Jan 2024 21:03:29 -0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=93=9D=20update=20configuration=20and=20d?= =?UTF-8?q?ocs=20for=20codebase=20indexing?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/config/types.ts | 191 ++++++++++-------- .../providers/CodebaseContextProvider.ts | 20 +- core/index.d.ts | 16 -- docs/docs/walkthroughs/codebase-embeddings.md | 99 ++++++--- extensions/vscode/config_schema.json | 146 ++++++------- .../vscode/manual-testing-sandbox/example.ts | 33 +-- extensions/vscode/src/continueIdeClient.ts | 7 + gui/src/hooks/useLoadEmbeddings.tsx | 93 +++++---- gui/src/hooks/useSetup.ts | 2 - 9 files changed, 327 insertions(+), 280 deletions(-) diff --git a/core/config/types.ts b/core/config/types.ts index a20a002ee..11f48ef95 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -1,11 +1,13 @@ const Types = ` declare global { + import { Chunk } from "./index/chunk"; + export interface ILLM extends LLMOptions { get providerName(): ModelProvider; - + uniqueId: string; model: string; - + title?: string; systemMessage?: string; contextLength: number; @@ -17,35 +19,35 @@ declare global { llmRequestHook?: (model: string, prompt: string) => any; apiKey?: string; apiBase?: string; - + engine?: string; apiVersion?: string; apiType?: string; region?: string; projectId?: string; - + _fetch?: (input: any, init?: any) => Promise; - + complete(prompt: string, options?: LLMFullCompletionOptions): Promise; - + streamComplete( prompt: string, options?: LLMFullCompletionOptions ): AsyncGenerator; - + streamChat( messages: ChatMessage[], options?: LLMFullCompletionOptions ): AsyncGenerator; - + chat( messages: ChatMessage[], options?: LLMFullCompletionOptions ): Promise; - + countTokens(text: string): number; } - + export interface ContextProviderDescription { title: string; displayTitle: string; @@ -53,39 +55,50 @@ declare global { dynamic: boolean; requiresQuery: boolean; } - + + interface ContextProviderExtras { + fullInput: string; + embeddingsProvider?: EmbeddingsProvider; + } + export interface CustomContextProvider { title: string; displayTitle?: string; description?: string; - getContextItems(query: string, fullInput: string): Promise; + getContextItems( + query: string, + extras: ContextProviderExtras + ): Promise; } - + export interface IContextProvider { get description(): ContextProviderDescription; - - getContextItems(query: string, fullInput: string): Promise; + + getContextItems( + query: string, + extras: ContextProviderExtras + ): Promise; } - + export interface PersistedSessionInfo { history: ChatHistory; title: string; workspaceDirectory: string; sessionId: string; } - + export interface SessionInfo { sessionId: string; title: string; dateCreated: string; workspaceDirectory: string; } - + export interface RangeInFile { filepath: string; range: Range; } - + export interface Range { start: Position; end: Position; @@ -99,15 +112,15 @@ declare global { range: Range; replacement: string; } - + export interface ContinueError { title: string; message: string; } - + export interface CompletionOptions { model: string; - + maxTokens: number; temperature?: number; topP?: number; @@ -117,19 +130,19 @@ declare global { frequencyPenalty?: number; stop?: string[]; } - + export type ChatMessageRole = "user" | "assistant" | "system"; - + export interface ChatMessage { role: ChatMessageRole; content: string; } - + export interface ContextItemId { providerTitle: string; itemId: string; } - + export interface ContextItem { content: string; name: string; @@ -137,7 +150,7 @@ declare global { editing?: boolean; editable?: boolean; } - + export interface ContextItemWithId { content: string; name: string; @@ -146,24 +159,24 @@ declare global { editing?: boolean; editable?: boolean; } - + export interface ChatHistoryItem { message: ChatMessage; editorState?: any; contextItems: ContextItemWithId[]; promptLogs?: [string, string][]; // [prompt, completion] } - + export type ChatHistory = ChatHistoryItem[]; - + // LLM - + export interface LLMFullCompletionOptions { raw?: boolean; log?: boolean; - + model?: string; - + temperature?: number; topP?: number; topK?: number; @@ -175,7 +188,7 @@ declare global { } export interface LLMOptions { model: string; - + title?: string; uniqueId?: string; systemMessage?: string; @@ -189,12 +202,12 @@ declare global { llmRequestHook?: (model: string, prompt: string) => any; apiKey?: string; apiBase?: string; - + // Azure options engine?: string; apiVersion?: string; apiType?: string; - + // GCP Options region?: string; projectId?: string; @@ -206,7 +219,7 @@ declare global { { [K in Keys]-?: Required> & Partial>>; }[Keys]; - + export interface CustomLLMWithOptionals { options?: LLMOptions; streamCompletion?: ( @@ -220,7 +233,7 @@ declare global { fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise ) => AsyncGenerator; } - + /** * The LLM interface requires you to specify either \`streamCompletion\` or \`streamChat\` (or both). */ @@ -228,14 +241,14 @@ declare global { CustomLLMWithOptionals, "streamCompletion" | "streamChat" >; - + // IDE - + export interface DiffLine { type: "new" | "old" | "same"; line: string; } - + export interface IDE { getSerializedConfig(): Promise; getConfigJsUrl(): Promise; @@ -262,10 +275,23 @@ declare global { diffLine: DiffLine ): Promise; getOpenFiles(): Promise; + getSearchResults(query: string): Promise; + + // Embeddings + /** + * Returns list of [tag, filepath, hash of contents] that need to be embedded + */ + getFilesToEmbed(): Promise<[string, string, string][]>; + sendEmbeddingForChunk( + chunk: Chunk, + embedding: number[], + tags: string[] + ): void; + retrieveChunks(v: number[], n: number, tags: string[]): Promise; } - + // Slash Commands - + export interface ContinueSDK { ide: IDE; llm: ILLM; @@ -275,20 +301,20 @@ declare global { params?: any; contextItems: ContextItemWithId[]; } - + export interface SlashCommand { name: string; description: string; params?: { [key: string]: any }; run: (sdk: ContinueSDK) => AsyncGenerator; - + // If true, this command will be run in NodeJs and have access to the filesystem and other Node-only APIs // You must make sure to dynamically import any Node-only dependencies in your command so that it doesn't break in the browser runInNodeJs?: boolean; } - + // Config - + type StepName = | "AnswerQuestionChroma" | "GenerateShellCommandStep" @@ -300,7 +326,7 @@ declare global { | "OpenConfigStep" | "GenerateShellCommandStep" | "DraftIssueStep"; - + type ContextProviderName = | "diff" | "github" @@ -311,7 +337,7 @@ declare global { | "url" | "tree" | "http"; - + type TemplateType = | "llama2" | "alpaca" @@ -322,7 +348,7 @@ declare global { | "none" | "openchat" | "deepseek"; - + type ModelProvider = | "openai" | "openai-free-trial" @@ -340,7 +366,7 @@ declare global { | "gemini" | "mistral" | "bedrock"; - + export type ModelName = // OpenAI | "gpt-3.5-turbo" @@ -376,7 +402,7 @@ declare global { | "mistral-tiny" | "mistral-small" | "mistral-medium"; - + export interface RequestOptions { timeout?: number; verifySsl?: boolean; @@ -384,42 +410,29 @@ declare global { proxy?: string; headers?: { [key: string]: string }; } - + export interface StepWithParams { name: StepName; params: { [key: string]: any }; } - + export interface ContextProviderWithParams { name: ContextProviderName; params: { [key: string]: any }; } - + export interface SlashCommandDescription { name: string; description: string; - step: StepName | string; params?: { [key: string]: any }; } - + export interface CustomCommand { name: string; prompt: string; description: string; } - export interface RetrievalSettings { - nRetrieve?: number; - nFinal?: number; - useReranking: boolean; - rerankGroupSize: number; - ignoreFiles: string[]; - openaiApiKey?: string; - apiBase?: string; - apiType?: string; - apiVersion?: string; - organizationId?: string; - } - + interface BaseCompletionOptions { temperature?: number; topP?: number; @@ -430,7 +443,7 @@ declare global { stop?: string[]; maxTokens: number; } - + export interface ModelDescription { title: string; provider: ModelProvider; @@ -444,14 +457,23 @@ declare global { requestOptions?: RequestOptions; promptTemplates?: { [key: string]: string }; } - - export interface ModelRoles { - default: string; - chat?: string; - edit?: string; - summarize?: string; + + export type EmbeddingsProviderName = "transformers.js" | "ollama" | "openai"; + + export interface EmbedOptions { + apiBase?: string; + apiKey?: string; + model: string; } - + + export interface EmbeddingsProviderDescription extends EmbedOptions { + provider: EmbeddingsProviderName; + } + + export interface EmbeddingsProvider { + embed(chunks: string[]): Promise; + } + export interface SerializedContinueConfig { disallowedSteps?: string[]; allowAnonymousTelemetry?: boolean; @@ -461,11 +483,11 @@ declare global { slashCommands?: SlashCommandDescription[]; customCommands?: CustomCommand[]; contextProviders?: ContextProviderWithParams[]; - retrievalSettings?: RetrievalSettings; disableIndexing?: boolean; userToken?: string; + embeddingsProvider?: EmbeddingsProviderDescription; } - + export interface Config { /** If set to true, Continue will collect anonymous usage data to improve the product. If set to false, we will collect nothing. Read here to learn more: https://continue.dev/docs/telemetry */ allowAnonymousTelemetry?: boolean; @@ -484,14 +506,14 @@ declare global { * A CustomContextProvider requires you only to define a title and getContextItems function. When you type '@title ', Continue will call \`getContextItems(query)\`. */ contextProviders?: (CustomContextProvider | ContextProviderWithParams)[]; - /** Settings related to the /codebase retrieval feature */ - retrievalSettings?: RetrievalSettings; /** If set to true, Continue will not index your codebase for retrieval */ disableIndexing?: boolean; /** An optional token to identify a user. Not used by Continue unless you write custom coniguration that requires such a token */ userToken?: string; + /** The provider used to calculate embeddings. If left empty, Continue will use transformers.js to calculate the embeddings with all-MiniLM-L6-v2 */ + embeddingsProvider?: EmbeddingsProviderDescription | EmbeddingsProvider; } - + export interface ContinueConfig { allowAnonymousTelemetry?: boolean; models: ILLM[]; @@ -499,12 +521,11 @@ declare global { completionOptions?: BaseCompletionOptions; slashCommands?: SlashCommand[]; contextProviders?: IContextProvider[]; - retrievalSettings?: RetrievalSettings; disableIndexing?: boolean; userToken?: string; + embeddingsProvider?: EmbeddingsProvider; } - } export {}; diff --git a/core/context/providers/CodebaseContextProvider.ts b/core/context/providers/CodebaseContextProvider.ts index 3f689d09d..73c67c939 100644 --- a/core/context/providers/CodebaseContextProvider.ts +++ b/core/context/providers/CodebaseContextProvider.ts @@ -23,8 +23,26 @@ class CodebaseContextProvider extends BaseContextProvider { if (!extras.embeddingsProvider) { return []; } + + const nRetrieve = this.options.nRetrieve || 20; + const nFinal = this.options.nFinal || 5; + const useReranking = false; + // this.options.useReranking === undefined + // ? true + // : this.options.useReranking; + + // Similarity search const [v] = await extras.embeddingsProvider.embed([extras.fullInput]); - const results = await new ExtensionIde().retrieveChunks(v, 5, []); + const results = await new ExtensionIde().retrieveChunks( + v, + this.options.useReranking === false ? nFinal : nRetrieve, + [] + ); + + // Re-ranking + if (useReranking) { + // TODO + } return results.map((r) => { const name = `${getBasename(r.filepath)} (${r.startLine}-${r.endLine})`; diff --git a/core/index.d.ts b/core/index.d.ts index e834adf8d..6b1fbd064 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -430,18 +430,6 @@ export interface CustomCommand { prompt: string; description: string; } -export interface RetrievalSettings { - nRetrieve?: number; - nFinal?: number; - useReranking: boolean; - rerankGroupSize: number; - ignoreFiles: string[]; - openaiApiKey?: string; - apiBase?: string; - apiType?: string; - apiVersion?: string; - organizationId?: string; -} interface BaseCompletionOptions { temperature?: number; @@ -493,7 +481,6 @@ export interface SerializedContinueConfig { slashCommands?: SlashCommandDescription[]; customCommands?: CustomCommand[]; contextProviders?: ContextProviderWithParams[]; - retrievalSettings?: RetrievalSettings; disableIndexing?: boolean; userToken?: string; embeddingsProvider?: EmbeddingsProviderDescription; @@ -517,8 +504,6 @@ export interface Config { * A CustomContextProvider requires you only to define a title and getContextItems function. When you type '@title ', Continue will call `getContextItems(query)`. */ contextProviders?: (CustomContextProvider | ContextProviderWithParams)[]; - /** Settings related to the /codebase retrieval feature */ - retrievalSettings?: RetrievalSettings; /** If set to true, Continue will not index your codebase for retrieval */ disableIndexing?: boolean; /** An optional token to identify a user. Not used by Continue unless you write custom coniguration that requires such a token */ @@ -534,7 +519,6 @@ export interface ContinueConfig { completionOptions?: BaseCompletionOptions; slashCommands?: SlashCommand[]; contextProviders?: IContextProvider[]; - retrievalSettings?: RetrievalSettings; disableIndexing?: boolean; userToken?: string; embeddingsProvider?: EmbeddingsProvider; diff --git a/docs/docs/walkthroughs/codebase-embeddings.md b/docs/docs/walkthroughs/codebase-embeddings.md index 69b6b0d35..a3a83e803 100644 --- a/docs/docs/walkthroughs/codebase-embeddings.md +++ b/docs/docs/walkthroughs/codebase-embeddings.md @@ -4,61 +4,110 @@ description: Talk to your codebase keywords: [talk, embeddings, codebase, experimental] --- -# Codebase Retrieval +# Codebase retrieval -Continue indexes your codebase so that when you input a message using Command+Enter, it can automatically pull in the most relevant context from throughout your workspace. This is done via a combination of embeddings-based retrieval and keyword search. By default, all embeddings are calculated locally with `all-MiniLM-L6-v2` and stored locally in `~/.continue/index`. +Continue indexes your codebase so that it can later automatically pull in the most relevant context from throughout your workspace. This is done via a combination of embeddings-based retrieval and keyword search. By default, all embeddings are calculated locally with `all-MiniLM-L6-v2` and stored locally in `~/.continue/index`. -The codebase retrieval feature allows the following customization options by editing `config.json` as follows: +## How to use codebase retrieval + +Currently, the codebase retrieval feature is available as the "codebase" context provider. You can use it by typing `@codebase` 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 to determine relevant files. + +There are a few options that let you configure the behavior of the codebase context provider. These can be set in `config.json`: ```json title="~/.continue/config.json" { - "retrievalSettings": { - "nRetrieve": 100, - ... + "contextProviders": [ + { + "name": "codebase", + "params": { + "nRetrieve": 25, + "nFinal": 5, + "useReranking": true + } } + ] } ``` ### `nRetrieve` -Number of results to initially retrieve from vector database (default: 50) +Number of results to initially retrieve from vector database (default: 25) ### `nFinal` -Final number of results to use after re-ranking (default: 10) +Final number of results to use after re-ranking (default: 5) ### `useReranking` -Whether to use re-ranking, which will allow initial selection of `nRetrieve` results, then will use an LLM to select the top `nFinal` results (default: True) +Whether to use re-ranking, which will allow initial selection of `nRetrieve` results, then will use an LLM to select the top `nFinal` results (default: true) -### `rerankGroupSize` +## Embeddings providers -Number of results to group together when re-ranking. Each group will be processed in parallel. (default: 5) +We also support other methods of generating embeddings, which can be configured with the `"embeddingsProvider"` property in `config.json`. We currently have built-in support for the following providers: -### `ignoreFiles` +### Transformers.js -Files to ignore when indexing the codebase. You can use glob patterns, such as `**/*.py`. This is useful for directories that contain generated code, or other directories that are not relevant to the codebase. (default: []) +[Transformers.js](https://huggingface.co/docs/transformers.js/index) is a JavaScript port of the popular [Transformers](https://huggingface.co/transformers/) library. It allows embeddings to be calculated locally in the browser (or in this case inside of the sidebar of your IDE). The model used is `all-MiniLM-L6-v2`, which is shipped alongside the Continue extension and generates embeddings of size 384. -### `openaiApiKey` +```json title="~/.continue/config.json" +{ + "embeddingsProvider": { + "name": "transformers.js" + } +} +``` -OpenAI API key. If set, Continue will calculate embeddings by calling OpenAI's `ada-002` embeddings API. (default: None) +### Ollama -### Azure OpenAI +[Ollama](https://ollama.ai) is the easiest way to get up and running with open-source language models. It provides an entirely local REST API for working with LLMs, including generating embeddings. The embeddings generated are slightly larger, with a size of 4096 for `codellama:7b`. -These settings allow you to connect to an Azure-hosted OpenAI API. All must be filled out in order to use Azure OpenAI for embeddings, as well as the `openaiApiKey`. +```json title="~/.continue/config.json" +{ + "embeddingsProvider": { + "name": "ollama", + "model": "codellama:7b", + "apiBase": "http://localhost:11434" // optional, defaults to http://localhost:11434 + } +} +``` -#### `apiBase` +### OpenAI -OpenAI API base URL (default: None) +```json title="~/.continue/config.json" +{ + "embeddingsProvider": { + "name": "openai", + "model": "text-embedding-ada-002", // optional, defaults to "text-embedding-ada-002" + "apiBase": "" // optional, defaults to OpenAI's API + } +} +``` -#### `apiType` +### Writing a custom `EmbeddingsProvider` -OpenAI API type (default: None) +If you have your own API capable of generating embeddings, Continue makes it easy to write a custom `EmbeddingsProvider`. All you have to do is write a function that converts strings to arrays of numbers, and add this to your config in `config.ts`. Here's an example: -#### `apiVersion` +```ts title="~/.continue/config.ts" +export function modifyConfig(config: Config): Config { + config.embeddingsProvider = { + embed: (chunks: string[]) => { + return Promise.all( + chunks.map(async (chunk) => { + const response = await fetch("https://example.com/embeddings", { + method: "POST", + body: JSON.stringify({ text: chunk }), + }); + const data = await response.json(); + return data.embedding; + }) + ); + }, + }; -OpenAI API version (default: None) + return config; +} +``` -#### `organizationId` +## Customizing which files are indexed -OpenAI organization ID (default: None) +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`. diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index dcbecb875..38bf4c816 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -771,7 +771,8 @@ "google", "search", "url", - "http" + "http", + "codebase" ], "type": "string" }, @@ -807,74 +808,45 @@ }, "required": ["params"] } + }, + { + "if": { + "properties": { + "name": { + "enum": ["codebase"] + } + } + }, + "then": { + "properties": { + "params": { + "properties": { + "nRetrieve": { + "title": "N Retrieve", + "description": "Number of results to initially retrieve from vector database", + "default": 50, + "type": "integer" + }, + "nFinal": { + "title": "N Final", + "description": "Final number of results to use after re-ranking", + "default": 10, + "type": "integer" + }, + "useReranking": { + "title": "Use Reranking", + "description": "Whether to use re-ranking, which will allow initial selection of nRetrieve results, then will use an LLM to select the top nFinal results. Disabling re-ranking will give faster, but less accurate, results.", + "default": true, + "type": "boolean" + } + } + } + } + } } ], "required": ["name"] }, - "RetrievalSettings": { - "title": "RetrievalSettings", - "type": "object", - "properties": { - "nRetrieve": { - "title": "N Retrieve", - "description": "Number of results to initially retrieve from vector database", - "default": 50, - "type": "integer" - }, - "nFinal": { - "title": "N Final", - "description": "Final number of results to use after re-ranking", - "default": 10, - "type": "integer" - }, - "useReranking": { - "title": "Use Reranking", - "description": "Whether to use re-ranking, which will allow initial selection of nRetrieve results, then will use an LLM to select the top nFinal results", - "default": true, - "type": "boolean" - }, - "rerankGroupSize": { - "title": "Rerank Group Size", - "description": "Number of results to group together when re-ranking. Each group will be processed in parallel.", - "default": 5, - "type": "integer" - }, - "ignoreFiles": { - "title": "Ignore Files", - "description": "Files to ignore when indexing the codebase. You can use glob patterns, such as **/*.py. This is useful for directories that contain generated code, or other directories that are not relevant to the codebase.", - "default": [], - "type": "array", - "items": { - "type": "string" - } - }, - "openaiApiKey": { - "title": "Openai Api Key", - "description": "OpenAI API key", - "type": "string" - }, - "apiBase": { - "title": "Api Base", - "description": "OpenAI API base URL", - "type": "string" - }, - "apiType": { - "title": "Api Type", - "description": "OpenAI API type", - "type": "string" - }, - "apiVersion": { - "title": "Api Version", - "description": "OpenAI API version", - "type": "string" - }, - "organizationId": { - "title": "Organization Id", - "description": "OpenAI organization ID", - "type": "string" - } - } - }, "continuedev__core__config__serialized_config__SerializedContinueConfig": { "title": "SerializedContinueConfig", "type": "object", @@ -988,24 +960,38 @@ "default": false, "type": "boolean" }, - "retrievalSettings": { - "title": "Retrieval Settings", - "description": "Settings for the retrieval system. Read more about the retrieval system in the documentation.", - "default": { - "nRetrieve": 50, - "nFinal": 10, - "useReranking": true, - "rerankGroupSize": 5, - "ignoreFiles": [], - "openaiApiKey": null, - "apiBase": null, - "apiType": null, - "apiVersion": null, - "organizationId": null + "embeddingsProvider": { + "title": "Embeddings Provider", + "description": "The method that will be used to generate codebase embeddings. The default is transformers.js, which will run locally in the browser.", + "type": "object", + "properties": { + "provider": { + "enum": ["transformers.js", "ollama"] + }, + "model": { + "type": "string" + }, + "apiKey": { + "type": "string" + }, + "apiBase": { + "type": "string" + } }, + "required": ["provider"], "allOf": [ { - "$ref": "#/definitions/RetrievalSettings" + "if": { + "properties": { + "provider": { + "enum": ["ollama"] + } + }, + "required": ["provider"] + }, + "then": { + "required": ["model"] + } } ] } diff --git a/extensions/vscode/manual-testing-sandbox/example.ts b/extensions/vscode/manual-testing-sandbox/example.ts index afb490c6a..926656243 100644 --- a/extensions/vscode/manual-testing-sandbox/example.ts +++ b/extensions/vscode/manual-testing-sandbox/example.ts @@ -1,32 +1,3 @@ function mergeSortAlgorithm(arr) { - // If the length of the array is less than or equal to one, return the original array - if (arr.length <= 1) { - return arr; - } - - // Find the middle index of the array - const mid = Math.floor(arr.length / 2); - - // Split the array into two halves: left and right - const left = arr.slice(0, mid); - const right = arr.slice(mid); - - // Recursively sort the left and right arrays - return merge(mergeSortAlgorithm(left), mergeSortAlgorithm(right)); -} - -function merge(left, right) { - let result = []; - let leftIndex = 0; - let rightIndex = 0; - while (leftIndex < left.length && rightIndex < right.length) { - if (left[leftIndex] < right[rightIndex]) { - result.push(left[leftIndex]); - leftIndex++; - } else { - result.push(right[rightIndex]); - rightIndex++; - } - } - return result.concat(left.slice(leftIndex)).concat(right.slice(rightIndex)); -} + // TODO +} \ No newline at end of file diff --git a/extensions/vscode/src/continueIdeClient.ts b/extensions/vscode/src/continueIdeClient.ts index 39cdecb1c..62eed2330 100644 --- a/extensions/vscode/src/continueIdeClient.ts +++ b/extensions/vscode/src/continueIdeClient.ts @@ -43,6 +43,13 @@ class IdeProtocolClient { const configJson = JSON.parse(config); this.configUpdate(configJson); configHandler.reloadConfig(); + } else if ( + filepath.endsWith(".continueignore") || + filepath.endsWith(".gitignore") + ) { + debugPanelWebview?.postMessage({ + type: "updateEmbeddings", + }); } }); diff --git a/gui/src/hooks/useLoadEmbeddings.tsx b/gui/src/hooks/useLoadEmbeddings.tsx index 3bd810bdb..716a09695 100644 --- a/gui/src/hooks/useLoadEmbeddings.tsx +++ b/gui/src/hooks/useLoadEmbeddings.tsx @@ -16,53 +16,66 @@ function useLoadEmbeddings() { (store: RootStore) => store.state.config.disableIndexing ); - useEffect(() => { - (async () => { - if (!embeddingsProvider || disableIndexing) { - return; - } + async function loadEmbeddings() { + if (!embeddingsProvider || disableIndexing) { + return; + } - const ide = new ExtensionIde(); + const ide = new ExtensionIde(); - const filesToEmbed = await ide.getFilesToEmbed(); - console.log("Files to embed", filesToEmbed); + const filesToEmbed = await ide.getFilesToEmbed(); - const total = filesToEmbed.length + 1; - let done = 1; + const total = filesToEmbed.length + 1; + let done = 1; - for (let [tag, filepath, hash] of filesToEmbed) { - try { - const contents = await ide.readFile(filepath); - const chunkGenerator = await chunkDocument( - filepath, - contents, - MAX_CHUNK_SIZE, - hash - ); - let chunks: Chunk[] = []; - for await (let chunk of chunkGenerator) { - chunks.push(chunk); - } - - if (chunks.length === 0) { - continue; - } - - const embeddings = await embeddingsProvider.embed( - chunks.map((c) => c.content) - ); - - for (let i = 0; i < chunks.length; i++) { - await ide.sendEmbeddingForChunk(chunks[i], embeddings[i], [tag]); - } - } catch (e) { - console.warn(`Failed to embed ${filepath}`, e); + for (let [tag, filepath, hash] of filesToEmbed) { + try { + const contents = await ide.readFile(filepath); + const chunkGenerator = await chunkDocument( + filepath, + contents, + MAX_CHUNK_SIZE, + hash + ); + let chunks: Chunk[] = []; + for await (let chunk of chunkGenerator) { + chunks.push(chunk); } - done++; - setProgress(done / total); + if (chunks.length === 0) { + done++; + setProgress(done / total); + continue; + } + + const embeddings = await embeddingsProvider.embed( + chunks.map((c) => c.content) + ); + + for (let i = 0; i < chunks.length; i++) { + await ide.sendEmbeddingForChunk(chunks[i], embeddings[i], [tag]); + } + } catch (e) { + console.warn(`Failed to embed ${filepath}`, e); } - })(); + + done++; + setProgress(done / total); + } + } + + useEffect(() => { + const eventListener = (event: any) => { + if (event.data.type === "updateEmbeddings") { + loadEmbeddings(); + } + }; + window.addEventListener("message", eventListener); + return () => window.removeEventListener("message", eventListener); + }, [embeddingsProvider, disableIndexing]); + + useEffect(() => { + loadEmbeddings(); }, [embeddingsProvider, disableIndexing]); return { progress }; diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 03953d98c..d1a8e71cf 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -21,9 +21,7 @@ function useSetup(dispatch: Dispatch) { try { const ide = new ExtensionIde(); let serialized = await ide.getSerializedConfig(); - console.log("serialized: ", serialized); let intermediate = serializedToIntermediateConfig(serialized); - console.log("i1", intermediate); const configJsUrl = await ide.getConfigJsUrl(); if (configJsUrl) {