AI Engineering & Evaluation8 min readUpdated: 2025-02-15

Measuring RAG Retrieval Quality, Semantic Groundedness, and Citation Fidelity in Production

A practical guide to implementing Context Recall@K, NLI-based Faithfulness scoring, and automated citation verification without breaking latency budgets.

RAGEvaluationGroundednessHallucination DetectionVector SearchPythonTypeScript

Core Takeaway

Retrieval-Augmented Generation (RAG) is the primary architecture for grounding LLMs in proprietary knowledge bases. However, moving RAG from prototypes to production introduces subtle failure modes: retrieved context may miss crucial factual nuggets, generative models may hallucinate claims absent from source documents, or inline citations may point to irrelevant paragraphs. This engineering note explains how to construct automated evaluation pipelines using Context Recall@K, Natural Language Inference (NLI) claim decomposition, and byte-offset citation checks.

Problem Statement & Context

Deterministic unit assertions (e.g., assert(response.text === expected)) cannot test generative AI pipelines because natural language answers vary syntactically across runs. When developers modify vector chunking strategies (e.g., sliding window vs semantic boundaries) or switch embedding models, manual spot-checking fails to detect subtle regressions in accuracy. Teams require quantifiable, automated metrics running in CI/CD that generate statistically sound PASS/FAIL gates before merging code.

Architectural Concepts & Implementation

1. The RAG Evaluation Triad: Context Relevance, Groundedness, and Answer Relevance

High-fidelity evaluation decouples retrieval quality from generation fidelity. Context Recall@K assesses whether the top-K retrieved document chunks contain the ground-truth facts. Faithfulness (groundedness) measures whether every factual claim in the generated answer is strictly entailed by the retrieved chunks. Answer Relevance evaluates whether the answer directly addresses the user query without superfluous deviation.

Context Recall@K Evaluation Function
export interface RetrievalEvalResult {
  recallAtK: number;
  hitCount: number;
  totalGroundTruthKeys: number;
}

export function evaluateContextRecallAtK(
  retrievedChunks: Array<{ id: string; text: string }>,
  groundTruthKeywords: string[],
  k: number = 5
): RetrievalEvalResult {
  const topKText = retrievedChunks
    .slice(0, k)
    .map((c) => c.text.toLowerCase())
    .join(' ');

  let hitCount = 0;
  for (const keyword of groundTruthKeywords) {
    if (topKText.includes(keyword.toLowerCase())) {
      hitCount++;
    }
  }

  const recallAtK = groundTruthKeywords.length > 0 ? hitCount / groundTruthKeywords.length : 1.0;

  return {
    recallAtK: Number(recallAtK.toFixed(3)),
    hitCount,
    totalGroundTruthKeys: groundTruthKeywords.length,
  };
}

2. Atomic Claim Decomposition for NLI Groundedness

Rather than querying a large model with a subjective prompt ('Is this answer accurate?'), the system segments the candidate answer into atomic factual claims. Each claim is evaluated against the retrieved context as a premise-hypothesis pair using Natural Language Inference (NLI). The overall Faithfulness score equals the fraction of claims entailed by the context.

Atomic Claim Entailment Scoring
export interface FaithfulnessReport {
  faithfulnessScore: number;
  entailedClaimsCount: number;
  hallucinatedClaims: string[];
}

export function computeFaithfulnessScore(
  atomicClaims: string[],
  retrievedContext: string
): FaithfulnessReport {
  const normalizedContext = retrievedContext.toLowerCase();
  const hallucinated: string[] = [];
  let entailed = 0;

  for (const claim of atomicClaims) {
    const tokens = claim
      .toLowerCase()
      .replace(/[^a-z0-9\s]/g, '')
      .split(/\s+/)
      .filter((t) => t.length > 3);

    const matches = tokens.filter((t) => normalizedContext.includes(t));
    const coverage = tokens.length > 0 ? matches.length / tokens.length : 0;

    // Minimum 75% entity and keyword overlap required for textual entailment
    if (coverage >= 0.75) {
      entailed++;
    } else {
      hallucinated.push(claim);
    }
  }

  const faithfulnessScore = atomicClaims.length > 0 ? entailed / atomicClaims.length : 1.0;

  return {
    faithfulnessScore: Number(faithfulnessScore.toFixed(3)),
    entailedClaimsCount: entailed,
    hallucinatedClaims: hallucinated,
  };
}

3. Automated Citation Verification and Source Paragraph Alignment

Generative models frequently append citation markers (e.g., [1], [2]) that point to irrelevant paragraphs. In production, citations should be anchored to specific chunk UUIDs with byte-offset ranges, allowing the automated gate to verify that the cited chunk actually contains the claim in question.

Common Pitfalls & Trade-offs

  • !Trade-off: Comprehensive NLI checking increases evaluation runtime. Running 50 QA triples with 5 claims each requires 250 evaluation checks. Run full evaluation suites in asynchronous CI workflows rather than synchronously on user inference requests.
  • !Pitfall: Chunk size mismatch. Splitting documents into tiny chunks (128 tokens) improves vector similarity scores but deprives the generator model of essential context, causing groundedness drops.
  • !Pitfall: Ignoring keyword exact matches. Relying solely on dense embeddings misses exact SKU numbers, proper names, and code tokens. Combine dense vector search with sparse BM25 retrieval.

Production Verification Checklist

  • Curate a golden test set containing at least 50 representative domain queries with verified source documents.
  • Benchmark Context Recall@K across multiple K values (K=3, 5, 10) before deploying vector index changes.
  • Integrate an automated CI gate requiring Faithfulness Score >= 0.85 on all golden test suites.
  • Verify that all generated citations map directly to valid, retrievable chunk IDs.
  • Log ungrounded queries to a review queue to expand future golden evaluation datasets.
Back to all engineering notes