Files
litellm/tests
Cesar GarciaandGitHub 0ed261b34e fix(gemini): fix negative text_tokens when using cache with images (#18768)
* 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.
2026-01-12 17:04:33 +05:30
..
2026-01-10 13:20:43 -08:00
2026-01-08 18:23:05 +05:30
2026-01-11 08:00:31 -08:00
2026-01-10 15:15:41 -08:00
2026-01-02 17:38:52 +09:00

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.