Agentic RAG: Planning, Tools and Multi-Step Retrieval
A retrieval pipeline executes one fixed recipe; an agentic system decides, at runtime, what to do next. It can reformulate a question after a poor first search, fan out sub-queries across a taxonomy, read a document and realize it needs a different one, call a calculator or a database when arithmetic would be unreliable, and stop when the evidence is sufficient rather than when a stage finished. That flexibility is the entire value proposition, and it is also where the risk lives: every additional decision is an opportunity to loop, to spend, or to answer from the wrong document with total confidence. Designing agentic RAG means designing the policy â which actions exist, what the state holds, and what constraints bound the whole episode.
From Fixed Pipeline to Policy
The shift is easiest to see as a table. Static retrieval has a shape decided at design time; agentic retrieval has a shape decided per question, within a budget.
| Concern | Pipeline RAG | Agentic RAG |
|---|---|---|
| Query handling | One rewrite, one search | Reformulate, decompose, re-search on evidence |
| Stop condition | Stages completed | Evidence sufficient or budget exhausted |
| Tool use | Retrieval only | Retrieval, calculators, SQL, browsers, APIs |
| Failure handling | Degrade quietly | Detect, retry with a different route |
| Cost profile | Predictable per request | Variable, needs hard caps |
| Debugging | Trace of fixed stages | Trajectory of decisions to replay |
Most production systems end up hybrid. A classifier routes simple questions down the cheap fixed path and reserves the agent for questions that need it, which keeps latency and cost bounded while preserving the capability for the hard tail. The classifier itself is trained from logs â questions the pipeline answered with citations and user approval never need the expensive route.
The Loop That Keeps Its Promises
The core loop is small; the discipline is in what it carries. A state object records the question, findings, citations and actions taken so far. A policy decides the next action from that state. A budget enforces hard ceilings on steps, tokens and wall-clock time. And a finalizer refuses to produce an answer unless the state contains supporting evidence, which converts "the model felt confident" into "the trace shows citations."
import time
from dataclasses import dataclass, field
@dataclass
class Episode:
question: str
findings: list = field(default_factory=list)
citations: list = field(default_factory=list)
actions: list = field(default_factory=list)
started: float = field(default_factory=time.perf_counter)
@property
def elapsed(self) -> float:
return time.perf_counter() - self.started
def evidence_enough(self, min_sources: int = 2) -> bool:
return len({c["doc_id"] for c in self.citations}) >= min_sources
def run_agent(question: str, policy, tools, budget) -> dict:
state = Episode(question=question)
while True:
if len(state.actions) >= budget.max_steps:
state.actions.append({"action": "stop", "reason": "step budget"})
break
if state.elapsed > budget.max_seconds:
state.actions.append({"action": "stop", "reason": "time budget"})
break
action = policy.next(state)
state.actions.append(action)
if action["action"] == "finish":
break
if action["action"] == "search":
hits = tools.search(action["query"], k=action.get("k", 6))
state.findings.extend(hits)
state.citations.extend(
{"doc_id": h["id"], "span": h["text"][:200]} for h in hits[:3]
)
elif action["action"] == "read":
state.findings.append(tools.read(action["doc_id"], action.get("page")))
elif action["action"] == "compute":
state.findings.append({"calc": tools.calculate(action["expr"])})
if not state.evidence_enough():
return {"answer": None, "status": "insufficient_evidence", "trace": state.actions}
return {"answer": compose(state), "status": "grounded", "trace": state.actions}
The policy can be a model prompted with the current state, or plain code with rules â start with code. Rules make the first version debuggable, and once you have a thousand logged trajectories you will know which decisions genuinely need judgment rather than which ones merely look like they might.
Tools Worth Giving the Agent
Tool design is prompt design with consequences. A tool that returns too much text floods the context and degrades everything after it; a tool with an ambiguous name gets called for the wrong job; a tool without an error contract produces stack traces that the model then invents explanations for.
import json
TOOLS = [
{"name": "search_docs", "description": "Keyword and vector search over internal docs. Returns id, title, score, snippet.",
"parameters": {"type": "object", "properties": {"query": {"type": "string"}, "k": {"type": "integer", "maximum": 10}}, "required": ["query"]}},
{"name": "read_doc", "description": "Fetch one document section by id. Returns plain text, max 2000 characters.",
"parameters": {"type": "object", "properties": {"doc_id": {"type": "string"}, "section": {"type": "integer"}}, "required": ["doc_id"]}},
{"name": "lookup_order", "description": "Query the order database by order id. Returns status, dates, line items.",
"parameters": {"type": "object", "properties": {"order_id": {"type": "string"}}, "required": ["order_id"]}},
{"name": "finish", "description": "End the episode with a grounded answer and the citations used.",
"parameters": {"type": "object", "properties": {"answer": {"type": "string"}, "citations": {"type": "array", "items": {"type": "string"}}}, "required": ["answer", "citations"]}},
]
def dispatch(name: str, args: dict, registry: dict) -> str:
"""Return structured JSON even on failure so the model can adapt."""
fn = registry.get(name)
if fn is None:
return json.dumps({"error": "unknown_tool", "name": name})
try:
return json.dumps({"ok": True, "result": fn(**args)})
except Exception as exc:
return json.dumps({"error": "tool_failed", "detail": str(exc)[:300]})
def tool_errors(response: str) -> bool:
try:
return "error" in json.loads(response)
except (ValueError, TypeError):
return True
Return errors as structured data and the model can correct course â retry with different arguments, choose another tool, or admit defeat. Let exceptions escape as raw text and it will produce confident nonsense about a tool that never ran.
Containing Failures Before They Reach Users
Autonomous loops fail in characteristic ways: they reissue a search that already failed, chase an irrelevant entity across six steps, or terminate early because a document merely mentioned the right nouns. Containment is layered rather than singular. Hard budgets on steps, tokens and seconds cap the blast radius of any runaway. A no-progress rule â two consecutive actions that add no new document identifiers â cuts loops that budgets alone would allow to burn. Deduplication of queries prevents the classic oscillation between two phrasings of the same dead end.
Permissions deserve their own layer. An agent inherits the tools you give it, and a search tool without access control turns one compromised prompt into an organization-wide read. Scope tools per user at the tool boundary, not in the instructions, and log every call with the identity that produced it.
| Failure mode | Symptom in logs | Containment |
|---|---|---|
| Search oscillation | Same query family repeated | Query deduplication, no-progress rule |
| Context flooding | Findings grow, quality drops | Per-tool return limits, summarization |
| Premature finish | One weak source, confident answer | Minimum distinct source requirement |
| Tool misuse | Wrong tool for the question | Tight tool descriptions, few-shot examples |
| Budget overrun | Steps hit the ceiling with no answer | Graceful degradation to the fixed pipeline |
Graceful degradation matters more than it sounds. When the agent runs out of budget, falling back to the standard pipeline and saying the answer is partial is far better than either failing loudly or fabricating closure.
Evaluating Trajectories, Not Just Answers
Answer-level metrics miss everything that makes agentic systems expensive. A correct response produced in nine steps with three redundant searches is a different product from the same response in two steps, and the difference shows up on the invoice and in tail latency. Evaluation therefore works on both artifacts: the final answer scored for groundedness and completeness, and the trajectory scored for efficiency.
Track answer correctness against a labeled set, citation precision â the share of cited spans that actually support their claim â steps and cost per resolved question, tool error rate, and the fallback rate that reveals how often the agent could not do the job. Compare each against the fixed pipeline on the same questions, because the agent's entire justification is the incremental quality it buys on the hard subset.
One discipline pays off repeatedly: keep trajectories as replayable fixtures. Given a saved sequence of tool responses, you can re-run a new policy deterministically and see whether it makes better decisions, without paying for live searches or contending with corpus drift. Offline policy improvement of this kind is how agentic systems get cheaper over time instead of merely getting longer.
When the Pipeline Still Wins
Plenty of workloads never justify an agent. Factual lookup over a stable corpus, classification, and summarization of a single document all have fixed shapes, and adding decisions adds variance where none is wanted. Agents also struggle when tools are slow or rate-limited, because their advantage depends on being able to try again quickly, and when the cost of a wrong intermediate step is severe â a domain where a single hallucinated entity can steer six subsequent actions.
The mature architecture is a router: a cheap classifier sends each question to the fixed pipeline, a light multi-query variant, or the full agent, based on observed difficulty. Everything above this lesson â query rewriting, reranking, critique â still applies on the agent's internal steps. Agentic RAG is retrieval engineering with a policy on top, not a replacement for doing the fundamentals well.
Common Mistakes
Giving the agent unbounded steps and hoping it converges
Fix: Set hard caps on steps, tokens and time, plus a no-progress rule
Scoping access control in the prompt
Fix: Enforce permissions at the tool boundary and log identity per call
Evaluating only the final answer
Fix: Score trajectories for steps, cost, tool errors and citation precision
Starting with a model-driven policy you cannot debug
Fix: Use rule-based policies first; promote to model decisions with logged evidence
Routing every question to the agent
Fix: Classify difficulty and reserve autonomy for the questions that need it
Key Takeaways
- Agentic RAG trades fixed shape for a runtime policy inside explicit budgets
- Structured tool errors let the model recover; raw exceptions make it fabricate
- Containment is layered: caps, no-progress rules, dedupe and permission scopes
- Evaluate trajectories as well as answers, and replay them offline for cheap iteration
- Most systems end up hybrid, with a router sending easy questions to the cheap path