Reranking, MMR Diversity, and Context Compression Under Token Budgets
Retrieving 30 candidate chunks is great for recall, yet stuffing all 30 into the LLM prompt hurts answer quality, increases latency, and wastes tokens. Research on the "lost in the middle" phenomenon shows models attend most strongly to the beginning and end of context while overlooking facts buried in noisy middle passages.
Two-Stage Retrieval: Bi-Encoder + Cross-Encoder
Embedding search uses a bi-encoder: query and document are encoded independently so millions of vectors can be precomputed. A cross-encoder reranker takes (query, passage) together through full self-attention, making it dramatically better at spotting subtle negation, scope, and exact relevance.
| Stage | Architecture | Typical Candidate Count | Latency Budget |
|---|---|---|---|
| Stage 1 (Recall) | BM25 + Bi-encoder ANN | 10,000+ down to 25-40 | 10-30ms |
| Stage 2 (Precision) | Cross-encoder reranker | 25-40 down to 5-8 | 40-120ms |
| Stage 3 (Diversity) | MMR + per-doc cap | 5-8 deduplicated passages | < 2ms |
Maximal Marginal Relevance (MMR)
Without diversity control, five slightly overlapping chunks from the same paragraph can fill the entire context window, crowding out a critical exception in another article. MMR iteratively picks the candidate that balances relevance to the query against novelty compared to chunks already selected:
export function selectDiverseTopK<T extends { id: string; docId: string; relevance: number; embedding: number[] }>(
candidates: T[],
topK: number,
lambda = 0.75,
maxPerDoc = 2
): T[] {
const selected: T[] = [];
const remaining = [...candidates];
const docCounts = new Map<string, number>();
while (selected.length < topK && remaining.length > 0) {
let bestIdx = -1;
let bestScore = -Infinity;
for (let i = 0; i < remaining.length; i++) {
const cand = remaining[i];
if ((docCounts.get(cand.docId) ?? 0) >= maxPerDoc) continue;
const maxSimToSelected =
selected.length === 0
? 0
: Math.max(...selected.map(s => cosineSimilarity(cand.embedding, s.embedding)));
const mmrScore = lambda * cand.relevance - (1 - lambda) * maxSimToSelected;
if (mmrScore > bestScore) {
bestScore = mmrScore;
bestIdx = i;
}
}
if (bestIdx === -1) break;
const [picked] = remaining.splice(bestIdx, 1);
selected.push(picked);
docCounts.set(picked.docId, (docCounts.get(picked.docId) ?? 0) + 1);
}
return selected;
}
Context Packing Best Practices
- Enforce a hard token budget: stop packing once cumulative context reaches a deterministic cap (for example 2,500 to 4,000 tokens) so prompt latency and cost stay bounded.
- Deduplicate overlapping spans: when two adjacent chunks from the same document are both selected, merge them in natural reading order instead of repeating overlap text.
- Include lightweight metadata headers: pass
[Source 1: Return Policy | Updated 2026-09]above each passage so the model resolves conflicts in favor of newer, authoritative documents.
Next: measure whether these stages actually improve recall and rank quality in Evaluating Retrieval Quality.