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.
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.
Static 1-shot RAG blindly feeds irrelevant chunks into the LLM and hallucinates; grading evidence first catches bad retrieval before generation.
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!
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!
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'!
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?'
In Corrective RAG (CRAG), what happens when the Relevance Grader scores all retrieved internal chunks as INCORRECT (< 0.4)?
- 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
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
Making retrieval an explicit agent decision solves both unnecessary lookups ('Hi!') and failed single-shot lookups.
3 Upgrades That Turn Naive RAG into Agentic RAG
- Conversational Query Rewriting: Resolves coreferences (
"it","they") into standalone search queries. - Multi-Tool Source Routing: Picks
query_sqlfor exact sums/counts,search_docsfor policies, andweb_searchfor today's news. - 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
Slide the Evidence Score in the mini-lab below across 0.1 → 0.95 to see CRAG switch cleanly between INCORRECT, AMBIGUOUS, and CORRECT!
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!
Corrective RAG (CRAG) Relevance Gate
3. Multi-Hop Query Decomposition
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!
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!
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?'
Embedding 'Does that apply to annual plans too?' has NO mention of 'refund' or 'enterprise' → retrieves wrong billing FAQ!
'that' loses all meaning outside chat history!Why does Query Decomposition improve retrieval on comparative questions like 'Compare Q3 revenue of Stripe vs. Adyen'?
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?
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!
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.
Perplexity-Style Deep Search & Enterprise Knowledge Agents
Combines Query Decomposition, Parallel Search, CRAG grading, and strict inline citations.
# 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))