fix(billing): count tool call tokens when upstream omits usage - #5255
fix(billing): count tool call tokens when upstream omits usage#5255mumingluan wants to merge 1 commit into
Conversation
When an upstream channel returns a tool/function-calling response without a usage object, OpenaiHandler estimates completion tokens locally via CountTextToken. The estimate only covered message content and reasoning content, ignoring tool call names and arguments, which undercounts completion tokens (and therefore billing) for tool-calling responses. Include each tool call's function name and arguments in the text passed to CountTextToken so the estimate reflects the full generated output.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
WalkthroughThe PR enhances the token estimation logic in the OpenAI relay handler by including tool-call function names and arguments in the text used for completion-token counting, alongside the existing message content and reasoning content. ChangesToken Estimation Enhancement
Estimated code review effort🎯 2 (Simple) | ⏱️ ~5 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
51fdfc5 to
2b6f1df
Compare
Problem
When an upstream channel returns a tool/function-calling response without a
usageobject,OpenaiHandlerfalls back to estimating completion tokens locally viaservice.CountTextToken.The current estimate only accounts for message content and reasoning content:
For tool-calling responses, the actual generated output (the tool call
function.nameandarguments) is not counted. This undercounts completion tokens, which in turn undercharges for requests that produce tool calls but whose upstream channel omits usage data.Fix
Include each tool call's
function.nameandargumentsin the text passed toCountTextToken, so the local estimate reflects the full generated output:Scope / Safety
Usage.PromptTokens == 0 && Usage.CompletionTokens == 0). Responses where the upstream provides usage are unchanged.Message.ParseToolCalls()helper; no new API.go build ./relay/channel/openai/passes; no new lint/type errors.Test plan
usage.Summary by CodeRabbit
Bug Fixes