Inferensys

Prompt

Retry Budget for Hallucination Self-Correction Prompt

A practical prompt playbook for using a Retry Budget for Hallucination Self-Correction Prompt in production AI workflows. This playbook provides a copy-ready template that cross-checks claims against provided context, limits regeneration attempts, and escalates to human review when the budget is exhausted.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the operational context for injecting a retry budget into a hallucination self-correction loop, targeting accuracy-critical product teams.

This prompt is a recovery and escalation control mechanism, not a primary answer generator. Its job is to act as a strict verifier within a retry loop after an initial model response has been flagged for containing unsupported claims. The ideal user is an AI product team that has already built a reliable hallucination detection mechanism—such as an LLM judge, a claim extraction pipeline, or a source-grounding validator—and now needs a predictable, cost-controlled way to attempt self-correction before falling back to human review. The required context includes the original user query, the flagged model response, the source evidence that should have grounded the answer, and the remaining retry budget as an integer.

You should use this prompt when the cost of a hallucination is high—for example, in clinical documentation, legal research, or financial audit summaries—and when you have a defined human review queue ready to receive escalations. The prompt enforces a hard limit on regeneration attempts by embedding the remaining budget directly into the instructions. When the budget reaches zero, the model is forced to output a structured escalation payload instead of another answer attempt, preventing infinite loops and unbounded latency. Do not use this prompt if you lack a reliable hallucination detector, as feeding false positives into the loop will degrade user experience without improving accuracy. It is also inappropriate for low-stakes creative or conversational tasks where a human review queue would be overkill.

Before integrating this prompt, ensure your harness tracks the retry budget per request, injects the current budget value into the [RETRY_BUDGET_REMAINING] placeholder, and can parse the structured escalation payload when the budget is exhausted. The next step is to pair this prompt with an eval suite that measures factual drift across retries—checking whether corrections introduce new unsupported claims—and to set a maximum budget based on your latency and cost tolerance. Avoid using this prompt as a substitute for improving your initial answer-generation prompt or your retrieval quality; it is a safety net, not a foundation.

PRACTICAL GUARDRAILS

Use Case Fit

Where the hallucination self-correction retry budget works, where it fails, and the operational preconditions required before deployment.

01

Good Fit: Grounded Generation with Verifiable Context

Use when: the model has access to a provided context window, retrieved documents, or a structured knowledge base that can be used to cross-check claims. Guardrail: The retry prompt must explicitly instruct the model to cite source spans; without a ground-truth anchor, self-correction becomes hallucination laundering.

02

Bad Fit: Open-Domain or Creative Generation

Avoid when: the task is creative writing, brainstorming, or open-ended Q&A where no source of truth exists in the prompt. Guardrail: Self-correction prompts in these scenarios often replace one hallucination with another. Escalate to human review or switch to a confidence-threshold model router instead of retrying.

03

Required Input: Source Material and Claim Mapping

What to watch: The prompt cannot self-correct if it only receives the previous hallucinated output. Guardrail: The retry payload must include the original user query, the full retrieved context, and a structured extraction of the unsupported claims. Without this, the model has no signal to correct against.

04

Operational Risk: Factual Drift Across Retries

What to watch: Each retry can introduce new, subtler hallucinations while fixing the original error. Guardrail: Run a semantic similarity or factual-consistency eval between retry attempts. If the output drifts significantly from the source context, stop retrying and escalate immediately.

05

Operational Risk: Budget Exhaustion Without Improvement

What to watch: The retry loop consumes tokens and latency but produces no measurable improvement in factual accuracy. Guardrail: Implement a monotonic improvement check. If the factual-consistency score does not increase between attempts, break the loop and escalate to a human reviewer or a fallback model.

06

Precondition: Human-in-the-Loop for Regulated Domains

What to watch: In healthcare, legal, or financial contexts, a self-corrected output can still carry liability. Guardrail: The retry budget must terminate in a human review queue, not silent acceptance. The escalation payload must include the full retry history and the final corrected output for audit purposes.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable system prompt that enforces a retry budget for hallucination self-correction by cross-checking claims against provided context and escalating when the budget is exhausted.

The following prompt template is designed to be injected as a system message on a retry attempt after a hallucination has been detected by an upstream validator. Its job is to force the model to regenerate its response by strictly grounding every factual claim in the provided [CONTEXT] and to self-audit its own output. The prompt enforces a hard retry budget: if the model cannot produce a fully grounded response within the allowed attempts, it must output a structured escalation payload instead of another hallucinated answer. This prevents infinite correction loops and ensures that unresolved failures reach a human reviewer with complete diagnostic information.

text
You are a fact-correction assistant operating under a strict retry budget.

## RETRY STATE
- Current attempt: [RETRY_ATTEMPT_NUMBER] of [MAX_RETRY_ATTEMPTS]
- Previous failure reason: [PREVIOUS_FAILURE_REASON]

## INPUT
User query: [USER_QUERY]
Previous response that was flagged for hallucination: [PREVIOUS_RESPONSE]

## GROUNDING CONTEXT
Use ONLY the following context to answer. If the context is insufficient, state that explicitly.
[CONTEXT]

## INSTRUCTIONS
1. Cross-check every factual claim in the previous response against the context above.
2. Identify and discard any claim that cannot be directly attributed to the context.
3. Generate a new response that contains ONLY claims supported by the context.
4. For each factual statement in your new response, append a citation tag referencing the specific source chunk in the context (e.g., [Source: chunk-3]).
5. If the context does not contain enough information to answer the user query, respond with: "INSUFFICIENT_CONTEXT: [explanation of what is missing]"
6. If you cannot produce a fully grounded response, do not guess. Instead, output the escalation format below.

## ESCALATION CONDITION
If this is the final allowed attempt (attempt [MAX_RETRY_ATTEMPTS]) and you still cannot produce a fully grounded response, you MUST output ONLY the following JSON and nothing else:
{
  "status": "ESCALATE_TO_HUMAN",
  "retry_attempts_exhausted": [MAX_RETRY_ATTEMPTS],
  "user_query": "[USER_QUERY]",
  "failure_summary": "[Concise description of why grounding failed across all attempts]",
  "last_ungrounded_claims": ["[Claim 1 that could not be verified]", "[Claim 2]"]
}

## OUTPUT FORMAT
- If grounded: Provide the answer with inline citations.
- If insufficient context: Output "INSUFFICIENT_CONTEXT" with an explanation.
- If escalating: Output ONLY the JSON object above.

To adapt this template, replace the square-bracket placeholders with values from your application's retry harness. [RETRY_ATTEMPT_NUMBER] and [MAX_RETRY_ATTEMPTS] should be injected by your orchestration layer, not the model. [PREVIOUS_FAILURE_REASON] should contain the specific output from your hallucination detector (e.g., "Claim 'Revenue grew 20%' not found in context"). [CONTEXT] must be the exact set of retrieved documents or source chunks that the model is permitted to use. The escalation JSON schema should match the contract expected by your human review queue or incident management system. For high-risk domains such as healthcare or finance, ensure that the escalation payload includes a full trace of all previous attempts and that the human reviewer is clearly instructed not to rely on any ungrounded claims from the retry history.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Retry Budget for Hallucination Self-Correction Prompt. Each variable must be populated before the prompt is assembled and sent to the model.

PlaceholderPurposeExampleValidation Notes

[ORIGINAL_QUERY]

The user's original question or instruction that triggered the initial response.

What were the key findings from the Q3 clinical trial?

Must be a non-empty string. Check that it matches the original user input exactly to prevent drift.

[PRIOR_RESPONSE]

The model's previous response that is suspected to contain hallucinations.

The trial showed a 45% reduction in symptoms across all cohorts.

Must be a non-empty string. Compare against [SOURCE_CONTEXT] to identify unsupported claims.

[SOURCE_CONTEXT]

The authoritative text passages, documents, or data the model should have used to generate its response.

Section 4.2: The primary endpoint showed a 23% reduction (p=0.03) in the high-dose cohort.

Must be a non-empty string. This is the ground truth for cross-checking. If null, the prompt must escalate immediately.

[HALLUCINATION_FLAGS]

A list of specific claims from [PRIOR_RESPONSE] that could not be verified against [SOURCE_CONTEXT].

['45% reduction claim', 'all cohorts statement']

Must be a valid JSON array of strings. If empty, the retry loop should terminate as no hallucinations were detected.

[RETRY_ATTEMPT_NUMBER]

The current retry count, used to enforce the budget and prevent infinite loops.

2

Must be an integer >= 1. The harness must increment this before each call and compare against [MAX_RETRY_BUDGET].

[MAX_RETRY_BUDGET]

The hard limit on regeneration attempts before escalating to human review.

3

Must be an integer >= 1. The harness must abort the loop and trigger the escalation path when [RETRY_ATTEMPT_NUMBER] exceeds this value.

[OUTPUT_SCHEMA]

The exact JSON schema the corrected response must conform to.

{ 'answer': 'string', 'citations': ['string'], 'corrections_made': ['string'] }

Must be a valid JSON Schema object. The harness must validate the final output against this schema before accepting it.

[ESCALATION_RECIPIENT]

The identifier for the human or system queue that receives the escalation payload when the retry budget is exhausted.

Must be a non-empty string. The harness must route the escalation payload to this recipient without further model processing.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the retry budget prompt into an application harness with validation, state tracking, and escalation logic.

The retry budget prompt is not a standalone script; it is a decision node inside a retry loop. The application harness must track the number of correction attempts, the cumulative cost or latency incurred, and the quality delta between each regeneration. Before invoking the prompt, the harness should inject the current attempt count, the maximum budget, the original context, the previous output, and any validator feedback into the prompt's placeholders. The prompt returns a structured decision—retry, escalate, or accept—which the harness must enforce without allowing the model to override the budget limits.

A concrete implementation wraps the prompt in a retry controller with these responsibilities: (1) maintain an atomic counter for attempts and a stopwatch for wall-clock budget; (2) call a factuality validator (e.g., an NLI model or a citation-overlap check) after each generation to produce structured error feedback; (3) inject [ATTEMPT_NUMBER], [MAX_ATTEMPTS], [PREVIOUS_OUTPUT], [VALIDATION_ERRORS], and [CONTEXT] into the prompt; (4) parse the model's JSON decision (action, rationale, confidence) and enforce it. If the model returns action: escalate or the attempt counter exceeds the budget, the harness must package the full retry history into an escalation payload and route it to a human queue or a fallback model. Log every attempt's input, output, validator score, and decision for auditability.

Validation and safety checks are critical. Before accepting a self-corrected output, run a regression check: compare the new output's factual claims against the original context to detect factual drift introduced during correction. A common failure mode is the model inventing new details to satisfy the validator while drifting further from the source. If the validator score does not improve across two consecutive retries, the harness should force escalation regardless of remaining budget. For high-stakes domains, require human approval on any output that required more than one correction attempt, even if the validator passes. Wire the escalation payload to include the original query, all retry outputs, validator scores, and the model's own rationale for each attempt so the human reviewer has full context.

IMPLEMENTATION TABLE

Expected Output Contract

The model must return a JSON object defining the retry budget and escalation plan. Validate each field before allowing the harness to consume the output.

Field or ElementType or FormatRequiredValidation Rule

retry_budget

object

Must contain max_attempts, current_attempt, and budget_remaining fields. Schema check required.

retry_budget.max_attempts

integer

Must be >= 1 and <= [MAX_RETRY_LIMIT]. Parse check: non-negative integer.

retry_budget.current_attempt

integer

Must be >= 1 and <= max_attempts. Parse check: non-negative integer.

retry_budget.budget_remaining

integer

Must equal max_attempts - current_attempt. Arithmetic validation required.

escalation_decision

string

Must be one of: retry, escalate_to_human, fallback_response, abort. Enum check required.

escalation_reason

string

Required when escalation_decision is not retry. Must reference specific failure mode from [ERROR_CONTEXT].

hallucination_audit

array

Each item must contain claim, source_grounding, and verdict fields. Verdict must be supported, unsupported, or contradicted. Citation check required.

next_step_instructions

string

Required when escalation_decision is escalate_to_human. Must summarize failure history and recommended human action. Null allowed for retry decisions.

PRACTICAL GUARDRAILS

Common Failure Modes

Hallucination self-correction retries can silently degrade accuracy if not tightly controlled. These failure modes show what breaks first and how to guard against it.

01

Factual Drift Across Retries

What to watch: The model replaces one hallucination with another, drifting further from the source context with each retry. The output sounds more confident but becomes less accurate. Guardrail: Run a fact-verification eval after every retry, comparing claims against the original context. Abort retries if the factual overlap score decreases or drops below a defined threshold.

02

Retry Loop Without Improvement

What to watch: The model regenerates nearly identical outputs with the same unsupported claims, consuming the retry budget without any measurable improvement. Guardrail: Implement a semantic similarity check between retry outputs. If consecutive attempts exceed a similarity threshold (e.g., >0.95) without passing validation, break the loop and escalate immediately.

03

Budget Exhaustion with No Escalation Payload

What to watch: The retry budget is fully consumed, but the system fails to package the failure context for human review, leaving operators with no actionable information. Guardrail: Require a structured escalation payload as a mandatory output when the budget is exhausted. The payload must include the original request, all retry outputs, eval scores per attempt, and the specific unsupported claims.

04

Over-Correction Removing Correct Information

What to watch: In attempting to fix one hallucinated detail, the model strips out or contradicts previously correct, source-grounded statements. Guardrail: Perform a claim-level diff between the original output and the retry output. Flag any correct claims that were removed or altered. Require the retry prompt to explicitly instruct the model to preserve verified claims.

05

Context Window Dilution from Retry History

What to watch: Packing all previous failed attempts and error messages into the retry context window pushes source evidence out, causing more hallucinations. Guardrail: Use a compressed failure summary (specific unsupported claims and the evidence that contradicts them) instead of full retry history. Set a maximum token budget for retry context to preserve source evidence.

06

Silent Hallucination Passing Weak Eval

What to watch: The retry output passes a lenient or poorly calibrated eval check while still containing subtle factual errors that a human would catch. Guardrail: Use a two-stage eval: an automated factual-consistency check for fast filtering, followed by a stricter LLM-as-judge eval with a calibrated rubric. Escalate any output that passes automation but fails the judge review.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test whether the retry budget prompt produces safe, correct, and production-ready self-correction behavior before deployment.

CriterionPass StandardFailure SignalTest Method

Retry limit enforcement

Prompt stops retrying after [MAX_RETRIES] attempts and returns the escalation payload

Output shows a retry attempt beyond [MAX_RETRIES] or loops without escalation

Run a test case that triggers persistent hallucination and count the retry attempts in the trace

Hallucination detection accuracy

Prompt correctly identifies unsupported claims not present in [CONTEXT] on each retry

Prompt marks a grounded claim as hallucinated or misses a fabricated detail

Provide a response with one grounded claim and one fabricated claim; verify the detection output flags only the fabricated claim

Factual drift prevention

Each retry output preserves all previously verified claims and only corrects the hallucinated portion

A previously correct claim is altered or removed in a subsequent retry

Compare the set of claims across retry outputs using a diff tool; no correct claim should disappear

Escalation payload completeness

Escalation output includes [RETRY_HISTORY], [FAILURE_SUMMARY], [LAST_OUTPUT], and [RECOMMENDED_ACTION]

Escalation payload is missing one or more required fields or contains empty values

Parse the escalation output against the [OUTPUT_SCHEMA] and validate all required fields are present and non-null

Context grounding fidelity

Every corrected claim in the final output has a direct match or paraphrase in [CONTEXT]

A corrected claim introduces new information not present in [CONTEXT]

Extract all claims from the final output and run a sentence-level entailment check against [CONTEXT]

Confidence threshold behavior

Prompt escalates when [CONFIDENCE_SCORE] remains below [CONFIDENCE_THRESHOLD] after retries

Prompt returns a low-confidence answer without escalation or escalates when confidence is above threshold

Inject a test case where context is insufficient; verify the output escalates rather than guessing

Retry budget exhaustion message

Final escalation message clearly states the budget is exhausted and does not suggest further retries

Message implies the user should try again or the system will retry later

Check the escalation message text for forbidden phrases like 'try again' or 'attempting another retry'

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base self-correction loop using a simple counter. Instruct the model to cross-check claims against [CONTEXT] and regenerate if unsupported. Limit retries to 2 and log each attempt.

code
You are a fact-checking assistant. Review your previous response against [CONTEXT].
If any claim is not directly supported by [CONTEXT], regenerate the response using only supported facts.
If you cannot find support, state "Insufficient evidence."
This is attempt [ATTEMPT_NUMBER] of [MAX_ATTEMPTS].

Watch for

  • Missing attempt counter in the prompt
  • Model regenerating the same hallucination with different wording
  • No distinction between minor rewording and factual drift
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.