The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent/gemini): count thinking tokens in usage and cost
Mehmet Ali983532311f8e
diff --git a/agent/gemini_native_adapter.py b/agent/gemini_native_adapter.pyindex d06255bc1ef..35385fb6779 100644--- a/agent/gemini_native_adapter.py+++ b/agent/gemini_native_adapter.py@@ -551,10 +551,21 @@ def _dump_call_args(fc: Dict[str, Any], **kwargs: Any) -> str:def _usage_from_metadata(usage_meta: Dict[str, Any]) -> SimpleNamespace:+ """Gemini ``usageMetadata`` → OpenAI-shaped usage.++ Hidden thinking is reported separately in ``thoughtsTokenCount``:+ ``candidatesTokenCount`` counts visible output only, while ``totalTokenCount``+ already includes thoughts. OpenAI's ``completion_tokens`` covers reasoning, so+ thoughts are folded in (otherwise a thinking turn bills a few percent of its+ real output and ``prompt + completion != total``) and also surfaced under+ ``completion_tokens_details.reasoning_tokens``, where ``normalize_usage`` reads+ them. Absent on non-thinking/older responses, which keeps their numbers as-is."""count = lambda key: int(usage_meta.get(key) or 0) # noqa: E731+ reasoning_tokens = count("thoughtsTokenCount")return SimpleNamespace(- prompt_tokens=count("promptTokenCount"), completion_tokens=count("candidatesTokenCount"),+ prompt_tokens=count("promptTokenCount"), completion_tokens=count("candidatesTokenCount") + reasoning_tokens,total_tokens=count("totalTokenCount"), prompt_tokens_details=SimpleNamespace(cached_tokens=count("cachedContentTokenCount")),+ completion_tokens_details=SimpleNamespace(reasoning_tokens=reasoning_tokens),)diff --git a/tests/agent/test_gemini_native_adapter.py b/tests/agent/test_gemini_native_adapter.pyindex f218584ec0f..5d65cd4d7ac 100644--- a/tests/agent/test_gemini_native_adapter.py+++ b/tests/agent/test_gemini_native_adapter.py@@ -819,3 +819,76 @@ def test_native_gemini_detection_covers_express_but_not_vertex_oauth_openapi():assert not is_native_gemini_base_url("https://aiplatform.googleapis.com/v1beta1/projects/p/locations/global/endpoints/openapi")+++def test_thinking_tokens_are_counted_as_output_and_surfaced_as_reasoning():+ """Gemini bills hidden thinking under its own ``thoughtsTokenCount``;+ ``candidatesTokenCount`` covers visible output only while ``totalTokenCount``+ includes thoughts. Dropping thoughts made the emitted usage internally+ inconsistent (prompt + completion != total) and billed a thinking turn at a+ fraction of its real output."""+ from agent.gemini_native_adapter import translate_gemini_response+ from agent.usage_pricing import normalize_usage++ prompt, visible, thoughts = 10, 200, 5000+ payload = {+ "candidates": [{"content": {"parts": [{"text": "done"}]}, "finishReason": "STOP"}],+ "usageMetadata": {+ "promptTokenCount": prompt,+ "candidatesTokenCount": visible,+ "thoughtsTokenCount": thoughts,+ "totalTokenCount": prompt + visible + thoughts,+ },+ }++ usage = translate_gemini_response(payload, model="gemini-2.5-flash").usage+ assert usage.prompt_tokens + usage.completion_tokens == usage.total_tokens+ assert usage.completion_tokens_details.reasoning_tokens == thoughts++ canonical = normalize_usage(usage, provider="google")+ assert canonical.output_tokens == visible + thoughts+ assert canonical.reasoning_tokens == thoughts+++def test_streaming_usage_counts_thinking_tokens_like_the_non_streaming_path():+ """Usage rides on the stream's finish chunk; it must agree with the+ non-streaming assembly rather than under-reporting thinking."""+ from agent.gemini_native_adapter import translate_stream_event++ prompt, visible, thoughts = 7, 3, 900+ event = {+ "candidates": [{"content": {"parts": [{"text": "done"}]}, "finishReason": "STOP"}],+ "usageMetadata": {+ "promptTokenCount": prompt,+ "candidatesTokenCount": visible,+ "thoughtsTokenCount": thoughts,+ "totalTokenCount": prompt + visible + thoughts,+ },+ }++ chunks = translate_stream_event(event, model="gemini-2.5-flash", tool_call_indices={})+ usage = chunks[-1].usage+ assert usage.prompt_tokens + usage.completion_tokens == usage.total_tokens+ assert usage.completion_tokens_details.reasoning_tokens == thoughts+++def test_response_without_thinking_tokens_keeps_its_output_count():+ """Non-thinking / older responses omit ``thoughtsTokenCount``; their numbers+ must not move, and reasoning stays zero."""+ from agent.gemini_native_adapter import translate_gemini_response+ from agent.usage_pricing import normalize_usage++ prompt, visible = 10, 5+ payload = {+ "candidates": [{"content": {"parts": [{"text": "hi"}]}, "finishReason": "STOP"}],+ "usageMetadata": {+ "promptTokenCount": prompt,+ "candidatesTokenCount": visible,+ "totalTokenCount": prompt + visible,+ },+ }++ usage = translate_gemini_response(payload, model="gemini-2.5-flash").usage+ assert usage.completion_tokens == visible+ assert usage.prompt_tokens + usage.completion_tokens == usage.total_tokens+ assert normalize_usage(usage, provider="google").reasoning_tokens == 0