Sub topic 10
Designing schemas that models fill in well
This chapter assumes you can write a Pydantic model, have read the chapters on JSON Schema and schema-constrained decoding, and run Python 3.10 or newer. It covers how to shape a schema so the model's output is accurate, not only valid.
A schema that parses is not the same as a schema that works. A model can return perfectly valid JSON in which every field is wrong. The schema is part of the prompt. The model reads its field names, descriptions, enum values, and order, and uses them to decide what to write. Design it as you would design instructions for a new colleague.
The schema is read by the model
With constrained decoding, the provider usually passes your schema to the model as text, or something close to it. The model never sees your Python class or your comments. It sees the JSON Schema that was generated from them.
Two things follow:
- Anything you want the model to know must appear in the schema itself: in a field name, a
description, or an enum value. - Anything you want to enforce must be checked by code, because the schema only constrains what the provider chooses to support.
The sections below cover each design choice with that in mind.
Prefer enums to free strings
A free str field lets the model invent spellings. Across 10,000 tickets you might get "Billing", "billing issue", "payments", and "BILLING". Downstream code that branches on the value then breaks quietly.
A Literal or Enum closes the set. The model picks one value, and a validator can reject anything else.
Enums also need an escape hatch. If every input must map to one of four labels, an input that fits none of them gets forced into a wrong label. Add "other" or "unknown", and say in the description when to use it. A wrong label that looks valid is harder to detect than an honest "unknown".
Keep the enum values meaningful on their own. Values like "A", "B", "C" force the model to remember a mapping defined elsewhere. Values like "billing" and "bug" carry their own meaning.
Write descriptions that settle ambiguity
Add a description wherever a careful human reader could interpret a field in more than one way. Good descriptions state:
- The unit or format:
"Total in cents, e.g. 1999 for 19.99". - The scale and direction:
"1 is most urgent, 3 is least urgent". - The source of the value:
"Vendor name exactly as printed on the invoice". - What to do when the information is absent:
"null if the due date is not stated".
Do not repeat the field name. name: str with the description "The name" adds nothing. Also avoid long essays. A description is read on every call, so every extra sentence costs tokens and latency.
Field names matter as much as descriptions. total_cents tells the model the unit. total does not. due_date suggests a date. due is vague.
A weak schema and a better one
Here is an invoice schema as many people first write it:
from pydantic import BaseModel
class WeakInvoice(BaseModel):
vendor: str
status: str
total: str
due: strThe model has to guess everything. Is total "$19.99", "19.99 USD", or "nineteen ninety-nine"? What does due contain when the invoice has no due date? The model may write "N/A", "none", or an empty string, and each choice breaks a different downstream parser.
This version removes those guesses:
import json
from datetime import date
from typing import Literal
from pydantic import BaseModel, Field
class Invoice(BaseModel):
vendor_name: str = Field(
description="Vendor name exactly as printed on the invoice"
)
status: Literal["paid", "unpaid", "unknown"] = Field(
description="Payment status. Use 'unknown' if the invoice does not say."
)
total_cents: int = Field(
ge=0,
description="Invoice total in the smallest currency unit, e.g. 1999 for 19.99",
)
currency: Literal["USD", "EUR", "GBP", "other"]
due_date: date | None = Field(
description="Due date as YYYY-MM-DD, or null if the invoice does not state one"
)
if __name__ == "__main__":
print(json.dumps(Invoice.model_json_schema(), indent=2))Run it and read the output the way the model would. Each field now has a known type, a closed set of values, or a stated rule for missing data.
due_date is required but nullable. That distinction matters in the next section.
Required versus nullable
Strict structured-output modes commonly require every property to be listed in required and additionalProperties to be false. Check your provider's documentation, since the rules differ and change over time. Under those rules you cannot make a field optional by leaving it out. You make it nullable instead:
| Pydantic declaration | In JSON Schema | Meaning for the model | Column |
|---|---|---|---|
| `x: str` | required, string | Must produce a string | |
| `x: str \ | None` (no default) | required, string or null | Must produce the key, may write `null` |
| `x: str \ | None = None` | not required, string or null | May omit the key entirely |
For strict modes, prefer the second form. The model must make an explicit decision about every field, and your code can tell "the model said there is no due date" from "the model forgot the field".
Never use an empty string, 0, or -1 as a stand-in for "missing". Those values look like real data. null does not.
Field order is generation order
A model writes its output one token at a time, from left to right. Every token depends on the tokens before it. Constrained decoding does not change this, and most providers emit properties in the order the schema lists them.
So if one field is a conclusion and another is the evidence for it, put the evidence first:
import json
from typing import Literal
from pydantic import BaseModel, Field
class ReviewVerdict(BaseModel):
evidence: str = Field(
max_length=300,
description="The sentence or phrase in the review that most supports the sentiment",
)
sentiment: Literal["positive", "negative", "mixed"]
class VerdictFirst(BaseModel):
sentiment: Literal["positive", "negative", "mixed"]
evidence: str = Field(max_length=300)
print(list(ReviewVerdict.model_json_schema()["properties"]))
print(list(VerdictFirst.model_json_schema()["properties"]))The first line prints ['evidence', 'sentiment'] and the second prints ['sentiment', 'evidence']. With the first model, the model writes its justification before it commits to a label. With the second, it commits first and then writes a justification for whatever it already chose.
Putting a short reasoning or evidence field ahead of the answer is a cheap way to improve accuracy on judgment tasks. Keep it short and bounded. It is extra output you pay for on every call, and an unbounded reasoning field is a common cause of truncation.
Keep the schema small and shallow
Models fill in small, flat schemas more accurately than large nested ones. Some practical limits:
- Ask for only the fields your code uses. Every extra field is another chance for an error and more output tokens.
- Avoid deep nesting. Two or three levels is comfortable. Beyond that, accuracy drops and some providers reject the schema outright.
- Avoid recursive types and large
anyOfunions unless you need them. Providers support these inconsistently. - For large documents, split the work into several smaller calls, each with its own schema, instead of one giant call.
Lists need extra care. A model asked for list[LineItem] decides for itself when to stop. If you know the list should have between 1 and 20 entries, say so in the description, and check the length in code.
Let code do the arithmetic
Models are poor at computation, such as summing a column or counting items, and good at reading. If a value can be derived from other fields, do not ask the model for it. Ask for the inputs and compute the result yourself:
from pydantic import BaseModel, Field
class LineItem(BaseModel):
description: str
unit_price_cents: int = Field(ge=0)
quantity: int = Field(ge=1)
def total_cents(items: list[LineItem]) -> int:
return sum(item.unit_price_cents * item.quantity for item in items)
items = [
LineItem(description="Widget", unit_price_cents=250, quantity=4),
LineItem(description="Shipping", unit_price_cents=599, quantity=1),
]
print(total_cents(items))This prints 1599. If you also need the printed total from the document, extract it as a separate field and compare it with your computed sum. A mismatch tells you the extraction is wrong somewhere, which is a check you cannot do if you only trust the model's own total.
What the schema can and cannot enforce
Pydantic accepts many constraints: ge, le, max_length, pattern. Provider support for the same constraints in constrained decoding is narrower. Many strict modes support types, enums, required, and additionalProperties, and reject or ignore numeric ranges, string lengths, and patterns. This is why the hand-written JSON Schema earlier in this tutorial lists priority as a plain integer, while the Pydantic model adds ge=1, le=3.
Plan for both layers:
| Constraint | Put it in the schema? | Also check in code? |
|---|---|---|
| Field types and required keys | Yes | Yes, by validation |
| Enum values | Yes | Yes |
| Numeric range, string length | If the provider supports it | Always |
| Cross-field rules (end after start) | Cannot express well | Always |
| Meaning ("is this the real vendor?") | No | Spot checks and tests |
A constraint the provider ignores still helps when you also state it in the description, because the model reads it. Then validation catches the cases where the model disregards it.
A design checklist
The diagram shows the order of decisions for each field.
Changing a schema safely
Schemas change as requirements change. Each change alters the prompt the model sees, so treat it like a code change:
- Adding an enum value or reordering fields can shift model behavior on inputs that previously worked. Rerun your test examples after every schema edit.
- Renaming a field is a breaking change for any stored data. Keep a
schema_versionin your own records, even though the model does not need to produce it. - Add new fields as nullable first, so old stored results still validate.
- Keep descriptions in the schema, not in a separate prompt, so they cannot drift apart.
Common mistakes
- Using
strfor every field, then parsing the strings afterwards. - Using
"","N/A", or0to mean missing. - Asking for a computed total, count, or percentage instead of the inputs.
- Putting a conclusion field before its supporting evidence.
- Writing descriptions that only repeat the field name.
- Enums with no
unknownoption, which force wrong answers. - Trusting a range or length limit that the provider does not enforce.
Exercise
A schema has the fields answer: Literal["yes", "no"] followed by explanation: str. The model's explanations often contradict its answer. Name two schema changes that could reduce this, and say why each helps.
Show answer
First, move explanation (or a better-named reasoning field) before answer. The model generates tokens left to right, so it then writes its reasoning first and picks the label with that reasoning already in context, instead of justifying a label it has already committed to. Second, add an "unclear" value to the enum and describe when to use it, because a forced yes/no on an ambiguous input produces an answer the explanation cannot honestly support. Bounding the explanation with a length limit, checked in code, also helps prevent rambling or truncation.
Exercise
A schema declares discount: float and the description says nothing else. Some replies contain 0.15, others 15, and others "15%" is rejected. Rewrite the field so the format is unambiguous, and say how you would handle invoices that have no discount.
Show answer
Use a precise name, type, and description, for example discount_percent: float | None = Field(ge=0, le=100, description="Discount as a percentage from 0 to 100, e.g. 15 for 15%. null if no discount is stated."). The unit in the name and the example in the description remove the ambiguity. Missing discounts become null instead of 0, which would wrongly claim that the invoice states a zero discount. Because the provider may ignore ge and le, still validate the range locally with Pydantic.