How to get structured output
This guide makes a model answer with JSON that follows a schema, so your program can parse it without checks. It assumes a server running with a chat model; the examples use mlx-community/Qwen3-4B-4bit (models below 1B parameters follow schemas, but often fill them poorly).
With the openai Python library and a Pydantic class
from openai import OpenAI
from pydantic import BaseModel
class City(BaseModel):
name: str
country: str
population: int
landmarks: list[str]
client = OpenAI(base_url="http://127.0.0.1:7920/v1", api_key="unused")
completion = client.beta.chat.completions.parse(
model="mlx-community/Qwen3-4B-4bit",
messages=[{"role": "user", "content": "Describe Lyon, France."}],
response_format=City,
)
city = completion.choices[0].message.parsed # a City instance
Run it with uv run --with openai --with pydantic python city.py. Recent versions of the library also offer client.chat.completions.parse(...).
With any client: a JSON Schema
Send response_format with the schema:
"response_format": {
"type": "json_schema",
"json_schema": {
"name": "city",
"strict": true,
"schema": {
"type": "object",
"additionalProperties": false,
"required": ["name", "country"],
"properties": {"name": {"type": "string"}, "country": {"type": "string"}}
}
}
}
The answer's content is a JSON string valid against the schema; parse it with your language's JSON library.
Any JSON object, without a schema
"response_format": {"type": "json_object"}
Say in your prompt which keys you want: only the syntax is guaranteed.
Variants
- Streaming: add
"stream": true; the JSON arrives in pieces indelta.content. Join them before parsing. - Reasoning models: with thinking on (
"reasoning_effort": "low"), the model thinks freely, then writes the JSON; the reasoning is inreasoning_content. Leave room inmax_tokensfor both. For simple extractions,"reasoning_effort": "none"is faster. - Order of the keys: properties come out in the order of the schema. Put a field such as
reasoningbeforeanswerif you want the model to write it first. - A 400 naming a keyword (
uniqueItems,multipleOf,not,if…): with"strict": truethe server refuses keywords it cannot enforce. Remove the keyword, or set"strict": falseand check that rule in your code. - Your own system message: keep it. The server appends one sentence asking for JSON (with the schema) to it.
- Tools and structured output together:
response_formatcannot be combined with a forced tool call (tool_choicerequiredor named); withtool_choice: "auto"it applies to the text answer.
See also
- Every field of
response_format: HTTP API reference. - How the constraint works, and its limits: constrained decoding.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
|