Tutorial
Get Structured JSON From an LLM With Schemas and Pydantic
Get reliable structured JSON from an LLM using a JSON schema and Pydantic validation in Python. Turn messy text into data your code can trust.
Quick answer
Language models are good at reading messy text and bad at following unwritten formatting rules. If you ask for “a JSON object” you will sometimes get extra commentary, missing fields or a wrong type. The fix is structured output: give the model a JSON schema, then validate the result in Python with Pydantic before your code touches it.
This tutorial turns a free-form customer message into a typed ticket object. The same pattern works for invoices, emails, meeting notes or anything else that arrives as unstructured text.
Why structure matters
Most useful AI features end the same way. A model reads something fuzzy, and then ordinary code has to act on it: file it, route it, store it. Ordinary code needs predictable fields. So the model handles the mess, and everything after it should stay strict and boring.
There are two layers of protection, and you should use both:
- Constrain the output. Ollama accepts a JSON schema in the
formatfield and makes the model produce output that matches it. See the structured outputs guide. - Validate the output. Treat the response like any other untrusted input and check it in your own code.
Setup
ollama pull llama3.2
pip install requests pydantic
You need Python 3.9 or newer and Pydantic 2.x. The model_json_schema and model_validate_json methods used below are Pydantic v2 APIs.
Save the code below, in order, as ticket.py. If you are new to running models locally, start with Run a Local LLM with Ollama.
Step 1: Define the shape with Pydantic
A Pydantic model describes the data you want, and it can generate the JSON schema for you. Using Literal restricts a field to a fixed set of values, which keeps categories consistent.
from typing import Literal
import requests
from pydantic import BaseModel, ConfigDict, ValidationError
class Ticket(BaseModel):
model_config = ConfigDict(strict=True, extra="forbid")
category: Literal["billing", "bug", "feature_request", "other"]
urgency: Literal["low", "medium", "high"]
summary: str
needs_human: bool
Pydantic can export the schema with Ticket.model_json_schema(). The Pydantic JSON schema docs cover every option.
Step 2: Ask for output that matches the schema
Pass the schema in format, and also describe the task in the prompt. It helps to do both: the schema controls the shape, while the prompt guides the content.
OLLAMA_URL = "http://localhost:11434/api/chat"
MODEL = "llama3.2"
INSTRUCTIONS = (
"You triage customer messages. Read the message and return a JSON object "
"with the category (billing, bug, feature_request or other), the urgency "
"(low, medium or high), a one-sentence summary, and whether a human "
"needs to step in."
)
def extract_ticket(message: str, retries: int = 1) -> Ticket:
if type(retries) is not int or retries < 0:
raise ValueError("retries must be a nonnegative integer")
last_error: Exception | None = None
for _ in range(retries + 1):
response = requests.post(
OLLAMA_URL,
json={
"model": MODEL,
"messages": [
{"role": "system", "content": INSTRUCTIONS},
{"role": "user", "content": message},
],
"format": Ticket.model_json_schema(),
"stream": False,
"options": {"temperature": 0},
},
timeout=120,
)
response.raise_for_status()
raw = response.json()["message"]["content"]
try:
return Ticket.model_validate_json(raw)
except ValidationError as error:
last_error = error # Try again, then give up loudly.
raise last_error
A low temperature can help consistency; it does not guarantee the same answer. Strict mode rejects type coercion, and extra="forbid" rejects unexpected fields. See Pydantic strict mode. Schema validation still does not prove the answer is factually right.
Step 3: Use the result like normal data
message = (
"Hi, I was charged twice for my subscription this month and I need "
"this fixed before Friday please."
)
ticket = extract_ticket(message)
print(ticket.category, ticket.urgency, ticket.needs_human)
print(ticket.summary)
Because ticket is a validated object, ticket.urgency is guaranteed to be one of three strings, and your routing code can rely on that. No more digging through free text.
Handle failure on purpose
Even with a schema, things go wrong: a field can be technically valid but wrong, or the call can fail. A few habits help:
- Retry once or twice, as the loop above does, then raise an error you can see.
- Log failed inputs. Every bad case is a free test for your next prompt change.
- Keep a human path. A
needs_humanflag, or a low-confidence route, beats silently guessing. - Check meaning, not just shape. A schema proves the JSON is well formed. It cannot prove the model read the message correctly.
- Remember the input is untrusted too. A customer message can try to steer the model, for example by claiming to be low urgency. Do not let fields like
urgencyorneeds_humanbe your only safeguard for anything important.
FAQ
How do you get structured JSON from an LLM in Python?
Give the model a JSON schema, then validate the result in Python with Pydantic before your code touches it. A Pydantic model can generate the schema with Ticket.model_json_schema(), and you pass it in Ollama’s format field. The tutorial then checks the response with model_validate_json.
What do you need to install for structured output with Ollama and Pydantic?
Run ollama pull llama3.2 and pip install requests pydantic. You need Python 3.9 or newer and Pydantic 2.x, because the model_json_schema and model_validate_json methods used in the tutorial are Pydantic v2 APIs.
Is a JSON schema enough, or do you still need to validate the output?
Use both layers. Ollama accepts a JSON schema in the format field and makes the model produce output that matches it, and you should still treat the response like any other untrusted input and check it in your own code. Even then, schema validation does not prove the answer is factually right.
What do Pydantic strict mode and Literal do?
Using Literal restricts a field to a fixed set of values, which keeps categories consistent. Strict mode rejects type coercion, and extra="forbid" rejects unexpected fields.
What should you do when the model returns invalid or wrong output?
Retry once or twice, as the loop in the tutorial does, then raise an error you can see. Log failed inputs, since every bad case is a free test for your next prompt change. Keep a human path, such as a needs_human flag, because a field can be technically valid but wrong.
Can a customer message trick the model into changing the extracted fields?
The input is untrusted too. A customer message can try to steer the model, for example by claiming to be low urgency. Don’t let fields like urgency or needs_human be your only safeguard for anything important, and remember that a low temperature can help consistency but does not guarantee the same answer.
Where to go next
- Let the model call your code and use structured arguments with Build an AI Agent in Python With Tool Calling.
- Feed extracted fields into a search index using Semantic Search in Python With Embeddings.
- Read the Ollama API documentation to see what else the
formatandoptionsfields can do.


