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
Merge remote-tracking branch 'origin/litellm_internal_staging' into litellm_block_unpriced_models
github-actions[bot]6bd21fad704a
diff --cc litellm/proxy/auth/auth_checks.pyindex 3639ef245cf,8708f96339f..5de3f9624aa--- a/litellm/proxy/auth/auth_checks.py+++ b/litellm/proxy/auth/auth_checks.py@@@ -285,64 -464,12 +464,64 @@@ def _is_cost_explicitly_configured(modereturn False+def _is_positive_cost(value: object) -> bool:+ return isinstance(value, (int, float)) and not isinstance(value, bool) and value > 0+++def _entry_has_priced_metric(entry: Mapping[str, object]) -> bool:+ for key, value in entry.items():+ if "cost_per" not in key:+ continue+ if _is_positive_cost(value):+ return True+ if isinstance(value, dict) and any(_is_positive_cost(nested) for nested in value.values()):+ return True+ return False+++def _model_group_has_pricing(model: str, llm_router: "Router") -> bool:+ """+ Check every deployment behind a model group for a positive price on any billed+ metric (tokens, characters, seconds, pages, images, queries, ...), so models that+ are 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 {}+ if _entry_has_priced_metric(litellm_params):+ return True++ model_id = (deployment.get("model_info") or {}).get("id")+ if model_id is None:+ continue++ model_info = llm_router.get_deployment_model_info(+ model_id=model_id, model_name=litellm_params.get("model") or ""+ )+ if model_info is not None and _entry_has_priced_metric(model_info):+ return True++ return False+++def model_has_no_cost_mapping(model: Optional[str], llm_router: Optional[Router]) -> bool:+ if not model or llm_router is None:+ return False++ if llm_router.get_model_group_info(model_group=model) is None:+ return False++ if _model_group_has_pricing(model=model, llm_router=llm_router):+ return False++ return not _is_cost_explicitly_configured(model, llm_router)++async def _run_project_checks(- project_object: Optional[LiteLLM_ProjectTableCachedObj],- _model: Optional[Union[str, List[str]]],- llm_router: Optional[Router],+ project_object: LiteLLM_ProjectTableCachedObj | None,+ _model: str | list[str] | None,+ llm_router: Router | None,skip_budget_checks: bool,- valid_token: Optional[UserAPIKeyAuth],+ valid_token: UserAPIKeyAuth | None,proxy_logging_obj: ProxyLogging,) -> None:"""@@@ -594,26 -729,11 +781,28 @@@ async def common_checksrequest=request,)- if route in MODEL_DISCOVERY_ROUTES:- skip_budget_checks = True+ skip_all_budget_checks: Final = skip_budget_checks or (+ route not in BUDGET_ENFORCED_SIDE_EFFECT_ROUTES+ and (route in MODEL_DISCOVERY_ROUTES or not RouteChecks.is_llm_api_route(route=route))+ )+ if (+ litellm.block_requests_for_models_without_pricing+ and isinstance(_model, str)+ and RouteChecks.is_llm_api_route(route=route)+ and model_has_no_cost_mapping(model=_model, llm_router=llm_router)+ ):+ raise ProxyException(+ message=(+ f"Model '{_model}' has no pricing in the cost map, so its spend would be tracked as $0. "+ "Requests for unpriced models are blocked because 'block_requests_for_models_without_pricing' "+ "is enabled. Add pricing for this model (input_cost_per_token/output_cost_per_token) to allow it."+ ),+ type=ProxyErrorTypes.model_cost_map_missing,+ param="model",+ code=status.HTTP_403_FORBIDDEN,+ )+# 1. If team is blockedif team_object is not None and team_object.blocked is True:raise Exception(f"Team={team_object.team_id} is blocked. Update via `/team/unblock` if you're an admin.")diff --cc litellm/proxy/management_endpoints/cost_tracking_settings.pyindex 2c18de6b903,56439172b63..444ffa434b3--- a/litellm/proxy/management_endpoints/cost_tracking_settings.py+++ b/litellm/proxy/management_endpoints/cost_tracking_settings.py@@@ -10,10 -10,11 +10,12 @@@ PATCH /config/cost_margin_config - UpdaPOST /cost/estimate - Estimate cost for a given model and token counts"""- from typing import Dict, Optional, Tuple, Union+ from collections.abc import Mapping+ from dataclasses import dataclass+ from typing import Finalfrom fastapi import APIRouter, Depends, HTTPException+from pydantic import BaseModelimport litellmfrom litellm._logging import verbose_proxy_loggerdiff --cc tests/test_litellm/proxy/auth/test_auth_checks.pyindex a078e041aa7,1d1bd9ebf8a..ce633699748--- a/tests/test_litellm/proxy/auth/test_auth_checks.py+++ b/tests/test_litellm/proxy/auth/test_auth_checks.py@@@ -2,7 -2,7 +2,8 @@@ import asynciimport jsonimport osimport sys+ from types import SimpleNamespace+from typing import Optionalfrom unittest.mock import AsyncMock, MagicMock, patchsys.path.insert(@@@ -13,7 -13,7 +14,7 @@@ from datetime import datetime, timedeltimport httpximport pytest--from fastapi import status++from fastapi import Request, statusimport litellmfrom litellm.proxy._types import (@@@ -2149,11 -2760,11 +2761,9 @@@ async def test_common_checks_metadata_rassert "metadata" not in request_body--def _pass_through_request() -> "Request":++def _pass_through_request() -> Request:"""A Request whose FastAPI-resolved endpoint carries the pass-through marker,i.e. the request was dispatched to a user-defined pass-through handler."""-- from fastapi import Request--from litellm.types.passthrough_endpoints.pass_through_endpoints import (LITELLM_PASS_THROUGH_ENDPOINT_MARKER,)@@@ -2165,10 -2776,10 +2775,9 @@@return Request(scope={"type": "http", "headers": [], "endpoint": pass_through_endpoint})--def _builtin_request() -> "Request":++def _builtin_request() -> Request:"""A Request dispatched to a built-in (non-pass-through) handler, e.g. what acustom path colliding with a core route actually resolves to."""-- from fastapi import Requestdef chat_completions():...@@@ -5168,182 -6315,245 +6313,426 @@@ async def test_get_project_object_db_feassert result.project_alias == "proj"+ @pytest.mark.asyncio+ async def test_project_allowlist_enforced_when_key_models_empty():+ """+ LIT-3803: a project-bound key with models=[] has no key-level restriction,+ but the project allowlist must still 403 team models outside it.+ """+ from litellm.proxy._types import (+ LiteLLM_ProjectTableCachedObj,+ ProxyErrorTypes,+ ProxyException,+ )+ from litellm.proxy.auth.auth_checks import _run_project_checks, can_key_call_model++ valid_token = UserAPIKeyAuth(+ api_key="hashed-key",+ project_id="p-1",+ team_id="t-1",+ models=[],+ )+ project = LiteLLM_ProjectTableCachedObj(+ project_id="p-1",+ team_id="t-1",+ models=["gemini-2.5-flash-image", "gemini-3.1-flash-lite-preview"],+ )++ assert (+ await can_key_call_model(+ model="gemini-2.5-flash",+ llm_model_list=None,+ valid_token=valid_token,+ llm_router=None,+ )+ is True+ )++ await _run_project_checks(+ project_object=project,+ _model="gemini-2.5-flash-image",+ llm_router=None,+ skip_budget_checks=True,+ valid_token=valid_token,+ proxy_logging_obj=MagicMock(),+ )++ with pytest.raises(ProxyException) as exc_info:+ await _run_project_checks(+ project_object=project,+ _model="gemini-2.5-flash",+ llm_router=None,+ skip_budget_checks=True,+ valid_token=valid_token,+ proxy_logging_obj=MagicMock(),+ )+ assert exc_info.value.type == ProxyErrorTypes.project_model_access_denied+ assert exc_info.value.code == "403"+++ def test_is_user_proxy_admin_rejects_view_only_admin():+ """This predicate skips `non_proxy_admin_allowed_routes_check` entirely, so an+ Admin Viewer answering True here would gain every write route. Read parity for+ that role belongs in the route checks, never here."""+ from litellm.proxy.auth.auth_checks import _is_user_proxy_admin++ viewer = LiteLLM_UserTable(+ user_id="viewer_user",+ user_email="[email protected]",+ user_role=LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY.value,+ )+ admin = LiteLLM_UserTable(+ user_id="admin_user",+ user_email="[email protected]",+ user_role=LitellmUserRoles.PROXY_ADMIN.value,+ )++ assert _is_user_proxy_admin(user_obj=viewer) is False+ assert _is_user_proxy_admin(user_obj=admin) is True+ assert _is_user_proxy_admin(user_obj=None) is False+++ def _make_wildcard_access_group_router():+ """+ `openai/*` tagged into an access group, plus an untagged `azure/*`, mirroring a+ proxy that fronts a whole provider behind one wildcard deployment.+ """+ from litellm import Router++ return Router(+ model_list=[+ {+ "model_name": "openai/*",+ "litellm_params": {"model": "openai/*", "api_key": "fake"},+ "model_info": {+ "id": "wildcard-openai",+ "access_groups": ["default-models"],+ },+ },+ {+ "model_name": "azure/*",+ "litellm_params": {"model": "azure/*", "api_key": "fake"},+ "model_info": {"id": "wildcard-azure"},+ },+ ]+ )+++ def test_can_object_call_model_access_group_wildcard_accepts_bare_model_name():+ """+ Regression: a key holding only the access group name was denied for `gpt-4o`+ while `openai/gpt-4o` was allowed, because group membership resolved through the+ pattern router's raw regex and skipped the `{provider}/{model}` retry that both+ routing and the direct-wildcard grant already perform.+ """+ from litellm.proxy.auth.auth_checks import _can_object_call_model++ router = _make_wildcard_access_group_router()++ assert (+ _can_object_call_model(+ model="gpt-4o",+ llm_router=router,+ models=["default-models"],+ object_type="key",+ )+ is True+ )+++ def test_can_object_call_model_access_group_wildcard_accepts_prefixed_model_name():+ from litellm.proxy.auth.auth_checks import _can_object_call_model++ router = _make_wildcard_access_group_router()++ assert (+ _can_object_call_model(+ model="openai/gpt-4o",+ llm_router=router,+ models=["default-models"],+ object_type="key",+ )+ is True+ )+++ @pytest.mark.parametrize(+ "model",+ [+ "totally-made-up-model-zzz", # no provider can be inferred+ "azure/some-deployment", # wildcard exists but carries no access group+ ],+ )+ def test_can_object_call_model_access_group_wildcard_does_not_over_grant(model):+ """The bare-name retry must not turn an access group into a blanket grant."""+ from litellm.proxy._types import ProxyException+ from litellm.proxy.auth.auth_checks import _can_object_call_model++ router = _make_wildcard_access_group_router()++ with pytest.raises(ProxyException):+ _can_object_call_model(+ model=model,+ llm_router=router,+ models=["default-models"],+ object_type="key",+ )+++ def test_can_object_call_model_access_group_rejects_unconsumed_namespace():+ """+ `bedrockz/...` infers provider `bedrock` from a fragment of the name, so+ re-prefixing would smuggle an unrecognized namespace through a `bedrock/*` group.+ """+ from litellm import Router+ from litellm.proxy._types import ProxyException+ from litellm.proxy.auth.auth_checks import _can_object_call_model++ router = Router(+ model_list=[+ {+ "model_name": "bedrock/*",+ "litellm_params": {"model": "bedrock/*"},+ "model_info": {+ "id": "wildcard-bedrock",+ "access_groups": ["bedrock-models"],+ },+ }+ ]+ )++ assert (+ _can_object_call_model(+ model="anthropic.claude-3-5-sonnet-20240620-v1:0",+ llm_router=router,+ models=["bedrock-models"],+ object_type="key",+ )+ is True+ )++ with pytest.raises(ProxyException):+ _can_object_call_model(+ model="bedrockz/anthropic.claude-3-5-sonnet-20240620-v1:0",+ llm_router=router,+ models=["bedrock-models"],+ object_type="key",+ )+++ def test_can_object_call_model_team_scoped_wildcard_accepts_bare_model_name():+ """+ Same regression as the proxy-wide wildcard, but for a team-scoped deployment+ whose public name is a wildcard: those live in a separate per-team pattern+ index that needed the same `{provider}/{model}` retry.+ """+ from litellm import Router+ from litellm.proxy.auth.auth_checks import _can_object_call_model++ router = Router(+ model_list=[+ {+ "model_name": "openai/*_team-a_abc",+ "litellm_params": {"model": "openai/*", "api_key": "fake"},+ "model_info": {+ "id": "team-byok-wildcard",+ "team_id": "team-a",+ "team_public_model_name": "openai/*",+ "access_groups": ["team-models"],+ },+ }+ ]+ )++ for model in ("gpt-4o", "openai/gpt-4o"):+ assert (+ _can_object_call_model(+ model=model,+ llm_router=router,+ models=["team-models"],+ object_type="team",+ team_id="team-a",+ )+ is True+ )+++++UNPRICED_UNDERLYING_MODEL = "openai/unpriced-model-lit4984-xyz"+++def _router_with_priced_and_unpriced_models() -> "Router":+ from litellm.router import Router++ return Router(+ model_list=[+ {+ "model_name": "priced-group",+ "litellm_params": {"model": "gpt-3.5-turbo", "api_key": "sk-test"},+ },+ {+ "model_name": "unpriced-group",+ "litellm_params": {"model": UNPRICED_UNDERLYING_MODEL, "api_key": "sk-test"},+ },+ ]+ )+++def test_model_has_no_cost_mapping_priced_model_is_false():+ from litellm.proxy.auth.auth_checks import model_has_no_cost_mapping++ router = _router_with_priced_and_unpriced_models()++ assert model_has_no_cost_mapping(model="priced-group", llm_router=router) is False+++def test_model_has_no_cost_mapping_unpriced_model_is_true():+ from litellm.proxy.auth.auth_checks import model_has_no_cost_mapping++ router = _router_with_priced_and_unpriced_models()++ assert model_has_no_cost_mapping(model="unpriced-group", llm_router=router) is True+++def test_model_has_no_cost_mapping_no_model_or_router_is_false():+ from litellm.proxy.auth.auth_checks import model_has_no_cost_mapping++ router = _router_with_priced_and_unpriced_models()++ assert model_has_no_cost_mapping(model=None, llm_router=router) is False+ assert model_has_no_cost_mapping(model="unpriced-group", llm_router=None) is False+++ "underlying_model",+ [+ "azure/speech/azure-tts",+ "mistral/mistral-ocr-latest",+ "vertex_ai/imagen-3.0-generate-001",+ ],+)+def test_model_has_no_cost_mapping_non_token_priced_model_is_false(underlying_model):+ from litellm.proxy.auth.auth_checks import model_has_no_cost_mapping+ from litellm.router import Router++ router = Router(+ model_list=[+ {+ "model_name": "non-token-priced-group",+ "litellm_params": {"model": underlying_model, "api_key": "sk-test"},+ }+ ]+ )++ assert model_has_no_cost_mapping(model="non-token-priced-group", llm_router=router) is False+++def test_model_has_no_cost_mapping_non_token_price_from_litellm_params_is_false():+ from litellm.proxy.auth.auth_checks import model_has_no_cost_mapping+ from litellm.router import Router++ router = Router(+ model_list=[+ {+ "model_name": "custom-tts",+ "litellm_params": {+ "model": UNPRICED_UNDERLYING_MODEL,+ "api_key": "sk-test",+ "input_cost_per_second": 0.0001,+ },+ }+ ]+ )++ assert model_has_no_cost_mapping(model="custom-tts", llm_router=router) is False+++async def _run_common_checks(+ model: Optional[str], llm_router: Optional["Router"], route: str = "/chat/completions"+) -> bool:+ from fastapi import Request++ from litellm.proxy.auth.auth_checks import common_checks++ return await common_checks(+ request_body={"model": model, "messages": [{"role": "user", "content": "hi"}]},+ team_object=None,+ user_object=None,+ end_user_object=None,+ global_proxy_spend=None,+ general_settings={},+ route=route,+ llm_router=llm_router,+ proxy_logging_obj=MagicMock(),+ valid_token=UserAPIKeyAuth(token="test-token"),+ request=MagicMock(spec=Request),+ )+++async def test_common_checks_blocks_unpriced_model_when_enabled(monkeypatch):+ monkeypatch.setattr(litellm, "block_requests_for_models_without_pricing", True)+ router = _router_with_priced_and_unpriced_models()++ with pytest.raises(ProxyException) as exc_info:+ await _run_common_checks(model="unpriced-group", llm_router=router)++ assert exc_info.value.code == "403"+ assert exc_info.value.type == ProxyErrorTypes.model_cost_map_missing+ assert exc_info.value.param == "model"+ assert "unpriced-group" in exc_info.value.message+ assert "pricing" in exc_info.value.message.lower()+++async def test_common_checks_allows_unpriced_model_when_disabled(monkeypatch):+ monkeypatch.setattr(litellm, "block_requests_for_models_without_pricing", False)+ router = _router_with_priced_and_unpriced_models()++ result = await _run_common_checks(model="unpriced-group", llm_router=router)++ assert result is True+++async def test_common_checks_allows_priced_model_when_enabled(monkeypatch):+ monkeypatch.setattr(litellm, "block_requests_for_models_without_pricing", True)+ router = _router_with_priced_and_unpriced_models()++ result = await _run_common_checks(model="priced-group", llm_router=router)++ assert result is True+++async def test_common_checks_ignores_non_llm_route_when_enabled(monkeypatch):+ monkeypatch.setattr(litellm, "block_requests_for_models_without_pricing", True)+ router = _router_with_priced_and_unpriced_models()++ result = await _run_common_checks(+ model="unpriced-group", llm_router=router, route="/model/new"+ )++ assert result is True+++async def test_common_checks_blocks_alias_resolving_to_unpriced_model(monkeypatch):+ from litellm.router import Router++ monkeypatch.setattr(litellm, "block_requests_for_models_without_pricing", True)+ router = Router(+ model_list=[+ {+ "model_name": "billed-underlying-group",+ "litellm_params": {"model": UNPRICED_UNDERLYING_MODEL, "api_key": "sk-test"},+ }+ ],+ model_group_alias={"public-alias": "billed-underlying-group"},+ )++ with pytest.raises(ProxyException) as exc_info:+ await _run_common_checks(model="public-alias", llm_router=router)++ assert exc_info.value.code == "403"+ assert exc_info.value.type == ProxyErrorTypes.model_cost_map_missing+ assert "public-alias" in exc_info.value.messagediff --cc tests/test_litellm/proxy/management_endpoints/test_cost_tracking_settings.pyindex 1124a4a31d4,7e83180bfcd..ff80bbe4938--- a/tests/test_litellm/proxy/management_endpoints/test_cost_tracking_settings.py+++ b/tests/test_litellm/proxy/management_endpoints/test_cost_tracking_settings.py@@@ -496,77 -494,192 +494,264 @@@ class TestResolveModelForCostLookup]with patch("litellm.proxy.proxy_server.llm_router", mock_router):- resolved_model, provider = _resolve_model_for_cost_lookup("gpt-4")+ resolved = _resolve_model_for_cost_lookup("gpt-4")++ assert resolved.model == "openai/gpt-4"+ assert resolved.provider is None+++ class TestEstimateCostOnPremProvider:+ """Regression tests for LIT-5210: /cost/estimate on on-prem deployment aliases."""++ @pytest.mark.asyncio+ async def test_estimate_cost_onprem_model_without_pricing(self):+ """+ On-prem deployments (custom_llm_provider set, model absent from the cost map)+ must not 500 with "LLM Provider NOT provided". The resolved provider has to be+ forwarded to completion_cost so provider inference doesn't run on the bare model.++ completion_cost is intentionally NOT mocked.+ """+ from litellm.proxy._types import CostEstimateRequest+ from litellm.proxy.management_endpoints.cost_tracking_settings import (+ estimate_cost,+ )++ request = CostEstimateRequest(+ model="nvidia/zai-org/glm-5.2",+ input_tokens=1000,+ output_tokens=500,+ )++ mock_router = MagicMock()+ mock_router.get_model_list.return_value = [+ {+ "model_name": "nvidia/zai-org/glm-5.2",+ "litellm_params": {+ "model": "zai-org/GLM-5.2",+ "custom_llm_provider": "openai",+ },+ "model_info": {},+ }+ ]++ saved_model_cost = dict(litellm.model_cost)+ litellm.register_model(+ {+ "openai/zai-org/GLM-5.2": {+ "input_cost_per_token": 0.0,+ "output_cost_per_token": 0.0,+ "litellm_provider": "openai",+ "mode": "chat",+ }+ }+ )+ try:+ with patch("litellm.proxy.proxy_server.llm_router", mock_router):+ response = await estimate_cost(request=request, user_api_key_dict=MagicMock())+ finally:+ litellm.model_cost = saved_model_cost++ assert response.model == "nvidia/zai-org/glm-5.2"+ assert response.provider == "openai"+ assert response.cost_per_request == 0.0++ @pytest.mark.asyncio+ async def test_estimate_cost_onprem_model_with_configured_pricing(self):+ """+ On-prem deployments with input/output_cost_per_token configured must estimate a+ real cost using that pricing, not fall back to 0.0.++ completion_cost is intentionally NOT mocked.+ """+ from litellm.proxy._types import CostEstimateRequest+ from litellm.proxy.management_endpoints.cost_tracking_settings import (+ estimate_cost,+ )++ request = CostEstimateRequest(+ model="nvidia/zai-org/glm-5.2",+ input_tokens=1000,+ output_tokens=500,+ num_requests_per_day=100,+ )++ mock_router = MagicMock()+ mock_router.get_model_list.return_value = [+ {+ "model_name": "nvidia/zai-org/glm-5.2",+ "litellm_params": {+ "model": "zai-org/GLM-5.2",+ "custom_llm_provider": "openai",+ "input_cost_per_token": 0.000001,+ "output_cost_per_token": 0.000002,+ },+ "model_info": {},+ }+ ]++ with patch("litellm.proxy.proxy_server.llm_router", mock_router):+ response = await estimate_cost(request=request, user_api_key_dict=MagicMock())++ assert response.provider == "openai"+ assert response.cost_per_request == pytest.approx(0.002)+ assert response.input_cost_per_request == pytest.approx(0.001)+ assert response.output_cost_per_request == pytest.approx(0.001)+ assert response.daily_cost == pytest.approx(0.2)+ assert response.input_cost_per_token == pytest.approx(0.000001)+ assert response.output_cost_per_token == pytest.approx(0.000002)++ @pytest.mark.asyncio+ async def test_estimate_cost_onprem_model_with_model_info_pricing(self):+ """+ Custom pricing configured under model_info (how DB / Admin UI added+ deployments store it) must be honored, not just litellm_params pricing.++ completion_cost is intentionally NOT mocked.+ """+ from litellm.proxy._types import CostEstimateRequest+ from litellm.proxy.management_endpoints.cost_tracking_settings import (+ estimate_cost,+ )++ request = CostEstimateRequest(+ model="nvidia/zai-org/glm-5.2",+ input_tokens=1000,+ output_tokens=500,+ )++ mock_router = MagicMock()+ mock_router.get_model_list.return_value = [+ {+ "model_name": "nvidia/zai-org/glm-5.2",+ "litellm_params": {+ "model": "zai-org/GLM-5.2",+ "custom_llm_provider": "openai",+ },+ "model_info": {+ "input_cost_per_token": 0.000003,+ "output_cost_per_token": 0.000004,+ },+ }+ ]++ with patch("litellm.proxy.proxy_server.llm_router", mock_router):+ response = await estimate_cost(request=request, user_api_key_dict=MagicMock())++ assert response.provider == "openai"+ assert response.cost_per_request == pytest.approx(0.005)+ assert response.input_cost_per_token == pytest.approx(0.000003)+ assert response.output_cost_per_token == pytest.approx(0.000004)++ @pytest.mark.asyncio+ async def test_estimate_cost_litellm_params_pricing_overrides_model_info(self):+ """+ When pricing is set in both places, litellm_params wins, matching the+ router's cost-map registration precedence.+ """+ from litellm.proxy._types import CostEstimateRequest+ from litellm.proxy.management_endpoints.cost_tracking_settings import (+ estimate_cost,+ )++ request = CostEstimateRequest(+ model="nvidia/zai-org/glm-5.2",+ input_tokens=1000,+ output_tokens=500,+ )++ mock_router = MagicMock()+ mock_router.get_model_list.return_value = [+ {+ "model_name": "nvidia/zai-org/glm-5.2",+ "litellm_params": {+ "model": "zai-org/GLM-5.2",+ "custom_llm_provider": "openai",+ "input_cost_per_token": 0.000001,+ "output_cost_per_token": 0.000002,+ },+ "model_info": {+ "input_cost_per_token": 0.000003,+ "output_cost_per_token": 0.000004,+ },+ }+ ]++ with patch("litellm.proxy.proxy_server.llm_router", mock_router):+ response = await estimate_cost(request=request, user_api_key_dict=MagicMock())++ assert response.cost_per_request == pytest.approx(0.002)+ assert response.input_cost_per_token == pytest.approx(0.000001)+ assert response.output_cost_per_token == pytest.approx(0.000002)+++- assert resolved_model == "openai/gpt-4"- assert provider is None+++class TestBlockRequestsForModelsWithoutPricing:+ """Test suite for the block_requests_for_models_without_pricing toggle endpoints"""++ @pytest.mark.asyncio+ async def test_get_reflects_in_memory_flag(self):+ with patch.object(litellm, "block_requests_for_models_without_pricing", True):+ response = client.get(+ "/config/block_requests_for_models_without_pricing",+ headers={"Authorization": "Bearer sk-1234"},+ )++ assert response.status_code == 200+ assert response.json() == {"enabled": True}++ @pytest.mark.asyncio+ async def test_patch_persists_and_updates_flag(self):+ mock_proxy_config = AsyncMock()+ mock_proxy_config.get_config = AsyncMock(return_value={"litellm_settings": {}})+ mock_proxy_config.save_config = AsyncMock()++ with (+ patch("litellm.proxy.proxy_server.prisma_client", MagicMock()),+ patch("litellm.proxy.proxy_server.proxy_config", mock_proxy_config),+ patch("litellm.proxy.proxy_server.store_model_in_db", True),+ patch.object(litellm, "block_requests_for_models_without_pricing", False),+ ):+ response = client.patch(+ "/config/block_requests_for_models_without_pricing",+ headers={"Authorization": "Bearer sk-1234"},+ json={"enabled": True},+ )++ assert response.status_code == 200+ assert response.json() == {"enabled": True}+ assert litellm.block_requests_for_models_without_pricing is True++ saved_config = mock_proxy_config.save_config.call_args.kwargs["new_config"]+ assert saved_config["litellm_settings"]["block_requests_for_models_without_pricing"] is True++ def test_peer_workers_pick_up_persisted_flag_on_config_reload(self):+ """A PATCH only mutates the flag on the worker that served it; peer workers must pick the+ persisted value up when they reload litellm_settings from the DB."""+ from litellm.proxy.proxy_server import ProxyConfig++ with patch.object(litellm, "block_requests_for_models_without_pricing", False):+ ProxyConfig()._update_config_fields(+ current_config={},+ param_name="litellm_settings",+ db_param_value={"block_requests_for_models_without_pricing": True},+ )++ assert litellm.block_requests_for_models_without_pricing is True++ @pytest.mark.asyncio+ async def test_patch_requires_store_model_in_db(self):+ with (+ patch("litellm.proxy.proxy_server.prisma_client", MagicMock()),+ patch("litellm.proxy.proxy_server.proxy_config", AsyncMock()),+ patch("litellm.proxy.proxy_server.store_model_in_db", False),+ ):+ response = client.patch(+ "/config/block_requests_for_models_without_pricing",+ headers={"Authorization": "Bearer sk-1234"},+ json={"enabled": True},+ )++ assert response.status_code == 500+ assert "error" in response.json()["detail"]diff --cc ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/cost_tracking_settings.tsxindex f6a3d487ade,3fce928ed67..52b66edcbe5--- a/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/cost_tracking_settings.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/cost_tracking_settings.tsx@@@ -1,18 -1,17 +1,18 @@@import React, { useState, useEffect } from "react";+ import { ChevronDown } from "lucide-react";import {- Title,- Text,- Button,- Accordion,- AccordionHeader,- AccordionBody,- TabGroup,- TabList,- Tab,- TabPanels,- TabPanel,- } from "@tremor/react";- import { Modal, Form, Switch } from "antd";+ AlertDialog,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+ } from "@/components/ui/alert-dialog";+ import { Button } from "@/components/ui/button";+ import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";++import { Switch } from "@/components/ui/switch";+ import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";import { CostTrackingSettingsProps } from "./types";import ProviderDiscountTable from "./provider_discount_table";import AddProviderForm from "./add_provider_form";@@@ -24,8 -22,8 +23,9 @@@ import { DocsMenu } from "@/components/import HowItWorks from "./how_it_works";import { useDiscountConfig } from "./use_discount_config";import { useMarginConfig } from "./use_margin_config";+import { useBlockUnpricedConfig } from "./use_block_unpriced_config";import { fetchAvailableModels, ModelGroup } from "@/components/llm_calls/fetch_models";+ import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";const DOCS_LINKS = [{ label: "Custom pricing for models", href: "https://docs.litellm.ai/docs/proxy/custom_pricing" },@@@ -297,52 -297,17 +306,45 @@@ const CostTrackingSettings: React.FC<Co</div>)}</div>- </AccordionBody>- </Accordion>+ </CollapsibleContent>+ </Collapsible>)}- {/* Accordion 3: Pricing Calculator - Available to all roles */}++ {/* Accordion 3: Block Unpriced Models - Only for proxy admins */}+ {isProxyAdmin && (- <Accordion>- <AccordionHeader className="px-6 py-4">- <div className="flex flex-col items-start w-full">- <Text className="text-lg font-semibold text-gray-900">Block Unpriced Models</Text>- <Text className="text-sm text-gray-500 mt-1">- Reject requests for models that have no pricing in the cost map instead of logging them as $0 spend- </Text>- </div>- </AccordionHeader>- <AccordionBody className="px-0">++ <Collapsible className="rounded-lg border">++ <SectionHeader++ title="Block Unpriced Models"++ description="Reject requests for models that have no pricing in the cost map instead of logging them as $0 spend"++ />++ <CollapsibleContent className="px-0">+ <div className="p-6">+ <div className="flex items-center justify-between">+ <div className="pr-6">- <Text className="text-gray-900 font-medium">Block requests for models without pricing</Text>- <Text className="text-sm text-gray-500 mt-1">++ <p className="text-foreground font-medium">Block requests for models without pricing</p>++ <p className="text-sm text-muted-foreground mt-1">+ When enabled, a request whose resolved model has no cost mapping is rejected with a 403 so an+ admin can add pricing for it. Off by default- </Text>++ </p>+ </div>+ <Switch+ checked={blockUnpriced}- loading={isUpdatingBlockUnpriced || isFetching}- onChange={(checked) => setBlockUnpriced(checked)}++ disabled={isUpdatingBlockUnpriced || isFetching}++ onCheckedChange={(checked) => setBlockUnpriced(checked)}+ />+ </div>+ </div>- </AccordionBody>- </Accordion>++ </CollapsibleContent>++ </Collapsible>+ )}++ {/* Accordion 4: Pricing Calculator - Available to all roles */}- <Accordion defaultOpen={true}>- <AccordionHeader className="px-6 py-4">- <div className="flex flex-col items-start w-full">- <Text className="text-lg font-semibold text-gray-900">Pricing Calculator</Text>- <Text className="text-sm text-gray-500 mt-1">- Estimate LLM costs based on expected token usage and request volume- </Text>- </div>- </AccordionHeader>- <AccordionBody className="px-0">+ <Collapsible defaultOpen={true} className="rounded-lg border">+ <SectionHeader+ title="Pricing Calculator"+ description="Estimate LLM costs based on expected token usage and request volume"+ />+ <CollapsibleContent className="px-0"><div className="p-6"><PricingCalculator accessToken={accessToken} models={models} /></div>diff --cc ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/use_block_unpriced_config.tsindex f4a110c7878,00000000000..5383f7350admode 100644,000000..100644--- a/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/use_block_unpriced_config.ts+++ b/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/use_block_unpriced_config.ts@@@ -1,63 -1,0 +1,63 @@@+import { useState, useCallback } from "react";+import { apiClient } from "@/components/networking";- import NotificationsManager from "@/components/molecules/notifications_manager";++import { toast } from "@/lib/toast";++export interface UseBlockUnpricedConfigProps {+ accessToken: string | null;+}++export interface UseBlockUnpricedConfigReturn {+ blockUnpriced: boolean;+ isUpdating: boolean;+ fetchBlockUnpriced: () => Promise<void>;+ setBlockUnpriced: (enabled: boolean) => Promise<void>;+}++interface BlockUnpricedResponse {+ enabled: boolean;+}++const ENDPOINT = "/config/block_requests_for_models_without_pricing";++export function useBlockUnpricedConfig({ accessToken }: UseBlockUnpricedConfigProps): UseBlockUnpricedConfigReturn {+ const [blockUnpriced, setBlockUnpricedState] = useState<boolean>(false);+ const [isUpdating, setIsUpdating] = useState<boolean>(false);++ const fetchBlockUnpriced = useCallback(async () => {+ if (!accessToken) return;+ try {+ const data = await apiClient.get<BlockUnpricedResponse>(ENDPOINT, { accessToken });+ setBlockUnpricedState(Boolean(data?.enabled));+ } catch (error) {+ console.error("Error fetching block-unpriced-models setting:", error);+ }+ }, [accessToken]);++ const setBlockUnpriced = useCallback(+ async (enabled: boolean) => {+ if (!accessToken) return;+ setIsUpdating(true);+ try {+ const data = await apiClient.patch<BlockUnpricedResponse>(ENDPOINT, { accessToken, body: { enabled } });+ setBlockUnpricedState(Boolean(data?.enabled));- NotificationsManager.success(++ toast.success(+ enabled+ ? "Requests for models without pricing will now be blocked"+ : "Requests for models without pricing are now allowed",+ );+ } catch (error) {+ console.error("Error updating block-unpriced-models setting:", error);+ } finally {+ setIsUpdating(false);+ }+ },+ [accessToken],+ );++ return {+ blockUnpriced,+ isUpdating,+ fetchBlockUnpriced,+ setBlockUnpriced,+ };+}diff --cc ui/litellm-dashboard/src/lib/http/schema.d.tsindex 5abe3b4d587,790ebcdd227..ba20f75f4c4--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts@@@ -1844,24 -2096,55 +2096,73 @@@ export interface pathspatch?: never;trace?: never;};+ "/comprehendmedical": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ get?: never;+ put?: never;+ /**+ * Comprehend Medical Sdk Proxy Route+ * @description AWS-SDK-shaped pass-through for Amazon Comprehend Medical: point the SDK's+ * `endpoint_url` at `/comprehendmedical` and the operation is read from the+ * `X-Amz-Target` header, per the AWS JSON 1.1 protocol.+ *+ * [Docs](https://docs.litellm.ai/docs/pass_through/comprehend_medical)+ */+ post: operations["comprehend_medical_sdk_proxy_route_comprehendmedical_post"];+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };+ "/comprehendmedical/{operation}": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ get?: never;+ put?: never;+ /**+ * Comprehend Medical Proxy Route+ * @description Pass-through for Amazon Comprehend Medical, e.g. `POST /comprehendmedical/DetectEntitiesV2`.+ *+ * The request body is forwarded as-is to the AWS JSON 1.1 API and signed with SigV4+ * using the proxy's AWS credentials.+ *+ * [Docs](https://docs.litellm.ai/docs/pass_through/comprehend_medical)+ */+ post: operations["comprehend_medical_proxy_route_comprehendmedical__operation__post"];+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };+ "/config/block_requests_for_models_without_pricing": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ /** Get Block Requests For Models Without Pricing */+ get: operations["get_block_requests_for_models_without_pricing_config_block_requests_for_models_without_pricing_get"];+ put?: never;+ post?: never;+ delete?: never;+ options?: never;+ head?: never;+ /** Update Block Requests For Models Without Pricing */+ patch: operations["update_block_requests_for_models_without_pricing_config_block_requests_for_models_without_pricing_patch"];+ trace?: never;+ };"/config/callback/delete": {parameters: {query?: never;@@@ -37125,59 -40106,57 +40134,110 @@@ export interface operations};};};+ comprehend_medical_sdk_proxy_route_comprehendmedical_post: {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ requestBody?: never;+ responses: {+ /** @description Successful Response */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": unknown;+ };+ };+ };+ };+ comprehend_medical_proxy_route_comprehendmedical__operation__post: {+ parameters: {+ query?: never;+ header?: never;+ path: {+ operation: string;+ };+ cookie?: never;+ };+ requestBody?: never;+ responses: {+ /** @description Successful Response */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": unknown;+ };+ };+ /** @description Validation Error */+ 422: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["HTTPValidationError"];+ };+ };+ };+ };+ get_block_requests_for_models_without_pricing_config_block_requests_for_models_without_pricing_get: {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ requestBody?: never;+ responses: {+ /** @description Successful Response */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["BlockUnpricedModelsResponse"];+ };+ };+ };+ };+ update_block_requests_for_models_without_pricing_config_block_requests_for_models_without_pricing_patch: {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ requestBody: {+ content: {+ "application/json": components["schemas"]["BlockUnpricedModelsRequest"];+ };+ };+ responses: {+ /** @description Successful Response */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["BlockUnpricedModelsResponse"];+ };+ };+ /** @description Validation Error */+ 422: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["HTTPValidationError"];+ };+ };+ };+ };delete_callback_config_callback_delete_post: {parameters: {query?: never;