接口

流式输出

请求里加 stream: true,按 SSE 逐段返回。

请求体加上 "stream": true 后,服务器用 Server-Sent Events 逐段返回。每一行以 data: 开头,内容是一个 JSON 片段;最后一行是 data: [DONE]。

返回的数据流
data: {"id":"chatcmpl-3f9a…","object":"chat.completion.chunk","model":"deepseek-v4.1-flash-heretic","choices":[{"index":0,"delta":{"role":"assistant","content":"你"}}]}

data: {"id":"chatcmpl-3f9a…","object":"chat.completion.chunk","model":"deepseek-v4.1-flash-heretic","choices":[{"index":0,"delta":{"content":"好"}}]}

data: {"id":"chatcmpl-3f9a…","object":"chat.completion.chunk","model":"deepseek-v4.1-flash-heretic","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":9,"completion_tokens":2}}

data: [DONE]

同一次请求里所有片段的 id 相同。把每个片段的 choices[0].delta.content 依次拼起来就是完整回复。

Python

stream.py
stream = client.chat.completions.create(
    model="deepseek-v4.1-flash-heretic",
    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)

注意

  1. 以 : 开头的行是保持连接用的心跳,直接忽略。
  2. 流中途出错时,会收到一条带 error 字段的 data,格式和非流式的报错一样。
  3. 带思考的模型,思考内容可能出现在 delta.reasoning_content 里,正文仍在 delta.content。