This playbook is for teams running extraction pipelines where models invent plausible but unsourced fields. When a model is asked to extract structured data from a document, it may add fields that sound correct but have no basis in the source text. This prompt uses few-shot counterexamples showing hallucinated versus grounded output pairs to teach field-level skepticism. Use it as a post-extraction repair step or as a guardrail before extracted data enters a database, CRM, or downstream system. It is not a replacement for a well-designed extraction schema, but it catches the most common class of fabrication errors that pass basic format validation.
Prompt
Hallucinated Field Detection and Removal Prompt

When to Use This Prompt
Identify when to deploy hallucinated field detection to prevent fabricated data from entering downstream systems.
Deploy this prompt when your extraction pipeline produces structured outputs that pass schema validation but contain fields that cannot be traced back to the source document. Common triggers include: models adding plausible dates, names, or amounts to incomplete records; filling in missing enum values with likely defaults; or expanding abbreviations into full terms without evidence. The prompt works best when paired with a source document reference and an extraction schema that defines which fields are required versus optional. For high-stakes domains like healthcare, legal, or finance, always route flagged outputs to human review rather than auto-deleting fields, as over-aggressive removal can drop critical information that was merely phrased differently than expected.
Do not use this prompt as your primary extraction instruction. It is a repair and guardrail step, not a replacement for clear schema definitions, explicit null-handling rules, and source-grounding instructions in your main extraction prompt. Also avoid using it when the extraction task requires inferential reasoning that legitimately goes beyond the literal source text—for example, sentiment analysis, risk scoring, or summarization tasks where the output is expected to synthesize rather than transcribe. In those cases, field-level hallucination detection will produce false positives by flagging valid inferences as unsourced. Start with this prompt after you have a working extraction pipeline and need to reduce the fabrication rate before data reaches production systems.
Use Case Fit
Where the Hallucinated Field Detection and Removal Prompt works well, where it breaks, and the operational prerequisites for safe deployment in extraction pipelines.
Good Fit: High-Precision Extraction
Use when: Your extraction pipeline requires strict field-level grounding and cannot tolerate invented data. Guardrail: Pair this prompt with a source-evidence requirement so the model must cite or nullify every field, making hallucination immediately visible.
Bad Fit: Creative Generation
Avoid when: The task is open-ended content creation, brainstorming, or narrative generation where 'invented' fields are expected features, not bugs. Guardrail: Route creative tasks to a different prompt template to prevent the model from over-correcting and stripping legitimate imaginative content.
Required Inputs
What you need: A raw model output containing structured data (JSON) and the original source text used for extraction. Guardrail: Implement a pre-check that rejects inputs without source grounding; running this prompt without source text turns it into a blind guess that may remove valid fields.
Operational Risk: Precision-Recall Trade-off
Risk: Aggressive hallucination removal can strip true but infrequently phrased fields, hurting recall. Guardrail: Run a golden dataset evaluation measuring both precision (hallucinated fields removed) and recall (valid fields preserved) before production deployment to calibrate the prompt's skepticism threshold.
Operational Risk: Latency and Cost
Risk: Adding a second LLM call for detection and removal doubles latency and cost for every extraction. Guardrail: Gate this prompt behind a lightweight heuristic check (e.g., field count anomaly or confidence score threshold) so it only fires when hallucination is suspected, not on every request.
Bad Fit: Unstructured Narrative Output
Avoid when: The model output is free-text prose rather than structured key-value pairs. Guardrail: Use a schema validation step first; if the output isn't structured, route to a structured extraction prompt instead of attempting field-level hallucination removal on narrative text.
Copy-Ready Prompt Template
A copy-ready prompt that teaches the model to detect and remove hallucinated fields using paired counterexamples.
This prompt template is designed to be pasted directly into your system. It uses few-shot counterexamples to teach the model the difference between grounded fields (derived from the source text) and hallucinated fields (plausible but unsupported inventions). The counterexamples are the critical teaching mechanism; keep them domain-specific and update them when you observe new hallucination patterns in production. Replace the square-bracket placeholders with your actual source text, extraction schema, and domain-relevant counterexamples before use.
textYou are an extraction auditor. Your job is to review a structured output and remove any field whose value cannot be directly supported by the source text. A field is hallucinated if it invents a fact, name, date, number, or relationship that does not appear in the source. Do not remove a field just because the source uses different wording. If the information is present and can be clearly inferred without adding new facts, keep it. If you are unsure, flag the field as [UNCERTAIN] instead of removing it. --- SOURCE TEXT: [SOURCE_TEXT] EXTRACTED OUTPUT TO AUDIT: [EXTRACTED_OUTPUT] --- COUNTEREXAMPLES: Example 1 - Hallucinated Field (REMOVE): Source: "Acme Corp reported Q3 revenue of $2.1 million." Extracted: {"company_name": "Acme Corp", "quarter": "Q3", "revenue": 2100000, "ceo": "Jane Smith"} Audit Decision: Remove "ceo". The source never mentions a CEO. Example 2 - Grounded Field (KEEP): Source: "The defendant, a 34-year-old engineer, was cited for speeding." Extracted: {"age": 34, "occupation": "engineer", "charge": "speeding", "gender": "male"} Audit Decision: Remove "gender". The source does not state the defendant's gender. "Engineer" does not imply gender. Example 3 - Uncertain Field (FLAG): Source: "The server crashed at 03:00 UTC." Extracted: {"event": "server crash", "timestamp": "03:00 UTC", "root_cause": "memory leak"} Audit Decision: Flag "root_cause" as [UNCERTAIN]. The source states a crash occurred but does not state the cause. --- TASK: Review the extracted output above. For each field, decide whether it is GROUNDED (directly supported by the source), HALLUCINATED (invents unsupported information), or UNCERTAIN (plausible but not confirmed). Return a JSON object with the following structure: { "audit_result": { "grounded_fields": { ... }, "removed_fields": { "field_name": "reason for removal" }, "uncertain_fields": { "field_name": "reason for uncertainty" } }, "cleaned_output": { ... }, "audit_notes": "Brief explanation of decisions" } The "cleaned_output" must contain only grounded and uncertain fields. Hallucinated fields must be excluded entirely. CONSTRAINTS: - Do not add any fields that were not in the original extracted output. - Do not modify field values unless correcting an obvious extraction error that is supported by the source. - If the entire output appears fabricated, return an empty "cleaned_output" and explain in "audit_notes".
To adapt this prompt for your domain, replace the counterexamples with real hallucination patterns you've observed in production. The three examples above cover removal, keeping, and flagging—maintain this structure. Update the [SOURCE_TEXT] and [EXTRACTED_OUTPUT] placeholders with your actual data. If your schema is deeply nested, add a counterexample showing nested field removal. For high-stakes domains like healthcare or finance, add a fourth counterexample demonstrating when to escalate to human review rather than making an automated removal decision. Test the prompt against a golden set of known hallucinated outputs before deploying, and monitor the uncertain_fields rate in production—a rising rate may indicate source quality issues or schema drift.
Prompt Variables
Required inputs for the hallucinated field detection and removal prompt. Validate each placeholder before sending to prevent injection, schema drift, or false negatives.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[EXTRACTED_FIELDS_JSON] | The raw structured output from the extraction model that may contain hallucinated fields | {"name": "Alice", "ssn": "123-45-6789", "favorite_color": "blue"} | Must be valid JSON. Parse check required. Reject if empty object or missing required source-mapped fields. Schema-agnostic validation only; do not enforce target schema here. |
[SOURCE_TEXT] | The original unstructured text from which fields were extracted | Alice reported her favorite color as blue during the intake interview. | Must be non-empty string. Length check: reject if under 10 characters or over context window. Strip control characters. Required for grounding comparisons. |
[FIELD_SCHEMA] | The expected output schema defining which fields are legitimate vs. hallucinated | {"allowed_fields": ["name", "favorite_color"], "required_fields": ["name"]} | Must be valid JSON with allowed_fields array. Each field must be a string. Reject if allowed_fields is empty. Optional required_fields subset for downstream validation. |
[HALLUCINATION_EXAMPLES] | Few-shot pairs showing hallucinated vs. grounded field removal decisions | [{"input": {"name": "Bob", "phone": "555-0100"}, "source": "Bob checked in.", "output": {"name": "Bob"}}] | Must be valid JSON array with 2-5 objects. Each object requires input, source, and output keys. Validate output only contains fields present in source. Reject if examples contradict each other. |
[CONFIDENCE_THRESHOLD] | Minimum confidence score for keeping a field; fields below this threshold are flagged for removal | 0.7 | Must be float between 0.0 and 1.0. Default 0.5 if not provided. Lower values increase hallucination risk; higher values increase false removal of legitimate fields. |
[REMOVAL_MODE] | Controls whether hallucinated fields are dropped silently or replaced with a placeholder | drop | Must be one of: drop, null_fill, flag. drop removes the field entirely. null_fill sets value to null. flag keeps field with a hallucinated: true marker. Reject unknown values. |
[OUTPUT_SCHEMA] | The exact JSON structure expected in the response, including field-level metadata | {"kept_fields": {}, "removed_fields": [{"field": "ssn", "reason": "no_source_evidence"}]} | Must be valid JSON Schema or example structure. Validate that removed_fields array items include field and reason keys. Reject schemas that don't distinguish kept from removed fields. |
Implementation Harness Notes
How to wire the hallucinated field detection prompt into an extraction pipeline with validation, retries, and human review gates.
This prompt is designed to sit between your initial extraction step and downstream consumers of structured data. After the model produces a JSON object from source text, pass both the raw output and the source evidence into this detection prompt. The prompt's job is to return a cleaned object with hallucinated fields removed and a removed_fields audit trail. Do not use this prompt as the primary extractor—it is a post-extraction safety filter that assumes the input is already structured JSON.
Wire the prompt into a validation pipeline with these stages: (1) Run the primary extraction prompt and parse the JSON. (2) If parsing fails, route to a JSON repair prompt first. (3) Pass the valid JSON and the original source text into this hallucination detection prompt. (4) Parse the cleaned output and compare removed_fields against the original object. (5) If removed_fields is non-empty, log the full audit record including source text, original output, cleaned output, and removal reasons. (6) Route outputs with high-confidence removals in critical fields to a human review queue before ingestion. For low-risk fields, you can auto-accept the cleaned output but still log for monitoring.
Model choice matters. This prompt relies on the model's ability to compare structured claims against unstructured evidence. Use a model with strong instruction-following and long-context handling, such as GPT-4o, Claude 3.5 Sonnet, or Gemini 1.5 Pro. Avoid smaller or older models that struggle with multi-field comparison tasks—they tend to either over-remove (killing correct fields) or under-remove (missing subtle hallucinations). If latency is critical, consider running this check asynchronously after the primary extraction returns to the user, flagging corrections for later reconciliation rather than blocking the response.
Retry logic should be minimal. If the detection prompt itself returns malformed JSON or fails to include the removed_fields key, retry once with a stricter output format instruction appended. If the second attempt fails, log the failure and fall back to the original extraction output with a hallucination_check_failed flag. Never silently drop data because the safety check itself broke. For high-stakes pipelines (healthcare, legal, finance), require human review on any output where the hallucination check could not complete successfully.
Evaluation and monitoring are essential. Track precision (did we remove genuinely hallucinated fields?) and recall (did we catch all hallucinations?) on a golden test set of source-output pairs with known hallucinated fields. Common failure modes include: the model removing correct but surprising fields (low precision), missing hallucinations that paraphrase source text (low recall), and inconsistent removal decisions across similar inputs. Run this eval weekly and whenever you change the primary extraction prompt, the source document type, or the model version. If precision drops below 90% or recall below 80%, escalate to human review for all outputs until the prompt is tuned.
Expected Output Contract
Define the exact shape of the cleaned output after hallucinated fields are detected and removed. Use this contract to build a post-processing validator that rejects malformed repair attempts before they reach downstream systems.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
cleaned_output | object | Must be valid JSON. Must not contain any field listed in the removed_fields array. Must preserve all fields from the original_input that were not flagged. | |
removed_fields | array of strings | Each element must be a string matching a key path from original_input. Array must be empty if no fields were removed. Must not contain duplicates. | |
hallucination_flags | array of objects | Each object must have 'field' (string), 'reason' (enum: unsourced, contradictory, implausible, fabricated), and 'confidence' (number 0-1). Length must match removed_fields. | |
original_input | object | Must be identical to the input payload provided to the prompt. Used for diff validation. Must pass deep equality check against the request payload. | |
processing_metadata | object | Must contain 'model' (string), 'timestamp' (ISO 8601 string), and 'version' (string). Used for audit trail and debugging. | |
uncertain_fields | array of strings | If present, each element must be a string matching a key path from original_input. Lists fields the model considered flagging but kept. Useful for human review sampling. | |
audit_token | string | Must match the audit_token provided in the prompt request. Used to prevent cross-request contamination in batch processing. Reject if missing or mismatched. |
Common Failure Modes
When using few-shot examples to teach hallucinated field detection, these failures surface first in production. Each card pairs a specific failure with a concrete guardrail you can implement before deployment.
Model Learns to Over-Delete Legitimate Fields
What to watch: The model becomes too aggressive after seeing negative examples and removes fields that are actually grounded in the source text, especially rare but valid entity types or optional schema fields. Guardrail: Include counterexamples where legitimate fields must be preserved, and run precision-recall evals on a golden dataset that includes edge-case valid fields before shipping.
Example Set Doesn't Cover Your Actual Hallucination Patterns
What to watch: Your few-shot examples show obvious fabrications like fake phone numbers, but production hallucinations are subtler—plausible-sounding dates, near-miss entity names, or inferred relationships that aren't in the source. Guardrail: Mine your production logs for real hallucination patterns and build examples from actual failures, not hypothetical ones. Update examples when new failure modes appear.
Model Confuses Missing Evidence with Negative Evidence
What to watch: When a field isn't mentioned in the source, the model marks it as hallucinated instead of distinguishing between 'not present' and 'contradicted by evidence.' This causes false-positive removal flags. Guardrail: Include examples that explicitly label fields as 'absent from source' vs. 'contradicted by source,' and require the model to cite the specific passage that grounds or contradicts each field.
Schema Drift Makes Examples Stale
What to watch: Your extraction schema adds new optional fields, but your few-shot examples still reference the old schema. The model either ignores new fields or flags them as hallucinated because they don't appear in the examples. Guardrail: Version your example sets alongside your schema, add schema-aware validation that checks whether removed fields actually exist in the current schema, and trigger example refresh on schema changes.
Token Budget Crowds Out Source Context
What to watch: Detailed few-shot examples with paired hallucinated-vs-grounded outputs consume significant context window space, leaving less room for the actual source document and increasing truncation risk on long inputs. Guardrail: Compress examples to show only the field-level decision, not full document pairs. Use a dedicated detection pass after extraction rather than combining extraction and hallucination detection in one prompt.
Model Hallucinates the Hallucination Explanation
What to watch: When you ask the model to explain why a field was flagged, it invents plausible-sounding justifications that reference non-existent source passages or misattribute evidence. Guardrail: Require verbatim source quotes for every removal decision, validate quotes against the original text programmatically, and treat unverifiable explanations as a separate failure mode in your eval harness.
Evaluation Rubric
Run these checks on a golden dataset of 50-100 source-extraction pairs with known hallucinated fields. Each criterion measures a distinct failure mode. Use the Test Method column to automate pass/fail gates before shipping.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Field-Level Precision | ≥0.95 precision on field removal decisions | Non-hallucinated fields flagged for removal in >5% of test cases | Compare removed fields against golden labels; count false positives |
Field-Level Recall | ≥0.90 recall on hallucinated field detection | Known hallucinated fields survive removal in >10% of test cases | Compare surviving fields against golden hallucination labels; count false negatives |
Source Grounding Verification | Every retained field cites a source span or returns null for source | Retained field present with no source reference or fabricated citation | Parse output for [SOURCE] field; assert non-null for every retained field |
Null Handling Discipline | Hallucinated fields removed rather than replaced with null or empty string | Output contains field with null, empty string, or placeholder value where field should be absent | Schema check: removed fields must not appear in output object keys |
Confidence Score Calibration | Mean confidence for removal decisions within ±0.1 of actual accuracy | High-confidence removal decisions on non-hallucinated fields or low-confidence on known hallucinations | Compute Brier score across confidence values vs. binary correctness labels |
Structural Integrity After Removal | Output remains valid JSON matching [OUTPUT_SCHEMA] after field removal | Output fails JSON parse or schema validation after hallucinated fields removed | Run JSON.parse and schema validator on every output; count structural failures |
Boundary Case Handling | Correct removal decisions on ambiguous fields where source partially supports claim | Systematic over-removal or under-removal on fields with partial source evidence | Isolate boundary cases in golden dataset; measure precision-recall separately |
Counterexample Transfer | Model correctly applies removal patterns from few-shot counterexamples to novel field types | Removal accuracy drops >10% on field categories not represented in few-shot examples | Stratify test set by field category; compare accuracy across seen vs. unseen categories |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Start with the base prompt and a small set of 3-5 hallucinated vs. grounded output pairs. Use inline comments to mark which fields were invented. Keep the output schema flat and the field count low (under 10 fields). Run against 20-30 known documents and manually review every removal decision.
Watch for
- Over-removal of low-confidence but correct fields
- The model learning to flag all optional fields as hallucinated
- No baseline precision/recall measurement before iterating

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.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us