Velamuvi AIAcademy

Lesson 13 of 16 · Generation and Quality

Evaluating RAG

Measure a RAG system: build a test set, score retrieval with hit rate and MRR, judge answer faithfulness and correctness, and use LLM-as-judge carefully.

  • 6 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Build a test set of questions with known answers and sources
  • Measure retrieval with hit rate and Mean Reciprocal Rank (MRR)
  • Judge answers for faithfulness, relevance and correctness
  • Use LLM-as-judge and automatic checks, and know their limits

Why measure?

Without measurements, every change is a guess: a new chunk size “feels better”, a new model “seems smarter”. A RAG system has many settings, and a change that fixes one question often breaks two others. Evaluation tells you which.

Evaluate the two halves separately, because they fail for different reasons:

  • Retrieval: did the right passages reach the prompt?
  • Generation: given those passages, was the answer faithful, relevant and correct?

Step 1: a test set

Good sources of test questions:

  • Real questions from users, support tickets or search logs (the best source).
  • Experts writing questions they would expect to be asked.
  • An LLM generating questions from your chunks, then a person checking them.

Include questions the documents can't answer, to check that the system says so. Start with 30 to 50 questions; grow towards a few hundred.

Step 2: retrieval metrics

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.",
}

VECS = {t: embed(t + ". " + text) for t, text in HANDBOOK.items()}

def retrieve(question, k=3):
    q = embed(question)
    return sorted(VECS, key=lambda t: cosine(q, VECS[t]), reverse=True)[:k]

# ---- Part 1: retrieval metrics on a test set ----
tests = [
    ("How many vacation days do I get?", "Annual leave"),
    ("Can partners take leave when a baby is born?", "Parental leave"),
    ("Who pays for my dinner on a work trip?", "Expenses"),
    ("What should I do if I get a phishing email?", "Security"),
    ("How long do I have to submit a receipt?", "Expenses"),
]
hits, reciprocal_ranks = 0, []
for question, right in tests:
    ranked = retrieve(question)
    rank = ranked.index(right) + 1 if right in ranked else None
    hits += rank is not None
    reciprocal_ranks.append(1 / rank if rank else 0)
    print(f"rank {rank or '-'}  {question}")
print(f"Hit rate@3: {hits}/{len(tests)}")
print(f"MRR: {sum(reciprocal_ranks) / len(tests):.2f}")

# ---- Part 2: a cheap grounding check on an answer ----
context = HANDBOOK["Expenses"]
answer = "Claim within 30 days. Meals are covered up to 50 euros per day."
unsupported = [n for n in re.findall(r"\d+", answer) if n not in re.findall(r"\d+", context)]
print("Numbers in the answer that aren't in the sources:", unsupported)

All five questions found the right section in the top 3 (hit rate 5/5), but the dinner question had it in second place, so MRR is 0.90 rather than 1. Retrieval metrics are cheap to compute (no LLM needed), so run them on every change.

The second part is a cheap automatic check on an answer: every number in the answer should appear in the sources. “50 euros” doesn't (the handbook says 40), so the answer is flagged. Checks like this catch a surprising share of errors at almost no cost.

Step 3: answer quality

QualityQuestion it asksTypical check
Faithfulness (groundedness)Is every claim supported by the retrieved sources?LLM-as-judge comparing answer and sources
Answer relevanceDoes it actually answer the question asked?LLM-as-judge, or user feedback
CorrectnessDoes it match the known right answer?Compare with the test set's answer
RefusalDoes it say “I don't know” when it should?Unanswerable questions in the test set

LLM judges are fast and scale to thousands of answers, but they make mistakes and can favour long or confident answers. Check a sample of their verdicts by hand, use clear yes/no criteria rather than 1–10 scores, and use a strong model as the judge. Open-source tools such as Ragas, DeepEval and TruLens package common RAG metrics if you'd rather not write your own.

Common mistakes

Practice exercise

Compute Mean Reciprocal Rank, a retrieval metric that rewards putting the right chunk near the top.

Your solutionPython
# Position of the right chunk for each test question (None = not retrieved at all)
ranks = [1, 3, None, 2]

# Mean Reciprocal Rank: average of 1/rank, counting None as 0.
# Print it with 2 decimal places, like: MRR: 0.46
Knowledge check

Hit rate@5 is 70%, but when the right chunk is retrieved, answers are almost always correct. Where should you focus first?

Summary

  • Evaluate retrieval and generation separately, using a test set of real questions with known answers and sources.
  • Retrieval metrics: hit rate@k and MRR, cheap enough to run on every change.
  • Answer quality: faithfulness, relevance, correctness and correct refusals, checked with LLM-as-judge, simple automatic checks and human review.
  • Keep evaluating after launch with logs and user feedback.

Next: the most common ways RAG systems fail, and how to fix each one.

Finished reading? Tick it off to track your progress.