Sub topic 10
Retrying and repairing invalid output
This chapter assumes you can call an LLM API, read JSON, and define a Pydantic model like the Invoice model from the schema chapter. It covers what to do when the model's answer fails validation.
Why output fails
Even with a clear prompt, a model sometimes returns output your code cannot use. Common causes:
- The JSON is wrapped in prose or a Markdown fence.
- A required key is missing, such as
invoice_number. - A value has the wrong type, such as
"total": "1,250.00"where a number is expected. - The JSON is cut off because the response hit the token limit.
Validation tells you that the output failed. A retry loop gives the model a chance to fix it.
The repair loop
The simplest loop validates the answer. If validation fails, it sends the same prompt again with the error message appended. The error names the exact field and problem, so the model has something concrete to correct.
from pydantic import ValidationError
def extract_invoice(document_text, call_llm, max_attempts=3):
"""call_llm(prompt: str) -> str is your own function that calls an LLM API."""
prompt = PROMPT_TEMPLATE.format(document_text=document_text)
last_error = None
for _ in range(max_attempts):
raw = call_llm(prompt if last_error is None else
prompt + f"\n\nYour previous answer was invalid: {last_error}\nReturn corrected JSON only.")
try:
return Invoice.model_validate_json(raw)
except ValidationError as exc:
last_error = str(exc)
raise ValueError(f"Extraction failed after {max_attempts} attempts: {last_error}")Two details matter. max_attempts caps the cost, so a document that cannot be parsed does not loop forever. The final raise makes failure visible, so the caller can route the document elsewhere instead of receiving bad data.
Retry or repair?
These are different fixes for different failures.
| Failure | Better response |
|---|---|
| Invalid JSON, wrong type, missing key | Retry with the validation error |
| Extra text around valid JSON | Repair in code: extract the text between the first `{` and last `}` |
| Truncated output | Raise the output token limit or shorten the document, then retry |
| Value is wrong but valid | Retrying does not help. Use grounding checks instead |
Repairing in code is cheaper than another model call. Use it for mechanical problems and keep retries for problems that need the model to reconsider.
Common errors
- Retrying without the error. Resending the identical prompt often returns the same mistake. Include the validation message.
- Retrying on a schema mismatch you caused. If many documents fail on the same field, the schema or prompt is wrong. Fix it there.
- No cap on attempts. Each retry costs money and adds latency.
- Treating a valid result as a correct one. A passing result can still contain an invented value. Validation checks shape, not truth.
Exercise
A document fails validation on all three attempts because total is returned as "N/A" where a float is expected. Name two changes that could reduce these failures without adding more retries.
Show answer
Make total Optional and tell the prompt to use null when a value is absent, so the model has a valid way to express "missing". Alternatively, add a repair step in code that maps placeholders like "N/A" to None before validation. Both address the cause instead of repeating the failing call.