Skip to main content
LearnMLAcademy
Advanced10 min read

Agentic RAG

Build agentic RAG systems with intelligent routing and verification, with workflow diagrams, tool-use traces, and safety-focused exercises.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

When retrieval needs more than one search

Agentic RAG lets an agent decide when, where, and how to retrieve, reformulate weak queries, use multiple sources, and verify whether evidence is sufficient.

What You Will Learn

  • Decide when adaptive retrieval is worth more than one fixed search.
  • Transform queries and choose sources from observed evidence gaps.
  • Grade relevance, authority, provenance, and conflicting evidence.
  • Stop retrieval using evidence and resource budgets.

What makes retrieval agentic?

Baseline RAG follows one designed retrieval path: transform the question, retrieve passages, and generate from them. Agentic RAG adds decisions around that path. The agent may decide retrieval is unnecessary, choose a source, reformulate a weak query, follow a cited document, compare evidence, or stop because the available sources cannot support an answer.

The agent should not merely ask whether passages look similar to the question. It should check relevance, authority, publication or effective date, provenance, and whether the evidence actually covers the claims the answer must make. When trusted sources conflict, the conflict is itself an outcome to report or escalate—not an invitation to average them together.

Baseline RAG versus Agentic RAG

Baseline RAG versus Agentic RAG
QuestionBaseline RAGAgentic RAG
Retrieval triggerAlways follows the designed retrieval stepModel or policy decides whether retrieval is needed
Number of searchesUsually oneOne or more within a budget
Query adaptationFixed transformRewrites after observing evidence gaps
Evidence checksOften relevance-focusedRelevance, authority, provenance, sufficiency and conflict
Latency / costLower and more predictableHigher and variable
Best fitRoutine grounded questionsComplex questions needing source or query adaptation

Instructional figure

Baseline RAG and Agentic RAG take different paths

Where does an adaptive retrieval system make extra decisions?

Baseline RAG

Question
Retrieve once
Answer

Agentic RAG

Decide retrieval
Choose source + query
Grade evidence
Rewrite / answer / abstain
Baseline RAG performs one designed retrieval. Agentic RAG can decide, grade, rewrite, change source, and abstain—but every extra loop adds latency and risk.

Retrieve, judge the evidence and choose the next search

  1. Classify whether retrieval is needed.

  2. Plan one or more searches with filters.

  3. Grade retrieved evidence and reformulate if weak.

  4. Synthesize with citations, verify support, and stop within a retrieval budget.

Bound the corrective retrieval loop

A weak result can trigger a more specific query, a different approved collection, or a request for clarification. Each retry must have a reason tied to an evidence gap. Stop after the configured attempt, latency, or cost limit, and return the best supported partial result or abstain.

Agentic RAG is not worthwhile when one well-tuned retrieval query already solves the task, when low latency is critical, or when the source space is too weak to benefit from adaptation. Extra searches add cost and increase exposure to irrelevant or hostile content.

Instructional figure

The corrective retrieval loop

What should happen when evidence is weak or conflicting?

Retrieve
approved source + focused query
Grade evidence
relevance • authority • date • provenance
Sufficient
grounded answer
Named gap
rewrite or change source ↺
Conflict / budget
report or abstain
Each retry targets a named evidence gap. The loop stops when evidence is sufficient, sources conflict, or retrieval/time/cost budgets are exhausted.

Worked Example: Comparing the latency of one retrieval with an adaptive loop

The times below are illustrative measured components for one question, not universal performance claims.

  1. Baseline RAG uses one retrieval taking 0.25 s and one answer generation taking 1.10 s.
  2. Baseline total = 0.25 + 1.10 = 1.35 s.
  3. Agentic RAG uses a 0.35 s decision, two retrievals at 0.25 s each, a 0.30 s evidence check, and a 1.10 s answer generation.
  4. Agentic total = 0.35 + (2 × 0.25) + 0.30 + 1.10 = 2.25 s.
  5. Extra latency = 2.25 − 1.35 = 0.90 s.

What the result means: Adaptive retrieval must earn its extra 0.90 seconds by improving evidence quality on the task; otherwise baseline RAG is the better design.

A Realistic Example: Researching a policy change

The agent searches the latest policy, follows a referenced amendment, compares effective dates, and refuses to answer if authoritative documents conflict.

Read the Mechanism in Code

Use the label and note to understand what this block represents before reading each line.

Conceptual pseudocode
for attempt in range(3):
    docs = retrieve(query, filters={"approved": True})
    grade = relevance_and_authority(docs, question)
    if grade.sufficient:
        return grounded_answer(question, docs)
    query = rewrite_query(question, docs, grade)
return escalate("Insufficient evidence")
Learner note: Conceptual adaptive-retrieval loop. retrieve(), grade, rewrite_query(), and grounded_answer() represent application components.

Hands-On Runnable Python Lab: Reject an Old Policy and Fill a Missing Refund Claim

The first fixture returns a current price and an outdated refund rule. Only the current price is accepted. A second targeted search returns the current 30-day policy. Two searches are allowed.

coverage = supported_required_fields / total_required_fields; 1/2 → 2/2
Coverage here measures two explicit fields, price_usd and refund_days. It is not a universal automatic score for factual correctness or answer quality.
  1. Accept D1’s $40 price and reject OLD because current=False.
  2. Compute the missing field: refund_days. Use that gap to select a policy lookup.
  3. Accept D2’s 30-day rule, retaining D2 as its source.
  4. Produce a supported answer only when both fields are present; test a second run without D2 to demonstrate a partial answer.

One missing claim drives one targeted retrieval

First search accepts D1 price 40 and rejects the obsolete 90-day rule. A targeted second search adds D2 refund 30 days, filling both required evidence fields.Search 1: broad plan queryD1 · price $40ACCEPTOLD · refund 90 daysREJECTCoverage: price ✓ / refund ?Search 2: refund policyD2 · refund 30 daysACCEPTCoverage 2/2 → $40 [D1], 30 days [D2]
A rejected 90-day policy never enters the answer. D1 supports the price and D2 supports the refund period; without D2 the answer remains partial.

A rejected 90-day policy never enters the answer. D1 supports the price and D2 supports the refund period; without D2 the answer remains partial.

Complete Python ExercisepythonRunnable
batches = [
    [{"id": "D1", "current": True, "facts": {"price_usd": 40}},
     {"id": "OLD", "current": False, "facts": {"refund_days": 90}}],
    [{"id": "D2", "current": True, "facts": {"refund_days": 30}}],
]
required = {"price_usd", "refund_days"}

def retrieve_and_check(search_results):
    evidence, sources = {}, {}
    for attempt, docs in enumerate(search_results[:2], start=1):
        print("search", attempt, "for", sorted(required - evidence.keys()))
        for doc in docs:
            if not doc["current"]:
                print(" rejected:", doc["id"], "(outdated)")
                continue
            for field, value in doc["facts"].items():
                if field in required:
                    evidence[field] = value
                    sources[field] = doc["id"]
        print(f" coverage: {len(evidence)}/{len(required)}")
        if required <= evidence.keys():
            break
    if required <= evidence.keys():
        print(f"Answer: USD {evidence['price_usd']} [{sources['price_usd']}]; "
              f"{evidence['refund_days']}-day refunds [{sources['refund_days']}]")
    else:
        print("Partial evidence:", evidence)
        print("Cannot verify:", ", ".join(sorted(required - evidence.keys())))

print("Complete run")
retrieve_and_check(batches)
print("Missing-policy run")
retrieve_and_check(batches[:1])
Run with Python 3 using only its standard library. No API key, paid service or model download is required. Model proposals and external observations are explicitly simulated; the application logic really executes.
Output from This Exact ProgramOutput
Complete run
search 1 for ['price_usd', 'refund_days']
 rejected: OLD (outdated)
 coverage: 1/2
search 2 for ['refund_days']
 coverage: 2/2
Answer: USD 40 [D1]; 30-day refunds [D2]
Missing-policy run
search 1 for ['price_usd', 'refund_days']
 rejected: OLD (outdated)
 coverage: 1/2
Partial evidence: {'price_usd': 40}
Cannot verify: refund_days
Captured with Python 3.12. Fixture timings, prices and evaluation results are teaching inputs, not provider benchmarks.

What This Run Shows

  1. The outdated 90-day rule never enters accepted evidence despite matching the topic.
  2. The second search has a visible purpose: fill one missing field.
  3. When D2 is unavailable, the controller names the missing claim instead of borrowing the rejected rule.

Compare adaptation with a well-tuned fixed pipeline on the same test set. Extra retrieval is justified only when its gain in supported answers outweighs latency, cost and exposure to untrusted material.

From the Exercise to an Application

From the Exercise to an Application
SituationPractical choiceImportant qualification
First result sufficientAnswer and stopMore searches can add cost without useful evidence.
One specific gapSearch the relevant authorized collectionKeep refinement tied to that gap.
Conflicting authoritative factsReport or resolve the conflict using policyDo not overwrite one with the last retrieved value.
Experiment: Mark the old policy as current=True.

The fixture is accepted and could prematurely produce a 90-day answer. Metadata quality and authority checks are part of retrieval correctness, not decoration.

Summary / Key Takeaways

  • Baseline RAG usually retrieves once; Agentic RAG lets the system decide whether, when, where, and how to retrieve.
  • An Agentic RAG loop can rewrite queries, change sources, grade evidence, and retrieve again when the first attempt is weak.
  • Evidence sufficiency and authority should be checked before generation, not assumed because retrieval returned documents.
  • Conflicting authoritative sources may require abstention or escalation rather than another blind retrieval loop.
  • Every additional retrieval and grading step adds latency, cost, and exposure to irrelevant or malicious content.
  • Retrieval attempts, source permissions, query rewrites, and tool authority should therefore be bounded.
  • Agentic RAG is justified when adaptive retrieval measurably improves difficult questions; simple RAG remains preferable for straightforward cases.

Verified Further Reading

These primary research papers and current official specifications support the concepts and implementation guidance in this lesson. The explanations, analogies, exercises, and code above remain original teaching material.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Agentic RAG"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5conceptual
What makes Agentic RAG different from a typical retrieve-once RAG pipeline?
Question 2 of 5numerical/formula
Baseline RAG takes 0.25 s for retrieval and 1.10 s for generation. What is the total sequential latency?
Question 3 of 5interpretation
In the worked example, Agentic RAG takes 2.25 s while baseline RAG takes 1.35 s. What should justify the extra 0.90 s?
Question 4 of 5application/scenario
Two authoritative sources disagree about the effective date of a policy. What is the safest agent behavior?
Question 5 of 5debugging/diagnostic
An Agentic RAG system rewrites the same query six times and returns nearly identical results. What is missing?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1What makes Agentic RAG different from a typical retrieve-once RAG pipeline?▼

Correct Answer: It can decide whether to retrieve, adapt queries/sources, grade evidence, and retrieve again

Agentic RAG adds adaptive retrieval decisions and evidence checks rather than using one fixed retrieval step.

2Baseline RAG takes 0.25 s for retrieval and 1.10 s for generation. What is the total sequential latency?▼

Correct Answer: 1.35 s

0.25 + 1.10 = 1.35 seconds.

3In the worked example, Agentic RAG takes 2.25 s while baseline RAG takes 1.35 s. What should justify the extra 0.90 s?▼

Correct Answer: Measurable improvement on difficult retrieval cases

Adaptive retrieval is worthwhile only when its extra steps produce enough quality/reliability benefit to justify added latency and cost.

4Two authoritative sources disagree about the effective date of a policy. What is the safest agent behavior?▼

Correct Answer: Surface the conflict and abstain/escalate unless it can be resolved

Conflicting authoritative evidence should not be hidden. The system should resolve it with a trusted source or abstain/escalate.

5An Agentic RAG system rewrites the same query six times and returns nearly identical results. What is missing?▼

Correct Answer: A no-progress/retrieval budget stop

Adaptive retrieval needs bounded attempts and no-progress detection to avoid expensive loops.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Next