llm.guideChapter 16RAG II: Advanced Architectures

RAG II: Advanced Architectures

Reranking, query transforms, routing, GraphRAG and text-to-SQL.

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

Routewhich path fits?1 path+50 msRewritea better query3 queries+300 msRetrievewide50 chunks+80 msReranknarrow5 chunks+200 msAnswerfrom what survived1 answerIllustrative counts and latencies. Each stage fixes one failure and adds its own cost.
Routewhich path fits? +50 msRewrite3 queries, +300 msRetrieve50 chunks, +80 msRerank5 chunks, +200 msAnswerfrom what survived
A retrieval pipeline with every optional stage added, as a funnel. Few systems need all of it; each stage should be justified by a failure it fixes.

Chapter 15 built the plain pipeline and catalogued ten ways it fails. This chapter is the matching set of repairs: reranking, parent-document retrieval, query rewriting, routing, agentic search, knowledge graphs, database queries and page-image retrieval. Each is worth knowing. None should be installed on reputation.

Where a repair can be tested without a language model, it is tested here, on the same 2,000 questions as the last two chapters. One of the best-known patterns helped in one setting and hurt in another, which is the argument of the chapter in miniature.

16.1A parts catalog

Every advanced pattern exists to fix one named failure.

Failure from section 15.7The part that addresses it
Distractor pull; lost in the middleReranking (section 16.2)
Orphaned chunks; the tension over chunk sizeParent-document retrieval (16.3)
Vocabulary mismatch; follow-up questions in a chatQuery rewriting and expansion (16.4)
Aggregation questions; mixed collectionsRouting (16.5) and database queries (16.7)
Multi-part questionsDecomposition (16.4); agentic retrieval (16.6)
Questions about themes across the whole collectionKnowledge graphs (16.7)
Parsing rot in layout-heavy documentsPage-image retrieval (16.8)

Each part adds latency, cost and a failure mode of its own. So the rule for adopting one is strict: find the failure class in your labeled set, add the one component that targets it, measure before and after, and stop.

Failure, from your labeled setThe one part that targets itDistractors, lost in the middleReranking16.2Orphaned chunksParent-document retrieval16.3Vocabulary mismatch, follow-upsQuery rewriting and expansion16.4Aggregation, mixed collectionsRouting, database queries16.5, 16.7Multi-part questionsDecomposition, agentic retrieval16.4, 16.6Themes across the collectionKnowledge graphs16.7Layout-heavy documentsPage-image retrieval16.8
Figure 16.1 The catalog as a map. Start from the left column, with a count from your own failures, and add one part at a time.

Common take“We’re building advanced RAG: reranking, query expansion, a graph, and agents.”

Sharper take“My architecture is the smallest set of components that my measured failures justify. Each one had to earn its place against a before-and-after number.”

16.2Reranking

Retrieve wide, then narrow with a more accurate scorer.

Section 14.4 described the bargain: a bi-encoder is fast and lossy, a cross-encoder is accurate and slow. Reranking uses each where it is strong.

the whole indexmillions of chunksretrievedthe top 50rerankedthe top 5fast, approximateslow, precise
Figure 16.2 The funnel. The first stage is judged on whether the right chunk is somewhere in its fifty. The second is judged on whether it ends up in the five.

It is usually the first part worth adding, because it resolves a trade that otherwise has no good answer. Retrieving more chunks raises recall and floods the prompt with near-misses. Retrieve widely, rerank, and send only the best few, and both improve together.

The numbers from Chapter 14 show how much room a reranker has. Keyword search ranked the right paragraph first for 70.2% of questions, put it in the top ten for 90.8%, and in the top hundred for 96.8%. The gap between 70 and 97 is what a better final ordering could win back. In Anthropic’s published tests, adding a reranker to hybrid retrieval cut the rate of failed retrievals from 2.9% to 1.9%.

The costs are real. A reranker is one more model to serve, version and evaluate. Scoring fifty pairs takes tens of milliseconds on a GPU, or a round trip to a hosted service, though a shorter prompt gives some of that time back. A general-purpose reranker can misjudge relevance in a specialized field, so test it on your own queries.

Common take“We added a reranker and the hard queries still fail.”

Sharper take“A reranker fixes order, not coverage. I check recall in the candidates going into it. If the right chunk isn’t among them, nothing downstream can help.”

16.3Parent-document retrieval

Match on small chunks, return large ones.

Section 15.3 left a tension. Small chunks give precise matches and too little context. Large chunks give context and blurred matches. Parent-document retrieval separates the unit you search from the unit you return: index the sentences, and when one matches, hand the model the paragraph or section it came from.

I tested it both ways. In each case the question is whether the correct paragraph was returned.

Search methodWhat is searchedRight paragraph firstIn the first 3In the first 5
Keyword searchParagraphs70.2%83.3%86.8%
Keyword searchSentences, returning their paragraphs63.1%75.4%80.2%
Keyword searchSentences with the article title added, returning their paragraphs65%78.6%83.1%
EmbeddingsParagraphs32.9%45.7%52.8%
EmbeddingsSentences, returning their paragraphs45.5%58.8%64.8%

The pattern helped one search method and hurt the other. With embeddings, matching on sentences found the right paragraph twelve points more often than embedding whole paragraphs, exactly as the theory says: a sentence’s vector is not diluted by the other sentences around it. With keyword search, the same change cost seven points, because keyword search benefits from having more of a paragraph’s words to match against.

That is the lesson of the chapter in one table. A pattern is a fix for a mechanism. Where the mechanism is absent, the pattern is only overhead, or worse. Adding the article title to each sentence helped the keyword version, as in section 15.4, and still did not make it better than searching paragraphs directly.

The costs elsewhere are bookkeeping, since the link from child to parent has to survive re-ingestion, and budget, since parents are large and a few of them fill the context.

Query“when is the feewaived?”Index: sentencesprecise match on one sentenceReturned: its paragraphthe context to answer
Figure 16.3 Search small, return large. My test above found it helps embeddings, which blur on long text, more than keyword search.

Common take“Small-to-big retrieval is a best practice, so we use it.”

Sharper take“It fixes blurred embeddings of long chunks. In my test it gained twelve points with embeddings and lost seven with keyword search. I use it where the mechanism it fixes is present.”

16.4Query transforms

Sometimes the query is the problem, not the index.

TransformWhat it doesWhat it fixesCost and risk
RewritingTurns a follow-up into a standalone query: “what about Germany?” becomes “parental leave policy in Germany”Chat follow-ups that mean nothing on their ownOne small model call. Required in any conversational product
Multi-queryA small model writes three to five paraphrases; all are searched and the results fused by rankVocabulary mismatch: one phrasing lands in the document’s dialectOne model call and several searches in parallel. The safe default of the group
DecompositionSplits “compare X with Y” into a query about X and a query about YMulti-part questionsOne model call; sub-answers may depend on each other
Hypothetical answerThe model writes a plausible answer, and that is embedded and searchedQuestions and documents are phrased differently; a fake answer looks like a real documentIf the model does not know the domain, its guess points the search at the wrong region

The last row needs care. A hypothetical answer is a hallucination put to use, and it inherits the model’s blind spots. For a new product the model has never heard of, the invented answer names older products and older terms, and the search dutifully retrieves the wrong era. Use it where the model already knows the domain well, and prefer paraphrases for new or private material.

“What about Germany?”after a question onparental leave in FranceRewrite“parental leave policy in Germany”Multi-query“German parental leave”, “Elternzeit rules”, “leave for new parents,Germany”Decompose“leave in France” and “leave in Germany”, for a comparisonHypothetical answer“In Germany, parents may take up to three years…” embedded and searched
Figure 16.4 Four transforms of one follow-up. Rewriting is required in any chat product; the others earn their extra calls only on failures they target.

Common take“We do query expansion.”

Sharper take“I rewrite follow-ups into standalone queries because chat requires it, and I add paraphrases when my failures are vocabulary mismatches. I can say which transform targets which failure.”

16.5Routing

Classify the question first, because one pipeline cannot serve every kind.

Some questions cannot be answered by retrieving a few chunks, however good the retrieval. “How many customers mentioned pricing last quarter?” needs a count over the whole collection. “What does HTTP stand for?” needs no retrieval at all. A router sends each question to the path that can answer it.

Kind of questionPath
General knowledge the model hasAnswer directly. Retrieval would add cost and distractors
A lookup in your documentsThe standard pipeline
Counts, totals, trendsA database query (section 16.7)
Clearly about one collectionThat collection’s index: separate indexes for policies, engineering and contracts beat one merged index
Multi-step or open-ended researchThe agentic path (section 16.6)

A router is a small classifier: a cheap model with schema-enforced output (section 11.4) that returns a route and a confidence, or plain rules for the obvious cases. It is also the cost structure of the system, since the direct and standard paths carry most traffic and the expensive ones are reserved for the questions that need them.

It is also a new point of failure. A misrouted question fails in a way nothing downstream can repair, so the router gets its own labeled examples and its own accuracy number, like any classifier.

Common take“Our RAG gives wrong numbers for analytics questions. We’ll tune retrieval.”

Sharper take“Retrieving five chunks can’t count across a collection. That question belongs on a different path, so the fix is a route to a query tool, and a test set for the router.”

16.6Agentic retrieval

Search inside a loop, for the questions that need it.

Take the function-calling loop of section 11.5 and make search the tool. The model reads the question, issues a search, reads the results, decides whether it has enough, and searches again if not. It can follow a lead, fill a gap, or check a claim, none of which a single retrieval step can do.

This is the right tool for a narrow set of questions: those that need several pieces of evidence found one after another, where what to look for next depends on what was just found. It is the wrong default. Each turn of the loop is a model call, so a five-step search costs roughly five times the latency and tokens of a single-step answer, and a loop can wander, repeat itself or stop early. Most questions in most products are single lookups.

The engineering that makes it safe is the same as for any agent (Part 5): a limit on steps, a budget in tokens, a record of every search issued, and the routing of section 16.5 in front, so that only questions that need the loop get it.

Common take“Agentic RAG is the modern approach, so we’ll make everything agentic.”

Sharper take“A loop is for questions where the next search depends on the last result. For a single lookup it multiplies cost and latency and adds ways to fail. I route to it; I don’t default to it.”

16.7Graphs, databases and the web

Knowledge graphs, databases and the web.

Knowledge graphs. “What are the main themes across these ten thousand support tickets?” has no answer in any five chunks. GraphRAG addresses such global questions at ingest time: a language model reads the collection, extracts entities and the relationships between them, groups related entities into communities, and writes a summary of each. Global questions are then answered from the summaries. The price is an expensive indexing pass that must be repeated as the collection changes, so it suits collections that are stable and questions that truly span them.

Databases. For counts, totals and comparisons, the model writes a query and a database runs it. Doing this well takes four pieces.

  • Schema linking. Show the model only the tables and columns relevant to the question, with descriptions and a few example values. A full schema of hundreds of tables buries the ones that matter.
  • Read-only execution. Run generated queries as a database user that can only read, with a time limit and a row limit. The model’s output is untrusted input to your database.
  • Result checks. An empty result, a single absurd number or a failed query should lead to a retry with the error, or to an honest “I couldn’t compute that”.
  • Showing the work. Return the query alongside the answer. A wrong join gives a confident, well-formatted, wrong number, and the query is the only thing a person can audit.

The web. A search engine is a retrieval source too, for questions about recent or public information. It brings freshness and coverage that no private index has, and two hazards: quality varies widely, and web pages are untrusted text that may contain instructions aimed at your model (Chapter 26). Cite sources, prefer primary ones, and treat fetched content strictly as material to read.

Common take“We’ll put the database rows into the vector index so the model can answer questions about them.”

Sharper take“Rows in a vector index can be found, not counted. For totals and trends I have the model write a read-only query, I check the result, and I show the query with the answer.”

16.8Visual documents

Retrieve the page image when the layout carries the meaning.

Section 15.2 showed how much is lost when tables, charts and multi-column pages are converted to text. A newer approach skips the conversion. In systems such as ColPali, a vision-language model embeds an image of each page directly, producing many vectors per page in the late-interaction style of section 14.4. A query is matched against page images, and the retrieved pages are handed to a vision model to read (Chapter 12).

The appeal is that nothing is parsed, so nothing is mangled: a table stays a table and a chart stays a chart. The costs are storage, since each page has many vectors, and the price and resolution limits of reading page images at answer time (sections 12.3 and 12.4). It is a good fit for collections where layout is the content, such as financial reports, slide decks and scanned forms, and unnecessary for clean prose.

Common take“We need a better PDF parser for these financial reports.”

Sharper take“For pages where the layout is the meaning, I can retrieve the page image itself and let a vision model read it. I’d compare that with the best parser on the same labeled questions.”

16.9The RAG triad

Three scores that locate a failure.

A single quality score for a RAG system says that something is wrong and not where. Three narrower scores, each judged separately, do better.

ScoreComparesA low score points to
Context relevanceThe retrieved chunks against the questionRetrieval: wrong or noisy chunks
GroundednessThe answer against the retrieved chunksGeneration: claims the context does not support
Answer relevanceThe answer against the questionEither: the answer is beside the point
QuestionRetrieved contextAnswerContext relevancelow: look at retrievalGroundednesslow: look at generationAnswer relevancelow: either side
Figure 16.5 Each score judges one edge of the triangle, so a drop in one of them says which side of the pipeline to open first.

This is section 15.6 turned into measurement. Each score is usually produced by a language model acting as a judge, which has to be checked against human judgment before it is trusted (Chapter 23). The retrieval metrics of section 14.10 remain the cheapest and most reliable of all, because they need no judge.

Common take“Our RAG quality score went from 3.8 to 3.6.”

Sharper take“I track three scores. If context relevance fell, I look at retrieval. If groundedness fell, I look at the prompt and the model. One blended number wouldn’t tell me which.”

16.10Retrieval, long context or fine-tuning

Retrieval, a long context, or fine-tuning.

RetrievalEverything in a long contextFine-tuning
Best forLarge or changing bodies of knowledgeA small, stable body of knowledgeBehavior: format, tone, a narrow skill
Size limitNone in practiceThe context window, and attention within itNot a way to store facts (Chapter 9)
UpdatingRe-ingest the documentEdit the promptRetrain
CitationsYes, to retrieved passagesPossible, to parts of the promptNo
Cost per questionLow: a few chunksHigh unless the prefix is cachedLow: a short prompt
Main riskThe right passage is not retrievedDetail lost in the middle of a long promptConfident answers from memorized patterns

The three combine more often than they compete. A common production design is a small fine-tuned model, for format and tone, answering over retrieved passages, for facts. And a long context is the right first version of many systems: if the knowledge fits, put it in the prompt, cache it, and add retrieval when it stops fitting.

Is the gap behavior: format, tone, a narrow skill?yesfine-tune (Chapter 17)noIs the knowledge small, stable, and cacheable as aprefix?yesput it all in the contextnoRetrievalfor large or changing knowledge, with citations; often paired with a fine-tuned model for format and tone
Figure 16.6 The table as a decision. Facts go in the context, by retrieval or by including them whole; behavior goes in the weights.

Common take“Context windows are huge now, so RAG is dead.”

Sharper take“If the knowledge fits in the window, I put it there and cache it. When it doesn’t fit, changes daily, or must be filtered by permission, I retrieve. The choice follows from the size and churn of the data.”

Key takeaways

  • Advanced RAG is a parts catalog indexed by failure. Add the one part that targets a measured failure, compare before and after, and stop.
  • Reranking lets you retrieve widely for recall and send narrowly for precision. It reorders candidates; it cannot add one.
  • The gap between ranking the right passage first (70%) and having it in the top hundred (97%) is the room a reranker has.
  • Parent-document retrieval gained twelve points with embeddings and lost seven with keyword search. A pattern helps only where its mechanism applies.
  • Rewrite chat follow-ups into standalone queries. Use paraphrases for vocabulary mismatch, and hypothetical answers only where the model knows the domain.
  • Route before retrieving: counts and trends go to a database, general knowledge goes straight to the model.
  • Agentic retrieval is for questions where the next search depends on the last result. It multiplies cost and latency.
  • Generated database queries run read-only, with limits, and are shown with the answer.
  • For layout-heavy documents, page images can be retrieved directly and read by a vision model.
  • If the knowledge fits in the context window, start there and add retrieval when it stops fitting.

Check your understanding

  1. Your system retrieves 20 chunks and answers from all of them. On your labeled set, the right chunk is among the 20 for 93% of questions, yet answers are right only 71% of the time, and the wrong answers often quote a passage that is similar to the right one. Name the failure and design the fix.

    Answer outline

    Recall is fine; precision is the problem. This is distractor pull, possibly with the right chunk lost in the middle of a long context. Fix: keep retrieving widely, add a reranker over the candidates, and send only the top few, placed first. Measure three things separately: recall in the candidates entering the reranker, the rank of the right chunk after it, and answer accuracy. Check that the reranker suits the domain. Do not change the embedding model: the right chunk is already being found.

  2. A colleague read that parent-document retrieval improves RAG and wants to switch your keyword-search system to index sentences and return paragraphs. Using the experiment in section 16.3, say what you expect and what you would do first.

    Answer outline

    The pattern fixes diluted embeddings of long chunks. Keyword search does not have that problem; it benefits from more matching words, and in the experiment it lost seven points when switched to sentences, while the embedding search gained twelve. So expect no gain and a possible loss for a keyword system. First run both configurations on the labeled set. If the system is hybrid, apply the pattern to the embedding side only and keep keyword search on paragraphs.

  3. Sales staff ask your assistant questions such as “which region had the most renewals last quarter?” The current pipeline retrieves five account notes and produces a confident, wrong answer. Design the path this question should take, including what protects the database.

    Answer outline

    This is an aggregation question, and no five chunks contain the answer. A router should classify it and send it to a database path: give the model the relevant tables and columns with descriptions and example values, have it write a query, run the query as a read-only user with a time limit and a row limit, check that the result is not empty or absurd, and answer with the figures and the query itself. Evaluate by whether generated queries return the same results as reference queries. Give the router its own labeled examples, since a misrouted question fails silently.

Further reading

  • Chip Huyen, AI Engineering, chapter 6: retrieval optimization, including reranking and query rewriting, and agents that use retrieval.
  • Edge et al. (2024), “From Local to Global: A Graph RAG Approach to Query-Focused Summarization”: the GraphRAG paper.
  • Faysse et al. (2024), “ColPali: Efficient Document Retrieval with Vision Language Models”: retrieval over page images.
  • Anthropic, “Introducing Contextual Retrieval”: measured gains from contextual chunks, hybrid search and reranking, stage by stage.

↑↓ to move↵ to openesc to close