ストリーミング
Server-Sent Eventsで、生成されたトークンを順次受け取ります。
"stream": trueを設定すると、レスポンスは1つのJSON本文ではなくServer-Sent Eventsとして届きます。イベントの構造はAPI形式ごとに異なります。
| エンドポイント | ストリームの形式 |
|---|---|
/v1/chat/completions | chat.completion.chunkオブジェクトのdata:行。最後はdata: [DONE] |
/v1/responses | response.output_text.deltaやresponse.completedなどの型付きイベント |
/v1/messages | Anthropicのイベント:message_start、content_block_delta、message_stop |
ストリームでのトークン使用量
Chat Completionsでは、"stream_options": { "include_usage": true }を追加すると、最後のチャンクでトークン数を受け取れます。ResponsesとMessagesのストリームは、終了時のイベントで使用量を返します。
例
stream = client.chat.completions.create(
model="deepseek-v4-1-flash",
messages=[{"role": "user", "content": "Write a haiku about rivers."}],
stream=True,
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)