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]

fix(gemini): bill context cache creation tokens from cachedContents responses (#46144)

Kerry Lu0eff31ae4e70
diff --git a/litellm/llms/vertex_ai/context_caching/vertex_ai_context_caching.py b/litellm/llms/vertex_ai/context_caching/vertex_ai_context_caching.py
index ebbe2c59886..c8608705eff 100644
--- a/litellm/llms/vertex_ai/context_caching/vertex_ai_context_caching.py
+++ b/litellm/llms/vertex_ai/context_caching/vertex_ai_context_caching.py
@@ -16,6 +16,7 @@ from litellm.llms.custom_httpx.http_handler import (
get_async_httpx_client,
)
from litellm.llms.openai.openai import AllMessageValues
+from litellm.types.llms.vertex_ai import VERTEX_AI_CACHE_CREATION_TOKENS_KEY
from litellm.utils import is_prompt_caching_valid_prompt
from ..common_utils import VertexAIError, get_vertex_base_url
@@ -43,9 +44,15 @@ class _CachedContentListBody(TypedDict):
nextPageToken: ReadOnly[NotRequired[str | None]]
+@with_config(ConfigDict(extra="allow", strict=True, hide_input_in_errors=True))
+class _CachedContentUsageMetadata(TypedDict):
+ totalTokenCount: ReadOnly[NotRequired[int | None]]
+
+
@with_config(ConfigDict(extra="allow", strict=True, hide_input_in_errors=True))
class _CreatedCachedContent(TypedDict):
name: ReadOnly[NotRequired[str | None]]
+ usageMetadata: ReadOnly[NotRequired[_CachedContentUsageMetadata | None]]
class _CachedContentListBodyRoot(RootModel[_CachedContentListBody]):
@@ -56,6 +63,11 @@ class _CreatedCachedContentRoot(RootModel[_CreatedCachedContent]):
model_config = ConfigDict(frozen=True, hide_input_in_errors=True)
+def _record_cache_creation_tokens(logging_obj: Logging, created: _CreatedCachedContent) -> None:
+ tokens: Final = (created.get("usageMetadata") or {}).get("totalTokenCount") or 0
+ logging_obj.model_call_details[VERTEX_AI_CACHE_CREATION_TOKENS_KEY] = tokens # rebind-ok: shared kwargs bag
+
+
class ContextCachingEndpoints(VertexBase):
"""
Covers context caching endpoints for Vertex AI + Google AI Studio
@@ -439,6 +451,7 @@ class ContextCachingEndpoints(VertexBase):
raise VertexAIError(status_code=408, message="Timeout error occurred.")
raw_response_cached: Final = _CreatedCachedContentRoot.model_validate(response.json()).root
+ _record_cache_creation_tokens(logging_obj, raw_response_cached)
return (
non_cached_messages,
optional_params,
@@ -592,6 +605,7 @@ class ContextCachingEndpoints(VertexBase):
raise VertexAIError(status_code=408, message="Timeout error occurred.")
raw_response_cached: Final = _CreatedCachedContentRoot.model_validate(response.json()).root
+ _record_cache_creation_tokens(logging_obj, raw_response_cached)
return (
non_cached_messages,
optional_params,
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 b259d194a32..e3b43e2bb64 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
@@ -54,6 +54,7 @@ from litellm.types.llms.openai import (
OpenAIChatCompletionFinishReason,
)
from litellm.types.llms.vertex_ai import (
+ VERTEX_AI_CACHE_CREATION_TOKENS_KEY,
VERTEX_AI_PROVIDER_METADATA_FIELDS,
VERTEX_CREDENTIALS_TYPES,
Candidates,
@@ -148,6 +149,11 @@ def _unsupported_reasoning_effort(reasoning_effort: str) -> UnsupportedParamsErr
)
+def _cache_creation_tokens(logging_obj: LoggingClass) -> int:
+ recorded: Final = logging_obj.model_call_details.get(VERTEX_AI_CACHE_CREATION_TOKENS_KEY)
+ return recorded if isinstance(recorded, int) else 0
+
+
def _served_model_name(model_version: object) -> str | None:
if not isinstance(model_version, str) or not model_version:
return None
@@ -1815,6 +1821,7 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
@staticmethod
def _calculate_usage(
completion_response: GenerateContentResponseBody | BidiGenerateContentServerMessage,
+ cache_creation_tokens: int = 0,
) -> Usage:
if completion_response is not None and "usageMetadata" not in completion_response:
raise ValueError(f"usageMetadata not found in completion_response. Got={completion_response}")
@@ -1981,11 +1988,14 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
completion_tokens = reasoning_tokens + completion_tokens
## GET USAGE ##
usage: Final = Usage(
- prompt_tokens=usage_metadata.get("promptTokenCount", 0) + billable_tool_use_prompt_tokens,
+ prompt_tokens=usage_metadata.get("promptTokenCount", 0)
+ + billable_tool_use_prompt_tokens
+ + cache_creation_tokens,
completion_tokens=completion_tokens,
- total_tokens=usage_metadata.get("totalTokenCount", 0),
+ total_tokens=usage_metadata.get("totalTokenCount", 0) + cache_creation_tokens,
prompt_tokens_details=prompt_tokens_details,
cache_read_input_tokens=cached_tokens,
+ cache_creation_input_tokens=cache_creation_tokens or None,
reasoning_tokens=reasoning_tokens,
completion_tokens_details=response_tokens_details,
)
@@ -1996,8 +2006,9 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
def calculate_usage(
cls,
completion_response: GenerateContentResponseBody | BidiGenerateContentServerMessage,
+ cache_creation_tokens: int = 0,
) -> Usage:
- return cls._calculate_usage(completion_response)
+ return cls._calculate_usage(completion_response, cache_creation_tokens)
@staticmethod
def _check_finish_reason(
@@ -2608,7 +2619,10 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
_, # cumulative_tool_call_index not needed in non-streaming
) = VertexGeminiConfig._process_candidates(_candidates, model_response, logging_obj.optional_params)
- usage: Final = VertexGeminiConfig._calculate_usage(completion_response=completion_response)
+ usage: Final = VertexGeminiConfig._calculate_usage(
+ completion_response=completion_response,
+ cache_creation_tokens=_cache_creation_tokens(logging_obj),
+ )
VertexGeminiConfig._set_grounding_usage_counters(usage, grounding_metadata)
@@ -3382,6 +3396,7 @@ class ModelResponseIterator:
usage: Final = VertexGeminiConfig.calculate_usage(
completion_response=processed_chunk,
+ cache_creation_tokens=_cache_creation_tokens(self.logging_obj),
)
VertexGeminiConfig.set_grounding_usage_counters(usage, grounding_metadata)
diff --git a/litellm/types/llms/vertex_ai.py b/litellm/types/llms/vertex_ai.py
index 116fdda0b5d..28a174729a8 100644
--- a/litellm/types/llms/vertex_ai.py
+++ b/litellm/types/llms/vertex_ai.py
@@ -583,6 +583,9 @@ class VertexAICachedContentResponseObject(TypedDict):
model: str
+VERTEX_AI_CACHE_CREATION_TOKENS_KEY: Final = "vertex_ai_cache_creation_input_tokens"
+
+
class TaskTypeEnum(Enum):
TASK_TYPE_UNSPECIFIED = "TASK_TYPE_UNSPECIFIED"
RETRIEVAL_QUERY = "RETRIEVAL_QUERY"
diff --git a/tests/integration/cost_calculation/cases/gemini.py b/tests/integration/cost_calculation/cases/gemini.py
index e4e5489edd1..2f9ffcb4daa 100644
--- a/tests/integration/cost_calculation/cases/gemini.py
+++ b/tests/integration/cost_calculation/cases/gemini.py
@@ -10,11 +10,11 @@ from integration.cost_calculation.cost_tracking_case import (
JsonResponse,
RecountExpected,
RecountRates,
+ RoutedResponse,
SseResponse,
)
from integration.cost_calculation.stream_parity.case import StreamParityTestCase, sse_frames
-
# gemini/gemini-3.1-pro
GEMINI_GEMINI_3_1_PRO_INPUT_TEXT: Final = CostTrackingTestCase(
name="gemini-gemini-3.1-pro-input_text",
@@ -3468,6 +3468,81 @@ GEMINI_NANO_BANANA_2_1_WEB_SEARCH_MULTIPLE_QUERIES: Final = CostTrackingTestCase
)
+GEMINI_GEMINI_3_1_PRO_CACHE_CREATION: Final = CostTrackingTestCase(
+ name="gemini-gemini-3.1-pro-cache_creation",
+ covers="quota_management.spend_tracking.cost_matrix.logs_cost",
+ model="gemini/gemini-3.1-pro",
+ request={
+ "model": "$MODEL",
+ "messages": [
+ {
+ "role": "system",
+ "content": [
+ {
+ "type": "text",
+ "text": "cacheable pricing-harness prefix " * 1000,
+ "cache_control": {"type": "ephemeral"},
+ }
+ ],
+ },
+ {
+ "role": "user",
+ "content": [{"type": "text", "text": "9c1d4e7a2b60 answer from the cached prefix in one line"}],
+ },
+ ],
+ "stream": False,
+ "allowed_openai_params": [],
+ },
+ response=RoutedResponse(
+ content_type="application/x-routed",
+ routes={
+ "GET /models/gemini-3.1-pro:cachedContents": JsonResponse(
+ content_type="application/json", body={"cachedContents": []}
+ ),
+ "POST /models/gemini-3.1-pro:cachedContents": JsonResponse(
+ content_type="application/json",
+ body={
+ "name": "cachedContents/$REQUEST_ID",
+ "model": "models/gemini-3.1-pro",
+ "createTime": "2026-10-13T00:00:00Z",
+ "expireTime": "2026-10-13T01:00:00Z",
+ "usageMetadata": {"totalTokenCount": 1280},
+ },
+ ),
+ "POST /models/gemini-3.1-pro:generateContent": JsonResponse(
+ content_type="application/json",
+ body={
+ "candidates": [
+ {
+ "content": {"parts": [{"text": "scripted answer 9c1d4e7a2b60"}], "role": "model"},
+ "finishReason": "STOP",
+ "index": 0,
+ }
+ ],
+ "usageMetadata": {
+ "promptTokenCount": 1536,
+ "candidatesTokenCount": 40,
+ "totalTokenCount": 1576,
+ "cachedContentTokenCount": 1280,
+ "promptTokensDetails": [{"modality": "TEXT", "tokenCount": 1536}],
+ },
+ "modelVersion": "gemini-3.1-pro",
+ },
+ ),
+ },
+ ),
+ expected=ExactExpected(
+ spend=0.003808,
+ input_cost=0.003328,
+ output_cost=0.00048,
+ cache_read_cost=0.000256,
+ cache_creation_cost=0.00256,
+ prompt_tokens=2816,
+ completion_tokens=40,
+ ),
+)
+
+
CASES: Final[tuple[CostTrackingTestCase, ...]] = (
GEMINI_GEMINI_3_1_PRO_INPUT_TEXT,
GEMINI_GEMINI_3_1_PRO_CACHE_READ,
@@ -3528,6 +3603,7 @@ CASES: Final[tuple[CostTrackingTestCase, ...]] = (
GEMINI_NANO_BANANA_2_1_MIXED_TEXT_IMAGE_OUTPUT,
GEMINI_NANO_BANANA_2_1_WEB_SEARCH_SINGLE_QUERY,
GEMINI_NANO_BANANA_2_1_WEB_SEARCH_MULTIPLE_QUERIES,
+ GEMINI_GEMINI_3_1_PRO_CACHE_CREATION,
)
PARITY: Final[tuple[StreamParityTestCase, ...]] = (
diff --git a/tests/unit/llms/vertex_ai/context_caching/test_vertex_ai_context_caching.py b/tests/unit/llms/vertex_ai/context_caching/test_vertex_ai_context_caching.py
index 67d78d6030e..abc0ec661a0 100644
--- a/tests/unit/llms/vertex_ai/context_caching/test_vertex_ai_context_caching.py
+++ b/tests/unit/llms/vertex_ai/context_caching/test_vertex_ai_context_caching.py
@@ -40,6 +40,7 @@ class TestContextCachingEndpoints:
"""Setup for each test method"""
self.context_caching = ContextCachingEndpoints()
self.mock_logging = MagicMock(spec=Logging)
+ self.mock_logging.model_call_details = {}
self.mock_client = MagicMock(spec=HTTPHandler)
self.mock_async_client = MagicMock(spec=AsyncHTTPHandler)
@@ -1790,6 +1791,7 @@ class TestCheckCachePagination:
"""Setup for each test method"""
self.context_caching = ContextCachingEndpoints()
self.mock_logging = MagicMock(spec=Logging)
+ self.mock_logging.model_call_details = {}
self.mock_client = MagicMock(spec=HTTPHandler)
self.mock_async_client = MagicMock(spec=AsyncHTTPHandler)
@@ -2289,3 +2291,111 @@ class TestContextCachingMultiRegionUrls:
assert url.startswith("https://aiplatform.googleapis.com/")
assert "/locations/global/cachedContents" in url
+
+
+def _created_cache_body(total_token_count: int) -> dict:
+ return {
+ "name": "cachedContents/created",
+ "model": "models/gemini-3.1-pro",
+ "usageMetadata": {"totalTokenCount": total_token_count},
+ }
+
+
+def _cacheable_messages() -> list:
+ return [
+ {
+ "role": "system",
+ "content": [
+ {"type": "text", "text": "cacheable prefix " * 1200, "cache_control": {"type": "ephemeral"}}
+ ],
+ },
+ {"role": "user", "content": "question"},
+ ]
+
+
[email protected](ContextCachingEndpoints, "check_cache", return_value=None)
[email protected](ContextCachingEndpoints, "_get_token_and_url_context_caching", return_value=("token", "https://u"))
+def test_check_and_create_cache_records_creation_tokens_for_billing(mock_url, mock_check):
+ from litellm.types.llms.vertex_ai import VERTEX_AI_CACHE_CREATION_TOKENS_KEY
+
+ logging_obj = MagicMock()
+ logging_obj.model_call_details = {}
+ client = MagicMock(spec=HTTPHandler)
+ client.post.return_value = MagicMock(json=lambda: _created_cache_body(1280))
+
+ _, _, cache_name = ContextCachingEndpoints().check_and_create_cache(
+ messages=_cacheable_messages(),
+ optional_params={},
+ api_key="k",
+ api_base=None,
+ model="gemini-3.1-pro",
+ client=client,
+ timeout=30.0,
+ logging_obj=logging_obj,
+ custom_llm_provider="gemini",
+ vertex_project=None,
+ vertex_location=None,
+ vertex_auth_header=None,
+ )
+
+ assert cache_name == "cachedContents/created"
+ assert logging_obj.model_call_details[VERTEX_AI_CACHE_CREATION_TOKENS_KEY] == 1280
+
+
[email protected](ContextCachingEndpoints, "check_cache", return_value="cachedContents/existing")
[email protected](ContextCachingEndpoints, "_get_token_and_url_context_caching", return_value=("token", "https://u"))
+def test_check_and_create_cache_records_no_creation_tokens_when_cache_exists(mock_url, mock_check):
+ from litellm.types.llms.vertex_ai import VERTEX_AI_CACHE_CREATION_TOKENS_KEY
+
+ logging_obj = MagicMock()
+ logging_obj.model_call_details = {}
+ client = MagicMock(spec=HTTPHandler)
+
+ _, _, cache_name = ContextCachingEndpoints().check_and_create_cache(
+ messages=_cacheable_messages(),
+ optional_params={},
+ api_key="k",
+ api_base=None,
+ model="gemini-3.1-pro",
+ client=client,
+ timeout=30.0,
+ logging_obj=logging_obj,
+ custom_llm_provider="gemini",
+ vertex_project=None,
+ vertex_location=None,
+ vertex_auth_header=None,
+ )
+
+ assert cache_name == "cachedContents/existing"
+ client.post.assert_not_called()
+ assert VERTEX_AI_CACHE_CREATION_TOKENS_KEY not in logging_obj.model_call_details
+
+
[email protected](ContextCachingEndpoints, "async_check_cache", return_value=None)
[email protected](ContextCachingEndpoints, "_get_token_and_url_context_caching", return_value=("token", "https://u"))
+async def test_async_check_and_create_cache_records_creation_tokens_for_billing(mock_url, mock_check):
+ from litellm.types.llms.vertex_ai import VERTEX_AI_CACHE_CREATION_TOKENS_KEY
+
+ logging_obj = MagicMock()
+ logging_obj.model_call_details = {}
+ client = MagicMock(spec=AsyncHTTPHandler)
+ client.post = AsyncMock(return_value=MagicMock(json=lambda: _created_cache_body(2048)))
+
+ _, _, cache_name = await ContextCachingEndpoints().async_check_and_create_cache(
+ messages=_cacheable_messages(),
+ optional_params={},
+ api_key="k",
+ api_base=None,
+ model="gemini-3.1-pro",
+ client=client,
+ timeout=30.0,
+ logging_obj=logging_obj,
+ custom_llm_provider="gemini",
+ vertex_project=None,
+ vertex_location=None,
+ vertex_auth_header=None,
+ )
+
+ assert cache_name == "cachedContents/created"
+ assert logging_obj.model_call_details[VERTEX_AI_CACHE_CREATION_TOKENS_KEY] == 2048
diff --git a/tests/unit/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py b/tests/unit/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py
index f98c78b2ae8..bc885891206 100644
--- a/tests/unit/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py
+++ b/tests/unit/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py
@@ -1486,7 +1486,7 @@ def test_vertex_ai_streaming_usage_calculation():
iterator.chunk_parser(chunk)
# Verify calculate_usage was called with correct parameters
- mock_calculate_usage.assert_called_once_with(completion_response=chunk)
+ mock_calculate_usage.assert_called_once_with(completion_response=chunk, cache_creation_tokens=0)
# Test non-streaming response parsing
with patch.object(VertexGeminiConfig, "_calculate_usage") as mock_calculate_usage:
@@ -1512,6 +1512,7 @@ def test_vertex_ai_streaming_usage_calculation():
# Verify _calculate_usage was called with correct parameters
mock_calculate_usage.assert_called_once_with(
completion_response=completion_response,
+ cache_creation_tokens=0,
)
@@ -9598,3 +9599,56 @@ def test_map_openai_params_audio_voice_reaches_speech_config_mapped() -> None:
drop_params=False,
)
assert optional_params["speechConfig"]["voiceConfig"]["prebuiltVoiceConfig"]["voiceName"] == "Kore"
+
+
+_CACHED_PROMPT_USAGE_METADATA = {
+ "promptTokenCount": 1536,
+ "candidatesTokenCount": 40,
+ "totalTokenCount": 1576,
+ "cachedContentTokenCount": 1280,
+ "promptTokensDetails": [{"modality": "TEXT", "tokenCount": 1536}],
+}
+
+
+def test_calculate_usage_bills_context_cache_creation_tokens_once():
+ from litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import VertexGeminiConfig
+
+ usage = VertexGeminiConfig._calculate_usage(
+ {"candidates": [], "usageMetadata": _CACHED_PROMPT_USAGE_METADATA}, cache_creation_tokens=1280
+ )
+
+ assert usage.prompt_tokens == 1536 + 1280
+ assert usage.total_tokens == 1576 + 1280
+ assert usage.cache_creation_input_tokens == 1280
+ assert usage.cache_read_input_tokens == 1280
+ assert usage.prompt_tokens_details.text_tokens == 256
+ assert usage.prompt_tokens_details.cache_creation_tokens == 1280
+
+
+def test_calculate_usage_without_cache_creation_leaves_usage_unchanged():
+ from litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import VertexGeminiConfig
+
+ usage = VertexGeminiConfig._calculate_usage({"candidates": [], "usageMetadata": _CACHED_PROMPT_USAGE_METADATA})
+
+ assert usage.prompt_tokens == 1536
+ assert usage.total_tokens == 1576
+ assert usage.cache_creation_input_tokens is None
+
+
+def test_streaming_usage_reads_cache_creation_tokens_recorded_on_logging_obj():
+ from litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import ModelResponseIterator
+ from litellm.types.llms.vertex_ai import VERTEX_AI_CACHE_CREATION_TOKENS_KEY
+
+ logging_obj = MagicMock()
+ logging_obj.model_call_details = {VERTEX_AI_CACHE_CREATION_TOKENS_KEY: 1280}
+ iterator = ModelResponseIterator(streaming_response=[], sync_stream=True, logging_obj=logging_obj)
+
+ chunk = iterator.chunk_parser(
+ {
+ "candidates": [{"content": {"parts": [{"text": "done"}]}, "finishReason": "STOP", "index": 0}],
+ "usageMetadata": _CACHED_PROMPT_USAGE_METADATA,
+ }
+ )
+
+ assert chunk.usage.prompt_tokens == 1536 + 1280
+ assert chunk.usage.cache_creation_input_tokens == 1280