LESSON 50 Β· RAG

What is RAG?

Learn how Retrieval-Augmented Generation connects search with an LLM so answers can use relevant external knowledge.

30 min readβ€’Beginnerβ€’Generative AI

By the end of this lesson, you will be able to:

  • Explain Retrieval-Augmented Generation in simple terms.
  • Understand why an LLM can benefit from retrieved information.
  • Describe the main stages of a RAG pipeline.
  • Understand documents, chunks, embeddings, retrieval, context, and generation.
  • Build a simple Python mental model of retrieval followed by generation.
  • Explain how RAG differs from relying only on an LLM's internal knowledge.
  • Recognize common RAG limitations and mistakes.
1

What Is RAG?

RAG stands for Retrieval-Augmented Generation. It is a pattern where an application first retrieves relevant information from an external knowledge source and then gives that information to a generative AI model as context for its answer.

Simple idea:Search for the right information first, then ask the LLM to answer using that information.
EXAMPLE 1Company knowledge

An employee asks about an internal leave policy. RAG retrieves the relevant policy section and places it in the LLM context before generating the answer.

EXAMPLE 2Product support

A customer asks how to configure a device. RAG retrieves the matching manual section and the LLM explains the steps using that evidence.

2

Why Do We Need RAG?

An LLM is powerful, but a general model does not automatically know every private, current, or domain-specific document your application needs.

LLM alone
  • Uses information available to the model
  • May lack private company knowledge
  • May not contain your latest documents
  • Can answer without showing your source context
LLM + RAG
  • Retrieves application-specific information
  • Can use updated documents
  • Supplies relevant context to generation
  • Can return source references alongside answers

RAG does not magically make an LLM correct. It gives the model a better information source for the question.

3

The RAG Pipeline

1. User queryAsk a question
β†’
2. RetrieveFind relevant chunks
β†’
3. Build contextPrepare evidence
β†’
4. GenerateLLM answers

In a real system, there are usually additional steps around this flow: document ingestion, chunking, embedding, indexing, filtering, reranking, prompt construction, citations, evaluation, and monitoring.

4

RAG Has Two Major Parts

PART 1

Retrieval

Find useful information from an external collection such as documents, a vector database, a search index, or another knowledge source.

PART 2

Generation

Give the retrieved information to a generative model and ask it to produce a useful answer.

RETRIEVAL GOAL

Relevant evidence

The retriever should bring back chunks that can actually help answer the user's question.

GENERATION GOAL

Useful response

The LLM should use the supplied context appropriately rather than inventing unsupported details.

5

Where Does the Knowledge Come From?

RAG can retrieve from many types of external knowledge. The source depends on the application.

01PDFs

Manuals, reports, policies, research papers, and guides.

02Web pages

Public documentation, help centers, or approved website content.

03Databases

Structured or semi-structured application information.

04Company documents

Internal knowledge bases, procedures, and project documentation.

05Support content

Tickets, FAQs, troubleshooting guides, and product knowledge.

06Multiple sources

A system can combine several approved knowledge collections.

6

Documents Become Chunks

Large documents are usually not placed into a vector index as one giant block. They are divided into smaller chunks so retrieval can find the specific parts that matter.

Document200-page handbook
β†’
ChunkingSplit into useful sections
β†’
EmbeddingsRepresent chunks as vectors
β†’
IndexStore for retrieval

Good chunking is important because retrieval quality depends heavily on whether each stored chunk contains enough useful meaning without carrying too much unrelated text.

7

Embeddings and Retrieval

In semantic RAG systems, chunks are commonly converted into embeddings. An embedding represents text as a vector so that semantically related queries and documents can be compared.

QUERY

User question

β€œHow can I reset my password?”

↔
CHUNK

Stored knowledge

β€œTo reset your password, open Account Settings and select Change Password.”

A vector search can find the second text even when the query and document do not use exactly the same words.

8

What Happens During a User Query?

1. QuestionUser asks a question
β†’
2. EmbedRepresent the query
β†’
3. SearchFind relevant chunks
β†’
4. ContextPrepare evidence
β†’
5. GenerateLLM writes answer

The exact implementation can differ. Some systems also use keyword search, metadata filters, hybrid search, reranking, query rewriting, or other retrieval strategies before generation.

9

Simple Python RAG Mental Model

The code below intentionally keeps retrieval and generation simple. It shows the core idea without requiring a specific vector database or LLM provider.

</> Python
documents = [
    "You can reset your password from Account Settings.",
    "Shipping usually takes 3 to 5 business days.",
    "Invoices are available from the Billing page.",
]

query = "How do I reset my password?"

# Simplified retrieval for teaching purposes.
keywords = set(query.lower().replace("?", "").split())

retrieved = sorted(
    documents,
    key=lambda doc: len(keywords & set(doc.lower().split())),
    reverse=True,
)[:2]

context = "\n".join(retrieved)

prompt = f"""Answer the question using the context below.

Context:
{context}

Question:
{query}
"""

print(prompt)

In production, the retrieval step would normally use embeddings/search and the final prompt would be sent to an LLM API.

10

RAG Context Goes Into the Prompt

The retrieved chunks are not the answer by themselves. They become context that the generation model can use.

Think of it like this:Retriever = β€œFind the evidence.”   LLM = β€œExplain the evidence.”
</> Python
context = """
Password reset is available from Account Settings.
A password must contain at least 12 characters.
"""

question = "How do I reset my password?"

prompt = f"""
Use only the supplied context when answering.
If the context does not contain the answer, say that you do not have enough information.

Context:
{context}

Question:
{question}
"""

print(prompt)

This pattern is commonly called grounding: the application supplies relevant external information that the model can use when generating its response.

11

RAG vs Fine-Tuning

RAG
  • Retrieves external information at query time
  • Good for changing knowledge
  • Good for private document collections
  • Knowledge can be updated by changing the source/index
Fine-tuning
  • Changes model behavior through training
  • Useful for style, format, or specialized behavior
  • Does not simply act as a live document lookup system
  • Updating knowledge can require another training process

They solve different problems and can also be used together. RAG is primarily about supplying relevant external information at inference time.

12

RAG Does Not Mean the LLM Knows Everything

01Bad retrieval

If the correct chunk is not retrieved, the LLM may not have the evidence it needs.

02Wrong chunk

Irrelevant context can distract the model.

03Too much context

Sending many unnecessary chunks can increase cost and reduce focus.

04Bad source data

Incorrect or outdated documents can produce poor answers.

05Weak instructions

The prompt should clearly explain how the model should use retrieved context.

06Hallucination

RAG reduces some risks but does not guarantee factual answers.

13

How RAG Fits With the Topics You Already Learned

CHUNKING

Prepare knowledge

Split documents into retrievable units.

EMBEDDINGS

Represent meaning

Convert text into vectors for semantic comparison.

VECTOR DATABASE

Store and search

Keep vectors and metadata so relevant chunks can be found.

RETRIEVAL

Find evidence

Return candidate chunks for the user's question.

RERANKING

Improve ordering

Score candidates more precisely when needed.

GENERATION

Answer

Give selected context to the LLM and generate the response.

14

What Makes a Good RAG System?

QUALITY SOURCESReliable and useful knowledge
GOOD CHUNKSMeaningful retrieval units
STRONG RETRIEVALRelevant evidence reaches the candidate set
GOOD RANKINGBest evidence moves toward the top
CONTROLLED CONTEXTUseful evidence without unnecessary text
GOOD GENERATIONAnswer follows the supplied evidence
Important: RAG quality is a pipeline problem. Improving only the LLM while ignoring chunking or retrieval can leave the real bottleneck untouched.
15

When Is RAG Useful?

01Private knowledge

Answer questions over company or application-specific information.

02Frequently changing content

Use a maintained knowledge source instead of depending only on static model knowledge.

03Document Q&A

Ask questions over manuals, policies, reports, or collections of documents.

04Customer support

Retrieve approved troubleshooting and product information.

05Internal search

Help teams find useful information across a knowledge base.

06Research assistants

Retrieve relevant sources before generating a summary or explanation.

16

Common RAG Mistakes

01Skipping evaluation

Do not assume retrieval is good because the demo looks impressive.

02Huge chunks

Very large chunks can contain too much unrelated information.

03Tiny chunks

Very small chunks can lose the context needed to answer a question.

04Retrieving too many

More context is not automatically better.

05Ignoring metadata

Filters such as access, product, language, or date can be important.

06Trusting every source

Retrieved content should come from sources your application is allowed to use.

17

How to Evaluate RAG

RETRIEVAL RECALLDid the system retrieve relevant evidence?
PRECISION@KHow much of the retrieved set is useful?
RANKING QUALITYAre the best chunks near the top?
GROUNDEDNESSDoes the answer stay supported by the context?
ANSWER QUALITYIs the final response useful and correct?
LATENCY & COSTIs the pipeline practical in production?

Evaluate the retrieval stage and the final answer separately. A good LLM cannot compensate for consistently missing evidence.

18

Practice: Design a Simple RAG System

Imagine you have 100 company policy documents and employees can ask questions about them. Design the flow from document ingestion to the final answer.

TASK

Build the RAG pipeline on paper

Write down what happens at each stage: document loading, chunking, embeddings, indexing, query processing, retrieval, context construction, and generation.

Quick Quiz

1. What does RAG stand for?

Retrieval-Augmented Generation.

2. What happens before generation?

The system retrieves relevant external information and prepares it as context for the LLM.

3. Why are documents usually chunked?

Smaller meaningful chunks make it easier to retrieve the specific information relevant to a query.

4. Does RAG guarantee a correct answer?

No. Poor source data, retrieval errors, irrelevant context, or model behavior can still lead to incorrect answers.

30-Second Recap

1. Retrieve

Find relevant external evidence.

2. Context

Give useful evidence to the model.

3. Generate

Ask the LLM to answer using the context.

4. Evaluate

Measure retrieval and final answer quality.

Key Takeaways

  • RAG combines retrieval with generative AI.
  • The retriever finds relevant external information; the LLM uses that information to generate an answer.
  • Documents are commonly chunked, embedded, and indexed before users ask questions.
  • At query time, retrieval finds candidate chunks that become context for generation.
  • RAG is useful for private, domain-specific, and frequently changing knowledge.
  • RAG is not a guarantee against hallucinations or incorrect answers.
  • Good RAG requires strong source data, chunking, retrieval, ranking, context construction, generation, and evaluation.