# RAG evaluation step by step: recall@k, MRR, nDCG, faithfulness and when a gain is real

A RAG system can fail at retrieval or at generation, and one score hides which. This guide computes recall@k, MRR, nDCG and MAP by hand, checks them against pytrec_eval, maps the LLM-judged metrics in Ragas, DeepEval and TruLens, and shows how to tell a real gain from noise.

A retrieval-augmented generation (RAG) system has two jobs: find the right evidence, then write a faithful answer from it. When an answer is wrong, the cause is in one of those two places, and the fix is completely different. Swapping the language model will not help if the right passage was never retrieved, and tuning the retriever will not help if the model ignores a perfect passage.

That is why RAG evaluation splits into two halves. Retrieval is measured with classic information retrieval metrics, recall@k, MRR, nDCG and MAP, computed against labelled relevant passages. Generation is measured with metrics such as faithfulness and answer relevance, usually scored by an LLM acting as a judge. This month two of the main open-source evaluation libraries shipped new versions and the TREC evaluation tool for Python had its first release in a year. This article computes the retrieval metrics by hand and verifies them with that tool, maps the generation metrics across libraries, and shows how many questions you need before a difference between two systems means anything.

An analogy: evaluating RAG is like grading a student's open-book essay. First check whether they opened the right pages. Then check whether what they wrote is actually on those pages. A single grade for the essay tells you neither.

## What happened

### DeepEval 4.3.5 released (24 November 2026)

DeepEval, Confident AI's open-source LLM evaluation framework, released 4.3.5 on PyPI on 24 November 2026, following 4.3.2 (27 October), 4.3.3 and 4.3.4. Its README groups RAG metrics as answer relevancy, faithfulness, contextual recall, contextual precision and contextual relevancy, plus a RAGAS composite described as the "average of answer relevancy, faithfulness, contextual precision, and contextual recall", and a turn faithfulness metric for multi-turn chatbots. The site's article on [DeepEval 4.3 agent metrics](/articles/deepeval-4-3-agent-metrics-offline) covers the agent side of the same release line.

### Ragas 0.4.4 and TruLens 2.16.0 (14 November and 19 October 2026)

Ragas released 0.4.4 on 14 November 2026, its first release since January; the site's [Ragas 0.4.4 article](/articles/ragas-0-4-4-faithfulness-tool-metrics) covers its faithfulness and tool metrics in detail. TruLens released 2.16.0 on 19 October 2026; its description centres on the "RAG triad" of context relevance, groundedness and answer relevance, and reports a groundedness F1 of 0.81 on the LLM-AggreFact benchmark as a project result.

### pytrec_eval 0.5.11 released (16 October 2026)

The `pytrec-eval-terrier` package, the Python binding of the standard `trec_eval` tool used in TREC and most retrieval research, released 0.5.11 on 16 October 2026, a year after 0.5.10. It is the reference implementation this article uses to check hand-computed retrieval metrics.

## Half one: retrieval metrics

You need a set of questions, and for each question the IDs of the passages that answer it (the qrels, short for relevance judgements). Graded relevance helps: 2 for a passage that fully answers, 1 for one that partly helps. Then run your retriever and compare its ranked list with the qrels.

| Metric | Formula in words | What it tells you |
|---|---|---|
| Recall@k | Relevant passages in top k ÷ all relevant passages | Did the evidence reach the prompt? The main RAG retrieval metric |
| Precision@k | Relevant passages in top k ÷ k | How much noise the prompt carries |
| Hit@k | 1 if any relevant passage is in top k | Simple pass or fail per question |
| Reciprocal rank (RR) | 1 ÷ rank of the first relevant passage | How soon the first useful passage appears; averaged over questions it is MRR |
| nDCG@k | Graded gains discounted by log2(rank + 1), divided by the ideal | Order quality with graded relevance; the standard reranking metric |
| Average precision (AP) | Mean of precision at each relevant hit | Order quality across all relevant passages; averaged it is MAP |

### Building the labelled set

The qrels are the expensive part, and a few rules keep them useful. Sample questions from real traffic or from the people who will use the system, not from the documents. Label at the passage level with stable IDs, because a document-level label cannot tell you whether the right paragraph made the top k. Let labellers search freely rather than only judging what your current retriever returns; otherwise the test set inherits that retriever's blind spots and cannot reward a better one. Record questions that have no answer in the corpus too, so you can test refusals. Finally, version the set: when chunking changes, passage IDs change, and the qrels must be mapped to the new chunks before scores are comparable. The site's [evaluation metrics page](/tools/evaluation-metrics) summarises the measures below, and the [RAG evaluation simulation](/ai-simulations/rag-evaluation-ragas) shows retrieval and generation scores side by side.

### A worked example, checked against pytrec_eval

Three questions, five retrieved passages each:

```python
import math, numpy as np

qrels = {"q1": {"d3": 2, "d7": 1}, "q2": {"d1": 2}, "q3": {"d4": 2, "d9": 2}}
run   = {"q1": ["d7", "d2", "d3", "d5", "d8"],
         "q2": ["d6", "d5", "d4", "d2", "d1"],
         "q3": ["d4", "d9", "d1", "d2", "d3"]}

def recall_at(r, rel, k):    return len(set(r[:k]) & set(rel)) / len(rel)
def precision_at(r, rel, k): return len(set(r[:k]) & set(rel)) / k
def rr(r, rel):              return next((1 / (i + 1) for i, d in enumerate(r) if d in rel), 0.0)
def ndcg_at(r, rel, k):
    dcg  = sum(rel.get(d, 0) / math.log2(i + 2) for i, d in enumerate(r[:k]))
    idcg = sum(g / math.log2(i + 2) for i, g in enumerate(sorted(rel.values(), reverse=True)[:k]))
    return dcg / idcg
def ap(r, rel):
    hits, s = 0, 0.0
    for i, d in enumerate(r):
        if d in rel: hits += 1; s += hits / (i + 1)
    return s / len(rel)
```

| Question | Recall@3 | Precision@3 | RR | nDCG@5 | AP |
|---|---|---|---|---|---|
| q1 | 1.00 | 0.67 | 1.00 | 0.760 | 0.833 |
| q2 | 0.00 | 0.00 | 0.20 | 0.387 | 0.200 |
| q3 | 1.00 | 0.67 | 1.00 | 1.000 | 1.000 |
| Mean | 0.67 | 0.44 | MRR 0.733 | 0.716 | MAP 0.678 |

Running the same qrels and run through `pytrec_eval` with the measures `recall.3`, `P.3`, `recip_rank`, `ndcg_cut.5` and `map` gives identical per-question values, so the hand formulas match the reference tool.

Each metric tells a different story about the same lists:

- **q1** ranks a partly relevant passage (d7, grade 1) first and the fully relevant d3 third. Reciprocal rank is a perfect 1.0, because it counts any relevant passage, while nDCG@5 is 0.760, because the best passage was not on top. Graded nDCG catches what binary metrics miss.
- **q2** finds its only relevant passage at rank 5. Recall@3 is 0, so with k = 3 the generator never sees the answer, yet nDCG@5 still gives partial credit of 0.387. Choose k to match what you actually put in the prompt.
- **q3** is perfect on every metric.

For RAG, recall at your prompt depth is the first number to watch: it caps everything downstream. nDCG matters once you add a reranker, and precision matters when prompt tokens are expensive or noise confuses the model. The [precision and recall simulation](/ai-simulations/precision-recall-threshold) shows the trade-off between them.

## Half two: generation metrics and LLM judges

Generation quality has no qrels to compare against, so most metrics use an LLM as a judge. The names differ by library, but the ideas line up:

| Idea | Ragas | DeepEval | TruLens | Question the judge answers |
|---|---|---|---|---|
| Faithfulness or groundedness | Faithfulness | Faithfulness | Groundedness | Is every claim in the answer supported by the retrieved context? |
| Answer relevance | Answer relevancy | Answer relevancy | Answer relevance | Does the answer address the question? |
| Context relevance | Context precision | Contextual relevancy, contextual precision | Context relevance | Is the retrieved context relevant, and is the relevant part ranked high? |
| Context recall | Context recall | Contextual recall | n/a in the triad | Does the context contain what a reference answer needs? |

Faithfulness is usually computed by splitting the answer into individual claims and asking the judge whether each claim is supported by the context; the score is the supported share. If an answer makes five claims and four are supported, faithfulness is 0.8. Context recall works the other way: split a reference answer into claims and check how many the retrieved context supports.

Judges need checking too. Before trusting a judge, label 50 to 100 cases by hand and measure agreement; the site's [LLM judge agreement simulation](/ai-simulations/llm-judge-agreement) shows how agreement statistics behave. The tool pages for [Ragas](/tools/ragas), [DeepEval](/tools/deepeval) and [TruLens](/tools/trulens) list each library's metrics and setup.

## When is a difference real?

Teams often compare two configurations on a few dozen questions and ship the one with the higher score. Small test sets make that a coin toss. The standard error of a success rate p over n questions is sqrt(p(1 − p) / n). For p = 0.70:

- n = 50: standard error 0.065, so a 95 percent interval is roughly ±0.13
- n = 200: standard error 0.032, roughly ±0.06

A 5-point gain on 50 questions is well inside the noise. Because both systems answer the same questions, a paired test is more sensitive than comparing two separate intervals. The paired bootstrap resamples questions with replacement and recomputes the difference each time:

```python
rng = np.random.default_rng(0)
a = rng.binomial(1, 0.70, 200).astype(float)            # per-question hit@5, system A
b = np.clip(a + rng.binomial(1, 0.12, 200) - rng.binomial(1, 0.04, 200), 0, 1)
diffs = [np.mean((b - a)[idx]) for idx in (rng.integers(0, 200, 200) for _ in range(10_000))]
lo, hi = np.percentile(diffs, [2.5, 97.5])
print(f"A={a.mean():.3f} B={b.mean():.3f} diff={b.mean()-a.mean():+.3f} CI=[{lo:+.3f}, {hi:+.3f}]")
```

On this simulated data system A scores 0.635 and system B 0.655 on 200 questions, a difference of +0.020 with a 95 percent bootstrap interval from +0.000 to +0.045. The interval touches zero: the gain might be real, but this test set cannot show it convincingly. For binary per-question outcomes, McNemar's test on the questions where the two systems disagree gives a similar answer; the site's [paired evaluation simulation](/ai-simulations/paired-eval-mcnemar-test) walks through it.

## What it means in practice

Evaluate the two halves separately and keep them in one report. A drop in recall@k points to chunking, embeddings, hybrid search or index changes. A drop in faithfulness with stable recall points to the prompt, the model or the context assembly. Without the split, every regression becomes a guessing game.

Build the test set from reality. Real user questions, with the passages that answer them labelled by someone who knows the documents, beat synthetic questions generated from chunks, which tend to copy the chunk's wording and flatter retrieval. Synthetic sets are useful for coverage, but anchor them with real ones.

The library releases this month make generation-side scoring easier to run in CI, but they do not remove the need for labelled retrieval data. Retrieval metrics are cheap, deterministic and reproducible with tools like `pytrec_eval`; LLM-judged metrics cost money, vary with the judge model and need calibration. Use both, and treat judged scores as estimates with error bars.

## What to do now

1. **Label 100 to 200 real questions.** Record the passage IDs that answer each, with graded relevance where possible.
2. **Measure recall at your prompt depth.** If the prompt gets five chunks, track recall@5 as the headline retrieval number.
3. **Add nDCG@10 when you rerank.** It captures order improvements that recall cannot see.
4. **Verify your metric code.** Cross-check hand-written metrics against `pytrec_eval` on a few questions, as this article did.
5. **Score faithfulness and answer relevance with a judge.** Use Ragas, DeepEval or TruLens, and log per-question scores, not just averages.
6. **Calibrate the judge.** Label 50 to 100 answers by hand and measure agreement before trusting judged trends.
7. **Compare systems with paired tests.** Use a paired bootstrap or McNemar's test and report intervals, not single numbers.
8. **Run the suite on every change.** Chunking, embedding, index, prompt and model changes all go through the same evaluation gate in CI.
9. **Slice the results.** Break scores down by question type, document source and language to find where failures cluster.

## Risks and open questions

**Qrels are incomplete.** Labellers rarely mark every relevant passage, so a retriever that finds an unlabelled good passage is penalised. Review "false positives" before concluding retrieval got worse.

**Judges have biases.** LLM judges can favour longer answers, answers in their own style, or answers that sound confident. Different judge models give different scores for the same output.

**Synthetic test sets flatter retrieval.** Questions generated from a chunk share its wording, which inflates recall compared with real user questions.

**Averages hide failures.** A mean faithfulness of 0.9 can include a cluster of completely unsupported answers on one topic. Always inspect the worst cases.

**Small samples mislead.** As the worked example shows, 200 questions may still not separate two close systems. Decide the size of difference that matters before testing.

**Watch next:** whether evaluation libraries converge on shared definitions for faithfulness and context metrics, and how judge-model choice and calibration become standard parts of published RAG results.

## Frequently asked questions

### What is the most important metric for RAG retrieval?

Recall at the number of chunks you put in the prompt, because the model cannot use evidence it never sees. Add nDCG@10 when you rerank, and precision@k when prompt cost or noise matters.

### What is the difference between MRR and nDCG?

MRR uses only the rank of the first relevant passage and treats all relevant passages as equal. nDCG uses graded relevance and every relevant passage in the top k, discounted by position. In the worked example, q1 had a perfect reciprocal rank of 1.0 but an nDCG@5 of 0.760.

### How many test questions do I need?

Enough that the difference you care about is larger than the noise. With a success rate around 0.70, 50 questions give a standard error of about 0.065 and 200 about 0.032. Use paired tests to compare systems on the same questions.

### Can I trust LLM-as-judge scores?

Only after calibration. Measure agreement between the judge and human labels on a sample, keep the judge model fixed when comparing systems, and treat scores as estimates with error bars.

### Which library should I use: Ragas, DeepEval or TruLens?

All three cover faithfulness, answer relevance and context metrics with different APIs and extras: Ragas focuses on RAG metrics, DeepEval on pytest-style testing across agents and RAG, and TruLens on tracing with the RAG triad. Pick the one that fits your workflow, and compute retrieval metrics with a reference tool such as `pytrec_eval`.

## Summary

RAG evaluation works best in two halves. Retrieval is scored against labelled passages with recall@k, precision@k, MRR, nDCG and MAP; the worked example computed them by hand and matched `pytrec_eval` exactly, and showed how a question can score a perfect reciprocal rank yet only 0.760 nDCG@5. Generation is scored with LLM-judged faithfulness, answer relevance and context metrics, now available in DeepEval 4.3.5, Ragas 0.4.4 and TruLens 2.16.0. Small test sets are noisy: at a 0.70 success rate, 50 questions carry a standard error of 0.065, and a paired bootstrap on 200 questions still could not confirm a 2-point gain. Label real questions, measure each half separately, calibrate judges and report intervals.

## Sources

- [PyPI: deepeval release history](https://pypi.org/project/deepeval/#history)
- [GitHub: DeepEval README](https://github.com/confident-ai/deepeval/blob/main/README.md)
- [PyPI: ragas release history](https://pypi.org/project/ragas/#history)
- [PyPI: trulens project description and release history](https://pypi.org/project/trulens/)
- [PyPI: pytrec-eval-terrier release history](https://pypi.org/project/pytrec-eval-terrier/#history)
- [ACM SIGIR 2018: Pytrec_eval: An Extremely Fast Python Interface to trec_eval (Van Gysel and de Rijke)](https://dl.acm.org/doi/10.1145/3209978.3210065)
- [ACM TOIS: Cumulated gain-based evaluation of IR techniques (Järvelin and Kekäläinen)](https://dl.acm.org/doi/10.1145/582415.582418)
- [arXiv: RAGAS: Automated Evaluation of Retrieval Augmented Generation (Es et al.)](https://arxiv.org/abs/2309.15217)
