跳转到正文

流式传输

RightNow AIOpen models流式传输 更新于

本页内容

在页面列出支持流式传输的模型上,在 POST /v1/chat/completions 上设置 stream: true,答案就会以 Server-Sent Events 的形式到达。 当你的客户端需要用量帧时,添加 stream_options.include_usage。 MODEL_ID 代表 开放模型 中任意可用的 ID。

TypeScript
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.rightnowai.co/v1",
  apiKey: process.env.RIGHTNOW_API_KEY,
});
const stream = await client.chat.completions.create({
  model: "MODEL_ID",
  messages: [{ role: "user", content: "Count from one to three." }],
  max_tokens: 16384,
  stream: true,
  stream_options: { include_usage: true },
});

for await (const chunk of stream) {
  if (chunk.usage) console.error("usage:", chunk.usage);
  process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
}
响应流
Text
data: {"id":"chatcmpl_example","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"One"}}]}

data: {"choices":[],"usage":{"prompt_tokens":12,"completion_tokens":4,"total_tokens":16,"prompt_tokens_details":{"cached_tokens":0},"cost":0.0000028,"runinfra":{"cost_microcents":280,"cached_input_tokens":0}}}

data: [DONE]

增量帧会一直重复,直到答案结束。 从每一帧读取 choices[].delta,并把 data: [DONE] 视为答案完整的唯一信号。 /v1/messages 使用它自己的具名事件语法进行流式传输,详见 Messages。

到达的内容与时间

流的时间线
Text
一个聊天流从请求到最后一帧的示意图。

流最多等待 180 秒获得第一个 token,整个流最长可持续 740 秒。部分输出通过 choices[].delta 到达,静默 10 秒后会收到一条 keep-alive 注释。用量帧只有在你请求时才会到达,除非没有交付最终答案。完整的流以 data: [DONE] 结束。流也可能在同样的 HTTP 200 下以错误帧或断开的连接结束:没有 [DONE] 的响应是不完整的。

帧的格式

响应带有 Content-Type: text/event-stream、Cache-Control: no-cache 和 Connection: keep-alive。 内容以兼容 chat 的 data: 帧到达。

帧携带的内容
增量帧choices[].delta 上的部分输出。
: keep-aliveChat completions 和 Responses 流在静默 10 秒后发送的注释。忽略以 : 开头的行。
用量帧一个空的 choices 数组和用量。在托管模型上,它还带有请求的费用以及按缓存价格计费的输入 token 数量,两者都在 Chat completions 中说明。
data: [DONE]完整流的结尾。
错误帧网关提前终止的流的结尾。其后不会有 [DONE]。
错误帧
Text
data: {"error":{"message":"The upstream stream ended before signalling completion. Please retry.","type":"api_error","param":null,"code":"upstream_stream_error"},"request_id":"req_example_0000"}

模型在服务时失败时,code 为 upstream_error;响应超过截止时间时为 hosted_inference_response_timeout;其他情况为 upstream_stream_error,如上面的示例。 参见 错误。

传输中断可能会在没有错误帧的情况下关闭流。 即使 HTTP 状态是 200,缺少 [DONE] 也应视为不完整的响应。 用同一个 Idempotency-Key 重试会返回原始请求的回执,如果它仍在运行则返回 409;它永远不会重放文本。 要获得答案,请用新密钥发送一个新请求,这是一次新的付费推理。 重试之前,请先阅读 重试流式请求。

是否总是包含用量?

不是。网关总会向模型请求用量以便结算请求,但只有当你的请求带有 stream_options.include_usage: true 时,才会把用量帧转发给你。 省略它时,内容帧仍会流式传输,只含用量的帧则会隐藏。 用量帧从不会被合成:如果模型没有报告某个请求的用量,就不会发送用量帧。

有一个例外,让你即使在没有交付答案时也能统计生成的 token。 当每个 choice 都在没有最终答案内容的情况下结束时,无论你是否选择接收,网关都会转发一个带注释的用量帧。

请求中断后,恢复会使用已持久化的用量证据。 检查点写入失败可能导致这些证据缺失或过期,因此无法从最后一个内容片段推断已交付的 token 数量或最终费用。 请保留请求 ID 以便联系支持团队。

流在没有答案时结束

在产生答案内容之前就达到生成上限的 choice,会在其终止帧上带有机器可读的状态:

终止帧
Text
data: {"choices":[{"index":0,"delta":{},"finish_reason":"length","runinfra":{"output_status":{"code":"generation_limit_reached_before_answer","message":"The model reached its generation limit before producing answer content. Increase max_tokens or max_completion_tokens if the model limit allows, or shorten the prompt, then retry."}}}]}

如果是其他终止 finish_reason 导致没有答案,代码则为 no_answer_content。 在决定是否重试之前,请检查保留的 finish_reason。

随后,带注释的用量帧会报告生成的输出中有多少不是答案:

带注释的用量帧
Text
data: {"choices":[],"usage":{"prompt_tokens":12,"completion_tokens":64,"total_tokens":76,"prompt_tokens_details":{"cached_tokens":0},"cost":0,"runinfra":{"output_token_accounting":{"visible_answer_tokens":0,"non_answer_completion_tokens":64,"sources":{"visible_answer_tokens":"proxy_classified","non_answer_completion_tokens":"provider_reported"}},"cost_microcents":0,"cached_input_tokens":0}}}

在这一帧中,没有任何生成的文本送达你,既没有答案也没有推理,所以没有任何计费:它显示 cost: 0 和 cached_tokens: 0。 如果一个流向你发送了推理内容,随后在答案之前耗尽预算,则会对其输入和这些 token 计费。

常见原因是对于先推理的模型来说,输出预算太小。 参见 给推理模型留出空间。