モデルの機能

JSON 出力

そのままパースできる JSON を取得できます。情報抽出、分類、フォーム入力などに利用できます。

JSON モード

response_format: {"type": "json_object"} は有効な JSON を保証しますが、フィールドは制約しません。

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)
JSON モードでは、プロンプトで明示的に JSON を要求し、フィールドを説明してください。そうしないと、モデルによってはエラーになったり、出力が不安定になったりします。

JSON Schema(構造化出力)

response_format: {"type": "json_schema", ...} と strict: true を指定すると、出力はスキーマに厳密に従います。厳密モードでは、すべてのプロパティを required に含め、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"}

対応状況

JSON モードの機能を持つモデルは json_object に対応しています。json_schema は主に新しい OpenAI モデルと Gemini モデルでサポートされています。それ以外のモデルでは ツール呼び出し を利用してください。関数を 1 つ定義し、モデルにその引数を入力させます。

堅牢性

  • 必ずパースと検証を行い、失敗時はリトライまたはフォールバックしてください。
  • finish_reason が length の場合、JSON が途中で切れている可能性があります。出力上限を引き上げてください。