功能特性
流式输出
边生成边返回,降低首字延迟
开启流式输出后,模型每生成一小段内容就立即返回,用户不必等待完整回答,适合聊天界面等对响应速度敏感的场景。
适用模型
所有对话模型均支持。
示例
from openai import OpenAI
client = OpenAI(api_key="YOUR_API_KEY", base_url="https://netnexus.top/api/v1")
stream = client.chat.completions.create(
model="gpt-5.4-mini",
messages=[{"role": "user", "content": "用三句话介绍一下智枢网关"}],
stream=True,
stream_options={"include_usage": True},
)
for chunk in stream:
if chunk.choices:
print(chunk.choices[0].delta.content or "", end="", flush=True)
if chunk.usage:
print("\n用量:", chunk.usage)返回格式
流式响应使用 SSE(Server-Sent Events)格式,每个数据块以 data: 开头,最后以 data: [DONE] 结束:
data: {"choices":[{"delta":{"content":"智枢"},"index":0}]}
data: {"choices":[{"delta":{"content":"网关"},"index":0}]}
data: [DONE]注意事项
- 设置
stream_options: {"include_usage": true}后,最后一个数据块会携带本次请求的 token 用量。 - 如果前面有 Nginx 等反向代理,需要关闭响应缓冲(如
proxy_buffering off),否则内容会被攒到最后一次性返回。
