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
feat(proxy): add admin toggle to block requests for models without pricing
mateo7e1f44f0cc15
diff --git a/litellm/__init__.py b/litellm/__init__.pyindex 3f8c742c5a2..d14f41ad49c 100644--- a/litellm/__init__.py+++ b/litellm/__init__.py@@ -443,6 +443,7 @@ max_end_user_budget_id: Optional[str] = None# backwards compatibility — arbitrary client-supplied identifiers still# pass through unchanged.validate_end_user_id_in_db: bool = False+block_requests_for_models_without_pricing: bool = Falsedisable_end_user_cost_tracking: Optional[bool] = Nonedisable_end_user_cost_tracking_prometheus_only: Optional[bool] = Noneenable_end_user_cost_tracking_prometheus_only: Optional[bool] = Nonediff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.pyindex c6d4ee1120a..450868edf06 100644--- a/litellm/proxy/_types.py+++ b/litellm/proxy/_types.py@@ -3540,6 +3540,8 @@ class ProxyErrorTypes(str, enum.Enum):Project does not have access to the model"""+ model_cost_map_missing = "model_cost_map_missing"+expired_key = "expired_key""""Key has expireddiff --git a/litellm/proxy/auth/auth_checks.py b/litellm/proxy/auth/auth_checks.pyindex c46bc110ca8..11a45e78410 100644--- a/litellm/proxy/auth/auth_checks.py+++ b/litellm/proxy/auth/auth_checks.py@@ -274,6 +274,22 @@ def _is_cost_explicitly_configured(model: str, llm_router: "Router") -> bool: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++ model_group_info = llm_router.get_model_group_info(model_group=model)+ if model_group_info is None:+ return False++ input_cost = model_group_info.input_cost_per_token or 0+ output_cost = model_group_info.output_cost_per_token or 0+ if input_cost > 0 or output_cost > 0:+ 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]]],@@ -534,6 +550,23 @@ async def common_checks(if route in MODEL_DISCOVERY_ROUTES:skip_budget_checks = True+ 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 --git a/litellm/proxy/management_endpoints/cost_tracking_settings.py b/litellm/proxy/management_endpoints/cost_tracking_settings.pyindex cd2c5704778..2c18de6b903 100644--- a/litellm/proxy/management_endpoints/cost_tracking_settings.py+++ b/litellm/proxy/management_endpoints/cost_tracking_settings.py@@ -13,6 +13,7 @@ POST /cost/estimate - Estimate cost for a given model and token countsfrom typing import Dict, Optional, Tuple, Unionfrom fastapi import APIRouter, Depends, HTTPException+from pydantic import BaseModelimport litellmfrom litellm._logging import verbose_proxy_logger@@ -407,6 +408,70 @@ async def update_cost_margin_config()+class BlockUnpricedModelsRequest(BaseModel):+ enabled: bool+++class BlockUnpricedModelsResponse(BaseModel):+ enabled: bool+++ "/config/block_requests_for_models_without_pricing",+ tags=["Cost Tracking"],+ dependencies=[Depends(user_api_key_auth)],+ response_model=BlockUnpricedModelsResponse,+)+async def get_block_requests_for_models_without_pricing() -> BlockUnpricedModelsResponse:+ return BlockUnpricedModelsResponse(enabled=bool(litellm.block_requests_for_models_without_pricing))+++ "/config/block_requests_for_models_without_pricing",+ tags=["Cost Tracking"],+ dependencies=[Depends(user_api_key_auth)],+ response_model=BlockUnpricedModelsResponse,+)+async def update_block_requests_for_models_without_pricing(+ request: BlockUnpricedModelsRequest,+) -> BlockUnpricedModelsResponse:+ from litellm.proxy.proxy_server import (+ prisma_client,+ proxy_config,+ store_model_in_db,+ )++ if prisma_client is None:+ raise HTTPException(+ status_code=500,+ detail={"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."},+ )++ try:+ config = await proxy_config.get_config()+ if "litellm_settings" not in config:+ config["litellm_settings"] = {}+ config["litellm_settings"]["block_requests_for_models_without_pricing"] = request.enabled+ await proxy_config.save_config(new_config=config)++ litellm.block_requests_for_models_without_pricing = request.enabled+ 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)}")+ raise HTTPException(+ status_code=500,+ detail={"error": f"Failed to update setting: {str(e)}"},+ )++@router.post("/cost/estimate",tags=["Cost Tracking"],diff --git a/tests/test_litellm/proxy/auth/test_auth_checks.py b/tests/test_litellm/proxy/auth/test_auth_checks.pyindex 34a353966bf..aec0ddc55f8 100644--- a/tests/test_litellm/proxy/auth/test_auth_checks.py+++ b/tests/test_litellm/proxy/auth/test_auth_checks.py@@ -2,6 +2,7 @@ import asyncioimport jsonimport osimport sys+from typing import Optionalfrom unittest.mock import AsyncMock, MagicMock, patchsys.path.insert(@@ -5164,4 +5165,140 @@ async def test_get_project_object_db_fetch_returns_cached_obj():assert isinstance(result, LiteLLM_ProjectTableCachedObj)assert result.project_id == "p-1"- assert result.project_alias == "proj"+++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+++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 --git a/tests/test_litellm/proxy/management_endpoints/test_cost_tracking_settings.py b/tests/test_litellm/proxy/management_endpoints/test_cost_tracking_settings.pyindex bc463d5e75d..4fb90e9fb2d 100644--- a/tests/test_litellm/proxy/management_endpoints/test_cost_tracking_settings.py+++ b/tests/test_litellm/proxy/management_endpoints/test_cost_tracking_settings.py@@ -500,3 +500,59 @@ class TestResolveModelForCostLookup: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++ @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 --git 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.tsxindex b32e7afd756..f6a3d487ade 100644--- 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@@ -12,7 +12,7 @@ import {TabPanels,TabPanel,} from "@tremor/react";-import { Modal, Form } from "antd";+import { Modal, Form, Switch } from "antd";import { CostTrackingSettingsProps } from "./types";import ProviderDiscountTable from "./provider_discount_table";import AddProviderForm from "./add_provider_form";@@ -24,6 +24,7 @@ import { DocsMenu } from "@/components/HelpLink";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";const DOCS_LINKS = [@@ -65,9 +66,16 @@ const CostTrackingSettings: React.FC<CostTrackingSettingsProps> = ({ userID, usehandleMarginChange,} = useMarginConfig({ accessToken });+ const {+ blockUnpriced,+ isUpdating: isUpdatingBlockUnpriced,+ fetchBlockUnpriced,+ setBlockUnpriced,+ } = useBlockUnpricedConfig({ accessToken });+useEffect(() => {if (accessToken) {- Promise.all([fetchDiscountConfig(), fetchMarginConfig()]).finally(() => {+ Promise.all([fetchDiscountConfig(), fetchMarginConfig(), fetchBlockUnpriced()]).finally(() => {setIsFetching(false);});@@ -82,7 +90,7 @@ const CostTrackingSettings: React.FC<CostTrackingSettingsProps> = ({ userID, use};loadModels();}- }, [accessToken, fetchDiscountConfig, fetchMarginConfig]);+ }, [accessToken, fetchDiscountConfig, fetchMarginConfig, fetchBlockUnpriced]);const handleAddProvider = async () => {const success = await addProvider(selectedProvider, newDiscount);@@ -293,7 +301,38 @@ const CostTrackingSettings: React.FC<CostTrackingSettingsProps> = ({ userID, use</Accordion>)}- {/* Accordion 3: Pricing Calculator - Available to all roles */}+ {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">+ <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">+ 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>+ </div>+ <Switch+ checked={blockUnpriced}+ loading={isUpdatingBlockUnpriced || isFetching}+ onChange={(checked) => setBlockUnpriced(checked)}+ />+ </div>+ </div>+ </AccordionBody>+ </Accordion>+ )}++ {/* 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">diff --git 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.tsnew file mode 100644index 00000000000..f4a110c7878--- /dev/null+++ b/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/use_block_unpriced_config.ts@@ -0,0 +1,63 @@+import { useState, useCallback } from "react";+import { apiClient } from "@/components/networking";+import NotificationsManager from "@/components/molecules/notifications_manager";++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(+ 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 --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.tsindex ed975c6be0a..5abe3b4d587 100644--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts@@ -1844,6 +1844,24 @@ export interface paths {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;@@ -21247,6 +21265,16 @@ export interface components {/** Team Id */team_id: string;};+ /** BlockUnpricedModelsRequest */+ BlockUnpricedModelsRequest: {+ /** Enabled */+ enabled: boolean;+ };+ /** BlockUnpricedModelsResponse */+ BlockUnpricedModelsResponse: {+ /** Enabled */+ enabled: boolean;+ };/** BlockUsers */BlockUsers: {/** User Ids */@@ -37097,6 +37125,59 @@ export interface operations {};};};+ 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;