Skip to content

fix(py/google-genai): report Gemini tool-use prompt tokens in usage.custom - #168

Merged
huangjeff5 merged 1 commit into
genkit-ai:mainfrom
pcbeingused33:fix/gemini-tool-use-tokens
Dec 1, 2026
Merged

huangjeff5 merged 1 commit into
genkit-ai:mainfrom
pcbeingused33:fix/gemini-tool-use-tokens

Conversation

@pcbeingused33

Copy link
Copy Markdown
Contributor

Cause. Gemini bills tool_use_prompt_token_count (results of google_search, code_execution, url_context) separately from prompt_token_count. _usage_from_metadata ignored it, so those billed tokens never showed up in usage. In addition, _create_usage_stats only copied five fields from the response usage, so any usage.custom would have been lost anyway.

Fix. Report the value as usage.custom = {'toolUseTokens': N}, the same key the JS plugin uses (js/plugins/google-genai/src/googleai/gemini.ts and vertexai/gemini.ts in firebase/genkit), and copy custom in _create_usage_stats. input_tokens and total_tokens are unchanged, as in JS.

Test. gemini_tool_use_tokens_test.py: with tool_use_prompt_token_count=7 the usage carries custom == {'toolUseTokens': 7} and input_tokens == 10; without the field custom is None. Red on main, green with the change.


Disclosure: this change was prepared with AI assistance.

…ustom

Gemini bills tool_use_prompt_token_count (google_search, code_execution,
url_context results) separately from the prompt. The Python plugin dropped it,
and _create_usage_stats discarded any usage.custom. Report it as
custom.toolUseTokens, the key the JS plugin uses, and keep custom when
building the final usage.

@huangjeff5 huangjeff5 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified unit tests and live Gemini API (gemini-flash-lite-latest with code_execution=True, both unary and streaming): tool_use_prompt_token_count now flows through _usage_from_metadata and _create_usage_stats into usage.custom['toolUseTokens'] without inflating input_tokens. Looks good!

@huangjeff5
huangjeff5 enabled auto-merge (squash) November 30, 2026 21:21
@huangjeff5
huangjeff5 merged commit d0685a2 into genkit-ai:main Dec 1, 2026
20 checks passed
@huangjeff5 huangjeff5 mentioned this pull request Dec 3, 2026
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