Sub topic 8
Getting structured output from the model
This chapter assumes you can call an LLM API from Python, read JSON, and have already defined a Pydantic schema such as the Invoice model from the previous chapters. Here you will learn the ways to make a model return data in a fixed shape, what each one guarantees, and where each one still fails.
Why free-form replies break pipelines
A model asked for "the invoice data" will often answer with a friendly sentence, a Markdown table, or JSON wrapped in prose. Code that expects a JSON object then fails on the first character. Even when the reply is JSON, it may have a trailing comma, a missing key, or a number written as "1,200.50".
There are three levels of control, from weakest to strongest:
- Prompt-only. You ask for JSON in the prompt and parse whatever comes back.
- JSON mode. The API guarantees the reply is syntactically valid JSON, but not that it matches your schema.
- Schema-constrained output. The API restricts generation so the reply conforms to a JSON Schema you supply.
Each level reduces failures, but none replaces the validation step covered in the next chapter.
Level 1: Prompt-only JSON
The prompt from the earlier chapter already names the keys and says "Return only a JSON object". This works with almost any model. The cost is that you must clean the reply before parsing. A common problem is a Markdown fence around the JSON.
import json
import re
def parse_json_reply(raw: str) -> dict:
"""Extract and parse the first JSON object in a model reply."""
cleaned = raw.strip()
# Remove a surrounding ```json ... ``` fence if present.
fenced = re.match(r"^```(?:json)?\s*(.*?)\s*```$", cleaned, re.DOTALL)
if fenced:
cleaned = fenced.group(1)
# Fall back to the outermost braces if prose surrounds the object.
start, end = cleaned.find("{"), cleaned.rfind("}")
if start == -1 or end == -1:
raise ValueError("No JSON object found in reply")
return json.loads(cleaned[start:end + 1])
print(parse_json_reply('Here you go:\n{"vendor": "Acme", "total": 12.5}'))This helper rescues many replies, but it is a patch. If you can use a stronger level, prefer it.
Level 2: JSON mode
Many providers offer a "JSON mode" or a response-format flag. It forces the output to parse as JSON. It does not force particular keys or types. A reply of {"company": "Acme"} is valid JSON mode output even though your schema expects vendor.
JSON mode usually still requires you to mention JSON in the prompt, and it can truncate. If the model hits its maximum output length mid-object, you get invalid JSON anyway. Check the stop reason in the API response, which is often named finish_reason or stop_reason, and treat a "length" value as a failure.
Level 3: Schema-constrained output
With schema-constrained output (also called structured outputs), you send a JSON Schema and the provider restricts token generation so the reply conforms. Pydantic can produce that schema for you:
import json
from typing import Optional
from pydantic import BaseModel, Field
class Invoice(BaseModel):
vendor: str = Field(description="Name of the company issuing the invoice")
invoice_number: str
invoice_date: Optional[str] = Field(default=None, description="ISO 8601 date, or null if absent")
currency: Optional[str] = Field(default=None, description="Three-letter currency code, or null if absent")
total: Optional[float] = Field(default=None, description="Grand total as a number, or null if absent")
print(json.dumps(Invoice.model_json_schema(), indent=2))The printed schema includes each field's description. Providers pass these descriptions to the model, so they act as per-field instructions. This is why the schema chapter asked you to write them carefully.
How you pass the schema depends on the provider. Some accept a response-format parameter that takes a JSON Schema. Others use tool calling (also called function calling): you define a "tool" whose parameters are your schema and instruct the model to call it. The arguments of that call are your structured data. Both approaches use the same schema. Check your provider's documentation for the exact parameter names, because they differ and change.
Required fields and the null trap
Constrained output guarantees the keys exist. This creates a subtle problem with required fields. If invoice_number is required and the document has none, the model must still emit a string, and it may invent one.
Two practical rules follow:
- Make a field optional (nullable) whenever the document may legitimately lack it. In the
Invoicemodel,vendorandinvoice_numberare required, so for documents that may lack them you should loosen them too. - Many strict modes require every property to appear in the schema's
requiredlist, with "optional" expressed as a union withnull. Pydantic'sOptional[str]producesanyOfwithnull, which satisfies this. A default value alone may not be enough for some providers.
Field order and reasoning
Constrained generation fills fields in schema order. If a field depends on reasoning, such as a total you want the model to compute from line items, place the supporting fields first. A model that writes line_items before total can use them. One that writes total first must guess.
If you need free-text reasoning, add an explicit field for it, placed before the answer fields, and discard it afterward:
from typing import Optional
from pydantic import BaseModel
class InvoiceWithNotes(BaseModel):
notes: str # short reasoning; ignored downstream
vendor: Optional[str] = None
invoice_number: Optional[str] = None
total: Optional[float] = None
print(InvoiceWithNotes.model_json_schema()["properties"].keys())Use this sparingly. It costs output tokens, and for plain field lookup it rarely helps.
Choosing a level
| Approach | Guarantees | Main failure modes | Use when |
|---|---|---|---|
| Prompt-only | Nothing | Prose, fences, wrong keys | The model has no JSON features |
| JSON mode | Valid JSON syntax | Wrong keys or types, truncation | Schema constraints are unavailable |
| Schema-constrained | Keys and types match the schema | Invented values for required fields, truncation, unsupported schema features | Default choice when offered |
| Tool calling | Similar to schema-constrained | Model may skip the tool call unless forced | Provider lacks a response-format option |
Edge cases to handle
- Truncation. A long list of line items can exceed the output limit. Check the stop reason and raise
max_tokens, or split the work as described in the chapter on long documents. - Refusals. Some providers return a refusal field instead of content when a safety filter triggers. Handle it before parsing.
- Type coercion. Models write amounts as
"1,200.50"or"$1200". Constrained output keeps the type asfloat, but unconstrained modes do not. Pydantic in its default mode will coerce"1200.5"to a float but reject"1,200.50". - Semantic errors. A reply can match the schema perfectly and still be wrong, for example a
datethat is valid but taken from the due date field. Schema conformance says nothing about truth. That is the job of validation, grounding and evaluation.
A combined parse function
This function accepts any raw reply, handles the fence problem, and validates with the model:
import json
import re
from typing import Optional
from pydantic import BaseModel, ValidationError
class Invoice(BaseModel):
vendor: Optional[str] = None
invoice_number: Optional[str] = None
total: Optional[float] = None
def parse_invoice(raw: str) -> Invoice:
cleaned = re.sub(r"^```(?:json)?|```$", "", raw.strip()).strip()
try:
return Invoice.model_validate(json.loads(cleaned))
except (json.JSONDecodeError, ValidationError) as exc:
raise ValueError(f"Unusable model reply: {exc}") from exc
print(parse_invoice('```json\n{"vendor": "Acme", "total": "99.5"}\n```'))The string "99.5" is coerced to 99.5. A reply with "total": "n/a" would raise, which feeds the retry loop in the next chapters.
Exercise
Your provider offers schema-constrained output. A scanned receipt has no invoice number, but your schema declares invoice_number: str as required. What is the likely result, and how do you fix it?
Show answer
The model must emit some string for the required field, so it will probably invent a plausible number. Declare the field as Optional[str] (nullable) and tell the prompt to return null when the value is absent. Then verify with a grounding check that any returned number appears in the source text.
Exercise
A reply parses as valid JSON in JSON mode, but json.loads fails on some long invoices. What should you check first?
Show answer
Check the stop reason. If it indicates the output hit the length limit, the JSON was cut off mid-object. Raise the output token limit or split the document, and treat a length stop as a failure rather than parsing the partial text.