コンテンツにスキップ

構造化出力

構造化出力を使うと、指定したスキーマに従う JSON をモデルに出力させられます。パース失敗や項目の欠落が発生しません。

最もシンプルな方式。response_format に json_object を指定します:

{
"model": "...",
"messages": [...],
"response_format": { "type": "json_object" }
}

モデルは構文的に正しい JSON を必ず返します。具体的な形はプロンプト次第です。

形まで保証したい場合は、スキーマを渡します:

response = client.chat.completions.create(
model="...",
messages=[{"role": "user", "content": "Extract: Jane Doe, jane@example.com"}],
response_format={
"type": "json_schema",
"json_schema": {
"name": "contact",
"strict": True,
"schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"email": {"type": "string"},
},
"required": ["name", "email"],
"additionalProperties": False,
},
},
},
)

strict: true を指定すると、出力はスキーマに厳密に従います — 余分なフィールドや必須フィールドの欠落はありません。

SDK は Pydantic モデルからスキーマを自動生成できます (client.chat.completions.parse() または responses.parse())。