From baca0805bf9935f7322100ca42e29f0224c1afe5 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 20 Dec 2024 12:27:42 -0800 Subject: [PATCH] embeddings provider in docs --- core/context/providers/DocsContextProvider.ts | 41 ++-- core/core.ts | 2 +- core/indexing/docs/DocsService.ts | 196 ++++++++---------- core/util/GlobalContext.test.ts | 21 +- core/util/GlobalContext.ts | 1 - gui/src/components/dialogs/AddDocsDialog.tsx | 16 ++ .../components/indexing/DocsIndexingPeeks.tsx | 1 + 7 files changed, 135 insertions(+), 143 deletions(-) diff --git a/core/context/providers/DocsContextProvider.ts b/core/context/providers/DocsContextProvider.ts index 6eab55fa4..47542bc1c 100644 --- a/core/context/providers/DocsContextProvider.ts +++ b/core/context/providers/DocsContextProvider.ts @@ -80,22 +80,28 @@ class DocsContextProvider extends BaseContextProvider { query: string, extras: ContextProviderExtras, ): Promise { + // Get docs service const docsService = DocsService.getSingleton(); - if (!docsService) { console.error(`${DocsService.name} has not been initialized`); return []; } - await docsService.isInitialized; + + // Get chunks let chunks = await docsService.retrieveChunksFromQuery( extras.fullInput, // confusing: fullInput = the query, query = startUrl in this case query, this.options?.nRetrieve ?? DocsContextProvider.nRetrieve, ); + if(!chunks?.length) { + return []; + } + // We found chunks, so check if there's a favicon for the docs page const favicon = await docsService.getFavicon(query); + // Rerank if there's a rerankder if (extras.reranker) { chunks = await this._rerankChunks( chunks, @@ -139,18 +145,30 @@ class DocsContextProvider extends BaseContextProvider { async loadSubmenuItems( args: LoadSubmenuItemsArgs, ): Promise { + // Get docs service const docsService = DocsService.getSingleton(); - if (!docsService) { console.error(`${DocsService.name} has not been initialized`); return []; } + await docsService.isInitialized; - const docs = (await docsService.listMetadata()) ?? []; - const canUsePreindexedDocs = await docsService.canUsePreindexedDocs(); - + // Create map of docs url -> submenu item const submenuItemsMap = new Map(); + // Add custom docs from config + const docs = (await docsService.listMetadata()) ?? []; + for (const { startUrl, title, favicon } of docs) { + submenuItemsMap.set(startUrl, { + title,\ + id: startUrl, + description: new URL(startUrl).hostname, + icon: favicon, + }); + } + + // Add pre-indexed docs if supported + const canUsePreindexedDocs = await docsService.canUsePreindexedDocs(); if (canUsePreindexedDocs) { for (const { startUrl, title } of Object.values(preIndexedDocs)) { submenuItemsMap.set(startUrl, { @@ -164,17 +182,8 @@ class DocsContextProvider extends BaseContextProvider { } } - for (const { startUrl, title, favicon } of docs) { - submenuItemsMap.set(startUrl, { - title, - id: startUrl, - description: new URL(startUrl).hostname, - icon: favicon, - }); - } - + // Create array and sort if pre-indexed is supported const submenuItems = Array.from(submenuItemsMap.values()); - if (canUsePreindexedDocs) { return this._sortByPreIndexedDocs(submenuItems); } diff --git a/core/core.ts b/core/core.ts index fb3840d05..bea254c81 100644 --- a/core/core.ts +++ b/core/core.ts @@ -286,7 +286,7 @@ export class Core { }); on("context/indexDocs", async (msg) => { - await this.docsService.syncOrReindexAllDocsWithPrompt(msg.data.reIndex); + await this.docsService.syncDocsWithPrompt(msg.data.reIndex); }); on("context/loadSubmenuItems", async (msg) => { diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 5480dc161..0af6aa28f 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -185,7 +185,6 @@ export default class DocsService { abort(startUrl: string) { const status = this.statuses.get(startUrl); if (status) { - this.docsIndexingQueue.delete(startUrl); this.handleStatusUpdate({ ...status, status: "aborted", @@ -193,6 +192,7 @@ export default class DocsService { description: "Canceled", }); } + this.docsIndexingQueue.delete(startUrl); } isAborted(startUrl: string) { @@ -256,93 +256,79 @@ export default class DocsService { this.docsCrawler = new DocsCrawler(this.ide, newConfig); + if (this.config.disableIndexing) { + return; + } + + // No point in indexing if no docs context provider + const hasDocsContextProvider = this.hasDocsContextProvider(); + if (!hasDocsContextProvider) { + return; + } + // Skip docs indexing if not supported + // No warning message here because would show on ANY config update const unsupported = await this.isUsingUnsupportedPreIndexedEmbeddingsProvider(); if (unsupported) { return; } - await this.syncOrReindexAllDocs(newConfig, oldConfig); + await this.syncDocs(oldConfig, newConfig, false); } } - private async syncOrReindexAllDocs( - newConfig: ContinueConfig, - oldConfig?: ContinueConfig, - ) { - // On embeddings provider change, reindex all non-preindexed docs - // change = doesn't match last successful embeddings provider - const curEmbeddingsProviderId = this.globalContext.get( - "curEmbeddingsProviderId", - ); - if ( - !curEmbeddingsProviderId || - curEmbeddingsProviderId !== newConfig.embeddingsProvider.embeddingId - ) { - // If not set, we're initializing - const currentDocs = await this.listMetadata(); - if (currentDocs.length > 0) { - await this.reindexDocsOnNewEmbeddingsProvider(); - return; - } - } - - await this.syncDocsOnConfigUpdate(oldConfig, newConfig); - } - - async syncOrReindexAllDocsWithPrompt(reIndex: boolean = false) { + async syncDocsWithPrompt(reIndex: boolean = false) { if (!this.hasDocsContextProvider()) { - const didAddDocsContextProvider = - await this.showAddDocsContextProviderToast(); + const actionMsg = "Add 'docs' context provider"; + const res = await this.ide.showToast( + "info", + "Starting docs indexing", + actionMsg, + ); - if (!didAddDocsContextProvider) { + if (res === actionMsg) { + addContextProvider({ + name: DocsContextProvider.description.title, + params: {}, + }); + + void this.ide.showToast( + "info", + "Successfuly added docs context provider", + ); + } else { return; } } - await this.syncOrReindexAllDocs(this.config); + await this.syncDocs(undefined, this.config, reIndex); void this.ide.showToast("info", "Docs indexing completed"); } + // Returns true if startUrl has been indexed with current embeddingsProvider async hasMetadata(startUrl: string): Promise> { const db = await this.getOrCreateSqliteDb(); const title = await db.get( - `SELECT title FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`, + `SELECT title FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`, startUrl, + this.config.embeddingsProvider.embeddingId, ); return !!title; } - async showAddDocsContextProviderToast() { - const actionMsg = "Add 'docs' context provider"; - const res = await this.ide.showToast( - "info", - "Starting docs indexing", - actionMsg, - ); - - if (res === actionMsg) { - addContextProvider({ - name: DocsContextProvider.description.title, - params: {}, - }); - - void this.ide.showToast( - "info", - "Successfuly added docs context provider", - ); - } - - return res === actionMsg; - } - async listMetadata() { + const embeddingsProvider = this.config.embeddingsProvider; + if (!embeddingsProvider) { + return []; + } const db = await this.getOrCreateSqliteDb(); const docs = await db.all( - `SELECT title, startUrl, favicon FROM ${DocsService.sqlitebTableName}`, + `SELECT title, startUrl, favicon FROM ${DocsService.sqlitebTableName} + WHERE embeddingsProviderId = ?`, + embeddingsProvider.embeddingId, ); return docs; @@ -363,15 +349,21 @@ export default class DocsService { ): Promise { const { startUrl } = siteIndexingConfig; + const canUsePreindexedDocs = await this.canUsePreindexedDocs(); + if (canUsePreindexedDocs) { + const preIndexedDoc = preIndexedDocs[startUrl]; + const isPreIndexedDoc = !!preIndexedDoc; + if (isPreIndexedDoc) { + console.warn("Can only use pre"); + } + } + // Queue - indexAndAdd is invoked circularly by config edits. This prevents duplicate runs if (this.docsIndexingQueue.has(startUrl)) { return; } const embeddingsProvider = await this.getEmbeddingsProvider(); - - this.docsIndexingQueue.add(startUrl); - const indexExists = await this.hasMetadata(startUrl); // Build status update - most of it is fixed values @@ -404,12 +396,9 @@ export default class DocsService { return; } } + this.docsIndexingQueue.add(startUrl); - // If not preindexed - const isPreIndexedDoc = !!preIndexedDocs[siteIndexingConfig.startUrl]; - if (!isPreIndexedDoc) { - this.addToConfig(siteIndexingConfig); - } + this.addToConfig(siteIndexingConfig); try { this.handleStatusUpdate({ @@ -650,13 +639,18 @@ export default class DocsService { return await this.retrieveChunks(startUrl, vector, nRetrieve); } + // This is split into its own function so that it can be recursive + // in the case of fetching preindexed docs from s3 async retrieveChunks( startUrl: string, vector: number[], nRetrieve: number, isRetry: boolean = false, ): Promise { - const isPreIndexedDoc = !!preIndexedDocs[startUrl]; + const preIndexedDoc = preIndexedDocs[startUrl]; + const isPreIndexedDoc = !!preIndexedDoc; + + // Lance doesn't have an embeddingsprovider column, instead it includes it in the table name const table = await this.getOrCreateLanceTable({ initializationVector: vector, isPreIndexedDoc, @@ -673,19 +667,21 @@ export default class DocsService { console.warn("Error retrieving chunks from LanceDB", e); } - const hasIndexedDoc = await this.hasMetadata(startUrl); - - if (!hasIndexedDoc && docs.length === 0) { - const preIndexedDoc = preIndexedDocs[startUrl]; - - if (isRetry || !preIndexedDoc) { + // No docs are found for preindexed? try fetching once + if (docs.length === 0 && isPreIndexedDoc) { + if (isRetry) { return []; } - await this.fetchAndAddPreIndexedDocEmbeddings(preIndexedDoc.title); return await this.retrieveChunks(startUrl, vector, nRetrieve, true); } + if (isPreIndexedDoc) { + void Telemetry.capture("docs_pre_indexed_doc_used", { + doc: preIndexedDoc["title"], + }); + } + return docs.map((doc) => ({ digest: doc.path, filepath: doc.path, @@ -747,9 +743,10 @@ export default class DocsService { Sync with no embeddings provider change Ignores pre-indexed docs */ - private async syncDocsOnConfigUpdate( + private async syncDocs( oldConfig: ContinueConfig | undefined, newConfig: ContinueConfig, + reindex: boolean, ) { try { this.isSyncing = true; @@ -869,9 +866,7 @@ export default class DocsService { return name.replace(/[^a-zA-Z0-9_.-]/g, "_"); } - private async getLanceTableNameFromEmbeddingsProvider( - isPreIndexedDoc: boolean, - ) { + private async getLanceTableName(isPreIndexedDoc: boolean) { const embeddingsProvider = await this.getEmbeddingsProvider(isPreIndexedDoc); @@ -892,7 +887,7 @@ export default class DocsService { const conn = await lancedb.connect(getLanceDbPath()); const tableNames = await conn.tableNames(); const tableNameFromEmbeddingsProvider = - await this.getLanceTableNameFromEmbeddingsProvider(!!isPreIndexedDoc); + await this.getLanceTableName(!!isPreIndexedDoc); if (!tableNames.includes(tableNameFromEmbeddingsProvider)) { if (initializationVector) { @@ -949,10 +944,11 @@ export default class DocsService { }: AddParams) { const db = await this.getOrCreateSqliteDb(); await db.run( - `INSERT INTO ${DocsService.sqlitebTableName} (title, startUrl, favicon) VALUES (?, ?, ?)`, + `INSERT INTO ${DocsService.sqlitebTableName} (title, startUrl, favicon, embeddingsProviderId) VALUES (?, ?, ?, ?)`, title, startUrl, favicon, + this.config.embeddingsProvider.embeddingId, ); } @@ -960,13 +956,23 @@ export default class DocsService { // Handles the case where a user has manually added the doc to config.json // so it already exists in the file const doesDocExist = this.config.docs?.some( - (doc) => doc.startUrl === siteIndexingConfig.startUrl, + (doc) => + doc.startUrl === siteIndexingConfig.startUrl && + doc.faviconUrl === siteIndexingConfig.faviconUrl && + siteIndexingConfig.title === doc.title, + // siteIndexingConfig.maxDepth === doc.maxDepth && + // doc.rootUrl === siteIndexingConfig.rootUrl, ); if (!doesDocExist) { editConfigJson((config) => ({ ...config, - docs: [...(config.docs ?? []), siteIndexingConfig], + docs: [ + ...(config.docs?.filter( + (doc) => doc.startUrl !== siteIndexingConfig.startUrl, + ) ?? []), + siteIndexingConfig, + ], })); } } @@ -1017,34 +1023,4 @@ export default class DocsService { this.deleteFromConfig(startUrl); this.messenger?.send("refreshSubmenuItems", undefined); } - - /** - * Currently this deletes re-crawls + re-indexes all docs. - * A more optimal solution in the future will be to create - * a per-embeddings-provider table for docs. - */ - private async reindexDocsOnNewEmbeddingsProvider() { - // We use config as our source of truth here since it contains additional information - // needed for re-crawling such as `faviconUrl` and `maxDepth`. - const { docs, embeddingsProvider } = this.config; - - if (!docs || docs.length === 0) { - return; - } - - console.log( - `Reindexing non-preindexed docs with new embeddings provider: ${embeddingsProvider.embeddingId}`, - ); - await Promise.allSettled(docs.map((doc) => this.indexAndAdd(doc))); - - // Important that this only is invoked after we have successfully - // cleared and reindex the docs so that the table cannot end up in an - // invalid state. - this.globalContext.update( - "curEmbeddingsProviderId", - embeddingsProvider.embeddingId, - ); - - console.log("Completed reindexing of all non-preindexed docs"); - } } diff --git a/core/util/GlobalContext.test.ts b/core/util/GlobalContext.test.ts index 6014a1d1d..0d6b9d799 100644 --- a/core/util/GlobalContext.test.ts +++ b/core/util/GlobalContext.test.ts @@ -75,7 +75,7 @@ describe("GlobalContext", () => { const value = globalContext.get("indexingPaused"); expect(value).toBeUndefined(); expect(consoleWarnMock).toHaveBeenCalledWith( - expect.stringContaining("Error parsing global context") + expect.stringContaining("Error parsing global context"), ); // Clean up @@ -99,7 +99,7 @@ describe("GlobalContext", () => { expect(value).toBeUndefined(); expect(consoleWarnMock).toHaveBeenCalledWith( - expect.stringContaining("Error updating global context") + expect.stringContaining("Error updating global context"), ); // Clean up @@ -113,10 +113,10 @@ describe("GlobalContext", () => { expect(globalContext.get("indexingPaused")).toBe(true); expect(globalContext.get("selectedTabAutocompleteModel")).toBe( - "test-model" + "test-model", ); expect(globalContext.get("hasDismissedConfigTsNoticeJetBrains")).toBe( - false + false, ); }); @@ -125,16 +125,7 @@ describe("GlobalContext", () => { expect(globalContext.get("hasAlreadyCreatedAPromptFile")).toBe(true); }); - it("should handle curEmbeddingsProviderId correctly", () => { - globalContext.update("curEmbeddingsProviderId", "test-provider-id"); - expect(globalContext.get("curEmbeddingsProviderId")).toBe( - "test-provider-id" - ); - }); - it("should not crash or throw when getting a key that hasn't been set", () => { - expect( - globalContext.get("hasAlreadyCreatedAPromptFile") - ).toBeUndefined(); + expect(globalContext.get("hasAlreadyCreatedAPromptFile")).toBeUndefined(); }); -}); \ No newline at end of file +}); diff --git a/core/util/GlobalContext.ts b/core/util/GlobalContext.ts index 1095234d8..5e4f7c6d7 100644 --- a/core/util/GlobalContext.ts +++ b/core/util/GlobalContext.ts @@ -12,7 +12,6 @@ export type GlobalContextType = { * * For VS Code users, it is unnecessary since we use transformers.js by default. */ - curEmbeddingsProviderId: string; hasDismissedConfigTsNoticeJetBrains: boolean; hasAlreadyCreatedAPromptFile: boolean; showConfigUpdateToast: boolean; diff --git a/gui/src/components/dialogs/AddDocsDialog.tsx b/gui/src/components/dialogs/AddDocsDialog.tsx index 0bcd40fd9..f816369c8 100644 --- a/gui/src/components/dialogs/AddDocsDialog.tsx +++ b/gui/src/components/dialogs/AddDocsDialog.tsx @@ -17,8 +17,10 @@ import DocsIndexingPeeks from "../indexing/DocsIndexingPeeks"; import preIndexedDocs from "core/indexing/docs/preIndexedDocs"; import { updateIndexingStatus } from "../../redux/slices/indexingSlice"; import { useAppSelector } from "../../redux/hooks"; +import { setConfig } from "../../redux/slices/configSlice"; function AddDocsDialog() { + const config = useAppSelector((store) => store.config.config); const posthog = usePostHog(); const dispatch = useDispatch(); @@ -125,6 +127,7 @@ function AddDocsDialog() { } const suggestedTitle = docsResult.details.title ?? docsResult.packageInfo.name; + if (docsResult.details?.docsLinkWarning) { setTitle(suggestedTitle); setStartUrl(docsResult.details.docsLink); @@ -143,6 +146,19 @@ function AddDocsDialog() { // Optimistic status update dispatch( + setConfig({ + ...config, + docs: [ + ...(config.docs?.filter( + (doc) => doc.startUrl !== docsResult.details.docsLink, + ) ?? []), + { + startUrl: docsResult.details.docsLink, + title: suggestedTitle, + faviconUrl: undefined, + }, + ], + }), updateIndexingStatus({ type: "docs", description: "Initializing", diff --git a/gui/src/components/indexing/DocsIndexingPeeks.tsx b/gui/src/components/indexing/DocsIndexingPeeks.tsx index f659b48f9..833c71430 100644 --- a/gui/src/components/indexing/DocsIndexingPeeks.tsx +++ b/gui/src/components/indexing/DocsIndexingPeeks.tsx @@ -3,6 +3,7 @@ import { IndexingStatus } from "core"; import { useMemo } from "react"; import { useNavigate } from "react-router-dom"; import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; +import { useAppSelector } from "../../redux/hooks"; export interface DocsIndexingPeekProps { status: IndexingStatus;