stream=true 后,客户端怎样把回答一点点拼出来?
查看完整题解
参考回答
直接回答
流式请求以 SSE 事件不断送来增量。Chat Completions 里通常按选择读取 delta.content 并拼接,同时处理空块、心跳、结束原因和最终用量。
讲清原理
早收到第一段能更快开始展示,但生成仍占着连接。断开时区分用户取消、网络错误和模型正常结束。推理字段与正文分开处理,工具调用的参数也要等片段组装完整。
例子与易错点
下面用模拟 SSE 事件让实际 SDK 解码。会验证两段正文如何合并、最后一个块如何带结束原因和用量。
import json
import httpx
from openai import OpenAI
def fake_stream(request):
assert json.loads(request.content)["stream"] is True
events = [": keep-alive\n\n"]
for part in ("您好,", "收到。", ""):
finished = part == ""
chunk = {
"id": "demo", "object": "chat.completion.chunk",
"created": 0, "model": "deepseek-flash",
"choices": [{"index": 0, "delta": {"content": part},
"finish_reason": "stop" if finished else None}],
}
if finished:
chunk["usage"] = {"prompt_tokens": 7, "completion_tokens": 3, "total_tokens": 10}
events.append(f"data: {json.dumps(chunk)}\n\n")
events.append("data: [DONE]\n\n")
return httpx.Response(200, content="".join(events).encode(),
headers={"Content-Type": "text/event-stream"})
with OpenAI(api_key="local-test-key", base_url="https://api.deepseek.com",
http_client=httpx.Client(transport=httpx.MockTransport(fake_stream))) as client:
chunks = list(client.chat.completions.create(
model="deepseek-flash", messages=[{"role": "user", "content": "你好"}],
stream=True,
))
answer = "".join(chunk.choices[0].delta.content or "" for chunk in chunks)
assert answer == "您好,收到。"
assert chunks[-1].choices[0].finish_reason == "stop" and chunks[-1].usage.total_tokens == 10
print(answer, "total_tokens=10")
这道题,你掌握得怎么样?
掌握程度由你主动标记,阅读和收藏不会自动改变状态。