串流輸出 (SSE)
啟用 Server-Sent Events(stream: true)即可在模型生成 Token 的當下即時推送給使用者,將體感首字延遲(TTFT)從數秒縮短至數百毫秒。
搭配用量遙測的 OpenAI SSE 串流
使用 OpenAI 相容端點進行串流時,建議一律帶入 stream_options: {"include_usage": true},讓最後一個 SSE 分塊回傳精準的輸入、輸出與快取命中 Token 數。
python
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["VANIX_API_KEY"],
base_url="https://api.vanix.io/v1",
)
stream = client.chat.completions.create(
model="gpt-4o-mini",
stream=True,
stream_options={"include_usage": True},
messages=[{"role": "user", "content": "Explain SSE chunk framing in 3 lines."}],
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
if chunk.usage:
print("\n--- Usage:", chunk.usage)ts
import OpenAI from 'openai'
const client = new OpenAI({
apiKey: process.env.VANIX_API_KEY,
baseURL: 'https://api.vanix.io/v1',
})
const stream = await client.chat.completions.create({
model: 'gpt-4o-mini',
stream: true,
stream_options: { include_usage: true },
messages: [{ role: 'user', content: 'Explain SSE chunk framing in 3 lines.' }],
})
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content ?? '')
}串流中的推論增量內容
深度推論模型(deepseek-reasoner、o3、Claude Extended Thinking)會在輸出最終回覆之前先傳送思考過程的 Token:
- OpenAI 相容串流:從
chunk.choices[0].delta.reasoning_content讀取思維鏈(Chain-of-Thought)增量,從delta.content讀取最終回覆內容。 - Anthropic 原生串流 (
/v1/messages):監聽content_block_delta事件,區分delta.type === "thinking_delta"與"text_delta"。
閘道串流可靠性保障
- 300s+ 閒置逾時:Vanix AI 負載平衡器會為長耗時推論串流維持連線,避免在深度思考停頓期間過早觸發
504中斷。 - 優雅排空(Graceful Drain):進行滾動部署更新時,執行中的串流連線最多可享有 120 秒的緩衝時間以完整結束,不會被強制切斷。
- 用戶端最佳實務:建議將 HTTP 用戶端的讀取逾時設為至少
120s(深度推論工作負載建議300s),並傳入AbortSignal或context.WithCancel,讓使用者取消對話時立即中止上游計費。