Velamuvi AIAcademy

Lesson 1 of 16 · Foundations

What Is RAG?

Retrieval-augmented generation explained simply: why LLMs need your documents, the retrieve, augment, generate steps, what RAG fixes, with runnable Python.

  • 6 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Explain what retrieval-augmented generation (RAG) is
  • Describe the three steps: retrieve, augment and generate
  • List the problems RAG solves: private data, fresh facts, sources
  • Recognise what RAG does not fix on its own

The problem: the model doesn't know your documents

A large language model learned from a huge amount of public text, up to a cut-off date. It has never seen your company handbook, your product manuals, yesterday's price list or your customer's contract. Ask it about them and it will either say it doesn't know or, worse, give a confident guess.

You could paste the right document into the prompt yourself. RAG automates exactly that.

The three steps

  1. Retrieve: search your documents for the passages most relevant to the question, usually with embeddings and a vector database.
  2. Augment: put those passages into the prompt, with instructions to answer only from them.
  3. Generate: the LLM writes the answer, ideally citing which passage it used.

Here are all three steps on a tiny company handbook. The search uses a small, see-inside embedding model (one dimension per topic, such as leave or expenses) so you can follow every number. The generate step needs an API key, so this program stops at the prompt the LLM would receive:

Try it yourselfPython
import math, re

# ---- A tiny see-inside embedding model: one dimension per concept ----
CONCEPTS = {
    "leave":     "leave holiday holidays vacation annual time-off carried",
    "sick":      "sick ill illness unwell doctor self-certify",
    "remote":    "remote home hybrid office hours",
    "expenses":  "expenses expense claim reimbursed receipt receipts meals",
    "equipment": "laptop laptops monitor headset equipment lost stolen",
    "security":  "password passwords 2fa two-factor login phishing security",
    "parental":  "parental maternity paternity baby birth adoption adoptive",
    "training":  "training course courses learning books conferences",
    "travel":    "travel trip trips flight flights train trains journeys",
    "pay":       "pay paid salary payroll",
}
WORDS = {c: set(words.split()) for c, words in CONCEPTS.items()}

def words(text):
    return re.findall(r"[a-z0-9'-]+", text.lower())

def embed(text):
    v = [sum(w in WORDS[c] for w in words(text)) for c in CONCEPTS]
    length = math.sqrt(sum(x * x for x in v))
    return [x / length for x in v] if length else v

def cosine(a, b):
    return sum(x * y for x, y in zip(a, b))       # vectors are unit length

# ---- The knowledge base: sections of a company handbook ----
HANDBOOK = {
    "Annual leave": "Full-time employees get 25 days of paid annual leave per year, plus public holidays. Book holiday in the HR portal at least two weeks ahead. Up to 5 unused days can be carried over to next year.",
    "Sick leave": "If you are ill, tell your manager before 10am on your first day off. You can self-certify for up to 7 days; after that you need a note from a doctor. Sick pay is your full salary for up to 10 days per year.",
    "Remote work": "You can work from home up to 3 days a week, with your manager's agreement. Core hours are 10am to 4pm. The office is open from 7am to 8pm.",
    "Expenses": "Claim expenses within 30 days in the finance app, with a photo of each receipt. Meals on work trips are reimbursed up to 40 euros per day. Approved expenses are paid with your next salary.",
    "Equipment": "New starters get a laptop, a monitor and a headset. Report a lost or stolen laptop to IT within 24 hours. Laptops are replaced every 4 years.",
    "Security": "Use a password manager and turn on two-factor login (2FA) for every work account. Never share your password. Report phishing emails with the Report button in your mail app.",
    "Parental leave": "Birth parents get 26 weeks of paid parental leave and partners get 4 weeks. Adoptive parents get the same leave as birth parents.",
    "Training": "Every employee has a learning budget of 1,000 euros per year for courses, books and conferences. Courses over 300 euros need your manager's approval.",
    "Business travel": "Book work trips in the travel portal. Fly economy for flights under 6 hours and premium economy for longer flights. Take the train for journeys under 4 hours.",
}

# ---- 1. Retrieve: find the sections most similar to the question ----
question = "How many vacation days do I get, and can I keep unused ones?"
q = embed(question)
ranked = sorted(HANDBOOK, key=lambda title: cosine(q, embed(title + ". " + HANDBOOK[title])), reverse=True)
top = ranked[:2]

# ---- 2. Augment: put the retrieved text into the prompt ----
context = "\n\n".join(f"[{title}]\n{HANDBOOK[title]}" for title in top)
prompt = f"""Answer the question using only the handbook sections below.
If they don't contain the answer, say you don't know.

{context}

Question: {question}"""

# ---- 3. Generate: in a real app, this prompt is sent to an LLM ----
print(prompt)

The question says “vacation” and “keep unused ones”; the handbook says “annual leave” and “carried over”. Retrieval found the right section anyway, by meaning. Sent to an LLM, this prompt produces an answer like:

Output
You get 25 days of paid annual leave per year, plus public holidays. You can carry up to 5 unused days over to next year. (Source: Annual leave)

Notice that the second retrieved section (parental leave) wasn't needed. The model is expected to ignore passages that don't help, which is why the instruction says to use only the sections, not all of them.

What RAG gives you

  • Private knowledge: the model can answer from documents it was never trained on.
  • Fresh facts: update a document and the next answer uses it. No retraining.
  • Sources: the app knows which passages were used, so it can show them and people can check.
  • Fewer made-up answers: with good passages and clear instructions, the model has less reason to guess, and can say “I don't know” when nothing relevant was found.

What RAG does not fix

RAG is only as good as its weakest step:

  • If the answer is not in your documents, retrieval can't find it.
  • If retrieval brings back the wrong passages, the model answers from the wrong facts.
  • If the documents are out of date or contradict each other, so will the answers.
  • The model can still misread a passage or add details from its general knowledge.

Most of this course is about making each step reliable, and measuring whether it is.

Common mistakes

Practice exercise

Augment a question with retrieved context: build the prompt that would be sent to the LLM.

Your solutionPython
question = "When are core hours?"
context = "Core hours are 10am to 4pm. The office is open from 7am to 8pm."

# Build the prompt in exactly this shape (three lines):
# Context: <context>
# Question: <question>
# Answer using only the context.
Knowledge check

In RAG, what happens in the “augment” step?

Summary

  • RAG answers questions by retrieving passages from your documents and giving them to an LLM with the question.
  • The steps are retrieve, augment and generate.
  • It brings private and fresh knowledge, sources, and fewer made-up answers.
  • It can't find what isn't in your documents, and each step needs to work well.

Next: when to use RAG and when to fine-tune a model instead.

Finished reading? Tick it off to track your progress.