Education › Evals & Harness › Stage 2: Evals in practice

Evaluating RAG systems

Retrieval recall and precision, groundedness, citation accuracy and answer quality, separately.

Intermediate ~40 min read Module 6 of 20

A retrieval-augmented generation (RAG) system can fail in two very different places: retrieval can miss the right passages, or generation can ignore, misread or embellish them. A single end-to-end score mixes those failures together and tells you nothing about which half to fix. This lesson splits RAG evaluation into retrieval metrics, generation metrics and end-to-end checks, shows how to build the labelled data each needs, and covers the RAG-specific traps: unanswerable questions, stale documents, and permissions.

After this module you can
  • Evaluate retrieval separately with recall@k, precision@k and MRR
  • Evaluate generation for faithfulness, relevance and citation correctness
  • Build a labelled RAG dataset with relevant document IDs
  • Test unanswerable questions and permission boundaries
  • Diagnose whether a failure is a retrieval or a generation problem

Split the pipeline

Think of RAG as two systems in series. The retriever takes a question and returns the top-k chunks. The generator takes the question plus those chunks and writes an answer. Evaluate them separately, then together. If retrieval recall is low, no prompt will rescue the answer; if recall is high but answers are wrong, the problem is in generation or chunk quality.

querytop-k chunksranked IDsanswer + contextQuestionRetrieversearch, rerankGeneratorquestion + chunksAnswerwith citationsLabelsrelevant IDsRetrieval evalrecall@k, MRRGeneration evalfaithfulnessEnd-to-end evalvs reference
Evaluate RAG in layers: retrieval against labelled relevant IDs, generation against the retrieved context, and the final answer against a reference.
LayerQuestionTypical metrics
RetrievalDid we fetch the passages that contain the answer?recall@k, precision@k, MRR
GenerationDid the answer use those passages correctly?faithfulness, answer relevance
CitationsDo cited sources actually support each claim?citation precision
End to endWould a user be satisfied and correct?correctness vs reference, task success

Retrieval metrics

For each question, label the document or chunk IDs that contain the answer. Then recall@k is the share of relevant chunks found in the top k, precision@k is the share of the top k that are relevant, and MRR (mean reciprocal rank) rewards putting the first relevant chunk near the top. Recall matters most for RAG, because the generator can ignore irrelevant chunks but cannot invent a missing one.

Retrieval metrics from labelled relevant IDs
python
def recall_at_k(retrieved: list[str], relevant: set[str], k: int) -> float:
    return len(set(retrieved[:k]) & relevant) / len(relevant)


def reciprocal_rank(retrieved: list[str], relevant: set[str]) -> float:
    for rank, doc_id in enumerate(retrieved, start=1):
        if doc_id in relevant:
            return 1 / rank
    return 0.0


def retrieval_report(cases, search, k=5):
    rec = [recall_at_k(search(c["q"]), set(c["relevant"]), k) for c in cases]
    mrr = [reciprocal_rank(search(c["q"]), set(c["relevant"])) for c in cases]
    return {f"recall@{k}": sum(rec) / len(rec), "mrr": sum(mrr) / len(mrr)}

Because retrieval metrics need no model calls, they are fast and cheap: run them on every change to chunking, embeddings, hybrid weights or reranking, and sweep k to see where recall plateaus.

Generation metrics

  • Faithfulness (groundedness): every claim in the answer is supported by the retrieved context. Usually judged by a calibrated LLM judge that lists claims and checks each against the context.
  • Answer relevance: the answer addresses the question that was asked, not a nearby one.
  • Correctness: the answer matches a reference answer or required facts (code checks where possible).
  • Citation precision: each citation points at a chunk that supports the sentence it is attached to; check by matching citation IDs to retrieved IDs and judging support.
  • Abstention: when the context does not contain the answer, the system says so instead of guessing.
Cheap code checks before any judge
python
import re


def citation_checks(answer: str, retrieved_ids: list[str]) -> dict:
    cited = set(re.findall(r"\[(doc-\d+)\]", answer))
    return {
        "has_citation": bool(cited),
        "cites_only_retrieved": cited <= set(retrieved_ids),   # no invented sources
        "n_citations": len(cited),
    }

Building the dataset

A RAG eval case needs the question, the IDs of the chunks that answer it, a reference answer or required facts, and slice metadata such as document type and question type. Good sources are real user questions matched to documents by subject experts. You can also generate questions from chunks (the chunk becomes the relevant ID), but generated questions tend to copy the chunk's wording, which makes retrieval look better than it is; paraphrase them or prefer real questions.

  • Unanswerable questions: include 10-20% whose answer is not in the corpus; the expected behaviour is a clear "I don't know".
  • Multi-hop questions: need two or more chunks combined; they expose chunking and k problems.
  • Stale or conflicting documents: two versions of a policy; the expected answer uses the current one.
  • Permissions: questions asked by a user who must not see the answering document; the expected behaviour is not to reveal it.

Diagnosing failures

For every failed end-to-end case, check retrieval first. If the relevant chunk was not retrieved, it is a retrieval failure: look at chunk boundaries, query wording versus document wording (consider hybrid keyword plus vector search), metadata filters and k. If it was retrieved but the answer is wrong, it is a generation failure: the chunk may be buried among irrelevant ones (try reranking or fewer chunks), the prompt may not insist on using the context, or the answer may require reasoning the model did poorly. Tag each failure with its layer and fix the biggest bucket first.

Watch out

Frameworks offer ready-made RAG metrics computed by an LLM. They are useful, but they are judges: calibrate them on a labelled sample from your own documents before trusting their numbers.

Hands-on practice

Evaluate a small RAG system layer by layer

  1. Index 30-50 documents you know well (product docs, policies) with any vector or keyword search.
  2. Write 40 questions with relevant chunk IDs and reference facts; include 6 unanswerable and 4 multi-hop questions.
  3. Compute recall@k and MRR for k in 1, 3, 5, 10 and plot where recall levels off.
  4. Generate answers and run the citation code checks.
  5. Judge faithfulness with a calibrated judge on all answers, and abstention on the unanswerable set.
  6. Tag every failure as retrieval or generation and fix the bigger bucket; re-run and compare.
Cheat sheet

Evaluating RAG systems — at a glance

Main things to focus on

  • Evaluate retrieval and generation separately, then end to end.
  • Recall@k first: generation cannot use a chunk it never saw.
  • Faithfulness: every claim supported by retrieved context.
  • Include unanswerable, multi-hop, stale and permission cases.
  • Diagnose failures by layer before changing anything.
  • Calibrate ready-made RAG judge metrics on your own data.

Retrieval

recall@k = found relevant / all relevantMost important for RAG
precision@k = relevant in top k / kNoise in context
MRR = mean(1 / rank of first hit)Ranking quality
sweep k: 1, 3, 5, 10Find the plateau

Generation

faithfulnessClaims supported by context
answer relevanceAnswers the actual question
correctness vs referenceRight facts
citation precisionCitations support claims
abstentionSays so when unanswerable

Dataset

q, relevant_ids, facts, sliceCase fields
10-20% unanswerableTests guessing
multi-hop questionsTests chunking and k
user without accessTests permissions

Fixes by layer

retrieval missChunking, hybrid search, filters, k
buried chunkReranking, fewer chunks
ignored contextPrompt: answer only from sources

Common pitfalls

  • One end-to-end score with no retrieval metrics.
  • Questions generated from chunks that copy their wording.
  • No unanswerable questions, so guessing is never punished.
  • Trusting framework RAG metrics without calibration.
  • Ignoring permission leaks in the eval.
Quiz

Check your understanding

5 questions · 4 to pass · answers are explained as you go. Your best score is saved on this device only.

Progress and quiz scores are saved in this browser only. Back up or restore on the hub.

Was this lesson useful? Tell me what to improve →