Sub topic 11
What still goes wrong: truncation, refusals, and wrong values
This chapter assumes you can write a Pydantic model, call an LLM API, and run the validate-and-retry loop from earlier chapters. Schema-constrained decoding and validation remove many errors. Three kinds of failure remain, and each needs its own handling.
Where the failures occur
Truncation
A model stops generating when it hits the output token limit. If that happens in the middle of a JSON object, you get text such as {"category": "bug", "priority": 2, "summ. Constrained decoding does not prevent this, because the grammar only controls which tokens are allowed. It does not guarantee the object is finished.
Check the finish reason before you parse. Providers name it differently, such as finish_reason or stop_reason, and the value for a length stop is often length or max_tokens. Check your provider's documentation for the exact names.
class TruncatedOutput(Exception):
pass
def check_finish(finish_reason: str) -> None:
if finish_reason in {"length", "max_tokens"}:
raise TruncatedOutput("Model hit the output limit before finishing")Retrying with the same prompt usually truncates again. Better fixes are to raise the token limit, shorten the schema's free-text fields (for example with max_length), or split a long input into smaller pieces. Do not try to repair partial JSON by guessing the missing closing braces, because the missing fields may matter.
Refusals
A model may decline a request, for example when the input touches a safety policy. The reply then contains an explanation instead of your data. Some providers return refusals in a separate field, so the output is empty or does not match the schema, even with constrained decoding on. Others return ordinary text such as "I can't help with that", which fails parsing.
Treat a refusal as a distinct outcome, not a validation error. Retrying with "your reply was invalid" will not change the model's decision and wastes calls.
from dataclasses import dataclass
from typing import Optional
@dataclass
class ExtractionResult:
data: Optional[TicketTriage]
status: str # "ok", "refused", "truncated", or "invalid"
detail: str = ""Return a result object like this one so callers must handle every status. Raising a single generic exception hides the difference between a refusal you should log and a transient error you should retry.
Wrong values that pass validation
Validation checks shape, not truth. This object is valid for TicketTriage and still wrong if the ticket was about a crash:
{"category": "billing", "priority": 3, "summary": "Customer reports a problem."}Common causes:
- Guessing a missing field. The schema requires
priority, the ticket gives no hint, and the model invents a number. - Vague summaries. The text satisfies
max_lengthbut says nothing. - Copy errors. Dates, amounts, or IDs are changed slightly when extracted.
Reduce these with changes to the schema and the checks around it:
- Allow an explicit "unknown" value, such as an
"other"category or a nullable field, so the model is not forced to guess. - Add cross-field rules in code, for example that a refund amount is not negative.
- Check extracted quotes, IDs, and numbers against the source text with a string search.
- Send low-confidence or rule-violating records to a human review queue.
def verify_against_source(ticket_text: str, order_id: str) -> bool:
"""Return True if the extracted order ID appears in the source text."""
return order_id in ticket_textSummary of handling
| Failure | How to detect | Response |
|---|---|---|
| Truncation | Finish reason is `length` or `max_tokens` | Raise the limit, shorten fields, or split the input |
| Refusal | Refusal field set, or a plain-text explanation | Log it and route to a fallback. Do not retry blindly |
| Wrong value | Source checks, cross-field rules, labeled tests | Allow "unknown", flag for review |
Exercise
A reply from the model fails JSON parsing, and the finish reason is "length". Your retry loop resends the prompt with the parse error. Why is this a poor response, and what should you do instead?
Show answer
The reply was cut off by the output limit, so the same prompt will likely be cut off again, and the parse error does not tell the model anything useful. Detect the length finish reason before parsing and treat it as truncation. Raise the token limit, shorten free-text fields, or split the input, and do not try to repair the partial JSON by guessing.
Exercise
The model returns {"category": "bug", "priority": 1, "summary": "App crashes on login"} for a ticket that only asks about a refund. The object passes validation. Name two checks that could catch this kind of error.
Show answer
Two options: compare the output with labeled examples in a test set, and add a check that the summary or category is consistent with the source text, for example by searching for key terms from the ticket. Routing results to human review when a rule fails is a third option.