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): count explicit zero prices on any billed metric as configured pricing
mateo-berri21891b44837b
diff --git a/litellm/proxy/auth/auth_checks.py b/litellm/proxy/auth/auth_checks.pyindex 5de3f9624aa..6f41fde4b88 100644--- a/litellm/proxy/auth/auth_checks.py+++ b/litellm/proxy/auth/auth_checks.py@@ -445,7 +445,9 @@ def _has_ptu_flat_cost(model: str, llm_router: "Router") -> bool:def _is_cost_explicitly_configured(model: str, llm_router: "Router") -> bool:"""Check if any deployment in the model group has cost fields explicitly- set in its litellm.model_cost entry.+ set in its litellm_params or its litellm.model_cost entry, on any billed+ metric. An explicit zero counts: pricing a model at 0 is a deliberate+ admin choice, distinct from a model missing from the cost map.When Router._create_deployment() registers a model not in the globalcost map, it creates a sparse entry like {"id": "<hash>"} with no cost@@ -455,6 +457,8 @@ def _is_cost_explicitly_configured(model: str, llm_router: "Router") -> bool:for deployment in llm_router.model_list:if deployment.get("model_name") != model:continue+ if _entry_has_explicit_cost_key(deployment.get("litellm_params") or _EMPTY_COST_ENTRY):+ return Truemodel_id = deployment.get("model_info", {}).get("id")if model_id is None:continue@@ -464,10 +468,20 @@ def _is_cost_explicitly_configured(model: str, llm_router: "Router") -> bool:return False+_EMPTY_COST_ENTRY: Final[Mapping[str, object]] = MappingProxyType({})++def _is_positive_cost(value: object) -> bool:return isinstance(value, (int, float)) and not isinstance(value, bool) and value > 0+def _entry_has_explicit_cost_key(entry: Mapping[str, object]) -> bool:+ return any(+ "cost_per" in key and isinstance(value, (int, float)) and not isinstance(value, bool)+ for key, value in entry.items()+ )++def _entry_has_priced_metric(entry: Mapping[str, object]) -> bool:for key, value in entry.items():if "cost_per" not in key:@@ -485,12 +499,12 @@ def _model_group_has_pricing(model: str, llm_router: "Router") -> bool:metric (tokens, characters, seconds, pages, images, queries, ...), so models thatare billed by a non-token metric are not treated as unpriced."""- for deployment in llm_router.get_model_list(model_name=model) or []:- litellm_params = deployment.get("litellm_params") or {}+ for deployment in llm_router.get_model_list(model_name=model) or ():+ litellm_params = deployment.get("litellm_params") or _EMPTY_COST_ENTRYif _entry_has_priced_metric(litellm_params):return True- model_id = (deployment.get("model_info") or {}).get("id")+ model_id = (deployment.get("model_info") or _EMPTY_COST_ENTRY).get("id")if model_id is None:continue@@ -503,7 +517,7 @@ def _model_group_has_pricing(model: str, llm_router: "Router") -> bool:return False-def model_has_no_cost_mapping(model: Optional[str], llm_router: Optional[Router]) -> bool:+def model_has_no_cost_mapping(model: str | None, llm_router: Router | None) -> bool:if not model or llm_router is None:return Falsediff --git a/litellm/proxy/management_endpoints/cost_tracking_settings.py b/litellm/proxy/management_endpoints/cost_tracking_settings.pyindex 444ffa434b3..842a6c54f33 100644--- a/litellm/proxy/management_endpoints/cost_tracking_settings.py+++ b/litellm/proxy/management_endpoints/cost_tracking_settings.py@@ -450,8 +450,8 @@ class BlockUnpricedModelsResponse(BaseModel):@router.get("/config/block_requests_for_models_without_pricing",- tags=["Cost Tracking"],- dependencies=[Depends(user_api_key_auth)],+ tags=("Cost Tracking",),+ dependencies=(Depends(user_api_key_auth),),response_model=BlockUnpricedModelsResponse,)async def get_block_requests_for_models_without_pricing() -> BlockUnpricedModelsResponse:@@ -460,8 +460,8 @@ async def get_block_requests_for_models_without_pricing() -> BlockUnpricedModels@router.patch("/config/block_requests_for_models_without_pricing",- tags=["Cost Tracking"],- dependencies=[Depends(user_api_key_auth)],+ tags=("Cost Tracking",),+ dependencies=(Depends(user_api_key_auth),),response_model=BlockUnpricedModelsResponse,)async def update_block_requests_for_models_without_pricing(@@ -476,19 +476,23 @@ async def update_block_requests_for_models_without_pricing(if prisma_client is None:raise HTTPException(status_code=500,- detail={"error": CommonProxyErrors.db_not_connected_error.value},+ detail={ # mutable-ok: HTTPException detail must be a plain mapping+ "error": CommonProxyErrors.db_not_connected_error.value+ },)if store_model_in_db is not True:raise HTTPException(status_code=500,- detail={"error": "Set `'STORE_MODEL_IN_DB='True'` in your env to enable this feature."},+ detail={ # mutable-ok: HTTPException detail must be a plain mapping+ "error": "Set `'STORE_MODEL_IN_DB='True'` in your env to enable this feature."+ },)try:config = await proxy_config.get_config()if "litellm_settings" not in config:- config["litellm_settings"] = {}+ config["litellm_settings"] = {} # mutable-ok: config is a plain-dict payload for save_configconfig["litellm_settings"]["block_requests_for_models_without_pricing"] = request.enabledawait proxy_config.save_config(new_config=config)@@ -496,11 +500,13 @@ async def update_block_requests_for_models_without_pricing(verbose_proxy_logger.info(f"Updated block_requests_for_models_without_pricing: {request.enabled}")return BlockUnpricedModelsResponse(enabled=request.enabled)- except Exception as e:- verbose_proxy_logger.error(f"Error updating block_requests_for_models_without_pricing: {str(e)}")+ except Exception as e: # noqa: BLE001 # any config persistence failure must surface as a 500 response, not a crash+ verbose_proxy_logger.error(f"Error updating block_requests_for_models_without_pricing: {e!s}")raise HTTPException(status_code=500,- detail={"error": f"Failed to update setting: {str(e)}"},+ detail={ # mutable-ok: HTTPException detail must be a plain mapping+ "error": f"Failed to update setting: {e!s}"+ },)diff --git a/tests/test_litellm/proxy/auth/test_auth_checks.py b/tests/test_litellm/proxy/auth/test_auth_checks.pyindex ce633699748..11a982472a8 100644--- a/tests/test_litellm/proxy/auth/test_auth_checks.py+++ b/tests/test_litellm/proxy/auth/test_auth_checks.py@@ -6646,6 +6646,27 @@ def test_model_has_no_cost_mapping_non_token_price_from_litellm_params_is_false(assert model_has_no_cost_mapping(model="custom-tts", llm_router=router) is False[email protected]("zero_cost_key", ["input_cost_per_second", "input_cost_per_token"])+def test_model_has_no_cost_mapping_explicit_zero_price_is_false(zero_cost_key):+ from litellm.proxy.auth.auth_checks import model_has_no_cost_mapping+ from litellm.router import Router++ router = Router(+ model_list=[+ {+ "model_name": "free-group",+ "litellm_params": {+ "model": UNPRICED_UNDERLYING_MODEL,+ "api_key": "sk-test",+ zero_cost_key: 0.0,+ },+ }+ ]+ )++ assert model_has_no_cost_mapping(model="free-group", llm_router=router) is False++async def _run_common_checks(model: Optional[str], llm_router: Optional["Router"], route: str = "/chat/completions") -> bool: