This prompt is for platform architects and AI reliability engineers who need to build an automated, multi-pass repair loop for structured outputs. The core job-to-be-done is turning a malformed model response (JSON, XML, YAML, or typed objects) into a valid, schema-conformant payload without losing semantic content. The ideal user is someone integrating LLM outputs into a production API pipeline where downstream parsers are strict and manual repair is not an option. You should use this prompt when a single retry is insufficient, and you need a controlled loop that feeds escalating validation errors back to the model until the output is clean or a retry budget is exhausted.
Prompt
Self-Correction Loop Prompt for Structured Output

When to Use This Prompt
Define the job, the ideal user, required inputs, and the operational boundaries for the Self-Correction Loop Prompt.
Before using this prompt, you must have three concrete inputs: the original model response that failed validation, the exact validation error messages from your parser (e.g., Ajv, Pydantic, Xerces), and the target schema or interface definition. The prompt is designed to be called iteratively within an application harness, not as a one-shot fix. Each iteration appends the previous failure context, instructing the model to fix only the identified issues while preserving all valid fields. This constraint is critical—without it, the model may rewrite the entire payload and introduce new errors. You should not use this prompt when the output is semantically nonsensical or when the failure is due to a fundamental misunderstanding of the task rather than a formatting error; in those cases, escalate to a human reviewer or restart with a clarified original prompt.
The prompt is most effective when paired with a strict retry budget (typically 3-5 attempts) and an escalation threshold. After each failed repair, the harness should check if the error count is decreasing. If errors are not converging, or if the repair introduces semantic drift (e.g., changing a date or a name to 'fix' a format), the loop should break and escalate. This prompt is not a substitute for robust initial schema prompting; it is a safety net for production systems where even well-prompted models occasionally produce malformed output under load, with long contexts, or when using smaller models. Wire this into your inference pipeline after your primary validation step, and always log each repair attempt for observability and debugging.
Use Case Fit
Where the self-correction loop prompt works, where it fails, and the operational preconditions required before wiring it into a production pipeline.
Good Fit: Deterministic Validators
Use when: you have a strict, programmatic validator (JSON Schema, Pydantic, type checker) that returns precise, field-level error messages. The loop prompt can feed these exact errors back to the model for targeted correction. Guardrail: always parse validator output into structured fix instructions before injecting them into the retry prompt.
Bad Fit: Semantic or Subjective Errors
Avoid when: the output is technically valid but factually wrong, poorly reasoned, or stylistically off. A self-correction loop that only checks structural validity will not catch hallucinations or bad logic. Guardrail: pair this prompt with a separate semantic evaluation or fact-checking step before accepting the output.
Required Input: Structured Error Context
Risk: feeding raw, unstructured error logs to the model leads to incomplete or incorrect repairs. Guardrail: pre-process all validation errors into a schema that maps each error to a specific field path, the invalid value, the constraint violated, and a suggested fix action before the retry prompt sees it.
Operational Risk: Infinite Retry Loops
Risk: a model may repeatedly produce the same invalid output, consuming tokens and latency without progress. Guardrail: enforce a hard retry budget (e.g., 3 attempts) and an escalation threshold. After the budget is exhausted, log the failure, salvage any valid fields, and route to a human or a dead-letter queue.
Operational Risk: Semantic Drift
Risk: each repair attempt can subtly alter the original meaning, especially when the model infers missing required fields. Guardrail: compute a repair confidence score after each fix. If confidence drops below a threshold or the number of altered fields exceeds a limit, escalate instead of accepting the repaired output silently.
Bad Fit: Non-Deterministic or Vague Schemas
Avoid when: the target schema is ambiguous, has conflicting constraints, or relies on natural-language descriptions without machine-readable validation. The loop will oscillate between different interpretations. Guardrail: formalize the schema with strict types, enums, and required fields before enabling automated retry loops.
Copy-Ready Prompt Template
A reusable, multi-pass self-correction prompt that iteratively repairs structured output against a schema and validation errors until valid or the retry budget is exhausted.
This template implements a controlled self-correction loop for structured output. It is designed to be called repeatedly by an application harness, not by an end user. On each pass, the prompt receives the original task, the previously failed output, and the specific validation errors that caused rejection. The model is instructed to fix only the identified issues while preserving all other content, and to stop and escalate if the output becomes unrepairable. The application layer controls the loop count; the prompt itself defines the repair discipline and the escalation condition.
textYou are a structured output repair agent operating inside an automated correction loop. Your task is to produce a valid output that satisfies the original request and the output schema. You have previously produced an output that failed validation. You will now receive the original request, the failed output, and a list of specific validation errors. Your job is to correct ONLY the identified errors and return a complete, valid output. ## ORIGINAL REQUEST [ORIGINAL_PROMPT] ## OUTPUT SCHEMA [OUTPUT_SCHEMA] ## PREVIOUS FAILED OUTPUT [FAILED_OUTPUT] ## VALIDATION ERRORS [VALIDATION_ERRORS] ## REPAIR ATTEMPT This is repair attempt [ATTEMPT_NUMBER] of [MAX_ATTEMPTS]. ## CONSTRAINTS - Fix ONLY the fields and structures identified in the validation errors. - Do not alter any other content, values, or structure. - If a required field is missing and no context exists to infer a safe value, insert an explicit null and add a "repair_note" field explaining the missing data. - If an enum value is invalid, map it to the closest valid enum member based on semantic similarity. If no safe mapping exists, use null and add a repair note. - If a data type is wrong, coerce it to the correct type where the conversion is lossless. If coercion would lose information, use null and add a repair note. - If the output is truncated, close all open brackets, tags, or structures. Flag any unrecoverable fields with a repair note. - If the errors cannot be repaired without guessing or fabricating data, set a top-level "repairable" field to false and explain why in "escalation_reason". ## REQUIRED OUTPUT FORMAT Return a JSON object with exactly these top-level keys: { "repairable": true or false, "repair_notes": ["string"], "output": { ... } } If repairable is false, "output" must be null. If repairable is true, "output" must contain the fully corrected payload conforming to the OUTPUT SCHEMA.
To adapt this template, replace the square-bracket placeholders with values from your application context. [ORIGINAL_PROMPT] should contain the full user request and any initial instructions. [OUTPUT_SCHEMA] should be the complete JSON Schema, TypeScript interface, or a plain-text description of required fields, types, and constraints. [FAILED_OUTPUT] is the raw string the model produced on the previous attempt. [VALIDATION_ERRORS] should be the structured or raw error messages from your validator, formatted so the model can map each error to a specific field and failure reason. [ATTEMPT_NUMBER] and [MAX_ATTEMPTS] let the model adjust its repair strategy as the budget shrinks. The application harness must parse the repairable flag and either use the corrected output or route to the escalation path defined in your Escalation Threshold Prompt.
Prompt Variables
Inputs required by the self-correction loop prompt to reliably repair structured outputs. Each variable must be populated by the application harness before the retry request is assembled.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[ORIGINAL_PROMPT] | The initial user or system instruction that produced the failed output | Generate a JSON object with fields: name, age, email | Must be non-empty string; log for debugging but never modify in retry |
[FAILED_OUTPUT] | The raw, malformed model response that failed validation | {"name": "Alice" "age": 30} | Must be non-empty string; preserve exactly as received including whitespace and errors |
[TARGET_SCHEMA] | The JSON Schema, interface definition, or format specification the output must satisfy | {"type": "object", "required": ["name", "age"]} | Must be valid JSON Schema or structured format spec; validate before injection |
[VALIDATION_ERRORS] | Structured list of errors from the validator, mapped to fields and fix actions | [{"field": "age", "error": "type_mismatch", "expected": "number"}] | Must be array of objects with field and error keys; parse from raw validator output before injection |
[RETRY_ATTEMPT] | Current retry count, starting at 1 and incrementing with each loop iteration | 2 | Must be integer >= 1; used to escalate specificity and decide when to stop retrying |
[MAX_RETRIES] | Hard limit on repair attempts before escalation or partial salvage | 3 | Must be integer >= 1; enforced by harness, not by model; stop loop when [RETRY_ATTEMPT] exceeds this value |
[REPAIR_INSTRUCTIONS] | Escalating guidance keyed to retry attempt number, telling the model how aggressively to fix errors | Attempt 1: Fix only syntax. Attempt 2: Coerce types. Attempt 3: Infer missing fields or escalate. | Must be a map or conditional string keyed by attempt number; define in harness config, not in prompt template |
Implementation Harness Notes
How to wire the self-correction loop into a production application with validation, retry budgets, and observability.
The self-correction loop prompt is not a standalone artifact; it is the core instruction set inside a retry harness that your application code orchestrates. The harness is responsible for calling the model, validating the structured output against a schema, collecting error details, and deciding whether to retry, salvage partial results, or escalate to a human. The prompt itself should be treated as a parameterized template that receives the original task, the failed output, and a structured error report on each iteration. Do not rely on the model to track its own retry count or decide when to stop—that logic belongs in the application layer to prevent infinite loops and unbounded costs.
A robust implementation follows a tight loop: (1) Send the initial prompt with the task, output schema, and constraints. (2) Parse the response and validate it against the expected schema using a library like Ajv (JSON), Pydantic (Python), or Xerces (XML). (3) If validation passes, return the output. If it fails, increment a retry counter and check against the retry budget. (4) Construct a retry payload containing the original task, the failed output, and a machine-readable error report mapping each failure to a specific field and violation type. (5) Feed this payload into the self-correction prompt template and go back to step 2. The retry budget should be small—typically 2 to 4 attempts—because beyond that, the model is unlikely to converge, and the risk of semantic drift or hallucinated fixes increases sharply.
Logging and observability are critical at every stage. Record each attempt's raw output, validation errors, repair actions taken, and the final outcome (success, partial salvage, or escalation). This trace data enables debugging of brittle prompts, identification of recurring schema violations that may indicate a poorly specified output contract, and cost attribution for retry overhead. For high-risk domains such as healthcare, finance, or legal workflows, insert a human review gate after any repair that modifies a field value rather than just reformatting it. A repair that changes a patient's medication name or a contract's liability clause must never be accepted silently. The harness should flag such modifications and route them to a review queue with the original and repaired values side by side.
Model choice matters for this pattern. Models with strong instruction-following and structured output capabilities (such as GPT-4o, Claude 3.5 Sonnet, or fine-tuned variants) will converge faster and require fewer retries. Weaker or smaller models may struggle to isolate the specific field that failed and instead regenerate the entire output, risking new errors. If you must use a smaller model, consider narrowing the repair scope by sending only the failed field's context rather than the full output. Finally, never wire this loop into a synchronous user-facing request path without a timeout. A stalled retry loop will block the user. Instead, return a partial result or an escalation message after the budget is exhausted, and process further repair attempts asynchronously if needed.
Expected Output Contract
Define the exact fields, types, and validation rules for the self-correction loop's output. Use this contract to programmatically gate the retry loop and decide when to stop.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
final_output | object | Must be a valid JSON object that passes the provided [TARGET_SCHEMA] validation. If null, the loop failed. | |
is_valid | boolean | Must be true if final_output is present and passes schema validation. Must be false if the retry budget is exhausted. | |
repair_attempts | integer | Must be an integer between 0 and [MAX_RETRIES]. Must equal the number of repair iterations executed. | |
repair_log | array of objects | Each object must contain an attempt_number (integer), an error_summary (string) from the validator, and the action_taken (string) to fix it. | |
escalation_reason | string or null | Required if is_valid is false. Must be a non-empty string from the [ESCALATION_REASONS] enum. Must be null if is_valid is true. | |
confidence_score | number | Must be a float between 0.0 and 1.0. Represents the model's confidence that the repaired output preserves the original semantic intent. Must be 0.0 if is_valid is false. | |
partial_result | object or null | If is_valid is false, this field may contain the subset of the output that passed validation. Must conform to a partial schema if present. Must be null if no fields are salvageable. |
Common Failure Modes
Self-correction loops fail in predictable ways. These are the most common failure modes when implementing multi-pass repair for structured output, and the guardrails that keep the loop from degrading into an expensive no-op.
Semantic Drift Under Repair Pressure
What to watch: The model fixes the schema violation but changes the meaning of the content. A repaired name field might become a placeholder, or a summary might be rewritten to a safer but incorrect statement just to pass validation. Guardrail: Diff the pre-repair and post-repair payloads semantically, not just structurally. Flag any field where the edit distance or embedding cosine similarity exceeds a threshold, and escalate those fields for human review.
Infinite Retry on Unrepairable Output
What to watch: The model receives the same validation error repeatedly and produces a slightly different invalid output each time, consuming the entire retry budget without converging. This often happens with contradictory constraints or when the model lacks the context to satisfy a required field. Guardrail: Implement a strict retry budget with a stall detector. If the same error class persists for two consecutive attempts, break the loop and escalate. Never allow more than N total attempts without a hard stop.
Error Message Blindness
What to watch: The retry prompt feeds raw validator output to the model, but the model ignores specific error details and makes broad, destructive changes—rewriting the entire JSON instead of fixing one missing field. Guardrail: Structure the retry prompt to isolate only the failed fields and instruct the model to preserve all other content verbatim. Use a diff instruction: 'Fix only the following fields and return the rest unchanged.' Validate that untouched fields are byte-for-byte identical after repair.
Escalation Without Salvage
What to watch: The repair loop escalates the entire payload to a human reviewer when only one field is unrepairable, blocking the pipeline and wasting the valid portions of the output. Guardrail: Implement partial salvage before escalation. Extract and return all valid fields with a partial_result: true flag, and escalate only the failed fields with their error context. Downstream systems can decide whether partial results are usable.
Validator-Model Mismatch
What to watch: The validator uses strict rules (e.g., regex patterns, exact enum matching) that the model cannot reason about from natural-language error messages alone. The model keeps guessing and failing. Guardrail: Translate raw validator errors into model-friendly fix instructions before feeding them into the retry prompt. Map each error to a specific field path, the constraint that failed, and a concrete example of a valid value. Never pass raw stack traces or library error codes directly to the model.
Context Starvation on Deeply Nested Failures
What to watch: A validation error deep inside a nested object (e.g., items[3].metadata.tags[7]) provides insufficient surrounding context for the model to infer the correct fix, leading to hallucinated values. Guardrail: In the retry prompt, include a window of sibling fields around the failed path, not just the error message. Provide the parent object and adjacent array elements so the model can infer the correct value from context rather than fabricating it.
Evaluation Rubric
Criteria for evaluating the quality of a self-correction loop before shipping to production. Use these checks to ensure the loop reliably repairs outputs without introducing new errors or exceeding resource budgets.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Schema Compliance | Output passes strict JSON Schema validation after ≤ [MAX_RETRIES] attempts. | Validator returns errors after retry budget is exhausted. | Run 50 known-invalid payloads through the loop; assert 100% final validity. |
Semantic Preservation | Repaired output preserves all original field values not flagged by the validator. | A valid field's value is altered or deleted during repair of an unrelated field. | Diff original and repaired payloads; assert no changes to valid fields. |
Retry Budget Adherence | Loop terminates after exactly [MAX_RETRIES] attempts or on first valid output. | Loop continues past [MAX_RETRIES] or terminates early on a non-valid signal. | Instrument loop counter; assert termination reason matches expected condition. |
Error Escalation | Produces a structured escalation payload with reason code when retries are exhausted. | Returns raw model output, empty object, or throws unhandled exception on exhaustion. | Force permanent validation failure; assert output matches [ESCALATION_SCHEMA]. |
Idempotency | Identical invalid input and error context produce identical repair output across runs. | Same input yields different repaired values across runs with temperature=0. | Run same invalid payload 5 times; assert byte-level output equality. |
Latency Budget | Total loop wall-clock time ≤ [MAX_LATENCY_MS] for 95th percentile of repairs. | P95 latency exceeds threshold under concurrent load. | Load test with 100 concurrent repair requests; measure P95 end-to-end time. |
Confidence Flag Accuracy | Repair confidence score correlates with actual repair correctness (high score = correct repair). | High-confidence repairs introduce semantic errors; low-confidence repairs are correct. | Label 100 repairs as correct/incorrect; assert AUROC ≥ 0.85 for confidence score. |
Partial Salvage Quality | When full repair fails, partial output contains only validated fields with correct values. | Partial output includes unrepaired invalid fields or omits valid fields. | Force partial salvage scenario; assert all returned fields pass individual field validation. |
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 loop prompt with a fixed retry budget of 2 and simple string matching for validation. Replace [VALIDATION_ERRORS] with raw error text from your parser. Skip the confidence scoring and partial salvage steps. Log each iteration to a local file for manual review.
codeYou are a structured output repair agent. The previous response failed validation. Fix ONLY the errors listed below. Preserve all other content unchanged. [ORIGINAL_PROMPT] [FAILED_OUTPUT] [VALIDATION_ERRORS] Return ONLY the corrected output with no additional text.
Watch for
- Infinite loops when the model can't fix the error
- Silent content drift across iterations
- No differentiation between minor format issues and semantic errors

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