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(cost_calculator): correct gpt-image-1 cost calculation using token-based pricing (#17906)
Cesar Garciac8950a5ba293
diff --git a/litellm/litellm_core_utils/llm_cost_calc/utils.py b/litellm/litellm_core_utils/llm_cost_calc/utils.pyindex 232d9bfc5d1..e36d6d68367 100644--- a/litellm/litellm_core_utils/llm_cost_calc/utils.py+++ b/litellm/litellm_core_utils/llm_cost_calc/utils.py@@ -161,6 +161,15 @@ def _get_token_base_cost(prompt_base_cost = cast(float, _get_cost_per_unit(model_info, input_cost_key))completion_base_cost = cast(float, _get_cost_per_unit(model_info, output_cost_key))++ # For image generation models that don't have output_cost_per_token,+ # use output_cost_per_image_token as the base cost (all output tokens are image tokens)+ if completion_base_cost == 0.0 or completion_base_cost is None:+ output_image_cost = _get_cost_per_unit(+ model_info, "output_cost_per_image_token", None+ )+ if output_image_cost is not None:+ completion_base_cost = cast(float, output_image_cost)cache_creation_cost = cast(float, _get_cost_per_unit(model_info, cache_creation_cost_key))@@ -342,6 +351,7 @@ class PromptTokensDetailsResult(TypedDict):cache_creation_token_details: Optional[CacheCreationTokenDetails]text_tokens: intaudio_tokens: int+ image_tokens: intcharacter_count: intimage_count: intvideo_length_seconds: int@@ -374,6 +384,10 @@ def _parse_prompt_tokens_details(usage: Usage) -> PromptTokensDetailsResult:cast(Optional[int], getattr(usage.prompt_tokens_details, "audio_tokens", 0))or 0)+ image_tokens = (+ cast(Optional[int], getattr(usage.prompt_tokens_details, "image_tokens", 0))+ or 0+ )character_count = (cast(Optional[int],@@ -398,6 +412,7 @@ def _parse_prompt_tokens_details(usage: Usage) -> PromptTokensDetailsResult:cache_creation_token_details=cache_creation_token_details,text_tokens=text_tokens,audio_tokens=audio_tokens,+ image_tokens=image_tokens,character_count=character_count,image_count=image_count,video_length_seconds=video_length_seconds,@@ -470,6 +485,11 @@ 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)+ prompt_cost += calculate_cost_component(+ model_info, "input_cost_per_image_token", prompt_tokens_details["image_tokens"]+ )+### CACHE WRITING COST - Now uses tiered pricingprompt_cost += calculate_cache_writing_cost(cache_creation_tokens=prompt_tokens_details["cache_creation_tokens"],@@ -533,6 +553,7 @@ def generic_cost_per_token(cache_creation_token_details=None,text_tokens=usage.prompt_tokens,audio_tokens=0,+ image_tokens=0,character_count=0,image_count=0,video_length_seconds=0,@@ -782,6 +803,50 @@ class CostCalculatorUtils:model=model,image_response=completion_response,)+ elif custom_llm_provider == litellm.LlmProviders.OPENAI.value:+ # Check if this is a gpt-image model (token-based pricing)+ model_lower = model.lower()+ if "gpt-image-1" in model_lower:+ from litellm.llms.openai.image_generation.cost_calculator import (+ cost_calculator as openai_gpt_image_cost_calculator,+ )++ return openai_gpt_image_cost_calculator(+ model=model,+ image_response=completion_response,+ custom_llm_provider=custom_llm_provider,+ )+ # Fall through to default for DALL-E models+ return default_image_cost_calculator(+ model=model,+ quality=quality,+ custom_llm_provider=custom_llm_provider,+ n=n,+ size=size,+ optional_params=optional_params,+ )+ elif custom_llm_provider == litellm.LlmProviders.AZURE.value:+ # Check if this is a gpt-image model (token-based pricing)+ model_lower = model.lower()+ if "gpt-image-1" in model_lower:+ from litellm.llms.openai.image_generation.cost_calculator import (+ cost_calculator as openai_gpt_image_cost_calculator,+ )++ return openai_gpt_image_cost_calculator(+ model=model,+ image_response=completion_response,+ custom_llm_provider=custom_llm_provider,+ )+ # Fall through to default for DALL-E models+ return default_image_cost_calculator(+ model=model,+ quality=quality,+ custom_llm_provider=custom_llm_provider,+ n=n,+ size=size,+ optional_params=optional_params,+ )else:return default_image_cost_calculator(model=model,diff --git a/litellm/llms/openai/image_generation/cost_calculator.py b/litellm/llms/openai/image_generation/cost_calculator.pynew file mode 100644index 00000000000..35caaf6e9b1--- /dev/null+++ b/litellm/llms/openai/image_generation/cost_calculator.py@@ -0,0 +1,63 @@+"""+Cost calculator for OpenAI image generation models (gpt-image-1, gpt-image-1-mini)++These models use token-based pricing instead of pixel-based pricing like DALL-E.+"""++from typing import Optional++from litellm import verbose_logger+from litellm.litellm_core_utils.llm_cost_calc.utils import generic_cost_per_token+from litellm.responses.utils import ResponseAPILoggingUtils+from litellm.types.utils import ImageResponse+++def cost_calculator(+ model: str,+ image_response: ImageResponse,+ custom_llm_provider: Optional[str] = None,+) -> float:+ """+ Calculate cost for OpenAI gpt-image-1 and gpt-image-1-mini models.++ Uses the same usage format as Responses API, so we reuse the helper+ to transform to chat completion format and use generic_cost_per_token.++ Args:+ model: The model name (e.g., "gpt-image-1", "gpt-image-1-mini")+ image_response: The ImageResponse containing usage data+ custom_llm_provider: Optional provider name++ Returns:+ float: Total cost in USD+ """+ usage = getattr(image_response, "usage", None)++ if usage is None:+ verbose_logger.debug(+ f"No usage data available for {model}, cannot calculate token-based cost"+ )+ return 0.0++ # Transform ImageUsage to Usage using the existing helper+ # ImageUsage has the same format as ResponseAPIUsage+ chat_usage = ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage(+ usage+ )++ # Use generic_cost_per_token for cost calculation+ prompt_cost, completion_cost = generic_cost_per_token(+ model=model,+ usage=chat_usage,+ custom_llm_provider=custom_llm_provider or "openai",+ )++ total_cost = prompt_cost + completion_cost++ verbose_logger.debug(+ f"OpenAI gpt-image cost calculation for {model}: "+ f"prompt_cost=${prompt_cost:.6f}, completion_cost=${completion_cost:.6f}, "+ f"total=${total_cost:.6f}"+ )++ return total_costdiff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.jsonindex 9451862ce7d..c585dac9063 100644--- a/litellm/model_prices_and_context_window_backup.json+++ b/litellm/model_prices_and_context_window_backup.json@@ -3663,12 +3663,16 @@"supports_web_search": true},"azure/gpt-image-1": {- "input_cost_per_pixel": 4.0054321e-08,+ "cache_read_input_image_token_cost": 2.5e-06,+ "cache_read_input_token_cost": 1.25e-06,+ "input_cost_per_image_token": 1e-05,+ "input_cost_per_token": 5e-06,"litellm_provider": "azure","mode": "image_generation",- "output_cost_per_pixel": 0.0,+ "output_cost_per_image_token": 4e-05,"supported_endpoints": [- "/v1/images/generations"+ "/v1/images/generations",+ "/v1/images/edits"]},"azure/hd/1024-x-1024/dall-e-3": {@@ -3771,12 +3775,16 @@]},"azure/gpt-image-1-mini": {- "input_cost_per_pixel": 8.0566406e-09,+ "cache_read_input_image_token_cost": 2.5e-07,+ "cache_read_input_token_cost": 2e-07,+ "input_cost_per_image_token": 2.5e-06,+ "input_cost_per_token": 2e-06,"litellm_provider": "azure","mode": "image_generation",- "output_cost_per_pixel": 0.0,+ "output_cost_per_image_token": 8e-06,"supported_endpoints": [- "/v1/images/generations"+ "/v1/images/generations",+ "/v1/images/edits"]},"azure/gpt-image-1.5": {@@ -18071,16 +18079,16 @@"supports_vision": true},"gpt-image-1": {- "input_cost_per_image": 0.042,- "input_cost_per_pixel": 4.0054321e-08,- "input_cost_per_token": 0.000005,- "input_cost_per_image_token": 0.00001,+ "cache_read_input_image_token_cost": 2.5e-06,+ "cache_read_input_token_cost": 1.25e-06,+ "input_cost_per_image_token": 1e-05,+ "input_cost_per_token": 5e-06,"litellm_provider": "openai","mode": "image_generation",- "output_cost_per_pixel": 0.0,- "output_cost_per_token": 0.00004,+ "output_cost_per_image_token": 4e-05,"supported_endpoints": [- "/v1/images/generations"+ "/v1/images/generations",+ "/v1/images/edits"]},"gpt-image-1-mini": {diff --git a/litellm/responses/utils.py b/litellm/responses/utils.pyindex ad99609e905..a92b5d25a37 100644--- a/litellm/responses/utils.py+++ b/litellm/responses/utils.py@@ -26,7 +26,7 @@ from litellm.types.llms.openai import (from litellm.types.responses.main import DecodedResponseIdfrom litellm.types.utils import (CompletionTokensDetailsWrapper,- PromptTokensDetails,+ PromptTokensDetailsWrapper,SpecialEnums,Usage,)@@ -431,7 +431,12 @@ class ResponseAPILoggingUtils:def _transform_response_api_usage_to_chat_usage(usage_input: Optional[Union[dict, ResponseAPIUsage]],) -> Usage:- """Tranforms the ResponseAPIUsage object to a Usage object"""+ """+ Transforms ResponseAPIUsage or ImageUsage to a Usage object.++ Both have the same spec with input_tokens, output_tokens, and+ input_tokens_details (text_tokens, image_tokens).+ """if usage_input is None:return Usage(prompt_tokens=0,@@ -445,18 +450,19 @@ class ResponseAPILoggingUtils:)prompt_tokens: int = response_api_usage.input_tokens or 0completion_tokens: int = response_api_usage.output_tokens or 0- prompt_tokens_details: Optional[PromptTokensDetails] = None+ prompt_tokens_details: Optional[PromptTokensDetailsWrapper] = Noneif response_api_usage.input_tokens_details:- prompt_tokens_details = PromptTokensDetails(- cached_tokens=response_api_usage.input_tokens_details.cached_tokens,- audio_tokens=response_api_usage.input_tokens_details.audio_tokens,+ prompt_tokens_details = PromptTokensDetailsWrapper(+ cached_tokens=getattr(response_api_usage.input_tokens_details, "cached_tokens", None),+ audio_tokens=getattr(response_api_usage.input_tokens_details, "audio_tokens", None),+ text_tokens=getattr(response_api_usage.input_tokens_details, "text_tokens", None),+ image_tokens=getattr(response_api_usage.input_tokens_details, "image_tokens", None),)completion_tokens_details: Optional[CompletionTokensDetailsWrapper] = None- if response_api_usage.output_tokens_details:+ output_tokens_details = getattr(response_api_usage, "output_tokens_details", None)+ if output_tokens_details:completion_tokens_details = CompletionTokensDetailsWrapper(- reasoning_tokens=getattr(- response_api_usage.output_tokens_details, "reasoning_tokens", None- )+ reasoning_tokens=getattr(output_tokens_details, "reasoning_tokens", None))chat_usage = Usage(diff --git a/litellm/types/utils.py b/litellm/types/utils.pyindex 144e503acdf..3eec67d9d26 100644--- a/litellm/types/utils.py+++ b/litellm/types/utils.py@@ -142,6 +142,7 @@ class ModelInfoBase(ProviderSpecificModelInfo, total=False):] # only for vertex ai modelsinput_cost_per_query: Optional[float] # only for rerank modelsinput_cost_per_image: Optional[float] # only for vertex ai models+ input_cost_per_image_token: Optional[float] # for gpt-image-1 and similar modelsinput_cost_per_audio_per_second: Optional[float] # only for vertex ai modelsinput_cost_per_video_per_second: Optional[float] # only for vertex ai modelsinput_cost_per_second: Optional[float] # for OpenAI Speech models@@ -1300,7 +1301,7 @@ class CacheCreationTokenDetails(BaseModel):class PromptTokensDetailsWrapper(PromptTokensDetails-): # wrapper for older openai versions+): # extends with image generation fields (text_tokens, image_tokens)text_tokens: Optional[int] = None"""Text tokens sent to the model."""diff --git a/litellm/utils.py b/litellm/utils.pyindex 102df5d595e..8b597d02883 100644--- a/litellm/utils.py+++ b/litellm/utils.py@@ -5216,6 +5216,9 @@ def _get_model_info_helper( # noqa: PLR0915input_cost_per_audio_token=_model_info.get("input_cost_per_audio_token", None),+ input_cost_per_image_token=_model_info.get(+ "input_cost_per_image_token", None+ ),input_cost_per_token_batches=_model_info.get("input_cost_per_token_batches"),diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.jsonindex 9451862ce7d..c585dac9063 100644--- a/model_prices_and_context_window.json+++ b/model_prices_and_context_window.json@@ -3663,12 +3663,16 @@"supports_web_search": true},"azure/gpt-image-1": {- "input_cost_per_pixel": 4.0054321e-08,+ "cache_read_input_image_token_cost": 2.5e-06,+ "cache_read_input_token_cost": 1.25e-06,+ "input_cost_per_image_token": 1e-05,+ "input_cost_per_token": 5e-06,"litellm_provider": "azure","mode": "image_generation",- "output_cost_per_pixel": 0.0,+ "output_cost_per_image_token": 4e-05,"supported_endpoints": [- "/v1/images/generations"+ "/v1/images/generations",+ "/v1/images/edits"]},"azure/hd/1024-x-1024/dall-e-3": {@@ -3771,12 +3775,16 @@]},"azure/gpt-image-1-mini": {- "input_cost_per_pixel": 8.0566406e-09,+ "cache_read_input_image_token_cost": 2.5e-07,+ "cache_read_input_token_cost": 2e-07,+ "input_cost_per_image_token": 2.5e-06,+ "input_cost_per_token": 2e-06,"litellm_provider": "azure","mode": "image_generation",- "output_cost_per_pixel": 0.0,+ "output_cost_per_image_token": 8e-06,"supported_endpoints": [- "/v1/images/generations"+ "/v1/images/generations",+ "/v1/images/edits"]},"azure/gpt-image-1.5": {@@ -18071,16 +18079,16 @@"supports_vision": true},"gpt-image-1": {- "input_cost_per_image": 0.042,- "input_cost_per_pixel": 4.0054321e-08,- "input_cost_per_token": 0.000005,- "input_cost_per_image_token": 0.00001,+ "cache_read_input_image_token_cost": 2.5e-06,+ "cache_read_input_token_cost": 1.25e-06,+ "input_cost_per_image_token": 1e-05,+ "input_cost_per_token": 5e-06,"litellm_provider": "openai","mode": "image_generation",- "output_cost_per_pixel": 0.0,- "output_cost_per_token": 0.00004,+ "output_cost_per_image_token": 4e-05,"supported_endpoints": [- "/v1/images/generations"+ "/v1/images/generations",+ "/v1/images/edits"]},"gpt-image-1-mini": {diff --git a/tests/test_litellm/test_gpt_image_cost_calculator.py b/tests/test_litellm/test_gpt_image_cost_calculator.pynew file mode 100644index 00000000000..0a2a62b6c97--- /dev/null+++ b/tests/test_litellm/test_gpt_image_cost_calculator.py@@ -0,0 +1,239 @@+"""+Tests for OpenAI gpt-image-1 cost calculator++This tests the fix for GitHub issue #13847:+https://github.com/BerriAI/litellm/issues/13847++gpt-image-1 uses token-based pricing:+- Text Input: $5.00/1M tokens+- Image Input: $10.00/1M tokens+- Image Output: $40.00/1M tokens+"""++import os+import sys++sys.path.insert(0, os.path.abspath("../.."))++import pytest++import litellm+from litellm.types.utils import (+ ImageResponse,+ ImageObject,+ ImageUsage,+ ImageUsageInputTokensDetails,+)+++class TestGPTImageCostCalculator:+ """Test the OpenAI gpt-image-1 cost calculator"""++ def test_gpt_image_1_cost_with_text_only(self):+ """Test cost calculation with only text input tokens"""+ from litellm.llms.openai.image_generation.cost_calculator import cost_calculator++ usage = ImageUsage(+ input_tokens=100,+ output_tokens=5000,+ total_tokens=5100,+ input_tokens_details=ImageUsageInputTokensDetails(+ text_tokens=100,+ image_tokens=0,+ ),+ )++ image_response = ImageResponse(+ created=1234567890,+ data=[ImageObject(url="http://example.com/image.jpg")],+ )+ image_response.usage = usage++ cost = cost_calculator(+ model="gpt-image-1",+ image_response=image_response,+ custom_llm_provider="openai",+ )++ # Expected cost:+ # Text input: 100 * $5/1M = 0.0005+ # Image output: 5000 * $40/1M = 0.2+ # Total: 0.2005+ expected_cost = 0.0005 + 0.2+ assert abs(cost - expected_cost) < 1e-6, f"Expected {expected_cost}, got {cost}"++ def test_gpt_image_1_cost_with_image_input(self):+ """Test cost calculation with both text and image input tokens (for edits)"""+ from litellm.llms.openai.image_generation.cost_calculator import cost_calculator++ usage = ImageUsage(+ input_tokens=600,+ output_tokens=5000,+ total_tokens=5600,+ input_tokens_details=ImageUsageInputTokensDetails(+ text_tokens=100,+ image_tokens=500,+ ),+ )++ image_response = ImageResponse(+ created=1234567890,+ data=[ImageObject(url="http://example.com/image.jpg")],+ )+ image_response.usage = usage++ cost = cost_calculator(+ model="gpt-image-1",+ image_response=image_response,+ custom_llm_provider="openai",+ )++ # Expected cost:+ # Text input: 100 * $5/1M = 0.0005+ # Image input: 500 * $10/1M = 0.005+ # Image output: 5000 * $40/1M = 0.2+ # Total: 0.2055+ expected_cost = 0.0005 + 0.005 + 0.2+ assert abs(cost - expected_cost) < 1e-6, f"Expected {expected_cost}, got {cost}"++ def test_gpt_image_1_mini_cost(self):+ """Test cost calculation for gpt-image-1-mini model"""+ from litellm.llms.openai.image_generation.cost_calculator import cost_calculator++ usage = ImageUsage(+ input_tokens=100,+ output_tokens=5000,+ total_tokens=5100,+ input_tokens_details=ImageUsageInputTokensDetails(+ text_tokens=100,+ image_tokens=0,+ ),+ )++ image_response = ImageResponse(+ created=1234567890,+ data=[ImageObject(url="http://example.com/image.jpg")],+ )+ image_response.usage = usage++ cost = cost_calculator(+ model="gpt-image-1-mini",+ image_response=image_response,+ custom_llm_provider="openai",+ )++ # Expected cost for gpt-image-1-mini:+ # Text input: 100 * $2/1M = 0.0002+ # Image output: 5000 * $8/1M = 0.04+ # Total: 0.0402+ expected_cost = 0.0002 + 0.04+ assert abs(cost - expected_cost) < 1e-6, f"Expected {expected_cost}, got {cost}"++ def test_gpt_image_1_cost_no_usage(self):+ """Test that cost returns 0 when no usage data is available"""+ from litellm.llms.openai.image_generation.cost_calculator import cost_calculator++ image_response = ImageResponse(+ created=1234567890,+ data=[ImageObject(url="http://example.com/image.jpg")],+ )++ cost = cost_calculator(+ model="gpt-image-1",+ image_response=image_response,+ custom_llm_provider="openai",+ )++ assert cost == 0.0+++class TestGPTImageCostRouting:+ """Test that gpt-image models are properly routed to the token-based calculator"""++ def test_openai_gpt_image_routes_to_token_calculator(self):+ """Test that OpenAI gpt-image-1 routes to token-based calculator"""+ from litellm.litellm_core_utils.llm_cost_calc.utils import CostCalculatorUtils++ usage = ImageUsage(+ input_tokens=100,+ output_tokens=5000,+ total_tokens=5100,+ input_tokens_details=ImageUsageInputTokensDetails(+ text_tokens=100,+ image_tokens=0,+ ),+ )++ image_response = ImageResponse(+ created=1234567890,+ data=[ImageObject(url="http://example.com/image.jpg")],+ )+ image_response.usage = usage++ cost = CostCalculatorUtils.route_image_generation_cost_calculator(+ model="gpt-image-1",+ completion_response=image_response,+ custom_llm_provider="openai",+ )++ expected_cost = 0.0005 + 0.2+ assert abs(cost - expected_cost) < 1e-6, f"Expected {expected_cost}, got {cost}"++ def test_openai_dalle_routes_to_pixel_calculator(self):+ """Test that OpenAI DALL-E still routes to pixel-based calculator"""+ from litellm.litellm_core_utils.llm_cost_calc.utils import CostCalculatorUtils++ image_response = ImageResponse(+ created=1234567890,+ data=[ImageObject(url="http://example.com/image.jpg")],+ )+ image_response.size = "1024x1024"+ image_response.quality = "standard"++ cost = CostCalculatorUtils.route_image_generation_cost_calculator(+ model="dall-e-3",+ completion_response=image_response,+ custom_llm_provider="openai",+ size="1024x1024",+ quality="standard",+ n=1,+ )++ assert cost >= 0+++class TestCompletionCostIntegration:+ """Test the full completion_cost integration for gpt-image-1"""++ def test_completion_cost_gpt_image_1(self):+ """Test completion_cost correctly calculates gpt-image-1 costs"""+ usage = ImageUsage(+ input_tokens=100,+ output_tokens=5000,+ total_tokens=5100,+ input_tokens_details=ImageUsageInputTokensDetails(+ text_tokens=100,+ image_tokens=0,+ ),+ )++ image_response = ImageResponse(+ created=1234567890,+ data=[ImageObject(url="http://example.com/image.jpg")],+ )+ image_response.usage = usage+ image_response._hidden_params = {"custom_llm_provider": "openai"}++ cost = litellm.completion_cost(+ completion_response=image_response,+ model="gpt-image-1",+ call_type="image_generation",+ custom_llm_provider="openai",+ )++ expected_cost = 0.0005 + 0.2+ assert abs(cost - expected_cost) < 1e-6, f"Expected {expected_cost}, got {cost}"+++if __name__ == "__main__":+ pytest.main([__file__, "-v"])