AI ENGINEERING · RETRIEVAL AND RAG IN DEPTH · RETRIEVAL · 24 OF 35

Advanced RAG: Query Rewriting, Multi-Hop, GraphRAG

What to add when one search and one answer is not enough: query rewriting for follow-ups, multi-query expansion with a worked fusion, HyDE, multi-hop questions with iterative retrieval, routing to the right index or database, agentic RAG, knowledge graphs and GraphRAG, long context versus RAG with a worked token count, citations, abstaining when nothing fits, and what each addition costs.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
1 / 19

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Rewrite and expand
  • iterate for multi-hop
  • route or go agentic
  • graphs for relations
  • cite
  • say "not found"

Notes

Where basic RAG breaks

Basic RAG is one search and one answer. Embed the question, fetch the top five chunks, paste them into the prompt. It works for clear, single fact questions, and breaks when the question is a vague follow-up, when the answer needs two lookups in a row, when the facts live in a database, when someone asks about the whole collection, and when nothing relevant exists and the model guesses anyway. Let us fix each one.

Basic RAG falls short when
  • the question is a vague follow-up: "and that one?"
  • the answer needs two lookups in a row
  • the facts live in a database
  • it asks about the whole corpus
  • nothing relevant exists, and the model guesses anyway

The idea

Advanced RAG is a set of upgrades added at three points. Before retrieval, you fix the query and pick where to search. During retrieval, you search more than once, or let the model drive the searching. After retrieval, you ground the answer in sources and refuse when nothing fits. Every upgrade costs time and money, so add one only when a measured failure calls for it.

Three places to add work
  • before retrieval rewrite, expand, route
  • during retrieval search again, or let the model drive (agentic)
  • after retrieval cite sources, check support, abstain when nothing fits
  • each adds a call: add only what your evals prove

Query rewriting

The cheapest upgrade is query rewriting. In a chat, people ask follow-ups. First, does the Pro plan include single sign on. Then, and how much is it per seat. Searched alone, that second message is just the word it. A small fast model reads the recent history and rewrites it as a standalone query: Pro plan price per seat. Tell it to keep every id, name and date exactly, because a rewrite that drops a constraint quietly breaks retrieval.

Rewrite with the history
turn 1: Does the Pro plan
        include SSO?
turn 2: and how much is it
        per seat?

search turn 2 as typed
  → any pricing page at all
rewritten: "Pro plan price
  per seat" → the right page

keep ids, names, dates intact

Multi-query

Expansion goes further. Instead of one rewrite, the model writes several versions of the question, each from a different angle. Why is my export slow becomes export performance tips, large CSV export timeout, and export queue delays. Run all three searches in parallel and take the top ten from each: thirty hits. Remove duplicates, and maybe eighteen remain. Fuse with reciprocal rank fusion, rerank, keep five. One extra model call buys much better recall.

Multi-query, worked
question: why is my export slow?
q1 export performance tips
q2 large CSV export timeout
q3 export queue delays

3 queries × top 10 = 30 hits
duplicates removed → 18 unique
fuse with RRF, rerank, keep 5

the 3 searches run in parallel

HyDE

One more query trick, called HyDE, short for hypothetical document embeddings. Questions and answers are worded differently, so their vectors can sit apart. HyDE asks the model to write a plausible answer first, with no sources, then embeds that draft and searches with it. The draft reads like a real answer, so it lands near real answers. Then answer from what you found. It costs a full generation, and misleads on private topics.

HyDE in one beat
  • hypothetical document
  • embeddings: 1 model writes a plausible answer, with no sources
  • 2 embed that draft, not the question, and search
  • 3 discard the draft; answer from the real chunks
  • risk: a confident wrong draft on private or niche topics

Multi-hop questions

Some questions need two lookups in a row. Which team owns the service that caused incident forty four seventy one? No chunk says both. The incident report names the service, payments A P I, and a separate service catalogue names its owner. One search finds one half at best. You must search for the incident, read the result, and only then can you write the second query. That is a multi-hop question.

A two-hop question
Q: which team owns the service
   that caused incident 4471?

no single chunk holds both
hop 1: search "incident 4471"
   → root cause: payments-api
hop 2: "payments-api owner"
   → Ledger team

query 2 needs answer 1

Iterative retrieval

The fix is iterative retrieval. Search, then ask the model two things: do I have enough to answer, and if not, what should I search for next. Append the new results and go around again. Cap it at about three hops, because every hop adds a model call and a search, often one to three seconds. If the parts are independent, split the question up front and search them in parallel instead.

Iterative retrieval
context = []
query = question
for hop in 1..3:
  context += search(query)
  step = model(question, context)
  if step.enough: break
  query = step.next_query
return answer(question, context)

cap the hops: each adds ~1-3 s

Routing

A policy question should search the help docs. How many refunds did we issue last week is a database question, and searching documents will never add up numbers correctly. Questions about who depends on what suit a graph. And hi or thanks needs no search at all. A router picks the destination: simple rules, a small classifier, or a small fast model. When it is unsure, search two places and fuse the results.

Route by question type
  • policy, how-to → doc index
  • "how many", totals → SQL
  • who depends on what → graph
  • "hi", "thanks" → no search
  • router: rules, a classifier, or a small fast model
  • unsure? search two places and fuse, or ask the user

Agentic RAG

Agentic RAG takes this to its end. Instead of a fixed pipeline, give the model search tools, one per index, and let it decide whether to search, what to search for, which tool to use, and when it has enough. It handles follow-ups, multi-hop and routing in one design. The price: two to ten model calls, five to thirty seconds, and runs that differ. Use a fixed pipeline when questions look alike, an agent when they truly vary.

Agentic RAG
  • each index is a tool the model may call, as often as it needs, before answering
  • + follow-ups, multi-hop and routing in one design
  • 2 to 10 calls, ~5 to 30 s
  • runs differ; harder to test
  • cap steps and tokens

Knowledge graphs

Some questions are about relationships, not passages. What breaks if the auth service goes down? The answer is scattered across fifty design docs. A knowledge graph stores those facts as entities and edges: checkout depends on auth, billing depends on auth, auth is owned by the identity team. A model extracts these from every chunk at indexing time. At question time you walk the edges and get checkout and billing, which top five search would likely miss.

Triples, extracted at index time
a model reads each chunk and
extracts (entity, relation, entity)

(checkout) depends_on (auth)
(billing)  depends_on (auth)
(auth)     owned_by   (Identity)

Q: what breaks if auth is down?
follow depends_on backwards
→ checkout, billing

GraphRAG

What are the main themes across two thousand incident reports? Top five retrieval sees maybe five reports, so it cannot answer. GraphRAG handles these global questions. At indexing time it builds the graph, groups closely linked entities into communities, and has a model summarise each one. At query time it drafts a partial answer from each summary, then merges them. Indexing is expensive, and must be refreshed as data changes.

GraphRAG for global questions
  • Q: main themes across 2,000 incident reports?
  • top 5 chunks see ~5 reports
  • index: extract the graph, cluster it into communities, summarise each community
  • query: partial answer from each summary, then merge
  • cost: many model calls per chunk

Long context or RAG

Models now read hundreds of thousands of tokens, so why not paste in everything? Sometimes you should. A two hundred page manual is about a hundred thousand tokens. If a few people ask questions that need the whole document, stuffing it in is simple, and prompt caching cuts the repeat cost. But RAG with five chunks sends two and a half thousand tokens, about forty times fewer. And facts in the middle of very long prompts get missed more often.

Stuff it all in, or retrieve?
manual: 200 pages × ~500 tok
        = ~100,000 tokens
stuff it in: ~100k tok per Q
RAG top 5:   5 × 500 = 2,500
→ ~40× fewer tokens per question

stuffing works: it fits, few
  questions, needs whole doc
RAG wins: corpus too big, many
  users, permissions, freshness

Citations

Grounding means the answer comes from the retrieved text, checkably. Number each chunk in the prompt, one to five, and tell the model to answer only from the sources and cite the number after every claim. Then verify in code. Every cited number must exist, and a small model or a simple overlap check can confirm each sentence is supported by its source. Shown as links, citations build trust and make wrong answers easy to spot.

A grounded answer
prompt: sources numbered [1]-[5]
"answer only from the sources;
 cite [n] after each claim"

output: Pro costs 12 USD per
  seat per month [2]. SSO is
  included [4].

check: every [n] exists; a small
  model confirms each claim is
  supported by its source

Say "not found"

The last upgrade is knowing when to stop. Hand a model five weak chunks and it still answers, confidently and wrongly. So check the reranker scores. If the best is below a threshold you tuned on labelled questions, say zero point three, skip generation and reply that the docs do not cover it, with a way to reach a person. Also tell the model in the prompt to say so when the sources do not answer the question.

Abstain on purpose
rerank scores: 0.08, 0.05, 0.03
threshold (tuned): 0.30
→ skip generation, reply:
  "I could not find this in the
   docs. Contact support?"

and in the prompt: if the
sources do not answer it, say so

an honest "not found" beats
a confident wrong answer

Numbers worth knowing

Numbers worth knowing, all rough. A small model rewrite adds about a fifth of a second to a second. Multi-query adds one call, and its searches run in parallel. HyDE adds a full generation. Reranking fifty candidates takes a tenth to half a second. Each extra hop costs one to three seconds. Agentic RAG runs two to ten calls, so five to thirty seconds. GraphRAG indexing costs many calls per chunk.

What each addition costs
query rewrite     +1 small call, ~0.2-1 s
multi-query (3)   +1 call, parallel search
HyDE              +1 full generation
rerank 50         ~0.1-0.5 s
each extra hop    ~1-3 s
agentic RAG       2-10 calls, ~5-30 s
GraphRAG index    many calls per chunk
stuff 100k tok    ~40× tokens of top 5

output tokens cost ~3-5× input

Common mistakes

Common mistakes. Adding every trick at once, with no evaluation. Rewrites that silently drop an id or a date. Loops with no cap on hops or agent steps. Building a knowledge graph for questions plain search already answers. Pasting a whole document set into a long context and forgetting that some users should not see some documents. Citations nobody verifies. And a system that never says not found, so it guesses instead.

Avoid these
  • every trick at once, with no eval showing which helped
  • rewrites that drop ids, dates
  • no cap on hops or agent steps
  • a graph for simple lookups
  • long context as an excuse to skip access control
  • citations nobody checks
  • never answering "not found"

Say it like this

How to say it. We started with hybrid search and reranking. Our evals showed follow-up questions failing, so a small model now rewrites them. A router sends counting questions to SQL and policy questions to the doc index. Multi-hop questions get up to three hops. Every answer cites its sources, and below a tuned rerank score we say not found. Each addition earned its place on the eval set, and we know its latency cost.

In the interview
  • "Hybrid search + rerank first. Evals showed follow-ups failing, so a small model rewrites them. A router sends counts to SQL. Multi-hop gets up to 3 hops. Answers cite sources; below a rerank score of 0.3 we say not found. Each step earned its place on the eval set."

Interview questions

Q1What is query rewriting in RAG and when do you need it?

A small model turns the user message, plus recent chat history, into a standalone search query, for example "and per seat?" into "Pro plan price per seat". You need it in any conversational product, and the rewrite must preserve ids, names and dates exactly.

Q2What is multi-query retrieval?

The model generates several phrasings of the question, each is searched (in parallel), and the result lists are merged with reciprocal rank fusion and reranked. It raises recall on vague questions for the cost of one extra model call.

Q3What is HyDE?

Hypothetical document embeddings: the model writes a plausible answer without sources, you embed that draft and search with it, because answer-shaped text sits closer to real answers than the question does. The draft is discarded; it costs a generation and can mislead on private topics.

Q4How do you answer a multi-hop question?

With iterative retrieval: search, let the model decide whether it has enough and what to search next, then search again, up to a hop cap of about three. If the sub-questions are independent you can decompose up front and search them in parallel instead.

Q5What is agentic RAG and what does it cost?

Search indexes are exposed as tools and the model decides whether, what and where to search and when to stop. It handles varied questions in one design but takes several model calls (often seconds to tens of seconds) and is less predictable, so cap steps and tokens.

Q6When is GraphRAG worth it?

For questions about relationships across many documents, or global questions like "main themes across all reports" that top-k chunks cannot cover. It extracts an entity graph, clusters it into communities and pre-summarises them, which makes indexing far more expensive and slower to refresh.

Q7With million-token context windows, is RAG still needed?

For small, stable document sets with few queries, stuffing everything in can be simpler and works, especially with prompt caching. At scale RAG is far cheaper per question (a 100k-token manual vs ~2.5k tokens of chunks), respects per-user permissions, stays fresh, and avoids facts lost in the middle of long prompts.

Q8How do you stop a RAG system from making things up when retrieval fails?

Abstain on purpose: if the best rerank score is below a threshold tuned on labelled data, or no results survive filters, skip generation and say the answer was not found. Also instruct the model to answer only from numbered sources, cite them, and verify citations in code.