流式響應
RouteAPI 的流式輸出使用 Server-Sent Events(SSE)。在請求中設置 stream: true 後,服務端會逐步返回增量內容。
curl https://www.routeapi.ai/v1/chat/completions \ -H "Authorization: Bearer $ROUTEAPI_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-4o", "stream": true, "messages": [ { "role": "user", "content": "逐步解釋什麼是流式輸出" } ] }'SSE 片段示例
Section titled “SSE 片段示例”data: {"id":"chatcmpl_xxx","choices":[{"delta":{"content":"RouteAPI"}}]}
data: {"id":"chatcmpl_xxx","choices":[{"delta":{"content":" 支持"}}]}
data: [DONE]客戶端應逐行讀取 data: 內容,並在收到 [DONE] 後結束本次響應。
usage 返回
Section titled “usage 返回”如果當前模型支持,流式請求可以通過 stream_options 請求在最後返回 usage:
{ "stream": true, "stream_options": { "include_usage": true }}是否支持該字段取決於所選模型和服務能力。
流式請求可能在連接建立後出現服務側錯誤,例如:
- 模型服務超時
- 賬戶額度不足
- 網絡中斷
- 客戶端主動斷開
- 工具調用參數生成失敗
建議客戶端:
- 為每次請求記錄 request id。
- 對網絡中斷做有限重試。
- 避免對已經產生副作用的工具調用自動重試。
- 在控制台使用日誌排查服務側錯誤。