Sub topic 9
Retrying with the validation error as feedback
This chapter assumes you can read Pydantic models, catch exceptions in Python, and have called an LLM API before. It builds on the TicketTriage model and the strip_code_fence helper from earlier chapters.
Why a retry can work
Validation sometimes fails even with a good prompt. The reply may be missing a key, use a category outside the allowed list, or put priority at 5 when the limit is 3. These errors are usually small. A second attempt that shows the model what went wrong often fixes them.
A plain retry with the same prompt is a weaker option. Model output varies from call to call, so it may succeed, but you pay for another call without giving the model any new information. A repair retry adds the bad reply and the exact error messages. The model can then change only what was wrong.
The loop
The loop has four parts:
- Send the prompt and receive the reply.
- Strip any code fence and validate the reply against the model.
- On success, return the validated object.
- On failure, build a new prompt that includes the bad reply and the errors, then try again, up to a fixed limit.
Here is the loop in code. It validates against the TicketTriage model and uses strip_code_fence from the earlier chapter.
from pydantic import ValidationError
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")What makes the feedback useful
Pydantic's error text names the field, the rule that failed, and the value received. For a reply with "priority": 5, the message includes priority, Input should be less than or equal to 3, and input_value=5. This is specific enough for the model to act on.
Two details in the loop matter:
- The original ticket is sent again. Each retry prompt is rebuilt from the ticket text, so the model has the full task and not just the correction request.
- The prompt is replaced, not extended. Only the latest bad reply and its errors are included. Appending every failed attempt makes the prompt grow and can confuse the model.
If your API supports chat messages, you can instead append the bad reply as an assistant message and the errors as a new user message. The effect is the same. The single-prompt version works with any client.
Testing the loop without a real model
Because call_llm is a plain function, you can test the loop with a fake that returns a scripted sequence of replies.
def make_fake_llm(replies):
replies = iter(replies)
prompts = []
def call_llm(prompt):
prompts.append(prompt)
return next(replies)
call_llm.prompts = prompts
return call_llm
bad = '{"category": "billing", "priority": 5, "summary": "Double charge"}'
good = '{"category": "billing", "priority": 1, "summary": "Double charge"}'
fake = make_fake_llm([bad, good])
result = extract_ticket("I was charged twice.", fake)
print(result.priority) # 1
print(len(fake.prompts)) # 2
print("less than or equal to 3" in fake.prompts[1]) # TrueThe last line confirms that the second prompt carried the validation error. A second test with three bad replies should confirm that ValueError is raised.
Common errors
- No attempt limit. A loop that retries until it succeeds can run forever and spend money on a reply that will never validate. Keep
max_attemptssmall, usually 2 or 3. Later attempts rarely succeed when the first two failed for the same reason. - Retrying errors that are not validation errors. Network failures, rate limits, and timeouts need their own handling, such as backoff. Do not mix them into this loop.
- Retrying a truncated reply. If the output was cut off at the token limit, the error says the JSON is incomplete, and the model cannot fix that by seeing the message. Raise the output limit or shorten the output instead.
- Treating success as correctness. A reply can pass validation and still be wrong, for example a
buglabeled asbilling. The loop checks shape and limits only. - Swallowing the final failure. After the last attempt, raise an error or return a clear failure result. Do not return a default value that looks like real data.
Exercise
In extract_ticket, why does the retry prompt include the previous reply and the validation errors, and why does the loop stop after max_attempts?
Show answer
The previous reply and the errors tell the model exactly what was wrong, so it can correct only those fields instead of guessing. The attempt limit bounds cost and time. If the model has failed several times, more attempts rarely help, and the function should raise an error so the caller can handle the failure safely.
Exercise
Write a test that checks extract_ticket raises ValueError when the model never returns valid output, using make_fake_llm.
Show answer
Use three invalid replies and expect the exception:
import pytest
def testgivesup():
bad = '{"category": "billing", "priority": 5, "summary": "x"}'
fake = makefakellm([bad, bad, bad])
with pytest.raises(ValueError):
extractticket("ticket", fake)
The fake is called exactly three times, matching the default `maxattempts. A fourth call would raise StopIteration`, which would also show a bug in the limit.