Inferensys

Prompt

Hallucination Root Cause Diagnosis Prompt

A practical prompt playbook for using Hallucination Root Cause Diagnosis Prompt in production AI workflows.
Operations team reviewing AI workflow automation on laptop, workflow builder visible, casual office setup.
PROMPT PLAYBOOK

When to Use This Prompt

A diagnostic tool for classifying why a model hallucinated before you apply a fix.

This prompt is for prompt engineers and AI reliability engineers who need to move beyond detecting hallucinations to understanding why they occur. Use it when you have a batch of hallucinated outputs and need to classify the root cause before applying a fix. This is a diagnostic tool, not a repair prompt. It assumes you have already identified hallucinated examples and collected the corresponding prompt, context, and model configuration. The output is a structured root cause analysis that tells you whether to fix the prompt, improve retrieval, add guardrails, or accept a model limitation.

Do not use this prompt when you need to repair a single hallucinated output in production—use a retry or regeneration prompt instead. Do not use it when you haven't yet confirmed that the output is actually hallucinated; run a fact-checking or claim-verification prompt first. This prompt is most effective when you have at least 5–10 confirmed hallucination examples from the same prompt template, because pattern analysis requires a sample size large enough to distinguish systematic failures from random noise. Before running this prompt, gather the original user input, the full prompt template with placeholders resolved, any retrieved context or tool outputs, the model ID and configuration, and the flagged hallucinated output.

The prompt produces a structured root cause classification—such as context insufficiency, prompt ambiguity, knowledge cutoff issues, or reasoning failures—along with a confidence score and a specific, actionable fix recommendation. Wire the output into your prompt debugging workflow: if the root cause is context insufficiency, improve retrieval or chunking; if it's prompt ambiguity, rewrite the instructions; if it's a knowledge cutoff, add up-to-date context or switch models. For high-stakes domains, always have a human review the diagnosis before applying the recommended fix to production prompts.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Hallucination Root Cause Diagnosis Prompt delivers value and where it introduces risk. Use this to decide if the prompt fits your debugging workflow before integrating it into your AI harness.

01

Good Fit: Systematic Hallucination Patterns

Use when: You observe recurring hallucination categories across multiple outputs—entity confusion, temporal errors, or fabricated citations—and need to identify the shared root cause. Guardrail: Feed the prompt batches of failures grouped by similarity, not isolated one-off errors, to surface systemic issues in prompt design or context assembly.

02

Good Fit: Pre-Deployment Prompt Hardening

Use when: You are iterating on RAG prompts or system instructions and want to understand why specific hallucination types persist across prompt versions. Guardrail: Run diagnosis on a golden dataset of known failures before each prompt release, and gate deployment on root cause resolution rather than surface-level output fixes.

03

Bad Fit: Real-Time Hallucination Correction

Avoid when: You need to fix a hallucinated output in a live user-facing response under latency constraints. Root cause diagnosis is an offline debugging tool, not a real-time repair prompt. Guardrail: Route live corrections to a Grounded Answer Regeneration Prompt; use this prompt in post-mortem analysis pipelines instead.

04

Bad Fit: Single Anomalous Failure Investigation

Avoid when: You have one unexplained hallucination and want a quick answer. The diagnosis prompt works best with patterns across multiple examples. Guardrail: Log the single failure with full context and accumulate at least 5–10 similar cases before invoking diagnosis; isolated anomalies often stem from transient model behavior rather than structural prompt flaws.

05

Required Inputs: Structured Failure Records

What to watch: The prompt cannot diagnose root causes from vague descriptions. It needs the original prompt template, retrieved context, the hallucinated output, and a validator's error annotation. Guardrail: Build a failure-logging harness that captures all four inputs per incident before invoking diagnosis; incomplete records produce unreliable classifications.

06

Operational Risk: Misattributed Root Causes

What to watch: The model may confidently attribute hallucinations to context insufficiency when the real cause is ambiguous system instructions, or vice versa. Guardrail: Require human review of diagnosis outputs for the first 20–30 analyses, and cross-validate findings by testing the recommended fix against the original failure set before accepting the root cause classification.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A copy-ready prompt that instructs the model to act as a hallucination diagnostician, analyzing a failure across multiple dimensions and producing a structured root cause classification with evidence and fix recommendations.

The prompt below is designed to be pasted directly into your AI harness or playground. It forces the model to move beyond surface-level correction and instead perform a systematic diagnosis of why a hallucination occurred. The output is a structured JSON report suitable for logging, automated routing, or feeding into a downstream repair pipeline. Replace every square-bracket placeholder with your actual data before execution.

text
You are a hallucination root cause diagnostician. Your job is to analyze a specific instance where a model produced a hallucinated or factually incorrect output. You will receive the original prompt, the provided context (if any), the model's incorrect output, and the ground-truth correction. You must classify the root cause, provide evidence for your classification, and recommend a concrete fix.

## INPUTS
- **Original Prompt:** [ORIGINAL_PROMPT]
- **Provided Context:** [PROVIDED_CONTEXT]
- **Incorrect Model Output:** [INCORRECT_OUTPUT]
- **Ground-Truth Correction:** [GROUND_TRUTH_CORRECTION]

## DIAGNOSIS DIMENSIONS
Analyze the failure across these dimensions. For each, state whether it contributed (YES/NO) and provide a brief evidence snippet.
1. **Context Insufficiency:** The provided context was missing the necessary fact, was ambiguous, or was truncated.
2. **Context Misinterpretation:** The context contained the fact, but the model misread, conflated entities, or drew an incorrect inference.
3. **Prompt Ambiguity:** The original prompt was underspecified, contradictory, or encouraged fabrication (e.g., "be creative").
4. **Knowledge Cutoff / Parametric Hallucination:** The model relied on outdated or incorrect internal knowledge instead of the provided context.
5. **Reasoning Failure:** The model combined facts incorrectly, made a logical error, or failed at multi-hop synthesis.
6. **Format or Constraint Pressure:** Output constraints (e.g., "must be under 50 words") forced the model to drop critical qualifiers or invent details.

## OUTPUT SCHEMA
Return a single JSON object with this exact structure:
{
  "failure_id": "[FAILURE_ID]",
  "primary_root_cause": "Context Insufficiency | Context Misinterpretation | Prompt Ambiguity | Knowledge Cutoff | Reasoning Failure | Format Pressure",
  "diagnosis": {
    "context_insufficiency": { "contributed": true/false, "evidence": "string" },
    "context_misinterpretation": { "contributed": true/false, "evidence": "string" },
    "prompt_ambiguity": { "contributed": true/false, "evidence": "string" },
    "knowledge_cutoff": { "contributed": true/false, "evidence": "string" },
    "reasoning_failure": { "contributed": true/false, "evidence": "string" },
    "format_pressure": { "contributed": true/false, "evidence": "string" }
  },
  "fix_recommendation": {
    "action": "REWRITE_PROMPT | ADD_CONTEXT | ADD_EXAMPLE | ADD_CONSTRAINT | ESCALATE_TO_HUMAN | FINE_TUNE | NO_FIX_NEEDED",
    "specific_change": "A concrete, one-sentence instruction for what to change.",
    "revised_prompt_snippet": "Optional. A corrected excerpt of the prompt or constraint."
  },
  "severity": "LOW | MEDIUM | HIGH | CRITICAL",
  "retry_likely_to_fix": true/false
}

## CONSTRAINTS
- Base your diagnosis strictly on the provided inputs. Do not invent external facts.
- If multiple dimensions contributed, set `primary_root_cause` to the most impactful one and note the others in the diagnosis fields.
- If the provided context is empty, `context_insufficiency.contributed` must be true.
- Do not wrap the JSON in markdown fences. Return only the raw JSON object.

To adapt this template, start by populating the four input fields with data from your production logs or evaluation harness. The [FAILURE_ID] should be a unique identifier from your tracing system so you can link the diagnosis back to a specific request. If your application does not use explicit context windows, set [PROVIDED_CONTEXT] to an empty string—the prompt will correctly flag context insufficiency. For batch analysis, wrap this prompt in a loop that iterates over logged failure records and writes each diagnosis to your observability platform. Always validate the output JSON against the schema before accepting the diagnosis; a malformed fix_recommendation object can break downstream automation.

This prompt is a diagnostic tool, not a repair tool. After classification, route the fix_recommendation.action to the appropriate workflow: REWRITE_PROMPT goes to your prompt registry, ADD_CONTEXT goes to your retrieval pipeline, and ESCALATE_TO_HUMAN should trigger a review ticket. For high-severity findings where retry_likely_to_fix is false, do not loop—escalate immediately. Run this diagnosis on a sample of failures weekly to detect systemic drift before it impacts users.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Hallucination Root Cause Diagnosis Prompt. Each variable must be populated before execution to ensure reliable root cause classification and actionable fix recommendations.

PlaceholderPurposeExampleValidation Notes

[HALLUCINATED_OUTPUT]

The model response containing suspected hallucinations to be diagnosed

The patient was prescribed 500mg of Amlodipine on March 15, 2024 by Dr. Chen

Must be non-empty string. Should be the raw output before any post-processing. Parse check: length > 0

[SOURCE_CONTEXT]

The ground-truth context or retrieved passages provided to the model when generating the output

Patient medication record: Amlodipine 5mg prescribed 2024-03-12 by Dr. Patel. No dosage change recorded.

Must be non-empty string. This is the evidence against which hallucinations are measured. Null not allowed

[PROMPT_TEMPLATE]

The full system and user prompt structure used when generating the hallucinated output, including instructions and constraints

System: You are a clinical assistant. Answer only from the provided patient record. User: What medications is this patient taking?

Must include both system and user messages if both were used. Schema check: contains instruction boundaries

[MODEL_IDENTIFIER]

The specific model and version that produced the hallucinated output

gpt-4-0125-preview

Must be a valid model identifier string. Used to assess knowledge cutoff and known failure patterns. Parse check: non-empty, matches known model format

[OUTPUT_TIMESTAMP]

ISO 8601 timestamp of when the hallucinated output was generated

2024-11-15T14:32:00Z

Must be valid ISO 8601 format. Used to compare against model knowledge cutoff date. Schema check: parseable as datetime

[HALLUCINATION_SEVERITY]

Pre-classified severity level of the detected hallucination from upstream detection systems

HIGH

Must be one of: LOW, MEDIUM, HIGH, CRITICAL. Enum check: value in allowed set. Used to prioritize diagnosis depth

[PREVIOUS_CORRECTION_ATTEMPTS]

Number of prior retry or self-correction attempts that failed to resolve this hallucination

2

Must be integer >= 0. Used to determine if this is a persistent pattern or first occurrence. Parse check: non-negative integer

[DOMAIN_TAXONOMY]

Optional domain-specific terminology, entity types, and fact patterns relevant to the output context

Medication names, dosages, prescriber names, dates of administration

Null allowed if no domain taxonomy exists. If provided, must be structured as comma-separated terms or JSON array. Used for domain-aware pattern matching

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Hallucination Root Cause Diagnosis Prompt into an automated debugging pipeline with validation, logging, and escalation.

This prompt is designed to be called programmatically after a hallucination event has been detected by an upstream validator or LLM judge. The harness should assemble the required inputs—the original user query, the full prompt template with system instructions, the retrieved context (if RAG was used), and the flagged hallucinated output—into a single structured request. Because the diagnosis prompt itself performs analysis rather than taking action, the harness should treat its output as a structured diagnostic record, not as a command to automatically modify production prompts. The recommended integration pattern is a post-detection callback: when a hallucination is flagged with a confidence score above a defined threshold, the harness fires this diagnosis prompt, logs the root cause classification, and routes the finding to the appropriate remediation queue.

Input Assembly and Validation: Before calling the diagnosis prompt, validate that all required fields are present and non-empty. The [HALLUCINATED_OUTPUT] must be the exact text that failed validation, not a summary. The [PROMPT_TEMPLATE] should include the full system prompt and any few-shot examples, as root causes often hide in instruction ambiguity or example conflict. The [RETRIEVED_CONTEXT] field must be the raw context chunks provided to the model, not post-hoc retrieved passages, to accurately diagnose context insufficiency. Implement a pre-flight schema check that rejects the diagnosis request if any field is missing or truncated. For high-volume production systems, batch multiple hallucination events and run diagnosis in a separate async worker to avoid adding latency to the primary response path. Use a structured output constraint on the diagnosis prompt itself—require JSON output with root_cause_category, confidence, evidence, and fix_recommendation fields—so the harness can parse and route results without manual inspection.

Retry, Logging, and Escalation: The diagnosis prompt should be treated as a non-retryable analysis step. If the model fails to return valid JSON or the output schema validation fails, log the raw response and escalate to a human reviewer rather than retrying, because a malformed diagnosis provides its own signal about prompt fragility. Log every diagnosis result with a composite key of [timestamp, session_id, hallucination_id] to enable trend analysis over time. When the diagnosis returns root_cause_category: context_insufficiency with high confidence, route to the retrieval pipeline team for context quality review. When it returns prompt_ambiguity or instruction_conflict, route to the prompt engineering backlog. Implement a severity threshold: if the same root cause category appears more than N times within a rolling window, trigger an automated alert to the on-call channel. Do not automatically apply the fix_recommendation field to production prompts without human review—the diagnosis is advisory, and prompt changes require regression testing against your golden evaluation set. The harness should write the fix recommendation into a prompt versioning system as a proposed change, not a direct mutation.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the structured output schema for the Hallucination Root Cause Diagnosis Prompt. Use this contract to validate the model's response before routing it to downstream systems or human reviewers.

Field or ElementType or FormatRequiredValidation Rule

root_cause_classification

enum string

Must match one of: 'context_insufficiency', 'prompt_ambiguity', 'knowledge_cutoff', 'reasoning_failure', 'source_conflict', 'overgeneralization'. Reject if missing or invalid.

confidence_score

float (0.0-1.0)

Must be a number between 0.0 and 1.0. If below 0.6, escalate for human review. Reject if null or non-numeric.

hallucinated_claim

string

Must be a non-empty string containing the exact text flagged as hallucinated. Reject if empty or identical to the full output.

evidence_for_claim

array of strings

Must contain at least one string excerpt from provided context. If empty, set root_cause_classification to 'context_insufficiency' and escalate.

diagnosis_rationale

string

Must be a non-empty string explaining the causal link between the root cause and the hallucination. Reject if shorter than 20 characters.

fix_recommendation

object with 'prompt_fix' and 'context_fix' string fields

Both sub-fields must be non-empty strings. If no fix is applicable for a field, set to 'NONE'. Reject if the object is missing.

retry_instruction

string

If present, must be a valid instruction for a regeneration prompt. If null, the system should not retry automatically.

escalation_flag

boolean

Must be true if confidence_score < 0.6 or root_cause_classification is 'knowledge_cutoff'. Used by the harness to trigger human review.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when diagnosing hallucination root causes and how to guard against misdiagnosis, shallow analysis, and unimplementable recommendations.

01

Misattributing Hallucination to a Single Cause

What to watch: The diagnosis prompt blames one factor (e.g., 'context was insufficient') when the hallucination actually resulted from interacting failures: ambiguous instructions plus knowledge cutoff plus missing retrieval. Guardrail: Require the prompt to produce a ranked list of contributing factors with confidence scores, not a single root cause. Add a constraint: 'If multiple factors likely contributed, list all with relative contribution estimates.'

02

Diagnosing Without the Original Context

What to watch: The prompt analyzes the hallucinated output and the prompt template but lacks the actual retrieved context, tool outputs, or conversation history that was present at generation time. The diagnosis becomes speculative. Guardrail: Make [FULL_CONTEXT_AT_GENERATION_TIME] a required input. If context is unavailable, the prompt must output 'INSUFFICIENT_EVIDENCE' rather than guessing. Log context alongside outputs in production for post-hoc diagnosis.

03

Producing Vague Fix Recommendations

What to watch: The diagnosis prompt outputs generic advice like 'improve context quality' or 'clarify instructions' without specifying what to change, where, or how to verify the fix worked. Guardrail: Constrain the output schema to require concrete, testable fix actions: 'Modify system prompt line X from Y to Z. Verify with test case A.' Include a 'verification_test' field that specifies the input and expected behavior change.

04

Confusing Knowledge Cutoff with Context Insufficiency

What to watch: The model fabricates a fact that exists nowhere in the provided context but is true in the world. The diagnosis incorrectly flags this as context insufficiency when the real issue is the model relying on parametric knowledge instead of grounding instructions. Guardrail: Add a classification dimension: 'Source of hallucinated claim: [Parametric Knowledge | Context Distortion | Fabrication | Inference Error].' If parametric knowledge is detected, recommend strengthening grounding constraints, not adding more context.

05

Ignoring Prompt Ambiguity as a Root Cause

What to watch: The diagnosis focuses on context and model behavior while overlooking that the prompt itself contains contradictory instructions, undefined terms, or implicit assumptions the model resolved incorrectly. Guardrail: Include a mandatory 'prompt_ambiguity_audit' step that identifies: undefined terms, conflicting constraints, missing output boundaries, and assumed knowledge. Flag any instruction that could be interpreted multiple ways.

06

Diagnosis Drift Across Repeated Runs

What to watch: Running the same diagnosis prompt on the same failure multiple times produces different root cause classifications, eroding trust in the diagnostic pipeline. Guardrail: Set temperature to 0 for diagnosis prompts. Add a consistency check: run diagnosis twice and flag if root cause rankings diverge beyond a threshold. If divergence detected, escalate to human review rather than accepting an unstable diagnosis.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to evaluate the quality of the Hallucination Root Cause Diagnosis Prompt's output before integrating it into your debugging pipeline. Each criterion targets a specific failure mode in root cause analysis.

CriterionPass StandardFailure SignalTest Method

Root Cause Classification

Output assigns exactly one primary root cause from the defined taxonomy: Context Insufficiency, Prompt Ambiguity, Knowledge Cutoff, or Reasoning Failure.

Output assigns multiple root causes, invents a new category, or fails to select a primary cause.

Automated check: Validate the output field against an enum of allowed categories.

Evidence Traceability

Each identified hallucination pattern is linked to a specific excerpt from the original prompt, context, or model output.

A pattern is described without a direct quote or reference to the source material.

Manual review of 5 random samples: Verify that every pattern has a corresponding source excerpt.

Actionable Fix Recommendation

At least one concrete, specific fix is proposed for the primary root cause (e.g., 'Add a constraint: If the user's tier is not in the context, respond with...').

Recommendations are vague (e.g., 'improve the prompt'), generic, or missing entirely.

Automated check: Use an LLM judge to confirm the recommendation references a specific prompt section or context field.

Context Sufficiency Analysis

If the root cause is 'Context Insufficiency', the output explicitly lists the missing information required to answer correctly.

The output blames the model without identifying what specific data was absent from the provided context.

Manual review: For a test case with intentionally removed context, check if the output identifies the missing field.

Prompt Ambiguity Identification

If the root cause is 'Prompt Ambiguity', the output pinpoints the exact ambiguous phrase or instruction and explains multiple valid interpretations.

The output states the prompt is ambiguous without quoting the problematic text or explaining the conflicting interpretations.

Automated check: Use string matching to verify the ambiguous text from the input prompt is present in the analysis output.

Knowledge Cutoff Handling

If the root cause is 'Knowledge Cutoff', the output correctly identifies the factual claim that requires post-training knowledge and suggests a retrieval or tool-use mitigation.

The output incorrectly attributes a hallucination to a knowledge cutoff when the information was present in the provided context.

Test with a known post-cutoff fact: Verify the output flags it as a cutoff issue and does not blame context or ambiguity.

Reasoning Failure Diagnosis

If the root cause is 'Reasoning Failure', the output identifies the specific logical leap, false assumption, or calculation error in the model's chain of thought.

The output gives a generic 'the model reasoned poorly' statement without isolating the faulty step.

Test with a multi-step math problem: Provide a model output with a deliberate arithmetic error and check if the diagnosis pinpoints the step.

Output Format Compliance

The output is a valid JSON object matching the specified [OUTPUT_SCHEMA] with all required fields present and correctly typed.

The output is malformed JSON, missing required fields like 'primary_root_cause' or 'evidence', or contains extra commentary outside the schema.

Automated schema validation: Parse the output with a JSON schema validator configured with the expected structure.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single hallucinated output and its source context. Skip formal schema validation. Focus on getting a useful root cause classification and one actionable fix recommendation. Run interactively in a notebook or chat UI.

Watch for

  • The model may over-explain without reaching a clear root cause
  • Without structured output constraints, results will be hard to compare across runs
  • Knowledge cutoff hallucinations may be misclassified as context insufficiency
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.