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: Anthropic model wildcard access issue
Sameer Kankute4ff1651699a4
diff --git a/litellm/__init__.py b/litellm/__init__.pyindex 97f36a9b00f..b44b99c91d9 100644--- a/litellm/__init__.py+++ b/litellm/__init__.py@@ -614,8 +614,9 @@ def is_openai_finetune_model(key: str) -> bool:return key.startswith("ft:") and not key.count(":") > 1-def add_known_models():- for key, value in model_cost.items():+def add_known_models(model_cost_map: Optional[Dict] = None):+ _map = model_cost_map if model_cost_map is not None else model_cost+ for key, value in _map.items():if value.get("litellm_provider") == "openai" and not is_openai_finetune_model(key):diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex c1181dd52c2..b196ca7e866 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -1,4 +1,3 @@-import anyioimport asyncioimport copyimport enum@@ -31,6 +30,7 @@ from typing import (get_type_hints,)+import anyiofrom pydantic import BaseModel, Jsonfrom litellm._uuid import uuid@@ -3598,9 +3598,6 @@ class ProxyConfig:parsed = valueelif isinstance(value, str):import json-- import yaml-try:parsed = yaml.safe_load(value)except (yaml.YAMLError, json.JSONDecodeError):@@ -4388,6 +4385,9 @@ class ProxyConfig:litellm.model_cost = new_model_cost_map# Invalidate case-insensitive lookup map since model_cost was replaced_invalidate_model_cost_lowercase_map()+ # Repopulate provider model sets (e.g. litellm.anthropic_models) so that+ # wildcard patterns like "anthropic/*" include any newly added models.+ litellm.add_known_models(model_cost_map=new_model_cost_map)# Update pod's in-memory last reload timelast_model_cost_map_reload = current_time.isoformat()@@ -11890,6 +11890,9 @@ async def reload_model_cost_map(litellm.model_cost = new_model_cost_map# Invalidate case-insensitive lookup map since model_cost was replaced_invalidate_model_cost_lowercase_map()+ # Repopulate provider model sets (e.g. litellm.anthropic_models) so that+ # wildcard patterns like "anthropic/*" include any newly added models.+ litellm.add_known_models(model_cost_map=new_model_cost_map)# Update pod's in-memory last reload timeglobal last_model_cost_map_reload@@ -12144,6 +12147,55 @@ async def get_model_cost_map_reload_status()+ "/model/cost_map/source",+ tags=["model management"],+ dependencies=[Depends(user_api_key_auth)],+ include_in_schema=False,+)+async def get_model_cost_map_source(+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),+):+ """+ ADMIN ONLY / MASTER KEY Only Endpoint++ Returns information about where the current model cost/pricing data was loaded from.++ Response fields:+ - source: "local" (bundled backup) or "remote" (fetched from URL)+ - url: the remote URL that was attempted (null when env-forced local)+ - is_env_forced: true if LITELLM_LOCAL_MODEL_COST_MAP=True forced local usage+ - fallback_reason: human-readable reason why remote failed (null on success)+ - model_count: number of models in the currently loaded cost map+ """+ if user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN:+ raise HTTPException(+ status_code=403,+ detail=f"Access denied. Admin role required. Current role: {user_api_key_dict.user_role}",+ )++ try:+ from litellm.litellm_core_utils.get_model_cost_map import (+ get_model_cost_map_source_info,+ )++ source_info = get_model_cost_map_source_info()+ model_count = len(litellm.model_cost) if litellm.model_cost else 0++ return {+ **source_info,+ "model_count": model_count,+ }+ except Exception as e:+ verbose_proxy_logger.exception(+ f"Failed to get model cost map source info: {str(e)}"+ )+ raise HTTPException(+ status_code=500,+ detail=f"Failed to get model cost map source info: {str(e)}",+ )++#### ANTHROPIC BETA HEADERS RELOAD ENDPOINTS ####diff --git a/tests/proxy_unit_tests/test_auth_checks.py b/tests/proxy_unit_tests/test_auth_checks.pyindex 5d63742c106..c92ec61b9b2 100644--- a/tests/proxy_unit_tests/test_auth_checks.py+++ b/tests/proxy_unit_tests/test_auth_checks.py@@ -261,6 +261,132 @@ async def test_can_key_call_model_wildcard_access(key_models, model, expect_to_wprint(e)+ "key_models, model, expect_to_work",+ [+ # After a cost-map reload, add_known_models() updates anthropic_models so+ # the anthropic/* wildcard can match a newly-added Anthropic model.+ (["anthropic/*"], "claude-brand-new-model-reload-test", True),+ # Wrong provider wildcard must still be denied even after reload.+ (["openai/*"], "claude-brand-new-model-reload-test", False),+ ],+)+async def test_wildcard_access_after_cost_map_reload(key_models, model, expect_to_work):+ """+ Regression test: after a cost-map hot-reload, calling+ add_known_models(model_cost_map=new_map) must update litellm.anthropic_models+ so that the anthropic/* wildcard correctly grants (or denies) access to+ newly-added models.++ Root cause: both reload paths in proxy_server.py only updated+ litellm.model_cost but never re-ran add_known_models(), so the provider sets+ stayed stale and wildcard matching failed for new models.++ Fix: each reload now calls litellm.add_known_models(model_cost_map=new_map)+ with the fetched map passed explicitly to avoid any reference ambiguity.+ """+ from litellm.proxy.auth.auth_checks import can_key_call_model++ # Build a new cost map that includes the brand-new model — exactly what+ # proxy_server.py receives from get_model_cost_map() during a reload.+ new_cost_map = dict(litellm.model_cost)+ new_cost_map[model] = {+ "litellm_provider": "anthropic",+ "max_tokens": 8192,+ "input_cost_per_token": 0.000003,+ "output_cost_per_token": 0.000015,+ }++ original_model_cost = litellm.model_cost+ litellm.model_cost = new_cost_map++ # Confirm the model is NOT yet in the provider set before reload propagation.+ assert model not in litellm.anthropic_models++ # Simulate what proxy_server.py now does after every reload.+ litellm.add_known_models(model_cost_map=new_cost_map)++ # After add_known_models(), the model must be in the set.+ assert model in litellm.anthropic_models++ llm_model_list = [+ {+ "model_name": "anthropic/*",+ "litellm_params": {"model": "anthropic/*", "api_key": "test-api-key"},+ "model_info": {"id": "test-id-anthropic-wildcard", "db_model": False},+ },+ {+ "model_name": "openai/*",+ "litellm_params": {"model": "openai/*", "api_key": "test-api-key"},+ "model_info": {"id": "test-id-openai-wildcard", "db_model": False},+ },+ ]+ router = litellm.Router(model_list=llm_model_list)+ user_api_key_object = UserAPIKeyAuth(models=key_models)++ try:+ if expect_to_work:+ await can_key_call_model(+ model=model,+ llm_model_list=llm_model_list,+ valid_token=user_api_key_object,+ llm_router=router,+ )+ else:+ with pytest.raises(Exception):+ await can_key_call_model(+ model=model,+ llm_model_list=llm_model_list,+ valid_token=user_api_key_object,+ llm_router=router,+ )+ finally:+ litellm.model_cost = original_model_cost+ litellm.anthropic_models.discard(model)+++async def test_add_known_models_explicit_map_updates_provider_sets():+ """+ Regression test: after a cost-map hot-reload, calling+ add_known_models(model_cost_map=new_map) with the new map passed explicitly+ must add any new provider models to the correct provider sets so that+ wildcard access checks (anthropic/*, openai/*, …) work immediately.++ This covers the proxy_server.py fix where both reload paths now call+ litellm.add_known_models(model_cost_map=new_model_cost_map) instead of+ relying on the module-level model_cost being up to date.+ """+ fake_new_model = "claude-brand-new-explicit-map-test"++ # Baseline: the model must not be in the sets before we do anything.+ assert fake_new_model not in litellm.anthropic_models++ new_cost_map = dict(litellm.model_cost)+ new_cost_map[fake_new_model] = {+ "litellm_provider": "anthropic",+ "max_tokens": 8192,+ "input_cost_per_token": 0.000003,+ "output_cost_per_token": 0.000015,+ }++ # Simulate what proxy_server.py does on reload.+ original_model_cost = litellm.model_cost+ litellm.model_cost = new_cost_map+ litellm.add_known_models(model_cost_map=new_cost_map)++ try:+ assert fake_new_model in litellm.anthropic_models, (+ "add_known_models(model_cost_map=...) did not add the new model to "+ "litellm.anthropic_models — wildcard access checks would fail."+ )+ finally:+ # Clean up: restore original state.+ litellm.model_cost = original_model_cost+ litellm.anthropic_models.discard(fake_new_model)++@pytest.mark.asyncioasync def test_is_valid_fallback_model():from litellm.proxy.auth.auth_checks import is_valid_fallback_model