Advanced RAG: query transformation, graph, agentic retrieval

Rewrite queries, hypothetical documents, multi-hop, self-correcting retrieval, GraphRAG, and when long context beats retrieval.

Advanced about 6 h

The picture

  1. 01

    Query

    ambiguous, multi-part

  2. 02

    Rewrite / decompose

    better queries

  3. 03

    Retrieve

    per sub-query

  4. 04

    Grade

    relevant enough?

  5. 05

    Retry or answer

    self-correct

When basic RAG is not enough

Basic RAG retrieves once, with the user's words. It struggles when the question is vague, has several parts, needs facts from different documents, or asks for a global summary over the whole corpus.

Query transformation

import json, anthropic
client = anthropic.Anthropic()

def llm(prompt, max_tokens=400):
    return client.messages.create(model="claude-sonnet-5-5", max_tokens=max_tokens, temperature=0,
                                  messages=[{"role": "user", "content": prompt}]).content[0].text

def decompose(question: str) -> list[str]:
    out = llm(f"Split this question into 1 to 4 standalone search queries. Return a JSON list of strings only.\n\nQuestion: {question}")
    return json.loads(out)

def hyde(question: str) -> str:
    """Hypothetical Document Embeddings: embed a plausible answer, not the question."""
    return llm(f"Write a short passage that would answer this question, as it might appear in documentation.\n\n{question}")

def multi_query_retrieve(question, retrieve, k=5):
    rankings = [[c["id"] for c in retrieve(q, 20)] for q in decompose(question) + [question]]
    return rrf(rankings)[:k]                  # reuse RRF from the hybrid-search topic

HyDE helps because answers resemble answers more than questions do. It can also invent misleading content, so measure it.

Self-correcting retrieval

Grade what you retrieved before generating. If it is irrelevant, rewrite the query and try again, or fall back to another source.

def grade(question, chunk_text) -> bool:
    out = llm(f"Question: {question}\n\nPassage: {chunk_text}\n\nDoes the passage help answer the question? Reply yes or no.", max_tokens=3)
    return out.strip().lower().startswith("yes")

def corrective_answer(question, retrieve, answer_fn, max_rounds=2):
    q = question
    for _ in range(max_rounds + 1):
        chunks = [c for c in retrieve(q, 8) if grade(question, c["text"])]
        if chunks:
            return answer_fn(question, chunks)
        q = llm(f"Rewrite this as a better search query for a document store:\n{q}", 60)
    return "I don't know based on the provided documents."

This is the seed of agentic RAG: the model decides whether to search, what to search, and when it has enough. You will build that in the agents stages. Each extra model call adds latency and cost, so use it only where measured gains justify it.

Global questions: GraphRAG and hierarchical summaries

"What are the main themes across all these documents?" cannot be answered from a few top chunks. GraphRAG extracts entities and relations into a graph, clusters it into communities, pre-writes a summary for each, and answers global questions from those summaries. RAPTOR builds a tree of recursive summaries. Both cost far more at indexing time, so reserve them for corpora where cross-document synthesis is the actual task.

RAG, long context or fine-tuning?

  • RAG: knowledge changes, you need citations and access control, the corpus is large.
  • Long context: a single, bounded document set; occasional use; the cost per call is acceptable. Check recall in the middle of the window.
  • Fine-tuning: to change behaviour, style or format, not to add facts reliably.

These combine: many strong systems fine-tune for format and use RAG for facts.

Common mistakes

  • Adding every advanced technique before measuring a baseline.
  • Letting a rewriting step drift away from the user's intent.
  • Using GraphRAG for factoid lookup.

Exercises

  1. Implement multi-query retrieval and report the change in recall@5 on multi-part questions.
  2. Compare HyDE and plain dense retrieval on a set of vague queries.

You are done when you can…

  • Implement query decomposition and multi-query retrieval with fusion
  • Describe when GraphRAG, hierarchical summaries or agentic retrieval earn their cost
  • Decide between RAG, long context and fine-tuning for a given problem