Lesson 14.8 · 8 of 8 · 5 min read · Reviewed 24 Nov 2026
Refusals, truncation and validation retries
By the end, you can
- Tell a refusal, a truncated reply and a validation failure apart before deciding what to do.
- Handle each one with the right action instead of a blind retry.
The validate-and-retry loop in 18.4 assumes every failure is a fixable mistake. In production, three different things land in the same “it didn’t parse” pile, and each needs a different response.
Three ways structured output goes wrong
| What happened | How you can tell | What to do |
|---|---|---|
| Truncated: the reply hit the token limit | Stop reason for the limit (max_tokens in Claude’s API, length in some others). JSON ends mid-value. |
Raise the limit, shrink the output, or split the input. Do not resend unchanged. |
| Refused: the model declined | A refusal stop reason or a separate refusal field. Text explains why instead of data. | Log it, return a safe message, route to review. Do not retry the same input in a loop. |
| Invalid: finished, but breaks a rule | Normal stop reason, parses or nearly parses, fails your validator | Retry with the exact errors, capped (14.4). |
Strict modes (14.2) remove most of the third row, but not the first two. A constrained decoder cannot finish an object it has no tokensToken: The unit a model reads and writes: a word, part of a word, a space or a symbol, mapped to an integer id. left for, and it does not turn a refusal into valid data.
Classify first
Put the check at the top of your handler, before any parsing:
def handle(resp):
if resp.stop_reason == "max_tokens":
return ("truncated", None)
if resp.stop_reason == "refusal":
return ("refused", None)
data, errors = parse_and_validate(resp)
if errors:
return ("invalid", errors)
return ("ok", data)
Then each label has one action. Names of stop reasonsStop reason: The field in a response that says why generation stopped: end_turn, max_tokens, stop_sequence, tool_use and others. differ by provider; check yours and map them to these labels.
Worked example
A nightly batch extracts fields from 1,000 support emails. In one run (illustrative):
- 940 are fine.
- 30 are invalid: dates in the wrong format. One retry with the errors fixes 25; 5 go to review.
- 20 are truncated: all are long email threads. The team raises
max_tokensfor inputs over a size threshold, and they pass next run. - 10 are refused: messages containing harmful content. They go straight to the trust-and-safety queue with the reason.
Before the split, the team retried all 60 up to three times. That cost 180 extra calls and still failed 30 of them.
Common mistakes
- Retrying truncation unchanged. Same input, same limit, same cut-off point.
- Parsing a refusal. Code tries to read fields from an apology and throws, or worse, stores empty values.
- Repairing truncated JSON by closing the brackets. You get a valid object with silently missing fields. Treat it as a failure.
- Counting refusals as validation errors. Dashboards then show a “format problem” that is really a policy question. Track the three rates separately (14.5).
- No cap. Every path still needs a limit and a review queue.
Key points
- Check why the reply stopped before you parse it: a stop reason such as max_tokens or refusal tells you the output is not a normal answer.
- Truncation needs more room or a smaller output; retrying the same request just truncates again.
- A refusal is a decision, not a format error: log it and route it, don't loop on it.
- Only a genuine validation failure gets a retry with the specific errors (14.4).
Classify failures before you retry
Handle truncated, refused and invalid replies with different actions instead of one blind retry loop.
You will have: A handle function that labels each simulated reply and a tally of actions taken for a batch of ten.
Steps
- Read the ten simulated responses: each has a stop_reason and text.
- Complete classify so it checks the stop reason first (max_tokens means truncated, refusal means refused), then parses and validates.
- Map each label to an action: accept, retry with errors, raise the token limit, or route to review.
- Print the tally and confirm no refused or truncated reply was retried unchanged.
Done when
- Truncated replies get the action 'raise max_tokens or split input'.
- Refused replies are routed to review and never parsed.
- The script prints 'ok: 5, invalid: 2, truncated: 2, refused: 1'.
Open in the Playground No API key needed.
Starter code (Python)
import json
RESPONSES = [
{"stop_reason": "end_turn", "text": '{"name": "Priya", "date": "2026-03-04"}'},
{"stop_reason": "end_turn", "text": '{"name": "Tom", "date": "2026-01-09"}'},
{"stop_reason": "max_tokens", "text": '{"name": "Ana", "items": ["mug", "lid", "pl'},
{"stop_reason": "end_turn", "text": '{"name": "Sam", "date": "03/04/2026"}'},
{"stop_reason": "refusal", "text": "I can't help with extracting details from this message."},
{"stop_reason": "end_turn", "text": '{"name": "Lee", "date": "2026-02-11"}'},
{"stop_reason": "max_tokens", "text": '{"name": "Kim", "date": "2026-0'},
{"stop_reason": "end_turn", "text": '{"name": "Ola"}'},
{"stop_reason": "end_turn", "text": '{"name": "Raj", "date": "2026-04-01"}'},
{"stop_reason": "end_turn", "text": '{"name": "Eve", "date": "2026-05-30"}'},
]
def validate(data):
errs = []
if "date" not in data:
errs.append("missing date")
elif len(data["date"]) != 10 or data["date"][4] != "-":
errs.append("date must match YYYY-MM-DD")
return errs
def classify(resp):
# TODO: check resp["stop_reason"] first: "max_tokens" -> "truncated", "refusal" -> "refused".
# TODO: then json.loads the text and validate: errors -> "invalid", else "ok".
return "ok"
ACTIONS = {
"ok": "accept",
"invalid": "retry with the exact errors (capped)",
"truncated": "raise max_tokens or split input",
"refused": "log and route to review",
}
tally = {k: 0 for k in ACTIONS}
for r in RESPONSES:
label = classify(r)
tally[label] += 1
print(f"{label:9} -> {ACTIONS[label]}")
print(", ".join(f"{k}: {v}" for k, v in tally.items()))
Show a solution
import json
RESPONSES = [
{"stop_reason": "end_turn", "text": '{"name": "Priya", "date": "2026-03-04"}'},
{"stop_reason": "end_turn", "text": '{"name": "Tom", "date": "2026-01-09"}'},
{"stop_reason": "max_tokens", "text": '{"name": "Ana", "items": ["mug", "lid", "pl'},
{"stop_reason": "end_turn", "text": '{"name": "Sam", "date": "03/04/2026"}'},
{"stop_reason": "refusal", "text": "I can't help with extracting details from this message."},
{"stop_reason": "end_turn", "text": '{"name": "Lee", "date": "2026-02-11"}'},
{"stop_reason": "max_tokens", "text": '{"name": "Kim", "date": "2026-0'},
{"stop_reason": "end_turn", "text": '{"name": "Ola"}'},
{"stop_reason": "end_turn", "text": '{"name": "Raj", "date": "2026-04-01"}'},
{"stop_reason": "end_turn", "text": '{"name": "Eve", "date": "2026-05-30"}'},
]
def validate(data):
errs = []
if "date" not in data:
errs.append("missing date")
elif len(data["date"]) != 10 or data["date"][4] != "-":
errs.append("date must match YYYY-MM-DD")
return errs
def classify(resp):
if resp["stop_reason"] == "max_tokens":
return "truncated"
if resp["stop_reason"] == "refusal":
return "refused"
try:
data = json.loads(resp["text"])
except json.JSONDecodeError:
return "invalid"
return "invalid" if validate(data) else "ok"
ACTIONS = {
"ok": "accept",
"invalid": "retry with the exact errors (capped)",
"truncated": "raise max_tokens or split input",
"refused": "log and route to review",
}
tally = {k: 0 for k in ACTIONS}
for r in RESPONSES:
label = classify(r)
tally[label] += 1
print(f"{label:9} -> {ACTIONS[label]}")
print(", ".join(f"{k}: {v}" for k, v in tally.items()))
Finished the chapter? Take the chapter check.