Elffuss BraidHub

kikocis/continue public

3ecf862e2425 · 8.1 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/lsTool";
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
64 constructor(protected readonly options: RetrievalPipelineOptions) {
65 void this.initLanceDb();
66 }
67
68 private async initLanceDb() {
69 const embedModel = this.options.config.selectedModelByRole.embed;
70
71 if (!embedModel) {
72 return;
73 }
74
75 this.lanceDbIndex = await LanceDbIndex.create(embedModel, (uri) =>
76 this.options.ide.readFile(uri),
77 );
78 }
79
80 private getCleanedTrigrams(
81 query: RetrievalPipelineRunArguments["query"],
82 ): string[] {
83 let text = nlp.string.removeExtraSpaces(query);
84 text = nlp.string.stem(text);
85
86 let tokens = nlp.string
87 .tokenize(text, true)
88 .filter((token: any) => token.tag === "word")
89 .map((token: any) => token.value);
90
91 tokens = nlp.tokens.removeWords(tokens);
92 tokens = nlp.tokens.setOfWords(tokens);
93
94 const cleanedTokens = [...tokens].join(" ");
95 const trigrams = nlp.string.ngram(cleanedTokens, 3);
96
97 return trigrams.map(this.escapeFtsQueryString);
98 }
99
100 private escapeFtsQueryString(query: string): string {
101 const escapedDoubleQuotes = query.replace(/"/g, '""');
102 return `"${escapedDoubleQuotes}"`;
103 }
104
105 protected async retrieveFts(
106 args: RetrievalPipelineRunArguments,
107 n: number,
108 ): Promise<Chunk[]> {
109 if (args.query.trim() === "") {
110 return [];
111 }
112
113 const tokens = this.getCleanedTrigrams(args.query).join(" OR ");
114
115 return await this.ftsIndex.retrieve({
116 n,
117 text: tokens,
118 tags: args.tags,
119 directory: args.filterDirectory,
120 });
121 }
122
123 protected async retrieveAndChunkRecentlyEditedFiles(
124 n: number,
125 ): Promise<Chunk[]> {
126 const recentlyEditedFilesSlice = Array.from(
127 openedFilesLruCache.keys(),
128 ).slice(0, n);
129
130 // If the number of recently edited files is less than the retrieval limit,
131 // include additional open files. This is useful in the case where a user
132 // has many tabs open and reloads their IDE. They now have 0 recently edited files,
133 // but many open tabs that represent what they were working on prior to reload.
134 if (recentlyEditedFilesSlice.length < n) {
135 const openFiles = await this.options.ide.getOpenFiles();
136 recentlyEditedFilesSlice.push(
137 ...openFiles.slice(0, n - recentlyEditedFilesSlice.length),
138 );
139 }
140
141 const chunks: Chunk[] = [];
142
143 for (const filepath of recentlyEditedFilesSlice) {
144 const contents = await this.options.ide.readFile(filepath);
145 const fileChunks = chunkDocument({
146 filepath,
147 contents,
148 maxChunkSize:
149 this.options.config.selectedModelByRole.embed
150 ?.maxEmbeddingChunkSize ?? DEFAULT_CHUNK_SIZE,
151 digest: filepath,
152 });
153
154 for await (const chunk of fileChunks) {
155 chunks.push(chunk);
156 }
157 }
158
159 return chunks.slice(0, n);
160 }
161
162 protected async retrieveEmbeddings(
163 input: string,
164 n: number,
165 ): Promise<Chunk[]> {
166 if (!this.lanceDbIndex) {
167 console.warn(
168 "LanceDB index not available, skipping embeddings retrieval",
169 );
170 return [];
171 }
172
173 return this.lanceDbIndex.retrieve(
174 input,
175 n,
176 this.options.tags,
177 this.options.filterDirectory,
178 );
179 }
180
181 run(args: RetrievalPipelineRunArguments): Promise<Chunk[]> {
182 throw new Error("Not implemented");
183 }
184
185 protected async retrieveWithTools(input: string): Promise<Chunk[]> {
186 const toolSelectionPrompt = `Given the following user input: "${input}"
187
188Available tools:
189${AVAILABLE_TOOLS.map((tool) => {
190 const requiredParams = tool.function.parameters?.required || [];
191 const properties = tool.function.parameters?.properties || {};
192 const paramDescriptions = requiredParams
193 .map(
194 (param: any) => `${param}: ${properties[param]?.description || "string"}`,
195 )
196 .join(", ");
197
198 return `- ${tool.function.name}: ${tool.function.description}
199 Required arguments: ${paramDescriptions || "none"}`;
200}).join("\n")}
201
202Determine 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:
203{
204 "tools": [
205 {
206 "name": "<tool_name>",
207 "args": { "<required_parameter_name>": "<required_parameter_value>" }
208 }
209 ]
210}`;
211
212 // Get LLM response for tool selection
213 const toolSelectionResponse = await this.options.llm.chat(
214 [{ role: "user", content: toolSelectionPrompt }],
215 new AbortController().signal,
216 );
217
218 let toolCalls: { name: string; args: any }[] = [];
219 try {
220 const responseContent =
221 typeof toolSelectionResponse.content === "string"
222 ? toolSelectionResponse.content
223 : toolSelectionResponse.content
224 .map((part) => (part.type === "text" ? part.text : ""))
225 .join("");
226 const parsed = JSON.parse(responseContent);
227 toolCalls = parsed.tools || [];
228 console.log("retrieveWithTools", toolCalls);
229 } catch (e) {
230 console.log("Failed to parse tool selection response", e);
231 return [];
232 }
233
234 // Execute tools and collect results
235 const allContextItems: ContextItem[] = [];
236
237 const toolExtras: ToolExtras = {
238 ide: this.options.ide,
239 llm: this.options.llm,
240 fetch: fetch,
241 tool: grepSearchTool,
242 config: this.options.config,
243 };
244
245 for (const toolCall of toolCalls) {
246 const tool = AVAILABLE_TOOLS.find(
247 (t) => t.function.name === toolCall.name,
248 )!;
249
250 const args = toolCall.args;
251 if (toolCall.name === BuiltInToolNames.GrepSearch) {
252 args.splitByFile = true;
253 }
254
255 toolExtras.tool = tool;
256 const contextItems = await callBuiltInTool(
257 toolCall.name,
258 args,
259 toolExtras,
260 );
261 allContextItems.push(...contextItems);
262 }
263
264 const chunks: Chunk[] = [];
265
266 // Transform ContextItem[] to Chunk[]
267 for (let i = 0; i < allContextItems.length; i++) {
268 const contextItem = allContextItems[i];
269 const filepath = contextItem.uri?.value || contextItem.name || "unknown";
270 const cleanedFilepath = filepath.replace(/^file:\/\/\//, "");
271
272 chunks.push({
273 content: contextItem.content,
274 startLine: -1,
275 endLine: -1,
276 digest: `file:///${cleanedFilepath}`,
277 filepath: `file:///${cleanedFilepath}`,
278 index: i,
279 });
280 }
281
282 console.log("retrieveWithTools chunks", chunks);
283 return chunks;
284 }
285}