跳到正文
全部文档

指南

流式输出

设置 stream: true,回复会像 OpenAI 的服务器推送事件一样逐字到达。请求用量信息后,最后一个分块会告诉你这次调用花了多少。

核对于 2026年10月26日

流式返回一条回复

import os
from openai import OpenAI

client = OpenAI(
    base_url="https://nokeep.ai/v1",
    api_key=os.environ["NOKEEP_API_KEY"],
)

stream = client.chat.completions.create(
    model="deepseek-v4.1-flash-uncensored",
    messages=[{"role": "user", "content": "Tell me a story in three lines."}],
    stream=True,
    stream_options={"include_usage": True},
)
for chunk in stream:
    if chunk.choices:
        print(chunk.choices[0].delta.content or "", end="", flush=True)
    if chunk.usage:
        print("\ncredits:", chunk.usage.model_extra.get("nokeep_credits"))

收到的内容

The stream
data: {"choices":[{"index":0,"delta":{"role":"assistant","content":""}}]}
data: {"choices":[{"index":0,"delta":{"content":"The"}}]}
data: {"choices":[{"index":0,"delta":{"content":" lighthouse"}}]}
…
data: {"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
data: {"choices":[],"usage":{"prompt_tokens":18,"completion_tokens":61,"nokeep_credits":0}}
data: [DONE]
  • 文字通过 delta.content 到达。开启思考时,思考内容会先通过 delta.reasoning_content 到达。
  • 工具调用通过 delta.tool_calls 到达,其参数分段传输,与 OpenAI 的方式一致。
  • 设置 stream_options.include_usage 后,最后一个 choices 为空列表的分块会携带 usage,包括 nokeep_credits,即本次调用的费用。
  • 流以 data: [DONE] 结束。

提前停止回复

关闭连接,模型就会停止输出。你只为停止前已发送的内容付费,之后的内容不计费。在 SDK 中,跳出循环并关闭流;在应用中,按下它的停止按钮即可。

Python
for chunk in stream:
    text = chunk.choices[0].delta.content if chunk.choices else ""
    if text and "THE END" in text:
        stream.close()  # the model stops here, and so does the bill
        break

模型提前中断时

如果模型在完成前结束了流,[DONE] 之前的最后一个事件会是 OpenAI 格式的错误,错误代码为 stream_cut。已输出的内容照常计费,不会多收。你可以重试,或从已收到的内容继续。

A cut stream
data: {"error":{"type":"api_error","code":"stream_cut","message":"The model stopped before it finished. What it wrote is billed, nothing more."}}
data: [DONE]

常见问题

流式输出更贵吗?

不。流式回复与整段回复消耗的 token 相同。

为什么流式回复中没有 x-nokeep-credits 响应头?

响应头在第一个字发出之前就已发送,那时还不知道费用。请求用量信息,然后在最后一个分块中读取 nokeep_credits。