流式传输
流式传输
设置 stream: true 开启 chat completions, 响应 或两者之一 厂商 SDK 并且回复将以 server-sent events 的形式到达。所有官方 SDK 都会为你处理分帧;以下是通过纯 HTTP 获得的数据格式。
import os from openai import OpenAI client = OpenAI( api_key=os.environ["OXYY_API_KEY"], base_url="https://api.oxyy.ai/v1" ) stream = client.chat.completions.create( model="gpt-5.5", messages=[{"role": "user", "content": "Write a haiku about caching."}], stream=True, stream_options={"include_usage": True}, # final chunk carries usage + cost ) for chunk in stream: if chunk.choices and chunk.choices[0].delta.content: print(chunk.choices[0].delta.content, end="", flush=True) elif chunk.usage: print(f"\n\ncost: {chunk.usage.cost}")
import OpenAI from 'openai'; const client = new OpenAI({ apiKey: process.env.OXYY_API_KEY, baseURL: 'https://api.oxyy.ai/v1' }); const stream = await client.chat.completions.create({ model: 'gpt-5.5', messages: [{ role: 'user', content: 'Write a haiku about caching.' }], stream: true, stream_options: { include_usage: true }, }); for await (const chunk of stream) { const delta = chunk.choices?.[0]?.delta?.content; if (delta) process.stdout.write(delta); if (chunk.usage) console.log('\ncost:', chunk.usage.cost); }
curl -N https://api.oxyy.ai/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OXYY_API_KEY" \ -d '{ "model": "gpt-5.5", "messages": [{"role": "user", "content": "Hello!"}], "stream": true, "stream_options": {"include_usage": true} }'
传输中
text/event-stream
data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","created":1700000000,"model":"gpt-5.5","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]}
data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","created":1700000000,"model":"gpt-5.5","choices":[{"index":0,"delta":{"content":"Cold"},"finish_reason":null}]}
data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","created":1700000000,"model":"gpt-5.5","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
// Only when stream_options.include_usage is true — choices is empty here.
data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","created":1700000000,"model":"gpt-5.5","choices":[],"usage":{"prompt_tokens":12,"completion_tokens":17,"total_tokens":29,"cost":0.000106}}
data: [DONE]| 参数 | 类型 | 必填 | 描述 |
|---|---|---|---|
| stream | boolean | 可选 | 以 server-sent events 形式流式传输回复。 默认 false |
| stream_options.include_usage | boolean | 可选 | 在 [DONE] 之前,输出最后一个包含 usage(token 计数和 cost)且 choices 数组为空的数据块。 默认 false |
值得了解的事项。 流总是以
data: [DONE]. 关闭连接会取消上游生成,您只需为已生成的内容付费。在第一个字节到达之后发生的故障将作为流内部的错误帧而不是 HTTP 状态码返回,因为状态码已经发送。Idempotency-Key 在流式请求中会被忽略——流无法重放。