Course contents

16. AI System Design Lesson 5 of 10

Agentic RAG

Let the model decide when and what to retrieve: agent loops, query rewriting, MCP tool calls, and the latency, cost and capacity price of each extra model call.

18 minAdvanced9 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Agentic RAG gives the model search (and other tools) and lets it loop until it can answer.
  • It handles comparisons, chained lookups and live data that single-shot RAG misses.
  • Each step is a full model call: latency adds up, input tokens grow per turn, model load multiplies.
  • Route only hard questions to the agent and enforce step, token and time budgets in the runtime.
  • The model proposes tool calls; the runtime executes them with the user’s permissions.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

Agentic RAG replaces the fixed “retrieve once, then generate” pipeline with a loop controlled by the model. The model receives the question and a set of tools (search the knowledge base, query a system, fetch a document) and, at each step, either requests a tool call or writes the final answer. A runtime executes the requested tools and feeds the results back as new messages, until the model answers or a budget runs out.

Why it exists

Single-shot RAG searches once with the user’s wording. That fails for comparisons (two policy versions), chained questions (find the manager, then the approval rule for that manager), vague follow-ups (“and for part-timers?”), and questions whose answer lives in a live system rather than in documents. Letting the model plan queries, inspect results and search again handles these, at the price of more model calls.

How it works

The loop. Runtime sends the conversation plus tool definitions to the model. The model returns either text or one or more tool calls (name and JSON arguments). The runtime validates and executes them, appends the results, and calls the model again. Each step sees everything so far.

Query rewriting and decomposition. Often the first model step: turn the conversation into standalone queries, split compound questions into sub-queries that can run in parallel, add formal terms or filters (year, department). Rewriting is also useful on its own, as one cheap call in front of plain RAG.

Tools beyond search. The same mechanism reaches APIs and databases. The Model Context Protocol (MCP) standardises how tools, resources and prompts are exposed by servers and discovered by clients, so one HR or ticketing integration can serve many agents. Tool results are untrusted input to the model: they can contain wrong data or injected instructions.

Who executes. The model never runs anything. The runtime checks the tool name and arguments against a schema, authorises the call for the current user, applies timeouts and rate limits, executes it, logs it, and returns the result.

Cost. Steps are sequential because each depends on the previous result, so latency is the sum of the model calls. Input tokens grow with every turn as the transcript gets longer. Model load is questions × average calls per question; capacity planning has to use calls and tokens, not questions.

Control. A query router (rules, a classifier or a small model) sends simple questions to single-shot RAG and only hard ones to the agent. Budgets cap tool calls, tokens and wall-clock time per run; when one is hit, the runtime asks for a best-effort final answer. Streaming progress (“searching the 2025 policy…”) keeps users informed during multi-second runs.

When to use it

  • Questions that compare, aggregate or chain facts across documents.
  • Assistants that mix document knowledge with live data from internal systems.
  • Conversational use where follow-ups need rewriting into standalone queries.
  • When answer quality on hard questions matters more than latency and cost per question.

When not to

  • Simple lookups and FAQs: single-shot RAG is faster, cheaper and more predictable.
  • Strict latency budgets (sub-second responses).
  • Workflows with a known sequence of steps: write them as code (a fixed pipeline or workflow) and use the model only where judgement is needed.
  • When you cannot evaluate or monitor multi-step behaviour yet: start with single-shot RAG plus query rewriting.

Trade-offs

Choice You gain You pay
Agent loop Multi-hop, comparison and tool-backed answers Latency adds per step; tokens grow per turn; less predictable
Query rewriting only Better retrieval for follow-ups and vague questions One extra model call
Router in front Agent cost only where needed Misrouted questions; another component to evaluate
Tight budgets Bounded worst-case cost and latency Some hard questions get incomplete answers
Parallel tool calls Lower latency for independent sub-queries More concurrent load on tools and model

Alternatives

  • Single-shot RAG with query rewriting and hybrid retrieval: covers many “hard” questions at a fraction of the cost.
  • Fixed multi-step pipelines: decompose, retrieve per sub-query, then synthesise, in code with a known number of calls.
  • Structured queries: for aggregations over records, let the model call a query API or generate SQL against a read-only view instead of reading many text chunks.
  • Precomputed answers or summaries for frequent complex questions.

Failure modes

  • Runaway loops: the model keeps searching or retrying tools; cost and latency explode without budgets.
  • Capacity multiplication: a traffic increase that single-shot RAG would absorb saturates the model deployment, and questions fail after several calls have already been paid for.
  • Wrong tool, wrong arguments: the model calls a tool with invented parameters; schema validation and clear tool descriptions reduce it.
  • Excessive agency: tools that write or delete without confirmation, or run with broader permissions than the user has.
  • Prompt injection through tool results: retrieved documents or API responses containing instructions the model follows.
  • Context bloat: long transcripts of tool results crowd out the question; summarise or truncate intermediate results.

In production

Trace every run as a tree: each model call (tokens, latency, model), each tool call (arguments, duration, result size) and the final answer; OpenTelemetry’s generative AI conventions cover the basics. Track calls and tokens per question, budget hits and tool error rates. Evaluate on multi-hop question sets, not only single-fact lookups. Run tools with the end user’s identity and least privilege, and require confirmation for actions with side effects. In .NET, Microsoft.Extensions.AI supports function invocation over IChatClient, the official MCP C# SDK provides clients and servers, and Semantic Kernel and Microsoft’s agent frameworks add orchestration on top.

Common misconceptions

  • "Agents are always smarter." They handle certain question shapes better; for simple ones they are just slower and more expensive.
  • "The model calls the API." The model emits a request; your runtime decides whether and how to execute it.
  • "Cost scales with the number of calls." It scales faster, because each call re-sends the growing transcript.
  • "A prompt instruction limits the loop." Only a budget enforced by the runtime does.
  • "More capacity fixes agent overload." It helps, but routing and step limits usually cut model load more cheaply.

Interview angle

When an interviewer extends a RAG design with “what about complex questions?”, describe the agent loop with search as a tool, query rewriting, and when to prefer a fixed pipeline. Quantify: calls per question, latency as the sum of sequential calls, tokens growing per turn, model capacity in calls per second. Then show control: a router, budgets, parallel sub-queries, streaming progress, and a runtime that validates and authorises every tool call, with tracing for debugging.

Model assumptions

The simulation is a simplified model, not a benchmark. Questions arrive randomly (Poisson). The agent runtime calls its dependencies one after another in connection order, so the agent loop is a fixed chain of LLM, search, LLM, search, LLM (separate connections to the same nodes); in reality the model decides the number of steps at run time. The LLM has 16 concurrent slots, ~1.5 s per call (lognormal, cv 0.4) and a short waiting line; every call is modelled as equally long, although real calls grow with the transcript. Search takes ~40 ms. The query router is a weighted balancer with a fixed 30/70 split. Tool-call messages, query rewriting, loop budgets and MCP calls are scripted illustrations. Token counts are illustrative.

The lesson as textEvery step of the simulation, written out.
  1. 1. One retrieval is not always enough

    This is classic RAG: search once, then generate once. It works for *“How many days of parental leave do we get?”* It fails for *“How did parental leave change between 2025 and 2026?”*: one search returns the 2026 policy chunks, the 2025 version never reaches the prompt, and the answer is half right.

    Questions that compare, chain facts (“who approves expenses for the manager of team X?”) or need data from different tools do not fit a fixed retrieve-then-generate pipeline. Each request here makes one LLM call: ~1.6 s.

    Scene: Each question triggers one search and one LLM call, about 1.6 seconds in total. A comparison question only retrieves the 2026 policy, so the answer is incomplete.

    Key idea: Single-shot RAG retrieves once with the user’s words; multi-part questions need more than one search.

  2. 2. Let the model decide what to search

    In agentic RAG the model gets search as a tool and works in a loop. It reads the question and plans: *search “parental leave policy 2025”*. The runtime runs the search and returns the results. The model looks at them and decides: *search “parental leave policy 2026”*. With both in hand, it writes the answer.

    The scripted packets show one such loop: three LLM calls and two searches, strictly one after another, because each decision depends on the previous result. Every simulated request now follows the same five-step chain.

    Scene: Scripted: the agent runtime asks the LLM, which requests a search; the runtime runs it and asks the LLM again, which requests a second search; the third LLM call writes the answer. Simulated requests now make three LLM calls and two searches each.

    Key idea: An agent loop alternates model decisions and tool calls until the model decides it can answer.

  3. 3. Better queries than the user typed

    Users write *“and what about part-timers?”* as a follow-up. Searching for that text finds nothing useful. Part of the agent’s first LLM call is query rewriting: turning the conversation into standalone search queries (*“parental leave part-time employees 2026”*), splitting a compound question into sub-queries, or adding the formal term (*annual leave* for *PTO*).

    The scripted packets show the rewrite producing two sub-queries that go to the search tool together. Rewriting can be a step inside the agent loop or a cheap, single LLM call in front of plain RAG; it often fixes retrieval without a full agent.

    Scene: Scripted: the first LLM call rewrites a vague follow-up question into two standalone sub-queries, which the agent runtime sends to the search tool in parallel.

    Key idea: Rewrite the user’s words into standalone, specific search queries; split compound questions.

  4. 4. Three model calls per question

    Compare with single-shot RAG: each question now waits for three sequential LLM calls, so P50 is around three times higher (~5 s instead of ~1.6 s). The searches are a rounding error.

    Cost grows faster than the call count, because every call re-sends the conversation so far: instructions, question, previous tool calls and their results. Illustratively ~1.5k, ~3k and ~4.5k input tokens, about 9k in total against ~3k for one call. Agents trade latency and money for the ability to handle harder questions.

    Scene: Each question makes three LLM calls one after another; median latency is about three times that of single-shot RAG.

    Key idea: Every agent step is another full model call: latency adds up, input tokens grow with each turn.

  5. 5. The model deployment fills up

    Traffic doubles to 4 questions per second. Single-shot RAG would need 4 LLM calls per second. The agent needs 12. The deployment has 16 slots at ~1.5 s per call, about 10.7 calls per second: it saturates, its queue fills, and questions fail mid-loop, after the first calls have already been paid for.

    The search tool is barely busy. When agents fail under load, look at the model first.

    Scene: At 4 questions per second the agent sends about 12 calls per second to the LLM, more than its capacity of about 10.7. The LLM is saturated and some questions fail; the search tool is mostly idle.

    Key idea: Agents multiply model load by the number of steps. Capacity plans must count calls, not questions.

  6. 6. Route only hard questions to the agent

    Most questions are simple lookups. A query router in front sends them down the single-shot RAG path (one LLM call) and only the hard ones, about 30% here, to the agent. Real routers use rules, a small classifier or a cheap model call; this one is a fixed 30/70 split.

    LLM load drops from 12 to about 6.4 calls per second, the errors stop and median latency falls, because most answers are single-shot again. The agent stays available for the questions that need it.

    Scene: A query router sends 30% of questions to the agent and 70% to a single-shot RAG path. The LLM receives about 6.4 calls per second, nothing fails and median latency drops.

    Key idea: Pay for agent loops only where they help: route simple questions to a single-shot path.

  7. 7. Stop the loop that never ends

    Sometimes the model keeps searching: each result looks almost right, so it tries one more query. Without limits a single question can make dozens of calls and cost more than a thousand normal ones.

    The agent runtime enforces budgets: at most 4 tool calls (in this example), a token budget and a wall-clock deadline. The scripted loop hits the limit after the fourth search; the runtime then asks the model for a final answer from what it has, flagged as possibly incomplete. Log every step so runaway patterns show up in monitoring.

    Scene: Scripted: the agent searches four times in a row; at the budget limit the runtime stops calling tools and asks the LLM for a final answer, which goes back to the Assistant API.

    Key idea: Every agent loop needs hard limits on steps, tokens and time, enforced by the runtime, not the model.

  8. 8. The model asks, the runtime acts

    Tools are not only search. The agent can also call a Model Context Protocol (MCP) server that exposes the HR system: *get_leave_balance(employee)*. The model never calls anything itself. It returns a structured tool call (name and JSON arguments); the runtime validates it, checks the user’s permissions, executes it and passes the result back as the next message.

    The scripted packets show that path: LLM → runtime → MCP server → runtime → LLM. Because the runtime sits in the middle, it is where you enforce authorisation, rate limits, timeouts and audit logging for everything an agent does.

    Scene: Scripted: the LLM returns a tool call to the agent runtime, which calls the HR system through its MCP server and sends the result back to the LLM for the final answer. The LLM never contacts the MCP server directly.

    Key idea: The model only proposes tool calls; the runtime executes them with the user’s permissions and limits.

  9. 9. When an agent is worth it

    Agentic RAG handles questions single-shot RAG cannot: comparisons, multi-step lookups, data from several tools, follow-ups that need rewriting. It costs more calls, more tokens, more latency and less predictability.

    The design moves: route only hard questions to the agent, rewrite queries, cap every loop, stream progress (“searching the 2025 policy…”) so users see something happen, and run tools through a runtime that enforces permissions. In .NET, Microsoft.Extensions.AI handles function calling over IChatClient, and Semantic Kernel and Microsoft’s agent frameworks add agent orchestration; the architecture questions stay the same.

    Scene: The final system: a query router, an agent runtime with search and MCP tools, a single-shot RAG path, and a shared LLM.

    Key idea: Use an agent where a fixed pipeline fails, behind a router, with budgets, permission checks and logging.