Skip to content

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]

fix(proxy): match partial wildcards against prefix-stripped model ids (#46390)

Mrunmayee Daware219694319505
diff --git a/litellm/proxy/auth/model_checks.py b/litellm/proxy/auth/model_checks.py
index 8a7b6dab419..c4c538083ee 100644
--- a/litellm/proxy/auth/model_checks.py
+++ b/litellm/proxy/auth/model_checks.py
@@ -1,16 +1,21 @@
# What is this?
## Common checks for /v1/models and `/model/info`
import copy
-from collections.abc import Sequence
+import functools
+import itertools
+import re
+from collections.abc import Callable, Mapping, Sequence
from typing import Final
import litellm
from litellm._logging import verbose_proxy_logger
from litellm.litellm_core_utils.credential_accessor import CredentialAccessor
+from litellm.llms.azure.ptu_capacity import is_str_keyed_mapping
from litellm.proxy._types import SpecialModelNames, UserAPIKeyAuth
from litellm.repositories.object_permission_repository import ObjectPermissionRepository
from litellm.router import Router
from litellm.router_utils.fallback_event_handlers import get_fallback_model_group
+from litellm.router_utils.pattern_match_deployments import PatternMatchRouter
from litellm.types.router import CredentialLiteLLMParams, LiteLLM_Params
from litellm.types.utils import LlmProviders
from litellm.utils import ProviderConfigManager, get_valid_models
@@ -269,7 +274,136 @@ def _hydrate_litellm_credential_name(
return litellm_params
-def get_known_models_from_wildcard(wildcard_model: str, litellm_params: LiteLLM_Params | None = None) -> list[str]:
+def _is_routing_segment(
+ segment: str, provider: str, name_segments: frozenset[str], provider_model_ids: tuple[str, ...]
+) -> bool:
+ return (
+ "*" not in segment
+ and segment != provider
+ and segment not in name_segments
+ and not any(model_id.startswith(f"{segment}/") for model_id in provider_model_ids)
+ )
+
+
+def _without_routing_segments(
+ model_pattern: str, provider: str, name_pattern: str, provider_model_ids: tuple[str, ...]
+) -> str:
+ segments: Final = model_pattern.split("/")
+ name_segments: Final = frozenset(name_pattern.split("/")[1:])
+ routing_segments: Final = tuple(
+ itertools.takewhile(
+ lambda segment: _is_routing_segment(segment, provider, name_segments, provider_model_ids), segments[:-1]
+ )
+ )
+ return "/".join(segments[len(routing_segments) :])
+
+
+def _lists_name_fragments(name_pattern: str, deployment_pattern: str) -> bool:
+ deployment_partial_word: Final = deployment_pattern.partition("*")[0].rpartition("/")[2]
+ name_partial_word: Final = name_pattern.partition("*")[0].rpartition("/")[2]
+ return deployment_partial_word[-1:].isalnum() and not name_partial_word
+
+
+def _routes_back_to(
+ listed_id: str,
+ name_regex: re.Pattern[str],
+ catalog_route: tuple[str, str],
+ deployment_pattern: str,
+ routes_to_model: Callable[[str, str], bool],
+) -> bool:
+ name_match: Final = name_regex.match(listed_id)
+ catalog_pattern, catalog_id = catalog_route
+ return (
+ name_match is not None
+ and PatternMatchRouter.set_deployment_model_name(
+ matched_pattern=name_match, litellm_deployment_litellm_model=catalog_pattern
+ )
+ == catalog_id
+ and routes_to_model(
+ listed_id,
+ PatternMatchRouter.set_deployment_model_name(
+ matched_pattern=name_match, litellm_deployment_litellm_model=deployment_pattern
+ ),
+ )
+ )
+
+
+def _ids_routing_to_catalog_models(
+ name_pattern: str,
+ deployment_pattern: str,
+ provider: str,
+ catalog_ids: Sequence[str],
+ routes_to_model: Callable[[str, str], bool],
+) -> tuple[str, ...]:
+ if name_pattern.count("*") != deployment_pattern.count("*") or _lists_name_fragments(
+ name_pattern, deployment_pattern
+ ):
+ return ()
+ provider_id_prefix: Final = f"{provider}/"
+ provider_model_ids: Final = tuple(catalog_id.removeprefix(provider_id_prefix) for catalog_id in catalog_ids)
+ catalog_pattern: Final = _without_routing_segments(
+ deployment_pattern.removeprefix(provider_id_prefix), provider, name_pattern, provider_model_ids
+ )
+ deployment_model_pattern: Final = f"{provider_id_prefix}{catalog_pattern}"
+ deployment_regex: Final = re.compile(PatternMatchRouter().pattern_to_regex(deployment_model_pattern))
+ name_regex: Final = re.compile(PatternMatchRouter().pattern_to_regex(name_pattern))
+ catalog_matches: Final = (
+ deployment_regex.fullmatch(f"{provider_id_prefix}{model_id}") for model_id in provider_model_ids
+ )
+ listed_ids: Final = (
+ (
+ PatternMatchRouter.set_deployment_model_name(
+ matched_pattern=catalog_match, litellm_deployment_litellm_model=name_pattern
+ ),
+ catalog_match.string,
+ )
+ for catalog_match in catalog_matches
+ if catalog_match is not None
+ )
+ return tuple(
+ dict.fromkeys(
+ listed_id
+ for listed_id, catalog_id in listed_ids
+ if listed_id
+ and _routes_back_to(
+ listed_id, name_regex, (deployment_model_pattern, catalog_id), deployment_pattern, routes_to_model
+ )
+ )
+ )
+
+
+def _model_info_field(deployment: Mapping[str, object], field: str) -> object:
+ model_info: Final = deployment.get("model_info")
+ return model_info.get(field) if is_str_keyed_mapping(model_info) else None
+
+
+def _deployment_team_id(deployment: Mapping[str, object]) -> str | None:
+ team_id: Final = _model_info_field(deployment, "team_id")
+ return team_id if isinstance(team_id, str) else None
+
+
+def _cached_wildcard_routing(llm_router: Router | None) -> Callable[[str, str | None], frozenset[str]] | None:
+ return None if llm_router is None else functools.cache(llm_router.wildcard_routed_models)
+
+
+def _routes_to_model(
+ routed_models: Callable[[str, str | None], frozenset[str]] | None, team_id: str | None
+) -> Callable[[str, str], bool]:
+ return lambda listed_id, model: routed_models is None or model in routed_models(listed_id, team_id)
+
+
+def _deployment_pattern_naming_listed_ids(wildcard_suffix: str, litellm_params: LiteLLM_Params | None) -> str | None:
+ if litellm_params is None or "/" not in litellm_params.model or not _check_wildcard_routing(litellm_params.model):
+ return None
+ deployment_suffix: Final = litellm_params.model.partition("/")[2]
+ return litellm_params.model if wildcard_suffix != "*" or deployment_suffix != "*" else None
+
+
+def get_known_models_from_wildcard(
+ wildcard_model: str,
+ litellm_params: LiteLLM_Params | None = None,
+ routes_to_model: Callable[[str, str], bool] = lambda _listed_id, _model: True,
+) -> list[str]:
wildcard_model_to_expand: Final = (
litellm_params.model
if wildcard_model == "*"
@@ -282,6 +416,7 @@ def get_known_models_from_wildcard(wildcard_model: str, litellm_params: LiteLLM_
wildcard_provider_prefix, wildcard_suffix = wildcard_model_to_expand.split("/", 1)
except ValueError: # safely fail
return []
+ deployment_pattern_naming_listed_ids: Final = _deployment_pattern_naming_listed_ids(wildcard_suffix, litellm_params)
# Use provider from litellm_params when available, otherwise from wildcard prefix
# (e.g., "openai" from "openai/*" - needed for BYOK where wildcard isn't in router)
@@ -299,22 +434,29 @@ def get_known_models_from_wildcard(wildcard_model: str, litellm_params: LiteLLM_
if wildcard_models is None:
return []
+ if deployment_pattern_naming_listed_ids is not None:
+ return list(
+ _ids_routing_to_catalog_models(
+ name_pattern=wildcard_model,
+ deployment_pattern=deployment_pattern_naming_listed_ids,
+ provider=provider,
+ catalog_ids=wildcard_models,
+ routes_to_model=routes_to_model,
+ )
+ )
if wildcard_suffix != "*":
- ## CHECK IF PARTIAL FILTER e.g. `gemini-*`
model_prefix: Final = wildcard_suffix.replace("*", "")
-
- deployment_repeats_prefix: Final = litellm_params is not None and litellm_params.model.endswith(
- f"/{wildcard_suffix}"
- )
- is_partial_filter: Final = deployment_repeats_prefix or any(
- wc_model.startswith(model_prefix) for wc_model in wildcard_models
- )
- if is_partial_filter:
- filtered_wildcard_models = [wc_model for wc_model in wildcard_models if wc_model.startswith(model_prefix)]
+ provider_id_prefix: Final = f"{provider}/"
+ filtered_wildcard_models: Final = [
+ wc_model
+ for wc_model in wildcard_models
+ if wc_model.removeprefix(provider_id_prefix).startswith(model_prefix)
+ ]
+ if filtered_wildcard_models:
wildcard_models = filtered_wildcard_models
else:
# add model prefix to wildcard models
- wildcard_models = [f"{model_prefix}{model}" for model in wildcard_models]
+ wildcard_models = [f"{model_prefix}{model.removeprefix(provider_id_prefix)}" for model in wildcard_models]
known_providers: Final = {provider.value for provider in LlmProviders}
suffix_appended_wildcard_models: Final = []
@@ -337,6 +479,7 @@ def get_known_models_from_wildcard(wildcard_model: str, litellm_params: LiteLLM_
def expand_wildcard_deployments_for_model_info(
deployments: list[dict[str, object]],
+ llm_router: Router | None = None,
) -> list[dict[str, object]]:
"""Expand wildcard deployments into one row per known provider model.
@@ -346,6 +489,7 @@ def expand_wildcard_deployments_for_model_info(
becomes one entry per known openai model, matching /v1/models behaviour.
"""
expanded: Final[list[dict[str, object]]] = []
+ routed_models: Final = _cached_wildcard_routing(llm_router)
for deployment in deployments:
model_name = str(deployment.get("model_name") or "")
raw_params = deployment.get("litellm_params")
@@ -355,7 +499,7 @@ def expand_wildcard_deployments_for_model_info(
# Determine the wildcard pattern to expand.
# Branch order matters: only fall to litellm_model when model_name is
# also a wildcard, so a concrete model_name is never overwritten.
- if _check_wildcard_routing(model_name) and "/" in model_name:
+ if _check_wildcard_routing(model_name) and ("/" in model_name or model_name == "*"):
wildcard_pattern = model_name
elif _check_wildcard_routing(model_name) and _check_wildcard_routing(litellm_model):
wildcard_pattern = litellm_model
@@ -373,6 +517,7 @@ def expand_wildcard_deployments_for_model_info(
expanded_names = get_known_models_from_wildcard(
wildcard_model=wildcard_pattern,
litellm_params=litellm_params,
+ routes_to_model=_routes_to_model(routed_models, _deployment_team_id(deployment)),
)
if not expanded_names:
expanded.append(deployment)
@@ -396,6 +541,7 @@ def _get_wildcard_models(
team_id: str | None = None,
) -> list[str]:
models_to_remove: Final = set()
+ routes_to_model: Final = _routes_to_model(_cached_wildcard_routing(llm_router), team_id)
all_wildcard_models: Final = []
for model in unique_models:
if _check_wildcard_routing(model=model):
@@ -411,6 +557,7 @@ def _get_wildcard_models(
get_known_models_from_wildcard(
wildcard_model=model,
litellm_params=LiteLLM_Params(**router_model["litellm_params"]),
+ routes_to_model=routes_to_model,
)
)
else:
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index 689a5f38416..bbdc996a027 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -17596,7 +17596,7 @@ async def model_info_v1(
alias_models: Final = copy.deepcopy(llm_router.get_model_list_from_model_alias())
all_models.extend(alias_models)
- all_models = expand_wildcard_deployments_for_model_info(all_models)
+ all_models = expand_wildcard_deployments_for_model_info(all_models, llm_router)
allowed_model_names: Final = await _get_v1_model_info_allowed_model_names_with_access_groups(
user_api_key_dict=user_api_key_dict,
diff --git a/litellm/router.py b/litellm/router.py
index 5a34a00e204..142b2019e6e 100644
--- a/litellm/router.py
+++ b/litellm/router.py
@@ -13331,6 +13331,14 @@ class Router:
return proxy_wide
return team_router.get_deployments_by_pattern(model=model)
+ def wildcard_routed_models(self, model: str, team_id: str | None) -> frozenset[str]:
+ """The models wildcard_route_deployments would route ``model`` to, without copying the deployments."""
+ proxy_wide: Final = self.pattern_router.get_models_by_pattern(model=model)
+ team_router: Final = self.team_pattern_routers.get(team_id) if team_id is not None else None
+ if proxy_wide or team_router is None:
+ return proxy_wide
+ return team_router.get_models_by_pattern(model=model)
+
def team_ptu_ceiling(self, team_id: str, model_group: str) -> PTUTeamCeiling | None:
"""The per-minute ceiling ``team_id``'s PTU shares set on the group serving ``model_group``,
else None, kept until the model list next changes."""
diff --git a/litellm/router_utils/pattern_match_deployments.py b/litellm/router_utils/pattern_match_deployments.py
index 62ba5592f90..f921f907f4c 100644
--- a/litellm/router_utils/pattern_match_deployments.py
+++ b/litellm/router_utils/pattern_match_deployments.py
@@ -3,6 +3,7 @@ Class to handle llm wildcard routing and regex pattern matching
"""
import copy
+import itertools
import re
from re import Match
from typing import Final
@@ -124,7 +125,7 @@ class PatternMatchRouter:
_pattern_to_regex = pattern_to_regex
- def _return_pattern_matched_deployments(self, matched_pattern: Match, deployments: list[dict]) -> list[dict]:
+ def _return_pattern_matched_deployments(self, matched_pattern: Match[str], deployments: list[dict]) -> list[dict]:
new_deployments: Final = []
for deployment in deployments:
new_deployment = copy.deepcopy(deployment)
@@ -182,7 +183,7 @@ class PatternMatchRouter:
@staticmethod
def set_deployment_model_name(
- matched_pattern: Match,
+ matched_pattern: Match[str],
litellm_deployment_litellm_model: str,
) -> str:
"""
@@ -259,6 +260,28 @@ class PatternMatchRouter:
return pattern_match
return []
+ def get_models_by_pattern(self, model: str, custom_llm_provider: str | None = None) -> frozenset[str]:
+ """The models get_deployments_by_pattern would route ``model`` to, without copying the deployments."""
+ provider: Final = custom_llm_provider or inferred_provider(model)
+ requests_by_pattern: Final = itertools.product((model, f"{provider}/{model}"), self.patterns)
+ matched: Final = next(
+ (
+ (pattern_match, pattern)
+ for request, pattern in requests_by_pattern
+ if (pattern_match := re.match(pattern, request)) is not None
+ ),
+ None,
+ )
+ if matched is None:
+ return frozenset()
+ pattern_match, pattern = matched
+ return frozenset(
+ PatternMatchRouter.set_deployment_model_name(
+ matched_pattern=pattern_match, litellm_deployment_litellm_model=deployment["litellm_params"]["model"]
+ )
+ for deployment in self.patterns[pattern]
+ )
+
# Example usage:
# router = PatternRouter()
diff --git a/tests/unit/proxy/auth/test_model_checks.py b/tests/unit/proxy/auth/test_model_checks.py
index 660cc93874d..83761620cc9 100644
--- a/tests/unit/proxy/auth/test_model_checks.py
+++ b/tests/unit/proxy/auth/test_model_checks.py
@@ -1,3 +1,5 @@
+from collections.abc import Generator, Mapping
+from contextlib import contextmanager
from typing import Final
from unittest.mock import patch
@@ -1196,3 +1198,326 @@ def test_custom_prefix_that_starts_a_discovered_id_still_prefixes_every_listed_m
"anthropic/anthropic.claude-haiku-4-5-20251001-v1:0",
"anthropic/us.anthropic.claude-haiku-4-5-20251001-v1:0",
]
+
+
+@contextmanager
+def _registered_chat_models(provider_by_model: Mapping[str, str]) -> Generator[None, None, None]:
+ import litellm
+
+ litellm.register_model(
+ {model: {"litellm_provider": provider, "mode": "chat"} for model, provider in provider_by_model.items()},
+ persist_across_reloads=False,
+ )
+ try:
+ yield
+ finally:
+ provider_model_sets: Final = tuple(known for known in vars(litellm).values() if isinstance(known, set))
+ for model in provider_by_model:
+ litellm.model_cost.pop(model, None)
+ for provider_models in provider_model_sets:
+ provider_models.discard(model)
+ litellm.add_known_models(model_cost_map={})
+
+
+ ("wildcard", "deployment_model", "catalog", "expected"),
+ [
+ pytest.param(
+ "cloudflare/@cf/partial-wildcard-org/*",
+ "cloudflare/@cf/partial-wildcard-org/*",
+ ("cloudflare/@cf/partial-wildcard-org/model-a", "cloudflare/@hf/partial-wildcard-org/model-b"),
+ ["cloudflare/@cf/partial-wildcard-org/model-a"],
+ id="prefixed-catalog-with-deployment",
+ ),
+ pytest.param(
+ "cloudflare/@cf/partial-wildcard-org/*",
+ None,
+ ("cloudflare/@cf/partial-wildcard-org/model-a", "cloudflare/@hf/partial-wildcard-org/model-b"),
+ ["cloudflare/@cf/partial-wildcard-org/model-a"],
+ id="prefixed-catalog-without-deployment",
+ ),
+ pytest.param(
+ "gemini/gemini-partial-wildcard-9*",
+ "gemini/gemini-partial-wildcard-9*",
+ (
+ "gemini-partial-wildcard-9-flash",
+ "gemini/gemini-partial-wildcard-9-pro",
+ "gemini/gemini-other-partial-wildcard-9",
+ ),
+ ["gemini/gemini-partial-wildcard-9-flash", "gemini/gemini-partial-wildcard-9-pro"],
+ id="mixed-bare-and-prefixed-catalog",
+ ),
+ ],
+)
+def test_partial_wildcard_lists_catalog_ids_stored_with_the_provider_prefix(
+ wildcard: str, deployment_model: str | None, catalog: tuple[str, ...], expected: list[str]
+) -> None:
+ from litellm.proxy.auth.model_checks import get_known_models_from_wildcard
+ from litellm.types.router import LiteLLM_Params
+
+ provider: Final = wildcard.split("/", 1)[0]
+ deployment: Final = None if deployment_model is None else LiteLLM_Params(model=deployment_model)
+ with _registered_chat_models(dict.fromkeys(catalog, provider)):
+ listed: Final = get_known_models_from_wildcard(wildcard, deployment)
+
+ assert sorted(listed) == expected
+
+
+_ROUTE_CF_ID: Final = "cloudflare/@cf/partial-route-org/model-a-instruct"
+_ROUTE_CF_SUFFIXED_ID: Final = "cloudflare/@cf/partial-route-org/model-b-instruct-v2"
+_ROUTE_HF_ID: Final = "cloudflare/@hf/partial-route-org/model-c"
+_ROUTE_GEMINI_ID: Final = "gemini-partial-route-9-flash"
+_ROUTE_OPENAI_ID: Final = "gpt-partial-route-9-mini"
+_ROUTE_BEDROCK_ID: Final = "anthropic.partial-route-9-v1:0"
+_ROUTE_CF_IDS: Final = {_ROUTE_CF_ID, _ROUTE_CF_SUFFIXED_ID}
+
+
+ ("model_name", "deployment_model", "key_model", "reachable"),
+ [
+ pytest.param("cloudflare/@cf/*", "cloudflare/@cf/*", None, _ROUTE_CF_IDS, id="filter"),
+ pytest.param(
+ "cloudflare/@cf/*-instruct", "cloudflare/@cf/*-instruct", None, {_ROUTE_CF_ID}, id="filter-with-suffix"
+ ),
+ pytest.param(
+ "cloudflare/@cf/*",
+ "cloudflare/*",
+ None,
+ {*_ROUTE_CF_IDS, _ROUTE_HF_ID},
+ id="alias-whose-prefix-matches-catalog-ids",
+ ),
+ pytest.param("cloudflare/team-*", "cloudflare/*", None, {*_ROUTE_CF_IDS, _ROUTE_HF_ID}, id="alias"),
+ pytest.param("cloudflare/cf-*", "cloudflare/@cf/*", None, _ROUTE_CF_IDS, id="alias-over-partial-deployment"),
+ pytest.param("my-cf/*", "cloudflare/@cf/*", None, _ROUTE_CF_IDS, id="bare-alias-over-partial-deployment"),
+ pytest.param(
+ "cloudflare/team-*", "cloudflare/@cf/*/*", None, set(), id="alias-with-fewer-wildcards-than-its-deployment"
+ ),
+ pytest.param("partial-route-v/*/*", "cloudflare/@cf/*/*", None, _ROUTE_CF_IDS, id="multi-wildcard-alias"),
+ pytest.param(
+ "partial-route-v/*-*", "cloudflare/@cf/*/*", None, set(), id="multi-wildcard-alias-routing-splits-elsewhere"
+ ),
+ pytest.param(
+ "partial-route-team/*", "openai/gpt-partial-route-9*", None, set(), id="alias-over-mid-word-deployment"
+ ),
+ pytest.param(
+ "team/gpt-partial-route-9*",
+ "openai/gpt-partial-route-9*",
+ None,
+ {f"openai/{_ROUTE_OPENAI_ID}"},
+ id="alias-repeating-the-deployment-partial-word",
+ ),
+ pytest.param(
+ "team/gpt-partial-route-9-prod*",
+ "openai/gpt-partial-route-9*",
+ None,
+ {f"openai/{_ROUTE_OPENAI_ID}"},
+ id="alias-extending-the-deployment-partial-word",
+ ),
+ pytest.param(
+ "partial-route-g/*",
+ "gemini/gemini-partial-route-*",
+ None,
+ {_ROUTE_GEMINI_ID},
+ id="alias-over-deployment-cut-at-a-word-boundary",
+ ),
+ pytest.param(
+ "cloudflare/*", "cloudflare/*", "cloudflare/@cf/*", _ROUTE_CF_IDS, id="key-filter-over-provider-wildcard"
+ ),
+ pytest.param("gemini/gemini-*", "gemini/*", None, {_ROUTE_GEMINI_ID}, id="alias-over-bare-id"),
+ pytest.param(
+ "gemini/*", "gemini/*", "gemini/gemini-partial-route-9*", {_ROUTE_GEMINI_ID}, id="key-filter-over-bare-id"
+ ),
+ pytest.param(
+ "openai/*", "openai/responses/*", None, {f"openai/responses/{_ROUTE_OPENAI_ID}"}, id="responses-route"
+ ),
+ pytest.param(
+ "openai/*",
+ "openai/responses/*",
+ "openai/gpt-partial-route-9*",
+ {f"openai/responses/{_ROUTE_OPENAI_ID}"},
+ id="key-filter-over-responses-route",
+ ),
+ pytest.param(
+ "bedrock/*", "bedrock/converse/*", None, {f"bedrock/converse/{_ROUTE_BEDROCK_ID}"}, id="converse-route"
+ ),
+ pytest.param(
+ "openai/partial-route-org/*",
+ "openai/partial-route-org/*",
+ None,
+ set(),
+ id="same-name-namespace-the-catalog-lacks",
+ ),
+ pytest.param(
+ "*", "openai/*", "openai/gpt-partial-route-9*", set(), id="provider-prefixed-key-filter-over-catch-all"
+ ),
+ pytest.param("*", "cloudflare/@cf/*", None, _ROUTE_CF_IDS, id="catch-all-over-partial-deployment"),
+ pytest.param("*", "gemini/gemini-partial-route-9*", None, set(), id="catch-all-over-mid-word-deployment"),
+ pytest.param("*", "openai/responses/gpt-partial-route-9*", None, set(), id="catch-all-over-mid-word-route"),
+ pytest.param(
+ "*", "gemini/gemini-partial-route-9-flash*", None, set(), id="catch-all-whose-only-match-is-its-fixed-text"
+ ),
+ ],
+)
+def test_every_listed_partial_wildcard_id_routes_to_the_catalog_model_it_names(
+ model_name: str, deployment_model: str, key_model: str | None, reachable: set[str]
+) -> None:
+ from pydantic import TypeAdapter
+
+ from litellm import Router
+ from litellm.proxy.auth.model_checks import expand_wildcard_deployments_for_model_info, get_complete_model_list
+ from litellm.types.router import LiteLLM_Params
+
+ routed_params: Final = TypeAdapter(tuple[LiteLLM_Params, ...])
+ router: Final = Router(model_list=[{"model_name": model_name, "litellm_params": {"model": deployment_model}}])
+
+ def routed_model(listed_id: str) -> str:
+ routed: Final = routed_params.validate_python(
+ tuple(deployment["litellm_params"] for deployment in router.wildcard_route_deployments(listed_id, None))
+ )
+ return routed[0].model if routed else listed_id
+
+ def routed_catalog_ids(listed: list[str]) -> list[str]:
+ routed_models: Final = [routed_model(listed_id) for listed_id in listed]
+ return sorted(
+ routed.removeprefix("gemini/") if routed.startswith("gemini/gemini-") else routed
+ for routed in routed_models
+ if "partial-route" in routed
+ )
+
+ with _registered_chat_models(
+ {
+ _ROUTE_CF_ID: "cloudflare",
+ _ROUTE_CF_SUFFIXED_ID: "cloudflare",
+ _ROUTE_HF_ID: "cloudflare",
+ _ROUTE_GEMINI_ID: "gemini",
+ _ROUTE_OPENAI_ID: "openai",
+ _ROUTE_BEDROCK_ID: "bedrock",
+ }
+ ):
+ v1_models: Final = get_complete_model_list(
+ key_models=[key_model or model_name],
+ team_models=[],
+ proxy_model_list=[model_name],
+ user_model=None,
+ infer_model_from_keys=False,
+ llm_router=router,
+ )
+ model_info_names: Final = [
+ str(row["model_name"])
+ for row in expand_wildcard_deployments_for_model_info(
+ [dict(deployment) for deployment in router.get_model_list() or []], router
+ )
+ if row["model_name"] != model_name
+ ]
+ listed_v1_models: Final = routed_catalog_ids(v1_models)
+ listed_model_info_names: Final = routed_catalog_ids(model_info_names)
+
+ unrouted_ids: Final = [
+ listed_id
+ for listed_id in [*v1_models, *model_info_names]
+ if not router.wildcard_route_deployments(listed_id, None)
+ ]
+ assert unrouted_ids == []
+ assert all(v1_models) and all(model_info_names)
+ if model_name == "*":
+ assert [listed_id for listed_id in v1_models if not routed_model(listed_id).endswith(f"/{listed_id}")] == []
+ assert listed_v1_models == sorted(reachable)
+ if key_model is None:
+ assert listed_model_info_names == sorted(reachable)
+
+
+def test_catch_all_lists_no_id_a_more_specific_sibling_wildcard_routes_elsewhere() -> None:
+ from litellm import Router
+ from litellm.proxy.auth.model_checks import expand_wildcard_deployments_for_model_info, get_complete_model_list
+
+ unshadowed_id: Final = "cloudflare/@cf/unshadowed-route-org/model-d"
+ router: Final = Router(
+ model_list=[
+ {"model_name": "*", "litellm_params": {"model": "cloudflare/@cf/*"}},
+ {"model_name": "partial-route-org/*", "litellm_params": {"model": "openai/*"}},
+ ]
+ )
+
+ def routed_models(listed: list[str]) -> dict[str, object]:
+ return {
+ listed_id: router.wildcard_route_deployments(listed_id, None)[0]["litellm_params"]["model"]
+ for listed_id in listed
+ if "route-org/model-" in listed_id
+ }
+
+ with _registered_chat_models(
+ {_ROUTE_CF_ID: "cloudflare", _ROUTE_CF_SUFFIXED_ID: "cloudflare", unshadowed_id: "cloudflare"}
+ ):
+ v1_models: Final = get_complete_model_list(
+ key_models=[],
+ team_models=[],
+ proxy_model_list=["*", "partial-route-org/*"],
+ user_model=None,
+ infer_model_from_keys=False,
+ llm_router=router,
+ )
+ model_info_names: Final = [
+ str(row["model_name"])
+ for row in expand_wildcard_deployments_for_model_info(
+ [dict(deployment) for deployment in router.get_model_list() or []], router
+ )
+ ]
+
+ assert routed_models(v1_models) == {"unshadowed-route-org/model-d": unshadowed_id}
+ assert routed_models(model_info_names) == {"unshadowed-route-org/model-d": unshadowed_id}
+
+
+def test_wildcard_lists_an_id_a_more_specific_sibling_serves_with_the_same_model() -> None:
+ from litellm import Router
+ from litellm.proxy.auth.model_checks import expand_wildcard_deployments_for_model_info, get_complete_model_list
+
+ router: Final = Router(
+ model_list=[
+ {"model_name": "openai/gpt-partial-route-9*", "litellm_params": {"model": "openai/gpt-partial-route-9*"}},
+ {
+ "model_name": "openai/gpt-partial-route-9-mini*",
+ "litellm_params": {"model": "openai/gpt-partial-route-9-mini*"},
+ },
+ ]
+ )
+ with _registered_chat_models({_ROUTE_OPENAI_ID: "openai"}):
+ v1_models: Final = get_complete_model_list(
+ key_models=["openai/gpt-partial-route-9*"],
+ team_models=[],
+ proxy_model_list=["openai/gpt-partial-route-9*", "openai/gpt-partial-route-9-mini*"],
+ user_model=None,
+ infer_model_from_keys=False,
+ llm_router=router,
+ )
+ model_info_names: Final = [
+ str(row["model_name"])
+ for row in expand_wildcard_deployments_for_model_info(
+ [dict(deployment) for deployment in router.get_model_list() or []], router
+ )
+ ]
+
+ assert v1_models == [f"openai/{_ROUTE_OPENAI_ID}"]
+ assert "openai/gpt-partial-route-9*" not in model_info_names
+
+
+def test_prefixed_alias_over_a_bare_catch_all_lists_ids_that_route_through_it(monkeypatch: pytest.MonkeyPatch) -> None:
+ from litellm import Router
+ from litellm.proxy.auth.model_checks import get_complete_model_list
+
+ monkeypatch.setenv("OPENAI_API_KEY", "sk-partial-route-test")
+ router: Final = Router(model_list=[{"model_name": "team-partial-route/*", "litellm_params": {"model": "*"}}])
+ with _registered_chat_models({_ROUTE_OPENAI_ID: "openai"}):
+ v1_models: Final = get_complete_model_list(
+ key_models=[],
+ team_models=[],
+ proxy_model_list=["team-partial-route/*"],
+ user_model=None,
+ infer_model_from_keys=False,
+ llm_router=router,
+ )
+
+ unrouted_ids: Final = [
+ listed_id for listed_id in v1_models if not router.wildcard_route_deployments(listed_id, None)
+ ]
+ assert f"team-partial-route/{_ROUTE_OPENAI_ID}" in v1_models
+ assert unrouted_ids == []
diff --git a/tests/unit/router_utils/test_pattern_match_deployments.py b/tests/unit/router_utils/test_pattern_match_deployments.py
index 01af021112b..0bb33064c68 100644
--- a/tests/unit/router_utils/test_pattern_match_deployments.py
+++ b/tests/unit/router_utils/test_pattern_match_deployments.py
@@ -210,6 +210,30 @@ def test_route_with_none():
assert router.route(None) is None
+ ("model", "custom_llm_provider"),
+ [
+ pytest.param("openai/gpt-4o", None, id="most-specific-pattern-wins"),
+ pytest.param("o3", "openai", id="provider-qualified-retry"),
+ pytest.param("openai/o3", None, id="every-deployment-on-the-pattern"),
+ pytest.param("mistral/large", "mistral", id="no-pattern-matches"),
+ ],
+)
+def test_get_models_by_pattern_names_the_models_get_deployments_by_pattern_routes_to(
+ model: str, custom_llm_provider: str | None
+):
+ router: Final = PatternMatchRouter()
+ router.add_pattern("openai/*", _wildcard_deployment("openai/*"))
+ router.add_pattern("openai/*", {"model_name": "openai/*", "litellm_params": {"model": "azure/*"}})
+ router.add_pattern("openai/gpt-*", {"model_name": "openai/gpt-*", "litellm_params": {"model": "azure/gpt-*-prod"}})
+
+ routed: Final = router.get_deployments_by_pattern(model, custom_llm_provider=custom_llm_provider)
+
+ assert router.get_models_by_pattern(model, custom_llm_provider=custom_llm_provider) == frozenset(
+ _matched_models(routed)
+ )
+
+
def test_route_with_multiple_matching_patterns():
"""
Tests that the router returns the first matching pattern when there are multiple matching patterns
diff --git a/tests/unit/test_router/test_router.py b/tests/unit/test_router/test_router.py
index 6403f00eb50..9b1bdbf702e 100644
--- a/tests/unit/test_router/test_router.py
+++ b/tests/unit/test_router/test_router.py
@@ -8618,6 +8618,9 @@ def test_wildcard_route_deployments_is_the_one_pattern_routing_serves_from(
assert tuple(Deployment.model_validate(d).model_info.id for d in served) == expected_ids
assert tuple(Deployment.model_validate(d).model_info.id for d in early_deployments) == expected_ids
+ assert router.wildcard_routed_models(requested, team_id) == frozenset(
+ Deployment.model_validate(d).litellm_params.model for d in served
+ )
def test_get_deployment_credentials_with_provider_aws_bedrock_runtime_endpoint():