Forward Deployed EngineeringAI EngineeringRAG Evaluation
How would you evaluate a RAG system before letting a customer launch it?
Question 18 of 73 · Updated
On this page
- Interview-ready answer
- 1. Establish what success means with the customer
- 2. Build a golden evaluation dataset
- 3. Evaluate every stage independently
- INGESTION AND INDEXING
- RETRIEVAL AND RERANKING
- GENERATION AND VALIDATION
- END-TO-END CUSTOMER WORKFLOW
- 4. Retrieval metrics
- 5. Generation and business-quality metrics
- 6. Tested Python examples
- Retrieval metrics for a single case
- Coverage and accuracy among answered cases
- 7. Human evaluation and LLM-as-a-judge
- 8. Debugging with controlled experiments
- 9. Security, privacy and reliability testing
- 10. Operational and performance evaluation
- 11. Customer acceptance criteria and launch gates
- 12. Pilot and staged rollout
- 13. Practical FDE scenario
- Engineering trade-offs
- Likely interviewer follow-ups
Interview-ready answer#
I would not approve a RAG system for launch simply because it produces convincing answers in a demo. I would evaluate whether it solves the customer's real tasks accurately, grounds its claims in applicable authorized evidence, behaves safely when information is missing, and meets production latency, cost and reliability requirements.
First, I would agree with the customer on the intended workflows, failure severity and measurable acceptance criteria. Then I would create a representative, versioned evaluation dataset with expected answers, supporting evidence, user permissions and unanswerable cases. I would evaluate retrieval and generation separately as well as end-to-end: evidence recall and ranking, answer correctness and completeness, claim-level groundedness, citation validity and appropriate abstention.
I would combine deterministic checks, calibrated automated judges and domain-expert review, then test security, freshness, load, failure recovery and operational monitoring. Finally, I would run a controlled pilot, compare against the existing workflow, and require explicit sign-off on agreed launch gates. If a critical security or reliability gate fails, I would block or narrow the launch rather than hide the failure behind a high average score.
1. Establish what success means with the customer#
Before selecting metrics, identify the people using the system, the decisions they make with it, the authoritative data sources, and the consequences of a wrong answer. A customer support assistant suggesting an article to a human operator and an assistant communicating a binding eligibility determination have different risk profiles.
Agree on:
- Scope: supported intents, languages, document sources, tenants and user roles.
- Ground truth: which sources are authoritative, their effective dates, and who resolves conflicts.
- Quality: required factual accuracy, evidence coverage, answer completeness and abstention behavior.
- Operations: expected traffic, latency targets, freshness requirements, availability and cost per completed task.
- Risk: unacceptable failures, escalation paths, accountable owners and release-blocking criteria.
For example, in a policy assistant, a wrong policy exception or unauthorized disclosure may be more serious than an incomplete explanation of a low-risk internal procedure. Do not average those failures into a single score that conceals their consequences.
2. Build a golden evaluation dataset#
A golden dataset is a curated, versioned collection of test cases with trusted reference judgments. It should reflect actual customer needs, not only questions generated from easy passages.
Each case can include:
| Field | Purpose |
|---|---|
| Case ID and intent | Reproducibility and grouping |
| Question and relevant history | Realistic user input |
| User identity and permission scope | Authorization testing |
| Corpus snapshot and effective date | Stable evaluation against the right source version |
| Expected answer or rubric | Assess correctness without requiring identical wording |
| Required evidence spans | Evaluate retrieval and citation support |
| Answerability and expected behavior | Distinguish answer, clarify, abstain or escalate |
| Severity and slice labels | Prioritize failures and analyze groups |
Source test questions from approved historical support tickets, interviews with customer domain experts, product workflows and carefully reviewed synthetic edge cases. Remove or protect sensitive data and keep test access limited.
Include common questions, rare but high-impact cases, paraphrases, exact identifiers, multilingual inputs, tables, multi-document reasoning, policy exceptions, outdated sources, conflicting documents, missing information and adversarial inputs. Annotate required evidence using stable source IDs and spans rather than a particular chunking configuration.
Separate development and held-out evaluation sets. Prevent leakage through duplicate questions, related document families or repeated optimization against the final test set. Keep a separate challenge set for discovered regressions. If oversampling rare failures, report slice metrics and distinguish the evaluation distribution from estimated production prevalence.
3. Evaluate every stage independently#
INGESTION AND INDEXING#
Check corpus completeness, parsing quality, table/header preservation, duplicate entries, embedding compatibility, source versions, permission metadata and synchronization lag. Test edits, deletions and access revocation. An answer cannot reliably cite a document that was never indexed correctly.
RETRIEVAL AND RERANKING#
Measure whether required authorized evidence is found in the candidate pool, survives reranking, and fits into the final context. Track performance before and after each stage.
GENERATION AND VALIDATION#
Evaluate whether the model answers the actual question, uses correct evidence, avoids unsupported assertions, provides useful citations and takes the expected action when information is insufficient.
END-TO-END CUSTOMER WORKFLOW#
Measure task completion, human intervention, latency, cost, reliability and business outcomes against the existing workflow. Good retrieval and generation scores are necessary diagnostic signals, but they do not establish business value on their own.
4. Retrieval metrics#
Let G be the set of required evidence IDs for a question and Rk be the first k retrieved IDs.
| Metric | Definition and interpretation |
|---|---|
| Recall@k | Number of relevant items in Rk divided by the number of required relevant items; measures evidence coverage |
| Hit@k | Whether at least one relevant item appears in the top k; insufficient by itself for multi-evidence questions |
| All-evidence success | Whether every required evidence item appears in the selected results |
| MRR@k | Mean reciprocal rank of the first relevant result within k, with zero for a miss |
| nDCG@k | Normalized discounted cumulative gain; rewards highly relevant results appearing earlier |
| Final-context evidence recall | Fraction of required evidence present after deduplication, expansion and token-budget truncation |
For nDCG, use an explicitly defined relevance scale, gain function and discount convention consistently across experiments. For example, graded relevance can use gain 2^relevance − 1 and logarithmic rank discount, normalized against the ideal ranking. Cases without relevant evidence need a separate evaluation policy rather than silently being scored as perfect retrieval.
Suppose a question requires evidence A, B and C. The first three retrieved results are A, X and B. Recall@3 is 2/3, reciprocal rank is 1, but all-evidence success is false. A high first-hit ranking score therefore does not establish that sufficient evidence exists to answer a multi-part question.
Use stable source evidence units for comparisons when chunk boundaries change. Map retrieved chunks to annotated spans using a documented coverage rule and deduplicate evidence units before scoring. Compare both a fixed retrieval budget and a fixed final-context token budget; larger chunks otherwise receive an unfair context advantage.
5. Generation and business-quality metrics#
| Metric | Evaluation question |
|---|---|
| Factual correctness | Is the response correct against authoritative ground truth? |
| Groundedness / claim support | Are factual assertions supported by the applicable retrieved evidence? |
| Completeness | Does the answer include all required facts, qualifications and exceptions? |
| Citation precision | Do cited sources actually support the associated claims? |
| Citation coverage | Are important factual claims supported by appropriate citations? |
| Answer relevance | Does the response address the customer's question without irrelevant content? |
| Appropriate abstention | Does the system clarify, decline or escalate when the task cannot be answered safely? |
| Answer coverage | What proportion of requests receives an answer rather than abstention? |
| Accuracy among answered requests | What proportion of answered cases is correct? |
| Workflow success | Was the intended customer task completed correctly, including any required handoff? |
Factuality and groundedness are different: a statement copied from a superseded policy may be grounded in that policy yet incorrect for the current customer. A valid citation ID does not prove the referenced passage entails the claim.
Measure both answer-level and claim-level results where useful. A response containing no claims must not receive perfect groundedness by default. Evaluate correctness alongside coverage, and score clarification or escalation against the expected behavior rather than treating all abstentions as mistakes.
6. Tested Python examples#
These small implementations calculate metrics from already-labeled evaluation cases. They do not automatically identify relevant passages or determine factual truth.
Retrieval metrics for a single case#
PYTHONdef retrieval_metrics(ranked, gold, k): if k < 1 or len(set(ranked)) != len(ranked): raise ValueError('Positive k and unique ranked IDs required') if not gold: return None hits = [item in gold for item in ranked[:k]] return {'recall': sum(hits)/len(gold), 'rr': next((1/i for i, hit in enumerate(hits, 1) if hit), 0.0), 'all_evidence': all(item in ranked[:k] for item in gold)}
The function assumes ranked is a list of unique hashable evidence IDs, gold is a set of required IDs, and k is a positive integer. A case with no required evidence returns None; evaluate unanswerable questions separately. Average the per-case reciprocal rank values over the appropriate evaluation set to obtain MRR@k.
The sample above, with ranked = ['A', 'X', 'B'], gold = {'A', 'B', 'C'} and k = 3, returns recall = 0.6667 (rounded), rr = 1.0 and all_evidence = False.
Coverage and accuracy among answered cases#
PYTHONdef coverage_accuracy(outcomes): if any(x not in {'correct', 'incorrect', 'abstain'} for x in outcomes): raise ValueError('Unknown outcome') n = len(outcomes) answered = n - outcomes.count('abstain') return {'coverage': answered/n if n else None, 'answered_accuracy': outcomes.count('correct')/answered if answered else None}
For outcomes ['correct', 'correct', 'incorrect', 'abstain'], coverage is 75%, and accuracy among answered requests is approximately 66.67%. The metric does not determine whether the abstention was appropriate; compare that decision with the expected case behavior separately. Empty datasets or zero answered requests return None for undefined denominators.
Local verification: 15,044 Python test cases passed: 5,200 combinations of unique ranked lists, evidence sets and k values over a four-ID universe; 9,841 outcome sequences of lengths zero through eight; and three invalid-input checks. Expected values were compared against independent set-intersection, rank and counting calculations. The two explicit examples also ran successfully. These are metric implementation tests, not measurements of an actual RAG system.
7. Human evaluation and LLM-as-a-judge#
A practical evaluation strategy uses three layers.
Deterministic validation: Check source IDs, permissions, response schemas, exact values, dates, required fields, arithmetic and transaction receipts wherever a trustworthy reference is available.
Automated semantic evaluation: Use a calibrated judge to assess answer correctness, completeness and whether individual claims are supported by supplied passages. Give the judge an explicit rubric, relevant evidence and a structured output format. Treat retrieved content as untrusted data, including when it is sent to an evaluator.
Human domain review: Have qualified reviewers resolve ambiguous claims, evaluate business applicability and adjudicate high-risk failures. Define a rubric with examples, double-label a representative subset and examine agreement. Report the judge's agreement and false-pass rate against human labels, especially on critical cases.
LLM judges may prefer fluent answers, longer responses, particular answer positions or outputs from familiar model families. They can overlook unsupported claims, misread evidence, or be influenced by prompt injection. A stronger judge is not automatically a reliable verifier.
Calibrate judges against a human-reviewed set, blind model identity where feasible, randomize answer order in pairwise evaluation, version judge prompts and models, and manually inspect disagreements. Avoid using one judge score as the sole launch gate. Protect confidential customer data when selecting any external evaluation service.
8. Debugging with controlled experiments#
When a case fails, isolate the earliest stage responsible instead of changing multiple parameters at once.
- Confirm that the correct document exists, is current and is authorized for the test identity.
- Inspect parsing output and the indexed evidence.
- Inspect retrieved candidates before and after reranking.
- Inspect the actual context delivered to the generator, including truncation and source scope.
- Run a gold-context experiment using the known correct evidence with the same generator.
- Compare generated claims and citations with the authoritative answer; inspect validation and abstention decisions.
If gold-context generation improves substantially, upstream evidence selection or assembly is a likely bottleneck. If the model still fails, investigate instructions, model capability, evidence ambiguity and label quality. This is a diagnostic experiment, not proof that a single component is the only cause.
Version the corpus, splitter, embedding model, retrieval configuration, generator, prompt, judge and test suite. Compare alternatives on the same cases and report paired differences, sample sizes and uncertainty. For example, bootstrap paired per-question metric differences using an appropriate sampling unit if cases are correlated by customer or document.
9. Security, privacy and reliability testing#
Security is a release requirement, not a numerical quality bonus. Test in an authorized non-production environment with synthetic restricted records and representative identities.
| Test area | Expected behavior |
|---|---|
| Tenant isolation | No cross-tenant records appear in retrieval, expanded context, citations or responses |
| Document permissions | Restricted documents remain inaccessible even through parent expansion, search filters or caches |
| Permission revocation and deletion | Revoked or deleted evidence stops being served within the agreed policy window |
| Prompt injection in retrieved documents | Embedded instructions cannot override authorization, application policy or tool controls |
| Sensitive information | Logs, traces, judge inputs and exports follow customer privacy and retention requirements |
| Tool and action validation | Any actions are authorized, arguments validated, and success confirmed from the actual system |
| Service and dependency failures | Timeouts, unavailable indexes and provider errors cause bounded retry or controlled fallback, not invented answers |
Use both negative and positive authorization tests: an unauthorized identity must not retrieve restricted evidence, and an authorized identity should still be able to complete legitimate tasks. Inspect intermediate retrieval and cache behavior, not only the final text. Critical findings need remediation and re-testing.
No observed security failure in a finite test suite is not proof that the system has no vulnerabilities. Combine testing with access-control design review, threat modeling and appropriate independent security assessment.
10. Operational and performance evaluation#
Benchmark with realistic prompt sizes, document distributions, query mixes and concurrency. Include cold and warm cache behavior, expected peak traffic, large documents and dependency failures.
Measure end-to-end p50, p95 and p99 latency, stage-specific latency, time to first token where streaming is relevant, throughput, timeout/error rates, index freshness, token consumption and cost per successful customer task. Tail latency requires a sufficiently large sample; report sample size and workload conditions.
Test graceful degradation: if reranking is unavailable, a fallback should only proceed if its quality and security behavior meets the approved policy. If evidence retrieval fails, the model should not fabricate a grounded response. Define monitoring, escalation, recovery and rollback responsibilities.
11. Customer acceptance criteria and launch gates#
The following is an illustrative gate matrix for a low-to-moderate-risk internal policy assistant. Thresholds must be negotiated with the customer and justified by task risk, baseline performance and sample size; they are not universal industry standards.
| Gate | Illustrative requirement |
|---|---|
| Required-evidence retrieval | At least 95% mean evidence Recall@10 on answerable held-out cases |
| End-to-end correctness | At least 90% correct among answered cases, with at least 85% answer coverage on answerable cases |
| Citation support | At least 95% of evaluated claim-citation links supported by applicable evidence |
| Unanswerable requests | At least 95% appropriate clarification, abstention or escalation |
| Critical security | No known unresolved release-blocking findings; no unauthorized disclosure in the agreed test suite |
| Critical factual failures | No observed critical false answers in the agreed high-risk regression suite; explicit review of remaining risk |
| Latency and cost | p95 end-to-end latency and cost per correctly completed task within agreed workload-specific budgets |
| Operations | Monitoring, support ownership, fallback and rollback tested; customer sign-off recorded |
Report numerator, denominator, sample size, confidence or uncertainty, and important slices for each statistical gate. A small test set cannot establish a very low failure rate. For example, under independent Bernoulli trials, observing zero failures in 100 cases gives a one-sided 95% upper bound of approximately 2.95%, not zero. Real test cases may be correlated, and the test distribution may not represent production.
A passing average must not override critical security findings or unacceptable failures in a high-risk slice. Predefine which gates are mandatory and how any approved scope restrictions or exceptions are documented.
12. Pilot and staged rollout#
Offline evaluation — Run the versioned test suite, compare with the existing system, and resolve release-blocking issues.
Shadow or supervised pilot — Where authorized and appropriate, evaluate the system without exposing unreviewed outputs to the customer workflow. Gather domain-expert feedback and inspect real failure patterns.
Restricted launch — Enable approved users and intents, retain human escalation, and monitor quality, operational health and security signals.
Expansion — Increase scope only when pilot results satisfy the agreed criteria. Use regression tests for model, prompt, retrieval and source changes.
A rollback should restore a known compatible configuration and preserve current permissions and source lifecycle requirements. Rolling back an index must not re-expose deleted or revoked material. The customer should know who owns incidents, how users report errors, and when the system will be disabled or restricted.
13. Practical FDE scenario#
A customer wants to launch an internal travel-policy assistant. The existing demo answers general travel questions well, but the customer has separate contractor policies, regional rules and effective dates.
I would work with HR and compliance owners to label realistic questions, including ambiguous employee status, superseded rules and restricted policies. I would evaluate evidence recall across the applicable policy versions, check whether citations support each eligibility claim, and test the same questions under different authorized roles.
Suppose a hypothetical pilot returns strong overall scores but fails several contractor-exception cases. I would not approve unrestricted launch. I would inspect whether those exceptions were missing from the index or final context, correct the relevant stage, add the failures to the regression suite and re-run the held-out evaluation. If necessary, restrict the pilot to approved employee workflows with a clear escalation path until contractor cases meet the gate.
This is an illustrative engineering scenario, not a measured customer deployment result.
Engineering trade-offs#
- More retrieval candidates may improve evidence recall but increase noise, reranking work and prompt cost.
- Larger evaluation suites improve coverage but require annotation and maintenance; use risk-based sampling and retain a stable holdout.
- Automated judges enable frequent evaluation but require calibration and human oversight.
- Strict abstention may reduce unsupported answers at the expense of usefulness; evaluate accuracy and coverage jointly.
- Additional verification increases latency; prioritize deterministic checks and risk-based review.
- A stronger model cannot fix stale documents, broken permissions or missing evidence. Measure the actual failing component before increasing serving cost.
Likely interviewer follow-ups#
Would a high retrieval Recall@k be enough to launch? No. Required evidence may not reach the final prompt, and the generator may misinterpret correct evidence. Measure final-context coverage, answer quality and end-to-end safety.
How do you evaluate without a labeled dataset? Begin with a small domain-expert-reviewed set, use customer workflows to expand it, and treat uncalibrated synthetic or automated labels as provisional. Do not use a lack of labels as justification for unsupported launch guarantees.
How do you decide which threshold to use? Agree with the customer on task risk, baseline, expected workload, business value and evidence strength. Use separate gates for critical failures and important user slices.
What if the model judge and domain expert disagree? Inspect the rubric, evidence and source applicability, adjudicate the case and use disagreements to improve judge calibration.
What happens after launch? Monitor quality and reliability, collect approved feedback, investigate incidents, add regression cases and re-evaluate changes before expanding scope.
References
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.OWASP GenAI Security Project (not live-verified)genai.owasp.org
Related questions
Explore other topics:AI AgentsAI System DesignLarge Language Models