OpenAI 官方 API 接口在流式调用时,默认是不会返回usage字段,但有提供参数来控制。
参考文档:https://platform.openai.com/docs/api-reference/chat/create
参数设置
// 请求体(额外附加参数:stream_options.include_usage = true)
{
"model": "gpt-4o-mini",
"messages": [
{
"role": "user",
"content": "hi"
}
],
"stream": true,
"stream_options": {
"include_usage": true
}
}
// 响应体(最后一个chunk块,附带了usage消耗字段)
{
"id": "chatcmpl-BzEOPxYeUggGc3nNPUVOJoR7mkOAX",
"object": "chat.completion.chunk",
"created": 1753933033,
"model": "gpt-4o-mini-2024-07-18",
"service_tier": "default",
"system_fingerprint": "fp_62a23a81ef",
"choices": [],
"usage": {
"prompt_tokens": 8,
"completion_tokens": 9,
"total_tokens": 17,
"prompt_tokens_details": {
"cached_tokens": 0,
"audio_tokens": 0
},
"completion_tokens_details": {
"reasoning_tokens": 0,
"audio_tokens": 0,
"accepted_prediction_tokens": 0,
"rejected_prediction_tokens": 0
}
}
}
补充
需要注意,以上的include_usage并不一定适用于所有的 OpenAI 兼容的大模型厂商,比如:DeepSeek、Grok等等,具体是否支持该参数,请具体阅读各厂商的官方文档。
Poixe AI 平台接口已默认为所有流式请求开启该参数,无需额外处理。
