API 参考
流式输出
以 server-sent events 的形式,边生成边接收回复。
为什么要用流式输出
不用流式输出时,你要等整条回复写完,才能一次性拿到。使用流式输出时,模型写出的文字会实时到达,用户几乎立刻就能看到回答开始出现。请求完全相同,只多一个字段:"stream": true。
返回的内容
回复的类型是 text/event-stream(server-sent events)。每个事件是一行 data: {…},包含一个 chat.completion.chunk;下一段文本位于 choices[0].delta.content。流以 data: [DONE] 结束。
[DONE] 之前的最后一个分块带有 usage,其中是 token 计数。每个流式请求我们都会向你的实例索取它,所以你无需自己设置 stream_options。
流示例
text
data: {"id":"chatcmpl-example","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","content":"Hel"}}]}
data: {"id":"chatcmpl-example","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"lo!"},"finish_reason":"stop"}]}
data: {"id":"chatcmpl-example","object":"chat.completion.chunk","choices":[],"usage":{"prompt_tokens":12,"completion_tokens":3,"total_tokens":15}}
data: [DONE]示例
cURL(流式)
bash
curl -N https://openllmbuddy-proxy.openllmbuddy.workers.dev/v1/chat/completions \
-H 'Authorization: Bearer ob_sk_000000000000000000000000000000000000000000000001' \
-H 'Content-Type: application/json' \
-d '{"model":"gemma4-26b-a4b-uncensored","stream":true,"messages":[{"role":"user","content":"Hello!"}]}'提示
- 使用 curl 时加上
-N,这样每段内容一到就会打印出来。 - 如果你前面有自己的代理(nginx 之类),请关闭响应缓冲,否则整条回复会在最后才一次性到达。
- 你可以中途停止读取流。到那时为止已写出的 token 仍会计入你的用量。
说明
流开始之前发生的错误会作为普通的 JSON 错误连同状态码返回,而不是作为事件。