流式响应
TokenSupernova 支持通过 Server-Sent Events(SSE)进行流式响应。设置 stream: true 即可实时接收 Token。
Python
Section titled “Python”from openai import OpenAI
client = OpenAI( api_key="tsn_live_xxx", base_url="https://api.tokensupernova.com/v1",)
stream = client.chat.completions.create( model="deepseek-chat", messages=[{"role": "user", "content": "写一首关于大海的俳句。"}], stream=True,)
for chunk in stream: if chunk.choices[0].delta.content is not None: print(chunk.choices[0].delta.content, end="")Node.js
Section titled “Node.js”import OpenAI from "openai";
const client = new OpenAI({ apiKey: "tsn_live_xxx", baseURL: "https://api.tokensupernova.com/v1",});
const stream = await client.chat.completions.create({ model: "deepseek-chat", messages: [{ role: "user", content: "写一首关于大海的俳句。" }], stream: true,});
for await (const chunk of stream) { process.stdout.write(chunk.choices[0]?.delta?.content || "");}curl "https://api.tokensupernova.com/v1/chat/completions" \ -H "Authorization: Bearer tsn_live_xxx" \ -H "Content-Type: application/json" \ -d '{ "model": "deepseek-chat", "messages": [{"role": "user", "content": "写一首关于大海的俳句。"}], "stream": true }'流式数据块格式
Section titled “流式数据块格式”每个数据块是以 data: 为前缀的 JSON 对象:
data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"深蓝"},"finish_reason":null}]}
data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"色"},"finish_reason":null}]}
data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
data: [DONE]流以 data: [DONE] 结束。