fix: add estimated openai usage stats#366
Open
majorcheng wants to merge 1 commit intochenyme:mainfrom
Open
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
修复当前 Python 主线下 OpenAI 兼容接口的 usage 统计问题。
在本次修改前:
/v1/chat/completions返回的usage基本是写死为 0/v1/chat/completions的最终 chunk 不带usage/v1/responses没有把 chat usage 正确映射到最终的response.completed这会导致像 CLIProxyAPI 这类上游客户端虽然能正常拿到响应,但看到的
prompt_tokens、completion_tokens、input_tokens、output_tokens始终是 0。
本 PR 采用最小侵入方式修复该问题:
/v1/responses非流式与流式完成事件都能透传 usage说明:
这里返回的是 本地估算的 usage,用于 OpenAI 兼容客户端展示与统计,
不是上游 Grok 官方精确 billing 口径。
Changes
具体改动:
新增
app/services/grok/utils/usage.py修改
app/services/grok/services/chat.pychat_openai()中先估算prompt_tokensCollectProcessor不再返回写死 0 的 usageStreamProcessor在最终 finish chunk 中附带 usage修改
app/services/grok/services/responses.py/v1/responses使用映射后的 usage/v1/responses从 chat completion 最终 chunk 中提取 usageresponse.completed中返回input_tokens/output_tokens新增回归测试
tests/test_openai_usage.pyRelated Issues
N/A
Verification
验证说明: