Agentic RAG: an agent that plans, searches and checks its own work
Agentic RAG lets a language model plan, pick between several sources, read what comes back and search again until it has enough. Use it for research-style questions that one lookup cannot answer.
Agentic RAG in 60 seconds
- What: an LLM-driven loop that plans, chooses a source or tool, reads the result, judges whether it has enough, and repeats if not.
- Why: some questions need several lookups across different stores, and the second lookup depends on what the first one found.
- Sources: a vector index for documents, a SQL database for exact figures, and web or API search for fresh facts.
- Cost: many model calls per question, so latency and spend are higher and less predictable than a single pass.
- Controls: a step budget, a cost budget, a timeout and a trace of every step are required, not optional.
Where this type fits
Agentic RAG belongs to the multi-step family, alongside branched, adaptive and speculative RAG. These types spend extra model calls to handle questions that a single retrieval cannot answer. Agentic RAG is the most open-ended of them, because the model, not the developer, decides how many steps to take. See the overview of RAG types for the whole map.
The problem it solves
A single-pass system retrieves once and answers. That works when the answer sits in one or two passages. It fails when the question is really several questions chained together. Take 'Which of our enterprise customers renewed last quarter, and did any of them raise a support ticket about the billing change?' The first half lives in a database of contracts. The second half lives in free-text tickets. A single vector search over everything returns a muddle of both, and the model has to guess.
Think of asking a new colleague to prepare a briefing. A weak colleague runs one search, pastes the top results and hands them over. A good colleague starts with a plan, opens the contracts system for the exact list, uses that list to search the tickets, notices that two customers are missing from the ticket data, and checks another source before writing anything. Agentic RAG tries to give the model the habits of the good colleague.
The second problem is source choice. Real organisations keep knowledge in many shapes: documents, tables, APIs and the open web. No one retrieval method suits all of them. Embedding search is poor at exact numbers and joins. SQL is poor at fuzzy meaning. An agent can route each sub-question to the store that suits it.
How it works
- Plan: the model reads the question and writes a short plan, or at least decides the next sub-question to answer.
- Choose a tool: it picks one source from a registry, for example vector search, SQL query or web search, and writes the arguments.
- Act: the system runs the tool with a timeout and returns the raw result to the model.
- Observe: the model reads the result and notes what it learned and what is still missing.
- Judge: the model decides whether the evidence is enough to answer. If not, it returns to the plan step with updated notes.
- Stop and answer: when the evidence is enough, or a budget runs out, the model writes the answer from its notes and cites the sources it used.
The loop is the whole idea. The planner and the judge are usually the same model prompted in different ways. The evidence notebook is a running list of facts with their sources. It matters because the model should answer from the notebook, not from the raw tool output of every step, which would overflow the context window.
The stop condition is where most designs differ. A safe design stops on any of three triggers: the judge says the evidence is enough, the step budget is used up, or the cost budget is used up. When a budget stops the loop, the answer should say what is still unknown rather than pretend to be complete.
A worked example
Acme Logistics runs an internal assistant. A manager asks: 'Which enterprise customers renewed last quarter, and did any complain about the new billing format?' Here is one request, step by step.
- Plan: the model writes two sub-goals: (1) list enterprise renewals in the last quarter, (2) find billing complaints from those customers.
- Step 1, SQL tool: it writes a read-only query against the contracts table. The result is three rows: Northwind Foods, Larkspur Health and Dovetail Freight.
- Observe: the notebook records the three names and the source, 'contracts table, renewals view'.
- Step 2, vector tool: it searches the ticket index with 'billing format complaint' and filters by those three customer ids. Two tickets come back, one from Northwind and one from Dovetail.
- Judge: nothing was found for Larkspur Health. The model is unsure whether that means no complaint or missing data, so it continues.
- Step 3, web or API tool: it queries the customer-success notes API for Larkspur Health and finds a note saying the customer was happy with the new format.
- Judge: enough evidence now. The loop stops after three tool calls.
- Answer: 'Three enterprise customers renewed. Northwind Foods and Dovetail Freight raised billing format tickets (ticket 4412 and 4430). Larkspur Health raised none, and a success note says they were satisfied.' Each claim carries its source.
{
'question': 'Enterprise renewals last quarter with billing complaints?',
'steps_used': 3,
'facts': [
{'claim': 'Renewed: Northwind Foods, Larkspur Health, Dovetail Freight', 'source': 'contracts.renewals'},
{'claim': 'Ticket 4412 (Northwind) complains about invoice layout', 'source': 'tickets/4412'},
{'claim': 'Ticket 4430 (Dovetail) complains about invoice layout', 'source': 'tickets/4430'},
{'claim': 'Larkspur note: satisfied with new format', 'source': 'cs-notes/larkspur'}
],
'open_questions': []
}Building it
The sketch below shows the control loop. The model call, the tools and the notebook are placeholders. The part worth studying is the set of limits around the loop: a step cap, a cost cap, a per-tool timeout and a trace.
import time
MAX_STEPS = 6 # hard cap so a confused agent cannot loop forever
MAX_COST = 0.50 # in currency units, checked before every model call
TOOL_TIMEOUT_S = 10
# Placeholders: llm.generate, vector_store, sql_db and web_search stand in for real components.
TOOLS = {
'vector': lambda q: vector_store.search(embed(q), top_k=5),
'sql': lambda q: sql_db.run_readonly(q),
'web': lambda q: web_search(q),
}
def agentic_rag(question, user):
notebook, trace, cost = [], [], 0.0
for step in range(MAX_STEPS):
if cost >= MAX_COST:
break # stop on money before stopping on quality
# The planner sees only the notebook, not raw tool output, to keep context small.
decision = llm.generate(plan_prompt(question, notebook, list(TOOLS)))
cost += decision.cost
if decision.action == 'answer':
break
tool = TOOLS.get(decision.tool)
if tool is None:
notebook.append('Unknown tool requested; ignored.')
continue # never execute a tool name the model invented
started = time.time()
try:
# Tools run with the user's permissions so the agent cannot see more than the user can.
raw = run_with_timeout(tool, decision.query, TOOL_TIMEOUT_S, user=user)
except TimeoutError:
raw = 'tool timed out'
# A short summary goes into the notebook; the full result stays in the trace.
summary = llm.generate(summarise_prompt(question, raw))
cost += summary.cost
notebook.append({'tool': decision.tool, 'query': decision.query,
'finding': summary.text, 'sources': extract_sources(raw)})
trace.append({'step': step, 'tool': decision.tool, 'query': decision.query,
'seconds': round(time.time() - started, 2), 'cost': cost})
exhausted = (step == MAX_STEPS - 1) or cost >= MAX_COST
final = llm.generate(answer_prompt(question, notebook, budget_exhausted=exhausted))
return {'answer': final.text, 'trace': trace, 'budget_exhausted': exhausted}import re
FORBIDDEN = re.compile(r'\b(insert|update|delete|drop|alter|grant|truncate)\b', re.I)
def run_readonly(sql, max_rows=50):
# Reject anything that is not a single SELECT. The database user should also be read-only,
# because a text filter alone is not a security boundary.
if ';' in sql.strip().rstrip(';') or FORBIDDEN.search(sql) or not sql.strip().lower().startswith('select'):
raise ValueError('only a single SELECT is allowed')
return db.execute(sql, limit=max_rows) # placeholder database handleDesign decisions
- Tool registry: keep a small, typed set of tools, each with a one-line description and a schema. Start with three or four. Every extra tool makes the model's choice harder and adds a new failure path.
- Step and cost budgets: default to 5 or 6 steps and a per-request spend cap. Stop on whichever hits first. Without caps, one ambiguous question can cost more than a hundred ordinary ones.
- Access control: run each tool as the asking user, not as a service account. An agent with broad credentials will eventually retrieve something the user should not see. See security.
- Latency: run independent tool calls in parallel when the plan allows, stream progress to the user, and set a total deadline. Users tolerate a visible 'searching contracts' better than a silent wait.
- Failure handling: treat tool errors and timeouts as observations the model can react to, retry reads at most once, and never retry writes. Make any write tool idempotent. See idempotency.
- Observability: store a trace per request with every plan, tool call, result size, cost and the stop reason. Agents fail in ways a final answer cannot reveal. See evaluation and observability.
- Orchestration: use a workflow or orchestrator to run the loop so that state, retries and deadlines live in code you control, not in the prompt.
Measuring it
- Answer correctness: score final answers against a reference set of multi-hop questions, by human review or a grader model checked against human labels. Report it per question type, not as one average.
- Faithfulness: the share of claims in the answer that are supported by the notebook sources. Split the answer into claims and check each against the cited text.
- Tool selection accuracy: on questions where you know the right source, count how often the first tool call was that source. Low scores point at weak tool descriptions.
- Steps and cost per question: track the median and the 95th percentile. The tail matters more than the median because loops fail at the tail.
- Budget exhaustion rate: the share of requests that ended because a budget ran out. A high rate means the plans are poor or the budgets are too low.
- Recovery rate: among requests where the first retrieval was poor, the share that still ended correct. This is the benefit that justifies the loop.
def summarise(runs):
# runs: list of dicts with trace, budget_exhausted, correct (bool from your grader)
steps = sorted(len(r['trace']) for r in runs)
p95 = steps[int(0.95 * (len(steps) - 1))]
return {
'accuracy': sum(r['correct'] for r in runs) / len(runs),
'median_steps': steps[len(steps) // 2],
'p95_steps': p95,
'budget_exhausted_rate': sum(r['budget_exhausted'] for r in runs) / len(runs),
}When to use it, and when not to
| Situation | Use this type? | Why |
|---|---|---|
| Research-style questions that need several lookups | Yes | The second lookup depends on the first result, which a single pass cannot do. |
| Knowledge spread across documents, tables and live APIs | Yes | The agent can route each sub-question to the store that suits it. |
| Predictable FAQ questions with one clear source | No | Simple RAG answers faster and cheaper, with fewer ways to fail. |
| Strict latency target under two seconds | No | Several sequential model calls rarely fit inside that budget. |
| Regulated answers that must be reproducible | Only with care | The path varies between runs, so you need fixed tools, logging and sign-off on the plan. |
| Mixed traffic where most questions are easy | Partly | Route easy questions to a cheaper type and send only hard ones to the agent. See adaptive RAG. |
Trade-offs
| Dimension | Effect | What to do about it |
|---|---|---|
| Quality | Higher on multi-hop questions because the agent can recover from a poor first search | Measure recovery rate and keep an evaluation set of hard questions. |
| Latency | Each step adds a model call and a tool call, so waits of ten seconds or more are normal | Parallelise independent calls, stream progress and cap total time. |
| Cost | Spend varies widely per question and can multiply with each extra step | Set a per-request cost cap and alert on the 95th percentile. |
| Complexity | More moving parts: tools, permissions, budgets, traces | Start with two tools and add more only when evaluation shows a gap. |
| Failure modes | Loops, wrong tool choice, invented tool names, answers built on one weak source | Hard caps, tool allow-lists, a judge step and full traces. |
Compared with related types
Branched RAG also uses several retrievals, but it fixes the plan up front: split the question, run the branches in parallel, merge. Agentic RAG decides each step after seeing the last one, which is more flexible and slower. Adaptive RAG is a router that picks how much work to do. It can sit in front of an agent so that only hard questions reach it.
Corrective RAG adds a grading step and a fallback to one retrieval. You can see agentic RAG as corrective RAG with the loop left open and several tools to choose from. If your problem is only 'sometimes the first retrieval is poor', corrective RAG is usually the cheaper answer.
What this means for your role
Common mistakes
Further reading
- Types of agents, for the planning and acting patterns that agentic RAG borrows.
- Types of orchestrators, for ways to run and supervise the loop.
Agentic RAG is a research habit given to a model: plan, look, check, look again. It pays off when questions are hard, and it stays safe only when budgets, permissions and traces are built in from the start.