Merge pull request #2826 from continuedev/pe/bm25

feat: use bm25 for fts
This commit is contained in:
Patrick Erichsen 2024-11-06 13:58:04 -08:00 • committed by GitHub
commit dae6770a89
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
12 changed files with 243 additions and 138 deletions

View file

@ -10,13 +10,11 @@ export async function fullTextRetrieve(
const searchStrings = prefix.split("\n").slice(-3);
const results: Chunk[] = [];
searchStrings.forEach(async (searchString) => {
const chunks = await index.retrieve(
[indexTag],
searchString,
3,
undefined,
undefined,
);
const chunks = await index.retrieve({
tags: [indexTag],
text: searchString,
n: 3,
});
results.push(...chunks);
});
return results;

View file

@ -1,32 +0,0 @@
import { BranchAndDir, Chunk } from "../../index.js";
import { FullTextSearchCodebaseIndex } from "../../indexing/FullTextSearchCodebaseIndex.js";
export async function retrieveFts(
query: string,
n: number,
tags: BranchAndDir[],
filterDirectory: string | undefined,
): Promise<Chunk[]> {
const ftsIndex = new FullTextSearchCodebaseIndex();
let ftsResults: Chunk[] = [];
try {
if (query.trim() !== "") {
ftsResults = await ftsIndex.retrieve(
tags,
query
.trim()
.split(" ")
.map((element) => `"${element}"`)
.join(" OR "),
n,
filterDirectory,
undefined,
);
}
return ftsResults;
} catch (e) {
console.warn("Error retrieving from FTS:", e);
return [];
}
}

View file

@ -1,14 +1,11 @@
import {
BranchAndDir,
Chunk,
ContinueConfig,
IDE,
ILLM,
} from "../../../index.js";
import { chunkDocument } from "../../../indexing/chunk/chunk.js";
import { LanceDbIndex } from "../../../indexing/LanceDbIndex.js";
import { retrieveFts } from "../fullTextSearch.js";
import { recentlyEditedFilesCache } from "../recentlyEditedFilesCache.js";
// @ts-ignore
import nlp from "wink-nlp-utils";
import { BranchAndDir, Chunk, ContinueConfig, IDE, ILLM } from "../../../";
import { chunkDocument } from "../../../indexing/chunk/chunk";
import { FullTextSearchCodebaseIndex } from "../../../indexing/FullTextSearchCodebaseIndex";
import { LanceDbIndex } from "../../../indexing/LanceDbIndex";
import { recentlyEditedFilesCache } from "../recentlyEditedFilesCache";
export interface RetrievalPipelineOptions {
llm: ILLM;
@ -23,11 +20,18 @@ export interface RetrievalPipelineOptions {
includeEmbeddings?: boolean; // Used to handle JB w/o an embeddings model
}
export interface RetrievalPipelineRunArguments {
query: string;
tags: BranchAndDir[];
filterDirectory?: string;
}
export interface IRetrievalPipeline {
run(options: RetrievalPipelineOptions): Promise<Chunk[]>;
run(args: RetrievalPipelineRunArguments): Promise<Chunk[]>;
}
export default class BaseRetrievalPipeline implements IRetrievalPipeline {
private ftsIndex = new FullTextSearchCodebaseIndex();
private lanceDbIndex: LanceDbIndex;
constructor(protected readonly options: RetrievalPipelineOptions) {
@ -38,6 +42,49 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
);
}
private getCleanedTrigrams(
query: RetrievalPipelineRunArguments["query"],
): string[] {
let text = nlp.string.removeExtraSpaces(query);
text = nlp.string.stem(text);
let tokens = nlp.string
.tokenize(text, true)
.filter((token: any) => token.tag === "word")
.map((token: any) => token.value);
tokens = nlp.tokens.removeWords(tokens);
tokens = nlp.tokens.setOfWords(tokens);
const cleanedTokens = [...tokens].join(" ");
const trigrams = nlp.string.ngram(cleanedTokens, 3);
return trigrams;
}
protected async retrieveFts(
args: RetrievalPipelineRunArguments,
n: number,
): Promise<Chunk[]> {
try {
if (args.query.trim() === "") {
return [];
}
const tokens = this.getCleanedTrigrams(args.query).join(" OR ");
return await this.ftsIndex.retrieve({
n,
text: tokens,
tags: args.tags,
directory: args.filterDirectory,
});
} catch (e) {
console.warn("Error retrieving from FTS:", e);
return [];
}
}
protected async retrieveAndChunkRecentlyEditedFiles(
n: number,
): Promise<Chunk[]> {
@ -75,15 +122,6 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
return chunks.slice(0, n);
}
protected async retrieveFts(input: string, n: number): Promise<Chunk[]> {
return retrieveFts(
input,
n,
this.options.tags,
this.options.filterDirectory,
);
}
protected async retrieveEmbeddings(
input: string,
n: number,
@ -96,7 +134,7 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
);
}
run(): Promise<Chunk[]> {
run(args: RetrievalPipelineRunArguments): Promise<Chunk[]> {
throw new Error("Not implemented");
}
}

View file

@ -1,10 +1,13 @@
import { Chunk } from "../../../index.js";
import { requestFilesFromRepoMap } from "../repoMapRequest.js";
import { deduplicateChunks } from "../util.js";
import BaseRetrievalPipeline from "./BaseRetrievalPipeline.js";
import { Chunk } from "../../../";
import { requestFilesFromRepoMap } from "../repoMapRequest";
import { deduplicateChunks } from "../util";
import BaseRetrievalPipeline, {
RetrievalPipelineRunArguments,
} from "./BaseRetrievalPipeline";
export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
async run(): Promise<Chunk[]> {
async run(args: RetrievalPipelineRunArguments): Promise<Chunk[]> {
const { input, nFinal, filterDirectory, includeEmbeddings } = this.options;
// We give 1/4 weight to recently edited files, 1/4 to full text search,
@ -15,7 +18,7 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
let retrievalResults: Chunk[] = [];
const ftsChunks = await this.retrieveFts(input, ftsNFinal);
const ftsChunks = await this.retrieveFts(args, ftsNFinal);
const embeddingsChunks = includeEmbeddings
? await this.retrieveEmbeddings(input, embeddingsNFinal)

View file

@ -1,17 +1,22 @@
import { Chunk } from "../../../index.js";
import { RETRIEVAL_PARAMS } from "../../../util/parameters.js";
import { requestFilesFromRepoMap } from "../repoMapRequest.js";
import { deduplicateChunks } from "../util.js";
import BaseRetrievalPipeline from "./BaseRetrievalPipeline.js";
import { Chunk } from "../../..";
import { RETRIEVAL_PARAMS } from "../../../util/parameters";
import { requestFilesFromRepoMap } from "../repoMapRequest";
import { deduplicateChunks } from "../util";
import BaseRetrievalPipeline, {
RetrievalPipelineRunArguments,
} from "./BaseRetrievalPipeline";
export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
private async _retrieveInitial(): Promise<Chunk[]> {
private async _retrieveInitial(
args: RetrievalPipelineRunArguments,
): Promise<Chunk[]> {
const { input, nRetrieve, filterDirectory, includeEmbeddings } =
this.options;
let retrievalResults: Chunk[] = [];
const ftsChunks = await this.retrieveFts(input, nRetrieve);
const ftsChunks = await this.retrieveFts(args, nRetrieve);
const embeddingsChunks = includeEmbeddings
? await this.retrieveEmbeddings(input, nRetrieve)
: [];
@ -104,9 +109,9 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
return results;
}
async run(): Promise<Chunk[]> {
const intialResults = await this._retrieveInitial();
const rankedResults = await this._rerank(this.options.input, intialResults);
async run(args: RetrievalPipelineRunArguments): Promise<Chunk[]> {
let results = await this._retrieveInitial(args);
results = await this._rerank(args.query, results);
// // // Expand top reranked results
// const expanded = await this._expandRankedResults(results);
@ -120,7 +125,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
// TODO: stitch together results
return rankedResults;
return results;
}
}

View file

@ -93,7 +93,11 @@ export async function retrieveContextItemsFromEmbeddings(
};
const pipeline = new pipelineType(pipelineOptions);
const results = await pipeline.run();
const results = await pipeline.run({
tags,
filterDirectory,
query: extras.fullInput,
});
if (results.length === 0) {
throw new Error(

View file

@ -1,6 +1,7 @@
import { BranchAndDir, Chunk, IndexTag, IndexingProgressUpdate } from "../";
import { getBasename } from "../util/index";
import { RETRIEVAL_PARAMS } from "../util/parameters";
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex";
import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex";
import {
@ -10,10 +11,20 @@ import {
type CodebaseIndex,
} from "./types";
export interface RetrieveConfig {
tags: BranchAndDir[];
text: string;
n: number;
directory?: string;
filterPaths?: string[];
bm25Threshold?: number;
}
export class FullTextSearchCodebaseIndex implements CodebaseIndex {
relativeExpectedTime: number = 0.2;
static artifactId = "sqliteFts";
artifactId: string = FullTextSearchCodebaseIndex.artifactId;
pathWeightMultiplier = 10.0;
private async _createTables(db: DatabaseConnection) {
await db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS fts USING fts5(
@ -71,17 +82,17 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex {
desc: `Indexing ${getBasename(item.path)}`,
status: "indexing",
};
markComplete([item], IndexResultType.Compute);
await markComplete([item], IndexResultType.Compute);
}
// Add tag
for (const item of results.addTag) {
markComplete([item], IndexResultType.AddTag);
await markComplete([item], IndexResultType.AddTag);
}
// Remove tag
for (const item of results.removeTag) {
markComplete([item], IndexResultType.RemoveTag);
await markComplete([item], IndexResultType.RemoveTag);
}
// Delete
@ -93,63 +104,81 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex {
await db.run("DELETE FROM fts WHERE path = ?", [item.path]);
markComplete([item], IndexResultType.Delete);
await markComplete([item], IndexResultType.Delete);
}
}
async retrieve(
tags: BranchAndDir[],
text: string,
n: number,
directory: string | undefined,
filterPaths: string[] | undefined,
bm25Threshold: number = RETRIEVAL_PARAMS.bm25Threshold,
): Promise<Chunk[]> {
async retrieve(config: RetrieveConfig): Promise<Chunk[]> {
const db = await SqliteDb.get();
// Notice that the "chunks" artifactId is used because of linking between tables
const tagStrings = tags.map((tag) => {
return tagToString({ ...tag, artifactId: ChunkCodebaseIndex.artifactId });
});
const query = this.buildRetrieveQuery(config);
const parameters = this.getRetrieveQueryParameters(config);
const query = `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 ?`;
let results = await db.all(query, parameters);
let results = await db.all(query, [
...tagStrings,
...(filterPaths || []),
Math.ceil(n),
]);
results = results.filter((result) => result.rank <= bm25Threshold);
results = results.filter(
(result) =>
result.rank <= (config.bm25Threshold ?? RETRIEVAL_PARAMS.bm25Threshold),
);
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,
};
});
return chunks.map((chunk) => ({
filepath: chunk.path,
index: chunk.index,
startLine: chunk.startLine,
endLine: chunk.endLine,
content: chunk.content,
digest: chunk.cacheKey,
}));
}
private buildTagFilter(tags: BranchAndDir[]): string {
const tagStrings = this.convertTags(tags);
return `AND chunk_tags.tag IN (${tagStrings.map(() => "?").join(",")})`;
}
private buildPathFilter(filterPaths: string[] | undefined): string {
if (!filterPaths || filterPaths.length === 0) {
return "";
}
return `AND fts_metadata.path IN (${filterPaths.map(() => "?").join(",")})`;
}
private buildRetrieveQuery(config: RetrieveConfig): string {
return `
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 ?
${this.buildTagFilter(config.tags)}
${this.buildPathFilter(config.filterPaths)}
ORDER BY bm25(fts, ${this.pathWeightMultiplier})
LIMIT ?
`;
}
private getRetrieveQueryParameters(config: RetrieveConfig) {
const { text, tags, filterPaths, n } = config;
const tagStrings = this.convertTags(tags);
return [
text.replace(/\?/g, ""),
...tagStrings,
...(filterPaths || []),
Math.ceil(n),
];
}
private convertTags(tags: BranchAndDir[]): string[] {
// Notice that the "chunks" artifactId is used because of linking between tables
return tags.map((tag) =>
tagToString({ ...tag, artifactId: ChunkCodebaseIndex.artifactId }),
);
}
}

64
core/package-lock.json generated
View file

@ -64,6 +64,7 @@
"vectordb": "^0.4.20",
"web-tree-sitter": "^0.21.0",
"win-ca": "^3.5.1",
"wink-nlp-utils": "^2.1.0",
"workerpool": "^9.1.3",
"yaml": "^2.4.2",
"zod": "^3.23.8"
@ -14850,6 +14851,69 @@
"node": ">=4"
}
},
"node_modules/wink-distance": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/wink-distance/-/wink-distance-2.0.2.tgz",
"integrity": "sha512-pyEhUB/OKFYcgOC4J6E+c+gwVA/8qg2s5n49mIcUsJZM5iDSa17uOxRQXR4rvfp+gbj55K/I08FwjFBwb6fq3g==",
"dependencies": {
"wink-helpers": "^2.0.0",
"wink-jaro-distance": "^2.0.0"
}
},
"node_modules/wink-eng-lite-web-model": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/wink-eng-lite-web-model/-/wink-eng-lite-web-model-1.8.0.tgz",
"integrity": "sha512-PlSaw2tzQ2SrKYEaH6AbxIUCFnQ9H7FeReVluV9O9VpgfYYa+urttUoAgzDrVujeMkJtACAIY8eFIkQgbEMpPg==",
"engines": {
"node": ">=16.0.0"
}
},
"node_modules/wink-helpers": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/wink-helpers/-/wink-helpers-2.0.0.tgz",
"integrity": "sha512-I/ZzXrHcNRXuoeFJmp2vMVqDI6UCK02Tds1WP4kSGAmx520gjL1BObVzF7d2ps24tyHIly9ngdB2jwhlFUjPvg=="
},
"node_modules/wink-jaro-distance": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/wink-jaro-distance/-/wink-jaro-distance-2.0.0.tgz",
"integrity": "sha512-9bcUaXCi9N8iYpGWbFkf83OsBkg17r4hEyxusEzl+nnReLRPqxhB9YNeRn3g54SYnVRNXP029lY3HDsbdxTAuA=="
},
"node_modules/wink-nlp": {
"version": "1.14.3",
"resolved": "https://registry.npmjs.org/wink-nlp/-/wink-nlp-1.14.3.tgz",
"integrity": "sha512-lvY5iCs3T8I34F8WKS70+2P0U9dWLn3vdPf/Z+m2VK14N7OmqnPzmHfh3moHdusajoQ37Em39z0IZB9K4x/96A=="
},
"node_modules/wink-nlp-utils": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/wink-nlp-utils/-/wink-nlp-utils-2.1.0.tgz",
"integrity": "sha512-b7PcRhEBNxQmsmht70jLOkwYUyie3da4/cgEXL+CumYO5b/nwV+W7fuMXToh5BtGq1RABznmc2TGTp1Qf/JUXg==",
"dependencies": {
"wink-distance": "^2.0.1",
"wink-eng-lite-web-model": "^1.4.3",
"wink-helpers": "^2.0.0",
"wink-nlp": "^1.12.0",
"wink-porter2-stemmer": "^2.0.1",
"wink-tokenizer": "^5.2.3"
}
},
"node_modules/wink-porter2-stemmer": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/wink-porter2-stemmer/-/wink-porter2-stemmer-2.0.1.tgz",
"integrity": "sha512-0g+RkkqhRXFmSpJQStVXW5N/WsshWpJXsoDRW7DwVkGI2uDT6IBCoq3xdH5p6IHLaC6ygk7RWUsUx4alKxoagQ=="
},
"node_modules/wink-tokenizer": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/wink-tokenizer/-/wink-tokenizer-5.3.0.tgz",
"integrity": "sha512-O/yAw0g3FmSgeeQuYAJJfP7fVPB4A6ay0018qASh79aWmIOyPYy4j4r9EQT8xBjicja6lCLvgRVAybmEBaATQA==",
"dependencies": {
"emoji-regex": "^9.0.0"
}
},
"node_modules/wink-tokenizer/node_modules/emoji-regex": {
"version": "9.2.2",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz",
"integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg=="
},
"node_modules/word-wrap": {
"version": "1.2.5",
"resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz",

View file

@ -95,6 +95,7 @@
"vectordb": "^0.4.20",
"web-tree-sitter": "^0.21.0",
"win-ca": "^3.5.1",
"wink-nlp-utils": "^2.1.0",
"workerpool": "^9.1.3",
"yaml": "^2.4.2",
"zod": "^3.23.8"

View file

@ -149,6 +149,7 @@
"vectordb": "^0.4.20",
"web-tree-sitter": "^0.21.0",
"win-ca": "^3.5.1",
"wink-nlp-utils": "^2.1.0",
"workerpool": "^9.1.3",
"yaml": "^2.4.2",
"zod": "^3.23.8"

1
gui/package-lock.json generated
View file

@ -151,6 +151,7 @@
"vectordb": "^0.4.20",
"web-tree-sitter": "^0.21.0",
"win-ca": "^3.5.1",
"wink-nlp-utils": "^2.1.0",
"workerpool": "^9.1.3",
"yaml": "^2.4.2",
"zod": "^3.23.8"

View file

@ -131,7 +131,6 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) {
const defaultModel = useSelector(defaultModelSelector);
const isTerminal = isTerminalCodeBlock(props.language, props.text);
const [isCopied, setIsCopied] = useState(false);
const [isApplying, setIsApplying] = useState(false);
const streamIdRef = useRef<string | null>(null);
if (streamIdRef.current === null) {
@ -149,10 +148,11 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) {
useWebviewListener(
"applyCodeFromChat",
async () => {
await ideMessenger.request("applyToCurrentFile", {
await ideMessenger.request("applyToFile", {
curSelectedModelTitle: defaultModel.title,
text: props.text,
streamId: streamIdRef.current,
filepath: props.filepath,
});
dispatch(incrementNextCodeBlockToApplyIndex({}));
},
@ -172,8 +172,6 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) {
}
async function onClickApply() {
if (isApplying) return;
if (isTerminal) {
await ideMessenger.ide.runCommand(getTerminalCommand(props.text));
return;
@ -232,7 +230,6 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) {
{!isJetBrains() && isTerminal && (
<ButtonWithTooltip
text="Run in terminal"
disabled={isApplying}
style={{ backgroundColor: vscEditorBackground }}
onClick={onClickApply}
>
@ -240,15 +237,11 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) {
</ButtonWithTooltip>
)}
<ButtonWithTooltip
text={isApplying ? "Applying..." : "Apply"}
text="Apply"
style={{ backgroundColor: vscEditorBackground }}
onClick={onClickApply}
>
{isApplying ? (
<CheckIcon className="h-4 w-4 text-green-400" />
) : (
<PlayIcon className="h-4 w-4 text-gray-400" />
)}
<PlayIcon className="h-4 w-4 text-gray-400" />
</ButtonWithTooltip>
<ButtonWithTooltip
text="Insert at cursor"