Structured outputs
Use response_format to force the model to answer with valid JSON.
JSON schema (recommended)
Section titled “JSON schema (recommended)”r = client.chat.completions.create( model="gpt-5.6-luna", messages=[{"role": "user", "content": "Name the capital of Japan."}], response_format={ "type": "json_schema", "json_schema": { "name": "city", "strict": True, "schema": { "type": "object", "properties": { "city": {"type": "string"}, "country": {"type": "string"}, }, "required": ["city", "country"], "additionalProperties": False, }, }, },)print(r.choices[0].message.content) # {"city":"Tokyo","country":"Japan"}With Pydantic (Python SDK)
Section titled “With Pydantic (Python SDK)”from pydantic import BaseModel
class City(BaseModel): city: str country: str
r = client.chat.completions.parse( model="gpt-5.6-luna", messages=[{"role": "user", "content": "Name the capital of Japan."}], response_format=City,)print(r.choices[0].message.parsed) # city='Tokyo' country='Japan'JSON mode
Section titled “JSON mode”For free-form JSON without a schema, use {"type": "json_object"} and say
“respond in JSON” in the prompt:
r = client.chat.completions.create( model="gpt-5.6-luna", messages=[{"role": "user", "content": "List three colours as JSON with a 'colours' array."}], response_format={"type": "json_object"},)- Keep
strict: trueandadditionalProperties: falsefor the most reliable results. - Every property must be listed in
requiredwhenstrictis on; use a union withnullfor optional fields. - Schema support differs between model families. If a model ignores the schema, try a GPT model or use tool calling with a single tool.