Skip to main content

An intro to agentic RAG

An introduction to agentic RAG: retrieval inside an agent loop, core architecture components, worked Python examples traced with W&B Weave, and when not to use it.
Last updated: July 28, 2026
Run a traditional RAG pipeline against a hard query and the problem agentic RAG solves becomes obvious: the first retrieved chunks are not quite right, the model generates anyway, and the answer is confidently incomplete. There is no second pass, no mechanism to catch the gap, and no path to a better result short of re-running the whole thing with a different query.
Agentic RAG addresses that by turning retrieval into a loop. An AI agent controls when to search, which sources to use, whether the evidence is sufficient, and when to stop. When the first retrieval pass comes back incomplete, the agent identifies what is missing, forms a more targeted query, and tries again. The result is a system that can handle multi-hop questions, route across different knowledge sources, and recover from poor retrieval instead of propagating it silently.
That flexibility comes with real costs: more loop iterations mean more latency, more model calls mean more spend, and an adaptive loop produces execution paths that are harder to predict and audit than a fixed pipeline. This article is a mechanism-first look at how the loop works, what it looks like when it breaks, and how to decide whether your problem actually needs it.


What agentic RAG is, and what it is not

In agentic RAG, an agent decides when, where, and how to retrieve content before generating an answer. The retrieval step is no longer a one-shot function call that fires before the model; it becomes a policy the agent can invoke repeatedly, with different queries and different tools, while accumulating evidence across multiple turns.
The key shift is from a fixed pipeline to an adaptive loop. In standard RAG, retrieval runs in one direction: embed the query, return chunks, pass them to the model. Whatever the search returns, the model works with it. There is no mechanism to inspect those results, judge their relevance, or try a different approach. In agentic RAG, retrieved content becomes part of the agent's working state. The agent reasons over that content, identifies gaps, forms new queries, and calls different tools before committing to an answer.
What it is not is worth being explicit about. Adding a chat interface to a RAG pipeline does not make it agentic. Writing a longer system prompt with instructions about retrieval does not make it agentic. Agentic RAG requires the system to actually make decisions about retrieval dynamically, based on accumulated evidence, with a real feedback loop connecting retrieval outcomes back to the next retrieval decision.

Agentic RAG vs traditional RAG

In traditional RAG, the flow runs once in one direction: the user query gets embedded, the vector store returns the top-k chunks by similarity, those chunks get assembled into a prompt, and the model generates. The entire process is a function call with no loop and no recovery path. If the retrieval was poor, the model either hallucinates, produces a vague answer, or, if you have guardrails, declines to respond. None of those outcomes feed back into a better retrieval attempt.
That architecture works well when queries are predictable and the right answer fits inside a single retrieval window. It starts failing when queries require information from multiple sources, when the relevant content is scattered or contradictory, when the right source depends on what the initial search returns, or when the question itself needs decomposition before any retrieval can be useful.
Agentic RAG addresses those failure modes by adding a decision loop. The agent can decompose a complex query into sub-queries, route each to a different source, inspect the results, detect gaps in the evidence, refine the approach, and repeat until the evidence is sufficient or a budget runs out.
Table by Author. Key design differences between traditional RAG and agentic RAG across six dimensions. Every agentic advantage comes from the loop, and so does the added cost, latency, and unpredictability.
The trade-off in that table is the central design tension. Every advantage agentic RAG has over traditional RAG comes from the loop, and the loop is also the source of the additional cost, latency, and unpredictability.

Agentic RAG vs agentic AI, Graph RAG, and agentic graph RAG

These terms overlap enough that separating them before going further avoids confusion later.
Agentic AI is the broader class: any system in which an AI agent plans, acts with tools, maintains state across steps, and pursues a goal without a human directing each action. Agentic RAG is a specific application of that pattern where the primary tool is retrieval. All agentic RAG systems are agentic AI systems, but not all agentic AI systems do RAG.
Graph RAG is a retrieval method, not an agent pattern. It structures the knowledge base as a graph rather than a flat vector index, which means queries can traverse entity relationships, follow provenance chains, and reason over connected information rather than treating each chunk as independent. Graph RAG is useful when the domain has strong relational structure, such as medical ontologies, legal precedent chains, or code dependency graphs. It does not inherently involve an agent loop. You can use graph retrieval in a traditional single-pass pipeline without any agentic behavior.
Agentic graph RAG combines both: a loop-driven agent where at least one of the retrieval tools performs graph traversal or knowledge-graph reasoning. It is what you build when queries require multi-hop reasoning over relational structure and the retrieval decisions themselves need to be adaptive. More powerful than either approach alone, and correspondingly harder to build, debug, and evaluate.
For most teams starting with agentic RAG, adding graph RAG on top of it compounds the complexity without clear benefit unless relational reasoning is actually the bottleneck. Get the basic loop working first.

The central mechanism: retrieval inside an agent loop

The loop has a predictable structure: observe the user input, update state, plan the next action, call a retrieval tool, inspect the evidence, reflect on whether it is sufficient, and either repeat or generate an answer. What makes it agentic is that the agent drives the planning and the reflection, rather than executing a fixed sequence.
In a standard RAG pipeline, the model plays one role: take the retrieved context and generate. In agentic RAG, the model plays two roles. It is both the controller, deciding what to retrieve and whether the result is good enough, and the generator, producing the final answer once the evidence is in place. Some architectures separate these into distinct models, with a smaller or faster model handling orchestration and a more capable one handling generation. The important thing is that both the control logic and the generation are model-driven.
Retrieved content does not just flow through and disappear. It accumulates in the agent's working state alongside the user question, the queries issued so far, the reflection notes, and any citations or constraints. Each retrieval step adds to that state, and each reflection step reads from it. This is what gives the loop coherence across multiple iterations rather than treating each step as independent.
The loop also needs an explicit stopping criterion, because without one it will run until the budget runs out or something fails. Common stopping conditions include the reflection step deciding evidence is sufficient, a maximum number of steps being reached, a cost or latency budget being exhausted, or a policy guard determining that further retrieval is not permitted. In practice you usually want several of these layered: budget constraints as hard stops, the evidence check as the primary exit.

Step-by-step execution trace for a hard query

Consider a query like: "Using the Omdia Report and support messages, identify which agentic RAG rollout risks we should prioritize for latency." This is a hard query because it explicitly references two distinct knowledge sources, requires evidence from both before any synthesis is possible, and cannot be answered from either source alone. The "Omdia Report" here is a placeholder representing any analyst-style document in the corpus; the mechanism is the same regardless of what the actual documents are.
A traditional RAG system would embed the full query, retrieve the top-k chunks by similarity score, and send them to the model. Depending on the index and the query embedding, it might return a chunk from the analyst report, a chunk from support messages, or a mix that misses the most relevant content from one source entirely. The model generates from whatever it received. No second chance.
An agentic RAG system handles it differently. Here is what the trace looks like.
  1. Step 1: initial retrieval. The agent starts with the full question as the first query. The retrieval tool returns a chunk from the analyst report covering governance requirements and citation quality, because that document scores highest on keyword and semantic overlap with the query.
  2. Step 2: reflection. The agent checks accumulated evidence against what the question requires. The question explicitly mentions support messages, but none have been retrieved yet. The reflection step records: "missing: support messages, latency evidence."
  3. Step 3: query refinement. The planning step generates a new query targeting the missing source: "support messages agentic RAG latency complaints."
  4. Step 4: second retrieval. The agent calls the retrieval tool again, this time with the analyst report excluded so it does not return the same document. It retrieves a chunk from support messages describing user complaints about retry loops, latency spikes, and irrelevant citations. That chunk also contains the word "latency," satisfying the latency evidence requirement.
  5. Step 5: reflection again. The evidence now covers both required sources. The reflection step records: "sufficient."
  6. Step 6: synthesis. The agent builds the final answer, citing both sources.
Two retrieval steps, one reflection cycle, one query refinement. That is a minimal trace, but it captures why the loop exists. A single-pass system had no path to the second retrieval.

Core components of an agentic RAG architecture

A practical agentic RAG system has two planes. The retrieval plane indexes and serves knowledge: document stores, vector indexes, keyword indexes, APIs, databases, and any other sources the agent can query. The control plane decides what to do next: the agent orchestrator, state store, planning logic, reflection logic, and evaluation mechanisms.
Not every system needs every component. A minimal agentic RAG can be a single loop function with a state dictionary, a retrieval tool, and a reflection check. What grows from there depends on the complexity of the queries, the diversity of the knowledge sources, and the governance requirements around reliability and auditability.

State, memory, and messages

State is the evolving record of the task. It typically holds the original question and any constraints, the queries issued so far, the retrieved content and source citations, reflection notes produced during the loop, and intermediate decisions the agent made. State is what makes the loop coherent across steps. Without it, each retrieval would be independent and the agent could not reason about what it already knows.
Short-term state lives inside the current task and is discarded when the task completes. Long-term memory persists across tasks and can store user preferences, session history, or domain-specific context the agent should carry forward. Semantic caching sits between the two: it stores results from previous retrievals so the agent can skip a tool call when the evidence already exists.
Messages structure how agents communicate, both within the agent's own reasoning trace and across tool calls or multi-agent handoffs. In tool-calling frameworks, messages are the primary substrate: the agent appends a tool call to the message list, the tool returns a result, and the agent continues reasoning from the updated list. This is the mechanism underlying function calling in most production agentic systems.
State management is also where subtle bugs accumulate. Stale state from a previous task can contaminate a new one if the state store is not properly scoped. Context windows that grow too large cause the model to lose track of constraints from early in the loop. Memory contamination occurs when retrieved content from one source implicitly biases retrieval from another. Provenance tracking is the partial solution: recording which piece of state came from where, so the reasoning path is auditable after the fact.

Retrieval and tool layer

The retrieval layer in agentic RAG is not a single vector database. It is a collection of search tools the agent can choose among: dense vector search for semantic similarity, BM25 or keyword search for exact-match queries, hybrid combinations of both, metadata filters for date or source constraints, SQL queries against structured databases, API calls for live data, graph traversal for relational knowledge, and multimodal retrieval across text, images, tables, or other formats.
Tool routing is what prevents the agent from querying everything on every step. A good router selects the cheapest reliable source for each query type. If the question is about a known product name, keyword search is faster and more precise than dense retrieval. If the question asks about recent events, an API call may be more reliable than a potentially stale vector index. The router makes that selection based on query type, available tools, and cost constraints.
Ranking and reranking also matter here. Initial retrieval by vector similarity returns candidates; a reranker scores those candidates for relevance to the specific query and reorders them before the agent inspects them. Citation tracking records which source each piece of evidence came from, which matters for both answer quality and post-hoc auditing. Source freshness is a concern whenever the corpus is updated regularly: the agent needs to know when an index was last refreshed and whether it can trust that version for time-sensitive queries.

Control layer and agent roles

The control layer is where the intelligence of an agentic RAG system lives. It handles planning (deciding what to retrieve next), routing (choosing which tool to use), reflection (judging whether the evidence is sufficient), and stopping (deciding when to generate rather than retrieve again).
In a single-agent design, one model handles all of these roles. That is the simplest architecture and a sensible starting point. In a supervisor-worker pattern, a planner agent orchestrates a set of specialist agents: one retrieves, one critiques, one synthesizes. In a collaborative multi-agent setup, agents operate in parallel and share state through a common message bus or state store. The right choice depends on how complex the tasks are and how much coordination overhead the system can absorb.
Common agent roles in production systems include the planner (decomposes the query and sets the retrieval strategy), the retriever (executes the tool calls), the critic (reflects on whether evidence meets the requirements), the synthesizer (builds the final answer from accumulated evidence), the verifier (checks citations and factual consistency), the router (selects the appropriate retrieval tool), and the policy guard (enforces access controls and content policies). In practice, a capable model can handle several of these within a single prompt. The role distinctions matter more at the architecture level than at the implementation level.
The engineering concerns around the control layer are primarily about safety and predictability. Tool permissions define which sources each agent can access. Retry limits prevent infinite loops when a tool call fails. Fallback paths define what happens when a tool returns nothing useful. Budget constraints cap total cost or time per query. These are not features you add later. They need to be designed into the loop from the start.

Agentic design patterns that enhance RAG

Four patterns appear consistently across well-designed agentic RAG systems, and they are not mutually exclusive.
  1. Reflection is the pattern of having the agent check its own evidence before committing to an answer. A reflection step reads the accumulated evidence, compares it against the requirements of the question, identifies contradictions or gaps, and returns a judgment: either "sufficient" or a description of what is still missing. A basic implementation is rule-based. A production implementation sends the question, the evidence, and a rubric to a language model and asks it to evaluate. Reflection is what drives additional loop iterations and what prevents the system from generating answers from incomplete retrieval.
  2. Planning is the pattern of decomposing a complex question into sub-queries before retrieval begins. A planner examines the question, identifies the distinct information needs it contains, and generates a retrieval plan: which sources to query, in what order, and with what dependencies. Multi-hop questions, where the answer to step one is needed as input to step two, require dependency-aware planning. The agent cannot retrieve in parallel if the second query depends on what the first one returns.
  3. Tool use in agentic RAG means giving the agent access to more than one retrieval method and letting it choose based on the query type. The agent might have a dense search tool for semantic questions, a keyword tool for exact product names, a SQL tool for structured data, and an API tool for live information. The value is not in having all of these available; it is in the routing logic that selects the right one for each sub-query.
  4. Multi-agent collaboration separates specialist roles across multiple agents when a single controller becomes too brittle for the task. A researcher agent handles retrieval, a critic handles reflection, a synthesizer builds the final answer. The benefit is that each agent can be tuned for its role. The cost is coordination complexity: multi-agent systems are harder to debug, harder to make deterministic, and harder to evaluate than single-agent ones. Use them when you have clear evidence that a single agent is the bottleneck, not as a default architectural choice.

Worked example: a minimal agentic RAG loop in Python

The clearest way to see how the loop works is to run a version with no framework dependencies, no embeddings, and no model API calls. The snippet below uses keyword overlap for retrieval and rule-based checks for reflection. Every step in the loop is visible and inspectable without anything else in the way.
import re

DOCS = [
{
"id": "omdia-report",
"source": "Omdia Report",
"text": (
"Omdia Report: enterprise AI teams adopting Agentic RAG need "
"fresh external content, strong citations, and governance controls."
),
},
{
"id": "support-messages",
"source": "support messages",
"text": (
"Support messages: users complain that agentic workflows can add "
"latency, retry too often, and cite irrelevant content when retrieval fails."
),
},
{
"id": "rag-baseline",
"source": "internal RAG notes",
"text": (
"Traditional RAG is fast and predictable for simple questions, but "
"it struggles with multi-step queries and source selection."
),
},
]

def tokens(text):
return set(re.findall(r"[a-z0-9]+", text.lower()))

def retrieve(query, exclude=None, k=1):
exclude = exclude or set()
q = tokens(query)
scored = []
for doc in DOCS:
if doc["id"] in exclude:
continue
score = len(q & tokens(f"{doc['source']} {doc['text']}"))
if score:
scored.append((score, doc))
return [doc for _, doc in sorted(scored, reverse=True, key=lambda x: x[0])[:k]]

def check_missing(question, evidence):
joined = " ".join(f"{d['source']} {d['text']}" for d in evidence).lower()
missing = []
if "omdia" in question.lower() and "omdia" not in joined:
missing.append("Omdia Report")
if "support messages" in question.lower() and "support messages" not in joined:
missing.append("support messages")
if "latency" in question.lower() and "latency" not in joined:
missing.append("latency evidence")
return missing

def plan_next_query(missing):
if "support messages" in missing:
return "support messages agentic RAG latency complaints"
if "Omdia Report" in missing:
return "Omdia Report Agentic RAG governance citations"
if "latency evidence" in missing:
return "agentic workflows latency retries"
return ""

def agentic_rag(question, max_steps=3):
state = {"question": question, "queries": [], "evidence": [], "reflections": []}
query = question
seen = set()

for _ in range(max_steps):
state["queries"].append(query)
docs = retrieve(query, exclude=seen)
for doc in docs:
state["evidence"].append(doc)
seen.add(doc["id"])

missing = check_missing(question, state["evidence"])
state["reflections"].append(
"enough evidence" if not missing else f"missing: {', '.join(missing)}"
)

if not missing:
break

query = plan_next_query(missing)
if not query:
break

citations = ", ".join(doc["id"] for doc in state["evidence"])
answer = (
"Prioritize governance, citation quality, and latency budgets. "
"The report-style evidence emphasizes fresh content and controls, while "
"support messages show operational risk from retries and irrelevant citations. "
f"Sources: {citations}"
)
return answer, state

if __name__ == "__main__":
answer, trace = agentic_rag(
"Using the Omdia Report and support messages, "
"which Agentic RAG risks should we prioritize for latency?"
)
print(answer)
print(trace)
Walk through what happens when you run this. The agent starts with the full question as the first query. retrieve() returns the Omdia Report document, which scores highest on keyword overlap with the question. check_missing() checks the accumulated evidence against what the question requires and finds that support messages and latency evidence are both absent. plan_next_query() generates a new query targeting the missing source. On the second iteration, retrieve() returns the support messages document, which also contains the word "latency." The reflection check passes and the loop exits.
The state dict after the run shows the full trace: two queries issued, two documents retrieved, one reflection noting gaps, one reflection noting sufficiency. That trace is the thing to inspect when something goes wrong in a real system.
The snippet deliberately leaves several things out. Retrieval is keyword overlap, not semantic similarity. There is no reranker. The answer is hardcoded rather than generated by a language model. There is no authentication, no access control, no governance, and no production observability. In a real system, retrieve() becomes a search stack combining dense and sparse retrieval with a reranker; check_missing() becomes a language model call with a structured evaluation rubric; and the state dict gets logged to a tracing tool on every step.
The full version of this code is in my GitHub repo. It adds @weave.op() to each of the four core functions, wraps the loop in an AgenticRAGModel class, defines a four-example EVAL_DATASET, and attaches two scorers: source_coverage_scorer and loop_efficiency_scorer. Running it sends both the single-query trace and the evaluation results to your Weights & Biases project at agentic-rag-demo. Here is what you should see.

What you see in the W&B Weave UI

After the script finishes, Weave prints two trace URLs to the terminal and everything lands in your Weights & Biases project. Open the project and go to Traces. Two rows appear: one labeled agentic_rag for the single-query call, and one labeled eval-2026-06-08-... for the evaluation run. The evaluation row already shows aggregated columns in the table, including loop_count, coverage scores, and true_fraction for the boolean scorers.
Screenshot by Author. The W&B Weave Traces view for the agentic-rag-demo project, showing the evaluation call and the single agentic_rag trace with aggregate scorer columns populated across the table.
Click the evaluation row to open the detail panel. The Scorers section on the left shows source_coverage_scorer:v0 reporting a mean coverage of 1.0 and all_found at 100%. Below it, loop_efficiency_scorer:v0 shows within_budget at 100% and a mean loop count of 1.25. Three of the four examples resolved in a single retrieval pass; the fourth, the multi-source query about latency priorities, required two. On the right side of the panel, all four examples are listed with their questions, expected sources, and the model answers. Clicking "View results" sorts them by failing first, though in this case none failed.
Screenshot by Author. The evaluation detail panel showing source_coverage_scorer at 100% all_found and loop_efficiency_scorer at 100% within_budget, with the four evaluation examples listed on the right.
The more instructive view is the single agentic_rag trace. Click that row and open the Call tab. Scroll to the Output section. The state dict is rendered as an expandable tree. The evidence array shows two items, one per document retrieved. The reflections array is the part to pay attention to: index 0 reads "missing: support messages, latency evidence" and index 1 reads "sufficient." That two-entry array is the loop made visible. One retrieval came back incomplete, the reflection said so, the second retrieval closed the gap.
Screenshot by Author. The Call tab for the single agentic_rag trace, showing the Output section with the reflections array expanded: index 0 reads "missing: support messages, latency evidence" and index 1 reads "sufficient".
Scroll down past the output and you reach the child calls. Each retrieve(), check_missing(), and plan_next_query() invocation appears as a nested span under the root agentic_rag call, with its own inputs and outputs visible. For this query, two retrieve spans are visible: the first returning the Omdia Report document, the second returning the support messages document. When something goes wrong in a real system, this nesting is where you start: open the failing trace, find the step where the wrong content came back, and work backwards from there.
Finally, open the Assets tab. Weave automatically versioned three objects during the run: AgenticRAGModel:v0, agentic_rag_loop_eval:v0, and Dataset:v0. These are not just one-time log entries. They are pinned versions you can reference in future runs, which means re-running the evaluation after changing the code produces a new row in the same evaluation view rather than an unrelated trace somewhere else.
Screenshot by Author. The Assets view in the agentic-rag-demo project showing AgenticRAGModel:v0 as a Model, agentic_rag_loop_eval:v0 as an Evaluation, and Dataset:v0 as a Dataset, each with one version

A more complete example: agentic codebase Q&A

The toy loop in the previous section teaches the structure, but every decision in it was hardcoded: a lookup table decided what to search for next, and a keyword rule decided when to stop. That approach works for a three-document corpus with a known question shape. It breaks the moment a new question type arrives, because someone has to write a new rule for it.
This second example removes those constraints. The agent uses an LLM to choose which search tool to call and what arguments to pass. A separate LLM call reads the accumulated evidence after every retrieval and decides whether it is sufficient. Nothing about the stopping criterion is domain-specific. The agent can handle any question about any codebase without changing a line of application code.
The use case is codebase Q&A: a developer asks how a part of the codebase works, the agent searches the source files, and stops when it has found enough code to answer. The retrieval tools are grep_code, find_file, and read_file, which mirror what you would run in a terminal. In production these call real bash commands or a code search API. In this demo they are Python functions operating on a small fake Flask application written to a temporary directory at startup.
The full file is in my GitHub repo. It requires openai in addition to weave and python-dotenv.
import json
import os
import re
import tempfile

import weave
from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()
The fake codebase written at startup contains four files: auth/middleware.py (a require_auth decorator that validates Bearer tokens), auth/tokens.py (JWT issue and decode functions), api/routes.py (a Flask app with one protected route), and tests/test_auth.py. See the GitHub repo for the full file contents.
The three search tools are plain Python functions. Each takes the codebase root as a parameter so the same code works against any directory:
def grep_code(pattern: str, codebase_root: str, path: str = ".") -> str:
"""Search Python files for a regex pattern. Returns filename:linenum: line."""
matches = []
for dirpath, _, filenames in os.walk(os.path.join(codebase_root, path)):
for fname in sorted(filenames):
if not fname.endswith(".py"):
continue
fpath = os.path.join(dirpath, fname)
rel = os.path.relpath(fpath, codebase_root)
with open(fpath) as f:
for i, line in enumerate(f, 1):
if re.search(pattern, line, re.IGNORECASE):
matches.append(f"{rel}:{i}: {line.rstrip()}")
return "\n".join(matches) if matches else "No matches found."

def find_file(name_pattern: str, codebase_root: str) -> str:
"""Find files whose name matches a pattern."""
results = []
for dirpath, _, filenames in os.walk(codebase_root):
for fname in sorted(filenames):
if re.search(name_pattern, fname, re.IGNORECASE):
results.append(os.path.relpath(os.path.join(dirpath, fname), codebase_root))
return "\n".join(results) if results else "No files found."

def read_file(relative_path: str, codebase_root: str) -> str:
"""Read the full content of a file."""
try:
with open(os.path.join(codebase_root, relative_path)) as f:
return f.read()
except FileNotFoundError:
return f"File not found: {relative_path}"
The tool schema tells OpenAI's function-calling API what tools are available and what arguments each one takes. The agent never sees the Python functions directly; it sees these JSON descriptions and decides from them. There are three entries in the list, one per tool. Here is the grep_code entry as a representative example:
TOOLS = [
{
"type": "function",
"function": {
"name": "grep_code",
"description": (
"Search all Python files for a regex pattern. "
"Returns matching lines with filename and line number."
),
"parameters": {
"type": "object",
"properties": {
"pattern": {"type": "string", "description": "Regex to search for"},
"path": {"type": "string", "description": "Subdirectory to search (default '.')"},
},
"required": ["pattern"],
},
},
},
# ... find_file and read_file follow the same shape
]
The reflection function is where this example diverges most sharply from the toy. Instead of checking whether a specific keyword is in the joined evidence text, it sends the full question and all accumulated code to an LLM and asks it to judge:
REFLECTION_SYSTEM = """\
You are a code search assistant deciding whether enough code has been retrieved to answer a question.
Return a JSON object with exactly these fields:
{
"sufficient": true or false,
"reasoning": "one sentence explaining your judgment",
"next_search": "describe what to look for next (empty string if sufficient)"
}
Return ONLY the JSON object."""

@weave.op()
def reflect(question: str, evidence: list, step: int) -> dict:
evidence_text = "\n\n---\n\n".join(
f"[{e['tool']}({e['args']})]\n{e['result']}" for e in evidence
)
client = OpenAI()
resp = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": REFLECTION_SYSTEM},
{"role": "user", "content": (
f"Question: {question}\n\n"
f"Search steps completed: {step}\n\n"
f"Code retrieved:\n{evidence_text or '(nothing yet)'}"
)},
],
temperature=0,
max_tokens=200,
)
try:
return json.loads(resp.choices[0].message.content.strip())
except json.JSONDecodeError:
return {"sufficient": False, "reasoning": "parse error", "next_search": ""}
The next_search field in the reflection output feeds directly into the next planning call. The planner sees what has already been searched and the reflection's guidance about what is still needed:
@weave.op()
def plan_tool_call(question: str, evidence: list, next_search_hint: str) -> tuple:
prior = "\n".join(f"- {e['tool']}({e['args']})" for e in evidence) or "(none yet)"
client = OpenAI()
resp = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are a code search agent. Choose ONE tool call."},
{"role": "user", "content": (
f"Question: {question}\n\n"
f"Searches so far:\n{prior}\n\n"
f"Reflection hint: {next_search_hint or 'Start fresh.'}"
)},
],
tools=TOOLS,
tool_choice="required", # always return a tool call, never plain text
temperature=0,
)
call = resp.choices[0].message.tool_calls[0]
return call.function.name, json.loads(call.function.arguments)
tool_choice="required" is the key setting. Without it, the model might respond with a text explanation of what it would search for rather than actually calling a tool. With it forced, every planning call returns an executable tool selection.
The loop connects all of this:
@weave.op()
def codebase_rag_agent(question: str, codebase_root: str, max_steps: int = 6) -> dict:
state = {
"question": question,
"evidence": [],
"reflections": [],
"tool_calls": [],
"answer": "",
}
next_search_hint = ""

for step in range(max_steps):
# LLM picks the next tool and its arguments
tool_name, tool_args = plan_tool_call(question, state["evidence"], next_search_hint)
state["tool_calls"].append({"step": step + 1, "tool": tool_name, "args": tool_args})

# Tool executes; result added to evidence
result = run_tool(tool_name, tool_args, codebase_root)
state["evidence"].append({"tool": tool_name, "args": str(tool_args), "result": result})

# LLM judges whether evidence is sufficient
reflection = reflect(question, state["evidence"], step + 1)
state["reflections"].append(reflection)

if reflection.get("sufficient"):
break

next_search_hint = reflection.get("next_search", "")
if not next_search_hint:
break # nothing more to suggest; stop rather than loop blindly

state["answer"] = generate_answer(question, state["evidence"])
return state
The structure is identical to the toy loop: plan, execute, reflect, repeat. The difference is that plan_tool_call and reflect are LLM calls rather than lookup tables. The hard budget (max_steps=6) is still there as a fallback, because an LLM-based reflection that fails to return sufficient: true for structural reasons, such as a parse error, should not run indefinitely.
Run it with:
if __name__ == "__main__":
weave.init("agentic-rag-demo")

with tempfile.TemporaryDirectory() as tmpdir:
setup_codebase(tmpdir)
state = codebase_rag_agent(
question=(
"How does authentication work in this codebase, "
"and where is token validation implemented?"
),
codebase_root=tmpdir,
)
print(state["answer"])
for tc in state["tool_calls"]:
print(f" Step {tc['step']}: {tc['tool']}({tc['args']})")
for i, r in enumerate(state["reflections"], 1):
print(f" Step {i}: sufficient={r.get('sufficient')} | {r.get('reasoning')}")
Running this produces terminal output like:
=== Answer ===
Authentication in this codebase is implemented using a decorator called require_auth,
which validates a Bearer token for protected routes. The token is extracted from the
Authorization header; if it does not start with "Bearer ", a 401 error is raised.
The token is decoded using decode_token, and if invalid or expired, another 401 is raised.
If valid, the user payload is attached to the request object.
Token validation is implemented in the require_auth decorator in [auth/middleware.py].

Search steps: 2
Step 1: find_file({'name_pattern': 'auth'})
Step 2: read_file({'relative_path': 'auth/middleware.py'})
Reflections:
Step 1: sufficient=False | Only file names found; actual implementation not yet read.
Step 2: sufficient=True | Full content of auth/middleware.py read; auth mechanism clear.
Walk through what happened. The planner called find_file(name_pattern="auth") on the first step, which returned the paths of both auth modules. The reflection said "only file names, not content" and named auth/middleware.py as the next file to read. The planner followed that hint directly, called read_file("auth/middleware.py"), and the reflection declared sufficient after reading the full decorator implementation.
Two steps. The loop stopped because the reflection's stopping criterion is explicit: full file reads are sufficient; grep snippets alone are not. That rule is what prevents the agent from declaring victory on three matching lines and producing a shallow answer.
The exact sequence can vary across runs. The planner might start with grep_code("require_auth") on one run and find_file("middleware") on another, depending on how the LLM interprets the question. Both paths converge to the same answer. That variation is the flexibility/determinism trade-off made concrete: LLM-driven loops produce different execution paths for the same input, which is why you need to test outcomes rather than sequences. The Weave trace is how you inspect those paths when the result is unexpected.

What the Weave trace looks like

After the script finishes, open the agentic-rag-demo project in your Weights & Biases account and go to Traces. The codebase_rag_agent run appears as the root span. Expanding it reveals the structure: two iterations of plan_tool_call → run_tool → reflect, followed by a single generate_answer span. Each plan_tool_call contains a nested openai.chat.completions.create call, as does each reflect. You are looking at six OpenAI calls total for a two-step run, which is what LLM-driven planning and reflection costs compared to the toy example's zero.
The right panel is where the diagnostic value sits. Click the root codebase_rag_agent span and scroll to the Output section. The state dict renders as an expandable tree: evidence (two items, one per tool result), reflections (two judgments, the second one with sufficient: true), tool_calls (the log of what ran at each step), and the final answer. Below the output, the "Child calls of plan_tool_call:v1" table shows the second planning call's inputs side by side, including the next_search_hint it received from the reflection and the read_file selection it returned. That table makes the reflection-to-planning handoff inspectable in a single view without clicking into each span individually.
Screenshot by Author. The Weave trace for the clean 2-step run. The tree shows exactly two iterations: plan_tool_call (find_file) → run_tool → reflect, then plan_tool_call (read_file) → run_tool → reflect, followed by generate_answer. The right panel shows the state dict output with evidence, reflections, tool_calls, and the final answer. The "Child calls of plan_tool_call:v1" table at the bottom shows the second planning call receiving the reflection hint "Read auth/middleware.py" and returning read_file as its tool selection.

Trade-offs analysis: accuracy vs latency, cost vs throughput, flexibility vs determinism

  • Agentic RAG does not improve on traditional RAG in every dimension. It is a trade, and the trade has four axes worth understanding before committing to the architecture.
  • Accuracy vs latency. Each additional retrieval step, reflection call, and reranking pass takes time. A loop that runs two or three retrieval iterations with a model-based reflection check might take four or five seconds where a single-pass pipeline takes under a second. The accuracy gain is real for the queries that need it: multi-hop questions, conflicting sources, and ambiguous queries all benefit from the loop. But for a use case where the answer needs to come back in under two seconds, that gain may be irrelevant because the latency constraint makes the design unshippable.
  • Cost vs throughput. Every additional model call in the loop adds to the per-query cost. At low query volumes this is negligible. At high throughput, with hundreds or thousands of queries per minute, the cost multiplier compounds quickly. A loop averaging two retrieval steps and one reflection call per query roughly triples the model spend compared to a single-pass pipeline handling the same traffic. Caching, routing to cheaper models for reflection calls, and setting tight step budgets are the main levers for controlling this.
  • Flexibility vs determinism. A fixed RAG pipeline produces the same execution path for the same query every time, which makes it easy to test, audit, and explain to a stakeholder. An adaptive loop might take different paths across runs depending on retrieval order, reflection judgments, or small variations in query formulation. That unpredictability is manageable in development with good tracing. In a regulated environment where an auditor needs to understand exactly why a specific answer was produced, it adds compliance overhead that a fixed pipeline avoids.
  • Autonomy vs governance. The more decisions the agent makes without human review, the harder the system is to audit and control. Tool permissions define which sources the agent can access; without them, a misbehaving agent queries anything it has credentials for. Policy guards intercept certain query types before they reach the retrieval layer. Audit logs record every tool call and the reasoning that triggered it. Human review checkpoints add latency but allow intervention on high-stakes decisions. The more autonomous the loop, the more governance infrastructure is required before it is safe in production.

Evaluation and observability for agentic RAG

Evaluating agentic RAG by final answer quality alone misses most of the ways it can fail. The answer might look correct while the retrieval path was inefficient, the loop ran too many iterations, the citations are wrong, or the agent bypassed a source it should have consulted. Final-answer metrics do not catch any of that.
The metrics that matter for agentic RAG span the full loop: retrieval recall (did the agent find the relevant chunks?), precision@k (of the retrieved chunks, how many were relevant?), citation faithfulness (do the citations in the answer match the actual sources consulted?), answer correctness, tool-selection accuracy (did the agent choose the right retrieval tool for each sub-query?), loop count (how many iterations did the task require?), latency per query, and cost per successful answer. Some of these require LLM-as-a-judge scoring. Others can be computed directly from the trace.
Trace-based debugging is the complement to aggregate metrics. When a query returns a bad answer, the trace tells you where it went wrong: which step retrieved the wrong content, what the reflection said, whether the loop stopped too early or ran too long, and whether the final answer is actually grounded in the evidence that was retrieved. Without traces, debugging an agentic RAG failure is mostly guesswork.
W&B Weave is a practical tool for this. Adding @weave.op() to the retrieval, reflection, and planning functions means every step in the loop is recorded as a span in the trace tree. The root span shows the full agentic_rag() call; the child spans show each retrieve(), check_missing(), and plan_next_query() invocation with inputs and outputs. You can inspect individual traces when something looks off, and run a weave.Evaluation over a labeled test set to get aggregate scores across multiple examples. Both views are in the same Weights & Biases project, which means you can move between a failing individual trace and the aggregate metric it belongs to without switching tools. The full implementation is in my GitHub repo.
Test sets for agentic RAG should include questions that require multiple retrieval steps, questions where relevant sources conflict, questions where no relevant content exists in the corpus, and questions that a traditional RAG baseline would answer correctly. That last category is the real test: if agentic RAG does not outperform the baseline on the hard queries, the loop is adding cost without adding value.

Edge cases and failure modes

The loop that makes agentic RAG adaptive is also the source of its specific failure modes. Most of them fall into four categories.
Looping failures happen when the loop runs longer than it should. The most common versions: the agent retrieves the same document twice because deduplication logic is missing or broken; the query drifts across iterations, moving further from the original question with each refinement; the agent issues redundant tool calls for sources it already has in state; and the reflection check never returns "sufficient," so the loop runs to the step budget every time. The mitigations are mostly mechanical: explicit deduplication on document IDs, step budgets as hard stops, reflection prompts that must return a structured judgment with a clear boolean condition, and logging to surface runaway loops before they become a cost problem.
Retrieval failures cover what happens when the relevant content exists in the corpus but the search does not find it. Stale indexes return outdated content for time-sensitive queries. Duplicate chunks create artificially high retrieval scores for documents that appear multiple times. Low-recall search at the initial threshold means the relevant chunk scores below the cutoff and never enters the evidence pool. Contradictory content from different sources may both score highly without the system flagging the conflict. High-scoring but irrelevant documents can mislead the reflection step into declaring the evidence sufficient when it is not.
Agent failures are harder to detect. Overconfident reflection means the agent decides it has enough evidence before it does, typically because the reflection prompt is too easy to satisfy with partial information. State corruption occurs when content from a previous task leaks into the current state through a caching bug or improper state scoping. Prompt injection from retrieved content is a real attack vector: a document in the corpus can contain text that looks like an instruction, which the model may follow when it processes that document as evidence. Invalid tool selection happens when the routing logic sends queries to the wrong source, which is hard to catch without tool-selection accuracy in the evaluation suite.
Context failures emerge as state grows larger. The message list eventually exceeds what the model can attend to reliably, and early constraints get effectively lost. Citation mismatches occur when the model generates an answer referencing a source ID that does not correspond to anything in the evidence state. Evidence buried deep in a long context window may be underweighted in favor of content closer to the end of the list, which skews the synthesis step toward recency rather than relevance.
Mitigation patterns for all four categories share a common thread: make the failure visible before it reaches a user. Step budgets, source allowlists, retrieval result validation before evidence is added to state, provenance checks on citations, policy guards that intercept certain queries before they reach the retrieval layer, and an explicit fallback to single-pass RAG when the loop fails to converge within budget. That last one is underused. Routing failed or edge-case queries to the simpler pipeline is both cheaper and more reliable than retrying indefinitely with the full agentic system.

When not to use agentic RAG

The loop should exist because the queries require it, not because the architecture looks more sophisticated.
If a fixed RAG pipeline already answers the majority of queries reliably within your latency and cost budget, adding an agent loop makes the system harder to understand, harder to debug, and more expensive to run without improving the answers that already work. The loop earns its place only when the baseline fails on queries that adaptive retrieval can realistically fix.
Agentic RAG is a poor fit for several common patterns. FAQ-style lookup, where users ask one of a small number of predictable questions against a stable corpus, does not need an adaptive loop. The query patterns are known, the right sources are fixed, and a well-tuned single-pass pipeline outperforms the loop on both speed and cost. High-throughput, low-latency endpoints face the same problem: the loop multiplies latency and cost per query, which compounds at scale in a way that quickly becomes uneconomical. Deterministic compliance workflows, where a regulated system must produce the same output for the same input every time, are fundamentally at odds with an adaptive loop whose path depends on evidence quality.
There is also a governance prerequisite. An agentic RAG system that cannot log its tool calls, cannot audit its retrieval decisions, and cannot be traced back to specific evidence for each answer is not production-ready, regardless of accuracy. If the infrastructure for trace logging and tool governance is not in place, the loop adds risk without a compensating observability benefit.
The practical decision heuristic: build and measure a standard RAG baseline first. Identify the failure cases by category. If failures are concentrated in multi-hop questions, ambiguous queries, or cases where multiple sources must be reconciled, an agent loop can address them. If failures are mostly retrieval quality issues, fix the retrieval stack before adding agentic complexity. An agentic layer on top of poor retrieval does not fix the retrieval.

Step-by-step implementation roadmap

The safest path to agentic RAG is to evolve from a working baseline, not to design an agentic system from scratch.
  1. Step 1 is to build and measure a standard RAG pipeline with a real evaluation suite. Not spot-checked manually, but measured on a labeled test set with retrieval and generation metrics. This is the baseline you will compare everything against. Without it, there is no way to know whether any change, agentic or otherwise, is actually helping.
  2. Step 2 is to add query routing or query rewriting before adding any looping behavior. Routing means the pipeline can direct different query types to different sources. Rewriting means it can reformulate ambiguous queries before retrieval. Both improve single-pass RAG and both are building blocks for the full agentic loop. Adding them first gives you incremental value without the full complexity of an agent.
  3. Step 3 is to add a reflection step for the queries where the baseline fails most badly. Start with a rule-based implementation. It is predictable, testable, and free of additional model calls. Upgrade to a model-based reflection check once the rule-based version has demonstrated value on your specific failure cases.
  4. Step 4 is to add budgets, policy guards, trace logging, and fallback behavior. These should go in before you expand the loop's autonomy, not after. Budgets prevent runaway costs during development. Trace logging from the start means you have data to analyze when something breaks. A fallback to single-pass RAG for cases where the loop fails to converge prevents degraded behavior from reaching users.
  5. Step 5 is to evaluate against the baseline from Step 1. Run the same test set, compare metrics, and inspect traces for cases where the loop helped and cases where it did not. Expand the loop's autonomy only for the query categories where traces show clear improvement. Everything else stays on the simpler pipeline.

Alternative use cases for agentic RAG

The right use cases for agentic RAG are the ones where adaptive retrieval is doing real work, not decorating a pipeline that would have functioned without it.
  • Enterprise research over analyst reports, internal documents, and customer messages is the clearest fit. A question like "What are our top customer complaints about the new onboarding flow, and how do they compare to what industry analysts predict?" requires routing to at least two distinct sources, reconciling what they say, and synthesizing a response that cites both. Single-pass RAG cannot do that reliably. An agent loop can.
  • Customer support triage benefits when the system needs to cross-reference a product knowledge base, a ticket history, and a policy document before deciding how to route or respond. The relevant source depends on the nature of the complaint, which the agent can determine from the initial retrieval and reflection step. Static pipelines with a single retrieval source miss the routing step entirely.
  • Financial research and market analysis involve questions that span structured and unstructured data: filings, earnings transcripts, news, and proprietary models. The agent can route each sub-query to the appropriate source, flag contradictions between sources, and hold off on synthesis until the evidence set is complete enough to support the claim.
  • Healthcare document review requires citation accuracy that single-pass RAG cannot guarantee reliably. Clinical questions may require evidence from trials, guidelines, and patient records simultaneously, and the agent needs to verify that each cited document actually supports the stated claim before the answer is returned.
  • Codebase question-answering, where a developer asks how a function works across a multi-repository codebase, benefits from an agent that can retrieve from the right repository, follow imports to related files, and detect when an answer would be incomplete without checking a dependency. A single vector search over a large codebase rarely surfaces all the relevant context in the top-k results.
  • Education tutoring systems benefit when a student's question spans multiple learning materials. A tutoring agent can retrieve the relevant concept explanation, find the worked example that applies it, and cross-reference a prerequisite the student may have missed, routing each retrieval to the appropriate part of the curriculum rather than returning whatever scores highest across the entire content library.
  • Multimodal operations, where the answer requires combining text, tables, and images from different sources, make the retrieval tool layer's diversity most visible. A question about a chart requires image retrieval; a question about a specific data point may require a SQL query; a question about the methodology behind either requires a text search. The agent routes to the right tool for each sub-query rather than applying a single retrieval method to all of them.
Where graph RAG or agentic graph RAG may be a better fit: any domain where entity relationships and provenance are central to the question. Knowledge graphs encode connections between entities in a way that flat vector indexes do not. If your questions are fundamentally about relationships, such as who approved a decision and what precedents influenced it, graph retrieval will outperform vector retrieval regardless of whether the loop is agentic.

Conclusion: the decision rule for agentic RAG

The decision rule comes down to what the loop actually buys you on your queries. Use agentic RAG when questions require multiple retrieval steps to resolve, when sources must be compared or reconciled before synthesis is reliable, or when single-pass retrieval failures are causing measurable harm in production. Do not use it when queries are predictable, the corpus is stable, the latency budget is tight, or when the trace logging and governance infrastructure to manage the loop safely is not yet in place.
Agentic RAG is an engineering trade-off, not an upgrade. Every benefit it offers over traditional RAG, from multi-hop reasoning to adaptive source selection, comes from the loop, and the loop adds latency, cost, and unpredictability in exchange. Whether that trade makes sense depends on what your specific queries actually require, and the only way to know that is to measure a baseline first.
The mechanism to hold on to is the one the worked examples make concrete: observe, retrieve, reflect, refine, repeat. That loop, constrained with step budgets, instrumented with tracing, and compared against a measured baseline, is the whole design. Everything else, the architecture patterns, the agent roles, the retrieval tools, the multi-agent variants, is a decision about how to build that loop for your particular constraints.
Start with the baseline. Validate with traces. Add agentic complexity only where the data shows it is warranted.
Iterate on AI agents and models faster. Try Weights & Biases today.