Agentic RAG
Put retrieval inside an agent loop: the model decides whether, what and where to search, judges the evidence, and searches again until it can answer — accuracy on hard questions for latency, tokens and predictability.
Analogy: A one-shot pipeline is a vending machine: one button, one product. Agentic RAG is a research assistant who checks the wiki, then the database, notices a gap and goes back before writing the memo.
How it works
- One-shot RAG breaks on multi-hop questions, where the second search depends on what the first one found.
- A typical loop: plan and pick a tool, retrieve, grade the results, then search again or answer.
- Corrective RAG grades retrieval with a lightweight evaluator and falls back to web search when documents look wrong.
- Each step re-sends a growing transcript, so latency climbs from ~1–3 s to ~10 s+ and tokens multiply.
- Cap the steps, trace everything, and route only hard questions to the loop.
Check yourself
Answer to mark it learned; your answers aren't scored.
Your support widget answers most questions well with one-shot RAG at ~2 s. Error analysis shows a small tail of multi-hop questions failing. A teammate proposes making every request agentic. What do you do?
Go deeper
Full explanation
Agentic RAG puts retrieval inside an agent loop. Instead of a fixed retrieve once → generate pipeline, the model decides whether to retrieve, what to search for, where (which index or tool) and whether the evidence is good enough.
One-shot RAG embeds the user's raw question once. That breaks on multi-hop questions — "Which German customers use the plan we deprecated last quarter?" — where the second search depends on what the first one found.
A typical loop:
- Plan — decompose the question and pick a tool: vector index, SQL, web search, a GraphRAG & knowledge graphs global search.
- Retrieve with a model-written query.
- Grade — are these results relevant and sufficient? Corrective RAG (CRAG) uses a lightweight evaluator and falls back to web search when retrieved documents look wrong.
- Iterate — reformulate and search again, or move on.
- Self-check — is every claim supported? Self-RAG trains the model to emit reflection tokens for exactly these decisions.
The costs are real. Each step is another LLM call that re-sends a growing transcript, so latency goes from ~1–3 s to ~10 s or more, tokens multiply, and two runs can take different paths. Cap the steps, trace everything, and route only hard questions to the loop.
Code A bounded agentic RAG loop with two tools
import json
from openai import OpenAI
client = OpenAI()
MODEL = "gpt-4.1-mini" # any tool-calling model
def tool(name, desc, arg):
return {"type": "function", "function": {"name": name, "description": desc,
"parameters": {"type": "object", "properties": {arg: {"type": "string"}}, "required": [arg]}}}
TOOLS = [tool("search_docs", "Hybrid search over internal docs; returns chunks with doc ids.", "query"),
tool("run_sql", "Read-only SQL over the customers database.", "sql")]
IMPL = {"search_docs": hybrid_search, "run_sql": readonly_sql}
def agentic_rag(question: str, max_steps: int = 6) -> str:
msgs = [{"role": "system", "content": "Search until every claim has evidence; cite doc ids. "
"If the evidence does not exist, say so."},
{"role": "user", "content": question}]
for _ in range(max_steps): # hard cap bounds latency and cost
msg = client.chat.completions.create(model=MODEL, messages=msgs, tools=TOOLS).choices[0].message
if not msg.tool_calls:
return msg.content # the model decided the evidence is enough
msgs.append(msg)
for call in msg.tool_calls:
result = IMPL[call.function.name](**json.loads(call.function.arguments))
msgs.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)})
return "I couldn't find enough evidence within the step budget." # abstain, don't guessReal example
An analyst asks "Did any enterprise customer churn after the March pricing change, and what reason did they give?" One-shot RAG embeds the whole sentence and returns pricing-page chunks: useless. The agent instead (1) searches the changelog and finds the change date, March 12; (2) runs SQL for enterprise accounts cancelled after that date and gets 4; (3) searches support tickets filtered to those 4 account ids; (4) grades the results, finds no ticket for one account and says so. Five tool calls, ~12 s and several times the tokens of the one-shot path: fine for an analyst tool, wrong for a chat widget.
Trade-offs +3 · −3
+ You gain
- Handles multi-hop and comparative questions where the next query depends on the last result.
- Picks the right source per sub-question: vector index, SQL, web search or an API.
- Can notice weak evidence and retry or abstain instead of answering from irrelevant chunks.
− You pay
- Latency and tokens multiply: every plan, grade and retry is another LLM call.
- Less predictable: different paths per run make caching, debugging and evaluation harder.
- New failure modes: loops, over-searching, or stopping early with false confidence.
Use it when
Multi-hop, comparative or research-style questions across several sources, where users accept seconds of extra latency (analyst tools, deep research, internal copilots) and a wrong answer costs more than tokens.
Avoid it when
High-volume, latency-sensitive Q&A where one retrieval usually suffices (FAQ bots, support widgets). Fix the one-shot pipeline first, then add Pattern: routing so only hard questions take the agentic path.
Numbers to know 4
- N agent steps cost more than N× the input tokens of one-shot RAG: each call re-sends the growing transcript.
- Self-RAG uses 4 reflection-token types: Retrieve, IsRel, IsSup, IsUse.
- CRAG's retrieval evaluator is a fine-tuned T5-large (~0.77B params), not the generator LLM: grading can be cheap.
- Rule of thumb: ~1–3 s for one-shot RAG vs ~10 s+ once the agent takes 3–5 steps.
Common pitfalls 4
- No step or token budget: a confused agent fires 20 searches at an unanswerable question.
- Making every request agentic instead of routing: you pay multi-step latency on questions one search answers.
- Evaluating only final answers: score the trajectory too (queries written, tools chosen, evidence used).
- Overlapping tool descriptions ("search_docs" vs "search_kb"), so the model picks between them at random.
Interview questions 2
Answer out loud first, then reveal.
When would you move from a classic RAG pipeline to agentic RAG?Show answer
When error analysis shows failures one retrieval can't fix: multi-hop questions, questions needing two sources like docs plus SQL, or comparisons. If the failures are bad chunks or missing lexical match, an agent just retries a broken retriever, so I'd fix that first. Then I'd add a router: simple questions stay on the one-shot path at ~1–3 s, and only complex ones enter the loop, with a step cap, a token budget and an explicit abstain option. The trade-off I'd name is latency, cost and predictability in exchange for accuracy on the hard tail.
How do you keep an agentic RAG system reliable and debuggable?Show answer
I treat it like any agent. Hard limits: max steps, max tokens, timeouts. Few, non-overlapping tools with clear descriptions, returning chunk ids so citations are checkable. Full tracing of every step — query written, tool chosen, results, grade — because a wrong answer usually traces back to one bad intermediate query. I evaluate trajectories, not just answers: right source, number of steps, abstaining when evidence is missing. And I keep a deterministic one-shot fallback for when the loop runs out of budget.