Перейти к содержимому
Главная

Потоковые ответы

Установите stream: true, чтобы получать инкрементальные события в формате SSE.

Окно терминала
curl -N "${BASE_URL}/chat/completions" \
-H "Authorization: Bearer ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-5.5",
"messages": [
{
"role": "user",
"content": "Output three troubleshooting suggestions in sequence"
}
],
"stream": true,
"stream_options": {
"include_usage": true
}
}'
data: {"id":"chatcmpl_xxx","object":"chat.completion.chunk","choices":[{"delta":{"content":"First"}}]}
data: {"id":"chatcmpl_xxx","object":"chat.completion.chunk","choices":[{"delta":{"content":" suggestion"}}]}
data: {"id":"chatcmpl_xxx","object":"chat.completion.chunk","choices":[{"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":20,"completion_tokens":30,"total_tokens":50}}
data: [DONE]
  • Разбирайте каждую SSE-строку data: независимо.
  • Закрывайте поток после получения [DONE].
  • Передавайте stream_options.include_usage=true, если клиенту нужны данные usage.
  • Если клиент отключился, запрос может завершиться и все равно сгенерировать usage или списание.
stream = client.chat.completions.create(
model="gpt-5.5",
messages=[{"role": "user", "content": "Output three troubleshooting suggestions in sequence"}],
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="")