Slides · Retrieval-augmented generation
The core RAG pipeline
1 / 26
The core RAG pipeline
Every stage from parsing to generation, the trade-off at each one, and how to tell which stage produced a confident wrong answer.
Concept
Answer quality is capped by retrieval quality
- Aarav receives three policy pages. The top one looks tidy and official, and it is headed with last year’s date. Which step was supposed to notice?
- The generator can only use what the earlier stages hand it. A better model cannot fix a chunk that was never retrieved.
- In interviews the stage names are the easy part. What separates answers is judging retrieval separately from generation, and knowing when not to use RAG.
Three things you will be able to do:
- Choose between RAG, fine-tuning and long context for a given need.
- Explain each pipeline stage and its main trade-off.
- Name the stages where a wrong answer can start, and run the test that separates retrieval from generation.
Concept
A library with a reference desk
- Librarians file the books ahead of time. That is the offline lane.
- When a question arrives, a clerk fetches candidate books, a specialist narrows them to the best few, and a writer composes the answer from only those books. That is the online lane.
- Each person fails differently: a mis-filed book, a clerk who fetches the wrong shelf, a specialist who ranks badly, a writer who ignores the open book.
Four different bugs, four different fixes. The whole lesson is about telling them apart.
Diagram
The two lanes meet at the index
Diagram
Follow one question through the stages
Text summary
This tool walks one question through a RAG pipeline in six steps: question, embed, retrieve, rerank, prompt and answer (generate). It uses six made-up passages from an imaginary library, and the question is “How do I renew a book online?”. No model runs and nothing is fetched. The passages were embedded ahead of time; at the embed step only the question becomes a vector, with the same embedding model. The vectors have four numbers each and are hand-made, and the cosine similarity scores are computed exactly from them. Retrieval here is dense (vector) retrieval only, to keep it simple. At the retrieve step, the passage about renewing a library card (P1) scores 0.926 and the passage about renewing a book online (P2) scores 0.855, so the wrong one comes first. Retrieve keeps the top three: P1, P2 and P3. At the rerank step, made-up scores from a pretend reranker (often a cross-encoder in real systems), on a 0 to 1 scale, put P2 first (0.91) and P1 second (0.22), so the two swap places. That is why a pipeline reranks: cheap vector similarity finds candidates, and a slower check that reads the question and passage together orders them. The cut from three passages to two is illustrative; real pipelines often shortlist about 50 and keep about 5. The prompt keeps the top two passages with their ids. The answer is written by hand and cites P2. Scores are shown in tables, not by colour alone.
The interactive version needs JavaScript. The text summary above says what it shows.
Compare
Three ways to get facts into an answer
| Approach | What it changes | Strength | Cost |
|---|---|---|---|
| Fine-tuning | Behaviour: style, format, task skill | Consistent output shape | Facts live in the weights and go stale; no citation; hard to delete one document |
| Long context | Puts the whole corpus in the prompt | Simple when the corpus is small and stable | Every token adds cost and latency; some corpora do not fit |
| RAG | Fetches facts at question time | Fresh, citable, permission-aware, cheap to update | You now run a retrieval system |
- The RAG paper describes knowledge held in model weights as parametric memory, and lists updating it and giving provenance as open problems. RAG adds an external, non-parametric memory (Lewis et al., 2020).
- Anthropic’s docs caution that a bigger window is not automatically better: accuracy and recall can degrade as the token count grows, an effect they name context rot.
- One-line rule: RAG for knowledge, fine-tuning for behaviour, and they can be combined.
Sources[1] Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks[2] Context windows
Diagram
Match the tool to what must change
Check yourself
Check: pick the approach
A support tool must stop using one customer’s data the day that customer asks to be forgotten. Separately, a team has a stable 30-page internal handbook and wants simple Q&A over it. Which approach fits each, and why?
Answer
Forgetting: keep the customer’s data in an external store (RAG) and delete the customer’s chunks. Facts baked into weights cannot be reliably removed one customer at a time. Handbook: a small, stable corpus may fit in the prompt, so long context can be the simplest choice; move to RAG if it grows, changes often or costs too much per request. Fine-tuning would not be the first tool for either, because neither need is about behaviour.
Concept
Stages 1 and 2: parse, tag and chunk
- Parse and tag. Garbage in, garbage out. PDFs with tables and multi-column layouts need layout-aware parsing. Attach metadata now (source, section, date, tenant or access list), because filtering and permissions depend on it later.
- Chunk. Small chunks are precise but context-poor. Large chunks carry context but dilute the embedding. Split on structure, not raw characters.
- Sizes and overlap are settings to tune on a labelled set, not constants. The previous lesson showed how.
Concept
Stage 3: embedding
- A bi-encoder maps text to a vector. It embeds the query and each chunk separately, so chunk vectors can be computed ahead of time.
- Queries and chunks must use the same model. Vectors from two models live in different spaces, so comparing them is meaningless even when the sizes match.
- Choose by domain fit, language coverage, vector size (storage and latency) and cost.
- Switching models means re-embedding the whole corpus, so version your index.
Compare
Stage 4: the vector index
Exact search compares the query with every vector. That gets slow at scale, so most systems use an approximate index and accept a little lost recall.
| Option | Idea | Trade-off (per the pgvector README) |
|---|---|---|
| Exact search | Compare against every vector | Perfect recall (the README’s default behaviour) |
| HNSW | Graph-based approximate index | Better speed-recall trade-off; slower to build and more memory |
| IVFFlat | Cluster-based approximate index | Faster to build and less memory; lower speed-recall performance |
- The pgvector README says an approximate index “trades some recall for speed”, and that results can differ after adding one.
- Say “recall versus latency versus memory” when you explain this in an interview.
Source[3] pgvector: open-source vector similarity search for Postgres
Compare
Stage 5: retrieve with two kinds of search
| Aspect | Dense (embeddings) | Sparse (BM25, keywords) |
|---|---|---|
| Matches | Meaning and paraphrase | Exact terms |
| Weak on | Exact tokens: IDs, error codes, rare names | Synonyms and paraphrase |
| Score scale | Bounded, for example cosine similarity | Usually unbounded (Elastic) |
- Anthropic’s contextual retrieval post makes the same point with an error code: an embedding model may return general error-code content and miss the exact match, while BM25 can find the specific string.
- Hybrid runs both and merges the lists. The scores are on incompatible scales, so merging by rank is attractive. That is where Reciprocal Rank Fusion comes in.
Sources[4] Introducing Contextual Retrieval[5] Elasticsearch hybrid search
Math
Reciprocal Rank Fusion (RRF)
RRFscore(d)=r∑k+rankr(d)1| Symbol | Meaning |
|---|---|
| d | One document (or chunk) |
| r | One ranked result list, for example the BM25 list or the vector list |
| rankr(d) | Position of d in list r (1 is best); a list that does not contain d adds nothing |
| k | A constant. Cormack, Clarke and Buettcher fixed k=60 in a pilot investigation and did not alter it afterwards |
- RRF uses ranks only, so you never normalise the incompatible score scales.
- The paper’s intuition: top ranks matter more, but lower-ranked documents still count (an exponential weighting would shrink them away). In the authors’ words, k “mitigates the impact of high rankings by outlier systems”.
- k=60 is a sensible default, not a law. In their pilot it came out near-optimal, and they describe the exact choice as “not critical”.
Source[6] Reciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods
Worked example
RRF with real numbers
Two ranked lists (invented documents P to U). BM25 returns P, Q, R, S. Vector search returns R, T, Q, U.
| Doc | BM25 rank | Vector rank | k=60 | k=0 |
|---|---|---|---|---|
| R | 3 | 1 | 631+611=0.0323 | 31+11=1.333 |
| Q | 2 | 3 | 621+631=0.0320 | 21+31=0.833 |
| P | 1 | not returned | 611=0.0164 | 11=1.000 |
| T | not returned | 2 | 621=0.0161 | 21=0.500 |
- With k=60 the fused order is R, Q, P, T. P was first in BM25, but it appears in one list only, so it loses to R and Q, which both retrievers liked.
- With k=0 the order becomes R, P, Q, T: a rank-1 hit in a single list jumps ahead of a document that two lists ranked 2nd and 3rd. A larger k flattens the difference between ranks and rewards agreement.
- (Documents S and U, ranked 4th in one list each, score 641=0.0156 at k=60.)
Source[6] Reciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods
Check yourself
Check: fuse two lists
With k=60, list 1 is A, B, C and list 2 is C, D, A. Which documents lead the fused order, and what are their scores?
Answer
A and C lead, tied. A: 611+631=0.0323 (rank 1 and rank 3). C: 631+611=0.0323 (rank 3 and rank 1). B and D follow, each at 621=0.0161. Ties are possible, so break them in a fixed, documented way (for example by the better single-list rank).
Source[6] Reciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods
Diagram
Stage 6: rerank a shortlist
- A cross-encoder reads the query and one chunk together and outputs a relevance score. It is more accurate than comparing two separate vectors.
- The Sentence Transformers docs say scoring thousands or millions of (query, document) pairs would be rather slow, so a retriever first produces a candidate set (their example is 100) that the cross-encoder re-ranks.
Source[7] Retrieve & Re-Rank
Worked example
Why not cross-encode everything?
Illustrative corpus of 1,000,000 chunks. A cross-encoder needs one model call per (query, chunk) pair.
| Plan | Cross-encoder calls per query |
|---|---|
| Score the whole corpus | 1,000,000 |
| Rerank a shortlist of 50 | 50 |
- 1,000,000/50=20,000 times fewer model calls.
- Trade-off: reranking adds latency and money to every request, and it can only reorder what retrieval already returned. If the right chunk is not in the shortlist of 50, no reranker can bring it back.
- Measure it on your own question set. It is not free and not always worth it.
Source[7] Retrieve & Re-Rank
Concept
Stage 7: generate from the context
- Tell the model to answer only from the context, to cite sources, and to say “I don’t know” when the context lacks the answer.
- Use a low temperature where the model allows it.
- Put the strongest chunks at the start or end of the context. Liu et al. (2023) found that models often do best when the relevant information is at the beginning or end of the input, and degrade when it is in the middle. Measure this on your own model.
Grounding instructions can help, but they do not guarantee faithfulness. That is why later lessons teach how to evaluate it.
Source[8] Lost in the Middle: How Language Models Use Long Contexts
Diagram
Debugging a wrong answer, one question at a time
Process
The test that separates retrieval from generation
- Take the failing query and find the correct passage in the corpus.
- Paste that passage into the prompt by hand.
- Read the answer.
- Now correct: the passage never arrived. Fix retrieval or ingestion.
- Still wrong: fix the prompt or the model.
- To make this possible after the fact, log the retrieved chunk ids and scores, and the final prompt, on every request.
Without the log you are guessing which stage failed.
Compare
Where a confident wrong answer can start
| Stage | Typical failure | What to check |
|---|---|---|
| Ingestion | Bad parse, passage split across chunks, stale page in the index | Is the passage in the index, at the current version? |
| Retrieval | Wrong embedder or query, a filter (date, tenant) that excluded it, ranked below the retrieval top-k | Is it in the retrieved top-k? |
| Ranking and context | Reranker dropped it, or trimming to the token budget cut it | Is it in the final prompt? |
| Generation | It was in the prompt, but the model ignored or misread it | Does the answer follow the passage? |
| The source | The passage itself is wrong or outdated | Compare it with the authoritative document |
Worked example
Worked diagnosis (illustrative cases)
Three failing questions, each checked with the logs and the paste test:
| Case | In the index? | In retrieved top-5? | In final prompt? | Paste test | Verdict |
|---|---|---|---|---|---|
| 1 | No (old PDF version only) | No | No | not run | Ingestion: re-ingest the current version |
| 2 | Yes | Yes, at rank 4 | No (cut by the token budget) | Correct | Context assembly: raise the budget or rerank first |
| 3 | Yes | Yes, rank 1 | Yes | Still wrong | Generation: tighten the grounding instruction |
- Case 2 is the sneaky one. Retrieval looks healthy, but the chunk never reaches the model.
- Walk the columns left to right. The first “No” names the failing stage.
Check yourself
Check: name the failing stage
A user asks about a warranty exclusion. The logs show the correct chunk is in the index and was retrieved at rank 7. The system sends only the top 5 chunks to the model, which answers without the exclusion. Which stage failed, and what are two fixes?
Answer
Ranking and context: retrieval found the chunk, but it fell below the cut-off, so it never reached the prompt. Run the paste test: if the model then answers correctly with the chunk in the prompt, generation is not at fault. Fixes: add or improve a reranker so the chunk moves into the top 5, or widen what goes to the prompt (a larger k within the token budget). Re-measure the hit rate in the top 5 afterwards.
Summary
Recap
- RAG for knowledge, fine-tuning for behaviour. Long context gets costly and noisy as it grows.
- Offline lane: parse and tag, chunk, embed, index. Online lane: retrieve, rerank, generate.
- Queries and chunks share one embedding model. Changing it means re-indexing.
- Hybrid search merged with RRF (k=60 by default) fixes exact-token misses without normalising scores.
- Rerank a wide shortlist down to a few. Reranking cannot recover what retrieval missed.
- Paste the correct passage into the prompt to separate retrieval from generation, and log retrieved chunk ids to make it possible.
References
References & Sources (1 of 2)
Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks (opens in a new tab)
Patrick Lewis, Ethan Perez, Aleksandra Piktus, Fabio Petroni, et al.2020NeurIPS 2020Paper
arXiv 2005.11401 (opens in a new tab)https://arxiv.org/abs/2005.11401
Used for Parametric memory (knowledge in weights) versus an external non-parametric memory, and the framing of knowledge updating and provenance as open problems for parametric-only models.
Context windows (opens in a new tab)
Anthropic2026Documentation
https://platform.claude.com/docs/en/build-with-claude/context-windows
Used for More context is not automatically better: as token count grows, accuracy and recall degrade (context rot).
pgvector: open-source vector similarity search for Postgres (opens in a new tab)
pgvector2026Repository
https://github.com/pgvector/pgvector
Used for Exact search gives perfect recall; approximate indexes trade some recall for speed; HNSW and IVFFlat differ in speed-recall trade-off, build time and memory.
Introducing Contextual Retrieval (opens in a new tab)
Anthropic2024Article
https://www.anthropic.com/news/contextual-retrieval
Used for Embedding search can miss an exact string such as an error code that BM25 finds.
Elasticsearch hybrid search (opens in a new tab)
Valentin Crettaz2025Article
https://www.elastic.co/search-labs/blog/hybrid-search-elasticsearch
Used for BM25 scores are unbounded while semantic scores are bounded; RRF ranks by position and needs no score calibration or normalisation.
References
References & Sources (2 of 2)
Gordon V. Cormack, Charles L. A. Clarke, Stefan Büttcher2009SIGIR 2009Paper
https://cormack.uwaterloo.ca/cormacksigir09-rrf.pdf
Used for The Reciprocal Rank Fusion formula, k = 60 fixed in a pilot investigation, and the intuition behind the constant.
Retrieve & Re-Rank (opens in a new tab)
Sentence Transformers2026Documentation
https://sbert.net/examples/applications/retrieve_rerank/README.html
Used for The retrieve-then-rerank pattern: scoring millions of pairs with a cross-encoder is slow, so a retriever supplies a candidate set (their example is 100) that the cross-encoder re-ranks.
Lost in the Middle: How Language Models Use Long Contexts (opens in a new tab)
Nelson F. Liu, Kevin Lin, John Hewitt, Ashwin Paranjape, et al.2023Transactions of the Association for Computational Linguistics (TACL)Paper
arXiv 2307.03172 (opens in a new tab)https://arxiv.org/abs/2307.03172
Used for Models perform best when relevant information is at the beginning or end of the input and worse when it is in the middle of a long context.
Keys: ← → move, Home End first and last, F full screen.