RAG II: Advanced Architectures
Reranking, query transforms, routing, GraphRAG and text-to-SQL.
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.7 | The part that addresses it |
|---|---|
| Distractor pull; lost in the middle | Reranking (section 16.2) |
| Orphaned chunks; the tension over chunk size | Parent-document retrieval (16.3) |
| Vocabulary mismatch; follow-up questions in a chat | Query rewriting and expansion (16.4) |
| Aggregation questions; mixed collections | Routing (16.5) and database queries (16.7) |
| Multi-part questions | Decomposition (16.4); agentic retrieval (16.6) |
| Questions about themes across the whole collection | Knowledge graphs (16.7) |
| Parsing rot in layout-heavy documents | Page-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.
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.
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 method | What is searched | Right paragraph first | In the first 3 | In the first 5 |
|---|---|---|---|---|
| Keyword search | Paragraphs | 70.2% | 83.3% | 86.8% |
| Keyword search | Sentences, returning their paragraphs | 63.1% | 75.4% | 80.2% |
| Keyword search | Sentences with the article title added, returning their paragraphs | 65% | 78.6% | 83.1% |
| Embeddings | Paragraphs | 32.9% | 45.7% | 52.8% |
| Embeddings | Sentences, returning their paragraphs | 45.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.
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.
| Transform | What it does | What it fixes | Cost and risk |
|---|---|---|---|
| Rewriting | Turns a follow-up into a standalone query: “what about Germany?” becomes “parental leave policy in Germany” | Chat follow-ups that mean nothing on their own | One small model call. Required in any conversational product |
| Multi-query | A small model writes three to five paraphrases; all are searched and the results fused by rank | Vocabulary mismatch: one phrasing lands in the document’s dialect | One model call and several searches in parallel. The safe default of the group |
| Decomposition | Splits “compare X with Y” into a query about X and a query about Y | Multi-part questions | One model call; sub-answers may depend on each other |
| Hypothetical answer | The model writes a plausible answer, and that is embedded and searched | Questions and documents are phrased differently; a fake answer looks like a real document | If 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.
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 question | Path |
|---|---|
| General knowledge the model has | Answer directly. Retrieval would add cost and distractors |
| A lookup in your documents | The standard pipeline |
| Counts, totals, trends | A database query (section 16.7) |
| Clearly about one collection | That collection’s index: separate indexes for policies, engineering and contracts beat one merged index |
| Multi-step or open-ended research | The 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.
| Score | Compares | A low score points to |
|---|---|---|
| Context relevance | The retrieved chunks against the question | Retrieval: wrong or noisy chunks |
| Groundedness | The answer against the retrieved chunks | Generation: claims the context does not support |
| Answer relevance | The answer against the question | Either: the answer is beside the point |
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.
| Retrieval | Everything in a long context | Fine-tuning | |
|---|---|---|---|
| Best for | Large or changing bodies of knowledge | A small, stable body of knowledge | Behavior: format, tone, a narrow skill |
| Size limit | None in practice | The context window, and attention within it | Not a way to store facts (Chapter 9) |
| Updating | Re-ingest the document | Edit the prompt | Retrain |
| Citations | Yes, to retrieved passages | Possible, to parts of the prompt | No |
| Cost per question | Low: a few chunks | High unless the prefix is cached | Low: a short prompt |
| Main risk | The right passage is not retrieved | Detail lost in the middle of a long prompt | Confident 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.
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
-
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.
-
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.
-
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.