跳转到主要内容
流式输出(Streaming)使模型的响应以增量方式逐步返回,而非等待全部生成完成后一次性返回。这可显著提升用户体验,并常用于长响应场景。

启用方式

在请求体中设置 "stream": true
{
  "model": "gpt-4o",
  "messages": [{"role": "user", "content": "写一首关于春天的诗"}],
  "stream": true
}

流式响应格式

启用流式后,服务器通过 Server-Sent Events(SSE)持续推送数据块(chunk),每块以 data: 开头:
data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]}

data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"春"},"finish_reason":null}]}

data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"风"},"finish_reason":null}]}

data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"拂面"},"finish_reason":null}]}

data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}

data: [DONE]
关键点:
  • 每个 chunk 的增量文本位于 choices[0].delta.content
  • 将所有 delta.content 按顺序拼接,即为完整响应。
  • 最后一个有效 chunk 的 finish_reason 变为 stop(正常结束)。
  • 流以 data: [DONE] 标志结束。

cURL 示例

curl https://moxus.ai/v1/chat/completions \
  -H "Authorization: Bearer sk-你的密钥" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o",
    "messages": [{"role": "user", "content": "写一首关于春天的短诗"}],
    "stream": true
  }'

Python 示例

使用官方 SDK 时,流式处理非常简单,遍历返回的迭代器即可:
from openai import OpenAI

client = OpenAI(
    api_key="sk-你的密钥",
    base_url="https://moxus.ai/v1",
)

stream = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "写一首关于春天的短诗"}],
    stream=True,
)

for chunk in stream:
    delta = chunk.choices[0].delta.content or ""
    print(delta, end="", flush=True)

print()

Node.js 示例

import OpenAI from "openai";

const client = new OpenAI({
  apiKey: "sk-你的密钥",
  baseURL: "https://moxus.ai/v1",
});

const stream = await client.chat.completions.create({
  model: "gpt-4o",
  messages: [{ role: "user", content: "写一首关于春天的短诗" }],
  stream: true,
});

for await (const chunk of stream) {
  const delta = chunk.choices[0]?.delta?.content || "";
  process.stdout.write(delta);
}

获取流式模式下的用量统计

默认情况下,流式响应可能不包含 usage(Token 统计)。如需在流式结束时获取本次消耗,可设置 stream_options
{
  "model": "gpt-4o",
  "messages": [{"role": "user", "content": "你好"}],
  "stream": true,
  "stream_options": {
    "include_usage": true
  }
}
启用后,流的最后会额外推送一个包含 usage 字段的 chunk,说明输入与输出 Token 数。 并非所有上游模型都支持 stream_options,具体以模型能力为准。

适用场景

场景建议
聊天界面或交互式应用推荐,用户体验更佳
长文生成(文章、报告)推荐,边生成边展示
后台批处理或仅需最终结果使用非流式更简单
需对完整结果进行 JSON 解析可使用流式,但须先拼接完整再解析

常见问题

流式与非流式的价格是否相同? 相同。计费仅与输入、输出 Token 数有关,与是否流式无关。 为何无法获取 usage 默认流式不返回 usage,需设置 stream_options.include_usage(且模型需支持)。 是否可中途停止? 可以。客户端断开连接即可停止接收,已生成的部分仍会计费。

后续步骤