メインコンテンツへスキップ
JSONモードを有効にすると、モデルに有効なJSON形式で応答を返すよう指示できます。ただし、応答のスキーマには一貫性がなかったり、特定の構造に従わなかったりする場合があります。一貫した構造化JSON応答が必要な場合は、可能であればstructured outputを使用することをおすすめします。 JSONモードを有効にするには、リクエストで"response_format"として指定します。
import json
import openai

client = openai.OpenAI(
    base_url='https://api.inference.wandb.ai/v1',
    api_key="<your-api-key>",  # https://wandb.ai/settings でAPIキーを作成します
)

response = client.chat.completions.create(
    model="openai/gpt-oss-20b",
    messages=[
        {"role": "system", "content": "You are a helpful assistant that outputs JSON."},
        {"role": "user", "content": "Give me a list of three fruits with their colors."},
    ],
    response_format={"type": "json_object"}  # これによりJSONモードが有効になります
)

content = response.choices[0].message.content
parsed = json.loads(content)
print(parsed)