流式响应
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。
- 对网络中断做有限重试。
- 避免对已经产生副作用的工具调用自动重试。
- 在控制台使用日志排查服务侧错误。