On this page
Agentic RAG is retrieval-augmented generation where the model controls the retrieval: it decides what to search for, inspects what comes back, and searches again until it has enough evidence to answer. Classic RAG runs one fixed retrieval step before generation. Agentic RAG turns retrieval into a loop, which handles multi-part questions, ambiguous queries, and heterogeneous sources far better, at the cost of latency, tokens, and some predictability.
Key takeaways
- Classic RAG fails quietly when the first retrieval misses. Agentic RAG lets the model notice the miss and try again with a better query or a different source.
- The core pattern is simple: give the model search tools and a reading tool, let it iterate within a budget, and require citations in the final answer.
- Don’t make everything agentic. A router that sends simple lookups down a fixed pipeline and complex questions to the agent loop often gives the best cost-quality balance.
- Retrieval quality still matters most. An agent cannot reason its way past a broken index, bad chunking, or missing metadata.
- Evaluate retrieval and answering separately. You need to know whether a wrong answer came from not finding the evidence or from misreading it.
Where classic RAG breaks
The standard RAG pipeline looks like this:
user question --> embed --> top-k vector search --> stuff chunks into prompt --> answer
It is fast, cheap, and easy to reason about. For “What is our parental leave policy?” against a well-chunked HR handbook, it works well.
It struggles in predictable ways:
- Multi-hop questions. “Which of our enterprise customers are on contracts that renew before the price change takes effect?” requires finding the price change date first, then querying contracts. One embedding of the whole question retrieves neither well.
- Vocabulary mismatch. The user says “PTO” and the documents say “annual leave.” Dense retrieval helps, but not always.
- Wrong source. The answer lives in a SQL table or a ticketing system, not the document index.
- Silent misses. When top-k returns irrelevant chunks, the model often answers anyway, confidently, from whatever it was given.
The last one is the most dangerous. Classic RAG has no step where anything checks whether the retrieved context actually answers the question.
What makes RAG agentic
Agentic RAG moves retrieval decisions into the model’s loop. Instead of one pre-planned search, the model can:
- Decompose the question into sub-questions.
- Choose a source for each: vector index, keyword search, SQL, an API.
- Formulate queries in the vocabulary of the target source.
- Judge whether the results are relevant and sufficient.
- Retrieve again with a refined query, or read a full document instead of a chunk.
- Answer with citations once it has enough, or say it couldn’t find the answer.
This is the ReAct pattern from the ReAct paper, interleaving reasoning and actions, applied to retrieval. In the vocabulary of Anthropic’s Building effective agents, it is an agent: the model directs its own process and tool usage rather than following a predefined path.
A working implementation
The implementation below uses the Anthropic Python SDK’s tool-use interface, but the structure transfers to any provider with function calling. It gives the model three tools: hybrid search over documents, a full-document reader, and a read-only SQL tool. It enforces a step budget and requires citations.
import json
import os
import anthropic
client = anthropic.Anthropic()
MODEL = os.environ["AGENT_MODEL"] # pin a model ID in config, not in code
MAX_STEPS = 8
TOOLS = [
{
"name": "search_docs",
"description": (
"Hybrid keyword + semantic search over internal documents "
"(policies, contracts, runbooks). Returns up to 8 passages with "
"doc_id, title, updated_at, and a ~300-word excerpt. Use short, "
"specific queries. Try synonyms if the first search misses."
),
"input_schema": {
"type": "object",
"properties": {
"query": {"type": "string"},
"doc_type": {
"type": "string",
"enum": ["policy", "contract", "runbook", "any"],
},
},
"required": ["query"],
},
},
{
"name": "read_doc",
"description": (
"Read a full document by doc_id. Use when an excerpt looks relevant "
"but is cut off, or when you need surrounding context such as "
"definitions or exceptions."
),
"input_schema": {
"type": "object",
"properties": {"doc_id": {"type": "string"}},
"required": ["doc_id"],
},
},
{
"name": "query_accounts",
"description": (
"Run a read-only SQL SELECT against the accounts warehouse. "
"Tables: accounts(id, name, tier, region), "
"contracts(account_id, start_date, renewal_date, arr_usd). "
"Returns at most 50 rows."
),
"input_schema": {
"type": "object",
"properties": {"sql": {"type": "string"}},
"required": ["sql"],
},
},
]
SYSTEM = """You answer questions for internal staff using company sources only.
Process:
- Break multi-part questions into sub-questions and retrieve evidence for each.
- If search results are off-topic, reformulate. Do not answer from weak evidence.
- Prefer the most recently updated document when sources conflict, and say so.
- Cite every factual claim as [doc_id] or [sql].
- If you cannot find sufficient evidence, say what you searched and what is missing.
"""
def run_tool(name: str, args: dict) -> str:
if name == "search_docs":
hits = search_index(args["query"], doc_type=args.get("doc_type", "any"), k=8)
return json.dumps(hits)
if name == "read_doc":
return fetch_document(args["doc_id"], max_chars=20_000)
if name == "query_accounts":
return run_readonly_sql(args["sql"], row_limit=50)
return f"Unknown tool: {name}"
def answer(question: str) -> str:
messages = [{"role": "user", "content": question}]
for _ in range(MAX_STEPS):
response = client.messages.create(
model=MODEL,
max_tokens=2048,
system=SYSTEM,
tools=TOOLS,
messages=messages,
)
messages.append({"role": "assistant", "content": response.content})
if response.stop_reason != "tool_use":
return "".join(b.text for b in response.content if b.type == "text")
tool_results = []
for block in response.content:
if block.type == "tool_use":
try:
output = run_tool(block.name, block.input)
is_error = False
except Exception as exc: # surface errors to the model, don't crash
output, is_error = f"Tool error: {exc}", True
tool_results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": output,
"is_error": is_error,
})
messages.append({"role": "user", "content": tool_results})
return (
"I couldn't gather enough evidence within the search budget. "
"Try narrowing the question or naming the relevant document."
)
search_index, fetch_document, and run_readonly_sql are your own functions. The SQL one deserves real care: run it against a read-only replica with a database role that can only SELECT from an allow-listed set of views, and enforce a statement timeout. Never rely on the prompt to keep the model from writing DELETE.
A few design choices in this code are worth calling out:
- Search returns metadata, including
updated_at, so the model can resolve conflicts between versions. - Reading is a separate tool. Chunks are good for finding things. Full documents are often needed for understanding them, especially when exceptions appear two pages after the rule.
- The budget is explicit.
MAX_STEPScaps cost and latency, and the fallback message is honest rather than a guess. - Errors go back to the model. A malformed SQL query becomes feedback, and the model can usually fix it on the next turn.
Our post on tool design for AI agents covers how to write descriptions like these so the model picks the right tool.
Patterns worth knowing
“Agentic RAG” covers a range of designs. Here are the ones we see most often, from least to most autonomous.
| Pattern | How it works | Good for | Trade-off |
|---|---|---|---|
| Query rewriting | LLM rewrites the query once before a fixed retrieval | Vocabulary mismatch, conversational follow-ups | One extra call; no recovery from misses |
| Routed RAG | Classifier sends the question to the right index or pipeline | Many distinct sources with clear boundaries | Misroutes fail silently |
| Corrective RAG | Grade retrieved chunks; if weak, re-query or fall back to another source | Reducing confident wrong answers | Grading adds latency and its own errors |
| Iterative agent | Model loops over search and read tools until satisfied | Multi-hop, exploratory, cross-source questions | Highest cost and variance |
| Multi-agent research | Orchestrator spawns parallel sub-agents per sub-question | Broad research over large corpora | Hard to evaluate; coordination overhead |
The first three are really workflows: the control flow is fixed in code, with LLM calls at specific steps. Only the last two are agents in the strict sense. That distinction matters because workflows are cheaper and easier to test. Use the least autonomous pattern that handles your real questions.
A practical hybrid: route first
A design that works well in production puts a cheap classifier in front:
question
|
v
[router] --simple lookup--> fixed RAG pipeline --> answer
|
+--multi-part / cross-source / low-confidence--> agent loop --> answer
Most traffic in a typical internal knowledge assistant is simple lookups. Sending those through a single retrieval keeps median latency and cost low, while hard questions still get the full loop. The router can be a small model or even a rules layer, and it should fall back to the agent when uncertain.
Retrieval quality still decides the outcome
Agentic loops make good retrieval better. They do not rescue bad retrieval. Before adding agency, fix the foundations:
- Hybrid search. Combine keyword (BM25 or similar) with dense vectors. Keyword search catches exact identifiers, product codes, and names that embeddings blur.
- Reranking. A cross-encoder reranker over the top candidates usually improves precision more than tuning embedding models.
- Chunking that respects structure. Split on headings and sections, not fixed character counts. Keep tables intact.
- Contextual chunk headers. Prepend each chunk with its document title and section path so a chunk saying “this does not apply to contractors” carries its subject with it.
- Metadata filters. Document type, owner, date, and access level let the agent narrow searches and let you enforce permissions.
- Permission-aware retrieval. Filter results by the requesting user’s access before they reach the model. An agent that can search everything will eventually quote something the user shouldn’t see.
The last point is a security requirement, not an optimization. Retrieved documents are also an injection vector: a document containing instructions can steer the agent, which is why the OWASP Top 10 for LLM Applications treats indirect prompt injection as a first-order risk.
Evaluating agentic RAG
Because the system has more moving parts, end-to-end accuracy alone won’t tell you what to fix. Measure at three levels.
Retrieval
Build a set of questions with known supporting documents. Measure whether the agent’s retrieved set, across all its searches, includes the gold documents (recall), and how much irrelevant material it pulled in. If recall is low, fix the index before touching prompts.
Answer faithfulness
Check that each claim in the answer is supported by a cited source. An LLM judge with a rubric can do this at scale, calibrated against human labels on a sample. Unsupported claims are the failure mode that destroys user trust fastest.
Process
Track steps per question, tokens per question, latency, and how often the agent hits the budget. A rise in average steps after a content migration, for example, often signals that the index has drifted from how people ask questions.
Also include questions that have no answer in your corpus. The correct behavior is to say so. Many systems that score well on answerable questions fail badly here.
For a broader framework, see how to evaluate AI agents.
Cost and latency controls
Agentic RAG spends more per question than a single-shot pipeline. Keep it bounded:
- Cap steps and total tool-output tokens per question.
- Truncate or summarize long tool results before they enter context. A 20,000-character document read is useful once, but it shouldn’t ride along for six more turns.
- Run independent sub-queries in parallel when the model issues multiple tool calls in one turn.
- Cache search results for repeated queries within a session.
- Use the router pattern so simple questions never enter the loop.
Managing what stays in the context window across turns is its own discipline, covered in our guide to context engineering.
FAQ
Is agentic RAG always better than classic RAG?
No. For single-hop lookups against a well-built index, classic RAG is faster, cheaper, and just as accurate. Agentic RAG pays off on multi-part questions, cross-source questions, and corpora where first-pass retrieval often misses. Many production systems use both behind a router.
Do we still need a vector database?
Usually yes, but it becomes one tool among several rather than the whole system. Many teams find hybrid search with keyword and vector retrieval outperforms either alone. Some corpora, like structured records or code, are better served by SQL or grep-style search tools.
How do we stop the agent from looping forever?
Enforce a hard step budget and a token budget in code, not in the prompt. When the budget runs out, return an honest “insufficient evidence” response along with what was searched. Track how often this happens, because frequent budget exhaustion usually points to retrieval gaps.
How does agentic RAG handle access control?
The same way any retrieval system should: filter by the end user’s permissions inside the retrieval tools, before results reach the model. Never give the agent a service account that can read everything and rely on the prompt to withhold sensitive content.
Working with TechnoKeen
We build retrieval systems and agent loops for teams whose knowledge lives across documents, databases, and SaaS tools, with evals that separate retrieval failures from reasoning failures. If your RAG system is answering confidently and wrongly, talk to us, or check your starting point with our agent readiness assessment.
- #agentic RAG
- #retrieval augmented generation
- #search
- #agent architecture
TechnoKeen Engineering
TechnoKeen is an enterprise agentic AI company. Our engineers design, deploy, and govern AI agents for organizations in regulated and complex industries, and share what we learn in the field.
About TechnoKeen →