Evaluating RAG
Every other doc in this track ends with "measure it on your eval set". This is where that set comes from and what you measure with it. RAG has two halves that fail differently, retrieval and generation, so you evaluate them separately and then together. The goal is not a single leaderboard number; it is a repeatable test you run on every change to chunking, embeddings, prompts or models, so you know whether you made things better.
Why it matters
Without evaluation, RAG tuning is vibes. Someone changes the chunk size, tries three questions, and ships. Two weeks later a different set of questions regresses and nobody knows why. RAG systems also fail quietly: an answer that cites the wrong policy reads just as confidently as one that cites the right one. You need numbers that separate "the right chunk was never retrieved" from "the right chunk was retrieved but the model ignored it" from "the model made something up", because each has a different fix.
How it works
Build the dataset
An evaluation set is a list of questions with, ideally, the ids of the chunks (or documents) that contain the answer and a reference answer. Sources, best first:
- Real user queries from logs, labeled by people who know the domain.
- Expert-written questions for areas with no traffic yet.
- Synthetic questions generated by an LLM from sampled chunks (the chunk becomes the gold label). Cheap and useful for retrieval tests, but biased toward questions that resemble the text. Filter and review a sample.
A few hundred well-labeled questions beats thousands of noisy ones. Include hard cases on purpose: exact identifiers, multi-hop, questions with no answer in the corpus, and questions that need the newest version of a document.
Retrieval metrics
Computed from ranked chunk ids against gold ids, with no LLM required:
- Recall@k: fraction of relevant chunks that appear in the top k. The most important retrieval metric for RAG, because a chunk that is not retrieved cannot be used.
- Precision@k: fraction of the top k that are relevant. Matters for token cost and noise.
- MRR (mean reciprocal rank): average of 1 / rank of the first relevant chunk. Rewards putting the right chunk near the top.
- nDCG@k: rank-aware and supports graded relevance.
Measure them at the stage boundaries: after first-stage retrieval (k = 50), after fusion, and after reranking (k = 5). That tells you which stage is losing the gold chunk.
Generation metrics
These need judgment, usually from an LLM judge with a careful rubric:
- Faithfulness (groundedness): are the answer's claims supported by the retrieved context? RAGAS computes it by extracting claims from the answer and checking each against the context (supported claims divided by total claims). Note it measures consistency with the context, not truth.
- Answer relevance: does the answer address the question?
- Context precision and context recall (RAGAS terms): whether the retrieved contexts are relevant, and whether they cover what the reference answer needs. Context recall needs a reference answer or gold contexts.
- Correctness: agreement with a reference answer, when you have one.
- Refusal behaviour: for unanswerable questions, did the system say it does not know?
Rendering diagram…
Reference architecture
Evaluation should run in three places: offline in CI on every change, as shadow runs before a model or index swap, and online on sampled production traffic.
Rendering diagram…
The arrow from human review back into the golden set is what keeps the eval honest. Failures you find in production become test cases.
Code
Retrieval metrics in plain Python, plus a minimal faithfulness judge. Libraries like RAGAS package these (and more), but writing the core once makes it clear what the numbers mean.
import json
import os
from statistics import mean
from openai import OpenAI
def recall_at_k(retrieved: list[str], gold: set[str], k: int) -> float:
return len(set(retrieved[:k]) & gold) / len(gold) if gold else 0.0
def reciprocal_rank(retrieved: list[str], gold: set[str]) -> float:
for rank, cid in enumerate(retrieved, start=1):
if cid in gold:
return 1.0 / rank
return 0.0
def retrieval_report(runs: list[dict], k: int = 5) -> dict:
return {
f"recall@{k}": mean(recall_at_k(r["retrieved"], set(r["gold"]), k) for r in runs),
"mrr": mean(reciprocal_rank(r["retrieved"], set(r["gold"])) for r in runs),
}
client = OpenAI()
JUDGE = os.environ.get("JUDGE_MODEL", "gpt-4.1")
def faithfulness(answer: str, contexts: list[str]) -> float:
prompt = (
"Split the ANSWER into atomic factual claims. For each claim, decide if it is "
"fully supported by the CONTEXT. Return JSON: "
'{"claims": [{"claim": str, "supported": bool}]}\n\n'
f"CONTEXT:\n{chr(10).join(contexts)}\n\nANSWER:\n{answer}"
)
resp = client.responses.create(
model=JUDGE, input=prompt, text={"format": {"type": "json_object"}}
)
claims = json.loads(resp.output_text)["claims"]
return sum(c["supported"] for c in claims) / len(claims) if claims else 1.0
runs = [
{"retrieved": ["hr-13", "hr-12", "it-04"], "gold": ["hr-13"]},
{"retrieved": ["it-04", "hr-12", "hr-13"], "gold": ["hr-12"]},
]
print(retrieval_report(runs, k=2)) # {'recall@2': 1.0, 'mrr': 0.75}
Trade-offs and pitfalls
- LLM judges are noisy and biased. Pin the judge model and prompt, calibrate against a human-labeled subset, and track trends rather than trusting absolute values. Judges can prefer longer answers or answers in their own style.
- Synthetic questions flatter retrieval. Questions generated from a chunk share its vocabulary, so recall looks better than on real traffic. Keep a real-query slice and report it separately.
- Gold labels go stale. Re-chunking changes chunk ids. Label at the document or span level, or map labels forward when you re-index.
- One average hides regressions. Report by slice: identifier lookups, multi-hop, unanswerable, per collection, per language.
- Faithful is not correct. A perfectly faithful answer built on an outdated policy is still wrong. Pair faithfulness with correctness checks and freshness tests.
- Cost of evaluation. Judging every production request is expensive. Sample, and run the full golden set offline.
- Metric names vary by library version. If you adopt RAGAS or a similar framework, pin its version, since metric definitions and required fields have changed across releases.
Checklist
- Build a golden set of a few hundred questions from real queries, with gold chunk or document ids.
- Include identifier lookups, multi-hop, unanswerable and freshness cases.
- Measure recall@k and MRR after each retrieval stage, not only at the end.
- Measure faithfulness, answer relevance and refusal behaviour with a calibrated LLM judge.
- Run the eval in CI and block changes that regress beyond tolerance.
- Sample production traces for async judging and human review, and feed failures back into the set.
- Report metrics by query slice, not just as one average.
Further reading
- RAGAS: Automated Evaluation of Retrieval Augmented Generation (arXiv 2309.15217)
- Ragas documentation: metrics
- BEIR: A Heterogeneous Benchmark for Zero-shot Evaluation of Information Retrieval Models (arXiv 2104.08663)
- Evaluating Chunking Strategies for Retrieval (Chroma Research)
- NVIDIA NeMo Evaluator: RAG evaluation metrics