문서 · 모델 기능

JSON 출력

Get JSON you can parse directly — for extraction, classification, form filling and more.

본문은 현재 영어로만 제공됩니다.

JSON mode

response_format: {"type": "json_object"} guarantees valid JSON but does not constrain the fields.

resp = client.chat.completions.create(
    model="gpt-4.1-mini",
    response_format={"type": "json_object"},
    messages=[
        {"role": "system", "content": "Reply in JSON with keys: title, tags (array of strings)."},
        {"role": "user", "content": "Summarize: MAX routes one API to many model vendors."},
    ],
)
data = json.loads(resp.choices[0].message.content)
In JSON mode, the prompt must explicitly ask for JSON and describe the fields; otherwise some models error out or produce unstable output.

JSON Schema (structured outputs)

With response_format: {"type": "json_schema", ...} and strict: true, the output follows your schema exactly. Strict mode requires every property in required and additionalProperties: false.

resp = client.chat.completions.create(
    model="gpt-4.1-mini",
    messages=[{"role": "user", "content": "Extract: Alice, 31, lives in Berlin."}],
    response_format={
        "type": "json_schema",
        "json_schema": {
            "name": "person",
            "strict": True,
            "schema": {
                "type": "object",
                "properties": {
                    "name": {"type": "string"},
                    "age": {"type": "integer"},
                    "city": {"type": "string"},
                },
                "required": ["name", "age", "city"],
                "additionalProperties": False,
            },
        },
    },
)
print(resp.choices[0].message.content)   # {"name":"Alice","age":31,"city":"Berlin"}

Support

Models with the JSON mode capability support json_object. json_schema is mainly supported by newer OpenAI and Gemini models. For other models, use tool calling: define one function and let the model fill in its arguments.

Robustness

  • Always parse and validate; retry or fall back on failure.
  • If finish_reason is length, the JSON may be truncated — raise the output cap.