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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix: include IMAGE token count in cost calculation for Gemini models (#18876)
Cesar Garcia932f06104d53
diff --git a/litellm/litellm_core_utils/llm_cost_calc/utils.py b/litellm/litellm_core_utils/llm_cost_calc/utils.pyindex cbc0763382c..65e77f014a3 100644--- a/litellm/litellm_core_utils/llm_cost_calc/utils.py+++ b/litellm/litellm_core_utils/llm_cost_calc/utils.py@@ -485,9 +485,14 @@ def _calculate_input_cost(model_info, "input_cost_per_audio_token", prompt_tokens_details["audio_tokens"])- ### IMAGE TOKEN COST (for gpt-image-1 and similar models)+ ### IMAGE TOKEN COST+ # For image token costs:+ # First check if input_cost_per_image_token is available. If not, default to generic input_cost_per_token.+ image_token_cost_key = "input_cost_per_image_token"+ if model_info.get(image_token_cost_key) is None:+ image_token_cost_key = "input_cost_per_token"prompt_cost += calculate_cost_component(- model_info, "input_cost_per_image_token", prompt_tokens_details["image_tokens"]+ model_info, image_token_cost_key, prompt_tokens_details["image_tokens"])### CACHE WRITING COST - Now uses tiered pricing@@ -521,7 +526,7 @@ def _calculate_input_cost(return prompt_cost-def generic_cost_per_token(+def generic_cost_per_token( # noqa: PLR0915model: str,usage: Usage,custom_llm_provider: str,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.pyindex 91100cf7d7b..b509548d365 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@@ -1515,8 +1515,8 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):)cached_tokens: Optional[int] = Noneaudio_tokens: Optional[int] = None- text_tokens: Optional[int] = Noneimage_tokens: Optional[int] = None+ text_tokens: Optional[int] = Noneprompt_tokens_details: Optional[PromptTokensDetailsWrapper] = Nonereasoning_tokens: Optional[int] = Noneresponse_tokens: Optional[int] = None@@ -1535,6 +1535,7 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):response_tokens_details.text_tokens = detail.get("tokenCount", 0)elif detail["modality"] == "AUDIO":response_tokens_details.audio_tokens = detail.get("tokenCount", 0)+########################################################### CANDIDATES TOKEN DETAILS (e.g., for image generation models) ##diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.jsonindex 2f34d2a7d3d..de341834694 100644--- a/model_prices_and_context_window.json+++ b/model_prices_and_context_window.json@@ -12532,6 +12532,7 @@"deprecation_date": "2026-01-15","cache_read_input_token_cost": 7.5e-08,"input_cost_per_audio_token": 1e-06,+ "input_cost_per_image_token": 3e-07,"input_cost_per_token": 3e-07,"litellm_provider": "vertex_ai-language-models","max_audio_length_hours": 8.4,diff --git a/tests/test_litellm/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py b/tests/test_litellm/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.pyindex d09de3a0f26..661965278f6 100644--- a/tests/test_litellm/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py+++ b/tests/test_litellm/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py@@ -518,19 +518,20 @@ def test_vertex_ai_usage_metadata_response_token_count():v = VertexGeminiConfig()usage_metadata = {- "promptTokenCount": 57,+ "promptTokenCount": 66,"responseTokenCount": 74,"totalTokenCount": 131,- "promptTokensDetails": [{"modality": "TEXT", "tokenCount": 57}],+ "promptTokensDetails": [{"modality": "TEXT", "tokenCount": 57}, {"modality": "IMAGE", "tokenCount": 9}],"responseTokensDetails": [{"modality": "TEXT", "tokenCount": 74}],}usage_metadata = UsageMetadata(**usage_metadata)result = v._calculate_usage(completion_response={"usageMetadata": usage_metadata})print("result", result)- assert result.prompt_tokens == 57+ assert result.prompt_tokens == 66assert result.completion_tokens == 74assert result.total_tokens == 131assert result.prompt_tokens_details.text_tokens == 57+ assert result.prompt_tokens_details.image_tokens == 9assert result.prompt_tokens_details.audio_tokens is Noneassert result.prompt_tokens_details.cached_tokens is Noneassert result.completion_tokens_details.text_tokens == 74diff --git a/tests/test_litellm/test_cost_calculator.py b/tests/test_litellm/test_cost_calculator.pyindex 7036a953b83..f94b758f06e 100644--- a/tests/test_litellm/test_cost_calculator.py+++ b/tests/test_litellm/test_cost_calculator.py@@ -41,17 +41,17 @@ def test_cost_calculator_with_response_cost_in_additional_headers():assert result == 1000-def test_cost_calculator_with_usage():+def test_cost_calculator_with_usage(monkeypatch):from litellm import get_model_infoos.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"litellm.model_cost = litellm.get_model_cost_map(url="")usage = Usage(- prompt_tokens=100,+ prompt_tokens=120,completion_tokens=100,prompt_tokens_details=PromptTokensDetailsWrapper(- text_tokens=10, audio_tokens=90+ text_tokens=10, audio_tokens=90, image_tokens=20,),)mr = ModelResponse(usage=usage, model="gemini-2.0-flash-001")@@ -68,15 +68,53 @@ def test_cost_calculator_with_usage():model_info = litellm.model_cost["gemini-2.0-flash-001"]+ # Step 1: Test a model where input_cost_per_image_token is not set.+ # In this case the calculation should use input_cost_per_token as fallback.+ assert model_info.get("input_cost_per_image_token") is None, "Test case expects that input_cost_per_image_token is not set"+expected_cost = (usage.prompt_tokens_details.audio_tokens* model_info["input_cost_per_audio_token"]+ usage.prompt_tokens_details.text_tokens * model_info["input_cost_per_token"]+ + usage.prompt_tokens_details.image_tokens * model_info["input_cost_per_token"]+ usage.completion_tokens * model_info["output_cost_per_token"])assert result == expected_cost, f"Got {result}, Expected {expected_cost}"+ # Step 2: Set input_cost_per_image_token.+ # In this case the explicit cost information should be used.+ temp_model_info_object = dict(model_info)+ temp_model_info_object["input_cost_per_image_token"] = 0.5++ monkeypatch.setattr(+ litellm,+ "model_cost",+ {+ "gemini-2.0-flash-001": temp_model_info_object+ },+ )++ result = response_cost_calculator(+ response_object=mr,+ model="",+ custom_llm_provider="vertex_ai",+ call_type="acompletion",+ optional_params={},+ cache_hit=None,+ base_model=None,+ )++ expected_cost = (+ usage.prompt_tokens_details.audio_tokens+ * temp_model_info_object["input_cost_per_audio_token"]+ + usage.prompt_tokens_details.text_tokens * temp_model_info_object["input_cost_per_token"]+ + usage.prompt_tokens_details.image_tokens * temp_model_info_object["input_cost_per_image_token"]+ + usage.completion_tokens * temp_model_info_object["output_cost_per_token"]+ )++ assert result == expected_cost, f"Got {result}, Expected {expected_cost}"+def test_transcription_cost_uses_token_pricing():from litellm import completion_costdiff --git a/tests/test_litellm/test_utils.py b/tests/test_litellm/test_utils.pyindex 8fb70e7f114..da52b7bcb39 100644--- a/tests/test_litellm/test_utils.py+++ b/tests/test_litellm/test_utils.py@@ -520,6 +520,7 @@ def test_aaamodel_prices_and_context_window_json_is_valid():"input_cost_per_audio_per_second": {"type": "number"},"input_cost_per_audio_per_second_above_128k_tokens": {"type": "number"},"input_cost_per_audio_token": {"type": "number"},+ "input_cost_per_image_token": {"type": "number"},"input_cost_per_character": {"type": "number"},"input_cost_per_character_above_128k_tokens": {"type": "number"},"input_cost_per_image": {"type": "number"},