Skip to content

fix: resolve zero token usage in Google GenAI adapter streaming path - #33050

Open
fktpp2022 wants to merge 1 commit into
BerriAI:mainfrom
fktpp2022:litellm_fix-gemini-zero-token-count
Open

fktpp2022 wants to merge 1 commit into
BerriAI:mainfrom
fktpp2022:litellm_fix-gemini-zero-token-count

Conversation

@fktpp2022

Copy link
Copy Markdown

Relevant issues

Fixes zero token counts reported by Gemini CLI when proxied through LiteLLM.

Pre-Submission checklist

  • I have added meaningful tests
  • My PR passes all CI/CD checks (e.g., lint, format, unit tests)
  • My PR scope is as isolated as possible; it only solves 1 specific problem

Type

🐛 Bug Fix
✅ Test

Changes

Root cause: Four independent failures conspired to produce zero token
counts when Gemini CLI sent requests through LiteLLM proxy. The Gemini
CLI uses Google GenAI generate_content format, which LiteLLM
translates to OpenAI format and back. Token usage metadata was lost
during this round-trip translation.

Failure 1: get_stream_options hostname check (openai.py)

get_stream_options checked api_base hostname against
api.openai.com. For custom endpoints it returned empty options, so
the upstream API never sent per-chunk usage data.

Fix: Removed the hostname guard. include_usage is now always
sent for streaming requests, regardless of api_base.

Failure 2: Adapter never set stream_options (handler.py)

The Google GenAI adapter's _prepare_completion_kwargs never added
stream_options for streaming requests.

Fix: When stream=True, set
completion_kwargs["stream_options"] = {"include_usage": true}.

Failure 3: chunk_creator discards usage (streaming_handler.py)

When include_usage is sent, the upstream appends a trailing chunk:
{"choices": [], "usage": {"prompt_tokens": N, ...}}

handle_openai_chat_completion_chunk correctly extracts usage, but
chunk_creator handles empty choices with an early return BEFORE
the usage-setting code runs. The returned ModelResponseStream has
usage=None, so stream_chunk_builder finds no usage data and falls back
to token_counter, which returns 0 for custom model names.

Not fixed in this PR (needs separate streaming_handler change).

Failure 4 (duplication): Fallback re-yielding (transformation.py)

The old async_google_genai_sse_wrapper yielded the finishReason
chunk with zero usage, then re-yielded it with fallback-injected usage.
The Gemini CLI's ChatRecordingService.recordMessageTokens
recorded the first {0,0,0} as the per-message token snapshot, and the
second real values went into a queued that was never flushed.

Fix: Rewrote async_google_genai_sse_wrapper to buffer the
finishReason chunk, merge usage before emission, and yield exactly
once. Extracted _compute_fallback_usage as a standalone helper.

Router fix (router.py)

When a model group alias was used, the alias name was passed in
input_kwargs["model"] to litellm.completion(). This caused
token_counter fallback to see the alias name instead of the real
deployment model.

Fix: Use the resolved deployment model name in input_kwargs for
both sync and async completion paths.

Tests added

  • test_get_stream_options.py: tests for all api_base scenarios
    (openai, custom, localhost, None, explicit options)
  • test_router_model_alias.py: verifies resolved model name is
    passed to litellm.completion/acompletion
  • test_google_genai_adapter_fixes.py: regression tests for
    no-zero-usage emission and usage-only chunk merging
  • Updated test_fallback_usage_attached_to_terminating_chunk to
    verify the finish chunk is emitted exactly once

@greptile-apps

greptile-apps Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR addresses zero token counts reported by Gemini CLI when proxied through LiteLLM by fixing four independent failure points in the streaming token-usage pipeline. The core changes are a rewrite of async_google_genai_sse_wrapper to buffer and merge usage into the terminating chunk before emission, explicit injection of stream_options: {include_usage: True} from the Google GenAI adapter's handler.py, and a router fix to pass the resolved deployment model name (not the alias) to litellm.completion/acompletion.

  • transformation.py: async_google_genai_sse_wrapper is rewritten to buffer the finish-reason chunk, merge any arriving usage-only chunk into it, and emit exactly once; _compute_fallback_usage is extracted as a standalone helper with a guarded stream_chunk_builder call.
  • openai.py: The api.openai.com hostname guard is removed so stream_options: {include_usage: True} is now sent to every provider through the OpenAI handler, which is broader than the Google GenAI path that motivated the fix.
  • conclusion.md: A 289-line analysis document is committed to the repo root, which violates the project's policy of keeping documentation in the litellm-docs repo.

Confidence Score: 3/5

The streaming-adapter and router fixes are well-targeted and well-tested, but the openai.py change affects all providers unconditionally and could break users whose custom endpoints reject the new stream_options field.

The get_stream_options change sends stream_options: {include_usage: True} to every provider routing through OpenAIChatCompletion. The handler.py fix already covers the Google GenAI adapter path specifically; the broader openai.py change goes further than the reported issue requires and has no opt-out mechanism. A committed conclusion.md doc should not be in this repo, and one of the new router tests asserts metadata state that the router fix does not actually set up.

litellm/llms/openai/openai.py (broad stream_options change), conclusion.md (should be removed), tests/router_unit_tests/test_router_model_alias.py (third test assertion on unimplemented metadata)

Important Files Changed

Filename Overview
litellm/llms/openai/openai.py Removes the api.openai.com hostname guard so stream_options: {include_usage: True} is now sent to ALL providers — a broader change than required and potentially backwards-incompatible for providers that reject unknown fields.
litellm/google_genai/adapters/transformation.py Rewrites async_google_genai_sse_wrapper to buffer the terminating chunk, merge usage before emission, and emit exactly once; extracts _compute_fallback_usage as a standalone helper. Logic is sound and well-tested.
litellm/google_genai/adapters/handler.py Adds stream_options: {include_usage: True} when stream=True in _prepare_completion_kwargs — minimal, targeted fix.
litellm/router.py Adds input_kwargs["model"] = model_name override in both sync and async completion paths to prevent alias names from being passed to litellm.completion/acompletion; the sync streaming-fallback dict is not updated with the same override but may be intentional.
litellm/litellm_core_utils/litellm_logging.py Adds early-return for already-transformed ModelResponse objects and a dict fallback when httpx_response is None; extends the function to handle responses that arrive without an httpx_response object.
conclusion.md New 289-line root-level analysis document — should not be committed to this repository per the policy that documentation lives in the litellm-docs repo.
tests/test_litellm/google_genai/test_google_genai_adapter_fixes.py Adds regression tests for no-zero-usage emission, finish-chunk deduplication, and usage-only chunk merging; all mock-based with no real network calls.
tests/router_unit_tests/test_router_model_alias.py Adds mock tests verifying the router passes the resolved deployment model name to litellm.completion/acompletion; the metadata-deployment assertion in the third test may not be supported by the current router code.
tests/test_litellm/llms/openai/test_get_stream_options.py New unit tests for the updated get_stream_options behavior; all mock-based and correctly cover the changed logic.

Reviews (1): Last reviewed commit: "fix: resolve zero token usage in Google ..." | Re-trigger Greptile

@codecov

codecov Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 72.85714% with 19 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/google_genai/adapters/transformation.py 73.13% 18 Missing ⚠️
litellm/router.py 50.00% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

Comment thread conclusion.md Outdated
Comment on lines +1 to +10
# Gemini CLI Token Count Zero via LiteLLM Proxy - Root Cause Analysis

## Overview

When Gemini CLI is configured to use LiteLLM Proxy as its LLM API base, all model
responses report zero token counts. The Gemini CLI uses the Google GenAI
`generate_content` format, which LiteLLM translates to OpenAI format and back.
Token usage metadata is lost during this round-trip translation.

## Request Flow

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Documentation file committed to the wrong repository

conclusion.md is a 289-line root-level analysis document that describes the root cause of the bug. Per the team's policy, documentation belongs in the litellm-docs repo, not this one. Please remove this file from the PR before merging.

Rule Used: Prevent documentation from being added - needs to ... (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Comment thread litellm/llms/openai/openai.py Outdated
Comment on lines 1127 to 1139
def get_stream_options(self, stream_options: Optional[dict], api_base: Optional[str]) -> dict:
"""
Pass `stream_options` to the data dict for OpenAI requests

Always includes usage by default (even for non-OpenAI api_base
endpoints) so streaming token counts are available for cost tracking.
"""
if stream_options is not None:
return {"stream_options": stream_options}
else:
# by default litellm will include usage for openai endpoints
if api_base is None or urlparse(api_base).hostname == "api.openai.com":
return {"stream_options": {"include_usage": True}}
return {}
return {"stream_options": {"include_usage": True}}

# Embedding
@track_llm_api_timing()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Backwards-incompatible broadening of stream_options delivery

Removing the api.openai.com hostname guard means stream_options: {include_usage: True} is now sent to every provider that goes through OpenAIChatCompletion, including local models (Ollama, LM Studio) and arbitrary custom endpoints. Providers that treat unknown request-body fields as errors (returning HTTP 400) or that silently strip the field and omit usage data will regress for existing users. The handler.py change already injects stream_options specifically for the Google GenAI adapter path, so the change in openai.py is broader than needed to fix the reported issue.

Per the team's policy, behaviour-changing defaults that affect all providers should be gated behind a user-controlled flag rather than applied unconditionally.

Rule Used: What: avoid backwards-incompatible changes without... (source)

Comment on lines +100 to +137
def test_router_completion_records_deployment_model_in_metadata():
"""
The resolved deployment model name should be recorded in metadata
for logging/tracking purposes.
"""
router = Router(
model_list=[
{
"model_name": "gpt-4o-mini",
"litellm_params": {
"model": "openai/gpt-4o-mini",
"api_key": "sk-test",
},
}
],
model_group_alias={"my-alias": "gpt-4o-mini"},
)

with patch.object(router, "_get_client", return_value=MagicMock()), patch(
"litellm.completion"
) as mock_completion:
mock_completion.return_value = MagicMock(
choices=[MagicMock()],
_hidden_params={},
)

router._completion(
model="my-alias",
messages=[{"role": "user", "content": "Hello"}],
mock_response="Hi",
)

call_kwargs = mock_completion.call_args.kwargs
metadata = call_kwargs.get("metadata", {}) or {}
# The deployment model name should be recorded in metadata
assert metadata.get("deployment") == "openai/gpt-4o-mini", (
f"Expected deployment='openai/gpt-4o-mini', got {metadata.get('deployment')}"
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Third test asserts metadata behavior that the router fix doesn't implement

test_router_completion_records_deployment_model_in_metadata asserts metadata.get("deployment") == "openai/gpt-4o-mini", but the router.py diff only adds input_kwargs["model"] = model_name — it adds nothing to a metadata dict. Unless _update_kwargs_with_deployment or another existing code path already writes a deployment key into metadata, this test will always fail, making it a broken assertion rather than a guard against regressions.

@codspeed

codspeed Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing fktpp2022:litellm_fix-gemini-zero-token-count (b4af751) with litellm_internal_staging (09889e1)

Open in CodSpeed

@fktpp2022
fktpp2022 force-pushed the litellm_fix-gemini-zero-token-count branch from e39bba6 to a895a79 Compare July 14, 2026 12:09
buffered_finish_chunk = None
yield _payload(transformed_chunk)

collected_chunks.append(chunk)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Medium: Unbounded streaming response retention

Every ModelResponseStream is retained until the upstream stream ends, after which _compute_fallback_usage synchronously assembles and tokenizes the full output. An authenticated client can open concurrent streams with large maxOutputTokens values to exhaust worker memory and block other requests; keep bounded/incremental usage state, or cap collection and omit the fallback once that cap is reached.

@veria-ai

veria-ai Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

PR overview

This pull request updates the Google GenAI adapter’s streaming path to address cases where token usage was reported as zero, adding fallback usage computation for streamed model responses.

There is one open security concern in the streaming implementation: it retains full streamed responses until completion and then tokenizes the accumulated output synchronously. An authenticated client could abuse large concurrent streams to drive memory pressure and worker blocking, so the PR still carries a moderate denial-of-service risk until usage tracking is made bounded or incremental.

Open issues (1)

Fixed/addressed: 0 · PR risk: 6/10

Root cause: four independent failures conspired to produce zero token
counts when Gemini CLI sent requests through LiteLLM proxy.

1. get_stream_options checked api_base hostname against api.openai.com,
   returning empty options for custom endpoints
2. Google GenAI adapter never set stream_options on completion kwargs
3. chunk_creator discarded usage from usage-only chunks before the
   usage-setting code could run
4. The fallback in async_google_genai_sse_wrapper re-yielded the
   finishReason chunk with injected usage, causing the client to receive
   zero-filled usageMetadata first and then a duplicate with real values,
   which corrupted per-message token persistence

Fixes 1 and 2: always include stream_options for streaming requests,
regardless of api_base hostname (fixes in openai.py and handler.py)

Fixes router: pass resolved deployment model name (not alias) in
input_kwargs so token_counter fallback sees the real model

Fixes 4 (duplication): rewrite async_google_genai_sse_wrapper to
buffer the finishReason chunk, merge usage before emission, and yield
exactly once. Extract _compute_fallback_usage as a standalone helper so
the logic is reusable and the method is half the length.

Adds tests: get_stream_options tests for all api_base scenarios,
router model alias resolution tests, regression tests for no-zero-usage
emission and usage-only chunk merging, and updated fallback test that
verifies no duplication.

This branch has not been deployed

No deployments
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