Sub topic 11
What still goes wrong: truncation, refusals, and wrong values
This chapter assumes you can define a Pydantic model, call an LLM API, and read a JSON Schema. It also assumes you know the basics of validation and retry loops from earlier chapters. Even with schema-constrained decoding, three kinds of failure remain: the output is cut off, the model declines to answer, or the output has the right shape but the wrong content. Each needs a different defense.
Why a valid shape does not mean a correct result
Schema enforcement guarantees structure. It does not guarantee that the data is complete, that the model tried to answer, or that the values are true. Treat these as three separate layers:
| Layer | Question | Who checks it |
|---|---|---|
| Syntax | Is this parseable JSON? | Parser, JSON mode, constrained decoding |
| Shape | Does it match the schema? | Schema validator, constrained decoding |
| Meaning | Is it correct for this input? | Your own checks, tests, and review |
Constrained decoding covers the first two layers when the output finishes normally. The failures below slip past it, or sit entirely in the third layer.
The order matters. Check the stop reason before you parse, because a truncated reply often fails to parse and the parse error hides the real cause.
Truncation
Truncation happens when the model reaches the maximum number of output tokens before it finishes the JSON. A token is a chunk of text, roughly three to four characters of English. If you set max_tokens to 200 and the object needs 350, the reply stops in the middle.
A truncated reply looks like this:
{"category": "bug", "priority": 2, "summary": "The export button fails when the report contains more than 10,000 roThis is not valid JSON. With constrained decoding the situation is subtler. The model was only ever allowed to produce characters consistent with the schema, but nothing forces it to reach the closing brace before the budget runs out. You still get a partial object.
Detect truncation by stop reason
Every major API reports why generation ended. The field name differs by provider, but the idea is the same. Common values:
| Provider style | Field | Truncation value |
|---|---|---|
| OpenAI chat completions | `finish_reason` | `length` |
| Anthropic messages | `stop_reason` | `max_tokens` |
| Google Gemini | `finishReason` | `MAX_TOKENS` |
Do not rely on a parse failure alone. A truncated array of objects can sometimes be cut exactly at a boundary and still parse if a repair tool closes it for you, giving you silently missing items.
from dataclasses import dataclass
class TruncatedOutput(Exception):
"""The model stopped because it ran out of output tokens."""
@dataclass
class ModelReply:
text: str
stop_reason: str # normalized: "end", "length", "refusal", or "other"
def require_complete(reply: ModelReply) -> str:
if reply.stop_reason == "length":
raise TruncatedOutput(
f"Output cut off after {len(reply.text)} characters"
)
return reply.text
try:
require_complete(ModelReply(text='{"category": "bug", "pri', stop_reason="length"))
except TruncatedOutput as err:
print("caught:", err)The ModelReply wrapper is a small adapter you write yourself. Map each provider's stop reason into one set of values so the rest of your code does not care which provider you use.
Fix truncation, do not just retry
Retrying with the same settings usually truncates again at the same point. Better options:
- Raise
max_tokens, with headroom. Estimate the largest realistic output and add 30 to 50 percent. - Shrink the schema. Drop fields you do not use. Long
description-style free-text fields are the most common cause. - Cap free-text fields with
max_lengthand mention the limit in the field description. - Split the job. For long lists, extract in chunks of input rather than asking for everything at once.
- Paginate by design. Ask for at most N items and a
has_moreflag, then ask for the rest in a second call.
A subtle case is a field that the model fills with repeated text. Under some decoders, a model can loop on whitespace or repeated tokens inside a string until the budget ends. A max_length in your validator will not stop generation, but a sensible max_tokens bounds the damage, and the stop reason will tell you what happened.
Refusals
A refusal is when the model declines to produce the requested content, usually for safety or policy reasons. Input that mentions self-harm, violence, or explicit material can trigger one even when your task is legitimate, such as moderating user messages.
Refusals break structured pipelines because a refusal is prose, not your schema. How it arrives depends on the mode:
- Prompt-only or JSON mode. The reply is plain text like "I can't help with that". Parsing fails, and the failure looks like an ordinary formatting error. A retry loop will waste attempts re-asking for something the model will keep declining.
- Schema-constrained outputs. Some providers add an explicit refusal field or a distinct stop reason alongside the content. The refusal text does not have to match your schema, so the content may be empty or absent. OpenAI, for example, exposes a
refusalfield on the message, and Anthropic uses arefusalstop reason. - Function calling. The model may reply in text instead of making the call, or call the function with empty or placeholder arguments.
Handle refusals as a separate outcome
Give refusals their own exception and do not retry them the same way you retry validation errors.
class ModelRefused(Exception):
"""The model declined to answer. Retrying the same prompt will not help."""
def check_refusal(reply: ModelReply) -> None:
if reply.stop_reason == "refusal":
raise ModelRefused(reply.text or "No explanation given")
try:
check_refusal(
ModelReply(text="I can't help with that request.", stop_reason="refusal")
)
except ModelRefused as err:
print("refused:", err)A good model of the outcomes is a result type with three branches: a valid object, a refusal, or a failure. Your calling code then decides what each means for the business. A moderation tool may treat a refusal as "flag for human review". A data-extraction job may log it and skip the record.
A schema can also make refusals unnecessary. If the input can legitimately be unanswerable, give the model a way to say so inside the schema:
from typing import Literal, Optional
from pydantic import BaseModel, Field
class Extraction(BaseModel):
status: Literal["ok", "not_found", "unsafe_content"]
invoice_total: Optional[float] = Field(
default=None,
description="Total in the invoice currency. Null unless status is ok.",
)
print(Extraction(status="not_found").model_dump())The status field gives the model a valid, schema-conforming way to report the problem. This reduces both refusals and invented values, which we turn to next.
Wrong values with a correct shape
This is the hardest category, because nothing throws an error. The output validates, and the data is wrong. Common patterns:
- Hallucinated values. The model fills a required field with something plausible because the schema demands a value. If the invoice has no total and
invoice_totalis required, you may get a made-up number. - Wrong enum choice. The model picks
"other"when"billing"fits, or picks the first option listed. - Misplaced values. A ship-to address lands in the bill-to field. The types match, so validation passes.
- Unit and format drift. Dates in the wrong order (
03/04/2025read as March 4 instead of 3 April), amounts in cents instead of dollars, or a percentage given as 0.15 in one reply and 15 in another. - Copy errors. The model transcribes a long ID with one digit changed.
- Schema-driven distortion. The order of fields matters. A model that must output
answerbeforereasoningcommits to a conclusion before thinking. - Defaulting. Booleans and zero values appear when the model did not know.
falseand0look like real data.
Reduce the problem at the schema
Most prevention is design, not code:
- Make fields that may be missing optional and nullable, and say in the description when to use null.
- Add an explicit
unknownornot_applicableenum member instead of forcing a guess. - State units and formats in descriptions: "Amount in US dollars as a decimal number, for example 12.50" and "Date in ISO 8601 format, YYYY-MM-DD".
- Put a reasoning or evidence field before the answer field when the task needs inference.
- Ask for a supporting quote from the source text for fields that must be grounded.
Verify with code
Grounding checks catch many errors cheaply. If the model returns a quote and a value, confirm that the quote really appears in the input.
import re
from datetime import date
from typing import Optional
from pydantic import BaseModel, field_validator, model_validator
class InvoiceFields(BaseModel):
invoice_number: str
invoice_date: date
total: Optional[float] = None
total_quote: Optional[str] = None
@field_validator("total")
@classmethod
def total_not_negative(cls, value):
if value is not None and value < 0:
raise ValueError("total must not be negative")
return value
@model_validator(mode="after")
def total_needs_quote(self):
if self.total is not None and not self.total_quote:
raise ValueError("a total requires a supporting quote")
return self
def check_grounding(fields: InvoiceFields, source_text: str) -> list[str]:
"""Return a list of problems found by comparing output to the source."""
problems = []
if fields.invoice_number not in source_text:
problems.append("invoice_number does not appear in the source")
if fields.total_quote and fields.total_quote not in source_text:
problems.append("total_quote does not appear in the source")
if fields.total is not None and fields.total_quote:
numbers = re.findall(r"\d+(?:[.,]\d+)?", fields.total_quote)
normalized = [float(n.replace(",", "")) for n in numbers]
if fields.total not in normalized:
problems.append("total does not match the number in its quote")
return problems
source = "Invoice INV-2041 dated 2025-04-03. Total due: 1,250.00 USD."
fields = InvoiceFields(
invoice_number="INV-2041",
invoice_date="2025-04-03",
total=1250.00,
total_quote="Total due: 1,250.00 USD",
)
print(check_grounding(fields, source))This prints an empty list. Change total to 125.00 and the last check reports a mismatch. Note the limits of this approach: it works for extraction, where the answer exists in the input, and not for open-ended generation.
Other cross-field checks that catch errors: line items that must sum to the total, an end date that must come after a start date, a country code that must match a currency, and a value that must fall within a plausible range.
Other residual failures
A few smaller issues appear in practice:
- Schema feature limits. Providers support only a subset of JSON Schema in constrained mode. Unsupported keywords such as certain numeric limits or string patterns may be rejected or silently ignored. Keep the validator in your own code as the source of truth.
- First-request latency. Some providers compile a schema on first use, which adds delay, and complex or deeply recursive schemas may be refused.
- Content filters. A filter can cut a response mid-stream and produce a stop reason distinct from both refusal and length.
- Language and encoding. Non-English text may use more tokens than you estimated, which makes truncation more likely.
- Model changes. A provider update can change how often these failures happen without any change to your code.
A combined guard
Put the checks in the right order in a single function. Provider calls vary, so this one takes the normalized ModelReply from earlier.
from pydantic import BaseModel, Field, ValidationError
class Result(BaseModel):
label: str
confidence: float = Field(ge=0, le=1)
def parse_reply(reply: ModelReply) -> Result:
check_refusal(reply)
text = require_complete(reply)
try:
return Result.model_validate_json(text)
except ValidationError:
raise
good = ModelReply(text='{"label": "spam", "confidence": 0.93}', stop_reason="end")
print(parse_reply(good))Each exception type maps to a different action:
| Exception | Meaning | Typical action |
|---|---|---|
| `TruncatedOutput` | Ran out of tokens | Raise limit or shrink the task, then retry |
| `ModelRefused` | Declined to answer | Do not retry the same prompt. Escalate or skip |
| `ValidationError` | Wrong shape or bad values | Retry with the error as feedback, bounded |
Exercise
A structured-output call returns text that fails JSON parsing. The stop reason is length. Your retry loop re-sends the prompt with the parse error. Why is this a poor response, and what should you do instead?
Show answer
The parse error is a symptom. The real cause is that the model ran out of output tokens, so the same prompt will likely be cut off again at the same point. Check the stop reason before parsing and raise a distinct truncation error. Then raise max_tokens, shrink the schema or cap free-text fields, or split the work into smaller calls.
Exercise
Your invoice schema has a required total field. Some invoices contain no total, and the model returns plausible numbers for them. Name two schema changes that reduce this problem.
Show answer
Make total optional and nullable, with a description saying to use null when no total appears. Alternatively, add a status field with values such as ok and not_found so the model has a valid way to report a missing value. Adding a required total_quote field that you check against the source text also exposes invented values.
Exercise
A schema-constrained call returns a message with an empty content field and a refusal field containing an explanation. Should the retry loop run? What should the caller do?
Show answer
No. A refusal is not a validation error, and re-sending the same prompt will usually produce the same refusal. Raise a separate refusal exception and let the caller decide, for example by logging and skipping the record or sending it to human review.