Перейти к содержимому
WRAITHERIXDocsENRU

Структурированный вывод

Используйте response_format, чтобы модель гарантированно отвечала валидным 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'

Для JSON в свободной форме без схемы используйте {"type": "json_object"} и укажите в промпте «respond in JSON» (отвечай в формате JSON):

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"},
)
  • Оставляйте strict: true и additionalProperties: false для наиболее надёжных результатов.
  • При включённом strict каждое свойство должно быть указано в required; для необязательных полей используйте объединение с null.
  • Поддержка схем различается между семействами моделей. Если модель игнорирует схему, попробуйте модель GPT или используйте вызов инструментов (tool calling) с единственным инструментом.