Elffuss BraidHub

kikocis/continue public

91fbf794ce85 · 4.3 KiBRawPermalink
1// @ts-ignore
2import nlp from "wink-nlp-utils";
3
4import { BranchAndDir, Chunk, ContinueConfig, IDE, ILLM } from "../../../";
5import { openedFilesLruCache } from "../../../autocomplete/util/openedFilesLruCache";
6import { chunkDocument } from "../../../indexing/chunk/chunk";
7import { FullTextSearchCodebaseIndex } from "../../../indexing/FullTextSearchCodebaseIndex";
8import { LanceDbIndex } from "../../../indexing/LanceDbIndex";
9
10const DEFAULT_CHUNK_SIZE = 384;
11
12export interface RetrievalPipelineOptions {
13 llm: ILLM;
14 config: ContinueConfig;
15 ide: IDE;
16 input: string;
17 nRetrieve: number;
18 nFinal: number;
19 tags: BranchAndDir[];
20 filterDirectory?: string;
21}
22
23export interface RetrievalPipelineRunArguments {
24 query: string;
25 tags: BranchAndDir[];
26 filterDirectory?: string;
27 includeEmbeddings: boolean;
28}
29
30export interface IRetrievalPipeline {
31 run(args: RetrievalPipelineRunArguments): Promise<Chunk[]>;
32}
33
34export default class BaseRetrievalPipeline implements IRetrievalPipeline {
35 private ftsIndex = new FullTextSearchCodebaseIndex();
36 private lanceDbIndex: LanceDbIndex | null = null;
37
38 constructor(protected readonly options: RetrievalPipelineOptions) {
39 void this.initLanceDb();
40 }
41
42 private async initLanceDb() {
43 const embedModel = this.options.config.selectedModelByRole.embed;
44
45 if (!embedModel) {
46 return;
47 }
48
49 this.lanceDbIndex = await LanceDbIndex.create(embedModel, (uri) =>
50 this.options.ide.readFile(uri),
51 );
52 }
53
54 private getCleanedTrigrams(
55 query: RetrievalPipelineRunArguments["query"],
56 ): string[] {
57 let text = nlp.string.removeExtraSpaces(query);
58 text = nlp.string.stem(text);
59
60 let tokens = nlp.string
61 .tokenize(text, true)
62 .filter((token: any) => token.tag === "word")
63 .map((token: any) => token.value);
64
65 tokens = nlp.tokens.removeWords(tokens);
66 tokens = nlp.tokens.setOfWords(tokens);
67
68 const cleanedTokens = [...tokens].join(" ");
69 const trigrams = nlp.string.ngram(cleanedTokens, 3);
70
71 return trigrams.map(this.escapeFtsQueryString);
72 }
73
74 private escapeFtsQueryString(query: string): string {
75 const escapedDoubleQuotes = query.replace(/"/g, '""');
76 return `"${escapedDoubleQuotes}"`;
77 }
78
79 protected async retrieveFts(
80 args: RetrievalPipelineRunArguments,
81 n: number,
82 ): Promise<Chunk[]> {
83 if (args.query.trim() === "") {
84 return [];
85 }
86
87 const tokens = this.getCleanedTrigrams(args.query).join(" OR ");
88
89 return await this.ftsIndex.retrieve({
90 n,
91 text: tokens,
92 tags: args.tags,
93 directory: args.filterDirectory,
94 });
95 }
96
97 protected async retrieveAndChunkRecentlyEditedFiles(
98 n: number,
99 ): Promise<Chunk[]> {
100 const recentlyEditedFilesSlice = Array.from(
101 openedFilesLruCache.keys(),
102 ).slice(0, n);
103
104 // If the number of recently edited files is less than the retrieval limit,
105 // include additional open files. This is useful in the case where a user
106 // has many tabs open and reloads their IDE. They now have 0 recently edited files,
107 // but many open tabs that represent what they were working on prior to reload.
108 if (recentlyEditedFilesSlice.length < n) {
109 const openFiles = await this.options.ide.getOpenFiles();
110 recentlyEditedFilesSlice.push(
111 ...openFiles.slice(0, n - recentlyEditedFilesSlice.length),
112 );
113 }
114
115 const chunks: Chunk[] = [];
116
117 for (const filepath of recentlyEditedFilesSlice) {
118 const contents = await this.options.ide.readFile(filepath);
119 const fileChunks = chunkDocument({
120 filepath,
121 contents,
122 maxChunkSize:
123 this.options.config.selectedModelByRole.embed
124 ?.maxEmbeddingChunkSize ?? DEFAULT_CHUNK_SIZE,
125 digest: filepath,
126 });
127
128 for await (const chunk of fileChunks) {
129 chunks.push(chunk);
130 }
131 }
132
133 return chunks.slice(0, n);
134 }
135
136 protected async retrieveEmbeddings(
137 input: string,
138 n: number,
139 ): Promise<Chunk[]> {
140 if (!this.lanceDbIndex) {
141 console.warn(
142 "LanceDB index not available, skipping embeddings retrieval",
143 );
144 return [];
145 }
146
147 return this.lanceDbIndex.retrieve(
148 input,
149 n,
150 this.options.tags,
151 this.options.filterDirectory,
152 );
153 }
154
155 run(args: RetrievalPipelineRunArguments): Promise<Chunk[]> {
156 throw new Error("Not implemented");
157 }
158}