Repository navigation
Conversation
Greptile SummaryThis 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
Confidence Score: 3/5The 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)
|
| 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 Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
| # 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 |
There was a problem hiding this comment.
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!
| 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() |
There was a problem hiding this comment.
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)
| 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')}" | ||
| ) |
There was a problem hiding this comment.
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.
e39bba6 to
a895a79
Compare
| buffered_finish_chunk = None | ||
| yield _payload(transformed_chunk) | ||
|
|
||
| collected_chunks.append(chunk) |
There was a problem hiding this comment.
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.
PR overviewThis 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.
a895a79 to
b4af751
Compare
Relevant issues
Fixes zero token counts reported by Gemini CLI when proxied through LiteLLM.
Pre-Submission checklist
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_contentformat, which LiteLLMtranslates to OpenAI format and back. Token usage metadata was lost
during this round-trip translation.
Failure 1:
get_stream_optionshostname check (openai.py)get_stream_optionscheckedapi_basehostname againstapi.openai.com. For custom endpoints it returned empty options, sothe upstream API never sent per-chunk usage data.
Fix: Removed the hostname guard.
include_usageis now alwayssent for streaming requests, regardless of
api_base.Failure 2: Adapter never set
stream_options(handler.py)The Google GenAI adapter's
_prepare_completion_kwargsnever addedstream_optionsfor streaming requests.Fix: When
stream=True, setcompletion_kwargs["stream_options"] = {"include_usage": true}.Failure 3:
chunk_creatordiscards usage (streaming_handler.py)When include_usage is sent, the upstream appends a trailing chunk:
{"choices": [], "usage": {"prompt_tokens": N, ...}}
handle_openai_chat_completion_chunkcorrectly extracts usage, butchunk_creatorhandles empty choices with an early return BEFOREthe 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_wrapperyielded the finishReasonchunk with zero usage, then re-yielded it with fallback-injected usage.
The Gemini CLI's
ChatRecordingService.recordMessageTokensrecorded 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_wrapperto buffer thefinishReason chunk, merge usage before emission, and yield exactly
once. Extracted
_compute_fallback_usageas a standalone helper.Router fix (
router.py)When a model group alias was used, the alias name was passed in
input_kwargs["model"]tolitellm.completion(). This causedtoken_counterfallback to see the alias name instead of the realdeployment model.
Fix: Use the resolved deployment model name in
input_kwargsforboth 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 ispassed to litellm.completion/acompletion
test_google_genai_adapter_fixes.py: regression tests forno-zero-usage emission and usage-only chunk merging
test_fallback_usage_attached_to_terminating_chunktoverify the finish chunk is emitted exactly once