Java 后端面试题库 / 全部题解免费阅读理解原理,有条理地回答

stream=true 后,客户端怎样接住一段段输出?

先说出你的答案

定义边界、关键机制、一个反例;P8题再补容量、失败与验证。

查看完整题解

参考回答

直接回答

开启流式后,服务通过事件返回增量。Chat Completions 通常从选项的 delta 读片段,Responses 有带事件类型的流。客户端把这些增量串起来,记录结束与失败状态。

讲清原理

首段可以更快出现,但总生成时间仍由模型与输出决定。某些统计块可以没有 choices,工具参数也可能分片。启用用量统计时按所用接口处理最后的统计事件。

例子与易错点

下面用 SDK 读两个模拟增量和一个独立用量块,核对正文与完成状态。

import json

import httpx
from openai import OpenAI

def serve(request):
    body = json.loads(request.content)
    assert body["stream"] and body["stream_options"]["include_usage"]
    base = {"id": "demo", "created": 0, "object": "chat.completion.chunk",
            "model": body["model"]}
    pieces = [
        {**base, "choices": [{"index": 0, "delta": {"content": "实"}, "finish_reason": None}]},
        {**base, "choices": [{"index": 0, "delta": {"content": "测"}, "finish_reason": "stop"}]},
        {**base, "choices": [], "usage": {"prompt_tokens": 7, "completion_tokens": 2, "total_tokens": 9}},
    ]
    stream_data = "".join(f"data: {json.dumps(piece)}\n\n" for piece in pieces)
    return httpx.Response(200, text=stream_data + "data: [DONE]\n\n",
                          headers={"Content-Type": "text/event-stream"})

with OpenAI(api_key="local-test-key",
            http_client=httpx.Client(transport=httpx.MockTransport(serve))) as client:
    stream = client.chat.completions.create(model="gpt-6.2-sol",
        messages=[{"role": "user", "content": "你好"}],
        stream=True, stream_options={"include_usage": True})
    parts, usage, finish = [], None, None
    for event in stream:
        if event.usage is not None:
            usage = event.usage.total_tokens
        if event.choices:
            choice = event.choices[0]
            parts.append(choice.delta.content or "")
            finish = choice.finish_reason or finish

assert ("".join(parts), usage, finish) == ("实测", 9, "stop")
print("stream assembled the text and accepted an empty-choices usage event")

相关题:第 19 题、第 20 题、第 21 题、第 24 题、第 28 题。

这道题,你掌握得怎么样?

掌握程度由你主动标记,阅读和收藏不会自动改变状态。