🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Evaluating RAG Systems: Faithfulness and Context

RAGopsEvaluation MetricsđŸŸĸ Free Lesson

One score cannot describe a RAG system

A retrieval-augmented generation pipeline fails in two independent places, and a single end-to-end number hides which one moved. The retriever can miss the supporting passage entirely, in which case the generator is being asked to improvise. Or the retriever can deliver the right passage and the generator can still paraphrase it into something unsupported. Confusing the two produces the most common wasted quarter in RAG operations: teams rewrite prompts for weeks while the real defect sits in chunk boundaries two stages upstream.

The remedy is to evaluate each stage against its own metrics, on the same fixed dataset, at every pipeline change. Retrieval is judged by whether relevant material was fetched and where it ranked. Generation is judged by whether the answer is grounded in what was fetched and whether it addresses the question asked. Only the conjunction — correct evidence, faithfully used, answering the right question — constitutes a good user experience, so the scorecard reports all three rather than averaging them into a single flattering figure.

This lesson covers the metric families, how to build a dataset that stays useful as the product changes, where automated judges are trustworthy, and how to wire the scores into a release gate that actually blocks bad deploys.

Retrieval metrics: was the evidence fetched?

Recall@K is the metric to watch first. It asks, of all the passages known to support the answer, how many appeared in the top K retrieved. Low recall@5 places a hard ceiling on answer quality no matter how capable the generator is. Precision@K is its counterpart: of the K passages returned, how many were relevant. High recall with low precision means the context window fills with distractors, and models attending over long contexts tend to blend them into the answer.

Ranking metrics add position sensitivity. Mean reciprocal rank scores a query by the rank of the first relevant passage — 1 for first, 0.5 for second, 0.1 for fifth — and is the right summary when one good passage is enough. Normalised discounted cumulative gain handles queries with several relevant passages of unequal usefulness, rewarding systems that surface the most valuable ones near the top.

MetricQuestion it answersSensitive to rank?Failure it exposes
Recall@KWas the evidence fetched?NoMissed passages, bad chunking
Precision@KIs the result set clean?NoDistractors crowding the context
MRRIs the best passage first?YesWeak query rewriting
NDCGAre the best passages ranked best?YesPoor ordering of multi-relevance answers

All four require labelled relevance. Start with a query set of one to two hundred items, each paired with the passages that support its answer, and grow it from real user questions that support or analytics teams flag as mishandled.

python
class ContextRankingMetrics:
    """Recall@K, precision@K and MRR over labelled relevance sets."""

    def recall_at_k(self, retrieved: list[str], relevant: set[str], k: int) -> float:
        if not relevant:
            return 0.0
        top = retrieved[:k]
        return len(set(top) & relevant) / len(relevant)

    def precision_at_k(self, retrieved: list[str], relevant: set[str], k: int) -> float:
        top = retrieved[:k]
        if not top:
            return 0.0
        return len(set(top) & relevant) / len(top)

    def mrr(self, retrieved: list[str], relevant: set[str]) -> float:
        for rank, doc_id in enumerate(retrieved, start=1):
            if doc_id in relevant:
                return 1.0 / rank
        return 0.0

    def evaluate_run(self, run: list[dict], k: int = 5) -> dict:
        recalls, precisions, mrrs = [], [], []
        for query in run:
            recalls.append(self.recall_at_k(query["retrieved"], query["relevant"], k))
            precisions.append(self.precision_at_k(query["retrieved"], query["relevant"], k))
            mrrs.append(self.mrr(query["retrieved"], query["relevant"]))
        n = max(len(run), 1)
        return {
            f"recall@{k}": sum(recalls) / n,
            f"precision@{k}": sum(precisions) / n,
            "mrr": sum(mrrs) / n,
            "queries": len(run),
        }

Score retrieval before generation on every pipeline change. A drop in recall with flat generation scores points at ingestion or chunking; flat recall with dropping faithfulness points at the prompt or the context assembly order.

Generation metrics: was the answer grounded?

Faithfulness is the central generation metric: of the factual claims the answer makes, what fraction are supported by the retrieved context? Measuring it requires decomposing the answer into claims and verifying each one against the context, either with an entailment model or with a judge model constrained to answer yes or no per claim. Answers that add plausible-sounding facts not present in the context score low even when nothing they say is false in the world — and in a corporate knowledge assistant, unsourced claims are precisely the failure users cannot detect.

Answer relevance asks the complementary question: does the response address what was asked? An answer can be perfectly faithful to a passage that is simply about something else. Relevance is commonly estimated by generating several questions that the answer would suit and measuring embedding similarity to the original question.

Context precision and context recall complete the picture from the generation side. Context precision measures how much of the supplied context was actually useful; context recall measures whether the context contained everything the answer needed. Together with faithfulness they triangulate: low context recall with normal faithfulness means the retriever starved the model; normal context recall with low faithfulness means the model wandered.

python
class FaithfulnessScorer:
    """Decompose an answer into claims and verify each against context."""

    def __init__(self, judge):
        self.judge = judge

    def score(self, question: str, answer: str, context: str) -> dict:
        claims = self._claims(answer)
        if not claims:
            return {"faithfulness": 0.0, "claims": 0, "supported": 0}

        supported = sum(
            1 for claim in claims
            if self._entailed(context, claim)
        )
        return {
            "faithfulness": supported / len(claims),
            "claims": len(claims),
            "supported": supported,
        }

    def _claims(self, answer: str) -> list[str]:
        prompt = (
            "Extract every independently verifiable factual claim from the "
            "answer below. One claim per line, no commentary.\n\n"
            f"Answer:\n{answer}\n\nClaims:"
        )
        lines = self.judge.generate(prompt).splitlines()
        return [line.strip("-* ").strip() for line in lines if line.strip()]

    def _entailed(self, context: str, claim: str) -> bool:
        prompt = (
            "Does the context fully support the claim? "
            "Answer with exactly yes or no.\n\n"
            f"Context:\n{context}\n\nClaim:\n{claim}\n\nAnswer:"
        )
        return self.judge.generate(prompt).strip().lower().startswith("yes")

Two details make this reliable in practice. The claim extractor must be prompted to produce atomic claims — bundled multi-part sentences will be marked unsupported if any single element is missing from the context. And the entailment prompt should ask whether the context fully supports the claim rather than whether it is generally plausible, because "generally plausible" lets the judge import its own knowledge and inflates every score.

Building an evaluation dataset that ages well

Synthetic generation from your own documents is the fastest way to get started and the easiest way to build a biased set: questions generated by a model from a passage tend to be answerable by that passage, which flatters recall. Balance generated pairs with questions harvested from production search logs and support tickets, including the ones your system currently fails.

Version the dataset alongside the pipeline. When the product adds a new document family, add queries for it; when a metric moves, you need to know whether the dataset changed at the same time. Keep a small human-verified core set that never changes, so quarter-over-quarter comparisons have an anchor.

Automated judging and its limits

Model judges are necessary at scale and unreliable in the small. They exhibit position bias, verbosity bias, and a marked tendency to agree with themselves when asked to grade their own outputs. Mitigations are practical: fix the judge model version, randomise the order when comparing two answers, grade one claim per call instead of a whole answer at once, and calibrate periodically against a few hundred human-labelled examples. If judge scores and human scores diverge by more than a few points, treat the human labels as ground truth and re-prompt the judge before trusting any trend line.

Turning metrics into a release gate

A scorecard only changes behaviour when it can block a release. Wire the evaluation suite into the deployment pipeline so every ingestion, embedding, or prompt change runs the full set and compares against the stored baseline for the current production version. Block when any primary metric regresses beyond a tolerance — a drop of two points in faithfulness or three in recall@5 is usually meaningful noise-free signal at a few hundred queries — and require an explicit, logged override to proceed anyway.

Common Mistakes

Reporting a single blended quality score for the whole RAG system

Fix: Report retrieval and generation metrics separately so regressions can be localised to a stage.

Building the evaluation set only from questions generated by a model over your own documents

Fix: Mix in production search queries and support tickets, including known failures.

Letting the judge model grade an entire answer in one call

Fix: Score one atomic claim per call and fix the judge version to keep scores comparable.

Comparing runs across a dataset that changed in between

Fix: Version the dataset and keep a frozen human-verified core set as the cross-quarter anchor.

Key Takeaways

  • Evaluate retrieval and generation separately — end-to-end scores cannot tell you which stage regressed.
  • Start with recall@K: if the evidence was never fetched, prompt work cannot recover the answer.
  • Faithfulness is measured claim by claim against the retrieved context, not by whether the answer sounds right.
  • Context precision and context recall separate a starved retriever from a wandering generator.
  • Model judges need version pinning, one-claim-per-call grading, and periodic calibration against human labels.
  • Wire the suite into CI with a stored baseline and a regression tolerance so evaluation actually gates releases.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert AI Ops & LLM Ops Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement