LLM Structured Output Repair Loop: Autocorrection and Re-Generation
The LLM structured output repair loop automatically fixes invalid JSON and schema errors by re-invoking the model with a description of the defect instead of failing the entire operation.
Why Output Breaks
Even with JSON mode enabled, the model can return output that does not conform to the schema. The causes fall into three classes: | Class | Example | Cause | |---|---|---| | Syntax | Unclosed bracket, extra text before JSON | Truncated generation, prompt influence | | Schema | Missing required field, wrong type | Ambiguous instruction | | Semantics | Value out of allowed range, reference to a non-existent ID | Model reasoning error | Syntax errors are fixed deterministically; schema and semantics require re-invoking the model. See llm-json-schema-validation and structured-output.
Loop Architecture
flowchart TD
A[Request to LLM] --> B[Extract JSON from response]
B --> C{Syntax valid?}
C -- No --> D[Deterministic repair]
C -- Yes --> E{Schema valid?}
D --> E
E -- No --> F{Attempt limit reached?}
E -- Yes --> G{Semantics valid?}
G -- No --> F
G -- Yes --> H[Result accepted]
F -- No --> I[Re-invoke with error description]
I --> A
F -- Yes --> J[Fallback or error]
The loop is limited in the number of iterations (usually 2–3). After the limit is exhausted, a structured-output-fallback is applied or the operation ends with an error.
Step 1: Deterministic Repair
Before re-invoking the model, operations that do not require generation are applied:
- removing text before the first { and after the last };
- removing the markdown ```json wrapper;
- closing unclosed brackets and quotes;
- replacing single quotes with double quotes;
- removing trailing commas.
import json
import re
def extract_json(text: str) -> str:
text = re.sub(r"^```(?:json)?\s*|\s*```$", "", text.strip())
start = text.find("{")
end = text.rfind("}")
if start == -1 or end == -1:
raise ValueError("JSON object not found")
return text[start:end + 1]
def try_parse(text: str):
try:
return json.loads(extract_json(text))
except json.JSONDecodeError:
return None
Step 2: Schema Validation
The schema is described in JSON Schema format. Validation is performed by a library (for example, jsonschema in Python) and returns a list of violations with paths to fields.
from jsonschema import Draft202012Validator
schema = {
"type": "object",
"required": ["title", "tags", "score"],
"properties": {
"title": {"type": "string", "minLength": 1},
"tags": {"type": "array", "items": {"type": "string"}, "maxItems": 5},
"score": {"type": "number", "minimum": 0, "maximum": 1},
},
"additionalProperties": False,
}
validator = Draft202012Validator(schema)
def validate(data):
return sorted(validator.iter_errors(data), key=lambda e: list(e.path))
path) and a message. This data is used at the re-invocation step.
Step 3: Re-Invocation with Feedback
The re-invocation includes the original prompt, the previous invalid answer, and the list of violations. The phrasing must be precise and free of ambiguity.
def build_repair_prompt(original_prompt: str, bad_output: str, errors: list) -> str:
error_lines = "\n".join(
f"- path {'.'.join(map(str, e.path)) or '<root>'}: {e.message}"
for e in errors
)
return (
f"{original_prompt}\n\n"
f"The previous answer does not conform to the schema.\n"
f"Answer:\n{bad_output}\n\n"
f"Violations:\n{error_lines}\n\n"
f"Return only the corrected JSON without explanations."
)
Step 4: Semantic Validation
The schema does not cover checks requiring external data: existence of identifiers, consistency of references, compliance with reference books. Such checks are performed by a separate validator.
def semantic_check(data: dict, known_ids: set) -> list[str]:
errors = []
for ref in data.get("references", []):
if ref not in known_ids:
errors.append(f"references: unknown identifier {ref}")
if data.get("score", 0) > 0.9 and not data.get("evidence"):
errors.append("score: high score without supporting data")
return errors
Limits and Cost
Each loop iteration is an additional model call. The token budget per operation is calculated in advance: | Parameter | Value | |---|---| | Base cost | 1 call | | Maximum iterations | 3 | | Worst case | 3 calls | | Expected share of repeats | 5–15% | When the limit is exceeded, a fallback is applied: returning a partial result, a default value, or an explicit error while preserving the original output for examination. See llm-api-cost-forecasting.
Logging and Examination
Each iteration is logged with fields: request identifier, attempt number, error class, list of violations, and the model used. This enables: - identifying schema fields that the model consistently fills incorrectly; - adjusting prompt phrasing; - estimating the share of operations that ended in fallback. Logs are integrated into the observability pipeline — see llm-observability-stack and llm-api-observability-tracing.
Implementation Checklist
- Syntactic repair runs before re-invoking the model.
- The schema is described formally and versioned.
- The re-invocation receives a list of specific violations, not a generic "fix it" request.
- Semantic checks are moved to a separate validator.
- The number of iterations is limited and a fallback is defined.
- Each iteration is logged with the error class.