| 1 | import { Chunk } from "../../index.js"; |
| 2 | import { getUriPathBasename } from "../../util/uri.js"; |
| 3 | import { BaseLLM } from "../index.js"; |
| 4 | |
| 5 | const RERANK_PROMPT = ( |
| 6 | query: string, |
| 7 | documentId: string, |
| 8 | document: string, |
| 9 | ) => `You are an expert software developer responsible for helping detect whether the retrieved snippet of code is relevant to the query. For a given input, you need to output a single word: "Yes" or "No" indicating the retrieved snippet is relevant to the query. |
| 10 | |
| 11 | Query: Where is the FastAPI server? |
| 12 | Snippet: |
| 13 | \`\`\`/Users/andrew/Desktop/server/main.py |
| 14 | from fastapi import FastAPI |
| 15 | app = FastAPI() |
| 16 | @app.get("/") |
| 17 | def read_root(): |
| 18 | return {{"Hello": "World"}} |
| 19 | \`\`\` |
| 20 | Relevant: Yes |
| 21 | |
| 22 | Query: Where in the documentation does it talk about the UI? |
| 23 | Snippet: |
| 24 | \`\`\`/Users/andrew/Projects/bubble_sort/src/lib.rs |
| 25 | fn bubble_sort<T: Ord>(arr: &mut [T]) {{ |
| 26 | for i in 0..arr.len() {{ |
| 27 | for j in 1..arr.len() - i {{ |
| 28 | if arr[j - 1] > arr[j] {{ |
| 29 | arr.swap(j - 1, j); |
| 30 | }} |
| 31 | }} |
| 32 | }} |
| 33 | }} |
| 34 | \`\`\` |
| 35 | Relevant: No |
| 36 | |
| 37 | Query: ${query} |
| 38 | Snippet: |
| 39 | \`\`\`${documentId} |
| 40 | ${document} |
| 41 | \`\`\` |
| 42 | Relevant: |
| 43 | `; |
| 44 | |
| 45 | export class LLMReranker extends BaseLLM { |
| 46 | static providerName = "llmReranker"; |
| 47 | |
| 48 | async scoreChunk(chunk: Chunk, query: string): Promise<number> { |
| 49 | const completion = await this.complete( |
| 50 | RERANK_PROMPT(query, getUriPathBasename(chunk.filepath), chunk.content), |
| 51 | new AbortController().signal, |
| 52 | { |
| 53 | maxTokens: 1, |
| 54 | model: |
| 55 | this.providerName.startsWith("openai") && |
| 56 | this.model.startsWith("gpt-4") |
| 57 | ? "gpt-3.5-turbo" |
| 58 | : this.model, |
| 59 | }, |
| 60 | ); |
| 61 | |
| 62 | if (!completion) { |
| 63 | // TODO: Why is this happening? |
| 64 | return 0.0; |
| 65 | } |
| 66 | |
| 67 | const answer = completion |
| 68 | .trim() |
| 69 | .toLowerCase() |
| 70 | .replace(/"/g, "") |
| 71 | .replace(/'/g, ""); |
| 72 | |
| 73 | if (answer === "yes") { |
| 74 | return 1.0; |
| 75 | } |
| 76 | if (answer === "no") { |
| 77 | return 0.0; |
| 78 | } |
| 79 | console.warn( |
| 80 | `Unexpected response from single token reranker: "${answer}". Expected "yes" or "no".`, |
| 81 | ); |
| 82 | return 0.0; |
| 83 | } |
| 84 | |
| 85 | async rerank(query: string, chunks: Chunk[]): Promise<number[]> { |
| 86 | const scores = await Promise.all( |
| 87 | chunks.map((chunk) => this.scoreChunk(chunk, query)), |
| 88 | ); |
| 89 | return scores; |
| 90 | } |
| 91 | } |