mirror of
https://github.com/tiennm99/litellm.git
synced 2026-07-15 18:21:44 +00:00
* fix(gemini): prevent negative text_tokens with explicit caching (#18750) ## Problem When using Gemini with explicit caching (especially with images), text_tokens would become negative (e.g., -3327) due to incorrectly subtracting total cached_tokens from modality-specific text_tokens. ## Root Cause The old code did: ```python text_tokens = text_tokens - cached_tokens # 737 - 4064 = -3327 ``` This was wrong because: - cached_tokens includes ALL modalities (text + image + audio + video) - text_tokens only contains text - Subtracting total from specific caused negative values ## Solution Parse cacheTokensDetails to get per-modality cached token breakdown: ```python if "cacheTokensDetails" in usage_metadata: cached_text_tokens = parse from cacheTokensDetails["TEXT"] text_tokens = text_tokens - cached_text_tokens # Correct! ``` Now we subtract cached tokens per modality, preventing negatives. ## Changes - Parse cacheTokensDetails field from Gemini response - Calculate non-cached tokens per modality (text, image, audio) - Remove incorrect global cached_tokens subtraction - Add tests for explicit caching and implicit/no caching scenarios ## Testing - Added test_gemini_cache_tokens_details_no_negative_values - Added test_gemini_without_cache_tokens_details - All existing Gemini caching tests pass Fixes #18750 * feat: add cache_read_input_tokens to Usage object Addresses reviewer feedback to include cached tokens at the top level of the Usage object. This aligns with how Anthropic provider handles cached tokens and ensures they are visible in the final usage response. * fix: add cacheTokensDetails field to UsageMetadata TypedDict Fixes mypy error where cacheTokensDetails was being accessed but not defined in the UsageMetadata TypedDict type definition.
In total litellm runs 1000+ tests
[02/20/2025] Update:
To make it easier to contribute and map what behavior is tested,
we've started mapping the litellm directory in tests/test_litellm
This folder can only run mock tests.