Intermediate about 4 h
The picture
01
Pydantic model
the contract
02
JSON Schema
sent to the model
03
Forced output
tool or schema mode
04
Validate
parse strictly
05
Repair loop
feed errors back
Three levels of strictness
- Ask nicely for JSON. Works most of the time and fails at the worst moment.
- Force a tool call whose input schema is your schema. The model must fill the schema; you still validate.
- Constrained decoding. The decoder is only allowed to emit tokens that keep the output valid against a grammar or schema, so syntactic validity is guaranteed (semantic correctness is not).
Always validate on your side, whichever level you use.
Forced tool use plus Pydantic
from typing import Literal
from pydantic import BaseModel, Field, ValidationError
import anthropic
class Invoice(BaseModel):
vendor: str
invoice_number: str
total: float = Field(ge=0)
currency: Literal["USD", "EUR", "INR", "GBP"]
due_date: str | None = Field(None, description="ISO 8601 date, or null if absent")
TOOL = {
"name": "record_invoice",
"description": "Record the fields extracted from an invoice.",
"input_schema": Invoice.model_json_schema(),
}
client = anthropic.Anthropic()
def extract(text: str, max_attempts: int = 3) -> Invoice:
messages = [{"role": "user", "content": f"Extract the invoice fields.\n<invoice>\n{text}\n</invoice>"}]
for _ in range(max_attempts):
resp = client.messages.create(
model="claude-sonnet-5-5", max_tokens=1024, temperature=0,
tools=[TOOL], tool_choice={"type": "tool", "name": "record_invoice"}, messages=messages,
)
block = next(b for b in resp.content if b.type == "tool_use")
try:
return Invoice.model_validate(block.input)
except ValidationError as e:
messages += [
{"role": "assistant", "content": resp.content},
{"role": "user", "content": [{"type": "tool_result", "tool_use_id": block.id, "is_error": True,
"content": f"Validation failed, fix these fields:\n{e}"}]},
]
raise ValueError("could not obtain a valid invoice")
The loop turns a validation error into the next prompt, which is far more effective than a blind retry.
Design the schema for the model
- Use enums (
Literal) for closed sets so the model cannot invent categories. - Add descriptions to fields; they act as per-field instructions.
- Make absent information expressible (
None), otherwise the model fabricates a value to satisfy the schema. - Keep schemas flat and small. Deep nesting raises error rates.
Open models and constrained decoding
With open models you can guarantee valid JSON by masking invalid tokens at each step (libraries such as Outlines or the grammar support in inference servers). Validity of syntax is guaranteed; whether the content is right still needs evaluation.
Common mistakes
- Parsing with a regex instead of a schema.
- Letting the model make up values for missing fields.
- Retrying without telling the model what was wrong.
Exercises
- Extract 30 invoices (or any documents) and report field-level accuracy and the share that needed a retry.
- Add a field the documents often lack and show how the
Noneoption changes hallucination.
You are done when you can…
- Define a Pydantic model and obtain validated instances from a model call
- Build a retry loop that feeds the validation error back to the model
- Explain the difference between prompting for JSON, forced tool use and constrained decoding