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.β
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.
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.
The Two Main Evaluation Layers
Did we find the right evidence?
Measure whether relevant documents or chunks appear near the top of the candidate list.
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.
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.
Recall@K
Recall@K asks whether the relevant evidence appears anywhere in the top K retrieved results.
If K = 5, the query counts as a retrieval success.
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.
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.
Precision@5 = 0.80.
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?β
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.
Reciprocal rank = 1.00.
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.
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.
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.
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))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.
- Many unrelated chunks
- Duplicate passages
- Old versions
- Large unnecessary context
- Relevant evidence
- Useful source diversity
- Current versions
- Clear source labels
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.
Answer: βThe refund window is 30 days.β
Answer: βThe refund window is 30 days, with free return shipping.β If shipping is not in context, that extra claim is unsupported.
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.
Check whether the answer states the correct value.
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.
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.
Separate Retrieval and Generation Failures
The correct chunk is absent from the top-K results.
The correct chunk was retrieved but discarded or drowned in noise.
The model had good evidence but produced an incorrect answer.
Evaluate Different K Values
Do not assume one Top-K value is optimal. Compare retrieval quality and downstream answer quality at several K values.
Compare Retrieval Strategies
Evaluation should compare system changes using the same test set. This makes improvements measurable instead of anecdotal.
Vector search
Measure current retrieval quality.
Metadata filtering
Check whether constraints reduce noise.
Keyword + vector
Test exact terms and semantic meaning together.
Second-stage ranking
Measure whether candidate ordering improves.
Human Evaluation
Automated metrics are valuable, but humans are still useful for ambiguous questions, nuanced answers, and failure analysis.
For example: correctness, relevance, faithfulness, completeness, and citation quality.
Group failures by retrieval, chunking, metadata, ranking, prompting, or generation.
Keep the rubric stable when comparing two versions of the system.
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.
Track Cost and Latency Too
A RAG change is not automatically an improvement if quality increases slightly while latency and cost increase dramatically.
- Recall@K
- Precision@K
- MRR / NDCG
- Faithfulness
- Answer correctness
- Retrieval latency
- Reranking latency
- LLM latency
- Tokens per request
- Cost per answer
Build a Repeatable Evaluation Loop
Keep evaluation data versioned. When chunking, embeddings, retrieval, reranking, prompts, or models change, rerun the same benchmark so you can compare the effect.
A Simple Python Evaluation Harness
Here is a small pattern for running the same retrieval test across multiple questions.
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))What Good RAG Evaluation Looks Like
Find the evidence
Relevant evidence appears reliably in the candidate set.
Keep it focused
Useful evidence reaches the prompt without unnecessary noise.
Answer accurately
The response addresses the question and stays grounded.
Show sources
Claims can be traced back to supporting evidence.
Common Evaluation Mistakes
You cannot tell whether the problem is retrieval or generation.
Results may not represent real user behavior.
It becomes difficult to compare system versions fairly.
Higher recall can come with much more noise.
Automated evaluators can make systematic mistakes.
A quality gain may not justify the operational cost.
Evaluation Checklist
Representative questions
Include different difficulty levels and query types.
Measure ranking
Track Recall@K, Precision@K, MRR, and NDCG.
Measure answer quality
Check correctness, relevance, and faithfulness.
Verify citations
Confirm that sources actually support claims.
Track performance
Record latency, tokens, and cost.
Compare versions
Run the same benchmark after every important change.
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.
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
Create a representative test set.
Measure Recall@K and Precision@K.
Use MRR and NDCG when ordering matters.
Check relevance and noise.
Measure correctness and relevance.
Check faithfulness to evidence.
Verify source attribution.
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.