Sub topic 9
Retrying with the validation error as feedback
This chapter assumes you can write a Pydantic model, catch exceptions in Python, and have called an LLM API at least once. It also assumes you have read the previous chapter on validating output. Validation tells you that a reply is wrong. A retry loop gives the model a chance to fix it.
Why a retry is worth building
Even with a careful prompt, a model sometimes returns output that fails validation. The reply may be wrapped in a code fence, use a value outside your enum, or leave out a field. These failures are usually random rather than systematic. Asking again often works.
A retry loop turns an occasional failure into a rare one. If a single call fails 5% of the time and failures were independent, two attempts fail together about 0.25% of the time. Failures are rarely fully independent, because a hard input tends to stay hard. That is why you feed the error back instead of repeating the same request.
A retry loop is a safety net, not a substitute for a good prompt or schema. If more than a few percent of calls need a retry, fix the prompt or the schema first. The retry rate is a useful signal, and the testing chapter returns to it.
The shape of a repair loop
A repair loop has four parts:
- Call the model with the task prompt.
- Parse and validate the reply.
- If validation fails, build a new prompt that contains the bad reply and the error messages, then call the model again.
- Stop after a fixed number of attempts and raise an error.
The limit in step 4 is not optional. Without it, a persistent failure becomes an endless loop that spends money on every pass.
A complete implementation
The loop below builds on the TicketTriage model from the earlier chapter on schema models and the strip_code_fence helper from the chapter on prompting for a format. Both are repeated here so the example runs on its own.
from typing import Literal
from pydantic import BaseModel, Field, ValidationError
class TicketTriage(BaseModel):
category: Literal["billing", "bug", "feature_request", "other"]
priority: int = Field(ge=1, le=3, description="1 is most urgent, 3 is least urgent")
summary: str = Field(max_length=200, description="One-sentence summary of the ticket")
def strip_code_fence(raw: str) -> str:
"""Remove a surrounding Markdown code fence, which models sometimes add."""
text = raw.strip()
if text.startswith("```"):
text = text.split("\n", 1)[1] if "\n" in text else ""
text = text.rstrip()
if text.endswith("```"):
text = text[:-3]
return text.strip()
def extract_ticket(ticket_text, call_llm, max_attempts=3):
"""call_llm(prompt) -> str is any function that returns the model's text reply."""
prompt = (
"Triage this support ticket. Reply with a single JSON object with keys "
"category, priority, summary and nothing else.\n\n" + ticket_text
)
for _ in range(max_attempts):
raw = strip_code_fence(call_llm(prompt))
try:
return TicketTriage.model_validate_json(raw)
except ValidationError as err:
prompt = (
"Your previous reply was invalid.\n"
f"Reply:\n{raw}\n\nErrors:\n{err}\n\n"
"Return a corrected JSON object only.\n\nTicket:\n" + ticket_text
)
raise ValueError(f"No valid output after {max_attempts} attempts")Four details matter here.
- The function takes
call_llmas an argument. Any provider works, and you can test the loop with a fake function that returns scripted replies. model_validate_jsondoes parsing and validation in one step. Malformed JSON and schema violations both raiseValidationError, so oneexceptclause handles both.- The repair prompt includes the original ticket. The model needs the source text to correct a wrong value, not only the broken reply.
- The prompt is rebuilt from the original task each time. Only the latest failure is included, so the prompt does not grow with each attempt.
What the model sees in the error
Pydantic error messages are written for developers, but they are specific enough for a model to act on. Suppose the model replied with this:
{"category": "refund", "priority": 5, "summary": "Customer wants money back"}The ValidationError text sent back looks like this:
2 validation errors for TicketTriage
category
Input should be 'billing', 'bug', 'feature_request' or 'other' [type=literal_error, input_value='refund', input_type=str]
priority
Input should be less than or equal to 3 [type=less_than_equal, input_value=5, input_type=int]Each error names the field, the rule that was broken, and the value that broke it. The model can read that and change refund to billing and 5 to 3. A vague message such as "Invalid output, try again" gives the model nothing to correct, and it will often repeat the same mistake.
Testing the loop without a model
Because call_llm is a plain function, you can script the replies. This test confirms that the loop recovers after one bad reply and that it stops at the limit.
def make_fake_llm(replies):
"""Return a call_llm function that yields the scripted replies in order."""
remaining = list(replies)
prompts = []
def call_llm(prompt):
prompts.append(prompt)
return remaining.pop(0)
call_llm.prompts = prompts
return call_llm
bad = '{"category": "refund", "priority": 5, "summary": "Wants money back"}'
good = '{"category": "billing", "priority": 2, "summary": "Wants money back"}'
# Recovers on the second attempt.
llm = make_fake_llm([bad, good])
result = extract_ticket("I was charged twice.", llm)
assert result.category == "billing"
assert "Errors:" in llm.prompts[1]
assert "refund" in llm.prompts[1]
# Gives up after max_attempts.
llm = make_fake_llm([bad, bad, bad])
try:
extract_ticket("I was charged twice.", llm)
except ValueError as exc:
print("Failed safely:", exc)The first assertions check that the second prompt really contains the error text. That is the behavior this chapter is about, so it deserves a direct test.
Design decisions
How many attempts
Two or three attempts is a common choice. The first retry fixes most recoverable errors because the model now sees exactly what was wrong. Later retries rarely help. If the model fails three times on the same input, the problem is usually the input, the schema, or the prompt, and a fourth try is likely to repeat the failure.
Which errors are worth retrying
Not every failure should trigger a repair prompt. Separate them by cause.
| Failure | Retry with error feedback? | Why |
|---|---|---|
| Malformed JSON | Yes | The model can usually fix syntax when shown the parser message. |
| Missing field or wrong type | Yes | The error names the field and the expected type. |
| Value outside enum or range | Yes | The error lists the allowed values or limits. |
| Truncated reply (hit the token limit) | No, change the request | The same request will truncate again. Raise the limit or shorten the input. |
| Refusal | No | A repair prompt will not change the model's decision. Handle the refusal explicitly. |
| Network error or rate limit | No, retry the call | This is a transport problem. Use backoff, not a repair prompt. |
Mixing these up wastes calls. A truncated reply produces a "JSON invalid" error, and a repair prompt that includes the truncated reply makes the next prompt even longer. The failure-modes chapter covers these cases in detail.
What to send back
The repair prompt in this chapter includes the invalid reply and the error text. There are two other options, and each has a cost.
- Errors only, without the reply. The prompt is shorter, but the model cannot see what it got wrong. Use this only when the reply is very long.
- A multi-turn conversation. You append the bad reply as an assistant message and the error as a new user message. This matches how chat models are trained and keeps the full history. It also grows the context on every attempt, so cap the attempts.
If your provider supports chat messages, the multi-turn form is often more natural than one long prompt. The loop logic stays the same.
Use feedback that is specific
Pydantic's text is a good default. You can improve it for fields where the model keeps making the same mistake. A custom message in a validator can say what you actually want.
from pydantic import BaseModel, Field, field_validator
class Ticket(BaseModel):
summary: str = Field(max_length=200)
@field_validator("summary")
@classmethod
def one_sentence(cls, value):
if value.count(". ") >= 1:
raise ValueError("summary must be a single sentence, not several")
return valueA message like "summary must be a single sentence" tells the model the fix directly. This works best for rules that the schema cannot express.
Edge cases and gotchas
- Retrying makes nondeterministic output more variable, not less. If you set the temperature to 0, a repeated identical prompt often returns an identical bad reply. The repair prompt differs from the first prompt, so it changes the output. Do not rely on a plain re-send.
- A valid reply can still be wrong. The loop checks shape and limits. It cannot know that
priority: 3was the wrong choice for an urgent ticket. Validation errors cover format, not meaning. - Retries multiply cost and latency. Each attempt is a full call. A loop with three attempts can take three times as long in the worst case. Log how many attempts each request used.
- Do not catch everything. The loop catches
ValidationErroronly. A bug in your own code or a network failure should surface instead of being hidden as a bad reply. - Sensitive data stays in the prompt. The repair prompt repeats the reply and the ticket text. If you log prompts, repair prompts will be logged too.
- Constrained decoding changes the picture. When the provider enforces your schema during generation, shape errors mostly disappear. A loop is still useful for rules the schema cannot express, such as the one-sentence check above, and for cases such as truncation.
Exercises
Exercise
A reply fails validation because it was cut off in the middle of a JSON string after the model hit the output token limit. Should the loop send a repair prompt that includes the truncated reply? What should you do instead?
Show answer
No. The same request will usually hit the limit again, and including the truncated reply makes the prompt longer. Detect the truncation (for example from the provider's stop reason), then raise the output token limit, shorten the input, or ask for a smaller object. Retry the changed request rather than sending a repair prompt.
Exercise
Modify extract_ticket so that it returns both the validated ticket and the number of attempts used. Why would you want that number?
Show answer
Track the attempt number with for attempt in range(1, max_attempts + 1): and return TicketTriage.model_validate_json(raw), attempt inside the try. The attempt count lets you calculate the retry rate across many requests. A rising rate points to a prompt or schema problem, and a rate near zero shows the loop is only a safety net.
Exercise
The test above uses a fake call_llm. Write one extra assertion for the scripted run [bad, good] that proves the second prompt still contains the original ticket text.
Show answer
Add assert "I was charged twice." in llm.prompts[1]. The repair prompt ends with the original ticket, so the assertion passes. If it failed, the model would be asked to correct a reply without seeing the source it was meant to summarize.