Forward Deployed EngineeringAI EngineeringReliability and Evaluation
Give me three concrete hallucination mitigations, and the cost of each.
Question 46 of 73 · Updated
On this page
- Interview-ready answer
- 1. Define the failure precisely
- 2. Mitigation one: evidence-grounded generation
- Implementation
- Costs and limitations
- 3. Mitigation two: independently verify consequential claims
- Implementation
- Costs and limitations
- 4. Mitigation three: calibrated abstention and escalation
- Implementation
- Costs and limitations
- 5. How the three controls fit together
- 6. Tested Python: verify structured facts and gate answers
- Local execution and verification
- 7. Quantify the cost of each layer
- 8. Choose controls by business risk
- 9. Realistic hypothetical customer scenarios
- 10. Evaluation, monitoring and deployment
- Likely interviewer follow-ups
- Interview takeaway
Interview-ready answer#
I would use three complementary controls, each addressing a different failure mode:
- Evidence-grounded generation: retrieve current, authorized facts from trusted documents or live systems, and require the model to answer from that evidence with traceable citations. The cost is retrieval infrastructure, indexing and freshness maintenance, additional input tokens, and search/ranking latency. Retrieval can also miss the correct evidence.
- Independent claim verification: extract the important factual claims from the draft and verify them against authoritative sources, deterministic calculations or a separately evaluated verifier before release. The cost is additional compute or model calls, source lookups, verification latency and handling false positives and false negatives. A second model can make correlated mistakes, so another model's agreement is not proof.
- Calibrated abstention and escalation: refuse to assert unsupported facts, ask for missing information, or route uncertain cases to a human. Choose the decision threshold against representative labeled evaluations and the cost of wrong answers. The cost is reduced automated coverage, possible extra user turns, human review and operational escalation capacity.
For an FDE, the best solution is usually a combination: ground the generation, check consequential claims, and abstain when the evidence or verification is inadequate. Measure factual error among delivered answers, task completion, coverage, p95 latency and cost per successful task. I would not optimize hallucination rate alone because a system that refuses every question can have a low error rate while providing no value.
1. Define the failure precisely#
A hallucination in this context is a generated factual assertion that is false or not adequately supported by the evidence required for the task. These are related but distinct failure categories: a true statement can lack evidence in the supplied context, while a statement supported by an outdated or erroneous source can still be wrong in the real world.
For an enterprise document assistant, distinguish at least the following during evaluation:
| Failure | Example |
|---|---|
| Unsupported claim | Invents a policy exception that is absent from the applicable source |
| Contradicted claim | Says the notice period is 14 days when the current agreement says 30 |
| Invalid citation | Cites an unrelated passage or nonexistent document |
| Wrong applicability | Uses a correct policy for the wrong jurisdiction, customer tier or date |
| Calculation or execution error | States a computed total or completed action that does not match the authoritative result |
| Unjustified certainty | Gives a definite answer despite incomplete or contradictory evidence |
These examples are hypothetical. The relevant definition of correctness must come from the customer's task and source-of-truth contract. Do not equate stylistic fluency, confidence or a valid JSON response with factual accuracy.
2. Mitigation one: evidence-grounded generation#
Implementation#
Use an instruct model with current, authorized evidence supplied through direct context, retrieval-augmented generation (RAG), or an approved live data tool. Identify the authoritative source and applicable revision before generation. Retrieve relevant facts, assemble a bounded context with stable source identifiers, and ask the model to distinguish supported facts from uncertain inferences.
For facts such as a current order status, a live authorized API is generally more suitable than retrieving an old support transcript. For a policy question, retrieve the relevant section, definitions and exceptions rather than simply sending the highest-scoring isolated sentence.
A useful generation contract is: answer the question using the provided applicable sources; cite the evidence for factual assertions; acknowledge conflicts or missing information; do not invent source IDs. This instruction improves the interface but does not enforce truth by itself. Validate the emitted citations against actual source records and verify their relevance.
Costs and limitations#
- Infrastructure: ingestion, indexing, embedding generation where used, ranking, metadata, synchronization, permission enforcement, storage and monitoring.
- Compute: search and ranking work, plus input tokens consumed by evidence and source metadata. Long contexts can increase prefill and memory requirements.
- Latency: retrieval and reranking may add stages to the critical path, although supplying focused evidence can reduce generation work compared with very long prompts.
- Accuracy trade-off: missing or irrelevant retrieval, stale documents, incorrect extraction, conflicting revisions and prompt injection can all undermine grounding.
For a tiny stable corpus, supplying approved content directly may avoid most index infrastructure. For a large, frequently changing corpus, retrieval can reduce the need to send all documents and support easier knowledge updates. The choice is workload-dependent.
3. Mitigation two: independently verify consequential claims#
Implementation#
Treat generated text as a candidate, not a committed result. Extract explicit factual assertions, especially numbers, dates, eligibility rules, citations, computed amounts and claims about executed actions. Verify against authoritative evidence using a method appropriate to the claim.
| Claim type | Suitable verification |
|---|---|
| Customer order status | Authorized lookup against the current order system |
| Policy threshold or deadline | Exact applicable structured record or source passage |
| Arithmetic | Independent deterministic calculation with correct units |
| Citation | Confirm the identifier resolves to an authorized source and the cited passage supports the assertion |
| Complex narrative claim | Separate evidence-grounded review, with expert review when necessary |
| Tool action completed | Authoritative operation receipt or reconciled service state |
A verifier should distinguish supported, contradicted, conflicting and insufficient-evidence claims. Reject or repair unsupported assertions, and verify the revised answer again. Bound retry attempts; repeated regeneration is not an evidence source.
Independence means more than using a different prompt. Prefer an authoritative data lookup or deterministic check when one exists. If a model-based verifier is needed, use evidence independent of the draft's unsupported reasoning and evaluate its errors separately. A second invocation of the same model may repeat the same mistake, and a different model can share training biases or receive the same bad source.
Claim extraction also has a recall problem: a verifier can check every extracted claim yet miss a claim that the extractor failed to identify. Where feasible, constrain the output to explicit fields and render user-visible statements from verified records. For unrestricted prose, check whether all material claims are represented and preserve a review path for uncertain content.
Costs and limitations#
- Compute and money: additional source/API lookups, claim extraction, entailment or verifier model calls, validation, and bounded repair.
- Latency: synchronous verification adds critical-path work. Independent checks can sometimes run concurrently, but shared service limits and the slowest relevant check affect tail latency.
- Engineering: implement typed contracts, claim-to-evidence mapping, unit and version checks, timeout handling and repair/rejection policies.
- Accuracy trade-off: overly strict verification may reject a correct paraphrase; weak verification may approve a fluent unsupported claim. Exact matching is valuable for structured facts but insufficient for general semantic entailment.
Do not claim that chain-of-thought, a confidence statement, repeated answers, or model agreement constitute independent verification. Use the strongest available evidence appropriate to the task.
4. Mitigation three: calibrated abstention and escalation#
Implementation#
A system should not be forced to answer every question. Design explicit outcomes such as verified answer, supported partial answer, clarification required, insufficient evidence, conflicting evidence, or human review required.
Choose the acceptance policy using a representative labeled development set. Features might include whether required evidence is present, whether authoritative checks passed, retrieval coverage, calibrated verifier scores and task-specific risk. Do not use a raw cosine score or the model's self-reported certainty as a probability of correctness without calibration evidence.
Define coverage as accepted answers divided by all evaluated requests. Define selective risk as incorrect accepted answers divided by accepted answers. With zero accepted answers, selective risk is undefined, not evidence of perfect reliability.
A hypothetical evaluation of 1,000 requests might show:
| Threshold policy | Accepted | Incorrect among accepted | Coverage | Selective risk |
|---|---|---|---|---|
| More permissive | 900 | 36 | 90% | 4.0% |
| Intermediate | 750 | 15 | 75% | 2.0% |
| Stricter | 500 | 5 | 50% | 1.0% |
These invented counts demonstrate the decision trade-off; real measured risk need not decrease monotonically with threshold. Evaluate uncertainty and rare high-impact failures, and choose the threshold on development data before measuring the selected policy on a held-out test set. Monitor changes in domain, traffic, model and source quality that can invalidate calibration.
For sensitive or consequential decisions, require the applicable deterministic controls or human approval regardless of a high score. A model score must never override an authorization failure or required human approval.
Costs and limitations#
- Coverage: more legitimate questions may remain unanswered, with reduced automation and possible customer frustration.
- Operational work: human review queues, training, service-level commitments and escalation ownership.
- Latency: extra clarification turns or review wait times, which should be included in customer-facing task latency.
- Calibration: labeling representative examples, tuning thresholds, drift monitoring and recurring evaluation.
Abstention is useful only if it has a meaningful next step, such as requesting the missing document, explaining the evidence conflict, or escalating to an authorized reviewer. Avoid generating a misleading answer merely to keep automation coverage high.
5. How the three controls fit together#
The repair path has an explicit retry and time budget. Verification errors, missing evidence and failed authorization are not permission to bypass the gate. A partial answer may be returned if its verified claims remain useful and the response explicitly states what cannot be established.
This architecture is not a guarantee of zero hallucinations. It provides several independently testable boundaries and an explicit response when evidence is insufficient. For a low-risk task, a lighter path may be adequate; for a consequential task, stronger evidence and review may be mandatory.
6. Tested Python: verify structured facts and gate answers#
The following dependency-free example deliberately uses a narrow structured contract rather than claiming to verify arbitrary natural-language statements. The facts are synthetic typed records already retrieved from an authorized, applicable source. In a real application, the upstream system must enforce tenant scope, permissions, source authority, revision and effective-date rules.
PYTHONfrom fractions import Fraction def check_claim(claim, facts): # Facts: authorized, applicable (field, value, source_id) records. field, value = claim matches = [(v, source) for f, v, source in facts if f == field] if not matches: return 'unknown', () if len({v for v, _ in matches}) != 1: return 'conflict', () if matches[0][0] != value: return 'contradicted', () return 'supported', tuple(sorted({source for _, source in matches})) def gate(verdicts, score, threshold): if not 0 <= score <= 1 or not 0 <= threshold <= 1: raise ValueError('invalid score or threshold') return bool(verdicts) and all(v == 'supported' for v in verdicts) and score >= threshold def risk_coverage(rows, threshold): if not rows: raise ValueError('empty evaluation set') accepted = [correct for verdicts, score, correct in rows if gate(verdicts, score, threshold)] return (Fraction(len(accepted), len(rows)), Fraction(accepted.count(False), len(accepted)) if accepted else None)
The check compares canonical field values with the relevant records. Conflicting applicable values produce a conflict outcome even if one source matches the proposed answer. Unknown fields are not treated as false or silently accepted. The gate requires a nonempty collection of verified claims and a score at least equal to the selected threshold. Its input score is assumed to be produced by a separately validated scoring pipeline; this function does not calibrate a model.
Worked hypothetical example:
PYTHONfacts = [('notice_days', 30, 'policy-v3')] claim = ('notice_days', 14) verdict, sources = check_claim(claim, facts) # verdict: 'contradicted'; sources: () # gate((verdict,), Fraction(9, 10), Fraction(4, 5)) is False. rows = [ (('supported',), Fraction(9, 10), True), (('supported',), Fraction(3, 5), False), (('unknown',), Fraction(9, 10), False), ] # risk_coverage(rows, Fraction(4, 5)) == (Fraction(1, 3), Fraction(0))
The example assumes hashable canonical field values, sortable string source IDs, already validated field types, boolean correctness labels, and reusable verdict sequences. Production code should validate schemas and units, bind evidence to source versions, use authoritative lookups, and check access again where required. Exact equality does not establish semantic entailment for free-form text. Never declare a whole narrative verified if only a subset of its claims was checked.
For n input fact records, the implementation scans O(n) records and uses O(n) worst-case temporary space; sorting the unique supporting source identifiers adds O(s log s) work for s sources. Indexed field lookups can improve the repeated-query path. The gate is linear in the number of claims, and evaluation is linear in the total number of verdicts across the rows, with additional accepted-label storage.
Local execution and verification#
Python 3.13.5 executed the exact three helpers on synthetic inputs:
- 2,304 claim checks: all 256 subsets of eight possible facts, with nine candidate field/value combinations per subset.
- 2,125 gate checks: every verdict sequence of length zero through three over four verdict types, with 25 score/threshold combinations each.
- 40,000 risk–coverage checks: all ordered three-row evaluation sets over twenty possible synthetic rows, at five thresholds.
- Three invalid-input rejection checks.
All 44,432 checks passed against independently constructed expected outcomes. The tests verify structured comparisons, the acceptance rule and metric arithmetic; they do not establish natural-language claim extraction, calibrated model confidence, retrieval quality, or live deployment safety.
7. Quantify the cost of each layer#
Suppose an illustrative support assistant has 10,000 monthly requests. Assume the underlying generator costs $0.01 per request, retrieval adds $0.004 per request plus $100/month of fixed service cost, verification adds $0.008 per request, and 10% of requests are escalated for three minutes of human review at an illustrative fully loaded rate of $30/hour.
| Item | Assumed incremental monthly cost |
|---|---|
| Baseline generator | $100 |
| Evidence grounding: retrieval and fixed service | $140 |
| Claim verification | $80 |
| Abstention: 1,000 human reviews at $1.50 each | $1,500 |
| Combined illustrative total | $1,820 |
This simple accounting assumes every request runs retrieval and verification and that every escalated case receives exactly one review. It excludes labeling, engineering labor, storage beyond the fixed estimate, retries, provider-specific pricing, taxes and other infrastructure. Actual cascades may skip generation or verification on insufficient evidence, so measure the path frequencies rather than treating this table as a cost forecast.
The main insight is that an extra model call is not necessarily the largest cost. Review labor, incomplete automation, and erroneous business decisions can dominate total economics.
Similarly, suppose a request has hypothetical stage times of 70 ms for retrieval, 350 ms for generation, 180 ms for verification and 20 ms for response handling. If these stages run serially, the illustrative automated path takes 620 ms. These are assumed single-request durations, not p95 measurements. Adding individual p95 values does not produce an end-to-end p95. Measure actual request latency including queueing, retries, parallel stages and review waits.
8. Choose controls by business risk#
Avoid unnecessary verification of low-consequence creative text when no factual guarantee was requested. Conversely, when an answer can cause financial loss, legal exposure or unauthorized operations, use explicit business rules, authoritative state and appropriately qualified human review.
Choose the control based on observed failure types. If the generator performs well with correct evidence but often retrieves the wrong document, improve retrieval rather than adding more verifier calls. If a numerical field is repeatedly invented, deterministic checking or rendering from structured data may be more reliable than an additional free-text judge.
9. Realistic hypothetical customer scenarios#
Employee policy assistant. A model answers a leave question from an obsolete policy. Use revision-aware authorized retrieval, verify the leave entitlement and relevant exception against the effective policy, and escalate if regional rules conflict. The costs are source maintenance, verification work and occasional HR review.
Billing support assistant. A user asks whether a refund was processed. The assistant should read authorized transaction status from the billing service, verify the claim against a transaction receipt or authoritative state, and avoid saying a refund succeeded when a timeout leaves its outcome unknown. The costs include service calls, reconciliation and review latency; inventing a successful refund may be much more expensive.
Contract review workflow. The model summarizes a contract obligation but omits an amendment. Preserve the applicable clause and amendment, verify critical claims with the source evidence and require qualified human review where the task's risk demands it. A plausible summary is not a substitute for complete contractual analysis.
These are fictional examples, not reported customer outcomes.
10. Evaluation, monitoring and deployment#
Create a task-specific evaluation set with supported, contradicted, unanswerable, stale, ambiguous and access-restricted cases. Include paraphrases, negation, quantities, date applicability, cross-document exceptions, multilingual queries when relevant, and adversarial text embedded in retrieved documents.
Measure each layer and the end-to-end system:
| Metric | What to learn |
|---|---|
| Required-evidence recall and source freshness | Whether generation sees applicable facts |
| Claim-level support and citation correctness | Whether delivered assertions have actual evidence |
| Verifier false acceptance and false rejection | Whether checks fail open or reject valid answers |
| Claim extraction recall | Whether all material assertions are actually checked |
| Selective risk and coverage | Whether abstention improves the accepted-answer trade-off |
| Task completion and escalation wait | Whether the customer receives useful outcomes |
| End-to-end latency and cost per successful task | Whether the safeguards fit the service objectives |
Report absolute error counts and denominators. An apparently improved average can hide a rare serious failure or a poor subgroup. Estimate uncertainty and obtain sufficient representative examples for high-risk categories; a small test with zero observed failures cannot demonstrate zero underlying risk.
Use an ablation study to compare grounding alone, grounding plus verification, and the complete acceptance policy. Evaluate the selected configuration on a separate held-out set. Measure real operational costs and obtain agreement on the acceptable trade-offs before expanding rollout.
Version the model, prompts, retrieval index, source revisions, claim schemas, verifier and gate policy. Monitor drift, human overrides and newly observed error types. Protect customer data in logs and evaluation records; permission checks must apply to the verifier and escalation queue as well as the generator. Do not let retrieved content instruct the application to disable controls.
Likely interviewer follow-ups#
Why isn't temperature zero enough? It can reduce sampling variability, but a deterministic decoding path can still produce an incorrect answer from a mistaken learned distribution or missing evidence.
Is a citation proof of correctness? No. The cited source must be real, authorized, applicable and actually support the claim. Even then, the source itself may be wrong or outdated.
Can a stronger LLM judge eliminate hallucinations? No. It can improve detection on some tasks, but may share biases, misunderstand sources or approve unsupported claims. Prefer deterministic or authoritative checks where possible.
How do you choose the abstention threshold? Use representative labeled development cases, the consequences of false acceptance versus false rejection, risk–coverage curves and an agreed operational capacity. Confirm the selected policy on held-out data.
What if abstention hurts the customer experience? Provide supported partial answers, clarification or an appropriate review route. Measure task completion and wait times as well as accuracy.
Which of the three would you implement first? For enterprise document QA, usually grounding with explicit insufficient-evidence behavior. Add independent verification based on material failure types, then calibrate the acceptance policy using measured results. The order can differ for deterministic or consequential workflows.
Interview takeaway#
Prevent unsupported generation with current evidence, detect incorrect claims with independent checks, and contain residual uncertainty through calibrated abstention. The costs are respectively retrieval and context overhead, verification computation and latency, and lower coverage or human-review work. The FDE's job is to find the configuration that meets the customer's accuracy, safety, latency and cost requirements—not to promise that any single mitigation eliminates hallucinations.
References
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.Python fractions documentation (not live-verified)docs.python.org
Related questions
Explore other topics:AI AgentsAI System DesignLarge Language Models