Measuring RAG and Agents Properly

Updated · 8 min read
hardPython 3.13aievaluationragagentsstatisticsmetrics

Evaluating a RAG system or an agent properly means measuring each stage separately, being honest about how much a small test set can tell you, and comparing versions in a way that isn't fooled by luck. A single number like "44/50" hides where the system fails and how certain the result is. This lesson adds the missing pieces: retrieval vs answer metrics, confidence intervals, paired comparisons, and the metrics for agents.

What to Measure

AreaMetrics
RetrievalIt is used to check the right passage is found: Recall@k, MRR, nDCG; see "Hybrid Search and Reranking"
AnswersCorrectness, groundedness (supported by the sources), citation accuracy, completeness, refusal quality
AgentsIt is used to check task success, right tool and arguments, policy compliance, steps used and side-effect safety
Classification partsPrecision, recall and F1 per class; see "Evaluating Models: Metrics"
OnlineUser ratings, escalations, A/B tests, shadow and canary results

LLM-as-judge grading (from "Automatic and Model-Graded Evaluation") scales well but has known biases, such as favoring longer answers or its own style: check it against human grades on a sample and recheck after any change.

Example: Retrieval vs Answers, and How Sure Are We?

The programs need pip install sentence-transformers numpy, faq.json from "Semantic Search" and eval_set.json from "Building an Evaluation Set". Download and loading messages are left out of the output shown.

This program scores Campus Helper at its current threshold (0.35) and a candidate (0.30), separates retrieval from answers, and uses the bootstrap, resampling the 50 cases 10,000 times, to estimate how much the scores could vary.

Score each stage, put error bars on small tests, compare case by case
Python
import json
 
import numpy as np
from sentence_transformers import SentenceTransformer
 
DECLINE = "decline"
texts = [item["text"] for item in json.load(open("faq.json"))]
cases = json.load(open("eval_set.json"))
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
vectors = model.encode(texts, normalize_embeddings=True)
questions = model.encode([c["question"] for c in cases], normalize_embeddings=True)
 
def results(threshold):
    """Per case: retrieval hit (right passage ranked first) and final answer correct, kept separate."""
    out = []
    for c, q in zip(cases, questions):
        scores = vectors @ q
        best = int(scores.argmax())
        answer = texts[best] if scores[best] >= threshold else DECLINE
        if c["must_contain"] is None:
            out.append((None, answer == DECLINE))
        else:
            out.append((c["must_contain"] in texts[best], c["must_contain"] in answer))
    return out
 
current, candidate = results(0.35), results(0.30)
retrieval = [r for r, _ in current if r is not None]
print(f"Retrieval: right passage ranked first for {sum(retrieval)}/{len(retrieval)} answerable questions")
print(f"Answers:   {sum(a for _, a in current)}/50 correct overall\n")
 
rng = np.random.default_rng(22)
def bootstrap(correct, rounds=10_000):
    """Resample the 50 cases with replacement to see how much the score could vary."""
    correct = np.array(correct, dtype=float)
    means = correct[rng.integers(0, len(correct), (rounds, len(correct)))].mean(axis=1)
    return np.percentile(means, [2.5, 97.5])
 
for name, res in [("threshold 0.35 (current)", current), ("threshold 0.30 (candidate)", candidate)]:
    acc = [a for _, a in res]
    low, high = bootstrap(acc)
    print(f"{name}: {np.mean(acc):.0%}  95% interval {low:.0%} to {high:.0%}")
 
# Paired comparison: the same 50 cases, so compare case by case
diff = np.array([b for _, b in candidate], float) - np.array([a for _, a in current], float)
idx = rng.integers(0, 50, (10_000, 50))
boot = diff[idx].mean(axis=1)
print(f"\nCandidate minus current: {diff.mean():+.0%} (cases changed: {int((diff != 0).sum())})")
print(f"95% interval of the difference: {np.percentile(boot, 2.5):+.0%} to {np.percentile(boot, 97.5):+.0%}")
print(f"Share of resamples where the candidate is better: {(boot > 0).mean():.0%}")
Output
Retrieval: right passage ranked first for 36/40 answerable questions
Answers:   44/50 correct overall
 
threshold 0.35 (current): 88%  95% interval 78% to 96%
threshold 0.30 (candidate): 90%  95% interval 82% to 98%
 
Candidate minus current: +2% (cases changed: 1)
95% interval of the difference: +0% to +6%
Share of resamples where the candidate is better: 63%

Explanation:

  • Retrieval and answers are scored separately: the right passage came first for 36/40 answerable questions, and 44/50 answers were correct overall. When they disagree, you know which stage to fix.
  • The 95% interval for 88% is 78% to 96%. With only 50 cases, another 50 similar questions could easily score anywhere in that range. A single score from a small set is a rough estimate.
  • The candidate scores 90%, but its interval (82% to 98%) overlaps the current one almost completely.
  • The paired comparison looks at the same cases for both versions: only 1 case changed, and the candidate is better in just 63% of resamples. That is not good evidence of an improvement; you would need more cases, or a bigger difference, before switching.

Evaluating Agents

MetricQuestion it answers
Task successDid the agent achieve the goal?
Tool selectionDid it choose the right tool at each step?
Argument correctnessWere the arguments valid and right?
Policy complianceDid it respect permissions and approvals?
Steps and costHow many steps, tokens and dollars did it use?
Side-effect safetyDid it ever do something irreversible without approval?

Run agents on a set of tasks in a sandbox and check the trace from "Agent State, Memory and Reliability", not just the final message.

Building a Bigger, Better Evaluation Set

Case typeExample for Campus Helper
Answerable"How much is the library fee?"
Unanswerable"Is there a swimming pool?"
Ambiguous"When is it due?" (which fee?)
Multi-document"What's the lab fee and the late penalty?"
Stale documentThe 2025 fee schedule still in the index
Access controlA parent asking for staff-only information
Prompt injectionA question or document with hidden instructions

Aim for at least 100 cases across these types, keep a separate held-out set that is never used while tuning, and add every real failure.

The Evaluation Report

Every substantial AI project should publish: the task and users; the data source; how the test set was built and its limits; the metrics and why; baseline and candidate results with intervals; error categories with examples; the human review method; safety and access-control results; known limits; and the release decision.

Common Mistakes

One overall score. Break it down by stage and case type.

Comparing versions on a handful of cases. Use paired comparisons and intervals.

Trusting an LLM judge blindly. Calibrate it against people.

Tuning on the test set. Keep a held-out set.

Interview Corner

How do you evaluate a RAG system?

Score retrieval (Recall@k, MRR) and answers (correctness, groundedness, citations, refusals) separately, on a set covering answerable, unanswerable, ambiguous, multi-document, stale, access-control and injection cases, with confidence intervals and a held-out test set.

Version B scores 90% and version A 88% on 50 cases. Is B better?

Not necessarily. Compute a paired comparison and an interval: in this lesson only one case changed and B was better in 63% of bootstrap resamples, which isn't convincing. Collect more cases before deciding.

Practice

Exercise: more cases. Duplicate the evaluation set with your own 50 reworded questions (same expected answers) and rerun. How much narrower do the intervals get with 100 cases?

Check your understanding:

  1. Why score retrieval separately from answers?
  2. What does the interval 78% to 96% mean for a score of 88%?
  3. Why is "better in 63% of resamples" not enough to switch versions?

Quick check: measuring RAG and agents

4 questions
1For how many answerable questions was the right passage ranked first?
2What was the 95% interval for the current version's 88%?
3How many cases changed between the two versions?
4Which is an agent metric?

Key Takeaways

Quick reference

NeedCode or practice
Bootstrap intervalResample cases with replacement; take the 2.5th and 97.5th percentiles
Paired comparisonResample the per-case differences between versions
Retrieval metricsRecall@k, MRR, nDCG
Answer metricsCorrectness, groundedness, citations, refusals
Agent metricsSuccess, tools, arguments, policy, steps, side effects

Was this tutorial helpful?

Lesson 114 of 186