diff --git a/core/context/providers/DocsContextProvider.ts b/core/context/providers/DocsContextProvider.ts index 80d5123c4..d1879f1a9 100644 --- a/core/context/providers/DocsContextProvider.ts +++ b/core/context/providers/DocsContextProvider.ts @@ -6,7 +6,6 @@ import { ContextSubmenuItem, LoadSubmenuItemsArgs, } from "../.."; -import { getIndexSqlitePath } from "../../util/paths"; class DocsContextProvider extends BaseContextProvider { static description: ContextProviderDescription = { @@ -26,14 +25,13 @@ class DocsContextProvider extends BaseContextProvider { async loadSubmenuItems( args: LoadSubmenuItemsArgs ): Promise { - const { open } = await import("sqlite"); - const sqlite3 = await import("sqlite3"); - // Load from SQLite, or shared registry - const db = await open({ - filename: getIndexSqlitePath(), - driver: sqlite3.Database, - }); - return []; + const { listDocs } = await import("../../indexing/docs/db"); + const docs = await listDocs(); + return docs.map((doc) => ({ + title: doc.title, + description: new URL(doc.baseUrl).hostname, + id: doc.baseUrl, + })); } } diff --git a/core/index.d.ts b/core/index.d.ts index c8d6ed768..c1a50fa40 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -11,6 +11,11 @@ export interface Chunk extends ChunkWithoutID { index: number; // Index of the chunk in the document at filepath } +export interface IndexingProgressUpdate { + progress: number; + desc: string; +} + export interface LLMReturnValue { prompt: string; completion: string; diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 996454400..feafc3a3a 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -1,7 +1,7 @@ // NOTE: vectordb requirement must be listed in extensions/vscode to avoid error import { v4 as uuidv4 } from "uuid"; import * as lancedb from "vectordb"; -import { Chunk, EmbeddingsProvider } from ".."; +import { Chunk, EmbeddingsProvider, IndexingProgressUpdate } from ".."; import { MAX_CHUNK_SIZE } from "../llm/constants"; import { getBasename } from "../util"; import { getLanceDbPath } from "../util/paths"; @@ -137,7 +137,7 @@ export class LanceDbIndex implements CodebaseIndex { items: PathAndCacheKey[], resultType: IndexResultType ) => void - ): AsyncGenerator<{ progress: number; desc: string }> { + ): AsyncGenerator { const tableName = this.tableNameForTag(tag); const db = await lancedb.connect(getLanceDbPath()); diff --git a/core/indexing/docs/crawl.ts b/core/indexing/docs/crawl.ts index f54efb326..909483b0c 100644 --- a/core/indexing/docs/crawl.ts +++ b/core/indexing/docs/crawl.ts @@ -44,6 +44,12 @@ async function crawlLinks(path: string, baseUrl: URL, visited: Set) { ); } +export async function crawlSubpages(baseUrl: URL) { + const visited = new Set(); + await crawlLinks(baseUrl.pathname, baseUrl, visited); + return [...visited]; +} + // class NoEscapeTurndownService extends TurndownService { // escape(str: string): string { // return str; @@ -68,7 +74,7 @@ async function crawlLinks(path: string, baseUrl: URL, visited: Set) { const nhm = new NodeHtmlMarkdown({}, undefined, undefined); -async function convertURLToMarkdown(url: string): Promise { +export async function convertURLToMarkdown(url: URL): Promise { try { const response = await fetch(url); const htmlContent = await response.text(); diff --git a/core/indexing/docs/db.ts b/core/indexing/docs/db.ts new file mode 100644 index 000000000..e16dff4cc --- /dev/null +++ b/core/indexing/docs/db.ts @@ -0,0 +1,93 @@ +import { open } from "sqlite"; +import sqlite3 from "sqlite3"; +import * as lancedb from "vectordb"; +import { Chunk } from "../.."; +import { getIndexSqlitePath, getLanceDbPath } from "../../util/paths"; + +const DOCS_TABLE_NAME = "docs"; + +interface LanceDbDocsRow { + title: string; + baseUrl: string; + // Chunk + content: string; + path: string; + startLine: number; + endLine: number; + vector: number[]; + [key: string]: any; +} + +export async function retrieveDocs( + baseUrl: string, + vector: number[] +): Promise { + const lance = await lancedb.connect(getLanceDbPath()); + const table = await lance.openTable(DOCS_TABLE_NAME); + const docs: LanceDbDocsRow[] = await table + .search(vector) + .limit(20) + .where(`baseUrl = '${baseUrl}'`) + .execute(); + + return docs.map((doc) => ({ + digest: doc.path, + filepath: doc.path, + startLine: doc.startLine, + endLine: doc.endLine, + index: 0, + content: doc.content, + })); +} + +export async function addDocs( + title: string, + baseUrl: URL, + chunks: Chunk[], + embeddings: number[][] +) { + const db = await open({ + filename: getIndexSqlitePath(), + driver: sqlite3.Database, + }); + await db.exec(`CREATE TABLE IF NOT EXISTS docs ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + title STRING NOT NULL, + baseUrl STRING NOT NULL + )`); + await db.run( + `INSERT INTO docs (title, baseUrl) VALUES (?, ?)`, + title, + baseUrl.toString() + ); + + const data: LanceDbDocsRow[] = chunks.map((chunk, i) => ({ + title, + baseUrl: baseUrl.toString(), + content: chunk.content, + path: chunk.filepath, + startLine: chunk.startLine, + endLine: chunk.endLine, + vector: embeddings[i], + })); + + const lance = await lancedb.connect(getLanceDbPath()); + const tableNames = await lance.tableNames(); + if (!tableNames.includes(DOCS_TABLE_NAME)) { + await lance.createTable(DOCS_TABLE_NAME, data); + } else { + const table = await lance.openTable(DOCS_TABLE_NAME); + await table.add(data); + } +} + +export async function listDocs(): Promise< + { title: string; baseUrl: string }[] +> { + const db = await open({ + filename: getIndexSqlitePath(), + driver: sqlite3.Database, + }); + const docs = await db.all(`SELECT title, baseUrl FROM docs`); + return docs; +} diff --git a/core/indexing/docs/index.ts b/core/indexing/docs/index.ts new file mode 100644 index 000000000..9cee2c5cb --- /dev/null +++ b/core/indexing/docs/index.ts @@ -0,0 +1,62 @@ +import { + Chunk, + ChunkWithoutID, + EmbeddingsProvider, + IndexingProgressUpdate, +} from "../.."; +import { MAX_CHUNK_SIZE } from "../../llm/constants"; +import { markdownChunker } from "../chunk/markdown"; +import { convertURLToMarkdown, crawlSubpages } from "./crawl"; +import { addDocs } from "./db"; + +export async function* indexDocs( + title: string, + baseUrl: URL, + embeddingsProvider: EmbeddingsProvider +): AsyncGenerator { + yield { + progress: 0, + desc: "Finding subpages...", + }; + + const subpaths = await crawlSubpages(baseUrl); + const chunks: Chunk[] = []; + const embeddings: number[][] = []; + + for (let i = 0; i < subpaths.length; i++) { + const subpath = subpaths[i]; + yield { + progress: (i + 1) / (subpaths.length + 1), + desc: `Indexing ${subpath}...`, + }; + + const subpathUrl = new URL(subpath, baseUrl); + + const markdown = await convertURLToMarkdown(subpathUrl); + const markdownChunks: ChunkWithoutID[] = []; + for await (const chunk of markdownChunker(markdown, MAX_CHUNK_SIZE, 0)) { + markdownChunks.push(chunk); + } + + const embeddings = await embeddingsProvider.embed( + markdownChunks.map((chunk) => chunk.content) + ); + + markdownChunks.forEach((chunk, index) => { + chunks.push({ + ...chunk, + filepath: subpath, + index, + digest: subpath, + }); + }); + embeddings.push(...embeddings); + } + + await addDocs(title, baseUrl, chunks, embeddings); + + yield { + progress: 1, + desc: "Done", + }; +} diff --git a/core/indexing/refreshIndex.ts b/core/indexing/refreshIndex.ts index cce0bf62e..94ee72a9f 100644 --- a/core/indexing/refreshIndex.ts +++ b/core/indexing/refreshIndex.ts @@ -1,6 +1,7 @@ import crypto from "crypto"; import { Database, open } from "sqlite"; import sqlite3 from "sqlite3"; +import { IndexingProgressUpdate } from ".."; import { getIndexSqlitePath } from "../util/paths"; import { CodebaseIndex, @@ -323,7 +324,7 @@ export class GlobalCacheCodeBaseIndex implements CodebaseIndex { tag: IndexTag, results: RefreshIndexResults, _: MarkCompleteCallback - ): AsyncGenerator<{ progress: number; desc: string }> { + ): AsyncGenerator { const add = [...results.compute, ...results.addTag]; const remove = [...results.del, ...results.removeTag]; await Promise.all([ diff --git a/core/indexing/types.ts b/core/indexing/types.ts index 7b749458f..dacc88ee6 100644 --- a/core/indexing/types.ts +++ b/core/indexing/types.ts @@ -1,3 +1,5 @@ +import { IndexingProgressUpdate } from ".."; + export enum IndexResultType { Compute = "compute", Delete = "del", @@ -16,7 +18,7 @@ export interface CodebaseIndex { tag: IndexTag, results: RefreshIndexResults, markComplete: MarkCompleteCallback - ): AsyncGenerator<{ progress: number; desc: string }>; + ): AsyncGenerator; } export type PathAndCacheKey = {