Structured Outputs in Python: Get Valid JSON From an LLM Every Time
The problem: your code needs data, the model writes text
Tool calls are one way a model hands structured data to your code. The other is the final answer. Often your agent's answer is not for a person to read but for code to use: a packing list to render as checkboxes, a day by day plan to save in a database, a decision like "needs_umbrella": true that drives the next step.
Asking politely for JSON does not make it reliable. Models wrap JSON in markdown fences, add a friendly sentence before it, drop a field, rename a key, or put a string where a number belongs. Any one of those crashes json.loads or, worse, passes parsing and breaks something later.
This lesson builds three layers of protection for the trip helper:
- Constrained output: ask the server to follow a JSON Schema with
response_format. - Validation: check the result with pydantic, including rules no schema can express.
- Retry with feedback: if validation fails, show the model exactly what was wrong and ask again.
Layer 1: response_format with a JSON Schema
In the chat completions API, response_format controls the shape of the reply. OpenAI documents two JSON options:
{"type": "json_object"}, called JSON mode, which produces valid JSON but does not enforce any particular shape.{"type": "json_schema", "json_schema": {...}}, called Structured Outputs, which makes the output follow the schema you supply.
OpenAI's structured outputs guide says Structured Outputs is the evolution of JSON mode and recommends it over JSON mode where possible. Ollama lists response_format among the request fields its OpenAI compatible endpoint supports.
Save this as json_schema_format.py:
python# file: json_schema_format.py import json from llm import client, MODEL packing_schema = { "type": "object", "properties": { "city": {"type": "string"}, "items": {"type": "array", "items": {"type": "string"}}, "needs_umbrella": {"type": "boolean"}, }, "required": ["city", "items", "needs_umbrella"], "additionalProperties": False, } response = client.chat.completions.create( model=MODEL, messages=[ {"role": "system", "content": "You write packing lists as JSON."}, {"role": "user", "content": "Packing list for 3 rainy days in Kyoto, at most 6 items."}, ], response_format={ "type": "json_schema", "json_schema": {"name": "packing_list", "schema": packing_schema, "strict": True}, }, temperature=0, ) raw = response.choices[0].message.content print("raw text from the model:", raw) data = json.loads(raw) # still a string until you parse it print("umbrella?", data["needs_umbrella"], "| items:", data["items"])
The json_schema object has a name, the schema itself, and strict. When run with qwen2.5:1.5b on Ollama, the reply was a clean JSON object with all three fields, needs_umbrella set to true, and six items. Note that "Sunglasses" made the list for three rainy days. The schema controls the shape of the answer, not whether its contents make sense.
Two details in the code matter:
message.contentis still a string. You must parse it withjson.loads.- The schema sets
"additionalProperties": Falseand lists every property inrequired. OpenAI's guide saysadditionalProperties: falsemust always be set on objects for Structured Outputs, and the same schema works on Ollama, so writing schemas this way keeps them portable.
Why a schema is not enough
Even perfectly shaped JSON can be wrong:
- a cost of
-3euros - a day number of
40in a 3 day trip - a total that does not match the sum of the days
- a date in the past
The OpenAI guide itself says your application still needs to handle refusals, incomplete responses and API errors, and to validate any business rules that the schema does not express. Also, not every server enforces every schema keyword the same way. So treat the schema as a strong hint to the model and do the real checking in your own code.
Layer 2: pydantic models as the single source of truth
Pydantic lets you define the data shape once as a Python class, generate the JSON Schema from it, and validate the model's output against it, including custom rules. Save this as trip_plan.py:
python# file: trip_plan.py import json from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator from llm import client, MODEL class DayPlan(BaseModel): model_config = ConfigDict(extra="forbid") day: int = Field(ge=1, le=14) activity: str cost_eur: float = Field(ge=0) class TripPlan(BaseModel): model_config = ConfigDict(extra="forbid") city: str days: list[DayPlan] total_cost_eur: float = Field(ge=0) @model_validator(mode="after") def total_matches_days(self): # A business rule that no JSON Schema can express. expected = round(sum(d.cost_eur for d in self.days), 2) if abs(expected - self.total_cost_eur) > 1: raise ValueError(f"total_cost_eur is {self.total_cost_eur} but the days add up to {expected}") return self def ask_structured(messages: list, schema_model: type[BaseModel], retries: int = 3) -> BaseModel: response_format = { "type": "json_schema", "json_schema": {"name": schema_model.__name__, "schema": schema_model.model_json_schema(), "strict": True}, } messages = list(messages) # do not modify the caller's list for attempt in range(1, retries + 1): response = client.chat.completions.create( model=MODEL, messages=messages, response_format=response_format, temperature=0 ) raw = response.choices[0].message.content or "" try: return schema_model.model_validate_json(raw) except ValidationError as exc: print(f"attempt {attempt} failed validation:\n{exc.errors(include_url=False)}") # Show the model its own output and the exact problems, then ask again. messages.append({"role": "assistant", "content": raw}) messages.append({"role": "user", "content": "That JSON is invalid: " + json.dumps(exc.errors(include_url=False), default=str) + ". Return the corrected JSON only."}) raise RuntimeError(f"No valid {schema_model.__name__} after {retries} attempts") if __name__ == "__main__": plan = ask_structured( [{"role": "system", "content": "You plan short trips. Costs are in EUR."}, {"role": "user", "content": "Plan 3 days in Lisbon on a small budget."}], TripPlan, ) for d in plan.days: print(f"day {d.day}: {d.activity} ({d.cost_eur} EUR)") print("total:", plan.total_cost_eur, "EUR")
What the classes say:
DayPlan.daymust be between 1 and 14 (Field(ge=1, le=14)), andcost_eurcannot be negative.ConfigDict(extra="forbid")rejects unknown keys and makes pydantic emitadditionalProperties: falsein the schema.TripPlan.total_matches_daysis a model validator that runs after the fields pass. It checks a rule across fields: the total must match the sum of the days, within 1 euro.
TripPlan.model_json_schema() turns the class into the JSON Schema sent in response_format. You never write the schema by hand, so the schema and the validation cannot drift apart. OpenAI's guide recommends the same thing: use native SDK schema helpers to avoid divergence between your schema and your types.
See validation catch a bad answer
Before involving a model, check that the rules actually reject bad data. Save this as validation_demo.py:
python# file: validation_demo.py from pydantic import ValidationError from trip_plan import TripPlan # Valid JSON that breaks the rules: a negative cost and a wrong total. bad = '{"city": "Lisbon", "days": [{"day": 1, "activity": "Tram 28", "cost_eur": -3}], "total_cost_eur": 50}' try: TripPlan.model_validate_json(bad) except ValidationError as exc: for err in exc.errors(include_url=False): print(err["loc"], err["msg"])
In the tested run it printed:
text('days', 0, 'cost_eur') Input should be greater than or equal to 0
The error says exactly where the problem is: the cost_eur field of the first item in days. That location is what you send back to the model in the retry step. The total mismatch in this example was not reported because pydantic runs the "after" model validator only once the individual fields are valid. Fix the cost to 3 and run it again to see the total rule fire.
Animation: JSON mode checks syntax, a schema checks shape, and pydantic checks the rules. Only the last one caught the negative cost.
Layer 3: retry with the validation errors
ask_structured in trip_plan.py ties it together:
- Build
response_formatfrom the pydantic class. - Call the model.
- Try
model_validate_jsonon the reply. - On success, return a typed Python object.
- On failure, append the model's own reply and a user message containing the validation errors, then try again, up to
retriestimes. - If every attempt fails, raise an error your agent can handle.
Running python trip_plan.py with qwen2.5:1.5b produced a valid 3 day Lisbon plan on the first attempt in the tested run, with a total that matched the day costs. The retry path still matters: models vary between runs, and a single failure in production should cost one extra call, not a crash.
A few design choices in the retry:
- The errors are specific.
exc.errors(include_url=False)gives the field location and message without links to pydantic's docs, which the model does not need. - The model sees its own mistake. Appending the bad reply as an assistant message lets the model correct that answer instead of starting from scratch.
- The caller's list is copied. Retries add messages, but the conversation outside this function stays clean.
- There is a limit. Three attempts, then a clear exception. An endless repair loop is a budget problem waiting to happen (lesson 11).
flowchart TD A["Build response_format from<br/>TripPlan.model_json_schema()"] --> B["Call the model"] B --> C{"model_validate_json<br/>passes?"} C -->|yes| D["Return a typed TripPlan"] C -->|no| E{"Attempts left?"} E -->|yes| F["Append the bad reply and<br/>the validation errors"] F --> B E -->|no| G["Raise a clear error"]
Diagram: Validate, and on failure send the bad reply plus the errors back, until the attempts run out.
The SDK's parse helper
The OpenAI Python SDK also has a helper that takes a pydantic class directly and returns the parsed object. The structured outputs guide shows it as client.responses.parse(..., text_format=YourModel) on the Responses API, and the SDK has client.chat.completions.parse(..., response_format=YourModel) for chat completions. These helpers are convenient on OpenAI. Outside OpenAI, compatibility varies, which is why this lesson builds the request by hand with model_json_schema(): it is the same idea and works on any server that accepts json_schema.
Structured outputs or a tool call?
Both produce JSON. OpenAI's guide draws the line this way: use function calling when you connect the model to tools, functions and data in your system, and use a json_schema response format when you want to structure the model's response to the user. In agent terms:
| You want | Use |
|---|---|
| The model to request an action or a lookup | a tool call (lessons 2 to 4) |
| The final answer in a fixed shape | response_format with json_schema |
| A plan your code will execute step by step | response_format (lesson 10 does this) |
This course does not combine tools and response_format in one request, because how a server handles both at once is not something to assume across providers. A simple, portable pattern is to run the tool loop to gather facts, then make one final call with response_format and no tools to produce the structured answer.
Common mistakes
- Parsing without validating.
json.loadssucceeding means the JSON is well formed, nothing more. - Optional fields in strict schemas. OpenAI's strict mode expects every property to be listed in
required. To allow a missing value, make the type nullable (for examplestr | Nonein pydantic) instead of leaving the field out. - Asking for JSON in the prompt but not in
response_format. Prompt instructions alone are a request;response_formatgives the server something to enforce. - Retrying forever. Cap the attempts and raise a clear error.
- Huge schemas. Every field is something the model must fill in. Keep schemas to what your code actually uses.
What to try next
- Change the user request to "Plan 20 days in Lisbon" and watch the
daylimit reject items, then see whether the retry fixes it. - Add a field
best_month: strtoTripPlanwith anenumof month names (useLiteral["January", ...]in pydantic) and check the generated schema. - Print
TripPlan.model_json_schema()to see exactly what the model receives. - Run
json_schema_format.pywithoutresponse_format, asking for JSON only in the prompt, and compare the raw output.
Next: tools that can do damage. You will add an allowlist, a human approval step for risky actions, and a defence against instructions hidden inside tool results.
