Documentation Index
Fetch the complete documentation index at: https://docs.tokenlab.sh/llms.txt
Use this file to discover all available pages before exploring further.
流式传输让你能够在输出生成过程中接收部分结果,从而改善感知延迟和用户体验。
对于新的 OpenAI 风格集成,优先选择Responses 流式传输。如果你的框架仍在使用 Chat Completions 流式传输,TokenLab 也支持该兼容路径。
推荐:Responses 流式传输
curl https://api.tokenlab.sh/v1/responses \
-H "Authorization: Bearer sk-your-api-key" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-5.4",
"input": "Write a short poem.",
"stream": true
}'
Chat Completions 流式传输
如果你的框架仍然需要来自 /v1/chat/completions 的 SSE 分块,这同样可行:
stream = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Write a short poem"}],
stream=True
)
for chunk in stream:
content = chunk.choices[0].delta.content
if content:
print(content, end="", flush=True)
流结束条件
典型的完成条件:
- Responses API 流使用
response.completed
- Chat Completions 流使用
finish_reason: "stop"
- 当达到 token 限制时使用
finish_reason: "length"
- 当模型希望使用工具时,会出现 tool/function call 事件
Web 应用模式
async function streamChat(message) {
const response = await fetch('https://api.tokenlab.sh/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': 'Bearer sk-your-api-key',
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'gpt-4o',
messages: [{ role: 'user', content: message }],
stream: true
})
});
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
const lines = chunk.split('\\n').filter(line => line.startsWith('data: '));
for (const line of lines) {
const data = line.slice(6);
if (data === '[DONE]') return;
const parsed = JSON.parse(data);
const content = parsed.choices?.[0]?.delta?.content;
if (content) {
document.getElementById('output').textContent += content;
}
}
}
}
最佳实践
如果你的 SDK 或应用已经支持 /v1/responses,请使用它。将 /v1/chat/completions 流式传输保留给出于兼容性需求的集成。
在 delta 分块到达时将其追加到 UI 或终端,而不是等待完整响应返回后再处理。
将网络中断和上游断连视为正常故障模式,并在长时间运行的会话中谨慎地重新连接。