RAG I: The Canonical Pipeline
Ingest, chunking, prompt assembly and the naive-RAG failure catalog.
A language model does not know your refund policy, last week’s incident report, or anything written after its training ended. Retrieval-augmented generation, RAG, is the standard answer: find the relevant text at question time and put it in the prompt. The idea takes a sentence. Making it reliable is a pipeline with half a dozen stages, each of which fails in its own way.
This chapter builds the plain version of that pipeline, names the ways it breaks, and gives a procedure for finding which stage is at fault. The measurements use the same 2,000 questions and 20,963 Wikipedia paragraphs as Chapter 14.
15.1Two pipelines
Two pipelines and one contract.
Section 2.9 listed grounding as one of the strongest remedies for hallucination: put the facts in the context, and the plausible continuation and the true one become the same tokens. RAG is that remedy built as a system. It has two pipelines that run on different clocks.
They fail independently and at different speeds. A retrieval problem shows up in individual answers. A parsing problem during ingest can poison the index for weeks, because nobody watches ingest.
What you get for building both is a contract that model knowledge alone cannot offer.
- Freshness. Change a document, re-ingest it, and answers change today, with no training.
- Private data. Your wiki was never in any model’s weights. This is the knowledge wall of section 13.10.
- Citations. Answers can point at passages that a person can check, a property that fine-tuning can never provide.
One caveat on scope. If the whole body of knowledge is small, you may not need retrieval at all. Anthropic’s guidance is that a knowledge base under about 200,000 tokens can simply be placed in the prompt, with caching to control the cost (section 11.6).
Common take“RAG is a vector database plus a language model.”
Sharper take“RAG is a contract for freshness and provenance, built as two pipelines. The offline one is where the invisible bugs live.”
15.2Parsing
The unglamorous stage that poisons everything downstream.
Real document collections are PDFs, wiki exports, web pages and slide decks, and naive text extraction mangles all of them.
| Source | What naive extraction produces | Damage downstream |
|---|---|---|
| Two-column PDF | Lines interleaved across the columns | Chunks of shredded sentences, which retrieve other shredded sentences |
| Tables | Rows and columns flattened into a stream of cells | The right table is retrieved and the model reads the wrong cell |
| Headers, footers, page numbers | “Acme Confidential, page 14” inside every chunk | Boilerplate dominates similarity; chunks match each other, not the query |
| Scanned pages | Nothing: an image with no text layer | Silent holes. The document exists and cannot be found (section 12.6) |
| Old and new versions together | All indexed as equals | Last year’s policy is retrieved beside this year’s and the answer blends them |
This stage outranks the choice of model in its effect on quality, for a simple reason: no later stage can detect the damage. A mangled chunk gets a mangled embedding and is retrieved for the wrong queries, and the language model grounds itself on it and answers fluently.
The practice is unglamorous too. Use parsers that respect structure: layout-aware extraction for PDFs, conversion of web pages to text that keeps headings, tables kept as tables. Strip boilerplate. Remove duplicates and track versions. Then open a random sample of chunks from each kind of source and read them. Half an hour of reading your own chunks finds more problems than a week of prompt changes.
Common take“We loaded all the documents, so the data is in.”
Sharper take“The files are in. Whether the text is in depends on the parser, so I read a sample of chunks from every source type before I measure anything else.”
15.3Chunking
It sets the resolution of the whole system.
Documents are split into chunks before indexing, and the chunk plays three roles at once. It is the unit of embedding: too large, and one vector has to stand for five topics. It is the unit of retrieval: too small, and what comes back lacks the context to answer, as in “the fee is waived in this case” with no sign of which case. And it is the unit of spending: the number of chunks times their size is the context you pay for.
I measured the trade on the Wikipedia collection by cutting it four ways and searching each with keyword search.
- the answer is in the single top-ranked chunk
- the answer is in the top chunks that fit within 500 words
| Chunk | Chunks in the index | Average words | Top chunk contains the answer | Words in the top chunk | Answer found within 500 words |
|---|---|---|---|---|---|
| One sentence | 103,344 | 24 | 57% | 25 | 83.7% |
| Three sentences | 41,556 | 59 | 67% | 67 | 88% |
| One paragraph | 20,963 | 117 | 74% | 123 | 87% |
| Whole article | 490 | 5,016 | 83.6% | 6,110 | does not fit |
Read the last row of the table. Retrieving a whole article finds the answer 84% of the time and hands the model six thousand words to do it. Three-sentence chunks reach 88% in under five hundred. Single sentences fall behind, because a sentence alone often lacks the words the question uses.
The optimum depends on the collection and on the search method, which is why it has to be measured. Common strategies:
| Strategy | How it splits | Where it fits |
|---|---|---|
| Fixed size with overlap | Every n tokens, with a 10 to 20% overlap so that boundary sentences appear twice | Uniform prose; a baseline |
| Structure-aware | On headings, then paragraphs, then sentences, merged up to a target size | The usual default for documents with any structure |
| Semantic | Where the similarity between neighboring sentences drops | Unstructured walls of text; extra cost at ingest |
| Native units | Keep a table, a slide or a function whole | Tabular data, presentations, code |
| Parent-document | Search small chunks, return the larger section around the match | When precise matching and rich context pull apart (section 16.3) |
Common take“We chunk at 512 tokens because that’s what the tutorial used.”
Sharper take“Chunking sets the resolution of the system. I compare chunking strategies on my labeled queries before I consider a better embedding model, because it usually moves the number more.”
15.4Enrichment and filters
A chunk forgets where it came from unless you tell it.
“The limit is $50,000 per incident.” That sentence can be retrieved. But which product, and which year? A chunk torn from its document has lost its identity, and there are two ways to give it back.
Put the context into the text before indexing. Prepend a breadcrumb: the document title and the section path.
[Enterprise Insurance Policy 2026 › Section 4: Liability › Coverage limits]
The limit is $50,000 per incident.I tested the simplest form of this on single-sentence chunks, adding only the article title to each sentence before indexing.
A stronger version has a language model write a sentence or two of context for each chunk at ingest, describing where it sits in its document. Anthropic reported that this cut the rate of failed retrievals in its tests from 5.7% to 3.7%, to 2.9% when the keyword index was contextualized as well, and to 1.9% with reranking added. It costs one model call per chunk, once.
Store metadata and filter on it. Keep fields beside each chunk: document, owner, type, effective date, version, who may see it. Then filter before the similarity search. Filters fix the blending of old and new versions from section 15.2, and they do something more important.
Common take“We store the text and its embedding.”
Sharper take“I store text with its provenance, and I treat the filter clause as carefully as the similarity clause. One decides relevance; the other decides who is allowed to see what.”
15.5Assembling the prompt
A set of policy decisions, not string concatenation.
SYSTEM
Answer using only the context below. If the context does not contain
the answer, say that you don't know based on the available documents.
After each claim, cite the chunk it came from, like [2].
<context>
<chunk id="1" source="policy_2026.pdf, section 4"> ... </chunk>
<chunk id="2" source="faq.md, refunds"> ... </chunk>
</context>
USER
{question}Each line of that template is a decision with a mechanism behind it.
- How many chunks. More chunks raise the chance that the right one is present. They also add near-misses that pull the answer off course, push good chunks into the middle of a long context where attention is weakest (section 2.4), and cost tokens. Three to eight chunks after reranking is a common range.
- Their order. Put the strongest chunks first or last, never buried mid-list.
- The delimiters. Tags mark retrieved text as material to read, not instructions to follow (section 13.4).
- The citation rule. A citation per claim gives your code and your users something to check, and it is what makes answers trustworthy enough to act on.
- The permission to abstain. Without it, an empty or wrong retrieval guarantees a confident invention, because the model must write something (section 2.9).
Common take“We paste the top results into the prompt.”
Sharper take“The prompt template sets how many chunks, in what order, how they are fenced off, whether claims must be cited, and what the model may say when the context has no answer. Each one changes the failure rate.”
15.6Faithfulness and relevance
Two different failures with different fixes.
| Quality | The question | A failure looks like | Where the cause usually is |
|---|---|---|---|
| Faithfulness, or groundedness | Does every claim follow from the retrieved chunks? | The right chunks were retrieved and the answer adds a plausible detail they do not contain | Generation: the prompt’s scope, the model, the sampling settings |
| Relevance | Does the answer address what was asked? | An accurate summary of the wrong thing: asked how to cancel, told how to subscribe | Retrieval: the wrong chunks were in the context |
The two are fixed in different places, and confusing them is the most common mistake in evaluating RAG. A team that sees wrong answers and upgrades to a larger model has addressed only the faithfulness share. The relevance share, usually the larger one, is untouched, because the right chunk is still missing from the context.
One question sorts them: could the correct answer have been derived from what was retrieved? If not, the problem is in retrieval, and no change to generation will help. Chapter 23 gives both qualities formal metrics.
Common take“The answers are wrong. We need a better model.”
Sharper take“Wrong how? If the answer adds things the chunks don’t say, that’s generation. If it faithfully answers from the wrong chunks, that’s retrieval, and a better model won’t see what was never retrieved.”
15.7The failure catalog
Ten named failures, told apart by their symptoms.
A pipeline with defaults at every stage breaks in recognizable ways. The value of this table is in telling them apart, since each has a different fix.
| Failure | Symptom | Mechanism | Fix |
|---|---|---|---|
| Parsing rot | Poor quality on particular source types | Shredded or empty chunks (section 15.2) | Better parsers; read samples |
| Orphaned chunk | Retrieved text is cut mid-thought and the model fills the gap | The answer straddles a chunk boundary | Overlap; structure-aware splitting; parent-document retrieval |
| Vocabulary mismatch | Paraphrased questions find nothing | The user’s words differ from the document’s | Embeddings; query rewriting (section 16.4) |
| Missed identifier | Product codes and error numbers return generic pages | Embeddings smooth away exact strings | Hybrid search (section 14.8) |
| Distractor pull | The right chunk is present, but the answer follows a similar wrong one | Near-misses compete for attention | Reranking; fewer chunks |
| Lost in the middle | Quality depends on where the right chunk fell in the list | Attention is weakest mid-context | Order deliberately; rerank; fewer chunks |
| Multi-part question | “Compare X’s policy with Y’s” returns chunks about only one | One query vector cannot point in two directions | Split the question; agentic retrieval (section 16.6) |
| Aggregation question | “How many customers mentioned pricing?” gets a confident wrong number | The top few chunks cannot be counted or summed over a collection | Route to a database query (section 16.5) |
| Stale blend | Answers mix old and new policy | Several versions indexed without a filter | Version metadata and filters |
| Empty retrieval | A question outside the collection gets a fluent invented answer | No permission to abstain | Abstention instruction; a minimum relevance score |
Listing fixes is the easy part. The skill is naming the failure from its symptom: “this looks like distractor pull, not a recall problem, so I would check precision and add a reranker before touching the embedding model.”
Common take“RAG sometimes gives wrong answers.”
Sharper take“It gives wrong answers in about ten distinguishable ways. I identify which one from the symptom, because the fix for a missed identifier does nothing for a stale blend.”
15.8Keeping the index current
Updates, deletions and versions.
The freshness promise in section 15.1 is kept by the ingest pipeline, day after day. Four things have to work.
- Incremental updates. Re-embedding everything nightly is wasteful and slow. Keep a hash of each chunk’s text, and re-embed only chunks whose hash changed. Track the delay between a document changing and the change being searchable, and alert when it grows.
- Deletions. When a document is deleted or a person asks for their data to be erased, the text must also leave the vector index, the keyword index, any cached answers, and stored prompts. A document that is gone from the source and still retrievable is a privacy failure and often a legal one. Give every chunk a stable link to its source record so that deletion can follow it.
- Versions. Decide what a question about “the policy” should see: usually the version in force now, sometimes the one in force on a given date. Store effective dates, and filter by them.
- Model changes. A new embedding model means a new index, built in full and switched over at once (section 14.5).
Common take“We indexed the knowledge base, so that part is done.”
Sharper take“Indexing is a running service. I monitor how far the index lags behind the source, and I can show that a deleted document is gone from every store that held a copy.”
15.9Debugging by bisection
Every wrong answer walks the same tree.
The first question does most of the work, and it is the one teams skip. It also gives the system an upper bound. If the right passage is in the context for 87% of questions, and the model answers correctly 90% of the time when it has the passage, the system is right about 78% of the time, and no amount of work on generation lifts it above 87%.
Two habits make the tree quick to walk. Log the identifiers and scores of the retrieved chunks with every request (Chapter 24); without that record, the first question cannot be answered after the fact. And turn every diagnosed failure into a new labeled query, so that the test set grows where the system is weak.
Common take“The model got it wrong.”
Sharper take“Before I say that, I check whether the answer was in what the model was shown. That one check sends the ticket to the right half of the system.”
Key takeaways
- RAG puts the relevant facts in the context so that the likely answer and the true answer coincide. It is two pipelines: ingest and query.
- It buys freshness, access to private data, and citations. A small knowledge base can skip retrieval and go in the prompt whole.
- Parsing errors poison everything after them and are invisible downstream. Read your own chunks.
- Chunk size trades the chance of containing the answer against the text to be read: whole articles held the answer 84% of the time at 6,110 words; three-sentence chunks reached 88% within 500.
- A chunk forgets its source. Adding the title to each sentence raised retrieval by two to three points at every depth.
- Filtering by permission at retrieval is a security boundary.
- The prompt template decides how many chunks, their order, citations, and whether the model may say it does not know.
- Faithfulness failures are fixed in generation; relevance failures in retrieval. Ask whether the answer was derivable from what was retrieved.
- Ingest is a running service: update incrementally, propagate deletions everywhere, filter by version.
- Retrieval recall is the ceiling on answer accuracy. Log retrieved chunk identifiers with every request.
Check your understanding
-
Your assistant answers questions about the company wiki well. Questions about the policy documents, which are PDFs, get vague or wrong answers. Walk the bisection tree for this case and say what you would look at first.
Answer outline
Take a few failing questions and check whether the passage with the answer was retrieved. If not, check whether it is in the index at all. For PDFs the likely findings are scanned pages with no text, two-column pages extracted as interleaved lines, tables flattened into cell streams, and repeated headers and footers dominating every chunk. So the first thing to look at is the chunks themselves: open a sample from the PDF folder and read them. The fix is in parsing, with layout-aware extraction and text recognition for scans, followed by re-ingesting. Changing the model or the prompt will not help.
-
To improve recall you raise the number of retrieved chunks from 5 to 20. Recall on your labeled set goes up, and answer quality goes down. Explain how both can be true and what you would change.
Answer outline
With 20 chunks the right passage is more often present, which is what recall measures. But it now arrives with fifteen more near-misses, some of which pull the answer toward the wrong passage, and it may sit in the middle of a long context where the model attends least. Precision fell while recall rose. The change is to keep retrieving widely and then narrow: rerank the 20 or more candidates with a more accurate scorer and send only the best few, placed first. Measure recall into the reranker and answer quality after it separately.
-
A customer exercises their right to erasure, and your team deletes their records from the main database. A week later a support answer quotes one of their old tickets. List every place the text could still be, and how you would design ingest so that this cannot happen.
Answer outline
The text can survive in the vector index, the keyword index, cached answers, stored prompts and logs, backups, and any evaluation set built from real traffic. Design: every chunk carries the identifier of its source record; deleting a record emits an event that removes its chunks from every index and invalidates caches that included them; retention limits apply to logs and stored prompts; and a periodic reconciliation job compares the indexes with the source of truth and removes anything whose source is gone. Then test it by deleting a record and searching for its text.
Further reading
- Chip Huyen, AI Engineering, chapter 6: the RAG architecture and its retrieval choices.
- Shreya Shankar and Hamel Husain, Evals for AI Engineers, chapter 7: evaluating retrieval and generation separately.
- Anthropic, “Introducing Contextual Retrieval”: the source of the failure-rate figures in section 15.4, with the prompt used to write context for each chunk.
- Lewis et al. (2020), “Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks”: the paper that named the idea.