ストリーミング
Chat Completions、Responses、Messagesで stream に true を指定すると、応答の完成を待たずに、生成された部分から順に受け取れます。
形式はServer-Sent Events(SSE)です。
リクエスト
curl では、-N を付けると、受信した順に表示されます。
curl -N https://ai-gateway.lolipop.jp/v1/chat/completions \
-H "Authorization: Bearer $AI_GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-sonnet-4-6",
"stream": true,
"messages": [
{ "role": "user", "content": "短い物語を書いてください。" }
]
}'OpenAI SDKでは、次のように受け取ります。
const stream = await client.chat.completions.create({
model: 'claude-sonnet-4-6',
stream: true,
messages: [{ role: 'user', content: '短い物語を書いてください。' }],
})
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content ?? '')
}レスポンスヘッダー
Content-Type: text/event-stream; charset=utf-8
Cache-Control: no-cacheX-AIGateway-Requested-Model、X-AIGateway-Served-Model、X-AIGateway-Fallback-Count も付きます。
Chat Completions
chat.completion.chunk を data: 行で順に返し、最後に data: [DONE] を返します。
data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","created":1767225600,"model":"claude-sonnet-4-6","choices":[{"index":0,"delta":{"role":"assistant","content":"大規模"}}]}
data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","created":1767225600,"model":"claude-sonnet-4-6","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
data: [DONE]stream_options に { "include_usage": true } を指定すると、最後のチャンクに使用量が含まれます。
Responses
イベントを data: 行で順に返し、最後に data: [DONE] を返します。
イベントの種類は type で示されます。
data: {"type":"response.created","response":{"id":"resp_abc123"}}
data: {"type":"response.output_text.delta","item_id":"msg_abc123","output_index":0,"content_index":0,"delta":"大規模"}
data: {"type":"response.completed","response":{"id":"resp_abc123","status":"completed"}}
data: [DONE]type | 内容 |
|---|---|
response.created、response.in_progress | 応答の開始 |
response.output_item.added、response.content_part.added | 出力アイテムとコンテンツパートの追加 |
response.output_text.delta | テキストの差分 |
response.output_text.done、response.content_part.done、response.output_item.done | テキスト、コンテンツパート、出力アイテムの完了 |
response.completed | 応答の完了 |
Messages
イベントを event: 行と data: 行の組で順に返します。
最後のイベントは message_stop です。
event: message_start
data: {"type":"message_start","message":{"id":"msg_abc123","type":"message","role":"assistant","model":"claude-sonnet-4-6","content":[]}}
event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"大規模"}}
event: message_stop
data: {"type":"message_stop"}| イベント | 内容 |
|---|---|
message_start | メッセージの開始 |
content_block_start、content_block_delta、content_block_stop | コンテンツブロックの開始、差分、終了 |
message_delta | 生成が終了した理由と使用量 |
message_stop | メッセージの完了 |
ping | 接続を維持するためのイベント |
エラー
システムの状態によっては、最後のイベント(data: [DONE] または message_stop)を受け取る前に接続が閉じる場合もあります。
この場合も、ステータスコードは 200 のままです。
利用額と利用制限
ストリームの途中で接続を切った場合も、そこまでの使用量が請求の対象になります。 予算、残高、レート制限の確認に使う見積りは、ストリームが終了するまで有効です。