Building a Safety Layer for Medical Text Generation
Machine LearningModel answerLast updated
Design a system to detect and prevent fabricated information in AI-generated clinical summaries, addressing severe class imbalance in the detection model.
Context
You're developing an automated system that generates summaries from medical documentation using a large language model. The system faces two critical challenges:
Challenge 1: Fabricated Information
The model sometimes generates content not present in the original documents—inventing medications, symptoms, or altering critical details.
Challenge 2: Detection at Scale
You need a classifier to identify problematic summaries, but fabrications appear in fewer than 1% of outputs, creating an extremely skewed dataset.
Your Task
Design a complete safety system addressing:
-
Prevention Architecture: Describe a retrieval-augmented approach that grounds generation in source documents. How would you structure prompts and implement verification to ensure every statement traces back to source material?
-
Imbalanced Classification: Explain your strategy for training a detector when positive cases represent less than 1% of data. Which techniques would you use for the imbalance? Which metrics matter most in this medical context, and why?
-
Cost-Benefit Reasoning: How would you balance computational expense (running verification checks) against safety risk (allowing errors through)? What factors would drive your decision on where to invest verification effort?
Clarifications to Consider
- Define what constitutes a "fabrication" in this context
- Consider the human review workflow
- Think about relative costs of different error types
Hints
Hint 1
Think about citation enforcement at generation time, not just post-hoc checking
Hint 2
In medical contexts, missing a dangerous error has vastly different consequences than creating a false alert
Hint 3
Consider stratifying verification intensity based on content risk rather than checking everything equally
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires layered defenses: preventing fabrications during generation, detecting them when they occur, and routing intelligently based on risk. Strong solutions recognize that perfect detection is impossible, so the architecture must degrade gracefully.
1. Prevention Through Grounded Generation
Core Pipeline
Build a retrieval-augmented system where every generated statement must link to source material:
-
Document Preparation: Break source documents into addressable segments (sentences or short paragraphs), each with a unique identifier like
[D2-P5](document 2, paragraph 5). -
Contextual Retrieval: Use hybrid search combining keyword matching (BM25) with semantic embedding similarity. Apply strict metadata filtering to retrieve only from the relevant patient's current encounter—never blend patients. Add a reranking layer to improve precision.
-
Constrained Generation: Structure the prompt to demand citations and forbid inference:
You summarize medical records using ONLY provided excerpts.
Format: {"statement": "...", "source_ids": ["D2-P5"]}
Rules:
- Every factual claim requires at least one source ID
- Preserve exact negations ("denies X" ≠ "has X")
- Never infer unstated information
- For missing data, write "Not documented"
Use temperature=0 and request structured JSON output for parseability.
-
Multi-Level Verification:
- Syntactic check: Flag any statement lacking citations
- Entity extraction: Use medical NER tools to extract drugs, diagnoses, and procedures from both summary and source. Any entity in the summary but absent from sources is a hard failure
- Semantic verification: Run a natural language inference model on (source_text, statement) pairs. Statements marked as "contradicted" or "neutral" get flagged
- Iterative refinement: Feed flagged statements back with instructions to revise or remove unsupported content (limit to 1-2 rounds)
Key Insight: Relying solely on the generator to verify itself is weak—the same model makes the same errors. Use a separate verification model or different architecture (cross-encoder vs. decoder-only).
2. Detection Under Extreme Imbalance
Data and Features
Classify at the statement level rather than summary level when possible—this increases positive examples and localizes errors. Useful signals include:
- NLI entailment/contradiction scores
- Semantic similarity between statement and cited source
- Entity overlap measures
- Generation confidence (token log probabilities, entropy)
- Cross-sample consistency (generate multiple times, flag disagreements)
- Citation validity flags
Addressing the 1% Base Rate
-
Cost-sensitive learning: Apply class weights inversely proportional to frequency (roughly 100:1 for negative:positive). Tune the exact ratio on validation data. Focal loss can also help by down-weighting easy negatives.
-
Synthetic positives: Generate realistic fabrications by programmatically corrupting good summaries—swap medications for similar ones, alter dosages, flip negations, insert plausible but unsupported symptoms. This creates hard negatives that stress-test the detector. Traditional oversampling (SMOTE) works for tabular features but produces nonsense for raw text—avoid or apply only to numeric feature vectors.
-
Targeted undersampling: Reduce the majority class for training efficiency, but always evaluate on a dataset reflecting true 1% prevalence. After training, recalibrate probability outputs using Platt scaling or isotonic regression on a held-out validation set.
-
Active learning: Route high-uncertainty cases to medical reviewers for labeling, progressively improving the detector on the hardest examples.
Metric Selection
In medical applications, missing a fabricated medication or flipped diagnosis carries enormous risk compared to triggering an unnecessary review. Therefore:
- Prioritize recall: Measure what fraction of actual fabrications you catch
- Monitor precision at fixed recall: If you set recall at 95%, what's your precision? Low precision (many false alarms) causes alert fatigue where reviewers stop taking flags seriously
- Use Precision-Recall AUC as your primary threshold-agnostic metric (ROC-AUC is misleadingly optimistic under severe imbalance)
- Report F-beta with beta=2 or 3 if you need a single number, emphasizing recall over precision
- Stratify by error type: Track performance separately for fabricated entities, wrong attributes (doses), and negation flips—these have different clinical severities
Threshold Selection
Choose based on cost: flag when P(fabrication) > cost_false_positive / (cost_false_positive + cost_false_negative). If a missed fabrication is 100× more costly than an unnecessary review, your threshold should be around 0.01.
3. Cost-Benefit Optimization
Frame the problem as minimizing:
Total Cost = Compute_verification + Labor_review × Flag_volume + Harm_cost × Missed_fabrications
Tiered Verification Strategy
Rather than running expensive checks on everything, cascade from cheap to expensive:
| Stage | Check | Cost | Coverage |
|---|---|---|---|
| Fast screen | Citation presence + entity string matching | negligible | 100% |
| Lightweight model | Small NLI classifier | low | 100% |
| LLM judge | Large model verification or self-correction | high | 10-20% (uncertain cases) |
| Human review | Expert clinician | highest | flagged outputs only |
Risk-Based Routing
Apply stricter thresholds and mandatory deep verification for high-stakes content:
- Medications, dosages, and allergies (errors cause direct harm)
- New diagnoses or changes to existing conditions
- Procedural recommendations
Use lighter verification for lower-risk content like social history or administrative notes.
Example Economics
For 100,000 summaries daily where full LLM verification costs $0.01 per summary, checking everything costs $1,000/day. A tiered system might reduce this to $150/day while maintaining high recall on critical content. This is justified when the expected cost of even one missed dangerous fabrication exceeds the annual savings.
Production Monitoring
Track:
- Flag rate over time (watch for drift)
- Reviewer override rate (proxy for precision)
- Random audits of auto-approved summaries to estimate miss rate
- Stratified performance by note type and content risk level
Common Mistakes
- Reporting accuracy or standard ROC-AUC on imbalanced data (predicting "safe" for everything scores 99% accuracy)
- Claiming to "maximize recall" without addressing precision or alert fatigue
- Trusting the generator to reliably verify its own outputs
- Applying SMOTE or other interpolation methods directly to text data
- Evaluating on artificially rebalanced test sets, which distorts precision estimates
- Treating all fabrications equally when dosage errors and negation flips are far more dangerous than minor omissions
Summary
Effective medical AI safety combines prevention (citation-grounded generation), detection (class-imbalanced classification with recall focus), and intelligent resource allocation (risk-based verification cascades). The key insight is that no single component achieves perfect safety—the system must layer defenses and fail gracefully, with monitoring to catch what slips through.