Inferensys

Prompt

Automated Guardrail Prompt for Hallucination Detection

A practical prompt playbook for using Automated Guardrail Prompt for Hallucination Detection in production AI workflows.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

When to Use This Prompt

Deploy a reusable, configurable guardrail that inspects generated answers against source evidence and returns a structured block, flag, or pass decision before the answer reaches the end user.

This prompt is a reusable system-level guardrail that sits between your answer generation step and the end user. It inspects a generated answer against the provided source evidence and returns a structured decision: block, flag for review, or pass. Platform teams use this to build centralized safety infrastructure that catches hallucinations, policy violations, and unsupported claims before they reach customers. Deploy this when you need a single, configurable checkpoint that enforces factual grounding across multiple RAG applications or product surfaces. This is not a prompt for generating answers. It is a prompt for verifying them.

The ideal user is a platform engineer or AI safety architect responsible for output quality across multiple product surfaces. You need the generated answer, the source evidence used to produce it, and a defined policy for what constitutes a violation. The guardrail prompt works best when you can supply a clear [POLICY] block that defines unacceptable behaviors—such as unsupported claims, fabricated citations, contradictions with source material, or statements that exceed the evidence. You should also supply an [OUTPUT_SCHEMA] so the guardrail returns a machine-readable decision your application can act on without parsing free text. For high-risk domains, configure the guardrail to flag for human review rather than auto-blocking, and log every decision with the guardrail's rationale for audit.

Do not use this prompt as your only safety measure for high-stakes regulated domains. It is a probabilistic check, not a deterministic validator. Combine it with citation-to-evidence cross-reference checks, human review for flagged outputs, and regression tests against known hallucination patterns. Avoid using this guardrail on very short or trivial answers where the overhead of verification exceeds the risk. Also avoid deploying it without first calibrating the [POLICY] against real production examples—an overly strict policy creates a noisy flag queue that operators will ignore, while an overly permissive policy lets hallucinations through. Start with a policy tuned to catch clear violations, measure the flag rate and accuracy on production traffic, then tighten iteratively.

PRACTICAL GUARDRAILS

Use Case Fit

Where this automated guardrail prompt works, where it fails, and what you must provide before deploying it in a production pipeline.

01

Good Fit: Post-Generation Safety Nets

Use when: you need a second LLM call to audit a generated answer against retrieved context before it reaches a user. Guardrail: deploy this as an asynchronous check in your release gate, not as a real-time blocker on the critical path for low-latency applications.

02

Bad Fit: Real-Time Chat with No Latency Budget

Avoid when: your application requires sub-second response times and cannot tolerate an additional model round-trip. Guardrail: for latency-sensitive paths, use a lightweight, rules-based check (regex, NER overlap) first, and escalate only ambiguous cases to this LLM guardrail.

03

Required Input: Source Evidence and Generated Answer

Risk: the guardrail cannot detect hallucination if it only sees the final answer. Guardrail: always pass the full retrieved context and the raw generated answer as separate, clearly delimited inputs. Never rely on the answer's self-reported citations.

04

Operational Risk: The Guardrail Itself Hallucinates

Risk: the verifying LLM can make mistakes, flagging faithful statements or missing subtle fabrications. Guardrail: periodically evaluate the guardrail's output against human-annotated ground truth. Implement a 'challenger' pattern where a second guardrail spot-checks the first on a sample of traffic.

05

Operational Risk: Prompt Drift Over Model Updates

Risk: a model upgrade can change the guardrail's strictness, causing a sudden spike in false positives (blocking good answers) or false negatives (passing hallucinations). Guardrail: version-lock your guardrail prompt and model. Run a regression suite of known hallucinations and faithful answers before promoting any model or prompt change.

06

Bad Fit: Ambiguous or Subjective Content

Avoid when: the distinction between faithful synthesis and fabrication is a matter of interpretation, such as in creative writing or strategic analysis. Guardrail: restrict this guardrail to domains with objective, verifiable claims against source text. For subjective tasks, route to human review instead.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A copy-ready system prompt for an LLM-based guardrail that audits generated answers for hallucinations against source evidence.

This prompt template is designed to be deployed as a system-level instruction for a secondary LLM call that sits between answer generation and user delivery. Its job is to act as a strict factual auditor: it receives the original user question, the generated answer, and the source evidence used to produce that answer, then returns a structured JSON decision. The guardrail does not rewrite the answer; it only decides whether the answer is supported, contains fabrications, or should be blocked based on configurable policies.

text
You are a strict factual auditor. Your only job is to compare a generated answer against provided source evidence and return a structured JSON decision. You do not answer the user question. You do not improve the answer. You only audit.

## INPUT
- User Question: [USER_QUESTION]
- Generated Answer: [GENERATED_ANSWER]
- Source Evidence: [SOURCE_EVIDENCE]

## AUDIT RULES
1. Every factual claim in the Generated Answer must be directly supported by the Source Evidence. If a claim cannot be traced to a specific source passage, flag it as UNSUPPORTED.
2. If the Generated Answer contradicts the Source Evidence, flag the contradiction explicitly.
3. If the Generated Answer introduces entities, numbers, dates, names, or events not present in the Source Evidence, flag them as FABRICATED.
4. If the Generated Answer makes claims that go beyond what the Source Evidence supports (inference, speculation, extrapolation), flag them as UNSUPPORTED_INFERENCE.
5. Citations in the Generated Answer that point to sources that do not contain the cited claim are CITATION_FABRICATION.
6. If the Source Evidence is insufficient to answer the User Question at all, and the Generated Answer attempts to answer anyway, flag as INSUFFICIENT_EVIDENCE.
7. Policy violations in the Generated Answer (disallowed content, unsafe advice, regulated claims without disclaimers) must be flagged as POLICY_VIOLATION regardless of source support.

## OUTPUT SCHEMA
Return ONLY valid JSON with this exact structure:
{
  "decision": "PASS" | "FLAG" | "BLOCK",
  "decision_rationale": "One-sentence explanation of the decision.",
  "findings": [
    {
      "claim": "The exact claim text from the Generated Answer.",
      "claim_type": "SUPPORTED" | "UNSUPPORTED" | "FABRICATED" | "UNSUPPORTED_INFERENCE" | "CITATION_FABRICATION" | "CONTRADICTION" | "POLICY_VIOLATION",
      "source_reference": "The supporting or contradicting source passage, or null if none found.",
      "severity": "CRITICAL" | "HIGH" | "MEDIUM" | "LOW",
      "explanation": "Why this claim received this classification."
    }
  ],
  "block_reason": "If decision is BLOCK, the primary reason. Otherwise null.",
  "requires_human_review": true | false
}

## SEVERITY GUIDELINES
- CRITICAL: Fabricated safety instructions, medical advice, legal claims, financial figures, or personally identifiable information.
- HIGH: Fabricated facts that would mislead a reasonable user, unsupported statistics, or policy violations.
- MEDIUM: Minor unsupported details that do not change the core answer meaning.
- LOW: Stylistic embellishments or phrasing that does not introduce new factual content.

## DECISION RULES
- PASS: All claims are SUPPORTED. No findings of UNSUPPORTED, FABRICATED, or CONTRADICTION. Return empty findings array.
- FLAG: One or more MEDIUM or LOW severity findings exist. Answer may be usable with warnings. Set requires_human_review to false unless a HIGH finding also exists.
- BLOCK: Any CRITICAL or HIGH severity finding, any POLICY_VIOLATION, or INSUFFICIENT_EVIDENCE. Set requires_human_review to true.

## CONSTRAINTS
- Do not hallucinate source passages. If no source supports a claim, source_reference must be null.
- Do not re-interpret the Source Evidence. Take it literally.
- If the Generated Answer is empty or nonsensical, return BLOCK with decision_rationale explaining why.
- Never output anything except the JSON object.

To adapt this template for your application, replace the square-bracket placeholders with your actual runtime values. [USER_QUESTION] should contain the original user query. [GENERATED_ANSWER] is the full text output from your primary RAG or generation model. [SOURCE_EVIDENCE] should be the concatenated retrieved passages with their document identifiers and chunk references preserved so the auditor can cite them precisely. If your application has additional policies beyond factual accuracy—such as tone requirements, disclosure mandates, or domain-specific disclaimers—add them to the AUDIT RULES section. The severity guidelines should be calibrated to your risk tolerance: a fabricated product price in e-commerce may be HIGH, while the same in a clinical setting would be CRITICAL. Test the adapted prompt against a golden dataset of known hallucinations and correct answers before deploying it as a production guardrail. The structured JSON output is designed to be consumed by an upstream router that can either pass the answer to the user, attach a warning flag, or block delivery and escalate for human review.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Automated Guardrail Prompt. Each placeholder must be populated before the guardrail evaluates a generated answer. Missing or malformed inputs will cause the guardrail to fail closed (block) by default.

PlaceholderPurposeExampleValidation Notes

[GENERATED_ANSWER]

The full text output from the primary LLM that needs to be checked for hallucinations and policy violations.

The capital of France is Berlin. It has a population of about 2 million.

Must be a non-empty string. If null or empty, the guardrail should return a BLOCK decision with reason 'Empty answer submitted for review'.

[SOURCE_EVIDENCE]

The retrieved context, documents, or ground-truth passages that the answer claims to be based on. This is the evidence against which claims are verified.

Document A: Paris is the capital of France. Document B: The population of Paris is approximately 2.1 million.

Must be a non-empty string or structured list of passages. If null or empty, the guardrail must return a BLOCK decision with reason 'No source evidence provided for verification'. This prevents ungrounded answers from passing.

[USER_QUERY]

The original question or prompt from the end-user. Provides context for evaluating whether the answer is responsive and whether deviations from the query introduce risk.

What is the capital of France and its population?

Must be a non-empty string. If null, set to 'Unknown query'. The guardrail should flag answers that are non-responsive or introduce unrelated content as a policy violation.

[GUARDRAIL_POLICY]

A structured definition of what constitutes a violation. Includes categories like unsupported_claim, contradiction, citation_fabrication, harmful_content, and off_topic. Defines severity thresholds.

policy: {rules: [{id: 'R1', type: 'unsupported_claim', action: 'flag', severity: 'high'}], default_action: 'pass'}

Must be a valid JSON object or structured string. If null or unparseable, the guardrail must fail closed with a BLOCK decision and log a configuration error. Do not default to permissive.

[OUTPUT_SCHEMA]

The exact JSON schema the guardrail must use for its structured output. Defines the fields for decision, reasons, flagged_spans, and confidence.

{decision: 'pass'|'flag'|'block', reasons: string[], flagged_spans: [{text: string, rule_id: string}], confidence: 0.0-1.0}

Must be a valid JSON schema definition. If null, use a default schema with decision, reasons, and confidence. The guardrail must validate its own output against this schema before returning.

[CITATION_MAP]

A mapping of citation markers in the answer to their corresponding source evidence passages. Used to verify that citations are genuine and support the attached claims.

{'[1]': 'Document A: Paris is the capital...', '[2]': 'Document B: The population...'}

Can be null if the answer does not use inline citations. If provided, must be a valid JSON object mapping string keys to string values. The guardrail should flag any citation key in the answer not present in this map as a fabricated citation.

[MODEL_CONFIG]

Runtime parameters for the guardrail model itself, including temperature, max_tokens, and any model-specific instructions for structured output adherence.

{temperature: 0.0, max_tokens: 1024, response_format: 'json_object'}

Must be a valid JSON object. If null, use safe defaults: temperature=0.0, max_tokens=1024. High temperature values should trigger a warning log, as they reduce the reliability of structured guardrail decisions.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Automated Guardrail Prompt into a production RAG pipeline with validation, retries, and structured decision routing.

This guardrail sits as a synchronous post-processing step between answer generation and user delivery. The generated answer and its source context are passed to the guardrail prompt, which returns a structured JSON decision (block, flag, or pass) along with a reason and a list of specific violations. The application layer must parse this decision and route accordingly: block prevents the answer from reaching the user and triggers an escalation or fallback; flag allows delivery but surfaces warnings to a review queue or end-user UI; pass permits normal delivery. The guardrail should never modify the answer—only inspect and decide.

Wire the prompt into a dedicated service or middleware function that accepts [ANSWER] and [CONTEXT] as inputs. Use a model with strong instruction-following and JSON output capabilities (e.g., GPT-4o, Claude 3.5 Sonnet) and set response_format to json_object with a strict schema. Implement a validation layer that checks the returned JSON against the expected schema before acting on the decision. If the guardrail model returns malformed JSON or a decision outside the allowed enum (block, flag, pass), retry once with the same inputs and a stronger format reminder. After a second failure, log the raw output and escalate to a human review queue—never default to pass on parse failure in high-stakes domains. For latency-sensitive applications, run the guardrail in parallel with other post-generation checks (citation validation, PII redaction) and aggregate decisions before routing.

Instrument the guardrail with structured logging: capture the decision, violation list, model used, latency, and a hash of the input context for traceability. Store guardrail decisions alongside the answer in your observability platform to monitor hallucination rates over time and detect model drift. For regulated domains, ensure every block or flag decision is reviewable by a human within your defined SLA. Avoid using the guardrail as a substitute for retrieval quality improvements—if block rates exceed 5-10%, investigate your retrieval pipeline and evidence sufficiency before tuning the guardrail threshold. The guardrail is a safety net, not a primary quality control mechanism.

IMPLEMENTATION TABLE

Expected Output Contract

The structured JSON object the guardrail prompt must return. Use this contract to validate the model's output before acting on the block/flag/pass decision.

Field or ElementType or FormatRequiredValidation Rule

decision

enum: block | flag | pass

Must be exactly one of the three allowed string values. Reject any other value.

reason

string

Non-empty string. Must contain a concise explanation grounded in the provided [POLICY] and [EVIDENCE]. Reject if null or whitespace only.

violations

array of objects

Must be a JSON array. Reject if not present. An empty array is valid when decision is pass.

violations[].claim

string

true (per violation)

The exact text span from [GENERATED_ANSWER] that is problematic. Must be a substring match. Reject if claim text is not found in the input answer.

violations[].rule

string

true (per violation)

Must reference a specific rule ID or policy clause from the provided [POLICY] document. Reject if rule reference is fabricated.

violations[].evidence

string or null

true (per violation)

If the violation is a hallucination, this must contain the contradicting or absent source passage from [EVIDENCE]. Use null only for policy violations not related to factual grounding.

violations[].severity

enum: critical | major | minor

true (per violation)

Must be one of the three allowed severity levels. Reject any other value. Critical should be used for fabricated facts; minor for stylistic embellishments.

confidence

number

Must be a float between 0.0 and 1.0 inclusive. Represents the model's confidence in its own decision. Reject if out of range or not a number.

PRACTICAL GUARDRAILS

Common Failure Modes

Automated hallucination guardrails fail in predictable ways. These are the most common production failure modes and the concrete mitigations that keep your safety net from becoming a source of false confidence.

01

The Guardrail Hallucinates Its Own Verdict

What to watch: The guardrail model fabricates source passages, invents citation offsets, or confidently declares a hallucination where none exists. This is most common when the guardrail prompt is too open-ended or asks the model to 'find evidence' rather than 'check provided evidence.' Guardrail: Constrain the guardrail to ONLY reference evidence explicitly provided in the prompt. Use strict output schemas that require exact text spans, not paraphrased summaries. Add a secondary check that verifies the guardrail's cited evidence actually appears in the original context.

02

False Negatives from Semantic Blindness

What to watch: The guardrail passes an answer that subtly contradicts the source by changing a key qualifier, swapping a causal direction, or fabricating a plausible-sounding statistic that fits the context's domain. The guardrail model sees semantic similarity and misses the factual error. Guardrail: Include few-shot examples of subtle contradictions in the guardrail prompt. Add a specific instruction to flag any quantitative claim, date, name, or causal statement that cannot be exactly matched in the source. Pair with a deterministic numeric extraction check for high-risk fields.

03

Context Window Truncation Silently Drops Evidence

What to watch: When the generated answer plus all source evidence exceeds the guardrail model's context window, evidence is silently truncated. The guardrail then flags claims as unsupported because the relevant passage was cut off, generating false positives that block valid answers. Guardrail: Implement a pre-flight context budget check. If the combined prompt exceeds a safe threshold, split verification into chunked passes or use a longer-context model. Log and alert on any truncation event rather than silently proceeding.

04

Citation Format Mismatch Causes Spurious Failures

What to watch: The answer uses citation format A (e.g., [1]) while the guardrail prompt expects format B (e.g., (source-3)). The guardrail reports missing citations or broken references even when the answer is properly attributed. Guardrail: Standardize citation formats at the generation layer before the guardrail runs. Pass the expected citation format explicitly in the guardrail prompt. Include a pre-processing step that normalizes citation references to a canonical form before verification.

05

Guardrail Latency Blocks Real-Time Delivery

What to watch: The guardrail adds 2-5 seconds of extra model inference to every answer, breaking latency SLOs for real-time chat or voice applications. Teams respond by skipping the guardrail under load, creating an intermittent safety gap. Guardrail: Implement tiered verification: fast deterministic checks (keyword presence, citation count, length bounds) run synchronously; full LLM guardrail runs asynchronously. If the async check fails, flag the answer for retroactive correction or user notification. Use a smaller, faster model for the guardrail when latency is critical.

06

Policy Drift Between Generator and Guardrail

What to watch: The answer generation prompt and the guardrail prompt encode different policies about what constitutes acceptable behavior. The generator is allowed to say 'I don't know' while the guardrail flags abstention as a failure to answer. Or the guardrail permits stylistic embellishments that the generator was instructed to avoid. Guardrail: Maintain a single source of truth for policy definitions used by both prompts. Version policy changes and test both generator and guardrail against the same policy revision. Add a consistency check that compares guardrail decisions against the generator's system instructions.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the guardrail prompt's output quality before integrating it into a production pipeline. Each criterion targets a specific failure mode in hallucination detection.

CriterionPass StandardFailure SignalTest Method

Unsupported Claim Detection

All claims in [GENERATED_ANSWER] not directly supported by [SOURCE_EVIDENCE] are flagged with a block or flag decision.

A fabricated statistic or entity is marked as pass.

Run against a golden set of 20 answers with known fabrications. Measure recall of fabricated claims >= 0.95.

Supported Claim Pass-Through

Claims directly paraphrased from [SOURCE_EVIDENCE] receive a pass decision with a valid citation.

A verbatim quote from the source is incorrectly flagged as unsupported.

Run against 20 fully grounded answers. Measure false positive rate < 0.05.

Output Schema Compliance

Output is valid JSON matching [OUTPUT_SCHEMA] with decision, reasons, and flagged_spans fields.

Output is missing the flagged_spans array or contains a malformed decision value.

Parse output with a JSON schema validator. Assert no validation errors across 50 test runs.

Policy Violation Flagging

Content matching [POLICY_TERMS] (e.g., disallowed advice, toxic language) triggers a block decision.

A clear policy violation in the answer receives a pass.

Inject 10 answers containing known policy violations. Assert block decision for all.

Citation Fabrication Detection

A citation present in [GENERATED_ANSWER] but absent from [SOURCE_EVIDENCE] is flagged as fabricated.

A hallucinated reference to 'Section 4.2' not in the source is ignored.

Provide answers with 5 fabricated citations. Assert each is flagged in flagged_spans with reason 'fabricated_citation'.

Partial Support Handling

A claim partially supported by [SOURCE_EVIDENCE] receives a flag decision with a note specifying the unsupported portion.

A claim where the source mentions the entity but not the specific action is marked as pass.

Test with 10 partially supported claims. Assert flag decision and reasons text contains 'partial' or 'unsupported detail'.

Empty Evidence Edge Case

When [SOURCE_EVIDENCE] is empty or null, all factual claims in [GENERATED_ANSWER] are flagged.

An answer with fabricated details passes when no source evidence is provided.

Run with source_evidence: null. Assert all factual sentences in the answer are flagged.

Confidence Threshold Adherence

Claims with a confidence score below [CONFIDENCE_THRESHOLD] are escalated to flag even if not definitively fabricated.

A low-confidence claim (e.g., model unsure about a date) receives a pass.

Calibrate with 30 borderline claims. Assert flag rate correlates with confidence scores below threshold.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base guardrail prompt and a single pass/fail decision. Use a simple JSON output with block, flag, or pass plus a one-line reason. Skip severity levels and multi-claim decomposition until you validate the detection signal.

code
[SYSTEM]: You are a hallucination guardrail. Given [ANSWER] and [SOURCE_CONTEXT], output JSON with "decision" (block|flag|pass) and "reason" (one sentence).

Watch for

  • Over-blocking safe answers because the prompt is too strict
  • Missing structured output enforcement—add response_format or a parseable schema early
  • Not logging decisions; even prototypes need a decision log for calibration
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.