Skip to main content
LearnMLAcademy
Intermediate10 min read

Retrieval-Augmented Generation (RAG)

Understand Retrieval-Augmented Generation (RAG): indexing vs query phases, source attribution, failure boundaries, diagrams, and self-check quiz.

What you will master in this lesson
Two-phase architecture: offline indexing vs real-time retrieval
Source citation mechanisms, context boundaries & failure modes
When to choose standard prompting vs RAG vs fine-tuning

What if the LLM simply does not know your information?

Imagine asking a general LLM: “According to our company's current HR manual, how many casual-leave days do I get?” The policy may be private, recently changed, or absent from the model's training data.

Fine-tuning is not the natural first solution when the problem is missing current evidence. A simpler idea is: find the relevant approved information first, give it to the LLM with the question, then generate the answer.

That pattern is called Retrieval-Augmented Generation (RAG).

End-to-End 2D RAG Architecture with Validation Gates & Fallbacks

Real production RAG gates context sufficiency before passing documents to the generator.

Happy PathValidation GateAbstain Branch
1. User Query“Casual leave rules?”2. Hybrid RetrievalDense (Bi-Encoder)+ Sparse (BM25)Top-K Candidate ChunksSufficiencyGateScore ≥ 0.75?PASS3. Prompt AssemblyGrounding Context+ User QuestionSystem Instructions4. LLM GenerationGrounded SynthesisAttribution VerificationCite: [HR-2026 §4.2]Verified Answer14 Days + Exact CitationFAIL (< 0.75)Safe Abstention GateRelevance InsufficientNo Hallucination AllowedExplicit Safe Refusal“Information not in handbook”Optional Query Rewrite

Two phases make the system work

Offline preparation versus online answering

Offline preparation versus online answering
PhaseWhat happensWhen
Offline indexingCollect approved sources, split them into chunks, create searchable representations, store text + metadataBefore individual user questions
Online questionRepresent/search the question, retrieve relevant chunks, assemble context, generate and validate an answerFor each user request

A complete beginner example

  1. Question

    The employee asks: “How many casual-leave days do I get?”

  2. Retrieve

    The search layer finds a current HR-policy chunk that says eligible employees receive 12 casual-leave days per year.

  3. Assemble context

    The application sends the user's question plus that policy passage to the LLM.

  4. Generate

    The LLM answers: “The current HR policy states 12 casual-leave days per year.”

  5. Validate and show source

    The application checks that the cited source ID really came from retrieval and presents the answer with traceable evidence.

Follow a source all the way into a citation

The previous example asked about the annual leave allowance. Here is a separate carry-forward question: how many unused days may an India employee carry into the next year? Similar words alone are not enough to choose the source.

CH-17 is the relevant India policy and supports five days. CH-42 discusses a different allowance, while CH-08 belongs to the wrong region. Only the accepted passage and its source ID should support the final claim. If that passage is unavailable, the application no longer has evidence for the number.

RAG evidence trace: a citation must remain connected to accepted evidence

User query

How many leave days can an India employee carry forward?

relevant + allowed

CH-17 · score 0.91

India leave policy: up to 5 days · ACCEPT

plausible wording

CH-42 · score 0.84

Meal allowance cannot carry over · REJECT

wrong region

CH-08 · score 0.80

UK leave policy: 8 days · REJECT

Context packet

Question + CH-17 text + source ID

Answer

Up to 5 unused days [CH-17]

Fallback

No accepted chunk → insufficient evidence

The similar-sounding travel chunk and the wrong-region policy are rejected. If CH-17 is missing, the correct behavior is to report insufficient evidence rather than invent a number.

RAG has several failure boundaries

Where a RAG answer can fail

Where a RAG answer can fail
StageExample failureWhat to inspect
Source/indexOld policy was indexedFreshness, versioning, authorization
RetrievalCorrect passage was not foundQuery representation, filters, retrieval method
Context assemblyCorrect passage was retrieved but droppedSelection, token budget, ordering
GenerationEvidence is present but answer contradicts itPrompt, model behavior, claim checks
Citation/validationAnswer cites a source ID that was never retrievedCitation mapping and provenance validation

What should happen when the evidence is missing?

If no approved source contains enough evidence, the safer behavior is often to abstain, ask for clarification, or escalate according to the application's policy—not invent a plausible answer.

Why the next lesson matters

The RAG idea is simple: retrieve relevant evidence. But how can retrieval find a passage even when the user's wording is different from the document?

Semantic Search with Embeddings →

Summary / Key Takeaways

  • RAG retrieves external evidence and supplies it to an LLM before generation.
  • RAG is useful for current, private, or domain information that should not rely only on model parameters.
  • Indexing prepares source documents before user questions; online retrieval and generation happen per request.
  • Retrieval, context assembly, generation, and citation validation are separate failure boundaries.
  • Citations should map to actually retrieved source metadata.
  • When approved evidence is insufficient, a controlled abstention or escalation is safer than unsupported generation.

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 "Retrieval-Augmented Generation (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
Why is RAG useful even when the LLM is already pretrained?
Question 2 of 5interpretation
Which operation belongs to the offline indexing phase rather than the online question phase?
Question 3 of 5debugging/diagnostic
The correct policy chunk is present in retrieval results but is dropped when context is assembled. Which stage failed first?
Question 4 of 5application/scenario
A generated answer cites source ID `policy-77`, but that ID was never among the retrieved records. What should the application conclude?
Question 5 of 5practical selection
A user asks a question for which no approved source contains sufficient evidence. What is a safer RAG behavior?

Knowledge Check Review & Explanations

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

1Why is RAG useful even when the LLM is already pretrained?▼

Correct Answer: It can supply current/private/domain evidence without retraining the whole model

Retrieval provides external evidence that may be newer or private rather than relying only on model parameters.

2Which operation belongs to the offline indexing phase rather than the online question phase?▼

Correct Answer: Chunking and embedding approved source documents

Source preparation and indexing occur before individual user questions.

3The correct policy chunk is present in retrieval results but is dropped when context is assembled. Which stage failed first?▼

Correct Answer: Context assembly

Retrieval succeeded, but the correct evidence was lost before generation.

4A generated answer cites source ID `policy-77`, but that ID was never among the retrieved records. What should the application conclude?▼

Correct Answer: The citation is not traceable evidence and should fail validation

Citations should map to actual retrieved source metadata rather than be invented.

5A user asks a question for which no approved source contains sufficient evidence. What is a safer RAG behavior?▼

Correct Answer: Abstain or escalate according to the application's evidence policy

When evidence is insufficient, a controlled no-answer/escalation is safer than unsupported generation.

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