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(proxy): fall back to the deployment model when a billed failure row's base_model is not in the cost map (#47568)
Kerry Lu97e5438ffba9
diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.pyindex d6dfd3ea359..b01f53c8c6b 100644--- a/litellm/proxy/utils.py+++ b/litellm/proxy/utils.py@@ -1200,32 +1200,47 @@ def _deployment_cost_per_token(deployment_id: str | None, model: str) -> CostPer)-def _estimated_input_cost(- model_call_details: Mapping[str, object],+def _priced_input_cost(+ pricing_model: str,+ custom_llm_provider: str | None,prompt_tokens: int,- deployment_id: str | None,- base_model: str | None,-) -> float:- """Input price for the estimated prompt: the deployment's registered rate when it has one, else- the cost map's rate for ``base_model`` or the deployment model (an Azure deployment name is not- in the cost map, its ``base_model`` is). An unpriceable model keeps the row at $0 rather than- dropping the failure row."""+ custom_cost_per_token: CostPerToken | None,+) -> float | None:try:- model: Final = str(model_call_details.get("model") or "")estimated_input_cost, _ = litellm.cost_per_token(- model=base_model or model,- custom_llm_provider=str(model_call_details.get("custom_llm_provider") or "") or None,+ model=pricing_model,+ custom_llm_provider=custom_llm_provider,prompt_tokens=prompt_tokens,- custom_cost_per_token=_deployment_cost_per_token(deployment_id, model),+ custom_cost_per_token=custom_cost_per_token,)except Exception as exc: # noqa: BLE001 # cost_per_token raises BadRequestError for an unmapped model and the row must still be written- verbose_proxy_logger.debug(- "failure spend estimate: could not price %s: %s", model_call_details.get("model"), exc- )- return 0.0+ verbose_proxy_logger.debug("failure spend estimate: could not price %s: %s", pricing_model, exc)+ return Nonereturn estimated_input_cost+def _estimated_input_cost(+ model_call_details: Mapping[str, object],+ prompt_tokens: int,+ deployment_id: str | None,+ base_model: str | None,+) -> float:+ """Input price for the estimated prompt: the deployment's registered rate when it has one, else+ the cost map's rate for ``base_model``, else the deployment model, the same candidate order+ ``completion_cost`` walks (an Azure deployment name is not in the cost map, its ``base_model``+ is; a ``base_model`` the cost map does not know falls through to the deployment model). A model+ no candidate can price keeps the row at $0 rather than dropping the failure row."""+ model: Final = str(model_call_details.get("model") or "")+ custom_llm_provider: Final = str(model_call_details.get("custom_llm_provider") or "") or None+ custom_cost_per_token: Final = _deployment_cost_per_token(deployment_id, model)+ pricing_models: Final = (base_model, model) if base_model is not None else (model,)+ candidate_costs: Final = (+ _priced_input_cost(pricing_model, custom_llm_provider, prompt_tokens, custom_cost_per_token)+ for pricing_model in pricing_models+ )+ return next((cost for cost in candidate_costs if cost is not None), 0.0)++_EMPTY_LIFT: Final = MappingProxyType({})diff --git a/tests/unit/proxy/test_proxy_utils_model_creation_and_error_logging.py b/tests/unit/proxy/test_proxy_utils_model_creation_and_error_logging.pyindex 5ab04724bc4..99cd569eb63 100644--- a/tests/unit/proxy/test_proxy_utils_model_creation_and_error_logging.py+++ b/tests/unit/proxy/test_proxy_utils_model_creation_and_error_logging.py@@ -1174,7 +1174,7 @@ from typing import castimport litellmfrom litellm.proxy.utils import create_model_info_responsefrom litellm.types.router import DeploymentModelListingInfo-from litellm.types.utils import ModelInfo+from litellm.types.utils import ModelInfo, ModelResponse, Usagedef _fake_model_info(**fields: object) -> ModelInfo:@@ -2337,6 +2337,34 @@ def test_an_azure_deployment_is_priced_at_its_base_model_like_the_success_path()assert lifted["response_cost"] == pytest.approx(expected_cost)+def test_an_unmapped_base_model_falls_back_to_the_deployment_model_like_the_success_path():+ """``completion_cost`` tries ``base_model`` first and then the deployment model, so a+ ``model_info.base_model`` the cost map does not know still prices a success row at the+ deployment model's rate. The failure row must land on the same number instead of $0."""+ from litellm.litellm_core_utils.get_litellm_params import get_litellm_params+ from litellm.proxy.utils import _failure_fields_to_lift++ logging_obj = _dispatched_failure_logging_obj(+ FAILURE_USAGE_MODEL,+ get_litellm_params(metadata={"model_info": {"base_model": "not-in-the-cost-map"}}),+ )+ logging_obj.model_call_details["custom_llm_provider"] = "openai"++ lifted = _failure_fields_to_lift({"litellm_logging_obj": logging_obj}, provider_billed=True)++ prompt_tokens = lifted["combined_usage_object"].prompt_tokens+ success_cost = litellm.completion_cost(+ completion_response=ModelResponse(+ model=FAILURE_USAGE_MODEL, usage=Usage(prompt_tokens=prompt_tokens, completion_tokens=0)+ ),+ model=FAILURE_USAGE_MODEL,+ custom_llm_provider="openai",+ base_model="not-in-the-cost-map",+ )+ assert success_cost > 0+ assert lifted["response_cost"] == pytest.approx(success_cost)++def test_a_litellm_params_key_in_the_request_body_cannot_zero_the_timeout_price():"""``model_call_details`` is flattened with the request's optional_params, so a body keynamed ``litellm_params`` can land there; the deployment rate must come from the logging