Elffuss BraidHub

kikocis/continue public

main · 8.7 KiBRawPermalink
1// @ts-ignore
2import nlp from "wink-nlp-utils";
3
4import {
5 BranchAndDir,
6 Chunk,
7 ContextItem,
8 ContinueConfig,
9 IDE,
10 ILLM,
11 Tool,
12 ToolExtras,
13} from "../../../";
14import { openedFilesLruCache } from "../../../autocomplete/util/openedFilesLruCache";
15import { chunkDocument } from "../../../indexing/chunk/chunk";
16import { FullTextSearchCodebaseIndex } from "../../../indexing/FullTextSearchCodebaseIndex";
17import { LanceDbIndex } from "../../../indexing/LanceDbIndex";
18import { BuiltInToolNames } from "../../../tools/builtIn";
19import { callBuiltInTool } from "../../../tools/callTool";
20import { globSearchTool } from "../../../tools/definitions/globSearch";
21import { grepSearchTool } from "../../../tools/definitions/grepSearch";
22import { lsTool } from "../../../tools/definitions/ls";
23import { readFileTool } from "../../../tools/definitions/readFile";
24import { viewRepoMapTool } from "../../../tools/definitions/viewRepoMap";
25import { viewSubdirectoryTool } from "../../../tools/definitions/viewSubdirectory";
26
27const DEFAULT_CHUNK_SIZE = 384;
28
29const AVAILABLE_TOOLS: Tool[] = [
30 globSearchTool,
31 grepSearchTool,
32 lsTool,
33 readFileTool,
34 viewRepoMapTool,
35 viewSubdirectoryTool,
36];
37
38export interface RetrievalPipelineOptions {
39 llm: ILLM;
40 config: ContinueConfig;
41 ide: IDE;
42 input: string;
43 nRetrieve: number;
44 nFinal: number;
45 tags: BranchAndDir[];
46 filterDirectory?: string;
47}
48
49export interface RetrievalPipelineRunArguments {
50 query: string;
51 tags: BranchAndDir[];
52 filterDirectory?: string;
53 includeEmbeddings: boolean;
54}
55
56export interface IRetrievalPipeline {
57 run(args: RetrievalPipelineRunArguments): Promise<Chunk[]>;
58}
59
60export default class BaseRetrievalPipeline implements IRetrievalPipeline {
61 private ftsIndex = new FullTextSearchCodebaseIndex();
62 private lanceDbIndex: LanceDbIndex | null = null;
63 private lanceDbInitPromise: Promise<void> | null = null;
64
65 constructor(protected readonly options: RetrievalPipelineOptions) {
66 void this.initLanceDb();
67 }
68
69 protected async initLanceDb() {
70 const embedModel = this.options.config.selectedModelByRole.embed;
71
72 if (!embedModel) {
73 return;
74 }
75
76 this.lanceDbIndex = await LanceDbIndex.create(embedModel, (uri) =>
77 this.options.ide.readFile(uri),
78 );
79 }
80
81 protected async ensureLanceDbInitialized(): Promise<boolean> {
82 if (this.lanceDbIndex) {
83 return true;
84 }
85
86 if (this.lanceDbInitPromise) {
87 await this.lanceDbInitPromise;
88 return this.lanceDbIndex !== null;
89 }
90
91 this.lanceDbInitPromise = this.initLanceDb();
92 await this.lanceDbInitPromise;
93 this.lanceDbInitPromise = null; // clear after init
94
95 return this.lanceDbIndex !== null;
96 }
97
98 private getCleanedTrigrams(
99 query: RetrievalPipelineRunArguments["query"],
100 ): string[] {
101 let text = nlp.string.removeExtraSpaces(query);
102 text = nlp.string.stem(text);
103
104 let tokens = nlp.string
105 .tokenize(text, true)
106 .filter((token: any) => token.tag === "word")
107 .map((token: any) => token.value);
108
109 tokens = nlp.tokens.removeWords(tokens);
110 tokens = nlp.tokens.setOfWords(tokens);
111
112 const cleanedTokens = [...tokens].join(" ");
113 const trigrams = nlp.string.ngram(cleanedTokens, 3);
114
115 return trigrams.map(this.escapeFtsQueryString);
116 }
117
118 private escapeFtsQueryString(query: string): string {
119 const escapedDoubleQuotes = query.replace(/"/g, '""');
120 return `"${escapedDoubleQuotes}"`;
121 }
122
123 protected async retrieveFts(
124 args: RetrievalPipelineRunArguments,
125 n: number,
126 ): Promise<Chunk[]> {
127 if (args.query.trim() === "") {
128 return [];
129 }
130
131 const tokens = this.getCleanedTrigrams(args.query).join(" OR ");
132
133 return await this.ftsIndex.retrieve({
134 n,
135 text: tokens,
136 tags: args.tags,
137 directory: args.filterDirectory,
138 });
139 }
140
141 protected async retrieveAndChunkRecentlyEditedFiles(
142 n: number,
143 ): Promise<Chunk[]> {
144 const recentlyEditedFilesSlice = Array.from(
145 openedFilesLruCache.keys(),
146 ).slice(0, n);
147
148 // If the number of recently edited files is less than the retrieval limit,
149 // include additional open files. This is useful in the case where a user
150 // has many tabs open and reloads their IDE. They now have 0 recently edited files,
151 // but many open tabs that represent what they were working on prior to reload.
152 if (recentlyEditedFilesSlice.length < n) {
153 const openFiles = await this.options.ide.getOpenFiles();
154 recentlyEditedFilesSlice.push(
155 ...openFiles.slice(0, n - recentlyEditedFilesSlice.length),
156 );
157 }
158
159 const chunks: Chunk[] = [];
160
161 for (const filepath of recentlyEditedFilesSlice) {
162 const contents = await this.options.ide.readFile(filepath);
163 const fileChunks = chunkDocument({
164 filepath,
165 contents,
166 maxChunkSize:
167 this.options.config.selectedModelByRole.embed
168 ?.maxEmbeddingChunkSize ?? DEFAULT_CHUNK_SIZE,
169 digest: filepath,
170 });
171
172 for await (const chunk of fileChunks) {
173 chunks.push(chunk);
174 }
175 }
176
177 return chunks.slice(0, n);
178 }
179
180 protected async retrieveEmbeddings(
181 input: string,
182 n: number,
183 ): Promise<Chunk[]> {
184 const initialized = await this.ensureLanceDbInitialized();
185
186 if (!initialized || !this.lanceDbIndex) {
187 console.warn(
188 "LanceDB index not available, skipping embeddings retrieval",
189 );
190 return [];
191 }
192
193 return this.lanceDbIndex.retrieve(
194 input,
195 n,
196 this.options.tags,
197 this.options.filterDirectory,
198 );
199 }
200
201 run(args: RetrievalPipelineRunArguments): Promise<Chunk[]> {
202 throw new Error("Not implemented");
203 }
204
205 protected async retrieveWithTools(input: string): Promise<Chunk[]> {
206 const toolSelectionPrompt = `Given the following user input: "${input}"
207
208Available tools:
209${AVAILABLE_TOOLS.map((tool) => {
210 const requiredParams = tool.function.parameters?.required || [];
211 const properties = tool.function.parameters?.properties || {};
212 const paramDescriptions = requiredParams
213 .map(
214 (param: any) => `${param}: ${properties[param]?.description || "string"}`,
215 )
216 .join(", ");
217
218 return `- ${tool.function.name}: ${tool.function.description}
219 Required arguments: ${paramDescriptions || "none"}`;
220}).join("\n")}
221
222Determine which tools should be used to answer this query. You should feel free to use multiple tools when they would be helpful for comprehensive results. Respond ONLY a JSON object containing the following and nothing else:
223{
224 "tools": [
225 {
226 "name": "<tool_name>",
227 "args": { "<required_parameter_name>": "<required_parameter_value>" }
228 }
229 ]
230}`;
231
232 // Get LLM response for tool selection
233 const toolSelectionResponse = await this.options.llm.chat(
234 [{ role: "user", content: toolSelectionPrompt }],
235 new AbortController().signal,
236 );
237
238 let toolCalls: { name: string; args: any }[] = [];
239 try {
240 const responseContent =
241 typeof toolSelectionResponse.content === "string"
242 ? toolSelectionResponse.content
243 : toolSelectionResponse.content
244 .map((part) => (part.type === "text" ? part.text : ""))
245 .join("");
246 const parsed = JSON.parse(responseContent);
247 toolCalls = parsed.tools || [];
248 } catch (e) {
249 console.log(
250 `Failed to parse tool selection response: ${toolSelectionResponse.content}\n\n`,
251 e,
252 );
253 return [];
254 }
255
256 // Execute tools and collect results
257 const allContextItems: ContextItem[] = [];
258
259 const toolExtras: ToolExtras = {
260 ide: this.options.ide,
261 llm: this.options.llm,
262 fetch: fetch,
263 tool: grepSearchTool,
264 config: this.options.config,
265 };
266
267 for (const toolCall of toolCalls) {
268 const tool = AVAILABLE_TOOLS.find(
269 (t) => t.function.name === toolCall.name,
270 )!;
271
272 const args = toolCall.args;
273 if (toolCall.name === BuiltInToolNames.GrepSearch) {
274 args.splitByFile = true;
275 }
276
277 toolExtras.tool = tool;
278 const contextItems = await callBuiltInTool(
279 toolCall.name,
280 args,
281 toolExtras,
282 );
283 allContextItems.push(...contextItems);
284 }
285
286 const chunks: Chunk[] = [];
287
288 // Transform ContextItem[] to Chunk[]
289 for (let i = 0; i < allContextItems.length; i++) {
290 const contextItem = allContextItems[i];
291 const filepath = contextItem.uri?.value || contextItem.name || "unknown";
292 const cleanedFilepath = filepath.replace(/^file:\/\/\//, "");
293
294 chunks.push({
295 content: contextItem.content,
296 startLine: -1,
297 endLine: -1,
298 digest: `file:///${cleanedFilepath}`,
299 filepath: `file:///${cleanedFilepath}`,
300 index: i,
301 });
302 }
303
304 console.log("retrieveWithTools chunks", chunks);
305 return chunks;
306 }
307}