導入

ストリーミング

stream: true を設定すると、生成されたトークンを Server-Sent Events(SSE)で随時受け取れます。最初のトークンが早く届き、長い出力でもクライアントのタイムアウトを回避できます。

curl https://api.link-io.cloud/v1/chat/completions \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4.1-mini",
    "messages": [{"role": "user", "content": "Hello!"}],
    "stream": true
  }'

イベント形式

各イベントは data: {JSON} の 1 行で、増分テキストは choices[0].delta.content に含まれます。ストリームは data: [DONE] で終了します。

data: {"id":"chatcmpl-...","choices":[{"index":0,"delta":{"role":"assistant","content":""}}]}

data: {"id":"chatcmpl-...","choices":[{"index":0,"delta":{"content":"Hel"}}]}

data: {"id":"chatcmpl-...","choices":[{"index":0,"delta":{"content":"lo!"},"finish_reason":"stop"}]}

data: [DONE]

ストリームでの使用量

stream_options.include_usage を設定すると、最後のチャンクにリクエスト全体の usage が含まれます。

stream = client.chat.completions.create(
    model="gpt-4.1-mini",
    messages=[{"role": "user", "content": "Write a haiku about routers."}],
    stream=True,
    stream_options={"include_usage": True},
)
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
    if chunk.usage:            # final chunk: empty choices, carries usage
        print("\n", chunk.usage)

注意点

  • 独自のリバースプロキシ(Nginx など)経由でストリームを中継する場合は、レスポンスのバッファリングを無効化してください(proxy_buffering off)。有効なままだと、最後にまとめて一度に届きます。
  • ストリームの読み取りタイムアウトは、リクエスト全体の時間ではなくチャンク間の間隔として設定してください。
  • 推論モデルでは、最初のトークンが届くまでに時間がかかる場合があります。これは想定された動作です。
  • Anthropic 形式では、ストリームイベントは Anthropic のもの(message_start、content_block_delta など)に対応します。Anthropic 形式 を参照してください。