Module 4 · Structured outputs & tools
JSON outputs and strict schemas
7 min read
When a model's answer is read by a program rather than a person, "almost right" is no longer enough: a missing field, a date in the wrong format or text before the JSON breaks whatever comes next. Lesson 1.4 laid out the format specification; this one shows how to get output guaranteed to match a schema with Claude, and how to approach that with a model that offers no such guarantee.
The schema, the source of truth
Everything starts with a schema written once, in code. With Pydantic, it serves three purposes: describing the format to the model, validating the answer, and giving the program a typed object.
class Commande(BaseModel):
model_config = ConfigDict(extra="forbid")
fournisseur: str = Field(description="Raison sociale du fournisseur, telle qu'écrite dans le document")
montant_ht: float = Field(description="Montant hors taxes, nombre décimal sans symbole")
devise: Literal["EUR", "USD", "CHF"]
echeance: date = Field(description="Date limite de paiement, format AAAA-MM-JJ")
penalites_retard: bool
Each element of the schema is an instruction:
| Element | What it enforces |
|---|---|
extra="forbid" | No extra fields (the generated JSON Schema contains "additionalProperties": false) |
Literal["EUR", "USD", "CHF"] | A closed list of values: no "€" or "euros" |
date | The ISO YYYY-MM-DD format, validated |
Field(description=...) | One instruction per field, passed to the model with the schema |
With Claude: guaranteed output
The Claude API constrains generation to the schema: the answer is valid, conforming JSON, with no text around it. The Python SDK accepts the Pydantic model directly and returns the validated object:
def extract_order(document: str) -> Commande:
"""Sortie structurée garantie : la réponse est un objet Commande validé, ou une exception."""
response = client().messages.parse(
model=config.CLAUDE_MODEL,
max_tokens=2000,
system="Tu extrais les informations clés des bons de commande pour qu'un programme les enregistre.",
messages=[{"role": "user", "content": f"<bon_de_commande>\n{document}\n</bon_de_commande>"}],
output_format=Commande,
)
return response.parsed_output
Without the high-level SDK, the same mechanism goes through output_config.format with a JSON Schema. Two important remarks:
- The guarantee covers form, not substance. The JSON will conform; the amount can still be wrong. The module 1 lessons (instructions, examples) remain necessary for accuracy;
- "Prefilling" no longer exists on current Claude models: ending the conversation with an assistant message (
{for instance) to force the start of the answer returns a 400 error. Structured outputs replace it, and do better.
Without a guarantee: schema, validation, retry
A small local model, or an API without constrained generation, guarantees nothing. You then combine three defenses:
- The schema in the prompt, as Pydantic produces it:
def schema_prompt(po: PurchaseOrder) -> list[dict]:
"""V2 + le schéma JSON complet, tel que Pydantic le produit."""
messages = prompt_v2(po)
schema = json.dumps(Commande.model_json_schema(), ensure_ascii=False, indent=1)
messages[1] = {"role": "user", "content": messages[1]["content"] + f"\n\nSchéma JSON à respecter :\n{schema}"}
return messages
- Strict validation, which returns a readable error message:
def validate(output: str) -> tuple[Commande | None, str | None]:
"""Renvoie l'objet validé, ou le message d'erreur à renvoyer au modèle."""
match = JSON_OBJECT.search(output)
if not match:
return None, "La réponse ne contient aucun objet JSON."
try:
return Commande.model_validate_json(match.group(0)), None
except ValidationError as e:
return None, "; ".join(f"{'.'.join(map(str, err['loc']))} : {err['msg']}" for err in e.errors())
- A retry that sends the model back its answer and the precise error ("echeance : Input should be a valid date"), rather than blindly asking the same question again.
The results on 100 purchase orders (Qwen2.5-1.5B):
| Variant | Schema-conforming | Exact (5 fields) | Supplier | Amount | Currency | Due date | Penalties |
|---|---|---|---|---|---|---|---|
| Format instructions only (V2) | 0.96 | 0.55 | 0.96 | 0.68 | 0.92 | 0.96 | 0.81 |
| + JSON schema in the prompt | 0.97 | 0.42 | 0.97 | 0.48 | 0.93 | 0.97 | 0.85 |
| + schema, validation, 1 retry | 0.99 | 0.43 | 0.99 | 0.49 | 0.94 | 0.99 | 0.87 |
Validation and retry do what is expected of them: 99% conforming outputs, at the cost of 3 retries out of 100. But accuracy drops from 0.55 to 0.43 as soon as the schema is added, and it all comes from a single field: the amount, which falls from 0.68 to 0.48 while the other four improve slightly.
Comparing, order by order, the amounts that are right without the schema and wrong with it reveals two mechanisms:
| Document | Without schema | With schema | Error |
|---|---|---|---|
| "Montant HT : 51.801,05 euros" | 51801.05 | 51.80105 | The thousands dot read as a decimal point |
| "Pour un total de 42.350,00 euros HT" | 42350.0 | 42.35 | Same: an amount divided by 1,000 |
| "Montant HT : 4 100,00 euros" | 4100.0 | 4100.5 | The ".5" of the format example copied |
| "… 60300,00 EUR, soit 12,060 EUR de TVA" | 60300.0 | 12450.5 | The instruction's example value copied verbatim |
The first mechanism is the most frequent: the long, technical Pydantic schema pulls attention away from the "no thousands separator" instruction, and the model falls back on the English reading of the dot. The second is example contamination: the instructions say "as a decimal number (12450.5)", and that number bleeds into the answers.
Three lessons:
- schema conformance does not measure accuracy: 0.99 valid outputs, 0.43 correct ones. A validation only catches what it checks;
montant_ht: 51.80105is a perfectly validfloat; - adding instructions can degrade a task: the "extra" schema cost 12 points. Every addition to the prompt must be measured, like everything else;
- format examples are examples: an illustrative value (12450.5) will sometimes be copied. Prefer an unambiguous value, or several complete examples (lesson 1.2).
With Claude and messages.parse, the first problem (form) disappears; the second (substance) remains to be measured. For a critical field like an amount, a consistency check in code (does the extracted amount appear in the document, once normalized?) catches what the schema lets through.
Designing a good schema
| Rule | Why |
|---|---|
| Explicit field names | montant_ht rather than m: the name is itself an instruction |
Closed lists (Literal, enum) whenever possible | The model cannot invent a value |
Precise types (date, float, bool) | Validation catches approximate formats |
| A field for absence | "echeance": null allowed, rather than an invented value when the information is missing |
| A flat, short schema | Each nesting level and each optional field increases errors |
| Amounts as numbers, not text | "12 450,00 €" is hard to compute with; 12450.0 is easy |
The last point echoes lesson 2.3: the model extracts, code computes. A well-designed schema is the boundary between the two.
Key takeaways
- A single Pydantic schema describes the format to the model, validates the answer and gives the program a typed object.
- With Claude,
messages.parseoroutput_config.formatguarantee conforming JSON; prefilling no longer exists.- The guarantee covers form, not the accuracy of the content: here, 0.99 conforming outputs but 0.43 correct ones.
- Adding the schema to the prompt cost 12 points (misread amounts, copied format example): measure every addition.
- Without a guarantee: schema in the prompt, strict validation, retry with the precise error.
- Closed lists, precise types, nullable fields, a flat schema.
Practice
- Run
examples/06_outputs_tools_injection.pyand read the most frequent validation errors: which fields cause trouble? - Make
echeanceoptional (date | None) and add purchase orders without a due date to the test set: does the model invent a date? - With
QUILL_FAKE=1, callclaude.extract_orderon a purchase order and inspect the returned object.