Library

Volume 2 · AI Evaluation Frameworks

Notebook
Sign in

Section 58

RAG-Specific Evaluation (RAGAS Framework Deep Dive, Golden Dataset Methodology, Evaluation Dimensions)

1,153 words · about 5 min

58.1 Retrieval Metrics (Upstream of Generation Quality)

Metric Description Target
Hit rate % of queries where the correct document is in the top-K >95%
MRR (Mean Reciprocal Rank) Average rank of the first relevant result >0.7
NDCG@10 Normalized Discounted Cumulative Gain >0.6
Context precision % of retrieved chunks that are relevant >80%
Context recall % of needed information that was retrieved >90%

Retrieval quality is upstream of everything else — a generation model cannot be faithful to context that was never retrieved. Any RAG evaluation program must measure retrieval and generation separately, because the two failure modes have entirely different fixes (search/index tuning vs. prompt/model tuning).

58.2 RAGAS Framework Deep Dive

RAGAS (Retrieval-Augmented Generation Assessment) is the most widely adopted open framework for automated RAG evaluation, providing reference-free and reference-based metrics computed via LLM-as-judge under the hood.

from ragas import evaluate
from ragas.metrics import (
    faithfulness,
    answer_relevancy,
    context_precision,
    context_recall,
    answer_correctness
)

# Prepare evaluation dataset
eval_data = {
    "question": ["What is the return policy for damaged items?", ...],
    "answer": ["Damaged items can be returned within 30 days...", ...],
    "contexts": [["Policy doc: Returns section...", ...], ...],
    "ground_truth": ["30-day return window for damaged goods...", ...]
}

results = evaluate(
    dataset=eval_data,
    metrics=[
        faithfulness,          # Is the answer grounded in the retrieved context?
        answer_relevancy,      # Does the answer address the question?
        context_precision,     # Are the retrieved chunks relevant?
        context_recall,        # Was all needed information retrieved?
        answer_correctness     # Is the answer correct vs. ground truth?
    ]
)
print(results)
# faithfulness: 0.92, answer_relevancy: 0.88,
# context_precision: 0.85, context_recall: 0.90

What each RAGAS metric actually catches:

Metric Failure Mode It Catches Points To
Faithfulness Generation adds claims not in retrieved context Prompt/generation issue (hallucination)
Answer relevancy Answer is grounded but doesn’t address the actual question Query understanding / generation issue
Context precision Too much irrelevant context retrieved Retrieval/ranking issue (noisy top-K)
Context recall Relevant information exists but wasn’t retrieved Retrieval/indexing issue (chunking, embedding, top-K too small)
Answer correctness Answer diverges from known ground truth Combination of retrieval + generation issue

58.3 Building a Golden Evaluation Dataset

Requirements:

  • 100-500 question-answer pairs (100 is the practical minimum for statistically meaningful gating)
  • Representative of the real production query distribution — mined from actual logs, not just imagined by engineers
  • Includes edge cases: ambiguous, multi-hop, unanswerable
  • Human-reviewed ground-truth answers (domain expert sign-off for regulated domains)
  • Refreshed quarterly as query patterns and the underlying corpus evolve

Recommended category distribution:

Golden Dataset Structure:
├── Simple factual (40%)        — "What is X?"
├── Complex analytical (20%)    — "Compare X and Y, considering Z"
├── Multi-hop reasoning (15%)   — "Given A and B, what is C?"
├── Unanswerable (10%)          — Questions outside corpus scope (must correctly decline)
├── Adversarial (10%)           — Trick questions, ambiguous phrasing, injection attempts
└── Multi-turn (5%)             — Follow-up questions requiring conversational context

Methodology for building it:

  1. Sample real production queries (stratified by frequency and by known-difficult categories).
  2. Draft candidate ground-truth answers with citations; route to domain experts for verification/correction.
  3. Explicitly construct “unanswerable” and “adversarial” cases — these are usually underrepresented if the dataset is built only from real logs, but they catch the most dangerous failure modes.
  4. Version the dataset (golden_v1, golden_v2, …) and track evaluation scores against each version over time — never silently swap the dataset without noting the version, or historical trend lines become meaningless.
  5. Refresh quarterly: add newly discovered failure patterns from production feedback (Section 63), retire stale/irrelevant cases as the corpus changes.

58.4 Domain-Specific Evaluation Example (High-Stakes RAG)

For a high-stakes domain (e.g., legal, medical, financial document assistants), the evaluation bar shifts materially:

Dimension Metric Target Why Critical
Factual accuracy Answer correctness vs. ground truth >98% Advice must be correct
Citation accuracy Correct document/section/clause cited >99% Must be independently verifiable
Hallucination Claims not in source documents <0.5% Near-zero tolerance
Completeness All relevant clauses/precedents surfaced >95% Missing information can be as dangerous as wrong information
Domain-context awareness Correct jurisdiction/context applied >99% Wrong context invalidates the answer even if text-accurate

Evaluation process for such domains layers automated and human checks: golden dataset scored via RAGAS + custom domain-specific validators (e.g., a citation checker that verifies cited clauses actually exist and say what’s claimed) on every change; a rotating sample of production responses reviewed weekly by domain experts; a full monthly audit report for compliance; and real-time alerting on any hallucination or miscitation detected in production.

Interview Q&A — Section 58

Q1: RAGAS shows high faithfulness but low context recall. What does that tell you and what do you fix? A: High faithfulness means the generation model is staying grounded in whatever it was given — it’s not hallucinating. Low context recall means the retrieval step isn’t surfacing all the information actually needed to answer correctly. The fix is entirely on the retrieval side, not the generation/prompt side: this could mean the chunking strategy is splitting relevant information across chunks so no single chunk contains the full answer, top-K is too small, the embedding model isn’t capturing domain-specific semantic similarity well, or the index needs hybrid (keyword + vector) search to catch exact-term matches that pure embedding similarity misses. I’d diagnose by manually inspecting the missed-recall query set to identify which specific failure mode dominates before picking a fix.

Q2: How large does a golden evaluation dataset need to be, and how do you keep it representative over time? A: 100 examples is the practical floor for a statistically meaningful regression gate; 300-500 gives more stable per-category signal, especially once you slice by category (simple/complex/multi-hop/unanswerable/adversarial). Representativeness is maintained by continuously mining new production query patterns and failure clusters (surfaced via the feedback loop in Section 63) into the dataset on a quarterly cadence, retiring stale cases tied to retired corpus content, and deliberately over-sampling the categories that cause the most harm when wrong (unanswerable and adversarial) even if they’re rare in raw traffic — a 40% share of “simple factual” queries in your dataset shouldn’t mean 40% of your evaluation attention, because that’s not where the risk is concentrated.

Q3: Design the evaluation approach for a RAG-based legal document assistant end to end. A: Golden dataset of 500 legal Q&A pairs with lawyer-verified ground truth and citations, covering the six category buckets above with extra weight on adversarial/unanswerable cases. Automated pipeline runs RAGAS (faithfulness, context precision/recall, answer correctness) plus a custom citation validator that confirms every cited clause exists and actually supports the claim, on every prompt/retrieval/model change, gated in CI (Section 62) with near-zero tolerance thresholds (hallucination <0.5%, citation accuracy >99%). Weekly, a rotating sample of real production responses is reviewed by practicing lawyers, feeding both the golden dataset and prompt/retrieval fixes. Monthly, a full evaluation report goes to the compliance/governance function (Section 69). Any hallucination or wrong-citation detected in production triggers an immediate alert and incident review, not just a metric dip on a dashboard.