Topic 4 of 5 · 4 min read
Repairing invalid output with targeted retries
Goal: Design a repair retry that returns the validation error to the model and stops after a bounded number of attempts.
When output fails validation, send the model its own reply and the exact error, allow a small fixed number of attempts, and have a defined fallback for when they run out. A blind retry of the same request repeats the same mistake.
Check yourself · 1 of 3
A reply fails validation because priority is "high". What should the retry message contain?
Why it matters
Models are not deterministic, so a second call may succeed, but it may also fail the same way. Telling the model what was wrong (for example refund_eur must be at most 80.00, the order total) makes the fix far more likely than hoping for luck. Without a bound, a stubborn failure becomes an endless loop that costs money and holds a request open.
How to do it
- Catch a specific error. Your validator raises an error with a message such as
unknown order ORD-99999orpriority must be one of low, normal, urgent. - Append two messages. Add the model's invalid reply as an assistant message, then a user message that states the error and asks for a corrected reply in the same format.
- Bound the attempts. Two or three tries is usual. Count them in code, not in the prompt.
- Fall back. After the last failure, do something deliberate: route to a human queue, return a clear error to the caller or use a safe default that does not write data. Log the inputs and errors.
- Do not retry what cannot change. A refusal for policy reasons, an authentication error or a timeout need different handling than a bad field.
Before and after
# Weak: same request, unbounded
while True:
try:
return parse(call_model(messages))
except Exception:
pass
# Fixed: error goes back, three attempts, fallback
for attempt in range(3):
reply = call_model(messages)
try:
return parse_and_validate(reply)
except InvalidOutput as e:
messages += [
{"role": "assistant", "content": reply},
{"role": "user", "content": f"That failed validation: {e}. Return corrected JSON only."},
]
queue_for_human(messages)
raise ExtractionFailed
What goes wrong
- Catching every exception. A network error or a bug in your code gets treated as bad model output.
- Sending the whole error trace. Give a short, specific message, not a stack trace.
- Retrying at high cost. Each retry repeats the long context. Keep the request small or cache the shared prefix where the provider supports it.
- No fallback. After the last attempt the code throws and the user sees a generic failure.
Examples
Error message the model can act on
Weak: Invalid output, try again.
Better: Field priority was "high". Allowed values: low, normal, urgent. Return the full JSON again with priority corrected.
The second names the field, the bad value and the allowed set.
Bounded retry in TypeScript
for (let attempt = 0; attempt < 3; attempt++) {
const reply = await callModel(messages);
const result = Ticket.safeParse(JSON.parse(reply));
if (result.success) return result.data;
messages.push(
{ role: "assistant", content: reply },
{ role: "user", content: `Validation failed: ${result.error.message}. Return corrected JSON only.` },
);
}
throw new ExtractionFailed();
Key points
- Return the invalid reply and the specific validation error to the model, not just the original request.
- Bound attempts in code, usually two or three.
- Define a fallback such as a human queue or a clear error for when repair fails.
- Retry only on errors the model can fix; refusals and network errors need different handling.
- Log the input, the replies and the errors so persistent failures can be analysed.
Common mistakes
- Retrying the identical request without telling the model what failed.
- Looping with no attempt limit.
- Catching all exceptions and treating them as bad model output.
- Having no fallback path after the last attempt.
Check yourself · 2 of 3
Why must the number of repair attempts be limited in code?
Check yourself · 3 of 3
All three repair attempts failed on a customer refund request. What is the best fallback?
Practice items, not counted towards your mastery.
Start here
- Structured outputs (Claude docs) (opens in a new tab)DocsFree
How Claude constrains output to a JSON schema, which schema features are supported and what the limits are.
- Structured model outputs (OpenAI API docs) (opens in a new tab)DocsFree
Strict schema mode versus JSON mode, supported keywords and how refusals appear in a structured response.
- Structured output (Gemini API docs) (opens in a new tab)DocsFree
How Gemini takes a response schema and which schema subset it accepts.