LESSON 56 Β· RAG

RAG Evaluation

Learn how to measure whether a RAG system retrieves the right evidence, uses it faithfully, and produces useful answers instead of relying on β€œthe answer looks good.”

45 min readβ€’Intermediateβ€’Generative AI

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

  • Explain why RAG needs both retrieval and generation evaluation.
  • Build a small evaluation dataset with questions, expected evidence, and reference answers.
  • Measure Recall@K, Precision@K, MRR, and NDCG.
  • Evaluate context relevance, faithfulness, and answer correctness.
  • Separate retrieval failures from generation failures.
  • Use Python to calculate simple retrieval metrics.
  • Design repeatable offline and production evaluation workflows.
1

Why Evaluate RAG?

A RAG system can produce a fluent answer and still be wrong. The failure may happen because the right chunk was never retrieved, the retrieved context was noisy, or the model used the evidence incorrectly.

QuestionUser intent
β†’
RetrievalFind evidence
β†’
ContextSelect evidence
β†’
GenerationWrite answer
β†’
EvaluationMeasure quality
Key idea:Do not evaluate only the final answer. A useful RAG evaluation traces quality through retrieval, context, generation, and source attribution.
2

The Two Main Evaluation Layers

RETRIEVAL

Did we find the right evidence?

Measure whether relevant documents or chunks appear near the top of the candidate list.

+
GENERATION

Did we use the evidence correctly?

Measure answer correctness, relevance, faithfulness, and source attribution.

A strong generator cannot reliably fix missing evidence. If the retriever misses the required policy clause, the model may have nothing trustworthy to use.

3

Build an Evaluation Dataset

Start with a representative set of questions. Each test case should describe what evidence is expected and, when practical, what a correct answer should contain.

QUESTIONWhat is the refund window?The exact user query.
RELEVANT EVIDENCEpolicy-17, chunk-4Known-good document/chunk IDs.
REFERENCE ANSWER30 daysExpected factual answer.
METADATAregion=USUseful retrieval constraints.
Tip:Include easy, ambiguous, multi-document, long-tail, and adversarial questions. A tiny set of obvious questions can make a weak system look strong.
4

Recall@K

Recall@K asks whether the relevant evidence appears anywhere in the top K retrieved results.

EXAMPLE 1Relevant chunk is rank 3

If K = 5, the query counts as a retrieval success.

EXAMPLE 2Relevant chunk is rank 8

If K = 5, it is a retrieval failure for Recall@5.

For a binary relevance test, a simple form is: Recall@K = successful queries with relevant evidence in top K Γ· total queries.

5

Precision@K

Precision@K measures how much of the top-K result set is relevant. It is useful when irrelevant chunks create noise or consume context.

HIGH PRECISION4 relevant out of 5

Precision@5 = 0.80.

LOW PRECISION1 relevant out of 5

Precision@5 = 0.20.

Recall and precision answer different questions: recall asks β€œdid we find it?” while precision asks β€œhow much of what we returned is useful?”

6

Mean Reciprocal Rank (MRR)

MRR rewards systems that place the first relevant result near the top. For a query, reciprocal rank is 1 Γ· rank of the first relevant result.

QUERY ARelevant result at rank 1

Reciprocal rank = 1.00.

QUERY BRelevant result at rank 4

Reciprocal rank = 0.25.

MRR is especially useful when the user needs one strong piece of evidence and the ordering of the first relevant result matters.

7

NDCG: Ranking Quality

Normalized Discounted Cumulative Gain (NDCG) is useful when several retrieved results have different degrees of relevance. Highly relevant results should appear earlier than marginally useful results.

Think of it this way:Recall tells you whether useful evidence appeared. MRR focuses on the first useful result. NDCG evaluates the quality of the whole ranking when relevance has multiple levels.
8

Calculate Retrieval Metrics in Python

You can begin evaluation without a vector database. Represent your retrieved chunk IDs and the known relevant IDs, then calculate metrics over your test set.

</> Python
def recall_at_k(retrieved, relevant, k):
    top_k = retrieved[:k]
    return int(any(item in relevant for item in top_k))


def precision_at_k(retrieved, relevant, k):
    top_k = retrieved[:k]
    if not top_k:
        return 0.0
    return sum(item in relevant for item in top_k) / len(top_k)


retrieved = ["chunk-8", "chunk-3", "chunk-4", "chunk-12", "chunk-9"]
relevant = {"chunk-4"}

print("Recall@5:", recall_at_k(retrieved, relevant, 5))
print("Precision@5:", precision_at_k(retrieved, relevant, 5))
9

Evaluate Context Relevance

Even when retrieval technically succeeds, the final context may contain too much irrelevant or repetitive information. Context relevance asks whether the evidence supplied to the model actually helps answer the question.

Noisy context
  • Many unrelated chunks
  • Duplicate passages
  • Old versions
  • Large unnecessary context
Focused context
  • Relevant evidence
  • Useful source diversity
  • Current versions
  • Clear source labels
10

Faithfulness: Is the Answer Supported?

Faithfulness asks whether the claims in the generated answer are supported by the retrieved context. A fluent answer can still contain unsupported claims.

SUPPORTEDContext says β€œ30 days”

Answer: β€œThe refund window is 30 days.”

UNSUPPORTEDContext says β€œ30 days”

Answer: β€œThe refund window is 30 days, with free return shipping.” If shipping is not in context, that extra claim is unsupported.

11

Answer Correctness

Answer correctness asks whether the final response actually answers the user's question accurately. Depending on the task, you can compare against a reference answer, structured facts, or human judgment.

FACTUALExpected: 30 days

Check whether the answer states the correct value.

EXPLANATORYExpected: policy + eligibility

Check whether all required parts are addressed.

Correctness and faithfulness are related but not identical. An answer can be plausible and correct by coincidence, or contain the right conclusion plus unsupported details.

12

Source Attribution

For many RAG applications, users need to know where an answer came from. Evaluate whether citations point to the correct document, page, section, or URL.

Answer claimWhat was stated?
β†’
SourceWhich document?
β†’
LocationWhich page/section?
β†’
VerificationCan the user check it?
13

Separate Retrieval and Generation Failures

01Retrieval failure

The correct chunk is absent from the top-K results.

02Context failure

The correct chunk was retrieved but discarded or drowned in noise.

03Generation failure

The model had good evidence but produced an incorrect answer.

Debugging rule:Inspect the retrieved chunks before changing the prompt. If the evidence is missing, prompt engineering alone is unlikely to solve the problem.
14

Evaluate Different K Values

Do not assume one Top-K value is optimal. Compare retrieval quality and downstream answer quality at several K values.

K = 3Low noiseMay miss supporting evidence.
K = 5BalancedOften a useful starting point.
K = 10More recallMay increase context noise.
K = 20Broad candidatesUsually better for a reranking stage than direct generation.
15

Compare Retrieval Strategies

Evaluation should compare system changes using the same test set. This makes improvements measurable instead of anecdotal.

BASELINE

Vector search

Measure current retrieval quality.

FILTERED

Metadata filtering

Check whether constraints reduce noise.

HYBRID

Keyword + vector

Test exact terms and semantic meaning together.

RERANKED

Second-stage ranking

Measure whether candidate ordering improves.

16

Human Evaluation

Automated metrics are valuable, but humans are still useful for ambiguous questions, nuanced answers, and failure analysis.

USE A RUBRICScore consistent dimensions

For example: correctness, relevance, faithfulness, completeness, and citation quality.

REVIEW FAILURESLook for patterns

Group failures by retrieval, chunking, metadata, ranking, prompting, or generation.

Keep the rubric stable when comparing two versions of the system.

17

LLM-as-a-Judge

An LLM can help score large evaluation sets against a rubric, but its scores should be treated as evaluation signals rather than unquestionable truth.

Best practice:Validate the judge against a human-labeled sample, use explicit criteria, and inspect disagreements. Do not let the same model blindly grade every aspect of its own output.
18

Track Cost and Latency Too

A RAG change is not automatically an improvement if quality increases slightly while latency and cost increase dramatically.

Quality metrics
  • Recall@K
  • Precision@K
  • MRR / NDCG
  • Faithfulness
  • Answer correctness
System metrics
  • Retrieval latency
  • Reranking latency
  • LLM latency
  • Tokens per request
  • Cost per answer
19

Build a Repeatable Evaluation Loop

DatasetFixed questions
β†’
RunEvaluate version
β†’
MetricsCalculate scores
β†’
FailuresInspect examples
β†’
ImproveChange one layer

Keep evaluation data versioned. When chunking, embeddings, retrieval, reranking, prompts, or models change, rerun the same benchmark so you can compare the effect.

20

A Simple Python Evaluation Harness

Here is a small pattern for running the same retrieval test across multiple questions.

</> Python
def evaluate_retrieval(cases, k=5):
    recall_scores = []
    precision_scores = []

    for case in cases:
        retrieved = case["retrieved"]
        relevant = set(case["relevant"])
        recall_scores.append(recall_at_k(retrieved, relevant, k))
        precision_scores.append(precision_at_k(retrieved, relevant, k))

    return {
        "recall_at_k": sum(recall_scores) / len(recall_scores),
        "precision_at_k": sum(precision_scores) / len(precision_scores),
    }

cases = [
    {"retrieved": ["a", "b", "c"], "relevant": ["c"]},
    {"retrieved": ["x", "y", "z"], "relevant": ["q"]},
]

print(evaluate_retrieval(cases, k=3))
21

What Good RAG Evaluation Looks Like

RETRIEVAL

Find the evidence

Relevant evidence appears reliably in the candidate set.

CONTEXT

Keep it focused

Useful evidence reaches the prompt without unnecessary noise.

GENERATION

Answer accurately

The response addresses the question and stays grounded.

ATTRIBUTION

Show sources

Claims can be traced back to supporting evidence.

22

Common Evaluation Mistakes

01Only testing final answers

You cannot tell whether the problem is retrieval or generation.

02Using too few questions

Results may not represent real user behavior.

03Changing the benchmark

It becomes difficult to compare system versions fairly.

04Optimizing one metric

Higher recall can come with much more noise.

05Trusting judge scores blindly

Automated evaluators can make systematic mistakes.

06Ignoring cost and latency

A quality gain may not justify the operational cost.

23

Evaluation Checklist

DATASET

Representative questions

Include different difficulty levels and query types.

RETRIEVAL

Measure ranking

Track Recall@K, Precision@K, MRR, and NDCG.

GENERATION

Measure answer quality

Check correctness, relevance, and faithfulness.

SOURCES

Verify citations

Confirm that sources actually support claims.

OPERATIONS

Track performance

Record latency, tokens, and cost.

REGRESSION

Compare versions

Run the same benchmark after every important change.

24

Practice: Diagnose a RAG System

Your RAG system answers a policy question incorrectly. The correct chunk is ranked at position 12, while unrelated chunks occupy the top 5 positions.

TASK

Find the likely bottleneck

Decide whether you would first investigate retrieval, context construction, or generation. Then choose two metrics that would help confirm your diagnosis.

Quick Quiz

1. Why is evaluating only the final answer not enough?

Because a wrong answer can originate from retrieval, context selection, or generation, and final-answer scoring alone does not identify the failure layer.

2. What does Recall@K measure?

Whether relevant evidence appears within the top K retrieved results.

3. What does Precision@K measure?

How much of the top-K result set is relevant.

4. What does MRR reward?

Placing the first relevant result as high in the ranking as possible.

5. What is faithfulness?

Whether claims in the generated answer are supported by the retrieved context.

6. Why track latency and cost?

A quality improvement may not be worthwhile if it creates unacceptable response time or operating cost.

30-Second Recap

1. Build

Create a representative test set.

2. Retrieve

Measure Recall@K and Precision@K.

3. Rank

Use MRR and NDCG when ordering matters.

4. Context

Check relevance and noise.

5. Generate

Measure correctness and relevance.

6. Ground

Check faithfulness to evidence.

7. Cite

Verify source attribution.

8. Compare

Track quality, latency, and cost across versions.

Key Takeaways

  • RAG evaluation should cover retrieval, context, generation, and source attribution.
  • Recall@K asks whether relevant evidence was found; Precision@K asks how much of the result set is relevant.
  • MRR and NDCG help evaluate ranking quality.
  • Faithfulness checks whether generated claims are supported by retrieved evidence.
  • Keep a stable, representative evaluation dataset so system versions can be compared fairly.
  • Use human evaluation and LLM judges as complementary signals, not unquestionable truth.
  • Track latency, token usage, and cost alongside quality metrics.
  • When an answer fails, inspect the retrieved evidence before assuming the prompt or model is the problem.