メインコンテンツへスキップ
モデルによっては、応答の生成に時間がかかることがあります。 stream オプションを true に設定すると、応答をチャンクのストリームとして受け取れるため、 応答全体の生成を待たずに、結果を段階的に表示できます。 ストリーミング出力は、すべての hosted モデルでサポートされます。特に reasoning models での使用を推奨します。ストリーミングでないリクエストでは、モデルが出力を開始する前に 長時間考え込むとタイムアウトする可能性があるためです。
import openai

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

stream = client.chat.completions.create(
    model="openai/gpt-oss-120b",
    messages=[
        {"role": "user", "content": "Tell me a rambling joke"}
    ],
    stream=True,
)

for chunk in stream:
    if chunk.choices:
        print(chunk.choices[0].delta.content or "", end="", flush=True)
    else:
        print(chunk) # CompletionUsage object を表示