Skip to content
WRAITHERIXDocsENRU

Structured outputs

Use response_format to force the model to answer with valid JSON.

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"}
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'

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: true and additionalProperties: false for the most reliable results.
  • Every property must be listed in required when strict is on; use a union with null for 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.