This prompt is designed for production engineers who need to teach a model how to repair malformed outputs, apply retry logic, or execute fallback behavior without restating the full error handling policy as procedural instructions. The core job-to-be-done is converting a stable, written policy into a compact set of broken-output to fixed-output demonstration pairs. These examples replace hundreds of tokens of rules with concrete before-and-after patterns, making the model's repair behavior more consistent and reducing per-request token costs. The ideal user is an engineer who already has a documented error handling policy and needs the model to internalize repair patterns rather than follow step-by-step instructions that can be brittle or ignored.
Prompt
Error Handling Policy to Repair Example Prompt

When to Use This Prompt
Determine if converting an error handling policy into repair examples is the right approach for your production system.
Use this approach when your error handling policy is stable enough to be captured in examples, when you need to reduce token costs by swapping verbose policy text for targeted demonstrations, and when the repair actions are deterministic enough that a well-chosen example set can cover the majority of production failure modes. This prompt is particularly effective for output repair loops where the same validation errors occur repeatedly—malformed JSON, missing required fields, incorrect enum values, or schema violations that follow predictable patterns. The resulting example set can be embedded directly in a system prompt or injected into a retry context, giving the model concrete patterns to follow without re-explaining the policy each time. You should also use this when you want to version-control your repair behavior as data (the example set) rather than as prompt text, making it easier to test, diff, and roll back changes.
Do not use this prompt when the error handling policy changes frequently, as the example generation and validation cycle will create unacceptable maintenance overhead. Avoid it when errors require real-time human judgment—for instance, when a repair action involves irreversible side effects like sending an email, modifying a database record, or making a financial transaction without a human approval gate. In these cases, the prompt should generate an escalation or hold-for-review signal rather than a repair example. Also avoid this approach when the policy is too complex to be captured in a reasonable number of examples; if you need more than 15-20 demonstration pairs to cover the policy, the examples may become contradictory or the model may struggle to generalize. In that scenario, consider breaking the policy into smaller, composable repair prompts or investing in programmatic validation and repair logic in the application layer instead.
Use Case Fit
Where error-handling-to-repair example prompts deliver value and where they introduce risk.
Good Fit: Structured Output Repair
Use when: You have a known output schema and a validator that produces specific, actionable error messages. The model needs to learn how to map a validation error to a precise structural fix. Avoid when: The error is semantic or requires external knowledge not present in the original context.
Bad Fit: Novel Failure Modes
Risk: The model encounters a broken output pattern not covered by your few-shot examples. It will hallucinate a repair or apply a mismatched fix. Guardrail: Implement a retry budget and a final fallback to a safe default or human escalation. Never let the repair loop run unbounded.
Required Input: Validator Error Payload
What to watch: Feeding the model only the broken output without the specific validator error message forces it to guess what is wrong. Guardrail: Always include the raw validator output (e.g., JSON Schema errors, Pydantic ValidationError string) as a first-class input in your repair prompt.
Operational Risk: Repair Loop Amplification
Risk: A single bad input can trigger multiple repair attempts, multiplying token cost and latency. If the repair itself introduces a new error, the system enters a costly loop. Guardrail: Set a hard limit of 1-2 repair attempts. If the output still fails validation, log the failure and return a controlled error to the user.
Operational Risk: Over-Correction Drift
Risk: The repair example teaches the model to be too aggressive, causing it to delete valid data or alter correct fields just to satisfy the validator. Guardrail: Include a negative example showing a valid output that should not be changed, paired with a no-op instruction. Test for data preservation, not just schema compliance.
Bad Fit: Policy or Safety Violations
Avoid when: The output was rejected for a content safety or policy violation. A repair example cannot safely teach the model to rephrase a disallowed answer. Guardrail: Route policy violations to a refusal or escalation path. Never use repair prompts to circumvent safety classifiers.
Copy-Ready Prompt Template
A copy-ready template that instructs the model to generate broken-output to fixed-output demonstration pairs from your error handling policy.
This template converts a natural-language error handling policy into a set of corrective few-shot examples. Instead of describing retry logic, fallback behavior, and repair patterns in prose, you provide the policy and constraints, and the model produces demonstration pairs that teach the desired behavior through worked examples. Each pair shows a broken or invalid output alongside the corrected version, making the repair pattern explicit for downstream models.
textYou are an expert prompt engineer converting an error handling policy into corrective demonstration pairs. Your task is to read the provided error handling policy and produce a set of broken-output to fixed-output example pairs that teach the repair patterns, retry logic, and fallback behavior described in the policy. ## INPUT Error Handling Policy: [POLICY_TEXT] ## CONSTRAINTS - Each example pair must show a realistic broken output and its corrected version. - Cover all distinct error categories mentioned in the policy. - Include at least one example per retry scenario, one per fallback scenario, and one per escalation scenario. - Broken outputs must reflect plausible model failures, not random noise. - Fixed outputs must strictly follow the repair rules in the policy. - Do not add repair behaviors not present in the policy. - If the policy specifies human review for certain error types, include an example where the fixed output is an escalation message rather than a repair attempt. ## OUTPUT FORMAT Return a JSON object with an "examples" array. Each element must have: - "error_category": the error type from the policy - "broken_output": the invalid model response - "fixed_output": the corrected response following the policy - "repair_action": one of "retry", "fallback", "escalate", or "self_correct" - "policy_reference": the specific clause or rule from the policy that applies ## EXAMPLE PAIR STRUCTURE { "error_category": "schema_validation_failure", "broken_output": "{ \"name\": null, \"value\": \"abc\" }", "fixed_output": "{ \"name\": \"UNKNOWN\", \"value\": \"abc\", \"confidence\": 0.0 }", "repair_action": "self_correct", "policy_reference": "Section 3.2: Null fields must be replaced with sentinel values and confidence set to 0.0" } Generate the full set of demonstration pairs now.
To adapt this template, replace [POLICY_TEXT] with your actual error handling rules. The policy should be specific enough to extract distinct error categories, repair actions, and escalation criteria. If your policy is long, consider splitting it into sections and running the prompt once per section to keep example sets focused. After generation, validate that every policy clause is covered by at least one example pair and that no repair action contradicts the written policy. For high-risk production systems, have a human reviewer spot-check the generated pairs before using them to train downstream behavior.
Prompt Variables
Required inputs for the Error Handling Policy to Repair Example Prompt. Each placeholder must be populated before the prompt can generate reliable broken-output to fixed-output demonstration pairs.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[ERROR_HANDLING_POLICY] | The source error handling rules, retry policies, or fallback procedures to convert into repair examples | Retry transient errors up to 3 times with exponential backoff. For validation failures, attempt schema normalization once. Escalate to human review if retries exhausted or confidence below 0.7. | Must contain at least one actionable rule. Parse check: policy text must include trigger conditions and recovery actions. Null not allowed. |
[FAILURE_MODE_CATEGORIES] | List of error categories the repair examples should cover | ["SchemaValidationError", "MissingRequiredField", "HallucinatedValue", "ToolTimeout", "LowConfidenceScore"] | Must be a JSON array of strings. Each category should map to at least one rule in [ERROR_HANDLING_POLICY]. Empty array allowed if policy is single-category. |
[BROKEN_OUTPUT_EXAMPLE] | A realistic malformed or failed output that the policy should address | {"customer_name": null, "order_total": "twelve dollars", "items": []} | Must be a concrete example of failure matching one of the [FAILURE_MODE_CATEGORIES]. Schema check: output should violate the expected contract in a way the policy covers. Null not allowed. |
[EXPECTED_REPAIR_OUTPUT] | The correct output after applying the error handling policy to [BROKEN_OUTPUT_EXAMPLE] | {"customer_name": "UNKNOWN", "order_total": 12.00, "items": [], "confidence": 0.45, "escalation_required": true} | Must demonstrate the repair action described in the policy. Schema check: output must be valid per the target contract. Must include any confidence or escalation fields required by the policy. |
[REPAIR_ACTION_LABEL] | Short label describing the specific repair action demonstrated | NormalizeNullToUnknown | Must be a camelCase or snake_case action identifier. Should match a verb from the policy: Retry, Normalize, Escalate, Fallback, Abstain. Validation: check label appears in policy text or is a reasonable abstraction of a policy step. |
[OUTPUT_SCHEMA] | The expected schema or contract that valid outputs must satisfy | {"type": "object", "required": ["customer_name", "order_total", "items"], "properties": {"customer_name": {"type": "string"}, "order_total": {"type": "number"}, "items": {"type": "array"}}} | Must be valid JSON Schema, TypeScript interface, or structured type definition. Schema check: parse and validate against JSON Schema spec. Null allowed only if repair is purely textual. |
[CONSTRAINTS] | Boundary conditions limiting the repair behavior | Do not invent customer names. Use UNKNOWN for missing required strings. Never hallucinate order totals. Escalate when confidence below 0.7. | Must list explicit prohibitions or limits. Each constraint should be testable: can verify whether repair output violates a constraint. Null allowed if policy has no additional constraints beyond the schema. |
[EXAMPLE_COUNT_TARGET] | Number of demonstration pairs to generate from the policy | 5 | Must be a positive integer between 1 and 20. Validation: parse as integer, check range. Higher counts require more diverse [FAILURE_MODE_CATEGORIES] coverage. Default to 3 if not specified. |
Implementation Harness Notes
How to wire the Error Handling Policy to Repair Example Prompt into a production repair loop with validation, retries, and escalation.
This prompt converts error-handling policies into corrective demonstration pairs, but its real value emerges when it's embedded in a repair harness—a pipeline that catches a model's malformed output, feeds the error and the original context into this prompt, and uses the generated examples to guide a second model call. The harness should treat the prompt's output as a structured artifact: a set of broken-output to fixed-output pairs that can be cached, versioned, and audited. Do not use this prompt as a one-off fix; wire it into a loop where validation failures trigger example generation, and the examples are appended to the retry prompt's few-shot block.
The implementation should follow a validate → generate → retry → escalate pattern. First, run the primary model's output through a deterministic validator (schema check, regex, field presence). On failure, call this prompt with the [ERROR_HANDLING_POLICY], the [FAILED_OUTPUT], and the [VALIDATION_ERROR]. Parse the resulting repair examples and inject them into a retry prompt that includes the original [INPUT], the [OUTPUT_SCHEMA], and a [CONSTRAINTS] block. Set a maximum of two retries before escalating to a human review queue or a fallback model. Log every repair attempt with the error type, the generated examples, and the final outcome to build a dataset for future fine-tuning or policy refinement.
Avoid wiring this prompt directly into a customer-facing response without a human review gate if the error involves regulated data, financial calculations, or clinical information. The generated repair examples are themselves model outputs and can contain subtle hallucinations—especially when the policy document is long or ambiguous. Before deploying, run a regression suite: take 20 known failure cases, generate repair examples, and measure whether the retry loop resolves them without introducing new errors. If the repair success rate drops below 90%, revisit the policy document for clarity or add a human-in-the-loop step before the final output is released.
Expected Output Contract
Defines the required structure, types, and validation rules for each demonstration pair generated by the Error Handling Policy to Repair Example Prompt. Use this contract to validate the model's output before integrating it into a retry or self-correction pipeline.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
[ERROR_CATEGORY] | string | Must match one of the categories provided in [ERROR_POLICY_DOCUMENT]. Check against an allowed-values list. | |
[BROKEN_OUTPUT] | string | Must be a syntactically or semantically invalid version of the target schema. Validate that it fails against [OUTPUT_SCHEMA]. | |
[FIXED_OUTPUT] | string or object | Must be a valid instance of [OUTPUT_SCHEMA]. Parse check required. Must correct the specific error in [BROKEN_OUTPUT] without introducing unrelated changes. | |
[REPAIR_INSTRUCTION] | string | Must be a concise, imperative instruction explaining the correction. Length must be under 300 characters. No markdown allowed. | |
[REQUIRES_ESCALATION] | boolean | Must be true if the error is unfixable or requires external data, otherwise false. If true, [FIXED_OUTPUT] must be an escalation message matching [ESCALATION_FORMAT]. | |
[RETRY_STRATEGY] | string | Must be one of: 'immediate_retry', 'backoff_retry', 'no_retry'. If [REQUIRES_ESCALATION] is true, this must be 'no_retry'. | |
[GROUNDING_SOURCE] | string or null | If the repair relies on a specific policy clause from [ERROR_POLICY_DOCUMENT], provide the exact quote. Otherwise, null. Citation check required if not null. |
Common Failure Modes
When converting error handling rules into repair examples, these failures surface first in production. Each card identifies a specific breakage pattern and the guardrail that prevents it.
Repair Example Teaches Wrong Fix
What to watch: The model learns a repair pattern from examples that doesn't match the actual error. A malformed JSON example paired with a fix for missing fields teaches the model to add fields when it should fix brackets. Guardrail: Validate that each broken-output to fixed-output pair addresses exactly one error class. Run the repair prompt against known error cases and confirm the fix matches the intended correction type.
Over-Escalation from Negative Examples
What to watch: Negative examples showing when to escalate cause the model to escalate too aggressively, refusing to repair errors it could handle. A few 'too broken to fix' examples can poison the repair threshold. Guardrail: Balance negative examples with positive repair examples at a minimum 3:1 ratio. Add explicit boundary conditions in the prompt: 'Only escalate when [SPECIFIC_CRITERIA], otherwise attempt repair.'
Hallucinated Repair for Valid Outputs
What to watch: The model applies repair logic to outputs that are already valid, introducing errors where none existed. This happens when repair examples don't include a 'no repair needed' demonstration. Guardrail: Include at least one example showing a valid output that requires no changes, with the instruction 'Output unchanged when input is already valid.' Add a pre-check step that validates before attempting repair.
Repair Drift Across Model Versions
What to watch: Repair examples that worked on one model version produce different fixes on another. A JSON structure repair that added quotes on GPT-4 might restructure the entire object on Claude. Guardrail: Test repair examples against every target model in your routing matrix. Store model-specific repair example sets. Add output schema validation as a hard gate regardless of which model performed the repair.
Incomplete Repair from Partial Examples
What to watch: Examples that show fixing one error type leave other errors untouched. A repair example fixing missing fields doesn't teach the model to also fix enum violations in the same output. Guardrail: Include multi-error repair examples that show fixing several violation types in one pass. Run repair prompts against outputs with compound errors and verify all violations are resolved, not just the demonstrated type.
Retry Loop from Unchanged Output
What to watch: The repair prompt returns the same broken output or a trivially different but still invalid version, causing infinite retry loops in production. Guardrail: Add a strict output comparison check: if the repaired output matches the input or still fails validation after one repair attempt, stop retrying and escalate. Include a max-retry counter in the application layer, not just the prompt.
Evaluation Rubric
Use this rubric to test the quality of generated error-handling example pairs before shipping them to production. Each criterion targets a specific failure mode common in repair demonstrations.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Repair Accuracy | The [FIXED_OUTPUT] correctly resolves the error described in the [ERROR_DESCRIPTION] without introducing new issues. | The fix is cosmetic, ignores the root cause, or creates a new schema violation. | Run a diff between [BROKEN_OUTPUT] and [FIXED_OUTPUT]; manually verify the change directly addresses the error signal. |
Error Signal Fidelity | The [BROKEN_OUTPUT] contains a realistic, specific error that matches the [ERROR_DESCRIPTION]. | The broken example is trivially wrong, nonsensical, or does not actually exhibit the target error. | Parse [BROKEN_OUTPUT] against the [OUTPUT_SCHEMA]; confirm the schema violation or logical error matches the description. |
Retry Logic Embedding | The [FIXED_OUTPUT] demonstrates a corrective action that would succeed on a retry, not just a final answer. | The fix assumes access to information not present in the original [INPUT] or hallucinates data to appear correct. | Check if [FIXED_OUTPUT] uses only fields derivable from [INPUT]; flag any introduced entities or values not in the source. |
Fallback Appropriateness | If repair is impossible, the example demonstrates a valid fallback (e.g., null field, explicit abstention) instead of a forced fix. | The [FIXED_OUTPUT] fabricates a plausible answer when the [BROKEN_OUTPUT] was unfixable due to missing data. | Identify cases where [INPUT] lacks required data; verify [FIXED_OUTPUT] uses a defined fallback pattern like |
Escalation Boundary | The example pair teaches when to escalate to a human or stop retrying, not just how to auto-fix. | Every example shows a successful auto-repair; no demonstration of giving up or requesting human review. | Count the ratio of repair vs. escalation examples; ensure at least one pair demonstrates a stop condition or human handoff. |
Schema Compliance | The [FIXED_OUTPUT] strictly validates against the target [OUTPUT_SCHEMA] with zero errors. | The 'fixed' output still fails schema validation or passes only because the schema is too loose. | Run a programmatic validator (e.g., JSON Schema, Pydantic) on [FIXED_OUTPUT]; reject any example that fails. |
Token Efficiency | The example pair is compact and teaches the pattern without verbose commentary or redundant instructions. | The demonstration is wrapped in long explanations, repeating the error description or adding meta-commentary. | Compare token count of the example block to the original verbose instruction; the example set should be significantly shorter. |
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
Use the base prompt with a single broken-output/fixed-output pair. Keep the error policy simple (e.g., one retry rule, one fallback). Skip schema validation in the prompt; rely on post-processing in application code.
code[ERROR_POLICY_RULE]: If output is malformed JSON, retry once with stricter format instructions. [BROKEN_OUTPUT]: { "status": "ok" "data": null } [FIXED_OUTPUT]: { "status": "ok", "data": null }
Watch for
- Missing schema checks leading to silent format drift
- Overly broad repair instructions that change correct outputs
- No retry limit, causing infinite loops in edge cases

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