| 1 | import { Chunk } from "../../.."; |
| 2 | import { RETRIEVAL_PARAMS } from "../../../util/parameters"; |
| 3 | import { Telemetry } from "../../../util/posthog"; |
| 4 | import { findUriInDirs } from "../../../util/uri"; |
| 5 | import { requestFilesFromRepoMap } from "../repoMapRequest"; |
| 6 | import { deduplicateChunks } from "../util"; |
| 7 | |
| 8 | import BaseRetrievalPipeline, { |
| 9 | RetrievalPipelineRunArguments, |
| 10 | } from "./BaseRetrievalPipeline"; |
| 11 | |
| 12 | export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { |
| 13 | private async _retrieveInitial( |
| 14 | args: RetrievalPipelineRunArguments, |
| 15 | ): Promise<Chunk[]> { |
| 16 | const { input, nRetrieve, filterDirectory, config } = this.options; |
| 17 | |
| 18 | let retrievalResults: Chunk[] = []; |
| 19 | |
| 20 | let ftsChunks: Chunk[] = []; |
| 21 | try { |
| 22 | ftsChunks = await this.retrieveFts(args, nRetrieve); |
| 23 | } catch (error) { |
| 24 | await Telemetry.captureError("reranker_fts_retrieval", error); |
| 25 | // console.error("Error retrieving FTS chunks:", error); |
| 26 | } |
| 27 | |
| 28 | let embeddingsChunks: Chunk[] = []; |
| 29 | try { |
| 30 | embeddingsChunks = Boolean(config.selectedModelByRole.embed) |
| 31 | ? await this.retrieveEmbeddings(input, nRetrieve) |
| 32 | : []; |
| 33 | } catch (error) { |
| 34 | await Telemetry.captureError("reranker_embeddings_retrieval", error); |
| 35 | console.error("Error retrieving embeddings chunks:", error); |
| 36 | } |
| 37 | |
| 38 | let recentlyEditedFilesChunks: Chunk[] = []; |
| 39 | try { |
| 40 | recentlyEditedFilesChunks = |
| 41 | await this.retrieveAndChunkRecentlyEditedFiles(nRetrieve); |
| 42 | } catch (error) { |
| 43 | await Telemetry.captureError("reranker_recently_edited_retrieval", error); |
| 44 | console.error("Error retrieving recently edited files chunks:", error); |
| 45 | } |
| 46 | |
| 47 | let repoMapChunks: Chunk[] = []; |
| 48 | try { |
| 49 | repoMapChunks = await requestFilesFromRepoMap( |
| 50 | this.options.llm, |
| 51 | this.options.config, |
| 52 | this.options.ide, |
| 53 | input, |
| 54 | filterDirectory, |
| 55 | ); |
| 56 | } catch (error) { |
| 57 | await Telemetry.captureError("reranker_repo_map_retrieval", error); |
| 58 | console.error("Error retrieving repo map chunks:", error); |
| 59 | } |
| 60 | |
| 61 | if (config.experimental?.codebaseToolCallingOnly) { |
| 62 | let toolBasedChunks: Chunk[] = []; |
| 63 | try { |
| 64 | toolBasedChunks = await this.retrieveWithTools(input); |
| 65 | } catch (error) { |
| 66 | console.error("Error retrieving tool based chunks:", error); |
| 67 | } |
| 68 | retrievalResults.push(...toolBasedChunks); |
| 69 | } else { |
| 70 | retrievalResults.push( |
| 71 | ...recentlyEditedFilesChunks, |
| 72 | ...ftsChunks, |
| 73 | ...embeddingsChunks, |
| 74 | ...repoMapChunks, |
| 75 | ); |
| 76 | } |
| 77 | |
| 78 | if (filterDirectory) { |
| 79 | // Backup if the individual retrieval methods don't listen |
| 80 | retrievalResults = retrievalResults.filter( |
| 81 | (chunk) => |
| 82 | !!findUriInDirs(chunk.filepath, [filterDirectory]).foundInDir, |
| 83 | ); |
| 84 | } |
| 85 | |
| 86 | const deduplicatedRetrievalResults: Chunk[] = |
| 87 | deduplicateChunks(retrievalResults); |
| 88 | |
| 89 | return deduplicatedRetrievalResults; |
| 90 | } |
| 91 | |
| 92 | private async _rerank(input: string, chunks: Chunk[]): Promise<Chunk[]> { |
| 93 | if (!this.options.config.selectedModelByRole.rerank) { |
| 94 | throw new Error("No reranker set up"); |
| 95 | } |
| 96 | |
| 97 | // remove empty chunks -- some APIs fail on that |
| 98 | chunks = chunks.filter((chunk) => chunk.content); |
| 99 | |
| 100 | try { |
| 101 | let scores: number[] = |
| 102 | await this.options.config.selectedModelByRole.rerank.rerank( |
| 103 | input, |
| 104 | chunks, |
| 105 | ); |
| 106 | |
| 107 | // Filter out low-scoring results |
| 108 | let results = chunks; |
| 109 | // let results = chunks.filter( |
| 110 | // (_, i) => scores[i] >= RETRIEVAL_PARAMS.rerankThreshold, |
| 111 | // ); |
| 112 | // scores = scores.filter( |
| 113 | // (score) => score >= RETRIEVAL_PARAMS.rerankThreshold, |
| 114 | // ); |
| 115 | |
| 116 | const chunkIndexMap = new Map<Chunk, number>(); |
| 117 | chunks.forEach((chunk, idx) => chunkIndexMap.set(chunk, idx)); |
| 118 | |
| 119 | results?.sort( |
| 120 | (a, b) => scores[chunkIndexMap.get(b)!] - scores[chunkIndexMap.get(a)!], |
| 121 | ); |
| 122 | results = results.slice(0, this.options.nFinal); |
| 123 | return results; |
| 124 | } catch (e) { |
| 125 | console.warn(`Failed to rerank retrieval results\n${e}`); |
| 126 | return chunks.slice(0, this.options.nFinal); |
| 127 | } |
| 128 | } |
| 129 | |
| 130 | private async _expandWithEmbeddings(chunks: Chunk[]): Promise<Chunk[]> { |
| 131 | const topResults = chunks.slice( |
| 132 | -RETRIEVAL_PARAMS.nResultsToExpandWithEmbeddings, |
| 133 | ); |
| 134 | |
| 135 | const expanded = await Promise.all( |
| 136 | topResults.map(async (chunk, i) => { |
| 137 | const results = await this.retrieveEmbeddings( |
| 138 | chunk.content, |
| 139 | RETRIEVAL_PARAMS.nEmbeddingsExpandTo, |
| 140 | ); |
| 141 | return results; |
| 142 | }), |
| 143 | ); |
| 144 | return expanded.flat(); |
| 145 | } |
| 146 | |
| 147 | private async _expandRankedResults(chunks: Chunk[]): Promise<Chunk[]> { |
| 148 | let results: Chunk[] = []; |
| 149 | |
| 150 | const embeddingsResults = await this._expandWithEmbeddings(chunks); |
| 151 | results.push(...embeddingsResults); |
| 152 | |
| 153 | return results; |
| 154 | } |
| 155 | |
| 156 | async run(args: RetrievalPipelineRunArguments): Promise<Chunk[]> { |
| 157 | let results = await this._retrieveInitial(args); |
| 158 | results = await this._rerank(args.query, results); |
| 159 | |
| 160 | // // // Expand top reranked results |
| 161 | // const expanded = await this._expandRankedResults(results); |
| 162 | // results.push(...expanded); |
| 163 | |
| 164 | // // De-duplicate |
| 165 | // results = deduplicateChunks(results); |
| 166 | |
| 167 | // // Rerank again |
| 168 | // results = await this._rerank(input, results); |
| 169 | |
| 170 | // TODO: stitch together results |
| 171 | |
| 172 | return results; |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | // Source: expansion with code graph |
| 177 | // consider doing this after reranking? Or just having a lower reranking threshold |
| 178 | // This is VS Code only until we use PSI for JetBrains or build our own general solution |
| 179 | // TODO: Need to pass in the expandSnippet function as a function argument |
| 180 | // because this import causes `tsc` to fail |
| 181 | // if ((await extras.ide.getIdeInfo()).ideType === "vscode") { |
| 182 | // const { expandSnippet } = await import( |
| 183 | // "../../../extensions/vscode/src/util/expandSnippet" |
| 184 | // ); |
| 185 | // let expansionResults = ( |
| 186 | // await Promise.all( |
| 187 | // extras.selectedCode.map(async (rif) => { |
| 188 | // return expandSnippet( |
| 189 | // rif.filepath, |
| 190 | // rif.range.start.line, |
| 191 | // rif.range.end.line, |
| 192 | // extras.ide, |
| 193 | // ); |
| 194 | // }), |
| 195 | // ) |
| 196 | // ).flat() as Chunk[]; |
| 197 | // retrievalResults.push(...expansionResults); |
| 198 | // } |
| 199 | |
| 200 | // Source: Open file exact match |
| 201 | // Source: Class/function name exact match |