🚧 Store / retrieve docs with LanceDB

This commit is contained in:
Nate Sesti 2024-01-20 21:32:26 -08:00
parent 86d89eba9d
commit 74a4539bfa
8 changed files with 181 additions and 14 deletions

View file

@ -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<ContextSubmenuItem[]> {
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,
}));
}
}

5
core/index.d.ts vendored
View file

@ -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;

View file

@ -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<IndexingProgressUpdate> {
const tableName = this.tableNameForTag(tag);
const db = await lancedb.connect(getLanceDbPath());

View file

@ -44,6 +44,12 @@ async function crawlLinks(path: string, baseUrl: URL, visited: Set<string>) {
);
}
export async function crawlSubpages(baseUrl: URL) {
const visited = new Set<string>();
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<string>) {
const nhm = new NodeHtmlMarkdown({}, undefined, undefined);
async function convertURLToMarkdown(url: string): Promise<string> {
export async function convertURLToMarkdown(url: URL): Promise<string> {
try {
const response = await fetch(url);
const htmlContent = await response.text();

93
core/indexing/docs/db.ts Normal file
View file

@ -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<Chunk[]> {
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;
}

View file

@ -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<IndexingProgressUpdate> {
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",
};
}

View file

@ -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<IndexingProgressUpdate> {
const add = [...results.compute, ...results.addTag];
const remove = [...results.del, ...results.removeTag];
await Promise.all([

View file

@ -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<IndexingProgressUpdate>;
}
export type PathAndCacheKey = {