Short answer: agentic RAG is retrieval-augmented generation where the language model controls the search. The model decides whether to search and which source to use. It judges whether the results are good enough and searches again with a better query if not. Classic RAG always does one search and one answer.
Below you will find the difference in plain terms, the main research patterns with their papers and an architecture you can draw. You will also get a toy agentic loop in Python. Every output shown was produced by running the code.
Classic RAG in three lines
RAG means retrieval-augmented generation. A language model (LLM) is a program that predicts text. RAG gives it extra documents at question time, so it can answer from your data.
- Retrieve: search your documents with the user's question and take the top few matches (the top k).
- Augment: paste those matches into the prompt.
- Generate: the LLM writes the answer from that prompt.
That is one search, one answer, always. If you want the full basics, read our guide on RAG vs MCP vs AI agents and our post on choosing a vector database for RAG. This post only covers what changes when the model takes control.
What makes RAG "agentic"?
An agent is an LLM that picks its own next action, looks at the result, and repeats until it is done. Anthropic's engineering guide says agents are "typically just LLMs using tools based on environmental feedback in a loop." It also advises stopping conditions, such as a maximum number of iterations. Agentic RAG puts retrieval inside that loop.
In classic RAG, your code decides everything. In agentic RAG, the model makes six decisions:
- Whether to retrieve at all. "What is the capital of France?" needs no search of your documents.
- What to search for. It writes the query, instead of using the user's words as typed.
- Which source to use. A vector index, a SQL database, a web search or an API.
- Whether the evidence is good enough. This is called grading: the model reads the results and judges them.
- Whether to rewrite and try again. If the results are weak, it writes a better query.
- When to stop. It answers once the evidence is enough, or gives up.
Retrieval stops being a fixed step. It becomes a tool the model can call, zero, one or many times.
Why one search is sometimes not enough
Take the question: "Where does the head of the team behind the Spark e-bike sit?" The answer needs three facts in a chain. The e-bike was designed by a team. The team has a lead. The lead sits in a city.
The question's words match the first fact. They do not match the second or third. The lead's name never appears in the question, so a single search cannot find the lead's document. This is a multi-hop question: each hop depends on the answer to the previous one.
The IRCoT paper (Trivedi et al., 2022) states it well. For multi-step questions, "what to retrieve depends on what has already been derived". One-step retrieval is not enough for those questions.
The main agentic RAG patterns, with their papers
Researchers have studied the pieces of agentic RAG for a few years. Here are the ones you will meet most often.
ReAct: reason, act, observe
ReAct (Yao et al., October 2022) lets a model interleave reasoning steps with actions, such as calling a search API. It then reads the result and reasons again. On the HotpotQA question-answering set, the authors used a simple Wikipedia API as the tool. Our loop in this post follows the same reason, act, observe cycle.
Adaptive-RAG: route by question difficulty
Adaptive-RAG (Jeong et al., March 2024) trains a small language model to predict how complex a question is. It then picks a strategy: no retrieval, single-step retrieval, or iterative retrieval. The goal is to avoid wasting effort on easy questions while still handling hard ones. This is routing, and it is the easiest agentic idea to add to an existing RAG system.
Self-RAG: the model critiques itself
Self-RAG (Asai et al., October 2023) trains one model to retrieve only when needed. It also trains the model to judge the retrieved passages and its own output. It does this with special tokens, called reflection tokens, that the model writes between pieces of text. The paper reports results for 7B and 13B parameter models. A parameter is one learned number inside the model, and "7B" means seven billion of them.
Corrective RAG (CRAG): grade, then fix
Corrective RAG (Yan et al., January 2024) adds a lightweight retrieval evaluator. It scores the retrieved documents and returns a confidence level. Depending on that level, the system can trigger different actions, including a web search when the local documents are weak. Our toy grader below plays the same role.
IRCoT: interleave retrieval with reasoning
IRCoT (Trivedi et al., December 2022) alternates between retrieving and writing one sentence of a chain of thought (step-by-step reasoning written out as text). Each new sentence guides the next search, and each search result improves the next sentence. With GPT-3, the authors report retrieval gains of up to 21 points and question-answering gains of up to 15 points across four multi-hop datasets. Those numbers are from their experiments, not a promise for your data.
The survey that names the architectures
The survey Agentic Retrieval-Augmented Generation (Singh et al., first posted 15 January 2025) sorts the field by number of agents, control structure and autonomy. It describes single-agent, multi-agent and hierarchical designs, plus corrective, adaptive and graph-based variants.
An architecture you can draw
Most agentic RAG systems have the same parts. Here are two common layouts, following the survey's names.
Layout 1: single-agent router. One agent sits in the middle.
- The user's question goes to the agent.
- The agent picks a source: vector search for documents, SQL for tables, web search for fresh facts, or none.
- The tool returns passages or rows.
- A grader (often the same model with a different prompt) checks them.
- If they are weak, the agent rewrites the query and goes back to step 2.
- If they are good, the agent writes the answer with sources.
Layout 2: multi-agent. A coordinator agent splits the question and hands each part to a specialist agent. One specialist might search the product documents, another the finance tables, a third the web. The coordinator collects the results and writes the answer. The survey notes that this adds "coordination complexity", because you now manage how the agents talk to each other.
Whatever the layout, add these three parts:
- A step budget: a hard limit on loops, so the agent cannot run forever.
- A trace log: a record of every query, result and decision, so you can debug it.
- Source citations: so a person can check each claim.
Build it: a tiny corpus and a BM25 retriever
Time to see the difference in code. We use no LLM and no libraries, only the Python standard library. That keeps every run exactly repeatable.
The documents belong to a made-up company, Kaveri Cycles. Every fact is invented for this post. The retriever is BM25, a classic ranking formula that scores documents by how often the query words appear in them. It also counts rare words as more important than common ones.
# file: kb.py
import math
import re
# A made-up company. Every document below is invented for this post.
DOCS = {
"d01": "Kaveri Cycles is a made-up company used in this post. It sells electric bikes in India.",
"d02": "The Spark e-bike was designed by the Hubli Design Team.",
"d03": "The Spark e-bike battery has a warranty of 24 months.",
"d04": "The Trail e-bike was designed by the Mysuru Product Team.",
"d05": "Meera Rao leads the Hubli Design Team.",
"d06": "Arjun Nair leads the Mysuru Product Team.",
"d07": "Meera Rao sits in Dharwad.",
"d08": "Arjun Nair sits in Mysuru.",
"d09": "The Trail e-bike battery has a warranty of 18 months.",
"d10": "Every team at Kaveri Cycles sends a weekly update every Friday.",
"d11": "The head office team handles payroll and leave requests.",
"d12": "Spark e-bike owners can book a free first service at any dealer.",
"d13": "Dealers sit in 40 cities and the dealer list is updated every quarter.",
}
STOP = {"the", "a", "an", "of", "is", "in", "at", "to", "and", "does", "do", "how", "on", "by", "any", "can"}
def tokens(text):
return [t for t in re.findall(r"[a-z0-9]+", text.lower()) if t not in STOP]
class BM25:
"""Okapi BM25 ranking, written from scratch (k1 = 1.5, b = 0.75)."""
def __init__(self, docs, k1=1.5, b=0.75):
self.ids = list(docs)
self.toks = {i: tokens(t) for i, t in docs.items()}
self.k1, self.b = k1, b
self.avg = sum(len(t) for t in self.toks.values()) / len(docs)
df = {}
for t in self.toks.values():
for w in set(t):
df[w] = df.get(w, 0) + 1
n = len(docs)
self.idf = {w: math.log(1 + (n - c + 0.5) / (c + 0.5)) for w, c in df.items()}
def score(self, query, doc_id):
toks, s = self.toks[doc_id], 0.0
for w in set(tokens(query)):
f = toks.count(w)
if f:
norm = f + self.k1 * (1 - self.b + self.b * len(toks) / self.avg)
s += self.idf[w] * f * (self.k1 + 1) / norm
return s
def search(self, query, k=2):
ranked = sorted(self.ids, key=lambda i: (-self.score(query, i), i))
return [(i, round(self.score(query, i), 2)) for i in ranked[:k] if self.score(query, i) > 0]
INDEX = BM25(DOCS)
if __name__ == "__main__":
for q in ["warranty on the Spark e-bike battery", "who leads the Hubli Design Team"]:
print(q, "->", INDEX.search(q, k=3))
Output:
warranty on the Spark e-bike battery -> [('d03', 6.55), ('d09', 5.2), ('d02', 3.18)]
who leads the Hubli Design Team -> [('d05', 6.56), ('d02', 4.12), ('d06', 2.75)]
The first query finds the warranty document first. The second finds the team-lead document first. Retrieval itself works fine. The problem comes next.
Classic RAG: fine for one fact, stuck on a chain
Now the classic pipeline: one retrieval with k = 2, then one answer. The "LLM" here is a stand-in function. It reads facts from the retrieved text with regular expressions and says "I cannot find that" when a fact is missing. A real LLM may behave differently when evidence is missing. It might guess, which is worse. We use the honest refusal to keep the demo clear.
# file: classic.py
import re
from kb import DOCS, INDEX
TOP_K = 2
def read_facts(texts):
"""Pull simple facts out of text with regexes. An LLM would do this by reading."""
facts = {"team_of": {}, "lead_of": {}, "city_of": {}, "warranty": {}}
for t in texts:
if m := re.match(r"The (.+?) was designed by the (.+?)\.", t):
facts["team_of"][m.group(1)] = m.group(2)
if m := re.match(r"(.+?) leads the (.+?)\.", t):
facts["lead_of"][m.group(2)] = m.group(1)
if m := re.match(r"(.+?) sits in (.+?)\.", t):
facts["city_of"][m.group(1)] = m.group(2)
if m := re.match(r"The (.+?) battery has a warranty of (.+?)\.", t):
facts["warranty"][m.group(1)] = m.group(2)
return facts
def llm_answer(question, context):
"""Stand-in for ONE LLM call: answer from the context only, else say so."""
facts = read_facts(context)
product = re.search(r"Spark e-bike|Trail e-bike", question)
product = product.group(0) if product else None
if "warranty" in question:
return facts["warranty"].get(product, "I cannot find that in the documents.")
team = facts["team_of"].get(product)
lead = facts["lead_of"].get(team)
return facts["city_of"].get(lead, "I cannot find that in the documents.")
def classic_rag(question):
hits = INDEX.search(question, k=TOP_K) # retrieval call 1 (always, exactly once)
answer = llm_answer(question, [DOCS[i] for i, _ in hits]) # LLM call 1 (always, exactly once)
return [i for i, _ in hits], answer
QUESTIONS = [
"How long is the warranty on the Spark e-bike battery?",
"Where does the head of the team behind the Spark e-bike sit?",
]
if __name__ == "__main__":
for q in QUESTIONS:
ids, answer = classic_rag(q)
print("Q:", q)
print(" retrieved:", ids, "| retrievals: 1 | LLM calls: 1")
print(" answer:", answer)
Output:
Q: How long is the warranty on the Spark e-bike battery?
retrieved: ['d03', 'd09'] | retrievals: 1 | LLM calls: 1
answer: 24 months
Q: Where does the head of the team behind the Spark e-bike sit?
retrieved: ['d02', 'd03'] | retrievals: 1 | LLM calls: 1
answer: I cannot find that in the documents.
The simple question works. The top two documents include the warranty line, and the answer is 24 months.
The chain question fails. The search returned d02 (which names the Hubli Design Team) and d03 (the warranty line, matching "Spark e-bike"). It never returned d05 (who leads that team) or d07 (where that person sits). The question does not contain the words that would match them.
The documents were chosen so this happens, to make the failure repeatable. Real corpora fail the same way when a question needs facts that share no words with it.
Agentic RAG: decide, retrieve, grade, rewrite, answer
Now the same questions through an agent loop. The loop has five steps.
- Planner: decide whether the question needs our documents.
- Retrieve: search with the current query.
- Grader: judge whether the evidence is enough. If yes, go to step 5.
- Rewriter: write a new query for the missing fact, then go to step 2.
- Answer: write the answer from the evidence.
Be clear about what is fake here. The planner, grader, rewriter and answer functions are deterministic rules, not an LLM. In a real system each one is an LLM call. The planner would be asked, "Do you need our documents to answer this?" The grader would be asked, "Do these passages answer the question? If not, what is missing?" The rewriter would write a better search query from the grader's reply. The answer step would write a cited answer from the evidence.
The code counts retrievals and "LLM calls", meaning how many times a real model would have been called. It also has a max-steps guard of three retrieval rounds. We added two extra questions: one needs no search, and one asks about a product that does not exist.
# file: agent.py
import re
from classic import DOCS, INDEX, QUESTIONS, TOP_K, read_facts
from kb import tokens
MAX_ROUNDS = 3 # the max-steps guard: at most 3 retrieval rounds per question
CORPUS_WORDS = {w for t in DOCS.values() for w in tokens(t)}
class Meter:
def __init__(self):
self.retrievals = 0
self.llm_calls = 0
# --- Each function below stands in for one LLM call. Rules replace the model. ---
def decide(q):
"""LLM would be asked: 'Do you need our documents to answer this?'"""
return "retrieve" if any(len(w) > 3 and w in CORPUS_WORDS for w in tokens(q)) else "answer directly"
def grade(q, facts):
"""LLM would be asked: 'Do these passages answer the question? If not, what is missing?'"""
product = re.search(r"[A-Z]\w+ (?:e-bike|scooter)", q).group(0)
if "warranty" in q:
return ("enough", None) if product in facts["warranty"] else ("not enough", f"warranty of the {product} battery")
team = facts["team_of"].get(product)
if team is None:
return "not enough", f"who designed the {product}"
lead = facts["lead_of"].get(team)
if lead is None:
return "not enough", f"who leads the {team}"
return ("enough", None) if lead in facts["city_of"] else ("not enough", f"where does {lead} sit")
def final_answer(q, facts):
"""LLM would write the answer from the evidence, and cite it."""
product = re.search(r"[A-Z]\w+ (?:e-bike|scooter)", q).group(0)
if "warranty" in q:
return facts["warranty"][product]
return facts["city_of"][facts["lead_of"][facts["team_of"][product]]]
def agentic_rag(q):
m, seen, query, step = Meter(), [], q, 0
m.llm_calls += 1
choice = decide(q)
print(f" step {step}: planner (LLM call {m.llm_calls}) -> {choice}")
if choice == "answer directly":
m.llm_calls += 1
print(f" step {step}: answer (LLM call {m.llm_calls}) from the model's own knowledge")
return "Paris", m # canned: no real model here
for rnd in range(1, MAX_ROUNDS + 1):
hits = INDEX.search(query, k=TOP_K)
m.retrievals += 1
seen += [DOCS[i] for i, _ in hits if DOCS[i] not in seen]
print(f" step {rnd}: retrieve #{m.retrievals} for {query!r} -> {[i for i, _ in hits]}")
m.llm_calls += 1
verdict, missing = grade(q, read_facts(seen))
print(f" step {rnd}: grader (LLM call {m.llm_calls}) -> {verdict}" + (f" (missing: {missing})" if missing else ""))
if verdict == "enough":
m.llm_calls += 1
print(f" step {rnd}: answer (LLM call {m.llm_calls})")
return final_answer(q, read_facts(seen)), m
if rnd == MAX_ROUNDS:
break
m.llm_calls += 1
query = missing # LLM would rewrite the query
print(f" step {rnd}: rewriter (LLM call {m.llm_calls}) -> new query {query!r}")
print(f" STOP: hit the limit of {MAX_ROUNDS} retrieval rounds")
return "I could not find that in the documents.", m
ASKED = QUESTIONS + [
"What is the capital of France?",
"Where does the head of the team behind the Zephyr scooter sit?",
]
if __name__ == "__main__":
for q in ASKED:
print("Q:", q)
answer, m = agentic_rag(q)
print(f" ANSWER: {answer} | retrievals: {m.retrievals} | LLM calls: {m.llm_calls}\n")
Output:
Q: How long is the warranty on the Spark e-bike battery?
step 0: planner (LLM call 1) -> retrieve
step 1: retrieve #1 for 'How long is the warranty on the Spark e-bike battery?' -> ['d03', 'd09']
step 1: grader (LLM call 2) -> enough
step 1: answer (LLM call 3)
ANSWER: 24 months | retrievals: 1 | LLM calls: 3
Q: Where does the head of the team behind the Spark e-bike sit?
step 0: planner (LLM call 1) -> retrieve
step 1: retrieve #1 for 'Where does the head of the team behind the Spark e-bike sit?' -> ['d02', 'd03']
step 1: grader (LLM call 2) -> not enough (missing: who leads the Hubli Design Team)
step 1: rewriter (LLM call 3) -> new query 'who leads the Hubli Design Team'
step 2: retrieve #2 for 'who leads the Hubli Design Team' -> ['d05', 'd02']
step 2: grader (LLM call 4) -> not enough (missing: where does Meera Rao sit)
step 2: rewriter (LLM call 5) -> new query 'where does Meera Rao sit'
step 3: retrieve #3 for 'where does Meera Rao sit' -> ['d07', 'd05']
step 3: grader (LLM call 6) -> enough
step 3: answer (LLM call 7)
ANSWER: Dharwad | retrievals: 3 | LLM calls: 7
Q: What is the capital of France?
step 0: planner (LLM call 1) -> answer directly
step 0: answer (LLM call 2) from the model's own knowledge
ANSWER: Paris | retrievals: 0 | LLM calls: 2
Q: Where does the head of the team behind the Zephyr scooter sit?
step 0: planner (LLM call 1) -> retrieve
step 1: retrieve #1 for 'Where does the head of the team behind the Zephyr scooter sit?' -> ['d11', 'd13']
step 1: grader (LLM call 2) -> not enough (missing: who designed the Zephyr scooter)
step 1: rewriter (LLM call 3) -> new query 'who designed the Zephyr scooter'
step 2: retrieve #2 for 'who designed the Zephyr scooter' -> ['d02', 'd04']
step 2: grader (LLM call 4) -> not enough (missing: who designed the Zephyr scooter)
step 2: rewriter (LLM call 5) -> new query 'who designed the Zephyr scooter'
step 3: retrieve #3 for 'who designed the Zephyr scooter' -> ['d02', 'd04']
step 3: grader (LLM call 6) -> not enough (missing: who designed the Zephyr scooter)
STOP: hit the limit of 3 retrieval rounds
ANSWER: I could not find that in the documents. | retrievals: 3 | LLM calls: 6
Read the traces one by one.
- Easy question: one retrieval, and the grader says "enough". It took 3 LLM calls (planner, grader, answer), against 1 for classic RAG. The agent stops after one round, but it still pays for the planner and grader.
- Chain question: the first search finds the design team. The grader notices the lead is missing and the rewriter asks "who leads the Hubli Design Team". The second search finds Meera Rao. The grader then notices her city is missing, and the third search finds Dharwad. That took 3 retrievals and 7 LLM calls.
- France question: the planner sees nothing in the question that matches our documents, so it skips retrieval. This is the "decide whether to retrieve" idea from Adaptive-RAG and Self-RAG, in miniature.
- Zephyr question: the product does not exist. The agent keeps searching and reaches the guard after 3 rounds. It then gives up instead of looping forever or inventing an answer. That was 6 LLM calls for no answer, so the guard matters.
The cost pattern is simple. One retrieval round costs 3 calls in this design (planner, grader, answer). Each extra round adds 2 more (grader and rewriter). So r rounds cost 2r + 1 calls.
The same graph in LangGraph
LangGraph is a Python library from LangChain for building agent loops as graphs. You define nodes (steps) and edges (which step comes next). Edges can be conditional, which is how loops are built. LangChain's own tutorial, "Build a custom RAG agent with LangGraph", builds the same shape: a model that decides whether to search, grades the documents, rewrites the question and answers.
Below is our loop as a LangGraph graph. It reuses the same rule-based functions from agent.py, so no LLM is involved and the answers must match. We ran it in a virtual environment with langgraph 1.2.24 (released 20 November 2026, the latest on PyPI on 1 December 2026). Pin that version if you want the same behaviour as shown here.
# file: graph.py
# needs: langgraph
from typing import TypedDict
from langgraph.graph import END, START, StateGraph
from agent import MAX_ROUNDS, DOCS, INDEX, TOP_K, ASKED, decide, final_answer, grade, read_facts
class State(TypedDict):
question: str
query: str
seen: list
rounds: int
llm_calls: int
retrievals: int
missing: str
verdict: str
answer: str
def planner(s):
return {"llm_calls": s["llm_calls"] + 1}
def retrieve(s):
hits = INDEX.search(s["query"], k=TOP_K)
seen = s["seen"] + [DOCS[i] for i, _ in hits if DOCS[i] not in s["seen"]]
return {"seen": seen, "rounds": s["rounds"] + 1, "retrievals": s["retrievals"] + 1}
def grader(s):
verdict, missing = grade(s["question"], read_facts(s["seen"]))
return {"verdict": verdict, "missing": missing or "", "llm_calls": s["llm_calls"] + 1}
def rewriter(s):
return {"query": s["missing"], "llm_calls": s["llm_calls"] + 1}
def answerer(s):
if s["verdict"] == "enough":
return {"answer": final_answer(s["question"], read_facts(s["seen"])), "llm_calls": s["llm_calls"] + 1}
if s["rounds"] == 0:
return {"answer": "Paris", "llm_calls": s["llm_calls"] + 1}
return {"answer": "I could not find that in the documents.", "llm_calls": s["llm_calls"]}
def after_planner(s):
return "retrieve" if decide(s["question"]) == "retrieve" else "answer"
def after_grader(s):
if s["verdict"] == "enough" or s["rounds"] >= MAX_ROUNDS: # the max-steps guard
return "answer"
return "rewriter"
g = StateGraph(State)
for name, fn in [("planner", planner), ("retrieve", retrieve), ("grader", grader),
("rewriter", rewriter), ("answer", answerer)]:
g.add_node(name, fn)
g.add_edge(START, "planner")
g.add_conditional_edges("planner", after_planner, ["retrieve", "answer"])
g.add_edge("retrieve", "grader")
g.add_conditional_edges("grader", after_grader, ["answer", "rewriter"])
g.add_edge("rewriter", "retrieve")
g.add_edge("answer", END)
app = g.compile()
for q in ASKED:
start = {"question": q, "query": q, "seen": [], "rounds": 0, "llm_calls": 0,
"retrievals": 0, "missing": "", "verdict": "", "answer": ""}
path, final = [], start
for update in app.stream(start, stream_mode="updates"):
for node, change in update.items():
path.append(node)
final = {**final, **change}
print("Q:", q)
print(" path:", " > ".join(path))
print(f" ANSWER: {final['answer']} | retrievals: {final['retrievals']} | LLM calls: {final['llm_calls']}\n")
Output:
Q: How long is the warranty on the Spark e-bike battery?
path: planner > retrieve > grader > answer
ANSWER: 24 months | retrievals: 1 | LLM calls: 3
Q: Where does the head of the team behind the Spark e-bike sit?
path: planner > retrieve > grader > rewriter > retrieve > grader > rewriter > retrieve > grader > answer
ANSWER: Dharwad | retrievals: 3 | LLM calls: 7
Q: What is the capital of France?
path: planner > answer
ANSWER: Paris | retrievals: 0 | LLM calls: 2
Q: Where does the head of the team behind the Zephyr scooter sit?
path: planner > retrieve > grader > rewriter > retrieve > grader > rewriter > retrieve > grader > answer
ANSWER: I could not find that in the documents. | retrievals: 3 | LLM calls: 6
The answers, retrieval counts and LLM-call counts match the plain Python loop. The path line is the useful extra. It shows the exact nodes the graph visited for each question. The conditional edge after grader is the loop, and the check on rounds is the max-steps guard. To make this real, you would replace each function body with an LLM call. Keep the graph shape and the guard as they are.
For a fuller walk-through, see Crio's LangGraph tutorial and the RAG explained guide. The RAG retrieval pipeline simulator lets you step through retrieval yourself.
Classic RAG vs agentic RAG
| Classic RAG | Agentic RAG | |
|---|---|---|
| Searches per question | Exactly 1 | 0 to the step limit (0, 1 and 3 in our run) |
| LLM calls per question | 1 in our toy (more if you add a reranker or rewriter) | 2r + 1 for r retrieval rounds when it answers (3 and 7 in our run), 2r when the guard stops it (6) |
| Latency | One search plus one generation | Calls run in sequence, so time grows with each round |
| Cost per query | Fixed and easy to predict | Varies per question, and can spike on hard ones |
| Multi-hop questions | Fails when later facts share no words with the question | Can find later facts by rewriting the query |
| Easy questions | Cheap and correct | Correct, but pays for planner and grader calls |
| Debuggability | One retrieval to inspect | Needs a trace of every step |
| Typical failure | Misses a fact, then answers from what it has | Loops, bad grader verdicts, runaway cost |
We measured the call counts in the table in our toy run. We did not measure latency or dollars, because the toy has no model. Real numbers depend on your model, prompt size and infrastructure. Measure them on your own data.
When not to use agentic RAG
Start with classic RAG. Move to agentic RAG only when you can show where it fails.
- Most questions are single-fact lookups. Classic RAG answers them with one call. The agent pays for planning and grading every time.
- You need predictable cost and latency. A fixed pipeline has a fixed bill. A loop does not.
- You cannot yet measure quality. If you have no test set, you cannot tell whether the agent helps. Build the test set first.
- Retrieval is the real problem. If your chunks are bad or your search is weak, a smarter loop on top will search badly several times. Fix chunking and add hybrid search first, as our RAG interview questions guide explains.
- A cheaper fix exists. Try a bigger k, a reranker, or one query rewrite before building a loop.
A good middle path is Adaptive-RAG's idea: route easy questions to the plain pipeline and only send hard ones to the loop.
Honest limits
Agentic RAG adds power and adds ways to fail. These are the main ones.
- More LLM calls mean more cost and delay. Our toy needed 7 calls for one question that classic RAG could not answer at all. The survey lists "computational overhead" and "coordination complexity" among the challenges of agentic RAG.
- Loops that do not end. A grader that never says "enough" keeps the agent searching. Always set a step limit, a token limit and a timeout. The Zephyr run above shows the guard working.
- Grader mistakes. An LLM grader can accept weak evidence or reject good evidence. A wrong "enough" gives a confident wrong answer. A wrong "not enough" wastes calls. Corrective RAG exists because retrieval quality is not reliable.
- Prompt injection through retrieved documents. Prompt injection means text that tries to give the model new instructions. The paper "Not what you've signed up for" (Greshake et al., 2023) shows that attackers can place instructions in data the app is likely to retrieve. OWASP lists indirect prompt injection, where the instructions arrive through external content such as websites or files, as part of its LLM01 prompt-injection risk. In an agent loop the risk is higher, because the model may also call tools. Treat retrieved text as data. Limit what each tool can do, and ask a human before anything risky.
- Evaluation is harder. With classic RAG you can score retrieval and answers separately. With a loop you must also judge the path: did it search the right source, stop at the right time and use sensible queries? Log every step so you can replay failures.
- Our toy is not a benchmark. The rules were written to fit these 13 documents. It shows the control flow, not how an LLM would perform.
Project ideas for students
- Add a real LLM to the toy loop. Replace one rule function at a time with a call to a small local or hosted model. Compare the LLM's planner and grader against the rules on 20 questions you write yourself. Count where they disagree.
- Build a routing RAG over your college handbook. Use two tools, a document search and a small SQL table of dates. Let the model pick the tool. Measure how often it picks the right one on 30 test questions.
- Reproduce a pattern from a paper on a small scale. Implement a CRAG-style evaluator that scores each retrieved passage and falls back to a second source when all scores are low. Report accuracy and average LLM calls per question, before and after.
For each project, write down your test questions first. Then show a trace for one success and one failure. That is what a reviewer or interviewer wants to see.
Common interview questions
- What is the difference between classic RAG and agentic RAG?
- Give an example of a question one-shot RAG cannot answer. (A multi-hop question.)
- What does a grader do, and what happens when it is wrong?
- When would you choose Adaptive-RAG-style routing over a full agent loop?
- How can a retrieved document attack your agent?
FAQ
What is agentic RAG in simple words?
Agentic RAG is RAG where the model runs the search. It decides whether to search, writes the query, reads the results and checks if they are enough. If they are not, it searches again with a better query. Classic RAG does exactly one search and then answers, whatever the results look like.
What is the difference between RAG and agentic RAG?
RAG follows a fixed path: retrieve once, then generate. Agentic RAG lets the model choose the path. It can skip retrieval, pick between sources, grade the evidence, rewrite the query and loop. The price is more model calls, more delay and behaviour that is harder to test.
Is agentic RAG better than traditional RAG?
Not always. It helps on multi-hop and ambiguous questions where one search misses facts. On simple lookups it adds cost and delay for no gain. Measure classic RAG on your own test questions first. Then add agentic steps only for the question types that fail.
What are examples of agentic RAG?
Research examples include Self-RAG, Corrective RAG, Adaptive-RAG and IRCoT, each in a paper linked above. In practice, a support bot that picks between a help-centre search and an order database, then retries with a rewritten query, is agentic RAG. So is the toy loop in this post.
How do I build agentic RAG with LangGraph?
Make each step a node: planner, retrieve, grader, rewriter and answer. Add a conditional edge after the grader that either goes to the answer or back through the rewriter to retrieve. Count the rounds in the state and stop at a limit. The graph in this post follows exactly that shape.
When should I not use agentic RAG?
Skip it when most questions are single-fact lookups, when you need fixed cost and latency, or when you have no way to measure quality. Also skip it when retrieval itself is weak. Fix chunking, hybrid search and reranking first, because a loop will only repeat bad searches.
Does agentic RAG fix hallucinations?
No. It can reduce them by checking evidence before answering, but a wrong grader still lets bad evidence through. The model can also still invent details when writing. Keep citations, test with questions that have known answers, and make the system say "not found" when evidence is missing.
Keep going
- RAG vs MCP vs AI agents: how retrieval, tool protocols and agent loops fit together.
- RAG interview questions: 30 questions with strong answers, including Self-RAG and CRAG.
To build agent systems like this with mentor feedback on real projects, look at the AI Engineering program.
