Sub topic 8
Getting structured output from the model
This chapter assumes you have a Pydantic Invoice model and an extraction prompt, as built in the previous chapters, and that you can call an LLM API. Here you choose how to make the model reply with JSON your code can parse.
Three ways to ask for JSON
| Approach | What it guarantees | Main weakness |
|---|---|---|
| Prompt only ("return only JSON") | Nothing. The model usually complies. | Extra prose, markdown fences, trailing commas |
| JSON mode | The reply is syntactically valid JSON. | Keys and types can still be wrong |
| Schema-constrained output (also called structured outputs, or tool calling with a schema) | The reply matches your JSON schema. | Only a subset of JSON Schema is supported, and the exact options differ by provider |
Check your provider's documentation for the exact parameter names. They differ between APIs and change over time.
Generating the schema from your model
Do not write the JSON schema by hand. Pydantic produces it from the class you already have, so the two cannot drift apart.
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")
schema = Invoice.model_json_schema()
print(json.dumps(schema, indent=2))If your provider accepts a JSON schema, pass this schema in the request. The field descriptions travel with it, so the model sees them as instructions.
Some providers support only part of JSON Schema. Common limits are that every field must be listed as required, or that extra keys must be forbidden. If a request is rejected, simplify the model first. Plain types and Optional fields are the safest.
When you only have prompt-based JSON
Without schema support, expect messy replies. A model may wrap the JSON in a sentence or in a markdown fence. A small helper that extracts the outermost object removes most of these failures.
import json
def parse_json_reply(raw: str) -> dict:
start = raw.find("{")
end = raw.rfind("}")
if start == -1 or end <= start:
raise ValueError("No JSON object found in reply")
return json.loads(raw[start:end + 1])
reply = 'Here is the result:\n{"vendor": "Acme Ltd", "invoice_number": "INV-42"}'
print(parse_json_reply(reply))This helper does not check the keys or types. That is the job of validation, which comes next.
What constrained output does not fix
Constraints can also affect quality in two ways:
- Keys are generated in schema order. If you put a field that needs reasoning before the fields it depends on, the model has less context when it fills it in.
- A strict schema pushes the model to fill every field. Keep missing values explicitly nullable (
Optional) so thatnullis a legal answer.
Choosing an approach
- Use schema-constrained output if your provider offers it. It removes most parsing failures.
- Otherwise use JSON mode and validate every reply.
- Use prompt-only JSON as a last resort, with a tolerant parser like the one above.
Whichever you choose, treat the reply as untrusted input until it passes validation.
Exercise
Your provider enforces your JSON schema, and every reply parses without errors. A teammate says validation and grounding checks are now unnecessary. What is wrong with that claim?
Show answer
Schema enforcement only guarantees that keys and types are correct. It says nothing about whether values are right or appear in the document. The model can still return a wrong total or an invented invoice number, so you still need validation of business rules and grounding checks against the source text.