askneo / rag /src /retrieve.ts
Faithology
Claude Opus 4.8
Deploy backend + RAG to Hugging Face Space (backend-only tree)
c6dfde3
Raw History Blame Contribute Delete
3.06 kB
import { config } from "./config.js";
import { chat, embed, parseJson } from "./providers.js";
import { normalize, type VectorStore } from "./store.js";
import type { ScoredChunk } from "./types.js";
/**
* Dense retrieval over Pinecone:
* 1. For every query variant: vector similarity search.
* 2. Reciprocal-rank fusion across the per-query result lists.
* 3. Optional listwise LLM rerank of the fused pool (fast model tier).
*/
export async function retrieve(
index: VectorStore,
queries: string[],
opts: { rerank?: boolean; topK?: number } = {},
): Promise<ScoredChunk[]> {
const topK = opts.topK ?? config.finalTopK;
const queryVecs = (await embed(queries)).map(normalize);
const lists = await Promise.all(
queryVecs.map((vec) => index.vectorSearch(vec, config.vectorTopK)),
);
const fused = reciprocalRankFusion(lists).slice(0, config.fusedTopK);
if (!opts.rerank || fused.length <= topK) return fused.slice(0, topK);
return rerank(queries[0]!, fused, topK);
}
/** Standard RRF (k=60), merging `via` tags and keeping best-rank metadata. */
function reciprocalRankFusion(lists: ScoredChunk[][], k = 60): ScoredChunk[] {
const byId = new Map<string, ScoredChunk>();
for (const list of lists) {
list.forEach((item, rank) => {
const contribution = 1 / (k + rank + 1);
const existing = byId.get(item.id);
if (existing) {
existing.score += contribution;
for (const v of item.via) if (!existing.via.includes(v)) existing.via.push(v);
} else {
byId.set(item.id, { ...item, score: contribution, via: [...item.via] });
}
});
}
return [...byId.values()].sort((a, b) => b.score - a.score);
}
/** Listwise LLM rerank: one fast-model call scoring every candidate 0-10. */
async function rerank(
question: string,
candidates: ScoredChunk[],
topK: number,
): Promise<ScoredChunk[]> {
const passages = candidates
.map((c, i) => `[${i}] ${c.text.slice(0, 700).replaceAll("\n", " ")}`)
.join("\n\n");
try {
const res = await chat(
[
{
role: "system",
content:
"You are a medical retrieval relevance grader. Score each passage 0-10 for how useful " +
'it is to answer the question. Respond with JSON only: {"scores": [{"index": 0, "score": 7}, ...]} ' +
"covering every passage index exactly once.",
},
{ role: "user", content: `Question: ${question}\n\nPassages:\n${passages}` },
],
{ fast: true, json: true, maxTokens: 2048 },
);
const parsed = parseJson<{ scores: Array<{ index: number; score: number }> }>(res.text);
const scoreOf = new Map(parsed.scores.map((s) => [s.index, s.score]));
return candidates
.map((c, i) => ({ ...c, score: scoreOf.get(i) ?? 0, via: [...c.via, "rerank"] }))
.sort((a, b) => b.score - a.score)
.slice(0, topK);
} catch (err) {
console.error(`[rerank] failed, using fused order: ${err instanceof Error ? err.message : err}`);
return candidates.slice(0, topK);
}
}