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
Litellm dev 04 30 2025 p1 (#10462)
Krish Dholakia6ad483dde711
diff --git a/litellm/cost_calculator.py b/litellm/cost_calculator.pyindex 1320d49123d..f7c13827d6b 100644--- a/litellm/cost_calculator.py+++ b/litellm/cost_calculator.py@@ -19,6 +19,7 @@ from litellm.litellm_core_utils.llm_cost_calc.tool_call_cost_tracking import (from litellm.litellm_core_utils.llm_cost_calc.utils import (_generic_cost_per_character,generic_cost_per_token,+ select_cost_metric_for_model,)from litellm.llms.anthropic.cost_calculation import (cost_per_token as anthropic_cost_per_token,@@ -226,34 +227,50 @@ def cost_per_token( # noqa: PLR0915# see this https://learn.microsoft.com/en-us/azure/ai-services/openai/concepts/modelsif call_type == "speech" or call_type == "aspeech":- if prompt_characters is None:- raise ValueError(- "prompt_characters must be provided for tts calls. prompt_characters={}, model={}, custom_llm_provider={}, call_type={}".format(- prompt_characters,- model,- custom_llm_provider,- call_type,+ speech_model_info = litellm.get_model_info(+ model=model_without_prefix, custom_llm_provider=custom_llm_provider+ )+ cost_metric = select_cost_metric_for_model(speech_model_info)+ prompt_cost: float = 0.0+ completion_cost: float = 0.0+ if cost_metric == "cost_per_character":+ if prompt_characters is None:+ raise ValueError(+ "prompt_characters must be provided for tts calls. prompt_characters={}, model={}, custom_llm_provider={}, call_type={}".format(+ prompt_characters,+ model,+ custom_llm_provider,+ call_type,+ ))+ _prompt_cost, _completion_cost = _generic_cost_per_character(+ model=model_without_prefix,+ custom_llm_provider=custom_llm_provider,+ prompt_characters=prompt_characters,+ completion_characters=0,+ custom_prompt_cost=None,+ custom_completion_cost=0,)- prompt_cost, completion_cost = _generic_cost_per_character(- model=model_without_prefix,- custom_llm_provider=custom_llm_provider,- prompt_characters=prompt_characters,- completion_characters=0,- custom_prompt_cost=None,- custom_completion_cost=0,- )- if prompt_cost is None or completion_cost is None:- raise ValueError(- "cost for tts call is None. prompt_cost={}, completion_cost={}, model={}, custom_llm_provider={}, prompt_characters={}, completion_characters={}".format(- prompt_cost,- completion_cost,- model_without_prefix,- custom_llm_provider,- prompt_characters,- completion_characters,+ if _prompt_cost is None or _completion_cost is None:+ raise ValueError(+ "cost for tts call is None. prompt_cost={}, completion_cost={}, model={}, custom_llm_provider={}, prompt_characters={}, completion_characters={}".format(+ _prompt_cost,+ _completion_cost,+ model_without_prefix,+ custom_llm_provider,+ prompt_characters,+ completion_characters,+ ))+ prompt_cost = _prompt_cost+ completion_cost = _completion_cost+ elif cost_metric == "cost_per_token":+ prompt_cost, completion_cost = generic_cost_per_token(+ model=model_without_prefix,+ usage=usage_block,+ custom_llm_provider=custom_llm_provider,)+return prompt_cost, completion_costelif call_type == "arerank" or call_type == "rerank":return rerank_cost(@@ -644,9 +661,9 @@ def completion_cost( # noqa: PLR0915or isinstance(completion_response, dict)): # tts returns a custom classif isinstance(completion_response, dict):- usage_obj: Optional[Union[dict, Usage]] = (- completion_response.get("usage", {})- )+ usage_obj: Optional[+ Union[dict, Usage]+ ] = completion_response.get("usage", {})else:usage_obj = getattr(completion_response, "usage", {})if isinstance(usage_obj, BaseModel) and not _is_known_usage_objects(diff --git a/litellm/exceptions.py b/litellm/exceptions.pyindex 6a927f07126..3cdc70b08aa 100644--- a/litellm/exceptions.py+++ b/litellm/exceptions.py@@ -203,6 +203,7 @@ class Timeout(openai.APITimeoutError): # type: ignoremax_retries: Optional[int] = None,num_retries: Optional[int] = None,headers: Optional[dict] = None,+ exception_status_code: Optional[int] = None,):request = httpx.Request(method="POST",@@ -211,7 +212,7 @@ class Timeout(openai.APITimeoutError): # type: ignoresuper().__init__(request=request) # Call the base class constructor with the parameters it needs- self.status_code = 408+ self.status_code = exception_status_code or 408self.message = "litellm.Timeout: {}".format(message)self.model = modelself.llm_provider = llm_providerdiff --git a/litellm/litellm_core_utils/exception_mapping_utils.py b/litellm/litellm_core_utils/exception_mapping_utils.pyindex 7578019dfff..e567c7daad8 100644--- a/litellm/litellm_core_utils/exception_mapping_utils.py+++ b/litellm/litellm_core_utils/exception_mapping_utils.py@@ -452,6 +452,7 @@ def exception_type( # type: ignore # noqa: PLR0915model=model,llm_provider=custom_llm_provider,litellm_debug_info=extra_information,+ exception_status_code=original_exception.status_code,)else:exception_mapping_worked = True@@ -804,6 +805,7 @@ def exception_type( # type: ignore # noqa: PLR0915model=model,llm_provider=custom_llm_provider,litellm_debug_info=extra_information,+ exception_status_code=original_exception.status_code,)elif custom_llm_provider == "bedrock":if (@@ -975,6 +977,7 @@ def exception_type( # type: ignore # noqa: PLR0915model=model,llm_provider=custom_llm_provider,litellm_debug_info=extra_information,+ exception_status_code=original_exception.status_code,)elif (custom_llm_provider == "sagemaker"@@ -1093,6 +1096,7 @@ def exception_type( # type: ignore # noqa: PLR0915model=model,llm_provider=custom_llm_provider,litellm_debug_info=extra_information,+ exception_status_code=original_exception.status_code,)elif (custom_llm_provider == "vertex_ai"@@ -1307,6 +1311,7 @@ def exception_type( # type: ignore # noqa: PLR0915message=f"GeminiException - {original_exception.message}",model=model,llm_provider="palm",+ exception_status_code=original_exception.status_code,)if "400 Request payload size exceeds" in error_str:exception_mapping_worked = True@@ -2050,6 +2055,7 @@ def exception_type( # type: ignore # noqa: PLR0915model=model,litellm_debug_info=extra_information,llm_provider="azure",+ exception_status_code=original_exception.status_code,)else:exception_mapping_worked = True@@ -2144,6 +2150,7 @@ def exception_type( # type: ignore # noqa: PLR0915model=model,llm_provider=custom_llm_provider,litellm_debug_info=extra_information,+ exception_status_code=original_exception.status_code,)else:exception_mapping_worked = Truediff --git a/litellm/litellm_core_utils/llm_cost_calc/utils.py b/litellm/litellm_core_utils/llm_cost_calc/utils.pyindex 48809fe856a..616d1a3db94 100644--- a/litellm/litellm_core_utils/llm_cost_calc/utils.py+++ b/litellm/litellm_core_utils/llm_cost_calc/utils.py@@ -1,7 +1,7 @@# What is this?## Helper utilities for cost_per_token()-from typing import Optional, Tuple, cast+from typing import Literal, Optional, Tuple, castimport litellmfrom litellm import verbose_logger@@ -15,6 +15,23 @@ def _is_above_128k(tokens: float) -> bool:return False+def select_cost_metric_for_model(+ model_info: ModelInfo,+) -> Literal["cost_per_character", "cost_per_token"]:+ """+ Select 'cost_per_character' if model_info has 'input_cost_per_character'+ Select 'cost_per_token' if model_info has 'input_cost_per_token'+ """+ if model_info.get("input_cost_per_character"):+ return "cost_per_character"+ elif model_info.get("input_cost_per_token"):+ return "cost_per_token"+ else:+ raise ValueError(+ f"Model {model_info['key']} does not have 'input_cost_per_character' or 'input_cost_per_token'"+ )++def _generic_cost_per_character(model: str,custom_llm_provider: str,diff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.jsonindex cd9e4c484ec..21cb055669a 100644--- a/litellm/model_prices_and_context_window_backup.json+++ b/litellm/model_prices_and_context_window_backup.json@@ -1567,6 +1567,17 @@"litellm_provider": "openai","supported_endpoints": ["/v1/audio/speech"]},+ "gpt-4o-mini-tts": {+ "mode": "audio_speech",+ "input_cost_per_token": 2.5e-6,+ "output_cost_per_token": 10e-6,+ "output_cost_per_audio_token": 12e-6,+ "output_cost_per_second": 0.00025,+ "litellm_provider": "openai",+ "supported_modalities": ["text", "audio"],+ "supported_output_modalities": ["audio"],+ "supported_endpoints": ["/v1/audio/speech"]+ },"azure/computer-use-preview": {"max_tokens": 1024,"max_input_tokens": 8192,diff --git a/litellm/proxy/_new_secret_config.yaml b/litellm/proxy/_new_secret_config.yamlindex 631dbee6257..c0e6776b8ad 100644--- a/litellm/proxy/_new_secret_config.yaml+++ b/litellm/proxy/_new_secret_config.yaml@@ -1,4 +1,8 @@model_list:+ - model_name: gpt-4o-mini-tts+ litellm_params:+ model: openai/gpt-4o-mini-tts+ api_key: os.environ/OPENAI_API_KEY- model_name: gpt-3.5-turbolitellm_params:model: azure/chatgpt-v-3diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.jsonindex cd9e4c484ec..21cb055669a 100644--- a/model_prices_and_context_window.json+++ b/model_prices_and_context_window.json@@ -1567,6 +1567,17 @@"litellm_provider": "openai","supported_endpoints": ["/v1/audio/speech"]},+ "gpt-4o-mini-tts": {+ "mode": "audio_speech",+ "input_cost_per_token": 2.5e-6,+ "output_cost_per_token": 10e-6,+ "output_cost_per_audio_token": 12e-6,+ "output_cost_per_second": 0.00025,+ "litellm_provider": "openai",+ "supported_modalities": ["text", "audio"],+ "supported_output_modalities": ["audio"],+ "supported_endpoints": ["/v1/audio/speech"]+ },"azure/computer-use-preview": {"max_tokens": 1024,"max_input_tokens": 8192,diff --git a/tests/local_testing/test_completion_cost.py b/tests/local_testing/test_completion_cost.pyindex 011672b04d3..e72009f636f 100644--- a/tests/local_testing/test_completion_cost.py+++ b/tests/local_testing/test_completion_cost.py@@ -949,7 +949,7 @@ def test_vertex_ai_mistral_predict_cost(usage):assert predictive_cost > 0[email protected]("model", ["openai/tts-1", "azure/tts-1"])[email protected]("model", ["openai/tts-1", "azure/tts-1", "openai/gpt-4o-mini-tts"])def test_completion_cost_tts(model):os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"litellm.model_cost = litellm.get_model_cost_map(url="")diff --git a/tests/local_testing/test_custom_callback_router.py b/tests/local_testing/test_custom_callback_router.pyindex 83289abf5fe..17b37dca5ca 100644--- a/tests/local_testing/test_custom_callback_router.py+++ b/tests/local_testing/test_custom_callback_router.py@@ -394,7 +394,7 @@ async def test_async_chat_azure():{"model_name": "gpt-3.5-turbo", # openai model name"litellm_params": { # params for litellm completion/embedding call- "model": "azure/chatgpt-v-3",+ "model": "azure/gpt-4o-new-test","api_key": os.getenv("AZURE_API_KEY"),"api_version": os.getenv("AZURE_API_VERSION"),"api_base": os.getenv("AZURE_API_BASE"),@@ -438,7 +438,7 @@ async def test_async_chat_azure():{"model_name": "gpt-3.5-turbo", # openai model name"litellm_params": { # params for litellm completion/embedding call- "model": "azure/chatgpt-v-3",+ "model": "azure/gpt-4o-new-test","api_key": "my-bad-key","api_version": os.getenv("AZURE_API_VERSION"),"api_base": os.getenv("AZURE_API_BASE"),diff --git a/tests/local_testing/test_exceptions.py b/tests/local_testing/test_exceptions.pyindex be7710f58aa..f4b0b4b6403 100644--- a/tests/local_testing/test_exceptions.py+++ b/tests/local_testing/test_exceptions.py@@ -1047,6 +1047,57 @@ async def test_exception_with_headers(sync_mode, provider, model, call_type, strassert exception_raised+def test_openai_gateway_timeout_error():+ """+ Test that the OpenAI gateway timeout error is raised+ """+ openai_client = OpenAI()+ mapped_target = openai_client.chat.completions.with_raw_response # type: ignore+ def _return_exception(*args, **kwargs):+ import datetime++ from httpx import Headers, Request, Response++ kwargs = {+ "request": Request("POST", "https://www.google.com"),+ "message": "Error code: 504 - Gateway Timeout Error!",+ "body": {"detail": "Gateway Timeout Error!"},+ "code": None,+ "param": None,+ "type": None,+ "response": Response(+ status_code=504,+ headers=Headers(+ {+ "date": "Sat, 21 Sep 2024 22:56:53 GMT",+ "server": "uvicorn",+ "content-length": "30",+ "content-type": "application/json",+ }+ ),+ request=Request("POST", "http://0.0.0.0:9000/chat/completions"),+ ),+ "status_code": 504,+ "request_id": None,+ }++ exception = Exception()+ for k, v in kwargs.items():+ setattr(exception, k, v)+ raise exception++ try:+ with patch.object(+ mapped_target,+ "create",+ side_effect=_return_exception,+ ):+ litellm.completion(model="openai/gpt-3.5-turbo", messages=[{"role": "user", "content": "Hello world"}], client=openai_client)+ pytest.fail("Expected to raise Timeout")+ except litellm.Timeout as e:+ assert e.status_code == 504++@pytest.mark.parametrize("sync_mode",[True, False],