DeepSeek 流式调用最小可运行示例(Python纯requests)

4 阅读1分钟

DeepSeek 流式调用最小可运行示例(Python)

不用 SDK,纯 requests,10 行看懂流式本质:

import requests, json

resp = requests.post(
    "https://5pcloud.top/v1/chat/completions",   # 任何 OpenAI 兼容端点都一样
    headers={"Authorization": "Bearer sk-你的key"},
    json={
        "model": "deepseek-v4.1-flash",
        "messages": [{"role": "user", "content": "写一句诗"}],
        "stream": True,
    },
    stream=True,
)

for line in resp.iter_lines():
    line = line.decode("utf-8")
    if not line.startswith("data: ") or line == "data: [DONE]":
        continue
    delta = json.loads(line[6:])["choices"][0]["delta"]
    if delta.get("content"):
        print(delta["content"], end="", flush=True)

三个要点:

  • data: [DONE] 是结束标志,收到就 break
  • 每帧是 choices[0].delta.content,不是 message.content(新手最常混)
  • 生产环境记得加 timeout= 和断流重试

用 openai SDK 更简单:client.chat.completions.create(..., stream=True),原理一样。