Özer Cem KELAHMETKELAHMET
Articles · Agentic RAG

Agentic RAG explained: agents that decide when, where and how to retrieve, step by step

In agentic RAG the model does not get one fixed retrieval. It decides whether to search, which source to use and what to ask next, looping until it can answer. This guide traces such a loop in runnable Python, prices its growing context and shows the limits it needs.

Download Markdown
At a glance
Reading time
14 min
Sections
7
Code examples
2
Tables
3
Sources
8
Published
24 Nov 2026
In 30 seconds
What changed
Haystack 3.5.0 ships a configurable Agent component
Why it matters
Agentic RAG is the right tool for multi-hop questions, questions that span several sources, and research tasks where the plan depends on what is found.
What to do
Route before you loop

Classic retrieval-augmented generation (RAG) is a fixed pipeline: take the question, retrieve the top passages once, generate an answer. It works when one search finds everything needed. It fails on questions that need a chain of lookups, such as "Who should I contact about last week's invoice outage?", which requires finding the outage, then the service that failed, then its owning team, then that team's lead. No single query retrieves all four facts.

Agentic RAG turns retrieval into a decision. The language model is given search tools and a loop. At each step it reads what it has so far and chooses: search again, search a different source, rewrite the query, or answer. Deep research products, which run many searches and write long reports, are the most visible form of this pattern. This month two major frameworks shipped releases with agent components that make the loop a few lines of configuration. This article explains how agentic RAG works, traces a loop in runnable Python, works out why its cost grows faster than the number of steps, and lists the guardrails it needs.

An analogy: classic RAG is asking a colleague to grab "the file on the outage" from the archive. Agentic RAG is asking a researcher to find out who to call; they look up the incident, check who owns the service, look up that team, and come back with a name and their sources.

What happened

Haystack 3.5.0 ships a configurable Agent component (10 November 2026)

Haystack 3.5.0, released on PyPI on 10 November 2026, includes an Agent component that "processes messages and calls tools until it meets an exit condition". In the installed package the constructor takes a chat generator, tools or toolsets, a system prompt, exit_conditions, a state_schema, max_agent_steps (default 100), tool_concurrency_limit (default 4) and lifecycle hooks for before_run, before_llm, before_tool, after_tool, on_exit and after_run. For agentic RAG, the retrievers become tools and the hooks give places to log, filter or block each retrieval.

LangChain 1.5 adds more agent middleware (11 November 2026)

LangChain 1.5.0 was released on 11 November 2026 and reached 1.5.2 on 18 November. Its create_agent function takes a model, tools, a system prompt and a list of middleware, plus a checkpointer and store for state. The installed 1.5.2 package exports middleware including ModelCallLimitMiddleware, ToolCallLimitMiddleware, SummarizationMiddleware, ContextEditingMiddleware, ToolRetryMiddleware, ModelFallbackMiddleware, HumanInTheLoopMiddleware and PIIMiddleware. Several of these address exactly the risks of agentic retrieval: runaway loops, growing context and sensitive data in retrieved text. The site's guide to LangChain 1.5 middleware covers them in depth.

How agentic RAG works

Retrieval becomes a tool

In agentic RAG, each retriever is exposed to the model as a function with a name, a description and parameters, for example search_tickets(query) and search_handbook(query). The model sees the tool descriptions in its prompt and emits a tool call when it wants information. The framework runs the search and appends the results to the conversation as an observation. This is the ReAct pattern, reason then act, described on the site's ReAct loop page.

The decisions an agent makes

Table 1. The decisions an agent makes
Decision Fixed pipeline Agentic RAG
Whether to retrieve Always Only when the model needs facts
Which source All, or one fixed index Chooses among tools (docs, tickets, SQL, web)
What query The user's text, maybe rewritten once Writes a new query per step, using earlier results
How many rounds One Until it can answer or hits a limit
When to stop After one generation Exit condition, step limit or budget

Designing retrieval tools

Tool design decides how well the agent chooses. Three habits help. First, make each tool narrow and named after its content, not its technology: search_incidents tells the model more than vector_search_2. Second, describe in the tool description what the source contains and what it does not, including its freshness, for example "incident tickets from the last 18 months". Third, return results in a compact, consistent format with an identifier per passage, so the model can cite them and so later context editing can drop them cleanly. Tools can also be shared across agents and applications through MCP, which turns an internal search index into a server any compatible agent can call.

Parallelism is the other design choice. When sub-questions are independent, such as "compare the parental leave policies of three subsidiaries", the agent can issue several retrieval calls in one step; Haystack's tool_concurrency_limit (default 4) governs how many run at once. Dependent hops, like the outage example below, must stay sequential. Graph-based frameworks such as LangGraph make the split explicit by modelling parallel branches and joins.

This flexibility is what lets the agent follow a chain. It is also what makes the system harder to predict, test and budget.

Deep research: the long-running form

Deep research agents push the same loop further. A typical design plans a set of sub-questions, runs many searches (often in parallel through sub-agents), reads and compresses the results, notes gaps, searches again, and finally writes a report with citations. LangChain's open-source Open Deep Research project describes itself as a configurable deep research agent that "works across many model providers, search tools, and MCP servers". The ingredients are the ones in this article, plus planning, parallelism and summarisation to keep context under control.

Tracing an agentic RAG loop

The script below runs a complete loop with two sources, a handbook and an incident tracker. To keep it runnable without an API key, the model's decisions are replaced by a small policy function that mimics what an LLM would choose given the notes so far, and retrieval is simple keyword overlap. Swap policy for a model call with tool definitions and search for a real retriever, and the structure is the same.

SOURCES = {
    "handbook": ["The Invoice service is owned by the Billing team.",
                 "The Billing team is led by Sam Lee.",
                 "Incidents are reported in the #ops channel."],
    "tickets":  ["INC-311: Invoice service outage on 12 November caused by Payments API timeouts.",
                 "INC-298: Login latency spike, resolved by cache restart."],
}
tok = lambda s: s.lower().replace(".", " ").replace(":", " ").replace(",", " ").split()
STOP = {"the", "is", "by", "who", "in", "on", "of", "a"}

def search(source, query, k=1):
    q = set(tok(query)) - STOP
    sc = [len(q & set(tok(d))) for d in SOURCES[source]]
    best = sorted(range(len(sc)), key=lambda i: -sc[i])[:k]
    return [SOURCES[source][i] for i in best if sc[i] > 0]

def policy(question, notes):            # stand-in for the LLM's choice at each step
    text = " ".join(notes).lower()
    if "outage" not in text:   return ("search", "tickets", "invoice service outage")
    if "owned by" not in text: return ("search", "handbook", "who owns the invoice service")
    if "led by" not in text:   return ("search", "handbook", "billing team led by")
    return ("answer", None, None)

def run(question, max_steps=6, base_tokens=1500, obs_tokens=800):
    notes, total_in = [], 0
    for step in range(1, max_steps + 1):
        ctx = base_tokens + obs_tokens * len(notes)    # prompt grows each step
        total_in += ctx
        action, source, query = policy(question, notes)
        print(f"step {step}: {action} {source or ''} {query or ''} input={ctx}")
        if action == "answer":
            return notes, total_in
        notes += search(source, query)
    return notes, total_in

notes, total = run("Who should I contact about last week's invoice outage?")
print(*notes, sep="\n"); print("total input tokens:", total)

The trace:

Table 2. Tracing an agentic RAG loop
Step Action Source Query Input tokens this step
1 search tickets invoice service outage 1,500
2 search handbook who owns the invoice service 2,300
3 search handbook billing team led by 3,100
4 answer n/a n/a 3,900

The agent collects three facts from two sources: incident INC-311 on the Invoice service, the Billing team's ownership, and Sam Lee as its lead. Each query depends on the previous result, which is the defining feature of multi-hop retrieval. The site's agentic RAG simulation shows the same kind of loop with live choices.

Why agentic RAG costs more than it looks

The trace assumes a 1,500-token base prompt (system prompt, tool definitions, question) and 800 tokens per observation. Because every step re-sends the whole conversation, input grows linearly per step and total input grows roughly with the square of the number of steps:

total input = n × B + O × (0 + 1 + ... + (n − 1)) = n × B + O × n(n − 1) / 2

For n = 4 calls, B = 1,500 and O = 800: 4 × 1,500 + 800 × 6 = 10,800 tokens, which matches the script. A single-shot RAG call with the same three passages would send 1,500 + 3 × 800 = 3,900 tokens once. The agent spends 2.8 times as many input tokens to get the same evidence, and makes four sequential model calls instead of one.

Table 3. Why agentic RAG costs more than it looks
Steps (model calls) Total input tokens (B = 1,500, O = 800) Versus one 3,900-token call
2 3,800 1.0x
4 10,800 2.8x
8 34,400 8.8x
16 120,000 30.8x

Three levers keep this under control. Prompt caching makes the repeated prefix cheaper, because each call shares the previous call's prompt as a prefix. Context editing and summarisation drop or compress old observations, which LangChain's middleware and Haystack's hooks support. Step and call limits cap the worst case; Haystack defaults to 100 agent steps, which is far more than most RAG questions need, so set your own. The site's simulations of agent loop token cost and step limits versus cost per task let you explore these curves.

What it means in practice

Agentic RAG is the right tool for multi-hop questions, questions that span several sources, and research tasks where the plan depends on what is found. It is the wrong tool for the large majority of simple lookups, where a fixed pipeline with hybrid retrieval and reranking is faster, cheaper and easier to test. Many production systems route: a classifier or a cheap first call decides whether a question needs the agent at all.

The framework releases this month show where the engineering effort has moved. The loop itself is solved; the work is in control. Hooks and middleware for call limits, retries, context editing, PII filtering and human approval are now standard parts of agent frameworks, and agentic RAG needs all of them because retrieved text is untrusted input that flows straight into a model making decisions.

Evaluation also changes. A fixed pipeline can be scored on retrieval recall and answer faithfulness. An agent must also be scored on its trajectory: did it pick sensible sources and queries, did it stop at the right time, and how many steps and tokens did it spend? The site's article on agent evaluation with trajectories and judges covers those methods, and RAG from naive to agentic places this pattern among the other RAG designs.

What to do now

  1. Route before you loop. Send simple questions to a fixed RAG pipeline and only multi-hop or multi-source questions to the agent.
  2. Expose each source as a narrow tool. Give every retriever a clear name, description and parameters so the model can choose well.
  3. Set hard limits. Cap model calls, tool calls and total tokens per question; do not rely on framework defaults such as 100 steps.
  4. Cache the shared prefix. Keep system prompt and tool definitions stable so prompt caching applies on every step.
  5. Compress old observations. Summarise or drop earlier tool results once their facts are captured in notes.
  6. Return sources with every answer. Keep the chunk IDs from each retrieval so the final answer can cite them.
  7. Log full trajectories. Record every decision, query, result and token count, and review failures by trajectory, not just by final answer.
  8. Evaluate steps as well as answers. Score tool choice, number of steps and cost alongside correctness and faithfulness.
  9. Filter retrieved text before it reaches the model. Use hooks or middleware to strip instructions, secrets and personal data from observations.

Risks and open questions

Prompt injection gets more power. A retrieved document that contains instructions can now change what the agent searches next or which tool it calls. Treat every observation as data and restrict what tools can do.

Loops and drift. Agents can repeat the same search, wander into irrelevant sources or stop too early. Step limits and duplicate-query checks help, but behaviour varies by model.

Costs are hard to predict. As the table shows, total input grows roughly with the square of the number of steps. A few long trajectories can dominate the bill.

Latency adds up. Every step is a sequential model call. Four steps at one to two seconds each is a different user experience from one call.

Evaluation is immature. Trajectory metrics and LLM judges are useful but noisy, and there is no single accepted benchmark for agentic RAG quality in enterprise settings.

Watch next: how frameworks standardise retrieval budgets and context editing for agents, and whether deep research patterns, with planning and parallel sub-agents, become the default for complex internal search.

Frequently asked questions

What is agentic RAG?

Agentic RAG is retrieval-augmented generation where a language model controls retrieval through tools inside a loop. It decides whether to search, which source to use, what query to send and when it has enough to answer, instead of following one fixed retrieve-then-generate step.

When is agentic RAG better than normal RAG?

When questions need several dependent lookups, several sources, or a plan that depends on what is found. For direct questions answered by one or two passages, normal RAG is faster, cheaper and easier to test.

Why is agentic RAG more expensive?

Each step is another model call that re-sends the growing conversation, so total input tokens grow roughly with the square of the number of steps. In the worked example, four calls used 10,800 input tokens versus 3,900 for one call with the same evidence.

How do I stop an agent from looping forever?

Set limits on model calls, tool calls and tokens per question, detect repeated queries, and define clear exit conditions. Frameworks such as Haystack and LangChain provide step limits and call-limit middleware for this.

Is deep research the same as agentic RAG?

Deep research is a long-running form of agentic RAG. It adds explicit planning, many parallel searches, summarisation of findings and a long cited report at the end, but the core loop of deciding, retrieving and reading is the same.

Summary

Agentic RAG makes retrieval a decision inside a loop: the model chooses whether to search, which source to use and what to ask next, which lets it answer multi-hop, multi-source questions that one fixed retrieval cannot. The traced example followed an incident to its service, owner and team lead in three searches across two sources. The price is cost and control: total input grows roughly with the square of the number of steps, so four calls used 2.8 times the tokens of a single-shot answer. Haystack 3.5.0 and LangChain 1.5 now ship agent components with step limits, hooks and middleware for exactly these problems. Route only hard questions to the agent, set budgets, cache prefixes, compress observations, and evaluate trajectories as well as answers.

Sources

Cite this article

Kelahmet, Ö. C. (2026, November 24). Agentic RAG explained: agents that decide when, where and how to retrieve, step by step. Özer Cem KELAHMET. https://www.ozercemkelahmet.com/articles/agentic-rag-retrieval-decisions-deep-research

BibTeX
@online{kelahmet2026agentic,
  author = {Kelahmet, {\"O}zer Cem},
  title  = {{Agentic RAG explained: agents that decide when, where and how to retrieve, step by step}},
  year   = {2026},
  month  = {nov},
  url    = {https://www.ozercemkelahmet.com/articles/agentic-rag-retrieval-decisions-deep-research}
}
Version historyfirst version
  1. Published

Factual corrections are listed here with what changed. Wording and formatting edits are not listed.

Last updated Nov 24, 2026
Type to search.
    ↑↓ navigate↵ open