Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 38/ 160
02. RAG

Agentic RAG

Agents that decide when to search, rewrite, browse, and verify before answering.

AdvancedTool-using RAG · Iterative Retrieve3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

Instead of searching once and answering, the AI decides where to look, checks whether it found enough, and searches again if it didn't.

Think of it like…

A fixed pipeline is a vending machine: press the button, get what's programmed. An agent is a research assistant: they decide where to look, read what they find, notice gaps, look elsewhere and only then write the answer, within the time you gave them.

Where you’ve seen it

A finance analyst assistant gets "How did our APAC gross margin change after the supplier switch, and what did management say about it?" The agent plans three steps: query the warehouse via a SQL tool for margin by quarter, search earnings-call transcripts for management commentary, then compare dates to verify the supplier switch quarter. It spots that the first search returned the wrong region, rewrites the query with a filter, and answers with sources. Cost: 5 model calls and 9 seconds versus 1 call and 2 seconds for simple RAG, which it can't answer correctly.

Words you’ll hear

Agent loop
Repeated cycle of reasoning, tool use and observation until done or out of budget.
Tool routing
Choosing among retrievers and tools (vector search, SQL, web, API) per sub-question.
Sufficiency check
Judging whether retrieved evidence answers the question before generating.
Step budget
Hard limits on iterations, tokens and time to prevent loops and runaway cost.

Visual diagram

Loading interactive diagram

Theory & deep dive

Patterns and components

Common patterns: routing (classify the question and pick a pipeline or tool), query planning and decomposition (split into sub-questions, run in parallel or in sequence), iterative retrieval (search, read, then refine the query based on what's missing), corrective RAG (grade retrieved documents; if poor, rewrite the query or fall back to web search) and self-reflection (the agent critiques its draft against the sources and fixes unsupported claims). Frameworks such as LangGraph, LlamaIndex workflows, and agent SDKs from model providers implement these as graphs or loops with tool calling.

Implementation details matter: expose each tool with a clear description and typed arguments; return concise, cited observations rather than raw dumps; keep a scratchpad of findings; track which evidence supports which claim; and run independent sub-queries in parallel to cut latency. Use a strong model for planning and a cheaper one for routine steps like summarising results.

A bounded controller (pseudo-code)

for step in range(MAX_STEPS): action = llm.decide(state); if action.type == "answer": break; result = tools[action.name](**action.args); state.add(result) with checks for repeated identical calls, token budget and wall-clock timeout.

Key takeaway: Route, decompose, iterate and self-check, with clear tools and hard limits.

Risks, evaluation and when not to use it

Risks: runaway loops and cost, compounding errors (a wrong early step misleads later ones), latency of several sequential calls, nondeterminism that complicates testing, and a larger attack surface, since retrieved text can contain instructions (indirect prompt injection) and tools can have side effects. Mitigate with step and cost budgets, read-only tools by default, allow-lists, input and output validation, human approval for risky actions, and tracing of every step (LangSmith, Langfuse, OpenTelemetry).

Evaluate end to end and per step: task success on a labelled question set (including hard multi-source ones), tool selection accuracy, retrieval quality at each step, citation correctness, number of steps, latency and cost per task. Compare with simple RAG: for single-hop questions it's usually faster, cheaper and as accurate, so route easy questions to the simple path (a classifier or the agent's own first decision). Reserve agentic behaviour for questions that need it, and keep the system explainable by returning the evidence trail.

Routing saves money

70% of traffic is single-lookup and goes to a simple pipeline (1 call, 2 s, $0.004). 30% goes to the agent (6 calls, 9 s, $0.03). Blended cost is about $0.012 per question instead of $0.03, with the agent's accuracy gains kept where they matter.

Key takeaway: Bound, trace and evaluate; route simple questions around the agent.

How it works, step by step

Step 1 of 4
Analysis

1. Identify questions that need agents

Find failures of single-pass RAG: multi-source, multi-step or ambiguous questions.

needs SQL + transcripts + comparison
Key numbers at this step
Keep
simple path for easy ones

When to use it & trade-offs

What it is

In classic RAG the pipeline is fixed: retrieve once, stuff the context, answer. In agentic RAG an LLM agent decides what to do: whether to search at all, which source or tool to use (vector store, SQL, web, calculator), how to rewrite or split the question, whether the evidence is sufficient, and whether to search again or verify before answering. It runs a loop of plan → retrieve → assess → refine until it can answer or admits it can't, using tool calls and a step budget.

Why it matters: Real questions vary: some need no retrieval, some need two sources, some need follow-up searches after the first results reveal a missing detail. A fixed pipeline either over-retrieves for easy questions or under-serves hard ones. Agentic RAG handles complex, multi-step research and heterogeneous data, but costs more, takes longer, is harder to evaluate and can loop or wander, so it must be bounded and measured.

When to reach for it

  • Research and analyst assistants spanning documents and databases
  • Questions requiring comparison or follow-up searches
  • Corrective retrieval when first results are poor

When to avoid or be careful

  • Agents for simple lookups
  • Unbounded loops with no budget
  • Tools with write permissions and no approval step

Fixed pipeline vs agent

Classic RAG (retrieve once, answer)
Best for: Single-hop questions over one knowledge base

Strengths: Fast, cheap, predictable, easy to test.

Watch out: Can't adapt when the first retrieval is wrong or incomplete.

Routed pipelines
Best for: A few known question types

Strengths: Specialised flows; bounded cost.

Watch out: Needs a good router; limited flexibility.

Agentic RAG
Best for: Multi-step, multi-source and ambiguous questions

Strengths: Adaptive; can verify and recover.

Watch out: Higher cost and latency; harder to test and secure.

Interview signals & numbers to know

When this topic comes up

  • “Questions need several searches or sources”
  • “What's the difference between RAG and agentic RAG?”
  • “The agent loops or wanders”
  • Corrective RAG
  • Tool routing

Benchmarks & rules of thumb

5 – 10 s -
typical agentic RAG latency
3 – 8 -
typical step limit
70 / 30 -
share of traffic routed simple / agentic in the example

Common mistakes & follow-ups

Common interview mistakes

  • Using an agent for every request and tripling latency and cost for questions simple RAG answers well.
  • Letting retrieved web text instruct the agent to call tools it shouldn't.
  • Evaluating only final answers, so you can't tell which step broke.

Likely interviewer follow-ups

  • When would you choose agentic RAG over classic RAG?
  • How do you prevent an agent from looping?
  • How would you evaluate an agentic system?
Interview tip: Always mention routing back to simple RAG. Knowing when not to use an agent shows engineering judgement.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Agentic RAG with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
GraphRAG
Next topic
Recall@k