流式输出
开启流式后,模型生成的内容会一段一段地返回,不用等整条回复生成完。适合聊天界面这类需要即时显示的场景,也能避免长回复触发超时。
所有文本模型都支持流式输出。
开启方式
在请求里加上 "stream": true。
python
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["HIHAI_API_KEY"],
base_url="https://gateway.hihapi.com/v1",
)
stream = client.chat.completions.create(
model="deepseek-flash",
messages=[{"role": "user", "content": "写一首关于秋天的短诗"}],
stream=True,
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)python
import os
from anthropic import Anthropic
client = Anthropic(
api_key=os.environ["HIHAI_API_KEY"],
base_url="https://gateway.hihapi.com",
)
with client.messages.stream(
model="deepseek-flash",
max_tokens=1024,
messages=[{"role": "user", "content": "写一首关于秋天的短诗"}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)bash
curl -N https://gateway.hihapi.com/v1/chat/completions \
-H "Authorization: Bearer $HIHAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "deepseek-flash",
"messages": [{"role": "user", "content": "写一首关于秋天的短诗"}],
"stream": true
}'返回格式
流式响应使用 SSE(Server-Sent Events)。Chat Completions 协议下,每个事件是一行以 data: 开头的 JSON,新增的内容在 choices[0].delta.content 里,最后以 data: [DONE] 结束:
text
data: {"choices":[{"index":0,"delta":{"content":"秋"}}]}
data: {"choices":[{"index":0,"delta":{"content":"风"}}]}
data: [DONE]Messages 协议的事件类型不同,建议直接用 Anthropic SDK 处理,不必手动解析。
获取用量
流式请求默认不返回用量。Chat Completions 协议下,在请求里加上 stream_options,最后一个数据块会带上完整的 usage:
python
stream = client.chat.completions.create(
model="deepseek-flash",
messages=[{"role": "user", "content": "写一首关于秋天的短诗"}],
stream=True,
stream_options={"include_usage": True},
)
for chunk in stream:
if chunk.usage:
print(chunk.usage)带用量的那个数据块 choices 是空数组,处理时注意不要直接读取 choices[0]。
支持在流式过程中返回用量的模型,在模型广场的模型能力里会标出「流式过程中返回用量」。
注意事项
- 读到结束再断开:提前断开连接时,服务端已经生成的内容仍然会计费。
- 超时时间要够长:把客户端的读取超时设长一些,等待首个数据块时连接上可能暂时没有数据。
- 代理和网关不要缓冲:自己的服务转发流式响应时,关闭反向代理的响应缓冲,否则内容会攒到最后一起到达。Nginx 需要设置
proxy_buffering off。 - 中途断开:流在生成中途断开多半是网络或本地代理不稳定。判断方法是看是否收到了结束标记,没有收到就按失败处理并重试。