Skip to content

fix: count Gemini toolUsePromptTokenCount as input tokens - #904

Merged
chenyme merged 2 commits into
DEEIX-AI:devfrom
pcbeingused333:fix/gemini-tool-use-prompt-tokens
Oct 31, 2026
Merged

chenyme merged 2 commits into
DEEIX-AI:devfrom
pcbeingused333:fix/gemini-tool-use-prompt-tokens

Conversation

@pcbeingused333

Copy link
Copy Markdown
Contributor

With Gemini's built-in tools (url_context, google_search), usageMetadata.toolUsePromptTokenCount reports the tokens of the tool results that are fed back to the model. They are separate from promptTokenCount and are part of totalTokenCount (for example 31 prompt + 73 candidates + 77 thought + 73 tool-use = 254), but parseGeminiUsage ignored them, so the input tokens came out too low, and so did the cost derived from them (Google's pricing page bills URL context "as input tokens per model pricing").

parseGeminiUsage now adds toolUsePromptTokenCount to promptTokenCount before it subtracts the cached tokens. The tool-use tokens are not part of the cached prefix, so they stay in the non-cached input. A response without the field gives the same result as before. The header comment of the file lists the field.

Tests in usage_test.go cover 31 prompt tokens plus 73 tool-use tokens giving 104 input tokens (it fails before the change), and a response with cached tokens and tool-use tokens (100 prompt, 40 cached, 25 tool-use gives 85 non-cached input and 40 cache reads). go test ./internal/infra/llm/ -run 'Usage|NonCached' passes, and gofmt and go vet are clean for the package. The rest of the suite and live requests were not run.

This change was made with Claude Code.

🤖 Generated with Claude Code

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@pcbeingused333
pcbeingused333 force-pushed the fix/gemini-tool-use-prompt-tokens branch from 0e05f78 to 12c5308 Compare October 29, 2026 02:20
@pcbeingused333 pcbeingused333 changed the title fix(llm): count Gemini toolUsePromptTokenCount as input tokens fix: count Gemini toolUsePromptTokenCount as input tokens Oct 29, 2026
@chenyme
chenyme self-requested a review October 31, 2026 08:52
@chenyme chenyme self-assigned this Oct 31, 2026
@chenyme
chenyme merged commit 1e3e5ff into DEEIX-AI:dev Oct 31, 2026
13 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants