コンテンツへスキップ
構造化出力

構造化出力

回答を JSON で要求します。任意の JSON オブジェクト、または送信したスキーマに従う JSON です。人ではなくプログラムが応答を読む場合に使ってください。

POST https://api.shannon-ai.com/v1/chat/completions

import json
from openai import OpenAI

client = OpenAI(api_key="YOUR_API_KEY", base_url="https://api.shannon-ai.com/v1")

response = client.chat.completions.create(
    model="Kimi-K3-3BIT-REAP",
    messages=[
        {"role": "user", "content": "Extract the person: John Doe, 30 years old, engineer."}
    ],
    response_format={
        "type": "json_schema",
        "json_schema": {
            "name": "person",
            "strict": True,
            "schema": {
                "type": "object",
                "properties": {
                    "name": {"type": "string"},
                    "age": {"type": "integer"},
                    "occupation": {"type": "string"},
                },
                "required": ["name", "age", "occupation"],
            },
        },
    },
)

# The JSON arrives as text in message.content: parse it, then check it.
try:
    person = json.loads(response.choices[0].message.content)
except json.JSONDecodeError:
    person = None  # ask again, or report the failure

print(person)

JSON は回答のテキストで、choices[0].message.content に入ります。

200 JSON
{
  "id": "chatcmpl-0c4e7a1b9d2f4e6a8b3c5d7e9f1a2b3c",
  "object": "chat.completion",
  "created": 1791590400,
  "model": "Kimi-K3-3BIT-REAP",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "{\"name\":\"John Doe\",\"age\":30,\"occupation\":\"engineer\"}",
        "reasoning_content": null
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 96,
    "completion_tokens": 19,
    "total_tokens": 115,
    "prompt_tokens_details": {"cached_tokens": 0},
    "completion_tokens_details": {"reasoning_tokens": 0}
  }
}

response_format で指定できるモードの種類

response_format は /v1/chat/completions のフィールドです。これがない場合、回答は通常のテキストです。

モード 値 得られるもの
JSON オブジェクト {"type": "json_object"} 回答は、決まった形のない JSON です。必要なキーはプロンプトで指定してください。
JSON スキーマ {"type": "json_schema", "json_schema": {"name": "…", "schema": {…}}} 回答は、送信したスキーマ(そのキー、型、必須フィールド)に従います。
Strict "strict": true json_schema のフィールドであり、三つ目のモードではありません。false を送信しない限り true です。
フィールド 型 デフォルト 説明 適用モデル
type string json_object または json_schema。response_format 内では必須です。text も受け付けられ、通常のテキストの回答になります。 そのモードに対応するすべてのモデル
json_schema.schema object 回答が従う JSON Schema。type が json_schema の場合は必ず送信してください。 そのモードに対応するすべてのモデル
json_schema.name string スキーマのラベル。OpenAI 形式と同じです。 ホスト型オープンウェイトモデル
json_schema.strict boolean true 回答がスキーマに厳密に従う必要があるかどうか。Shannon モデルは、すべてのスキーマを strict として適用します。 ホスト型オープンウェイトモデル

JSON オブジェクトモードにスキーマは不要です。プロンプトでキーを指定します。

リクエストボディ
{
  "model": "shannon-3",
  "messages": [
    {
      "role": "user",
      "content": "Name the capital of France. Answer as JSON with the keys city and country."
    }
  ],
  "response_format": {"type": "json_object"}
}

モデルごとの対応状況

モデル json_object json_schema
すべての Shannon モデル(shannon-*) はい はい
ホスト型オープンウェイトモデル(下記に挙げるものを除く) はい はい
Laguna-S-2.1-W4A16-AUTOROUND-REAP — —
inkling-W4A16-AUTOROUND-REAP はい —

GET /v1/models は、ID ごとに同じ内容を報告します。すべてのモデルで capabilities.json_schema、ホスト型オープンウェイトモデルでは capabilities.response_format です。 モデルと料金

サポートされるスキーマのキーワード

モデルがスキーマのどの部分を受け取るかは、モデルとエンドポイントによって異なります。

モデル /v1/chat/completions /v1/responses
Shannon モデル 下記のキーワードのサブセット。strict として適用されます。 送信したとおりのスキーマ。strict として適用されます。
ホスト型オープンウェイトモデル 送信したとおりのスキーマ。送信しない限り、strict は true です。 送信したとおりのスキーマ。送信しない限り、strict は true です。

/v1/chat/completions での Shannon モデルのキーワードのサブセット:

キーワード 読み取り方
読み取られるキーワード type, format, title, description, nullable, enum, items, properties, required, minItems, maxItems, minimum, maximum, minLength, maxLength, pattern, anyOf, default
$ref スキーマの最上位にある $defs または definitions から解決されます。description など、$ref の隣に書かれたキーワードは保持されます。対応する定義のない参照は {"type": "object"} として読み取られます。
allOf メンバーはひとつのスキーマに統合されます。二つのメンバーが同じキーワードを設定している場合は、後のものが優先されます。
oneOf anyOf として読み取られます。
自分自身を参照するスキーマ 24 階層まで展開されます。それより深い階層は {"type": "object"} として読み取られます。
サブセット外 それ以外のすべてのキーワード。たとえば additionalProperties、const、multipleOf、uniqueItems、exclusiveMinimum、exclusiveMaximum、patternProperties、prefixItems、minProperties、maxProperties、not、if / then / else です。これらは、モデルが受け取るスキーマには含まれません。

/v1/responses を使う場合:text.format で指定する

/v1/responses では、同じリクエストを text.format で指定します。スキーマは json_schema キーの下ではなく、format 内の name と strict の隣に直接置きます。JSON オブジェクトモードでは {"format": {"type": "json_object"}} を送信します。

リクエストボディ
{
  "model": "Kimi-K3-3BIT-REAP",
  "input": "Extract the person: John Doe, 30 years old, engineer.",
  "text": {
    "format": {
      "type": "json_schema",
      "name": "person",
      "strict": true,
      "schema": {
        "type": "object",
        "properties": {
          "name": {"type": "string"},
          "age": {"type": "integer"},
          "occupation": {"type": "string"}
        },
        "required": ["name", "age", "occupation"]
      }
    }
  }
}

JSON は、message アイテムの output_text パートの text です。

200 JSON
{
  "output": [
    {
      "id": "msg_7e1d3c5b9a2f4d6e8c0b1a3f5e7d9c2b",
      "type": "message",
      "role": "assistant",
      "status": "completed",
      "content": [
        {
          "type": "output_text",
          "text": "{\"name\":\"John Doe\",\"age\":30,\"occupation\":\"engineer\"}",
          "annotations": []
        }
      ]
    }
  ]
}

モデルごとの対応状況とエラーは、/v1/chat/completions と同じです。 Responses API

/v1/messages では、スキーマとしてのツール

Messages 形式に、構造化出力のフィールドはありません。同じモデルで JSON を得るには、同じキーで /v1/chat/completions または /v1/responses を呼び出してください。

/v1/messages にとどまるには、オブジェクトをツールとして記述します。スキーマを input_schema に入れ、tool_choice でツールを名前指定します。すると tool_use ブロックの input が、パース済みのオブジェクトになります。名前付きの tool_choice は、ホスト型オープンウェイトモデルで適用されます。

リクエストボディ
{
  "model": "Kimi-K3-3BIT-REAP",
  "max_tokens": 1024,
  "messages": [
    {
      "role": "user",
      "content": "Extract the person: John Doe, 30 years old, engineer."
    }
  ],
  "tools": [
    {
      "name": "record_person",
      "description": "Record the extracted person.",
      "input_schema": {
        "type": "object",
        "properties": {
          "name": {"type": "string"},
          "age": {"type": "integer"},
          "occupation": {"type": "string"}
        },
        "required": ["name", "age", "occupation"]
      }
    }
  ],
  "tool_choice": {"type": "tool", "name": "record_person"}
}
200 JSON
{
  "stop_reason": "tool_use",
  "content": [
    {
      "type": "tool_use",
      "id": "toolu_4b8d2f6a1c3e4a5b9d7f0e2c4a6b8d1f",
      "name": "record_person",
      "input": {"name": "John Doe", "age": 30, "occupation": "engineer"}
    }
  ]
}

ブロックを読む前に、stop_reason が tool_use であることを確認してください。 関数呼び出し

JSON の届き方

  • JSON は文字列です。応答には、パース済みのオブジェクトは付きません。message.content に対して JSON パーサーを実行してください。
  • stream: true の場合、JSON は delta.content の断片として届きます。ストリームが終了してから連結してパースしてください。断片だけでは有効な JSON ではありません。
  • ホスト型オープンウェイトモデルは、response_format を指定したリクエストに推論テキストなしで応答します。reasoning_content は null です。

受け取った内容を確認する

スキーマは、モデルの書き方を導くものです。API は、完成した回答をスキーマと照合しないため、最終的な確認はお使いのコードで行います。

  • 冒頭のサンプルのように、エラーハンドラー内でパースします。
  • パースしたオブジェクトを、同じスキーマで、ご自身のコード内で検証します。たとえば JSON Schema ライブラリ、Pydantic、Zod を使います。
  • 長い回答は、JSON が完成する前に終わることがあります。ストリームでない応答は finish_reason として stop または tool_calls しか報告しないため、パースエラーが目印になります。もう一度依頼するか、より小さいオブジェクトを依頼してください。

エラー

ステータス タイプ メッセージ 発生条件
400 invalid_request_error <id> does not accept response_format モデルがどちらのモードにも対応していません。
400 invalid_request_error <id> does not accept response_format json_schema; use json_object モデルは json_object に対応していますが、json_schema が送信されました。
422 invalid_request_error Failed to deserialize the JSON body into the target type: … response_format に type がないか、JSON オブジェクトではありません。

二つの 400 応答は、残高から何かが引かれる前に送信されます。 エラー処理