Skip to content

Chapter 3 · Advanced RAG


3.1 From Naive to Advanced RAG ★

Stage Problem with naive RAG Techniques Section
Before retrieval (the query) The user's question is a poor search query: vague, conversational, multi-part, or worded unlike the documents Query rewriting, HyDE, decomposition, multi-query 3.2
Retrieval (one shot) A single retrieval can't follow a chain of facts Iterative and multi-hop retrieval (IRCoT) 3.3
Index structure Flat chunks can't answer questions about the corpus as a whole GraphRAG, hierarchical summaries 3.4
After retrieval (the context) Too many chunks, noisy, badly ordered Reranking, deduplication, compression, reordering 3.5
Architecture Do we need retrieval at all, or just a long context? Long context vs RAG, hybrids 3.6
Data type The facts live in tables and databases, not prose Table handling, text-to-SQL, routing 3.7

The standard pipeline from Chapter 1 (retrieve the top-k once using the original question, put them in the prompt, generate) is often called naive RAG. The survey by Gao et al. (2023) groups later improvements into three stages: Naive RAG, Advanced RAG and Modular RAG. Advanced RAG keeps the "retrieve, then generate" backbone and optimizes the query before retrieval and the context after retrieval; Modular RAG goes further and breaks the pipeline into freely composable modules, adding routing, iteration, multiple data sources and so on.

This chapter follows the order of the table above, covering the typical problem at each stage of naive RAG and the techniques that address it. Two related topics are not expanded here: when to retrieve and how much (for example, skipping retrieval when the model already knows the answer) is in Chapter 4; letting the model act as an agent that decides for itself what to search and how many times, and training that ability with reinforcement learning, is in Chapter 6.

Interview questions

  • ★ What problems does naive RAG have, and at which stages does advanced RAG improve it?

3.2 Query-Side Techniques ★★

The user's question is written for people, not for a retriever. It may depend on the chat history ("And how much does it cost?"), contain small talk and irrelevant details, ask several things at once, or be worded very differently from the documents (the query–document asymmetry from Chapter 2). The ceiling on retrieval quality is largely set by the query, so "fixing" the query before retrieval is often the most cost-effective improvement. The four techniques below each target a different problem.

Query rewriting ★★

The most common, and most necessary, rewrite is turning a question from a multi-turn conversation into a standalone question. A user first asks "What's the battery capacity of the iPhone 16 Pro?" and then "And how much does it cost?" Searched on its own, the second question has no idea what "it" refers to, so the results are bound to be wrong. The rewrite hands the chat history and the current question to an LLM and asks it to produce a self-contained, searchable question: "What is the price of the iPhone 16 Pro?" In conversational RAG products this step is practically mandatory.

Another kind of rewrite is cleaning and expansion: drop pleasantries like "Hi, I was wondering if maybe you could…"; fix typos; expand abbreviations ("k8s" → "Kubernetes"); and add synonyms or key terms to help BM25 match. There is also step-back prompting (Zheng et al. 2023): for a very specific question, first have the model pose a more abstract "step back" question, for example turning "What is the pressure of an ideal gas if its temperature doubles and its volume halves?" into "What is the ideal gas law?", retrieve the underlying principles with it, and then answer the original question.

Rewriting can also be trained. Rewrite-Retrieve-Read (Ma et al. 2023) uses a small model as the rewriter, warms it up on supervised data, and then trains it with reinforcement learning, where the reward comes from whether the downstream LLM answers correctly after reading the retrieved results. The motivation: a query that people consider "well written" isn't necessarily the one that makes the retriever find the right documents.

The cost of rewriting is an extra LLM call, usually adding a few hundred milliseconds of latency. Another risk is intent drift: the model may misread the question while rewriting, or slip in assumptions (for example, rewriting "the latest version" as a specific version number it believes is latest but is actually outdated). A common safeguard is to retrieve with both the original and the rewritten question and merge the results.

Interview questions

  • ★★ In multi-turn conversational RAG, what processing is needed before retrieval?
  • ★ What are the risks of query rewriting, and how can they be mitigated?

HyDE ★★

\[\hat{\mathbf{v}}_q = \frac{1}{N + 1}\left[\sum_{k=1}^{N} f(\hat{d}_k) + f(q)\right], \qquad \hat{d}_k \sim \mathrm{LLM}(\cdot \mid \text{instruction}, q)\]

HyDE (Hypothetical Document Embeddings, Gao et al. 2022) is counterintuitive: before retrieving anything, have an LLM write a hypothetical answer document \(\hat{d}\) for the question, factual errors and all; then encode this fake document with an encoder \(f\) and use that vector to find the most similar documents in the real corpus. In the formula, \(q\) is the original question, \(\hat{d}_1, \dots, \hat{d}_N\) are \(N\) hypothetical documents sampled from the LLM, and the final search vector \(\hat{\mathbf{v}}_q\) is the average of their vectors and the question's own vector. The original paper used InstructGPT to generate the fake documents and the fully unsupervised Contriever as the encoder.

Why does this help? First, it sidesteps the query–document asymmetry from Chapter 2. A question and its answer look very different, but a fake document that "looks like an answer" is very close to real answer documents in wording, sentence structure and terminology, so "question finds answer" becomes "document finds document", which even unsupervised encoders handle well. Second, factual errors in the fake document matter little. When the encoder squeezes a passage into one vector, it mainly keeps the topic, the terminology and the overall semantic pattern; a wrong number barely moves the vector. The paper describes this as the encoder's "dense bottleneck" filtering out hallucinated details: a real document isn't excluded just because the fake one got a year wrong. Third, it is fully zero-shot and needs no relevance labels. The paper reports that HyDE clearly outperforms Contriever alone and is comparable to fine-tuned retrievers across tasks such as web search, QA and fact verification, and across several languages.

HyDE also has clear limits. First, it's slow: generating a passage of a few hundred words takes much longer than rewriting a question, and it sits on the critical path of every query. Second, it depends on the LLM knowing the domain: if the question is about a company's internal systems or newly coined terms, the LLM has no idea what the answer looks like, and the fake document may be completely off-topic, steering retrieval the wrong way. Third, it can amplify the model's prior biases: if the LLM holds a common misconception about a question, the fake document will be written accordingly, and the retrieved documents are more likely to support that misconception. Fourth, it doesn't help with exact-match lookups such as IDs and model numbers. Also, the stronger the retriever already is (say, trained with supervision in the relevant domain), the smaller HyDE's gain. A related idea is Query2doc (Wang et al. 2023), which concatenates the pseudo-document with the original question as the new query; this also expands the vocabulary for sparse retrieval such as BM25.

Interview questions

  • ★★ How does HyDE work, and why don't errors in the fake document matter?
  • ★★ When does HyDE fail?

Query decomposition ★★

Some questions contain several parts. Comparisons: "Which phone has longer battery life, A or B?" Multi-aspect: "What are the definition, advantages and limits of RAG?" Multi-hop: "Where was the director of Inception born?" Encoding the whole question into one vector gives a blend of the sub-questions' meanings, and the retrieved top-k often covers only part of it, for example only documents about phone A and none about phone B.

Query decomposition has an LLM split the complex question into a few simple sub-questions, retrieve for each, and finally combine the sub-results into an answer. There are two modes. One is parallel: the sub-questions are independent, such as "What is A's battery life?" and "What is B's battery life?", and can be retrieved at the same time. The other is sequential: a later sub-question depends on an earlier answer; you have to find "the director of Inception is Nolan" before you can ask "Where was Nolan born?" Sequential decomposition is essentially the iterative retrieval of the next section; least-to-most prompting (Zhou et al. 2022) and Self-Ask (Press et al. 2022) are prompting methods of this "answer the easy sub-question first, then use its answer to move on" kind.

The cost is an extra LLM call for decomposition, more retrievals as the number of sub-questions grows, and a final synthesis step. Decomposition itself can go wrong: a bad split, a missing key sub-question, or a simple question chopped into needlessly fine pieces. So it suits clear comparison, multi-aspect and multi-hop questions, while simple questions should just be retrieved directly (methods for judging question complexity and choosing a strategy are in Chapter 4).

Interview questions

  • ★ When is query decomposition needed, and how do parallel and sequential decomposition differ?

Multi-query ★

Multi-query has an LLM rephrase the same question several ways (usually 3 to 5), for example "How do I make a Python program run faster?", "Python performance optimization methods" and "How to reduce the running time of Python code", retrieves for each phrasing, and merges the results: the simple way is a deduplicated union, and the more common way is RRF fusion (see Chapter 2), a combination sometimes called RAG-Fusion.

The motivation: embeddings are quite sensitive to wording, so the same meaning phrased differently can retrieve very different neighbors, and we don't know in advance which phrasing the document authors used. Each phrasing covers a different neighborhood in vector space, so together they give higher recall. RRF also rewards documents that "several phrasings all retrieve", which makes the result more robust. Note the difference from decomposition: multi-query is different wordings of the same question, while decomposition is different sub-questions.

The cost is N times the retrievals (retrieval itself is cheap and can run in parallel; the main cost is the LLM call that writes the variants); more candidates also means more noise, so it's usually paired with a reranker; and the variants can drift from the original meaning and pull in irrelevant documents.

Interview questions

  • ★ How does multi-query differ from decomposition, and why does it improve recall?

Extracting filters from the query ★

Many questions carry hard constraints: "Which financial reports from 2023 onward mention layoffs?", "store policies for the East China region", "API docs for version 2.0". Semantic retrieval is bad at such constraints: "2023" and "2021" sit very close together in vector space, the embedding can't tell them apart, and the results may well be 2021 reports. Yet these constraints usually exist as ready-made metadata fields (date, region, version).

So a very practical approach (sometimes called self-query) has an LLM first split the question into two parts: a semantic query ("financial reports mentioning layoffs") and a structured filter (year >= 2023), the latter output in a fixed format based on the metadata field definitions. Retrieval first filters exactly on the conditions, then runs semantic search over what remains. This hands "fuzzy semantic matching" and "exact condition filtering" to the tools that are good at each. The risk is a wrongly extracted filter (a misspelled field name, "last year" converted to the wrong year), which directly filters out the right answer or even returns nothing; so validate that the extracted fields and values are legal, and fall back to unfiltered retrieval when filtering leaves too few results.

Interview questions

  • ★ How should retrieval handle hard constraints like dates or versions in the user's question?

Comparing query-side techniques ★

Technique Problem it targets Extra cost Main risk
Query rewriting Conversational, vague or noisy questions One short LLM call Intent drift, injected assumptions
HyDE Query–document asymmetry; no labeled data for the retriever One longer LLM generation Off-topic fake documents in unfamiliar domains; amplified biases
Decomposition Comparison, multi-aspect and multi-hop questions LLM call + one retrieval per sub-question + synthesis Bad splits, missing sub-questions
Multi-query Sensitivity to wording; low recall LLM call + N retrievals More noise; variants drift from the original meaning
Filter extraction Hard constraints (dates, versions, regions) that embeddings can't enforce One short LLM call Wrong filters remove the right answer

These techniques aren't mutually exclusive and can be stacked as needed: rewrite a conversational question into a standalone one, extract filters, then decompose complex questions or generate several phrasings. But every extra step adds an LLM call and another chance to go wrong, so apply them selectively by question type and verify with retrieval metrics on your own data that each step actually helps, rather than piling them all on.

Interview questions

  • ★★ What can be done to the query before retrieval, and what problem does each technique solve?

3.3 Multi-Hop and Iterative Retrieval ★★

Why one retrieval isn't enough ★★

Many questions can only be answered by chaining several facts; these are multi-hop questions. Take "Where was the director of Inception born?": the first hop finds that the director is Christopher Nolan, and the second hop finds that Nolan was born in London. The problem is that the document needed for the second hop ("Nolan was born in London…") has almost nothing in common with the original question: the word "Nolan" never appears in it, so retrieving with the original question is unlikely to rank that document near the top. The bridge entity linking the two hops is only known after reading the first hop's document. Datasets such as HotpotQA (Yang et al. 2018), 2WikiMultihopQA and MuSiQue are designed to test exactly this ability.

So retrieval for multi-hop questions has to happen over several rounds, with each round's query built from what has been read so far. (Why fixed pipelines can't handle these questions, and fully agent-driven approaches, are covered in Chapter 6.)

Interview questions

  • ★★ Why are multi-hop questions hard to solve with a single retrieval?

Iterative retrieval ★

The basic loop of iterative retrieval is: retrieve → generate → build a new query from what was generated → retrieve again, and so on. The key is that the generated text contains information that wasn't known before retrieval (such as the bridge entity), so using it as the next query finds documents the original question couldn't.

Methods differ in "what is generated each round and what is used as the query". Iter-RetGen (Shao et al. 2023) generates a complete answer in every round and uses "the original question + this round's answer" as the next query: even an imperfect answer mentions relevant entities and terms that help the next retrieval, and better retrieval in turn helps generate a better answer, so the two reinforce each other. IRCoT, below, is finer-grained, retrieving after every sentence of reasoning. (There were also earlier specially trained multi-hop dense retrievers such as MDR, which concatenate the question with the first-hop passage as the second-hop query.)

Interview questions

  • ★ What is the basic loop of iterative retrieval, and why does retrieving with generated text find documents the original question can't?

IRCoT ★★

P ← Retrieve(q, K)                          # initial retrieval with the question
CoT ← []
repeat:
    s ← LLM(q, P, CoT)                      # generate the next reasoning sentence
    CoT.append(s)
    if "answer is" in s or steps ≥ max: break
    P ← P ∪ Retrieve(s, K)                  # use the new sentence as the next query
answer ← extract from CoT (or a reader reads q and P)

IRCoT (Interleaving Retrieval with Chain-of-Thought, Trivedi et al. 2022) alternates retrieval with chain-of-thought (CoT) reasoning. The first step retrieves \(K\) paragraphs with the original question. Then a loop begins: the LLM reads the question, all paragraphs collected so far and the reasoning written so far, and generates only the next sentence of reasoning; that sentence is then used as a query to retrieve \(K\) more paragraphs, which are added to the set. This continues until a sentence contains "the answer is…" or the step limit is hit; the answer is then taken from the reasoning, or a reader answers from all the collected paragraphs.

The benefit runs both ways. On one hand, reasoning guides retrieval: when the model writes "The director of Inception is Christopher Nolan", the bridge entity "Nolan" appears, and retrieving with that sentence naturally finds Nolan's birthplace. On the other hand, retrieval constrains reasoning: each reasoning step sees newly retrieved facts instead of making things up from memory, so factual errors (hallucinations) in the CoT drop noticeably. On four datasets, HotpotQA, 2WikiMultihopQA, MuSiQue and IIRC, the paper reports that with GPT-3, retrieval improves by up to about 21 points and QA by up to about 15 points; similar gains hold out of distribution and with small models such as Flan-T5, without extra training.

The costs are just as clear. First, it's slow and expensive: every reasoning sentence costs an LLM call plus a retrieval, so latency is several times that of single-shot RAG. Second, error propagation: if one reasoning sentence is wrong (say, it names the wrong director), it retrieves wrong documents, and later reasoning drifts further from the truth. Third, when to stop relies on heuristics ("the answer is" appears, or the step limit), which aren't always reliable, and the context grows as paragraphs pile up, so it needs a cap. Fourth, it's pure waste on simple questions. So in practice you first decide whether a question needs multi-step retrieval at all (Adaptive-RAG in Chapter 4 chooses among no retrieval, single-step and multi-step by question complexity), or retrieve only when the model is uncertain (e.g. FLARE, also in Chapter 4). Going one step further, letting the model decide at each step whether to search, read or answer, and training that with reinforcement learning, is the agentic RAG of Chapter 6.

Interview questions

  • ★★ How does IRCoT interleave retrieval with reasoning, and why does it work?
  • ★ What are the costs and risks of iterative retrieval?

3.4 GraphRAG ★★

Local vs global questions ★★

Ordinary vector RAG is good at local questions, where the answer sits in one or two chunks, such as "What is this product's warranty period?" But there is a kind of question it handles very poorly: "Across these hundreds of user interviews, what are people mainly complaining about?" or "What are the main themes in this dataset?" These are global "sensemaking" questions: the answer isn't in any single chunk but requires generalizing and aggregating over the entire corpus.

Why does vector RAG fail? Because top-k retrieval returns the \(k\) chunks whose wording is most similar to the question. For "What are the main themes?", the chunks with similar wording are essentially a few random passages that can't represent the corpus, and there's no way to count "which kind of complaint comes up most". Stuffing the whole corpus into the context doesn't work either: millions of tokens often exceed the context window, and even when they fit, the model misses much of the content in the middle (see 3.5). This is essentially query-focused summarization over a large corpus.

Interview questions

  • ★★ What is a global question, and why does ordinary vector RAG answer it poorly?

Indexing: entity graph and community summaries ★★

chunks → LLM extracts entities, relationships, claims → merge into a knowledge graph
       → hierarchical community detection (Leiden) → LLM writes a summary for every community (bottom-up)

The core idea of GraphRAG (Edge et al. 2024) is to process the entire corpus into a hierarchical summary structure before any question arrives. Indexing has several steps:

  1. Chunk. Split the source documents into chunks (600 tokens each in the paper, with 100-token overlaps).
  2. Extract graph elements with an LLM. For each chunk, call an LLM to extract entities (name, type, description), relationships between entities (source, target, description, strength), and claims, i.e. verifiable factual statements about entities such as dates and events.
  3. Merge into a graph. The same entity extracted from different chunks is merged into one node, relationships become edges, and a relationship seen multiple times gets a higher edge weight. Information about the same entity scattered across many documents is thereby gathered in one place.
  4. Detect communities. Run the Leiden algorithm for hierarchical community detection: first split the graph into a few large communities, then recursively split each into smaller sub-communities. Each level is a complete partition of all nodes. A community is a group of tightly connected entities, roughly corresponding to a "theme" in the corpus.
  5. Write community summaries. Use an LLM to write a report-style summary for every community. Leaf communities are summarized directly from the descriptions of their entities, relationships and claims; for higher-level communities whose content won't fit, sub-community summaries replace the raw descriptions. So the summaries are generated bottom-up, level by level, becoming more general toward the top.

Interview questions

  • ★★ How is the GraphRAG index built, and how are the community summaries produced?

Global search: map-reduce ★★

To answer a global question, first pick a community level, then run map-reduce. In the map step, the summaries of all communities at that level are shuffled and split into batches, and the LLM writes an intermediate answer to the question from each batch in parallel, along with a 0–100 "helpfulness" score; answers scoring 0 are discarded. In the reduce step, the remaining intermediate answers are sorted by score from high to low, as many as fit are put into the context, and the LLM combines them into the final global answer.

Why does this answer global questions? First, the community summaries are query-independent and precomputed, so a "map" covering the whole corpus exists before any question is asked. Every part of the corpus appears in the map step through some community, unlike top-k, which only sees a few passages with similar wording. Second, communities roughly correspond to themes, so the reduce step naturally organizes the answer by theme, making it more comprehensive and diverse. Third, the hierarchy provides a cost–quality knob: top-level summaries are cheap but general, lower-level ones detailed but expensive. Fourth, the graph links information about the same entity across different documents, surfacing cross-document connections.

The paper used an LLM as a judge for head-to-head comparisons on a podcast-transcript dataset of about 1 million tokens and a news dataset of about 1.7 million tokens. Global GraphRAG beat vector RAG on comprehensiveness with win rates of about 72% to 83% and on diversity with about 62% to 82%, while vector RAG won on directness, a control metric (directness naturally trades off against comprehensiveness and diversity). Even using only the top-level community summaries, each query needed over 97% fewer tokens than map-reduce summarization over the source text, while still outperforming vector RAG.

Interview questions

  • ★★ How does GraphRAG's global search (map-reduce) work?
  • ★★ Why can GraphRAG answer global questions, and what role do community summaries play?

Global search's map-reduce reads a whole level of community summaries, which is both expensive and not detailed enough for questions about "a specific entity", such as "Which projects has Zhang San worked on, and with whom?" For these questions GraphRAG provides local search: use embeddings to find the few entities most related to the question, expand outward on the graph from them, collect the entities' descriptions, their relationships and neighboring entities, the summaries of the communities they belong to, and the source text chunks they were extracted from, rank all of this by importance to fill the context budget, and hand it to the LLM.

Compared with ordinary vector RAG, the benefit of local search is finding information by following the graph's structure: facts about Zhang San may be scattered across dozens of documents, and vector retrieval only finds the few passages worded most like the question, while the "Zhang San" node in the graph already gathered this information together at indexing time and can follow relationship edges to his collaborators. So a full GraphRAG system usually offers both kinds of search: global questions go through map-reduce, entity-centric questions through local search, and specific fact lookups can still be handled by ordinary vector retrieval.

Interview questions

  • ★ How do GraphRAG's local and global search differ, and which questions does each suit?

Costs and limits ★

GraphRAG's biggest problem is indexing cost: every chunk needs an LLM call to extract entities and relationships, and every community needs another to write its summary. Compared with a vector index that just runs an embedding model once, this costs several orders of magnitude more and gets very expensive for large corpora. Second, updates are hard: new documents change the graph's structure and communities, often requiring community detection and summaries to be redone, so incremental updates are difficult. Third, extraction quality: the LLM may miss entities or invent relationships, and wrongly merging different entities with the same name (or failing to merge different names for the same entity) pollutes the whole graph. Fourth, it has no advantage on local factual lookups: for a specific number, vector RAG is cheaper and more direct. Also, the paper's evaluation relies on an LLM judge and generated questions, and criteria such as "comprehensiveness" and "diversity" are somewhat subjective.

Much follow-up work lowers the cost or uses a different structure. LightRAG (Guo et al. 2024) combines graph retrieval with vector retrieval and supports incremental updates; LazyGraphRAG, later proposed by Microsoft, defers the expensive LLM summarization to query time, on demand; HippoRAG (Gutiérrez et al. 2024) runs Personalized PageRank over an entity graph for multi-hop retrieval; RAPTOR (Sarthi et al. 2024) builds no explicit entity graph but recursively clusters and summarizes chunks into a summary tree, relying on the same idea of hierarchical summaries.

Interview questions

  • ★ What are GraphRAG's drawbacks, and when shouldn't it be used?

3.5 Context Post-Processing ★★

The retrieved candidates aren't suitable for pasting into the prompt as is: there are too many, they contain duplicates and noise, and their order may be wrong. As Chapter 1 explained, noisy documents distract the model, and longer prompts cost more and take longer. So between retrieval and generation there is usually a context post-processing step: keep the best, remove duplicates, compress what's irrelevant, and put things in a good order.

Reranking, deduplication and diversity ★

\[\mathrm{MMR} = \arg\max_{d \in C \setminus S} \Big[\lambda \cdot \mathrm{sim}(d, q) - (1 - \lambda) \max_{d' \in S} \mathrm{sim}(d, d')\Big]\]

The first step is usually reranking: use a cross-encoder to rescore the top 50 or 100 candidates and keep only the best few (how this works is in Chapter 2). You can also set a score threshold and drop everything below it, preferring fewer documents over noisy ones; if every candidate falls below the threshold, that itself signals that "the knowledge base may not contain the answer".

The second step is deduplication and diversification. The top-k often contains nearly identical chunks: overlap from chunking, multiple versions of the same document, the same passage reposted on several web pages. They take up valuable slots without adding information. MMR (Maximal Marginal Relevance, Carbonell & Goldstein 1998) is the classic approach: greedily pick documents one at a time, each one relevant to the question but not too similar to those already picked. In the formula, \(C\) is the candidate set, \(S\) is the set already selected, the first term is relevance to the question \(q\), the second is the maximum similarity to the selected documents (redundancy), and \(\lambda\) balances the two: at \(\lambda = 1\) it reduces to ranking by relevance alone. For multi-aspect questions, diversity also improves coverage of the different aspects. The cost is that it may drop a useful chunk that merely resembles another relevant one.

Interview questions

  • ★ How does MMR balance relevance and diversity?

Context compression ★★

Even relevant chunks usually contain only a sentence or two that truly matter; the rest is background or unrelated content. Context compression shortens the context while keeping the useful information, giving shorter prompts, lower cost and latency, and less noise. Methods fall roughly into three groups:

  1. Extractive. Pick the sentences in the retrieved documents that are relevant to the question and drop the rest. RECOMP (Xu et al. 2023) trains an extractive compressor that learns to pick sentences "that help the language model answer correctly". The upside is that it introduces no new errors, since every output sentence comes from the source; the downside is a limited compression ratio, and it may cut away context needed for understanding.
  2. Abstractive. A (usually smaller) model writes a question-focused summary of the retrieved documents. RECOMP provides this kind of compressor too, and when the documents are irrelevant to the question, it can output an empty string, meaning "don't add retrieved content this time". The compression ratio is higher, but the summarizer may hallucinate or drop details.
  3. Token-level pruning. LLMLingua (Jiang et al. 2023) uses a small language model to estimate each token's information content: tokens the small model predicts easily (low perplexity) carry little information and can be deleted, while hard-to-predict tokens are kept. The paper reports compressing prompts by up to 20× on some tasks with little performance loss. The compressed text doesn't read fluently, but a large model can still understand it. LongLLMLingua (Jiang et al. 2023) builds on this by making compression aware of the question and reordering documents to ease the lost-in-the-middle problem described below.

(Another family compresses documents into a few continuous vectors (soft tokens) fed directly into the model; this gives the highest compression but requires training the model specifically.)

The core trade-off of compression: the compressor itself takes time, and it only pays off if the prefill time saved outweighs that; and the harder you compress, the greater the risk of losing key information. This risk is especially sharp for multi-hop questions: a sentence that seems unrelated to the question (say, "Nolan was born in London", when "Nolan" never appears in the question) may be exactly the link the reasoning chain needs, and compressing by relevance to the question can easily delete it.

Interview questions

  • ★★ What kinds of context compression are there, and what are their pros and cons?
  • ★ Why is context compression riskier for multi-hop questions?

Ordering and lost in the middle ★★

Lost in the middle (Liu et al. 2023) is one of the most cited phenomena in RAG: in multi-document QA, accuracy is highest when the document containing the answer is placed first or last and lowest when it's in the middle, a U-shaped curve; sometimes putting it in the middle is even worse than giving no documents at all. The experimental details and the causes are in LLM Basic Chapter 2, 2.8; here we only cover what it means for RAG. It shows that the same set of chunks can produce answers of different quality depending on how they are arranged, so the order used when building the prompt is itself something to design.

In practice, there are several things you can do:

  1. Put the most relevant at both ends. Since the reranker has already produced scores, place rank 1 first, rank 2 last, rank 3 second, rank 4 second to last, and so on, leaving the least relevant in the middle. The retrieval reordering proposed by Jin et al. (2024) follows this idea and needs no training.
  2. Include fewer. Reranking and compression reduce the number of documents, which shortens "the middle" itself.
  3. Put the question after the documents. This keeps the question right next to where the model starts generating; some setups place the question both before and after the documents.
  4. Preserve the original order. If several chunks come from the same document, arranging them in their original order rather than by relevance keeps the narrative coherent. OP-RAG (Yu et al. 2024) found this works better for long-document QA, and observed that answer quality first rises and then falls as the number of chunks grows, an inverted U. Whether to order by relevance or by original position depends on the task: scattered fact lookups suit the former, questions that need the flow of context suit the latter.
  5. Training. Fine-tune the model on data where the relevant information appears at random positions, so it learns to use the whole context evenly (see Chapter 7).

Interview questions

  • ★★ How does lost in the middle affect RAG? (the phenomenon itself: see LLM Basic Chapter 2)
  • ★★ In what order should retrieved documents go into the prompt?

3.6 Long Context vs RAG ★★

Long context (put everything in the prompt) RAG
Cost per query Grows with corpus size: every query pays to prefill the whole corpus (prompt caching helps when the same corpus is reused) Only \(k\) chunks; roughly constant
Latency Long prefill, high time-to-first-token Retrieval adds tens of milliseconds; short prompt
Corpus size Bounded by the context window (roughly \(10^5\)–\(10^6\) tokens) Practically unbounded (millions of documents)
Accuracy Sees everything; strong on synthesis and cross-document reasoning, but degrades with length and position Capped by retrieval recall: a miss means a wrong answer; strong on needle-style lookups
Noise Everything irrelevant is in the context too Filtered by retrieval and reranking, though near-miss distractors get in
Updates Just send the new documents Re-index changed documents
Access control and citations Hard to enforce per user; coarse citations Filter at retrieval time; chunk-level citations
Engineering Simple: no pipeline Chunking, embeddings, index and reranker to maintain

Strengths and weaknesses of each ★★

Once context windows grew from a few thousand tokens to hundreds of thousands or even millions, a common question became: if all the documents fit, do we still need RAG? The answer is that each has its own use cases, and they are often combined.

Cost and latency are long context's biggest weaknesses. Prefill compute grows at least linearly with length (the attention part grows quadratically), so reprocessing a million-token corpus on every query costs several orders of magnitude more, in both money and time-to-first-token, than processing a few thousand tokens of retrieved results. Prompt caching can reuse the KV cache of an identical prefix, greatly cutting cost when the same corpus is queried repeatedly, but the KV cache for a million tokens itself takes a huge amount of GPU memory, and it only hits when the prefix is exactly the same (see LLM Basic Chapter 6).

On accuracy, each wins sometimes. Long context's advantage is that the model sees everything, which suits questions that need synthesis across a whole document or reasoning across several documents, where RAG's chunking and retrieval would fragment the information. But long-context quality drops with length: there's often a gap between the context length a model claims and the length it can actually use effectively (findings from benchmarks such as RULER, see LLM Basic Chapter 2); lost in the middle still applies; and the more seemingly relevant distractors the context holds, the more easily the model is led astray (Jin et al. 2024). RAG's ceiling is set by retrieval recall: if retrieval misses, the answer is wrong.

Empirical results aren't one-sided. Xu et al. (2023) found that a 4K-context LLM with simple retrieval matched a fine-tuned model extended to a 16K context on long-context tasks, with far less compute, and that retrieval also helped models whose context had already been extended. Li et al. (2024) found, with the strongest long-context models of the time, that given enough resources long context consistently beat RAG on average, but RAG cost far less. OP-RAG (Yu et al. 2024), on the other hand, found that with the right number of chunks, RAG could reach higher answer quality than feeding in the whole document, using far fewer tokens.

Interview questions

  • ★★ As context windows keep growing, is RAG still necessary?
  • ★★ Compare long context and RAG in cost, latency and accuracy.

How to combine them ★★

In practice the best approach is often to combine the two:

  1. Routing: RAG first, long context if needed. Self-Route (Li et al. 2024) starts from an observation: for most questions (about 63% in the paper), RAG and long context give exactly the same answer, so there's no need to pay for long context every time. It works in two steps. First, the question and the top-k retrieved chunks (default \(k = 5\)) go to the model, with the instruction "if the query can't be answered from this text, output unanswerable"; if the model answers, that answer is used. Second, only for questions judged unanswerable, the full long context is given to the model to answer again. The "can I answer?" judgment is generated in the same call as the answer, so the routing itself adds almost no cost. The paper reports that most questions are settled in the first step, cutting computation cost by about 39% (GPT-4o) to 65% (Gemini-1.5-Pro), with average quality close to using long context for everything. It relies on the model recognizing fairly accurately that it can't answer; if the model answers anyway from irrelevant chunks, questions that should have been escalated stay at the RAG step (the same calibration problem discussed in Chapter 4).
  2. Use the long-context model as a stronger reader. Since the model can read longer inputs, retrieval doesn't have to return only a few small chunks; it can return more and larger units (whole sections or documents). LongRAG (Jiang et al. 2024) groups related Wikipedia documents into retrieval units of about 4K tokens, greatly reducing the number of units, so the retriever only needs to find a few units and a long-context reader handles the rest. This lightens the retriever's burden and reduces the fragmentation caused by chunking.
  3. Choose by scenario. A small, fixed corpus that is queried repeatedly (a contract, a product manual, a medium-sized codebase): put it straight into the context with prompt caching, which is simple and accurate. A large, frequently changing corpus that needs access control or precise citations (an enterprise knowledge base, web search): use RAG. For questions that need global synthesis, long context or methods like GraphRAG fit better; for specific fact lookups, RAG is cheaper and more precise.

Interview questions

  • ★★ When should you use long context directly, when RAG, and how can they be combined?
  • ★ How does Self-Route route between RAG and long context?

Cache-augmented generation ★

When a knowledge base is small enough to fit entirely in the context, there's an even more thorough option: Cache-Augmented Generation (CAG, Chan et al. 2024). At deployment time, all the documents are fed to the model once, and the KV cache for those documents is computed and saved; after that, each question is simply appended to this precomputed KV cache and generation continues, with no retrieval step at all. (How the KV cache works is in LLM Basic Chapter 1.)

The benefits: no retrieval latency, no "retrieval missed it" errors, and a much simpler system with no chunking, embeddings or index to maintain. The documents are prefilled only once, so afterwards each question costs mainly reading the cache and generating the answer. The costs and limits are just as clear: the knowledge base must be small enough to fit in the context window; the KV cache itself takes a lot of GPU memory or storage, growing more expensive with more documents; whenever the documents change, the cache must be recomputed; and the usual long-context problems (lost in the middle, distracting content) still apply. So CAG suits small, stable knowledge bases, such as a product manual or a fixed set of regulations, consistent with the "choose by scenario" conclusion above; once the knowledge base grows large or changes often, it's back to RAG.

Interview questions

  • ★ What is CAG, and which scenarios suit it versus RAG?

3.7 RAG over Structured Data ★

Tables ★

A lot of key business information lives in tables: financial reports, price lists, product specs, experimental results. Tables are unfriendly to the standard RAG pipeline. First, chunking breaks tables: split by length, a table ends up in several pieces, and the later pieces lose the header, so nobody knows what "128 in column 3" means. Second, tables embed poorly: rows of numbers carry almost no semantic signal, so for "Which product is the most expensive?", the chunks with similar wording are usually prose paragraphs rather than the price list. Third, questions over tables often need computation: sums, comparisons, sorting, filtering, which require seeing every row of the table, while top-k only returns a few pieces.

Common remedies: keep the table structure intact during parsing (convert it to Markdown or HTML) and make small tables a single chunk; split large tables by rows and repeat the header in every chunk; serialize each row into a sentence ("Product A's revenue in Q1 2024 was 120 million yuan") so embeddings match more easily; or use multi-representation indexing: have an LLM write a description of the table (what it's about, its columns, the period it covers), retrieve on the description, and once it's hit, hand the original table to the generator. When a table is large and the question needs computation, a better approach is to load the table into a database or DataFrame and have the model write SQL or code to compute the answer, rather than doing mental arithmetic in the prompt.

Interview questions

  • ★ What problems do tables cause in RAG, and how do you handle them?

Text-to-SQL ★

When the data already lives in a relational database, the most fitting "retrieval" is a SQL query. The text-to-SQL flow is: give the LLM the database schema (table names, column names, types, a few sample rows, descriptions of what columns mean) together with the user's question and have it generate SQL; execute the SQL and hand the results back to the LLM to answer in natural language. Compared with vector RAG, it can do exact aggregation, filtering and joins over all the data, for example "the three products with the highest return rate in East China last month", something that can never be computed from the top-k text chunks.

There are four main difficulties. First, schema linking: an enterprise database may have hundreds of tables and thousands of columns that can't all fit in the prompt, so the relevant tables and columns must be found first. This is itself a retrieval problem: index the table and column descriptions and past example queries, retrieve, then generate SQL. Second, ambiguity in business meaning: "active users" or "revenue" may be defined differently by different departments, so metric definitions need to be written down and given to the model. Third, silent errors: the SQL runs, but the logic is wrong (a missing filter, a join on the wrong table), and the result looks reasonable but is incorrect. Common mitigations are showing the generated SQL to the user, self-correcting on execution errors, and validating important queries. Fourth, security: use read-only accounts, enforce row-level permissions per user, limit query size, and guard against injection. Common benchmarks are Spider (Yu et al. 2018) and the more realistic BIRD (Li et al. 2023), whose databases are larger and whose data is "dirtier".

Interview questions

  • ★ When should you use text-to-SQL instead of vector retrieval, and what are its main difficulties?

Routing across data sources ★

In real systems, knowledge is often spread across several kinds of sources: unstructured documents suit vector or hybrid retrieval, structured business data suits SQL, and knowledge graphs with explicit entity relations suit graph query languages (such as Cypher or SPARQL). So many systems put a router at the front: rules or an LLM classifier decide which source (or sources) a question should go to. For example, "What is the return policy?" goes to the document store, "How many orders were returned last month?" goes to the database, and a question involving both queries both and merges the results into one answer. If routing is wrong, everything after it is wrong, so the router itself needs evaluation. Wrapping each data source as a tool and letting the model decide in a loop which one to call leads naturally to the agentic RAG of Chapter 6.

Interview questions

  • ★ How would you design a RAG system when knowledge is spread across documents and databases?