Production RAG Evaluation for Groundedness and Retrieval Quality

AI & Agents

Build a production RAG evaluation gate for groundedness, retrieval precision, answer relevance, and semantic drift using versioned fixtures and paired replays.

TL;DR

  • Production RAG evaluation measures retrieval, groundedness, and answer quality separately. Record the exact evidence the model saw and the evidence a reviewer expected. Those two records let you tell whether a failure began in the index, the context builder, or the answer.
  • Use deterministic checks for ranked evidence IDs, authorization scope, and citation resolution. Use human judgments or a calibrated model judge for whether evidence supports individual claims. Keep unsupported, contradicted, and unreviewable claims distinct so a broken judge cannot inflate the score.
  • Replay a fixed, versioned dataset before releasing changes. Supplement it with reviewed traffic and synthetic cases that cover hard negatives, changed policies, and correct abstentions. Compare candidate and baseline on the same case IDs, then look at individual risk slices and tail latency before increasing traffic.

What breaks in a production RAG pipeline

Consider a support assistant that answers questions from a product manual, a shipping policy, and an account-specific knowledge base. The team changes chunking to preserve more section context and sees a higher average similarity score. Then a customer asks whether a refund deadline applies to an order they already received. The assistant retrieves an archived policy, cites it correctly, and gives the wrong deadline. A faithfulness score based only on the retrieved passages can pass this answer. The operational defect concerns source authority and freshness.

Retrieval defects have different shapes. Sometimes the authoritative document never enters the candidate set because the question uses a product nickname. Sometimes the right evidence ranks sixth and the prompt takes only five chunks. Sometimes the chunk arrives in the prompt but its exception is separated from the rule by an extraction error. Logging only the vector results conflates these cases. Record the candidate list, the active filters, and the actual ordered set of passages sent to the model.

Generation has its own failure modes. The answer may correctly quote a sentence and add a deadline the source never supplies. It may answer one clause of a two-part question or bury the requested recommendation beneath unrelated material. A reviewer should score those behaviors separately. An answer can be supported and irrelevant, or relevant and unsupported. The original RAGAS paper separates evidence relevance, faithfulness, and response relevance for this reason.

Quality also changes when traffic changes. A flat aggregate can hide a decline for newly onboarded products while common questions improve. A nightly evaluation of old fixtures catches regressions on those fixtures. A production sample catches new intents, stale assumptions about the corpus, and behavior at prompt sizes the fixed set rarely reaches. Plan for both sources of evidence before selecting your judge.

Design the evaluation around the evidence trail

Measure retrieval on the context the model receives

Retrieval precision at k is the fraction of the top k context slots judged relevant. A strict five-slot budget counts an empty slot as a miss. Also record the returned count so the report shows whether the system intentionally emitted fewer passages. Recall asks how many labeled relevant items made it into the selected set. If your annotation set contains only a few known passages, describe recall as measured against that set. Alternative valid passages may be missing from the labels.

When ranked position matters, add a ranking metric such as average precision or normalized discounted cumulative gain. Record where the authoritative source first appears and evaluate the order after reranking, deduplication, and token truncation. Ragas uses its own definition of context precision. Name your formulas and denominators in the report so reviewers can distinguish a slot-based score from an order-sensitive one.

Judge groundedness, correctness, and response relevance separately

Groundedness is the fraction of factual claims supported by the supplied evidence. Break a sentence such as “The return window is 30 days and opened items are eligible” into two claims. Require the reviewer to identify supporting passages. Check that cited IDs resolve to the right version, then judge whether the identified passage actually entails the claim. Citation resolution can be deterministic. Entailment depends on interpretation, especially when a table, exception, or effective date carries the meaning.

Correctness adds the authoritative answer or policy expectation. Response relevance tracks whether the answer addresses the user’s actual request, including required parts. For an unanswerable fixture, score abstention or escalation as its own outcome. A response with zero factual claims supplies no groundedness denominator. Give a compliant abstention credit in its own metric and keep it out of groundedness averages.

Version each layer of the evaluation

A replay row should carry a stable case ID, question, expected outcome, evidence labels, effective date, and slice labels. Attach corpus and index identifiers to the run. Capture model, embedding, reranking, prompt, and judge versions separately. A single build identifier identifies a release, while a row-level diff helps explain the release. If chunk IDs change, preserve an evidence ID at the passage or source-revision level, and store offsets so reviewers can inspect the specific text selected.

For a first dataset, collect cases from domains where support outcomes are known, then commission a small set of hard questions from domain owners. Create synthetic questions from document passages to add rare variants such as misspellings, multi-part questions, and references to superseded policy. Hold out complete document families or versions when tuning and testing. A split at the question level allows paraphrases from the same source paragraph to leak between the two sets. Hand-review generated answers and preserve their evidence pointers. Ragas test data generation documentation.

Compare a frozen benchmark with recent traffic

Semantic drift is a change in what people ask, what sources mean in context, or how the system interprets an intent over time. Keep a frozen replay set to detect changes to the pipeline itself. Track a rolling evaluation set by intent, language, source revision, and answerability to detect changing coverage in production. Look for increases in no-result queries, large changes in where relevant passages rank, and new disagreements between the model and reviewers. A shift in embedding similarity is a triage signal. Review labeled evidence and answer outcomes to decide whether it represents degradation.

Implement a paired replay gate

Score evidence and claim labels offline

Start with an evaluator that works on captured outputs and reviewed labels. The example uses Python 3.12 and permits any corpus or model provider. The retriever emits evidence IDs in final prompt order. The reviewer records one status per claim, and relevance is a separate pass or fail judgment against the question. A gate can read these objects from JSON Lines using your existing report pipeline.

# scores.py — Python 3.12
from dataclasses import dataclass
from typing import Literal

Verdict = Literal["supported", "unsupported", "contradicted", "unreviewable"]


@dataclass(frozen=True)
class Case:
    evidence: frozenset[str]
    answerable: bool


@dataclass(frozen=True)
class Replay:
    context: tuple[str, ...]
    claims: tuple[Verdict, ...]
    relevant_answer: bool
    abstained: bool


def score(case: Case, replay: Replay, *, k: int = 5) -> dict[str, float | None]:
    if k < 1:
        raise ValueError("k must be positive")
    chosen = replay.context[:k]
    # A repeated passage consumes a slot without adding evidence.
    hits = len(case.evidence.intersection(chosen))
    verdicts = set(replay.claims)
    if verdicts - {"supported", "unsupported", "contradicted", "unreviewable"}:
        raise ValueError("unknown claim label")
    grounded = None
    if replay.claims and "unreviewable" not in verdicts:
        grounded = replay.claims.count("supported") / len(replay.claims)
    return {
        "precision": hits / k if case.evidence else None,
        "recall": hits / len(case.evidence) if case.evidence else None,
        "groundedness": grounded,
        "relevance": float(replay.relevant_answer) if case.answerable else None,
        "abstention": float(replay.abstained and not replay.claims) if not case.answerable else None,
    }

The gate should count judge failures and claim-free answers separately. A timeout or an invalid judge response creates an unreviewable case. Retry bounded transient errors and send repeated failures to reviewers. Archive the rubrics and a few scored examples. If humans consistently disagree about whether a sentence is supported, clarify the decision rule before increasing the number of automated judgments.

Compare the same cases and enforce a coverage floor

The comparison below uses a mapping from fixture IDs to groundedness scores for answerable cases. It fails when coverage is insufficient and compares means only over the shared scored IDs. Use a paired bootstrap or another interval appropriate to your sample design for release decisions near a threshold. Run similar checks for recall, correct abstention, and the human-reviewed critical slice. Keep an explicit zero-tolerance release condition for unauthorized evidence and policy violations requiring human escalation.

# gate.py — Python 3.12
from statistics import fmean


def groundedness_gate(
    baseline: dict[str, float | None],
    candidate: dict[str, float | None],
    *,
    min_coverage: float,
    min_score: float,
    max_drop: float,
    min_pairs: int,
) -> float:
    if baseline.keys() != candidate.keys() or not baseline:
        raise ValueError("compare matching, nonempty fixture sets")
    if min_pairs < 1 or any(
        not 0 <= threshold <= 1 for threshold in (min_coverage, min_score, max_drop)
    ):
        raise ValueError("invalid coverage, score, or regression thresholds")
    for scores in (baseline, candidate):
        if any(value is not None and not 0 <= value <= 1 for value in scores.values()):
            raise ValueError("groundedness values must be in [0, 1]")
    pairs = [
        (baseline[case_id], candidate[case_id])
        for case_id in sorted(baseline)
        if baseline[case_id] is not None and candidate[case_id] is not None
    ]
    if len(pairs) < min_pairs or len(pairs) / len(baseline) < min_coverage:
        raise RuntimeError("insufficient paired judge coverage")
    baseline_mean, candidate_mean = map(fmean, zip(*pairs))
    if candidate_mean < min_score or baseline_mean - candidate_mean > max_drop:
        raise RuntimeError(f"groundedness gate failed: {candidate_mean:.3f}")
    return candidate_mean

A rollout job can read the following settings from a checked-in JSON file. These values are illustrative. Apply the groundedness configuration to answerable cases, give retrieval and abstention their own coverage rules, and size release slices according to the consequence of an error and available review capacity.

{
  "dataset": "support-policy-eval-v3",
  "k": 5,
  "groundedness": {
    "min_coverage": 0.98,
    "min_score": 0.95,
    "max_drop": 0.02,
    "min_pairs": 100
  },
  "critical_slices": ["effective-date", "account-scope", "answer-absent"]
}

Use a staged release: fixed replay on merge candidates, a scheduled test over curated traffic, and a limited rollout with comparison dashboards. Log evaluation metadata alongside trace and request IDs so reviewers can connect a reported answer to a particular retrieval and generation path. Keep raw document content and customer questions in controlled storage with an explicit retention policy. The log event can carry opaque case IDs, scores, and revision identifiers. Correlating structured logs with OpenTelemetry traces.

Failure modes your release report should expose

Archive documents crowd out the active policy

A fresh index rebuild exposes superseded policies because ingest metadata lacks effective dates. Groundedness stays high because answers quote retrieved text accurately, while policy correctness falls. Store source authority and effective dates, filter early, and replay the same question against different as-of dates. A new revision should leave a report entry showing which expected evidence IDs changed and why.

More context hides the source the answer needs

A larger retrieval budget raises recall but puts a key passage in the middle of redundant text. Quality drops on questions requiring an exception or cross-reference. Record rank and position in the final prompt, then compare results for alternate orderings and deduplicated passages. Controlled experiments found position sensitivity in the models studied by Liu and colleagues. Measure the effect for your own model and prompt before changing the budget.

The judge starts scoring a different rubric

A provider update changes the judge response or a revised prompt tolerates deductions that earlier reviews rejected. Replaying the baseline with the new judge isolates how its scores moved. Keep a set with stable human labels, compare judge disagreement per category, and sample its wrong verdicts. Inspect “unreviewable” counts before interpreting a jump in mean groundedness.

The replay excludes an important slice

Overall relevance rises after reranking, while cases involving two different policy sections lose their second required source. A report grouped by multi-document questions exposes the regression. When a slice has few cases, publish its count and reviewed failures alongside the average. Add fixtures from related but distinct source documents before drawing conclusions from small differences.

Choose an evaluation approach for the available evidence

Reference-based checks are a good fit for stable, regulated answers with named authorities. Exact strings may be appropriate for dates and amounts, while meaning still requires a review. Ownership of the reference answer is essential because it ages along with the corpus.

Reference-free judgments scale to diverse traffic where an approved answer is unavailable. Use them for relevant context, claim support, and candidate discovery. When the source itself may be wrong or unsafe to disclose, add separate domain and authorization checks. For exploratory releases, review a portion of flagged and passing rows to estimate how often the judge agrees with experts.

Human-only assessment makes sense for a small volume of consequential answers with nuanced policies. Invest in a rubric, adjudication rules, and independent assessment of overlapping cases. Automate deterministic prerequisites even when answer quality stays manual. This reserves review time for decisions that require domain knowledge.

Illustrative release numbers

Assume 200 answerable fixture IDs, with 198 scored in both baseline and candidate. Suppose candidate groundedness improves from 96.1% to 96.3%, while recall on an effective-date slice falls from 20 of 24 cases to 15 of 24. The groundedness gate passes because 99% of eligible rows have paired scores. The release still needs investigation because recall fell by five cases on a defined slice. These figures describe a hypothetical evaluation, with no claim about measured client performance.

Use the first 15 minutes after release to inspect sampling coverage, error classes, and p95 latency on comparable request sizes. For a hypothetical search budget of 300 milliseconds, the relevant measure is the distribution of time from retrieval start to the final context, including the reranker. Averages can hide a latency breach even if relevance rises. Retain a route back to the previous index snapshot while comparing the candidate.

Frequently asked questions

How do you measure groundedness in production RAG evaluation?

Split each answer into factual claims and compare every claim with the exact context shown to the model. Record whether the evidence supports, contradicts, or leaves the claim unsupported. Count unreviewable answers separately and report coverage beside the groundedness score. Validate source freshness and policy correctness with their own tests.

Does higher retrieval precision always improve a RAG answer?

Higher retrieval precision can reduce distracting context, but it may also omit a low-ranked passage required for a multi-part answer. Compare precision, recall, and response quality on the same cases. Treat source authority, ordering, and the prompt token budget as separate variables, then replay cases where one metric improved and another declined.

How often should a team rerun RAG evaluations?

Run the fixed replay set before changing embeddings, chunking, prompts, reranking, or models. Schedule additional runs as source documents and ordinary traffic change. Reassess the judge whenever its model or rubric changes, using stable human annotations. Set the cadence according to source update frequency and the consequence of an incorrect answer.

Further reading

Review your RAG release gate

If you’re implementing production RAG evaluation, talk to our engineering team about evidence coverage, reviewer calibration, or a safe rollout for a retrieval change.

Dumb Potato Editorial

Putting this into practice?

Share the problem you’re solving and the tradeoffs you’re weighing with our engineering team.

See how we help with ai solutions

Discuss your project