Validate LLM Output
Verify LLM outputs against ground truth sources, enforce structured schemas, and implement human review thresholds — preventing hallucinated facts, fabricated citations, and incorrect decisions from propagating into production systems.
Why This Is Best Practice
Adopted by: OWASP Top 10 for LLM Applications 2025 LLM09 (Overreliance). NIST AI RMF 1.0 (2023) Measure 2.5 requires AI output monitoring and human review mechanisms. The EU AI Act (2024) Article 9 mandates human oversight for high-risk AI system outputs. Microsoft Azure AI Content Safety, AWS Bedrock Guardrails, and Google Vertex AI Evaluation all provide output validation tooling.
Status: Emerging — hallucination detection and output validation are active research areas; no single complete solution exists, and techniques are still rapidly improving.
Impact: A US federal attorney was sanctioned by a judge for submitting AI-generated legal briefs containing fabricated case citations (Mata v. Avianca, 2023). A medical AI system gave drug dosage recommendations that were factually incorrect due to hallucination. LLMs confidently generate plausible-sounding but false statistics, fake academic citations, and invented API parameters — all at a high confidence level that can mislead users and downstream systems.
Why best: User-level review for every output is the alternative — it's too slow for real-time applications and subject to automation bias (users trust AI outputs without scrutinizing them). Automated structural validation + confidence thresholds + selective human review provides scalable quality control.
Sources: OWASP LLM Top 10 2025 LLM09; Mata v. Avianca (2023); NIST AI RMF 1.0 Measure 2.5; EU AI Act Article 9
Steps
Use structured output with schema validation:
from pydantic import BaseModel, validator
from typing import Optional
class ProductRecommendation(BaseModel):
product_id: str # must reference a real product
reason: str
confidence: float # 0.0–1.0
@validator('product_id')
def product_must_exist(cls, v):
if not db.product_exists(v):
raise ValueError(f"LLM hallucinated product ID: {v}")
return v
@validator('confidence')
def confidence_in_range(cls, v):
if not 0.0 <= v <= 1.0:
raise ValueError("Confidence must be 0–1")
return v
response = openai.beta.chat.completions.parse(
model="gpt-4o",
messages=messages,
response_format=ProductRecommendation,
)
result = response.choices[0].message.parsed
# If product_id doesn't exist in DB, pydantic raises ValueError — handle it
Verify citations and references against source documents:
def verify_citations(llm_response: str, source_documents: list[str]) -> dict:
"""Check that claims in LLM response are grounded in source documents."""
# Extract claims from response
claims = extract_claims(llm_response)
verification_results = {}
for claim in claims:
# Check if claim is supported by any source document
supported = any(
is_semantically_similar(claim, chunk)
for doc in source_documents
for chunk in split_into_chunks(doc)
)
verification_results[claim] = 'supported' if supported else 'unverified'
unverified_count = sum(1 for v in verification_results.values() if v == 'unverified')
return {
'verified_fraction': 1 - unverified_count / max(len(claims), 1),
'claims': verification_results
}
Flag low-confidence outputs for human review:
CONFIDENCE_THRESHOLDS = {
'medical_advice': 0.95,
'legal_summary': 0.90,
'financial_analysis': 0.90,
'general_query': 0.70,
}
def route_for_review(output: dict, task_type: str) -> dict:
threshold = CONFIDENCE_THRESHOLDS.get(task_type, 0.80)
confidence = output.get('confidence', 0.0)
if confidence < threshold:
queue_for_human_review(output, task_type, reason='low_confidence')
return {
'status': 'pending_review',
'message': 'This response requires expert review before use.',
'estimated_review_time': '2 hours'
}
return output
Cross-validate with deterministic checks where possible:
def validate_llm_analysis(llm_output: dict, raw_data: dict) -> bool:
"""Re-check LLM's numerical claims against source data."""
# LLM said revenue grew 15% — verify against actual numbers
if 'revenue_growth' in llm_output:
actual_growth = (
(raw_data['revenue_2024'] - raw_data['revenue_2023'])
/ raw_data['revenue_2023']
)
llm_claimed = llm_output['revenue_growth']
if abs(actual_growth - llm_claimed) > 0.02: # 2% tolerance
logger.warning("LLM hallucinated revenue growth: claimed=%s actual=%s",
llm_claimed, actual_growth)
return False
return True
Set appropriate user expectations — surface uncertainty in the UI:
def format_response_with_confidence(response: dict) -> dict:
confidence = response.get('confidence', 0.0)
disclaimer = None
if confidence < 0.70:
disclaimer = "⚠️ This response has low confidence. Verify before acting on it."
elif confidence < 0.85:
disclaimer = "This response is AI-generated. Please verify important details."
return {
**response,
'disclaimer': disclaimer,
'sources_verified': response.get('sources_grounded', False),
}
Monitor output quality over time — hallucination rates drift with model updates:
def sample_for_quality_audit(response_id: str, sample_rate: float = 0.05):
"""Send a sample of responses for human quality review."""
if random.random() < sample_rate:
queue_for_quality_review(response_id)
Rules
- Never use LLM outputs as authoritative sources for safety-critical decisions (medical dosing, legal advice, financial transactions) without human review.
- "The model said it with confidence" is not validation — LLMs express high confidence on hallucinated content.
- Schema validation catches structural errors; it does not verify factual accuracy. Both are needed.
- Grounding (RAG + citation verification) is currently the most effective hallucination reduction technique for factual queries.
Common Mistakes
- Displaying LLM-generated citations as clickable links without verifying they exist — hallucinated URLs and DOIs are common.
- Using LLM output as input to another LLM without validation — hallucinations compound across chains.
- Treating structured output (JSON mode) as validated output — the structure is correct, but the values may still be hallucinated.
- No feedback loop for incorrect outputs — without tracking which outputs were wrong, you cannot improve the system.
1---2name: validate-llm-output3description: Use when LLM outputs are used to make decisions, generate content, answer questions, or drive application logic — to detect hallucinations, verify factual grounding, and prevent over-reliance on unverified AI-generated content.4source: 'OWASP Top 10 for LLM Applications 2025 LLM09 (owasp.org/www-project-top-10-for-large-language-model-applications/); NIST AI RMF 1.0 Measure 2.5; Anthropic Constitutional AI research; CWE-1188'5tags: [security, owasp, llm, hallucination, output-validation, grounding, ai-safety, emerging]6emerging: true7metadata:8 source: https://skillmd.com/skills/jeffreytse/validate-llm-output9---1011# Validate LLM Output1213Verify LLM outputs against ground truth sources, enforce structured schemas, and implement human review thresholds — preventing hallucinated facts, fabricated citations, and incorrect decisions from propagating into production systems.1415## Why This Is Best Practice1617**Adopted by:** OWASP Top 10 for LLM Applications 2025 LLM09 (Overreliance). NIST AI RMF 1.0 (2023) Measure 2.5 requires AI output monitoring and human review mechanisms. The EU AI Act (2024) Article 9 mandates human oversight for high-risk AI system outputs. Microsoft Azure AI Content Safety, AWS Bedrock Guardrails, and Google Vertex AI Evaluation all provide output validation tooling.18**Status:** Emerging — hallucination detection and output validation are active research areas; no single complete solution exists, and techniques are still rapidly improving.19**Impact:** A US federal attorney was sanctioned by a judge for submitting AI-generated legal briefs containing fabricated case citations (Mata v. Avianca, 2023). A medical AI system gave drug dosage recommendations that were factually incorrect due to hallucination. LLMs confidently generate plausible-sounding but false statistics, fake academic citations, and invented API parameters — all at a high confidence level that can mislead users and downstream systems.20**Why best:** User-level review for every output is the alternative — it's too slow for real-time applications and subject to automation bias (users trust AI outputs without scrutinizing them). Automated structural validation + confidence thresholds + selective human review provides scalable quality control.2122Sources: OWASP LLM Top 10 2025 LLM09; Mata v. Avianca (2023); NIST AI RMF 1.0 Measure 2.5; EU AI Act Article 92324## Steps25261. **Use structured output with schema validation**:2728 ```python29 from pydantic import BaseModel, validator30 from typing import Optional3132 class ProductRecommendation(BaseModel):33 product_id: str # must reference a real product34 reason: str35 confidence: float # 0.0–1.03637 @validator('product_id')38 def product_must_exist(cls, v):39 if not db.product_exists(v):40 raise ValueError(f"LLM hallucinated product ID: {v}")41 return v4243 @validator('confidence')44 def confidence_in_range(cls, v):45 if not 0.0 <= v <= 1.0:46 raise ValueError("Confidence must be 0–1")47 return v4849 response = openai.beta.chat.completions.parse(50 model="gpt-4o",51 messages=messages,52 response_format=ProductRecommendation,53 )54 result = response.choices[0].message.parsed55 # If product_id doesn't exist in DB, pydantic raises ValueError — handle it56 ```57582. **Verify citations and references against source documents**:5960 ```python61 def verify_citations(llm_response: str, source_documents: list[str]) -> dict:62 """Check that claims in LLM response are grounded in source documents."""63 # Extract claims from response64 claims = extract_claims(llm_response)65 verification_results = {}6667 for claim in claims:68 # Check if claim is supported by any source document69 supported = any(70 is_semantically_similar(claim, chunk)71 for doc in source_documents72 for chunk in split_into_chunks(doc)73 )74 verification_results[claim] = 'supported' if supported else 'unverified'7576 unverified_count = sum(1 for v in verification_results.values() if v == 'unverified')77 return {78 'verified_fraction': 1 - unverified_count / max(len(claims), 1),79 'claims': verification_results80 }81 ```82833. **Flag low-confidence outputs for human review**:8485 ```python86 CONFIDENCE_THRESHOLDS = {87 'medical_advice': 0.95,88 'legal_summary': 0.90,89 'financial_analysis': 0.90,90 'general_query': 0.70,91 }9293 def route_for_review(output: dict, task_type: str) -> dict:94 threshold = CONFIDENCE_THRESHOLDS.get(task_type, 0.80)95 confidence = output.get('confidence', 0.0)9697 if confidence < threshold:98 queue_for_human_review(output, task_type, reason='low_confidence')99 return {100 'status': 'pending_review',101 'message': 'This response requires expert review before use.',102 'estimated_review_time': '2 hours'103 }104 return output105 ```1061074. **Cross-validate with deterministic checks where possible**:108109 ```python110 def validate_llm_analysis(llm_output: dict, raw_data: dict) -> bool:111 """Re-check LLM's numerical claims against source data."""112 # LLM said revenue grew 15% — verify against actual numbers113 if 'revenue_growth' in llm_output:114 actual_growth = (115 (raw_data['revenue_2024'] - raw_data['revenue_2023'])116 / raw_data['revenue_2023']117 )118 llm_claimed = llm_output['revenue_growth']119 if abs(actual_growth - llm_claimed) > 0.02: # 2% tolerance120 logger.warning("LLM hallucinated revenue growth: claimed=%s actual=%s",121 llm_claimed, actual_growth)122 return False123 return True124 ```1251265. **Set appropriate user expectations** — surface uncertainty in the UI:127128 ```python129 def format_response_with_confidence(response: dict) -> dict:130 confidence = response.get('confidence', 0.0)131 disclaimer = None132133 if confidence < 0.70:134 disclaimer = "⚠️ This response has low confidence. Verify before acting on it."135 elif confidence < 0.85:136 disclaimer = "This response is AI-generated. Please verify important details."137138 return {139 **response,140 'disclaimer': disclaimer,141 'sources_verified': response.get('sources_grounded', False),142 }143 ```1441456. **Monitor output quality over time** — hallucination rates drift with model updates:146147 ```python148 def sample_for_quality_audit(response_id: str, sample_rate: float = 0.05):149 """Send a sample of responses for human quality review."""150 if random.random() < sample_rate:151 queue_for_quality_review(response_id)152 ```153154## Rules155156- Never use LLM outputs as authoritative sources for safety-critical decisions (medical dosing, legal advice, financial transactions) without human review.157- "The model said it with confidence" is not validation — LLMs express high confidence on hallucinated content.158- Schema validation catches structural errors; it does not verify factual accuracy. Both are needed.159- Grounding (RAG + citation verification) is currently the most effective hallucination reduction technique for factual queries.160161## Common Mistakes162163- **Displaying LLM-generated citations as clickable links without verifying they exist** — hallucinated URLs and DOIs are common.164- **Using LLM output as input to another LLM without validation** — hallucinations compound across chains.165- **Treating structured output (JSON mode) as validated output** — the structure is correct, but the values may still be hallucinated.166- **No feedback loop for incorrect outputs** — without tracking which outputs were wrong, you cannot improve the system.