RAG evaluation metrics
A retrieval-augmented generation system has two places to fail: the retriever can fetch the wrong chunks, and the generator can misuse the right ones. If you only grade the final answer, you know something is broken but not where. The core habit of RAG evaluation is to score the two stages separately, with metrics designed for each, so a low number points you at the component to fix.
Why it matters
Imagine your answer accuracy drops after a change. Was it the new chunking strategy, the new embedding model, the reranker, or the prompt? Without stage-level metrics you are guessing. With them, a pattern like "context recall stayed flat, faithfulness dropped" tells you the retriever is fine and the generator started ignoring or embellishing the context.
The Ragas paper and library popularised a set of reference-free and reference-based metrics for exactly this split, and most observability tools (Langfuse, Phoenix, Databricks MLflow and others) either ship similar metrics or integrate Ragas directly.
How it works
Rendering diagram…
Retrieval metrics (did we fetch the right stuff?)
- Recall@k: of the chunks that should have been retrieved, what fraction appear in the top k? This needs labelled relevant chunk IDs per question. It is the single most useful retrieval number, because the generator cannot use what it never sees.
- MRR (mean reciprocal rank): how high does the first relevant chunk appear? Useful when the generator weights early context more, or you only pass a few chunks.
- Context precision: are relevant chunks ranked above irrelevant ones? In Ragas this is computed with an LLM deciding relevance of each chunk; low values often point at ranking or reranking problems.
- Context recall: does the retrieved context contain all the information needed to produce the reference answer? Ragas computes it by checking whether claims in the reference are attributable to the context, so it needs a reference answer.
Generation metrics (did we use it well?)
- Faithfulness (groundedness): what fraction of claims in the answer are supported by the retrieved context? Ragas breaks the answer into claims and asks a judge to verify each one, then reports supported claims over total claims. This is your hallucination metric.
- Answer relevance: does the answer actually address the question? A faithful answer can still dodge the question.
- Answer correctness: compared to a reference answer, is it right? This needs labels but is the closest thing to an end-to-end score.
These metrics are orthogonal on purpose. High faithfulness with low relevance means the model stuck to the context but did not answer the question. High recall with low precision means you retrieved the right information plus a lot of noise.
Reference architecture
Rendering diagram…
Labelling relevant chunk IDs is the expensive part. A practical shortcut: have a model propose candidate relevant chunks for each question, then have a human confirm or reject them. Keep chunk IDs stable across re-indexing (for example, derive them from document ID plus a content hash) or your labels break every time you re-chunk.
Code
Pure-Python retrieval metrics plus a claim-level faithfulness check with a judge. I am writing faithfulness by hand here so the mechanics are visible; in practice you might use Ragas, which implements the same idea.
import json
def recall_at_k(retrieved: list[str], relevant: set[str], k: int) -> float:
if not relevant:
return 1.0
hits = len(set(retrieved[:k]) & relevant)
return hits / len(relevant)
def reciprocal_rank(retrieved: list[str], relevant: set[str]) -> float:
for i, doc_id in enumerate(retrieved, start=1):
if doc_id in relevant:
return 1.0 / i
return 0.0
def call_judge(prompt: str) -> str:
raise NotImplementedError # your LLM client, temperature 0
def faithfulness(answer: str, contexts: list[str]) -> float:
claims = json.loads(call_judge(
"Split this answer into short standalone factual claims. "
f"Return a JSON list of strings.\n\nANSWER:\n{answer}"
))
if not claims:
return 1.0
ctx = "\n---\n".join(contexts)
supported = 0
for claim in claims:
verdict = json.loads(call_judge(
f"CONTEXT:\n{ctx}\n\nCLAIM: {claim}\n\n"
'Is the claim fully supported by the context? Reply JSON {"supported": true|false}'
))
supported += bool(verdict["supported"])
return supported / len(claims)
def evaluate(rows: list[dict], k: int = 5) -> dict[str, float]:
r, mrr, faith = [], [], []
for row in rows:
rel = set(row["relevant_ids"])
r.append(recall_at_k(row["retrieved_ids"], rel, k))
mrr.append(reciprocal_rank(row["retrieved_ids"], rel))
faith.append(faithfulness(row["answer"], row["retrieved_texts"]))
n = len(rows)
return {f"recall@{k}": sum(r) / n, "mrr": sum(mrr) / n, "faithfulness": sum(faith) / n}
Retrieval metrics are code, so they are cheap enough to run on every commit. Faithfulness costs one call per claim plus one, so sample it on large sets.
Trade-offs and pitfalls
- Judge-based metrics are judges. Ragas-style faithfulness and context precision use an LLM under the hood. Calibrate them against human labels on your domain before treating thresholds as meaningful.
- Borrowed thresholds. You will see blog posts suggest targets like 0.8 or 0.9 for various metrics. Those are community rules of thumb, not standards. Set your own from labelled data and user outcomes.
- Library API churn. Ragas has changed its dataset column names and metric classes across versions. Pin the version and read the docs for the one you install.
- Chunk ID instability. Re-chunking invalidates relevance labels unless IDs are stable. Plan for this before you label thousands of questions.
- Unanswerable questions. Include questions whose answer is not in the corpus, and grade whether the system declines. Otherwise you reward confident hallucination.
- Faithful but wrong sources. Faithfulness only checks the answer against retrieved text. If the corpus is outdated, a perfectly faithful answer can still be wrong. Track correctness too.
Checklist
- Golden set has relevant chunk IDs and a reference answer for each question.
- Recall@k and MRR run in code on every change to retrieval.
- Faithfulness and answer relevance run on a sample with a calibrated judge.
- Results are reported per stage, not just as one end-to-end score.
- The set includes unanswerable questions with an expected refusal.
- Chunk IDs are stable across re-indexing.
- Library versions (Ragas or similar) are pinned.