llm.guideChapter 15RAG I: The Canonical Pipeline

RAG I: The Canonical Pipeline

Ingest, chunking, prompt assembly and the naive-RAG failure catalog.

Part 4: Retrieval and adaptation. 9 sections, about 15 minutes.

Ingest path, offlineDocumentsPDFs, wiki, pagesParsetext, tables, layoutChunkthe unit of retrievalEnrich, embedmetadata, vectorsIndexvectors and keywordsQuery path, per requestQuestionfrom the userRetrievethe step that decidesAssemblecontext, rules, sourcesGenerate, checkanswer and citationstop chunks
Ingest: parse, chunkoffline, document by documentIndexvectors and keywordsQuery: retrievethe step that decides mostAssemblecontext, rules, sourcesGenerate, checkanswer with citations
Two pipelines meet at one index. Most of a RAG system’s quality is decided on the ingest path and in retrieval, before any model writes a word.

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.

Ingest: runs when documents changeFilesParseChunkEnrichEmbedIndexQuery: runs on every requestQuestionRetrieveAssembleGenerateAnswer
Figure 15.1 The two pipelines. Ingest prepares documents for search whenever they change. The query pipeline uses that index on every request.

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.

SourceWhat naive extraction producesDamage downstream
Two-column PDFLines interleaved across the columnsChunks of shredded sentences, which retrieve other shredded sentences
TablesRows and columns flattened into a stream of cellsThe right table is retrieved and the model reads the wrong cell
Headers, footers, page numbers“Acme Confidential, page 14” inside every chunkBoilerplate dominates similarity; chunks match each other, not the query
Scanned pagesNothing: an image with no text layerSilent holes. The document exists and cannot be found (section 12.6)
Old and new versions togetherAll indexed as equalsLast 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.

The pagePlanPriceSeatsBasic$101Team$255Business$6020Naive extractionPlan Price Seats Basic $10 1 Team $25 5 Business $60 20→ “Which plan has 5 seats?” The chunk has the numbers, but nothing ties $25 to Team or 5 to seats.Structure-aware parsingPlan: Basic | Price: $10 | Seats: 1Plan: Team | Price: $25 | Seats: 5Plan: Business | Price: $60 | Seats: 20→ each row is a record the model can read correctly
Figure 15.2 The same table parsed badly and well. Both chunks would be retrieved; only the second can be read without guessing.

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.

The documentheadings (highlighted) and paragraphsFixed sizeOverlappingStructure-awareFixed size splits mid-sentence. Overlap repeats text, so each sentence is whole in some chunk.Structure-aware chunks follow the headings, so a section stays together.
Figure 15.3 Three ways to cut the same document. Structure-aware splitting needs a clean parse (section 15.2); with a poor parse, fixed windows with overlap are the safer fallback.

I measured the trade on the Wikipedia collection by cutting it four ways and searching each with keyword search.

50%60%70%80%90%sentence3 sentencesparagrapharticlequestions whose answer was retrievedsize of each chunkthe top chunk onlyas many chunks as fit in 500 words
50%60%70%80%90%sentence3 sent.paragrapharticlequestions whose answer was retrievedsize of each chunkthe top chunk onlychunks that fit in 500 words
  • the answer is in the single top-ranked chunk
  • the answer is in the top chunks that fit within 500 words
Figure 15.4 Real experiment on 2,000 questions. Larger chunks are more likely to contain the answer, at the price of more text to read. Under a fixed budget of 500 words, medium-sized chunks do best.
ChunkChunks in the indexAverage wordsTop chunk contains the answerWords in the top chunkAnswer found within 500 words
One sentence103,3442457%2583.7%
Three sentences41,5565967%6788%
One paragraph20,96311774%12387%
Whole article4905,01683.6%6,110does 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:

StrategyHow it splitsWhere it fits
Fixed size with overlapEvery n tokens, with a 10 to 20% overlap so that boundary sentences appear twiceUniform prose; a baseline
Structure-awareOn headings, then paragraphs, then sentences, merged up to a target sizeThe usual default for documents with any structure
SemanticWhere the similarity between neighboring sentences dropsUnstructured walls of text; extra cost at ingest
Native unitsKeep a table, a slide or a function wholeTabular data, presentations, code
Parent-documentSearch small chunks, return the larger section around the matchWhen 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.

50%60%70%80%90%1351020questions whose answer was retrievedsentences retrievedtitle added to each sentence: 86%sentence alone: 83%
50%60%70%80%90%1351020questions whose answer was retrievedsentences retrievedwith title: 86%alone: 83%
Figure 15.5 Real experiment. Adding the title improved retrieval at every depth, by two to three points. The sentences are unchanged; they have only been told what they are about.

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.

QualityThe questionA failure looks likeWhere the cause usually is
Faithfulness, or groundednessDoes every claim follow from the retrieved chunks?The right chunks were retrieved and the answer adds a plausible detail they do not containGeneration: the prompt’s scope, the model, the sampling settings
RelevanceDoes the answer address what was asked?An accurate summary of the wrong thing: asked how to cancel, told how to subscribeRetrieval: 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.

Unfaithful, relevant“Cancel under Billing; you get arefund within 30 days.” The refund isinvented. Fix generation.Faithful and relevant“Open Billing, choose Cancel plan,confirm.” Every step is in theretrieved article.NeitherAn invented account of upgrading. Fixretrieval first, then generation.Faithful, irrelevantAn accurate summary of how to upgrade.The wrong chunk was retrieved. Fixretrieval.not faithfulfaithfuldoes every claim follow from the chunks?relevantirrelevantanswers the question?
Figure 15.6 Example answers to “How do I cancel my plan?” in each cell. The column tells you whether to work on generation; the row, whether to work on retrieval.

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.

FailureSymptomMechanismFix
Parsing rotPoor quality on particular source typesShredded or empty chunks (section 15.2)Better parsers; read samples
Orphaned chunkRetrieved text is cut mid-thought and the model fills the gapThe answer straddles a chunk boundaryOverlap; structure-aware splitting; parent-document retrieval
Vocabulary mismatchParaphrased questions find nothingThe user’s words differ from the document’sEmbeddings; query rewriting (section 16.4)
Missed identifierProduct codes and error numbers return generic pagesEmbeddings smooth away exact stringsHybrid search (section 14.8)
Distractor pullThe right chunk is present, but the answer follows a similar wrong oneNear-misses compete for attentionReranking; fewer chunks
Lost in the middleQuality depends on where the right chunk fell in the listAttention is weakest mid-contextOrder deliberately; rerank; fewer chunks
Multi-part question“Compare X’s policy with Y’s” returns chunks about only oneOne query vector cannot point in two directionsSplit the question; agentic retrieval (section 16.6)
Aggregation question“How many customers mentioned pricing?” gets a confident wrong numberThe top few chunks cannot be counted or summed over a collectionRoute to a database query (section 16.5)
Stale blendAnswers mix old and new policySeveral versions indexed without a filterVersion metadata and filters
Empty retrievalA question outside the collection gets a fluent invented answerNo permission to abstainAbstention instruction; a minimum relevance score
Parsedocuments to textParsing rotChunktext to piecesOrphaned chunkIndexversions and filtersStale blendRetrievefind candidatesVocabulary mismatchMissed identifierMulti-part questionAggregation questionAssembleorder the contextDistractor pullLost in the middleGeneratewrite the answerEmpty retrieval
Figure 15.7 The same ten failures, placed on the stage where each one starts. Four begin at retrieval, which is why retrieval metrics are the first thing to check, and only one starts in generation.

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).
Source changeedit or deleteRe-chunkhash each chunkHash changed?only these re-embedunchanged: skipVector indexKeyword indexAnswer cachePrompt logsEvery chunk keeps a stable link to its source record, so a deletion can find every copy.Track the delay from source change to searchable, and alert when it grows.
Figure 15.8 How a change flows through the index. Hashes keep updates cheap; source links keep deletions complete, which is the part with legal weight.

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.

A wrong answer is reportedWas the passage with the answeramong the retrieved chunks?noyesThe problem is in retrievalThe problem is in generationNot in the index at all?Ingest: parsing, a scanned page,a version filterIn the index, but ranked low?Recall: vocabulary, identifiers,multi-part questionsRetrieved, but mangled?Chunking or parsingFollows a similar, wrong chunk?Distractors or ordering:rerank, reorder, send fewerAdds claims found in no chunk?Faithfulness: tighten the prompt,change the modelFaithful, but beside the point?Look at the first question againwith fresh eyes
Figure 15.9 The bisection tree. The first question splits every wrong answer into a retrieval problem or a generation problem, and no change on one side can fix a fault on the other.

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

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

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

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

↑↓ to move↵ to openesc to close