New cohort: Agentic AI & LLM Engineering remote internship. Limited seats.Apply now
Lesson 15 of 21 26 minFree

Retrieval-Augmented Generation (RAG) and Vector Databases

Make an LLM answer from your own documents: retrieve the right chunks, add them to the prompt, and generate grounded answers with citations.

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

  • Explain what RAG is and why it beats asking the model on its own.
  • Walk through the RAG pipeline: ingest, retrieve, augment, generate.
  • Write a grounded prompt that cites sources and admits when the answer isn't there.
  • Improve and evaluate a RAG system: chunking, hybrid search, re-ranking and groundedness.

The problem: the model doesn't know your stuff

Students ask our study buddy about their school: "When do exams start?", "What did our notes say about Ohm's law?", "What's the fee for next term?". The model's training data doesn't contain your school's documents. It also has a knowledge cut-off. Ask anyway and you get a polite guess, or a confident hallucination.

Retrieval-Augmented Generation (RAG) solves this. Before the model answers, your app retrieves the most relevant pieces of your own documents and adds them to the prompt. The model then generates an answer grounded in that text, with citations.

Watch RAG work

On the left are chunks from the school's documents: physics notes, biology notes and admin notices. Ask a question and watch the three best chunks fly into the prompt before the model answers.

The RAG pipeline

Phase 1: ingest your documents

  1. Load PDFs, web pages, notes and FAQs, and extract clean text.
  2. Chunk them into passages of a few hundred tokens with a little overlap (Lesson 8). Keep metadata: title, page, class, subject, date.
  3. Embed each chunk with an embedding model.
  4. Store the vectors, text and metadata in a vector database or search index: Azure AI Search, PostgreSQL with pgvector, Chroma, Qdrant, Pinecone and others.

Phase 2: answer a question

  1. Retrieve: embed the question and fetch the top 3–5 most similar chunks. Add metadata filters if you need them, for example only Class 10.
  2. Augment: put those chunks in the prompt, numbered, inside clear delimiters (Lesson 13).
  3. Generate: ask the model to answer only from the sources, cite them, and say so if the answer isn't there.

A grounded RAG prompt:

You are Vidya, the school's study helper.
Answer the question using ONLY the sources below.
Cite sources like [1] after each fact.
If the answer is not in the sources, say "I couldn't find that in the school's documents."

<sources>
[1] Ohm's law: V = I × R (Physics notes, Class 10, p.4)
[2] Resistance grows with wire length (Physics notes, p.5)
</sources>

Question: What is Ohm's law?

RAG vs fine-tuning

RAG

Best for knowledge: facts, documents and policies that change. Update a document and answers update immediately. Gives citations. No training needed.

Fine-tuning (Lesson 18)

Best for behaviour: a consistent style, format or narrow skill. Needs many training examples and retraining when things change. Doesn't give citations.

Many production systems use both: RAG for knowledge, light fine-tuning or good prompts for style.

Making RAG good

  • Chunking matters most: too big and retrieval gets vague, too small and context is lost. Split by headings or paragraphs where you can.
  • Hybrid search: combine keyword search (exact terms, codes, names) with vector search (meaning).
  • Re-ranking: retrieve 20 candidates, then use a re-ranker model to pick the best 3–5.
  • Metadata filters: class, subject, date, language, permissions. Students should only see what they're allowed to see.
  • Evaluate (Lesson 14): measure retrieval (did the right chunk come back?) and groundedness (is every claim supported by a cited source?).

RAG reduces hallucinations; it doesn't eliminate them. If retrieval returns the wrong chunks, the model can still answer confidently from them. Always cite sources and let users click through to check.

Hands-on: a tiny RAG system in pure Python

Your task: real systems use embeddings. Here we use simple word overlap so it runs anywhere. Complete score() (count how many question words appear in the chunk) and build_prompt() (number the top chunks as [1] ...). Expected: the line Retrieved: [1] Exams start on 3 March.

import re

chunks = [
    "Ohm's law states that voltage equals current times resistance.",
    "Exams start on 3 March and end on 21 March.",
    "The library is open from 8 am to 6 pm on weekdays.",
    "Fees for the next term are 4999 rupees, payable by 15 February.",
    "Photosynthesis needs sunlight, water and carbon dioxide.",
]
STOP = {"the", "a", "an", "is", "on", "and", "of", "to", "for", "when", "do", "does", "what", "are"}

def words(text):
    return {w for w in re.findall(r"[a-z0-9']+", text.lower()) if w not in STOP}

def score(question, chunk):
    # TODO: return how many of the question's words also appear in the chunk
    return 0

def retrieve(question, k=2):
    return sorted(chunks, key=lambda c: score(question, c), reverse=True)[:k]

def build_prompt(question, top):
    # TODO: number each chunk like "[1] ...", one per line
    sources = ""
    return f"Answer ONLY from these sources and cite them.\n<sources>\n{sources}\n</sources>\nQuestion: {question}"

question = "When do exams start?"
top = retrieve(question)
prompt = build_prompt(question, top)
print(prompt)
print("---")
first = prompt.split("<sources>\n")[1].split("\n")[0]
print("Retrieved:", first.split(" and end")[0])
Show solution
def score(question, chunk):
    return len(words(question) & words(chunk))

    sources = "\n".join(f"[{i}] {c}" for i, c in enumerate(top, 1))

Your task: a simple but powerful groundedness check: every citation in the answer must point to a source that was actually given. Find all [n] numbers in the answer and print the ones that don't exist. Expected: Ungrounded citations: [3].

import re

sources = ["Exams start on 3 March and end on 21 March.", "The library is open from 8 am to 6 pm."]
answer = "Exams begin on 3 March [1]. The library opens at 8 am [2]. Results come out in May [3]."

# TODO: cited = all numbers inside [ ] in the answer (as ints), e.g. using re.findall(r"\[(\d+)\]", answer)
cited = []
# TODO: bad = citations that are not between 1 and len(sources)
bad = []

print("Cited:", cited)
print("Ungrounded citations:", ", ".join(f"[{n}]" for n in bad) if bad else "none")
Show solution
cited = [int(n) for n in re.findall(r"\[(\d+)\]", answer)]
bad = [n for n in cited if not 1 <= n <= len(sources)]

Check your understanding

What does the "augment" step of RAG do?

  1. Retrains the model on your documents
  2. Makes the model bigger
  3. Adds the retrieved chunks to the prompt
  4. Translates the answer

Retrieve finds the chunks, augment puts them in the prompt, generate writes the grounded answer.

The school changes its fee policy. With RAG, what do you need to do?

  1. Update the document in the index. Answers change immediately
  2. Fine-tune the model again
  3. Wait for the next model release
  4. Change the temperature

That's RAG's superpower: knowledge lives in your documents, not in the model's weights.

The answer isn't in any retrieved chunk. A well-designed RAG prompt makes the model…

  1. Answer from general knowledge without saying so
  2. Make up a source
  3. Return an error code
  4. Say it couldn't find the answer in the documents

Grounded prompts tell the model to admit when the sources don't contain the answer.

Use RAG or fine-tuning to make answers come from the latest school notices?

  1. Fine-tuning
  2. RAG
  3. Neither
  4. Only a bigger context window

Changing facts and documents are RAG's job. Fine-tuning is for style and behaviour.

Key takeaways

  • RAG = retrieve relevant chunks + augment the prompt + generate a grounded answer.
  • Ingest once (chunk, embed, store), then retrieve for each question.
  • Prompt for citations and an honest "not found".
  • Improve with good chunking, hybrid search, re-ranking and filters, and evaluate retrieval and groundedness.

Next: open-source models and Hugging Face.

Your progress is saved in this browser.

Adapted from Lesson 15 of Microsoft's "Generative AI for Beginners" (MIT License), rewritten and extended by Aiprojects4U. View source