Retrieval-Augmented Generation
Retriever + generator: how to build it, measure it and fix it.
Shape
- Indexing (ahead of time): documents → chunks → index (inverted index for terms; vector DB for embeddings).
- Querying (per request): query → retriever → top-k chunks → generator (query + chunks) → answer.
- Knowledge base under ~200K tokens (~500 pages, Anthropic's guidance for Claude)? Try putting it all in the prompt first.
Retrievers
| Term-based (TF-IDF, BM25) | Embedding-based | |
|---|---|---|
| Matches | Words | Meaning |
| Strength | Fast, cheap, strong baseline; exact codes and names | Paraphrases and natural queries; improvable by finetuning |
| Weakness | Synonyms; ambiguous terms | Exact strings; cost (embedding, storage, ANN search) |
Hybrid search: in sequence (cheap fetch → precise rerank) or in parallel (reciprocal rank fusion: Σ 1/(k + rank), k ≈ 60).
Measure
- Context precision = relevant retrieved ÷ retrieved. Easy: judge only what was retrieved.
- Context recall = relevant retrieved ÷ all relevant. Hard: every document must be labeled per query.
- Ranking-aware metrics: NDCG, MAP, MRR. Embedding benchmark: MTEB.
- Evaluate retrieval, embeddings and the final answer separately. A correct chunk that was never retrieved is a retriever bug.
Fix
| Symptom | Tactic |
|---|---|
| Exact codes or names missed by embeddings | Hybrid search |
| Facts cut at chunk boundaries; chunks too big or small | Chunking: recursive splits, overlap, tune size |
| Too many candidates; stale results | Reranking (precision or recency) |
| Follow-ups like “How about Emily?” | Query rewriting |
| Chunks lack their document's context; users phrase things differently from the docs | Contextual retrieval: add tags, questions answered, a 50–100-token summary |
Beyond text
- Multimodal: retrieve images by caption or with joint embeddings (CLIP).
- Tabular: text-to-SQL → execute → generate.
- Retrieved content is untrusted: indirect prompt injection (see Prompting).