Slides · Retrieval-augmented generation

The core RAG pipeline

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:

  1. Choose between RAG, fine-tuning and long context for a given need.
  2. Explain each pipeline stage and its main trade-off.
  3. 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: Two chains meet at the index.

Offline: parse, tag

Offline: chunk

Offline: embed

Vector index

Online: embed query

Online: retrieve

Online: rerank

Online: generate

Diagram summary: Two chains meet at the index. The offline steps (parse and tag, chunk, embed, index) run ahead of time and fill the vector index. The online steps (embed the query, retrieve, rerank, generate) run for every question, and retrieve reads from that index.

Diagram

Follow one question through the stages

The RAG pipeline, one step at a time

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

ApproachWhat it changesStrengthCost
Fine-tuningBehaviour: style, format, task skillConsistent output shapeFacts live in the weights and go stale; no citation; hard to delete one document
Long contextPuts the whole corpus in the promptSimple when the corpus is small and stableEvery token adds cost and latency; some corpora do not fit
RAGFetches facts at question timeFresh, citable, permission-aware, cheap to updateYou 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.

Sources1 Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks2 Context windows

Diagram

Match the tool to what must change

Diagram: Facts that change, are private or need citations go in RAG.

Facts that change,
private or citable

Style, format,
task skill

Small, stable corpus

What must change?

RAG

Fine-tuning

Long context

Can be combined

Diagram summary: Facts that change, are private or need citations go in RAG. Style, format and task skill go in fine-tuning. A small, stable corpus may simply fit in the prompt. RAG and fine-tuning can be combined.

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.

OptionIdeaTrade-off (per the pgvector README)
Exact searchCompare against every vectorPerfect recall (the README’s default behaviour)
HNSWGraph-based approximate indexBetter speed-recall trade-off; slower to build and more memory
IVFFlatCluster-based approximate indexFaster 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.

Source3 pgvector: open-source vector similarity search for Postgres

Compare

Stage 5: retrieve with two kinds of search

AspectDense (embeddings)Sparse (BM25, keywords)
MatchesMeaning and paraphraseExact terms
Weak onExact tokens: IDs, error codes, rare namesSynonyms and paraphrase
Score scaleBounded, for example cosine similarityUsually 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.

Sources4 Introducing Contextual Retrieval5 Elasticsearch hybrid search

Math

Reciprocal Rank Fusion (RRF)

RRFscore(d)=∑r1k+rankr(d)\mathrm{RRFscore}(d) = \sum_{r} \frac{1}{k + \mathrm{rank}_r(d)}
SymbolMeaning
ddOne document (or chunk)
rrOne ranked result list, for example the BM25 list or the vector list
rankr(d)\mathrm{rank}_r(d)Position of dd in list rr (1 is best); a list that does not contain d adds nothing
kkA constant. Cormack, Clarke and Buettcher fixed k=60k = 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=60k = 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”.

Source6 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.

DocBM25 rankVector rankk=60k = 60k=0k = 0
R31163+161=0.0323\frac{1}{63} + \frac{1}{61} = 0.032313+11=1.333\frac{1}{3} + \frac{1}{1} = 1.333
Q23162+163=0.0320\frac{1}{62} + \frac{1}{63} = 0.032012+13=0.833\frac{1}{2} + \frac{1}{3} = 0.833
P1not returned161=0.0164\frac{1}{61} = 0.016411=1.000\frac{1}{1} = 1.000
Tnot returned2162=0.0161\frac{1}{62} = 0.016112=0.500\frac{1}{2} = 0.500
  • With k=60k = 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=0k = 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 kk flattens the difference between ranks and rewards agreement.
  • (Documents S and U, ranked 4th in one list each, score 164=0.0156\frac{1}{64} = 0.0156 at k=60k = 60.)

Source6 Reciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods

Check yourself

Check: fuse two lists

With k=60k = 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: 161+163=0.0323\frac{1}{61} + \frac{1}{63} = 0.0323 (rank 1 and rank 3). C: 163+161=0.0323\frac{1}{63} + \frac{1}{61} = 0.0323 (rank 3 and rank 1). B and D follow, each at 162=0.0161\frac{1}{62} = 0.0161. Ties are possible, so break them in a fixed, documented way (for example by the better single-list rank).

Source6 Reciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods

Diagram

Stage 6: rerank a shortlist

Diagram: Each stage narrows the field for a more expensive one.

Whole corpus
e.g. 1,000,000 chunks

Hybrid retrieve
shortlist about 50

Cross-encoder rerank
keep about 5

Prompt

Diagram summary: Each stage narrows the field for a more expensive one. A fast search runs over everything, a slower reranker reads only the shortlist, and only the few best chunks reach the prompt. The 1,000,000, 50 and 5 are illustrative.
  • 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.

Source7 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.

PlanCross-encoder calls per query
Score the whole corpus1,000,000
Rerank a shortlist of 5050
  • 1,000,000/50=20,0001{,}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.

Source7 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.

Source8 Lost in the Middle: How Language Models Use Long Contexts

Diagram

Debugging a wrong answer, one question at a time

Diagram: Ask first whether the right text was in the retrieved chunks.

no

no

yes

low

top

no

yes

A wrong answer

Was the answer text
in the retrieved chunks?

In the
index?

Fix
ingestion

Fix
retrieval

Fix
rerank

Model
used it?

Fix
prompt

Check
source

Diagram summary: Ask first whether the right text was in the retrieved chunks. If not, check whether it is in the index: if not, fix ingestion (parsing, chunking); if yes, fix retrieval (hybrid, query rewrite, embedder). If it was retrieved but ranked low (“low”), fix reranking or the shortlist size. If it ranked near the top (“top”) and the model still ignored it, fix the prompt, ordering or grounding instruction. If it was in the prompt and still ignored, it is generation. If the model used it faithfully, the source itself may be wrong or out of date.

Process

The test that separates retrieval from generation

  1. Take the failing query and find the correct passage in the corpus.
  2. Paste that passage into the prompt by hand.
  3. Read the answer.
    • Now correct: the passage never arrived. Fix retrieval or ingestion.
    • Still wrong: fix the prompt or the model.
  4. 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

StageTypical failureWhat to check
IngestionBad parse, passage split across chunks, stale page in the indexIs the passage in the index, at the current version?
RetrievalWrong embedder or query, a filter (date, tenant) that excluded it, ranked below the retrieval top-kIs it in the retrieved top-k?
Ranking and contextReranker dropped it, or trimming to the token budget cut itIs it in the final prompt?
GenerationIt was in the prompt, but the model ignored or misread itDoes the answer follow the passage?
The sourceThe passage itself is wrong or outdatedCompare it with the authoritative document

Worked example

Worked diagnosis (illustrative cases)

Three failing questions, each checked with the logs and the paste test:

CaseIn the index?In retrieved top-5?In final prompt?Paste testVerdict
1No (old PDF version only)NoNonot runIngestion: re-ingest the current version
2YesYes, at rank 4No (cut by the token budget)CorrectContext assembly: raise the budget or rerank first
3YesYes, rank 1YesStill wrongGeneration: 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=60k = 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)

  1. 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

    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.

  2. Context windows (opens in a new tab)

    Anthropic2026Documentation

    Used for More context is not automatically better: as token count grows, accuracy and recall degrade (context rot).

  3. pgvector: open-source vector similarity search for Postgres (opens in a new tab)

    pgvector2026Repository

    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.

  4. Introducing Contextual Retrieval (opens in a new tab)

    Anthropic2024Article

    Used for Embedding search can miss an exact string such as an error code that BM25 finds.

References

References & Sources (2 of 2)

  1. Reciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods (opens in a new tab)

    Gordon V. Cormack, Charles L. A. Clarke, Stefan Büttcher2009SIGIR 2009Paper

    Used for The Reciprocal Rank Fusion formula, k = 60 fixed in a pilot investigation, and the intuition behind the constant.

  2. Retrieve & Re-Rank (opens in a new tab)

    Sentence Transformers2026Documentation

    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.

  3. 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

    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.