| 1 | // @ts-ignore |
| 2 | import nlp from "wink-nlp-utils"; |
| 3 | |
| 4 | import { |
| 5 | BranchAndDir, |
| 6 | Chunk, |
| 7 | ContextItem, |
| 8 | ContinueConfig, |
| 9 | IDE, |
| 10 | ILLM, |
| 11 | Tool, |
| 12 | ToolExtras, |
| 13 | } from "../../../"; |
| 14 | import { openedFilesLruCache } from "../../../autocomplete/util/openedFilesLruCache"; |
| 15 | import { chunkDocument } from "../../../indexing/chunk/chunk"; |
| 16 | import { FullTextSearchCodebaseIndex } from "../../../indexing/FullTextSearchCodebaseIndex"; |
| 17 | import { LanceDbIndex } from "../../../indexing/LanceDbIndex"; |
| 18 | import { BuiltInToolNames } from "../../../tools/builtIn"; |
| 19 | import { callBuiltInTool } from "../../../tools/callTool"; |
| 20 | import { globSearchTool } from "../../../tools/definitions/globSearch"; |
| 21 | import { grepSearchTool } from "../../../tools/definitions/grepSearch"; |
| 22 | import { lsTool } from "../../../tools/definitions/lsTool"; |
| 23 | import { readFileTool } from "../../../tools/definitions/readFile"; |
| 24 | import { viewRepoMapTool } from "../../../tools/definitions/viewRepoMap"; |
| 25 | import { viewSubdirectoryTool } from "../../../tools/definitions/viewSubdirectory"; |
| 26 | |
| 27 | const DEFAULT_CHUNK_SIZE = 384; |
| 28 | |
| 29 | const AVAILABLE_TOOLS: Tool[] = [ |
| 30 | globSearchTool, |
| 31 | grepSearchTool, |
| 32 | lsTool, |
| 33 | readFileTool, |
| 34 | viewRepoMapTool, |
| 35 | viewSubdirectoryTool, |
| 36 | ]; |
| 37 | |
| 38 | export 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 | |
| 49 | export interface RetrievalPipelineRunArguments { |
| 50 | query: string; |
| 51 | tags: BranchAndDir[]; |
| 52 | filterDirectory?: string; |
| 53 | includeEmbeddings: boolean; |
| 54 | } |
| 55 | |
| 56 | export interface IRetrievalPipeline { |
| 57 | run(args: RetrievalPipelineRunArguments): Promise<Chunk[]>; |
| 58 | } |
| 59 | |
| 60 | export 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 | |
| 188 | Available 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 | |
| 202 | Determine 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 | } catch (e) { |
| 229 | console.log( |
| 230 | `Failed to parse tool selection response: ${toolSelectionResponse.content}\n\n`, |
| 231 | e, |
| 232 | ); |
| 233 | return []; |
| 234 | } |
| 235 | |
| 236 | // Execute tools and collect results |
| 237 | const allContextItems: ContextItem[] = []; |
| 238 | |
| 239 | const toolExtras: ToolExtras = { |
| 240 | ide: this.options.ide, |
| 241 | llm: this.options.llm, |
| 242 | fetch: fetch, |
| 243 | tool: grepSearchTool, |
| 244 | config: this.options.config, |
| 245 | }; |
| 246 | |
| 247 | for (const toolCall of toolCalls) { |
| 248 | const tool = AVAILABLE_TOOLS.find( |
| 249 | (t) => t.function.name === toolCall.name, |
| 250 | )!; |
| 251 | |
| 252 | const args = toolCall.args; |
| 253 | if (toolCall.name === BuiltInToolNames.GrepSearch) { |
| 254 | args.splitByFile = true; |
| 255 | } |
| 256 | |
| 257 | toolExtras.tool = tool; |
| 258 | const contextItems = await callBuiltInTool( |
| 259 | toolCall.name, |
| 260 | args, |
| 261 | toolExtras, |
| 262 | ); |
| 263 | allContextItems.push(...contextItems); |
| 264 | } |
| 265 | |
| 266 | const chunks: Chunk[] = []; |
| 267 | |
| 268 | // Transform ContextItem[] to Chunk[] |
| 269 | for (let i = 0; i < allContextItems.length; i++) { |
| 270 | const contextItem = allContextItems[i]; |
| 271 | const filepath = contextItem.uri?.value || contextItem.name || "unknown"; |
| 272 | const cleanedFilepath = filepath.replace(/^file:\/\/\//, ""); |
| 273 | |
| 274 | chunks.push({ |
| 275 | content: contextItem.content, |
| 276 | startLine: -1, |
| 277 | endLine: -1, |
| 278 | digest: `file:///${cleanedFilepath}`, |
| 279 | filepath: `file:///${cleanedFilepath}`, |
| 280 | index: i, |
| 281 | }); |
| 282 | } |
| 283 | |
| 284 | console.log("retrieveWithTools chunks", chunks); |
| 285 | return chunks; |
| 286 | } |
| 287 | } |