Chapter 17 of 32 · ~22 min read & lab+85 XP
Chapter 17 · Agentic AI

Agentic RAG: Query Rewriting, Corrective RAG (CRAG) & Self-Routing Retrieval

Upgrading blind 1-shot RAG into a self-correcting Retrieval Agent: Query Rewriting & Multi-Hop Decomposition, Corrective RAG (CRAG) 3-band evidence grading, Self-Routing across Vector/SQL/Web tools, and bounded retrieval loops.

What Is It?

Agentic RAG (including Corrective RAG / CRAG) lets the agent rewrite vague queries, grade retrieved document relevance, and trigger a second search or web fallback when evidence is weak.

Why Is It Required?

Static 1-shot RAG blindly feeds irrelevant chunks into the LLM and hallucinates; grading evidence first catches bad retrieval before generation.

Everyday Analogy: A researcher who checks whether the first book they pulled actually answers the question—and walks back to the catalog with better keywords if it doesn't.
Why ML Engineers & Data Scientists Actually Need This

Naive RAG breaks whenever the user uses pronouns (*'How much did they grow?'*), asks a multi-hop comparison, or asks about something missing from your vector DB — Agentic RAG fixes all three!

ML / AI Engineer

Adding a fast 100 ms Query Rewriter + CRAG Relevance Grader turns a brittle RAG pipeline into an adaptive retrieval agent that knows when to retry or fall back to Web Search!

Data Scientist

Treating Retrieval as a Tool (search_docs, query_sql, web_search) lets the agent skip retrieval entirely on 'Hello!' and fire 2 parallel sub-queries on 'Compare Stripe vs. Adyen'!

Interview & Debug Edge

High-signal RAG + Agents crossover question: 'How does Corrective RAG (CRAG) work, and how would you upgrade a standard RAG bot to handle multi-hop comparative questions?'

Step 0 · Test Your Gut Before Any Math!

In Corrective RAG (CRAG), what happens when the Relevance Grader scores all retrieved internal chunks as INCORRECT (< 0.4)?

What You Will Master in This Chapter
  • Contrast Naive 1-Shot RAG (blind single retrieval) with Agentic RAG (rewrite → retrieve → grade → retry/fallback)
  • Implement Query Rewriting (resolving pronouns like 'it' from chat history) and Multi-Hop Query Decomposition
  • Apply Corrective RAG (CRAG) 3-band grading: CORRECT (answer), AMBIGUOUS (supplement), INCORRECT (discard & Web/Fallback search)
  • Equip an Agent with multiple retrieval tools (Vector Docs, SQL DB, Web Search) and cap retrieval retries to protect latency
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 3
CRAG\text{CRAG}Say aloud:“Corrective Retrieval-Augmented Generation”
Plain-English Meaning
Grades retrieved chunks into CORRECT / AMBIGUOUS / INCORRECT before generating an answer
Everyday Example
Blocks stale/irrelevant context!
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

Naive RAG is like an intern who grabs the first 5 folders from a cabinet without even checking if they're from the right year. Agentic RAG (CRAG) is a sharp analyst who reads the question carefully, splits multi-part questions into 2 clean searches, checks whether the folders actually answer the question, and if the cabinet is outdated, goes straight to the web for the latest numbers!

1. Naive 1-Shot RAG vs. Self-Correcting Agentic RAG

Everyday Story First (Zero Math Yet!)

Making retrieval an explicit agent decision solves both unnecessary lookups ('Hi!') and failed single-shot lookups.

Naive 1-Shot RAG vs. Self-Correcting Agentic RAGNaive RAG (Blind 1-Shot)Query → Top-5 → AnswerBad query or missing doc → hallucinates!Agentic RAG (Rewrite + Grade + Fallback)Rewrite → Retrieve → Grade? → Retry/WebVerifies evidence BEFORE answering ✓
Naive RAG retrieves ONCE blindly and hopes for the best; Agentic RAG rewrites queries, grades retrieved chunks, and retries or switches to Web Search when evidence is weak!

3 Upgrades That Turn Naive RAG into Agentic RAG

  1. Conversational Query Rewriting: Resolves coreferences ("it", "they") into standalone search queries.
  2. Multi-Tool Source Routing: Picks query_sql for exact sums/counts, search_docs for policies, and web_search for today's news.
  3. Evidence Grading + Retry (CRAG): Verifies retrieved chunks BEFORE answering (capped at max 2 retrieval loops!).

2. Corrective RAG (CRAG): The 3-Way Evidence Grading Gate

Everyday Story First (Zero Math Yet!)

Slide the Evidence Score in the mini-lab below across 0.1 → 0.95 to see CRAG switch cleanly between INCORRECT, AMBIGUOUS, and CORRECT!

Corrective RAG (CRAG): 3-Way Evidence Grading GateCORRECT (≥ 0.8)Refine & Answer Directly ✓AMBIGUOUS (0.4–0.8)Keep Best + Web SupplementINCORRECT (< 0.4)Discard + Rewrite / Web Search!
Corrective RAG (CRAG) evaluates retrieved context into 3 bands: CORRECT (answer directly), AMBIGUOUS (refine + supplement), or INCORRECT (discard & run Web/Fallback search)!

Keep the Grader Fast!

Use a lightweight Cross-Encoder reranker score or a tiny fast LLM (gpt-4o-mini / gemini-flash-lite) for the CRAG grader so evidence gating adds <80 ms instead of 2 seconds!

Animated Mini-Lab • 3.4

Corrective RAG (CRAG) Relevance Gate

AMBIGUOUS → Keep Top Chunk + Supplement via Web Search

3. Multi-Hop Query Decomposition

Everyday Story First (Zero Math Yet!)

A single vector embedding cannot point cleanly to BOTH Stripe's Q3 filing AND Adyen's Q3 filing at once — decomposition splits it into 2 parallel hits!

Query Decomposition: Splitting Multi-Hop Questions into Parallel Sub-Queries"Compare Q3 revenue ofStripe vs. Adyen"Sub-Q1: Stripe Q3 revenueSub-Q2: Adyen Q3 revenueSynthesize ✓
Multi-hop questions ('Compare Q3 revenue of Stripe vs. Adyen') fail single-vector lookup — Query Decomposition splits them into 2 sharp parallel sub-queries!

Parallel Sub-Query Execution

Run [search("Stripe Q3 2026 revenue"), search("Adyen Q3 2026 revenue")] concurrently via Batch Tool Execution (Module 2.2) — doubling recall at zero extra latency!

Walk Through With Me · Interactive Worked Example

Worked Example: Standalone Query Rewriting in Multi-Turn Chat

Turn 1: 'What is our enterprise refund window?' → '30 days.' Turn 2: 'Does that apply to annual plans too?'

11. Naive raw searchStep 1 / 2

Embedding 'Does that apply to annual plans too?' has NO mention of 'refund' or 'enterprise' → retrieves wrong billing FAQ!

Teacher's Note: Pronoun 'that' loses all meaning outside chat history!
Pause & Check · Quick Intuition Pulse

Why does Query Decomposition improve retrieval on comparative questions like 'Compare Q3 revenue of Stripe vs. Adyen'?

Try It YourselfStandard

Why should you cap Agentic RAG retrieval retries at max_retrievals = 2 (or 3) instead of letting the agent search indefinitely when a document truly doesn't exist?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

When latency budget is super tight (<500 ms) and queries are single-turn, single-fact lookups over a clean internal corpus — add Agentic Query Rewriting + CRAG as soon as you have multi-turn chat, multi-hop questions, or heterogeneous data sources!

Interactive Visual Lab
Lab Challenge: Watch all 4 stages of the 60 FPS CRAG Decision Loop catch stale 2022 chunks and self-correct via Web Fallback.
Interactive Animation • 3.4 Deep Lab

Corrective Agentic RAG (CRAG): Grade → Discard Stale → Web Fallback

See how Agentic RAG detects stale internal vector hits and self-corrects via query rewriting and web fallback.

Step 1 / 4
1. Initial Vector Search
Query: '2026 tax rate' → Top-3 chunks are from 2022!
0%
1. Initial Vector Search
Intuition Takeaway: Agentic RAG upgrades blind 1-shot retrieval with Conversational Query Rewriting, Parallel Multi-Hop Decomposition, CRAG 3-band evidence grading, and bounded Web/SQL fallbacks.
Where This Powers Real ML, Deep Learning & Generative AI

Perplexity-Style Deep Search & Enterprise Knowledge Agents

Combines Query Decomposition, Parallel Search, CRAG grading, and strict inline citations.

Production NumPy & PyTorch Code Patterns
# Corrective RAG (CRAG) Decision Gate: Grade Retrieved Docs -> Rewrite or Fallback
def grade_relevance(query: str, doc: str) -> float:
    q_terms = set(query.lower().split())
    d_terms = set(doc.lower().split())
    return len(q_terms & d_terms) / max(1, len(q_terms))

def crag_retrieve(query: str, docs: list[str], high: float = 0.5, low: float = 0.2) -> dict:
    scored = [(grade_relevance(query, d), d) for d in docs]
    best_score, best_doc = max(scored, key=lambda x: x[0])
    if best_score >= high:
        return {"action": "GENERATE_GROUNDED", "context": best_doc}
    if best_score >= low:
        return {"action": "REWRITE_QUERY_AND_RETRY", "rewritten": f"{query} official documentation"}
    return {"action": "WEB_SEARCH_FALLBACK", "context": None}

corpus = ["PyTorch DataLoader supports num_workers for parallel batching.", "Sourdough bread recipe."]
print(crag_retrieve("PyTorch DataLoader parallel", corpus))
print(crag_retrieve("Kubernetes ingress TLS", corpus))
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Running a heavy 70B LLM grader sequentially on each of 10 retrieved chunks (10× latency!).
Best Practice: Grade chunks in 1 single batched call or use a fast Cross-Encoder score (<30 ms) as the CRAG gate!
Chapter Mastery Check (+85 XP)
Score: 0 / 1
1In multi-turn RAG chat, what problem does Conversational Query Rewriting solve?

Apply What You Learned — Solve Matching Coding Problems