Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

Capture Gemini reasoning tokens usage in streaming mode - fix (#10789)

Dima-Mediator11740ce14493
diff --git a/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py b/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py
index caf591585b2..c230d062cca 100644
--- a/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py
+++ b/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py
@@ -1626,6 +1626,11 @@ class ModelResponseIterator:
total_tokens=processed_chunk["usageMetadata"].get(
"totalTokenCount", 0
),
+ completion_tokens_details={
+ "reasoning_tokens": processed_chunk["usageMetadata"].get(
+ "thoughtsTokenCount", 0
+ )
+ }
)
returned_chunk = GenericStreamingChunk(
diff --git a/tests/litellm/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py b/tests/litellm/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py
index 133d4aebb37..6438fbe7785 100644
--- a/tests/litellm/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py
+++ b/tests/litellm/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py
@@ -316,6 +316,31 @@ def test_vertex_ai_candidate_token_count_inclusive(
assert usage.completion_tokens == expected_usage.completion_tokens
assert usage.total_tokens == expected_usage.total_tokens
+def test_streaming_chunk_includes_reasoning_tokens():
+ from litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import ModelResponseIterator
+ # Simulate a streaming chunk as would be received from Gemini
+ chunk = {
+ "candidates": [
+ {
+ "content": {
+ "parts": [{"text": "Hello"}]
+ }
+ }
+ ],
+ "usageMetadata": {
+ "promptTokenCount": 5,
+ "candidatesTokenCount": 7,
+ "totalTokenCount": 12,
+ "thoughtsTokenCount": 3,
+ }
+ }
+ iterator = ModelResponseIterator(streaming_response=[], sync_stream=True)
+ streaming_chunk = iterator.chunk_parser(chunk)
+ assert streaming_chunk["usage"] is not None
+ assert streaming_chunk["usage"]["prompt_tokens"] == 5
+ assert streaming_chunk["usage"]["completion_tokens"] == 7
+ assert streaming_chunk["usage"]["total_tokens"] == 12
+ assert streaming_chunk["usage"]["completion_tokens_details"]["reasoning_tokens"] == 3
def test_check_finish_reason():
config = VertexGeminiConfig()