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(router)!: keep RPM, region, and param checks when token counting fails (#44544)

武本龍門43be1c2ae7f7
diff --git a/litellm/router.py b/litellm/router.py
index 96c96310d45..151a8a75dc3 100644
--- a/litellm/router.py
+++ b/litellm/router.py
@@ -329,6 +329,7 @@ from litellm.types.router import (
FallbackBudgetCheck,
GuardrailTypedDict,
LiteLLM_Params,
+ LiteLLMParamsTypedDict,
MockRouterTestingParams,
ModelGroupInfo,
OptionalPreCallChecks,
@@ -486,6 +487,7 @@ _CLAUDE_CODE_SESSION_ID_RE: Final = re.compile(r"^[a-zA-Z0-9_\-]{8,}$")
_CLAUDE_CODE_SESSION_ROUTER_TTL_SECONDS: Final = 3600
CLAUDE_CODE_SESSION_ROUTER_BINDING_TARGET: Final = "claude_code_session_router_binding"
+_PRE_CALL_CHECK_FILTERED_PARAMS: Final = frozenset({"response_format"})
_RUNTIME_TOGGLEABLE_PRE_CALL_CHECKS: Final[Mapping[str, type[CustomLogger]]] = MappingProxyType(
{
"prompt_caching": PromptCachingDeploymentCheck,
@@ -12691,16 +12693,34 @@ class Router:
str(deployment_params.get("model") or ""), deployment_params.get("custom_llm_provider")
):
return True
+ return Router._deployment_supports_param(deployment, group, param)
+
+ @staticmethod
+ def _capability_model_and_provider(deployment_params: LiteLLMParamsTypedDict, group: str) -> tuple[str, str]:
+ model_label: Final = str(deployment_params.get("model") or group)
+ authenticating_provider: Final = declared_authenticating_provider(
+ model_label, deployment_params.get("custom_llm_provider")
+ )
+ if authenticating_provider is not None:
+ return model_label.removeprefix(f"{authenticating_provider}/"), authenticating_provider
+ model, custom_llm_provider, _, _ = litellm.get_llm_provider(
+ model=model_label,
+ custom_llm_provider=deployment_params.get("custom_llm_provider"),
+ litellm_params=LiteLLM_Params.model_validate(deployment_params),
+ )
+ return model, custom_llm_provider
+
+ @staticmethod
+ def _deployment_supports_param(deployment: DeploymentTypedDict, group: str, param: str) -> bool:
+ deployment_params: Final = deployment.get("litellm_params")
+ if not deployment_params:
+ return True
deployment_model_info: Final = deployment.get("model_info")
base_model: Final = (
deployment_model_info.get("base_model") if deployment_model_info else None
) or deployment_params.get("base_model")
try:
- model, custom_llm_provider, _, _ = litellm.get_llm_provider(
- model=deployment_params.get("model") or group,
- custom_llm_provider=deployment_params.get("custom_llm_provider"),
- litellm_params=LiteLLM_Params.model_validate(deployment_params),
- )
+ model, custom_llm_provider = Router._capability_model_and_provider(deployment_params, group)
supported: Final = litellm.get_supported_openai_params(
model=model,
custom_llm_provider=custom_llm_provider,
@@ -12708,7 +12728,7 @@ class Router:
)
except Exception as e: # noqa: BLE001 # best-effort filter: an unresolvable provider must not narrow the request
verbose_router_logger.debug(
- "litellm.router.py::_deployment_accepts_param: keeping %s for model=%s. Got - %s", param, group, e
+ "litellm.router.py::_deployment_supports_param: keeping %s for model=%s. Got - %s", param, group, e
)
return True
return supported is None or param in supported
@@ -13205,7 +13225,8 @@ class Router:
Returns None when no deployment limits its context window, and when counting fails. The
caller pairs this with ``skip_inline_token_count`` so neither case puts the count back on
- the loop: a failed count leaves the deployments unfiltered, exactly as before.
+ the loop: a failed count only skips the context-window check - RPM, region and
+ invalid-params checks still run for every deployment.
"""
if messages is None and input is None:
return None
@@ -13223,6 +13244,66 @@ class Router:
)
return None
+ def _resolve_pre_call_check_input_tokens(
+ self,
+ messages: Sequence[Mapping[str, str]] | None,
+ input: str | Sequence[object] | None,
+ request_kwargs: Mapping[str, object] | None,
+ input_token_count: int | None,
+ count_inline: bool,
+ ) -> int | None:
+ if input_token_count is not None:
+ return input_token_count
+ if not count_inline:
+ return None
+ try:
+ return self._count_pre_call_check_tokens(
+ messages=cast(list[dict[str, str]] | None, messages), # cast-ok: forwarded to the sync counter
+ input=cast(str | list[object] | None, input), # cast-ok: forwarded to the sync counter
+ request_kwargs=request_kwargs,
+ )
+ except Exception as e:
+ verbose_router_logger.error(
+ "litellm.router.py::_pre_call_checks: failed to count tokens. "
+ "Skipping the context-window check only; RPM/region/param checks still apply. Got - %s",
+ e,
+ )
+ return None
+
+ @staticmethod
+ def _params_neither_dropped_nor_allowed(params: Mapping[str, object], candidates: frozenset[str]) -> frozenset[str]:
+ if params.get("drop_params") is True:
+ return frozenset()
+ dropped: Final = params.get("additional_drop_params")
+ dropped_names: Final = (
+ frozenset(entry for entry in dropped if isinstance(entry, str))
+ if isinstance(dropped, list)
+ else frozenset()
+ )
+ return candidates - Router._declared_param_allowlist(params) - dropped_names
+
+ @staticmethod
+ def _deployment_lacks_params(deployment: DeploymentTypedDict, group: str, params: frozenset[str]) -> bool:
+ return any(not Router._deployment_supports_param(deployment, group, param) for param in params)
+
+ @staticmethod
+ def _deployment_rejects_params(
+ deployment: DeploymentTypedDict, group: str, params: frozenset[str], request_kwargs: Mapping[str, object]
+ ) -> bool:
+ call_settings: Final[Mapping[str, object]] = {**(deployment.get("litellm_params") or {}), **request_kwargs}
+ return Router._deployment_lacks_params(
+ deployment, group, Router._params_neither_dropped_nor_allowed(call_settings, params)
+ )
+
+ @staticmethod
+ def _pre_call_check_requested_chat_params(request_kwargs: Mapping[str, object]) -> frozenset[str]:
+ requested: Final = litellm.utils.get_non_default_params(passed_params=dict(request_kwargs))
+ return frozenset(
+ param
+ for param, value in requested.items()
+ if param in _PRE_CALL_CHECK_FILTERED_PARAMS and not isinstance(value, str)
+ )
+
def _pre_call_checks(
self,
model: str,
@@ -13232,6 +13313,7 @@ class Router:
request_kwargs: dict | None = None,
input_token_count: int | None = None,
skip_inline_token_count: bool = False,
+ request_deployments: Sequence[DeploymentTypedDict] | None = None,
):
"""
Filter out model in model group, if:
@@ -13250,13 +13332,6 @@ class Router:
invalid_model_indices: Final = set() # Use set for O(1) membership checks
- # Token counting (tiktoken) is the dominant on-loop cost for large prompts.
- # Only count when a deployment actually declares max_input_tokens, and count
- # at most once; for model groups with no context-window limit it is skipped.
- # Async callers pass the count in, already computed off the event loop, and set
- # skip_inline_token_count so a failed off-loop count is not retried back on the loop.
- input_tokens: int | None = input_token_count
-
_context_window_error = False
_potential_error_str = ""
_rate_limit_error = False
@@ -13265,6 +13340,24 @@ class Router:
has_countable_input: Final = (messages is not None or input is not None) and not compaction_pending(
request_kwargs
)
+ deployment_max_input_tokens: Final = tuple(
+ self._deployment_max_input_tokens(model, deployment) for deployment in _returned_deployments
+ )
+ input_tokens: Final = self._resolve_pre_call_check_input_tokens(
+ messages=messages,
+ input=cast(str | list[object] | None, input), # cast-ok: forwarded to the resolver
+ request_kwargs=cast(Mapping[str, object] | None, request_kwargs), # cast-ok: forwarded to the resolver
+ input_token_count=input_token_count,
+ count_inline=has_countable_input
+ and not skip_inline_token_count
+ and any(limit is not None for limit in deployment_max_input_tokens),
+ )
+ request_settings: Final[Mapping[str, object]] = request_kwargs if request_kwargs is not None else {}
+ requested_params: Final[frozenset[str]] = (
+ self._pre_call_check_requested_chat_params(request_settings)
+ if request_kwargs is not None and litellm.drop_params is False
+ else frozenset()
+ )
## get model group RPM ##
dt: Final = get_utc_datetime()
@@ -13278,39 +13371,22 @@ class Router:
_litellm_params = deployment.get("litellm_params", {})
_model_info = deployment.get("model_info", {})
- # see if we have the info for this model
- _deployment_model = None # per-deployment model name (avoids overwriting the outer `model` group name)
- try:
- base_model = _model_info.get("base_model", None)
- if base_model is None:
- base_model = _litellm_params.get("base_model", None)
- _deployment_model = base_model or _litellm_params.get("model", None)
- model_info = self.get_router_model_info(deployment=deployment, received_model_name=model)
-
- max_input_tokens = model_info.get("max_input_tokens") if isinstance(model_info, dict) else None
- if isinstance(max_input_tokens, int) and has_countable_input:
- if input_tokens is None:
- if skip_inline_token_count:
- return _returned_deployments
- try:
- input_tokens = self._count_pre_call_check_tokens(
- messages=messages, input=input, request_kwargs=request_kwargs
- )
- except Exception as e:
- verbose_router_logger.error(
- "litellm.router.py::_pre_call_checks: failed to count tokens. Returning initial list of deployments. Got - %s",
- e,
- )
- return _returned_deployments
- if input_tokens > max_input_tokens:
- invalid_model_indices.add(idx)
- _context_window_error = True
- _potential_error_str += (
- f"Model={_deployment_model}, Max Input Tokens={max_input_tokens}, Got={input_tokens}"
- )
- continue
- except Exception as e:
- verbose_router_logger.exception("An error occurs - %s", e)
+ max_input_tokens = deployment_max_input_tokens[idx]
+ if (
+ max_input_tokens is not None
+ and has_countable_input
+ and input_tokens is not None
+ and input_tokens > max_input_tokens
+ ):
+ invalid_model_indices.add(idx)
+ _context_window_error = True
+ deployment_model = (
+ _model_info.get("base_model") or _litellm_params.get("base_model") or _litellm_params.get("model")
+ )
+ _potential_error_str += (
+ f"Model={deployment_model}, Max Input Tokens={max_input_tokens}, Got={input_tokens}"
+ )
+ continue
model_id = _model_info.get("id", "")
## RPM CHECK ##
@@ -13342,53 +13418,57 @@ class Router:
invalid_model_indices.add(idx)
continue
- ## INVALID PARAMS ## -> catch 'gpt-3.5-turbo-16k' not supporting 'response_format' param
- if request_kwargs is not None and litellm.drop_params is False:
- # get supported params — use per-deployment model to avoid overwriting the outer model group name
- _dep_model_for_params: str = _deployment_model or model
- try:
- (
- _dep_model_for_params,
- custom_llm_provider,
- _,
- _,
- ) = litellm.get_llm_provider(
- model=_dep_model_for_params,
- litellm_params=LiteLLM_Params.model_validate(_litellm_params),
- )
- except Exception as e: # noqa: BLE001 # best-effort filter: an unresolvable provider must not fail the request
- verbose_router_logger.debug(
- "litellm.router.py::_pre_call_checks: skipping supported-params check for model=%s. Got - %s",
- _dep_model_for_params,
- e,
- )
- continue
-
- supported_openai_params = litellm.get_supported_openai_params(
- model=_dep_model_for_params,
- custom_llm_provider=custom_llm_provider,
- )
+ typed_deployments: Final = tuple(
+ cast(DeploymentTypedDict, deployment) # cast-ok: router deployments are plain dicts
+ for deployment in _returned_deployments
+ )
+ param_candidates: Final = tuple(
+ (idx, deployment) for idx, deployment in enumerate(typed_deployments) if idx not in invalid_model_indices
+ )
+ candidates_lacking_params: Final = tuple(
+ self._deployment_lacks_params(deployment, model, requested_params) for _, deployment in param_candidates
+ )
+ no_deployment_takes_params: Final = bool(candidates_lacking_params) and all(candidates_lacking_params)
+ candidates_failing_params: Final = (
+ tuple(
+ self._deployment_rejects_params(deployment, model, requested_params, request_settings)
+ for _, deployment in param_candidates
+ )
+ if no_deployment_takes_params
+ else candidates_lacking_params
+ )
+ excluded_indices: Final = frozenset(invalid_model_indices) | frozenset(
+ idx for (idx, _), fails in zip(param_candidates, candidates_failing_params, strict=True) if fails
+ )
- if supported_openai_params is None:
- continue
- else:
- # check the non-default openai params in request kwargs
- non_default_params = litellm.utils.get_non_default_params(passed_params=request_kwargs)
- special_params = ["response_format"]
- # check if all params are supported
- for k, v in non_default_params.items():
- if k not in supported_openai_params and k in special_params:
- # if not -> invalid model
- verbose_router_logger.debug("INVALID MODEL INDEX @ REQUEST KWARG FILTERING, k=%s", k)
- invalid_model_indices.add(idx)
-
- if len(invalid_model_indices) == len(_returned_deployments):
+ if len(excluded_indices) == len(_returned_deployments):
"""
- no healthy deployments available b/c context window checks or rate limit error
- First check for rate limit errors (if this is true, it means the model passed the context window check but failed the rate limit check)
"""
+ group_deployments: Final = (
+ tuple(request_deployments)
+ if request_deployments is not None
+ else (tuple(self.get_all_deployments(model_name=model)) or typed_deployments)
+ )
+ if (
+ not _context_window_error
+ and group_deployments
+ and all(
+ self._deployment_rejects_params(deployment, model, requested_params, request_settings)
+ for deployment in group_deployments
+ )
+ ):
+ raise litellm.UnsupportedParamsError(
+ message=(
+ f"no deployment of model={model} supports {sorted(requested_params)}. "
+ "To drop these, set `litellm.drop_params=True` or for proxy `litellm_settings: drop_params: true`, "
+ f"or send allowed_openai_params={sorted(requested_params)} to pass them through"
+ ),
+ model=model,
+ )
if _rate_limit_error is True: # allow generic fallback logic to take place
raise RouterRateLimitErrorBasic(
model=model,
@@ -13400,9 +13480,9 @@ class Router:
model=model,
llm_provider="",
)
- if len(invalid_model_indices) > 0:
+ if len(excluded_indices) > 0:
# Single-pass filter using set for O(1) lookups (avoids O(n^2) from repeated pops)
- _returned_deployments = [d for i, d in enumerate(_returned_deployments) if i not in invalid_model_indices]
+ _returned_deployments = [d for i, d in enumerate(_returned_deployments) if i not in excluded_indices]
return _returned_deployments
@@ -13825,6 +13905,10 @@ class Router:
)
return healthy_deployments
+ request_deployments: Final = cast( # cast-ok: router deployments are plain dicts
+ Sequence[DeploymentTypedDict], healthy_deployments
+ )
+
# Health-check-based filtering (before cooldown)
healthy_deployments = await self._async_filter_health_check_unhealthy_deployments(
healthy_deployments=healthy_deployments,
@@ -13884,6 +13968,7 @@ class Router:
request_kwargs=request_kwargs,
),
skip_inline_token_count=True,
+ request_deployments=request_deployments,
)
# check if user wants to do tag based routing
healthy_deployments = await get_deployments_for_tag(
@@ -15050,6 +15135,9 @@ class Router:
return healthy_deployments
parent_otel_span: Final[Span | None] = get_parent_otel_span_from_kwargs(request_kwargs)
+ request_deployments: Final = cast( # cast-ok: router deployments are plain dicts
+ Sequence[DeploymentTypedDict], healthy_deployments
+ )
# Health-check-based filtering (before cooldown)
healthy_deployments = self._filter_health_check_unhealthy_deployments(
@@ -15081,6 +15169,7 @@ class Router:
messages=messages,
input=input,
request_kwargs=request_kwargs,
+ request_deployments=request_deployments,
)
## ORDER FILTERING ## -> if user set 'order' in deployments, return deployments with lowest order (e.g. order=1 > order=2)
@@ -15244,6 +15333,9 @@ class Router:
# 4. Apply health-check and cooldown filtering
parent_otel_span: Final[Span | None] = get_parent_otel_span_from_kwargs(request_kwargs)
+ request_deployments: Final = cast( # cast-ok: router deployments are plain dicts
+ Sequence[DeploymentTypedDict], pass_through_deployments
+ )
pass_through_deployments = self._filter_health_check_unhealthy_deployments(
healthy_deployments=pass_through_deployments,
parent_otel_span=parent_otel_span,
@@ -15265,6 +15357,7 @@ class Router:
messages=messages,
input=input,
request_kwargs=request_kwargs,
+ request_deployments=request_deployments,
)
if self._is_priority_routing_group(model):
diff --git a/tests/code_coverage_tests/router_code_coverage.py b/tests/code_coverage_tests/router_code_coverage.py
index 2fd2549c0ac..a3ed70f4a56 100644
--- a/tests/code_coverage_tests/router_code_coverage.py
+++ b/tests/code_coverage_tests/router_code_coverage.py
@@ -114,6 +114,13 @@ ignored_function_names = [
"_deployment_that_just_failed", # Tested through the same-boundary hop test in test_router_order_fallback.py
"_collect_ptu_share_teams", # Cached behind team_ptu_ceiling, tested through the live model list test in test_router.py
"_resolve_team_ptu_ceiling", # Cached behind team_ptu_ceiling, tested through the live model list test in test_router.py
+ "_resolve_pre_call_check_input_tokens", # Tested through the token-count failure pre-call check tests in test_router.py
+ "_params_neither_dropped_nor_allowed", # Tested through the allowed-or-dropped param pre-call check tests in test_router.py
+ "_deployment_rejects_params", # Tested through the unsupported-param pre-call check tests in test_router.py
+ "_deployment_lacks_params", # Tested through the unsupported-param pre-call check tests in test_router.py
+ "_pre_call_check_requested_chat_params", # Tested through the unsupported-param pre-call check tests in test_router.py
+ "_deployment_supports_param", # Tested through the deployment-capability pre-call check tests in test_router.py
+ "_capability_model_and_provider", # Tested through the authenticating-provider pre-call check test in test_router.py
"_exact_base_model_max_input_tokens", # Tested through get_router_model_info in test_router_model_cost_isolation.py
"_base_model_widened_window", # Tested through get_router_model_info in test_router_model_cost_isolation.py
"_provider_model_id", # Tested through get_router_model_info in test_router_model_cost_isolation.py
diff --git a/tests/integration/routing/test_end_user_region_routing.py b/tests/integration/routing/test_end_user_region_routing.py
index 16638d04bd8..d8ba2da042a 100644
--- a/tests/integration/routing/test_end_user_region_routing.py
+++ b/tests/integration/routing/test_end_user_region_routing.py
@@ -1,5 +1,5 @@
import uuid
-from collections.abc import Iterator
+from collections.abc import Callable, Iterator
from pathlib import Path
from typing import Final
@@ -8,12 +8,17 @@ import pytest
import yaml
from integration._support.client import Gateway, gateway_from_environment
from integration._support.process import owned_proxy
+from pydantic import JsonValue
pytestmark: Final = pytest.mark.timeout(180)
MODEL: Final = "regional-model"
UPSTREAM_BY_REGION: Final = {"eu": "regional-eu-upstream", "us": "regional-us-upstream"}
CALLS: Final = 5
+UNCOUNTABLE_MODEL: Final = "regional-uncountable-model"
+PINNED_REGION: Final = "eu"
+WEIGHT_BY_REGION: Final = {"eu": 1, "us": 99}
+SILENT_WAV: Final = "UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAIA+AAACABAAZGF0YQAAAAA="
@pytest.fixture(scope="module")
@@ -22,16 +27,32 @@ def candidate(tmp_path_factory: pytest.TempPathFactory) -> Iterator[Gateway]:
with gateway_from_environment() as base:
config: Final = yaml.safe_load(Path("tests/integration/proxy_config.yaml").read_text())
config["model_list"] = [
- {
- "model_name": MODEL,
- "litellm_params": {
- "model": f"openai/{upstream}",
- "api_base": f"{base.upstream_url}/v1",
- "api_key": "synthetic-region-key",
- "region_name": region,
- },
- }
- for region, upstream in UPSTREAM_BY_REGION.items()
+ *(
+ {
+ "model_name": MODEL,
+ "litellm_params": {
+ "model": f"openai/{upstream}",
+ "api_base": f"{base.upstream_url}/v1",
+ "api_key": "synthetic-region-key",
+ "region_name": region,
+ },
+ }
+ for region, upstream in UPSTREAM_BY_REGION.items()
+ ),
+ *(
+ {
+ "model_name": UNCOUNTABLE_MODEL,
+ "litellm_params": {
+ "model": f"openai/{upstream}",
+ "api_base": f"{base.upstream_url}/v1",
+ "api_key": "synthetic-region-key",
+ "region_name": region,
+ "weight": WEIGHT_BY_REGION[region],
+ },
+ "model_info": {"id": f"{UNCOUNTABLE_MODEL}-{region}", "max_input_tokens": 128000},
+ }
+ for region, upstream in UPSTREAM_BY_REGION.items()
+ ),
]
config["router_settings"] = {**config["router_settings"], "enable_pre_call_checks": True}
path: Final = directory / "region-routing.yaml"
@@ -70,3 +91,55 @@ def test_an_end_users_allowed_region_pins_every_call_to_that_regions_deployment(
assert [response.headers.get("x-litellm-model-region") for response in responses] == [region] * CALLS
observed: Final = upstream.get("/__observations").json()["requests"]
assert [request["body"]["model"] for request in observed] == [UPSTREAM_BY_REGION[region]] * CALLS
+
+
+def _uncountable_chat(marker: str, end_user: str) -> tuple[str, dict[str, JsonValue]]:
+ return (
+ "/v1/chat/completions",
+ {
+ "model": UNCOUNTABLE_MODEL,
+ "user": end_user,
+ "messages": [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": f"region {marker}"},
+ {"type": "input_audio", "input_audio": {"data": SILENT_WAV, "format": "wav"}},
+ ],
+ }
+ ],
+ },
+ )
+
+
+def _uncountable_embedding(marker: str, end_user: str) -> tuple[str, dict[str, JsonValue]]:
+ return "/v1/embeddings", {"model": UNCOUNTABLE_MODEL, "user": end_user, "input": [f"region {marker}", marker]}
+
+
+ ("build", "recorded_chat_calls"),
+ [
+ pytest.param(_uncountable_chat, CALLS, id="chat-input-audio"),
+ pytest.param(_uncountable_embedding, 0, id="embeddings-list-input"),
+ ],
+)
+def test_an_uncountable_prompt_still_pins_an_end_user_to_their_region(
+ candidate: Gateway, build: Callable[[str, str], tuple[str, dict[str, JsonValue]]], recorded_chat_calls: int
+) -> None:
+ with (
+ candidate.scenario() as scenario,
+ httpx.Client(base_url=candidate.upstream_url, timeout=5, trust_env=False) as upstream,
+ ):
+ end_user: Final = f"integration-end-user-{uuid.uuid4().hex}"
+ candidate.post("/end_user/new", {"user_id": end_user, "allowed_model_region": PINNED_REGION})
+ scenario.cleanups.callback(candidate.post, "/end_user/delete", {"user_ids": [end_user]})
+ key: Final = scenario.key(models=[UNCOUNTABLE_MODEL])
+ upstream.get("/__observations").raise_for_status()
+ requests: Final = tuple(build(uuid.uuid4().hex, end_user) for _ in range(CALLS))
+ responses: Final = tuple(candidate.request("POST", path, body, key=key) for path, body in requests)
+ assert [response.status_code for response in responses] == [200] * CALLS, [r.text for r in responses]
+ pinned_deployment: Final = f"{UNCOUNTABLE_MODEL}-{PINNED_REGION}"
+ assert [response.headers.get("x-litellm-model-id") for response in responses] == [pinned_deployment] * CALLS
+ observed: Final = upstream.get("/__observations").json()["requests"]
+ pinned_upstream: Final = UPSTREAM_BY_REGION[PINNED_REGION]
+ assert [request["body"]["model"] for request in observed] == [pinned_upstream] * recorded_chat_calls
diff --git a/tests/integration/routing/test_pre_call_response_format_filter.py b/tests/integration/routing/test_pre_call_response_format_filter.py
new file mode 100644
index 00000000000..24a4434fb5a
--- /dev/null
+++ b/tests/integration/routing/test_pre_call_response_format_filter.py
@@ -0,0 +1,161 @@
+import uuid
+from collections.abc import Iterator, Mapping
+from pathlib import Path
+from typing import Final
+
+import httpx
+import pytest
+import yaml
+from integration._support.client import Gateway, gateway_from_environment
+from integration._support.process import owned_proxy
+from pydantic import JsonValue
+
+pytestmark: Final = pytest.mark.timeout(180)
+
+LACKS_JSON_MODE: Final = "gpt-4"
+TAKES_JSON_MODE: Final = "gpt-4o-mini"
+UNSUPPORTED: Final = "json-mode-unsupported"
+DROPPING: Final = "json-mode-dropped"
+MIXED: Final = "json-mode-mixed"
+FALLBACK_SOURCE: Final = "json-mode-fallback-source"
+SMALL_WINDOW: Final = "json-mode-small-window"
+FALLBACK_TARGET: Final = "json-mode-fallback-target"
+JSON_MODE: Final[Mapping[str, JsonValue]] = {"type": "json_object"}
+CALLS: Final = 4
+SMALL_WINDOW_TOKENS: Final = 50
+
+
+def _deployment(group: str, upstream_model: str, upstream_url: str, **params: JsonValue) -> dict[str, JsonValue]:
+ return {
+ "model_name": group,
+ "litellm_params": {
+ "model": f"openai/{upstream_model}",
+ "api_base": f"{upstream_url}/v1",
+ "api_key": "synthetic-json-mode-key",
+ **params,
+ },
+ }
+
+
[email protected](scope="module")
+def candidate(tmp_path_factory: pytest.TempPathFactory) -> Iterator[Gateway]:
+ directory: Final = tmp_path_factory.mktemp("json-mode-filter")
+ with gateway_from_environment() as base:
+ config: Final = yaml.safe_load(Path("tests/integration/proxy_config.yaml").read_text())
+ url: Final = base.upstream_url
+ config["model_list"] = [
+ _deployment(UNSUPPORTED, LACKS_JSON_MODE, url),
+ _deployment(DROPPING, LACKS_JSON_MODE, url, drop_params=True),
+ _deployment(MIXED, LACKS_JSON_MODE, url),
+ _deployment(MIXED, TAKES_JSON_MODE, url),
+ _deployment(FALLBACK_SOURCE, LACKS_JSON_MODE, url),
+ {
+ **_deployment(SMALL_WINDOW, LACKS_JSON_MODE, url),
+ "model_info": {"max_input_tokens": SMALL_WINDOW_TOKENS},
+ },
+ _deployment(FALLBACK_TARGET, TAKES_JSON_MODE, url),
+ ]
+ config["router_settings"] = {
+ **config["router_settings"],
+ "enable_pre_call_checks": True,
+ "fallbacks": [{FALLBACK_SOURCE: [FALLBACK_TARGET]}],
+ "context_window_fallbacks": [{SMALL_WINDOW: [FALLBACK_TARGET]}],
+ }
+ path: Final = directory / "json-mode-filter.yaml"
+ path.write_text(yaml.safe_dump(config))
+ with owned_proxy(base, directory, {}, config=path) as proxy:
+ yield proxy
+
+
+def _json_mode_chat(group: str, text: str, **extra: JsonValue) -> dict[str, JsonValue]:
+ return {
+ "model": group,
+ "response_format": dict(JSON_MODE),
+ "messages": [{"role": "user", "content": f"Answer in JSON. {text}"}],
+ **extra,
+ }
+
+
+def _drain(upstream: httpx.Client) -> list[dict[str, JsonValue]]:
+ response: Final = upstream.get("/__observations")
+ response.raise_for_status()
+ return [request["body"] for request in response.json()["requests"]]
+
+
+def upstream(candidate: Gateway) -> Iterator[httpx.Client]:
+ with httpx.Client(base_url=candidate.upstream_url, timeout=5, trust_env=False) as client:
+ _drain(client)
+ yield client
+
+
[email protected]("stream", [False, True], ids=["non-streaming", "streaming"])
+def test_json_mode_answers_400_without_an_upstream_call_when_no_deployment_takes_it(
+ candidate: Gateway, upstream: httpx.Client, stream: bool
+) -> None:
+ response: Final = candidate.request(
+ "POST", "/v1/chat/completions", _json_mode_chat(UNSUPPORTED, uuid.uuid4().hex, stream=stream)
+ )
+
+ assert response.status_code == 400, response.text
+ assert _drain(upstream) == []
+
+
+ ("group", "extra", "forwarded_format"),
+ [
+ pytest.param(DROPPING, {}, None, id="deployment-drop-params"),
+ pytest.param(UNSUPPORTED, {"allowed_openai_params": ["response_format"]}, JSON_MODE, id="request-allowlist"),
+ pytest.param(UNSUPPORTED, {"drop_params": True}, None, id="request-drop-params"),
+ ],
+)
+def test_json_mode_reaches_a_deployment_that_lacks_it_once_drop_or_allow_is_set(
+ candidate: Gateway,
+ upstream: httpx.Client,
+ group: str,
+ extra: Mapping[str, JsonValue],
+ forwarded_format: Mapping[str, JsonValue] | None,
+) -> None:
+ response: Final = candidate.request(
+ "POST", "/v1/chat/completions", _json_mode_chat(group, uuid.uuid4().hex, **extra)
+ )
+
+ assert response.status_code == 200, response.text
+ received: Final = _drain(upstream)
+ assert [body["model"] for body in received] == [LACKS_JSON_MODE]
+ assert received[0].get("response_format") == forwarded_format
+
+
+def test_json_mode_in_a_mixed_group_always_reaches_the_deployment_that_takes_it(
+ candidate: Gateway, upstream: httpx.Client
+) -> None:
+ responses: Final = tuple(
+ candidate.request("POST", "/v1/chat/completions", _json_mode_chat(MIXED, uuid.uuid4().hex))
+ for _ in range(CALLS)
+ )
+
+ assert [response.status_code for response in responses] == [200] * CALLS, [r.text for r in responses]
+ received: Final = _drain(upstream)
+ assert [(body["model"], body.get("response_format")) for body in received] == [
+ (TAKES_JSON_MODE, dict(JSON_MODE))
+ ] * CALLS
+
+
+ ("group", "text"),
+ [
+ pytest.param(FALLBACK_SOURCE, "short", id="generic-fallback"),
+ pytest.param(SMALL_WINDOW, "padding " * (4 * SMALL_WINDOW_TOKENS), id="context-window-fallback"),
+ ],
+)
+def test_json_mode_falls_back_to_a_group_that_takes_it(
+ candidate: Gateway, upstream: httpx.Client, group: str, text: str
+) -> None:
+ response: Final = candidate.request(
+ "POST", "/v1/chat/completions", _json_mode_chat(group, f"{uuid.uuid4().hex} {text}")
+ )
+
+ assert response.status_code == 200, response.text
+ assert [(body["model"], body.get("response_format")) for body in _drain(upstream)] == [
+ (TAKES_JSON_MODE, dict(JSON_MODE))
+ ]
diff --git a/tests/unit/test_router/test_router.py b/tests/unit/test_router/test_router.py
index 5a6da70d756..3bd051d71d4 100644
--- a/tests/unit/test_router/test_router.py
+++ b/tests/unit/test_router/test_router.py
@@ -11,6 +11,7 @@ import threading
import warnings
from collections.abc import AsyncIterable, AsyncIterator, Awaitable, Callable, Mapping
from datetime import datetime, timedelta, timezone
+from pathlib import Path
from types import SimpleNamespace
from typing import TYPE_CHECKING, Final, Literal, cast
from unittest.mock import AsyncMock, MagicMock, Mock, patch
@@ -82,6 +83,7 @@ from litellm.types.router import (
ModelInfo,
PreRoutingHookResponse,
RetryPolicy,
+ RouterRateLimitError,
RoutingContext,
)
from litellm.litellm_core_utils.logging_worker import GLOBAL_LOGGING_WORKER
@@ -12190,7 +12192,7 @@ def test_pre_call_checks_uses_deployment_model_when_model_info_lookup_raises(mon
model="custom-alias",
healthy_deployments=deployments,
messages=[{"role": "user", "content": "hi"}],
- request_kwargs={},
+ request_kwargs={"response_format": {"type": "json_object"}},
)
assert len(result) == 1
@@ -26764,3 +26766,471 @@ def test_completion_streams_a_wrapper_that_hands_iteration_to_another_iterator()
streamed = list(response)
assert streamed == chunks
+
+
+_PRE_CALL_CHECK_UNPARSEABLE_MESSAGES: Final = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "image_url", "image_url": {"detail": "not-a-real-detail-value"}},
+ ],
+ }
+]
+
+
+def test_pre_call_checks_filters_deployment_when_token_count_exceeds_limit():
+ model_list: Final = [
+ {
+ "model_name": "fake-openai-endpoint",
+ "litellm_params": {"model": "openai/my-fake-model", "api_key": "my-fake-key"},
+ "model_info": {"id": "small", "max_input_tokens": 5},
+ },
+ {
+ "model_name": "fake-openai-endpoint",
+ "litellm_params": {"model": "openai/my-other-fake-model", "api_key": "my-fake-key"},
+ "model_info": {"id": "large", "max_input_tokens": 10000},
+ },
+ ]
+ router: Final = Router(model_list=model_list, enable_pre_call_checks=True, num_retries=0)
+
+ filtered: Final = router._pre_call_checks(
+ model="fake-openai-endpoint",
+ healthy_deployments=model_list,
+ messages=[{"role": "user", "content": " ".join(["word"] * 100)}],
+ )
+
+ assert [d["model_info"]["id"] for d in filtered] == ["large"]
+
+
+def test_pre_call_checks_rpm_check_still_enforced_when_token_counting_fails():
+ from litellm.types.router import RouterRateLimitErrorBasic
+
+ model_list: Final = [
+ {
+ "model_name": "fake-openai-endpoint",
+ "litellm_params": {"model": "openai/my-fake-model", "api_key": "my-fake-key", "rpm": 0},
+ "model_info": {"max_input_tokens": 100},
+ },
+ ]
+ router: Final = Router(model_list=model_list, enable_pre_call_checks=True, num_retries=0)
+
+ with pytest.raises(RouterRateLimitErrorBasic):
+ router._pre_call_checks(
+ model="fake-openai-endpoint",
+ healthy_deployments=model_list,
+ messages=_PRE_CALL_CHECK_UNPARSEABLE_MESSAGES,
+ )
+
+
+def test_pre_call_checks_context_window_check_is_skipped_but_not_fatal_when_token_counting_fails():
+ model_list: Final = [
+ {
+ "model_name": "fake-openai-endpoint",
+ "litellm_params": {"model": "openai/my-fake-model", "api_key": "my-fake-key"},
+ "model_info": {"max_input_tokens": 100},
+ },
+ ]
+ router: Final = Router(model_list=model_list, enable_pre_call_checks=True, num_retries=0)
+
+ filtered: Final = router._pre_call_checks(
+ model="fake-openai-endpoint",
+ healthy_deployments=model_list,
+ messages=_PRE_CALL_CHECK_UNPARSEABLE_MESSAGES,
+ )
+
+ assert len(filtered) == 1
+
+
+def test_pre_call_checks_keeps_unsupported_param_filter_when_token_counting_fails(monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setattr(litellm, "drop_params", False)
+ no_json_mode_model: Final = "gpt-3.5-turbo-16k"
+ assert "response_format" not in (
+ litellm.get_supported_openai_params(model=no_json_mode_model, custom_llm_provider="openai") or []
+ )
+ model_list: Final = [
+ {
+ "model_name": "fake-openai-endpoint",
+ "litellm_params": {"model": f"openai/{deployment_model}", "api_key": "my-fake-key"},
+ "model_info": {"id": deployment_model, "max_input_tokens": 100},
+ }
+ for deployment_model in (no_json_mode_model, "gpt-4o")
+ ]
+ router: Final = Router(model_list=model_list, enable_pre_call_checks=True, num_retries=0)
+
+ filtered: Final = router._pre_call_checks(
+ model="fake-openai-endpoint",
+ healthy_deployments=model_list,
+ messages=_PRE_CALL_CHECK_UNPARSEABLE_MESSAGES,
+ request_kwargs={"response_format": {"type": "json_object"}},
+ )
+
+ assert [d["model_info"]["id"] for d in filtered] == ["gpt-4o"]
+
+
+async def test_async_get_healthy_deployments_keeps_region_check_when_token_counting_fails():
+ model_list: Final = [
+ {
+ "model_name": "fake-openai-endpoint",
+ "litellm_params": {"model": "openai/my-fake-model", "api_key": "my-fake-key", "region_name": region},
+ "model_info": {"id": f"{region}-deployment", "max_input_tokens": 100},
+ }
+ for region in ("eu", "us")
+ ]
+ router: Final = Router(model_list=model_list, enable_pre_call_checks=True, num_retries=0)
+
+ healthy: Final = await router.async_get_healthy_deployments(
+ model="fake-openai-endpoint",
+ request_kwargs={"allowed_model_region": "eu"},
+ messages=_PRE_CALL_CHECK_UNPARSEABLE_MESSAGES,
+ input=None,
+ specific_deployment=False,
+ parent_otel_span=None,
+ )
+
+ assert [deployment["model_info"]["id"] for deployment in healthy] == ["eu-deployment"]
+
+
+ "messages",
+ [_PRE_CALL_CHECK_UNPARSEABLE_MESSAGES, [{"role": "user", "content": "hi"}]],
+ ids=["uncountable", "countable"],
+)
+def test_completion_answers_400_when_no_deployment_supports_the_requested_param(
+ monkeypatch: pytest.MonkeyPatch, messages: list[dict[str, object]]
+):
+ monkeypatch.setattr(litellm, "drop_params", False)
+ router: Final = Router(
+ model_list=[
+ {
+ "model_name": "no-json-mode",
+ "litellm_params": {"model": "openai/gpt-3.5-turbo-16k", "api_key": "my-fake-key"},
+ "model_info": {"max_input_tokens": 100},
+ }
+ ],
+ enable_pre_call_checks=True,
+ num_retries=2,
+ )
+
+ with pytest.raises(litellm.UnsupportedParamsError) as error:
+ router.completion(
+ model="no-json-mode",
+ messages=messages,
+ response_format={"type": "json_object"},
+ mock_response="should not be served",
+ )
+
+ assert error.value.status_code == 400
+ assert "allowed_openai_params" in str(error.value)
+
+
+ ("deployment_params", "request_kwargs"),
+ [
+ ({}, {"allowed_openai_params": ["response_format"]}),
+ ({}, {"drop_params": True}),
+ ({}, {"additional_drop_params": ["response_format"]}),
+ ({"allowed_openai_params": ["response_format"]}, {}),
+ ({"drop_params": True}, {}),
+ ],
+ ids=["request-allowlist", "request-drop", "request-additional-drop", "deployment-allowlist", "deployment-drop"],
+)
+def test_pre_call_checks_keeps_deployment_whose_unsupported_param_is_allowed_or_dropped(
+ monkeypatch: pytest.MonkeyPatch, deployment_params: Mapping[str, object], request_kwargs: Mapping[str, object]
+):
+ monkeypatch.setattr(litellm, "drop_params", False)
+ model_list: Final = [
+ {
+ "model_name": "no-json-mode",
+ "litellm_params": {"model": "openai/gpt-3.5-turbo-16k", "api_key": "my-fake-key", **deployment_params},
+ "model_info": {"id": "only", "max_input_tokens": 100},
+ }
+ ]
+ router: Final = Router(model_list=model_list, enable_pre_call_checks=True, num_retries=0)
+
+ filtered: Final = router._pre_call_checks(
+ model="no-json-mode",
+ healthy_deployments=model_list,
+ messages=[{"role": "user", "content": "hi"}],
+ request_kwargs={"response_format": {"type": "json_object"}, **request_kwargs},
+ )
+
+ assert [d["model_info"]["id"] for d in filtered] == ["only"]
+
+
+def test_pre_call_checks_keeps_retryable_429_when_a_cooling_down_deployment_supports_the_param(monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setattr(litellm, "drop_params", False)
+ model_list: Final = [
+ {
+ "model_name": "mixed-json-mode",
+ "litellm_params": {"model": f"openai/{deployment_model}", "api_key": "my-fake-key"},
+ "model_info": {"id": deployment_model, "max_input_tokens": 100},
+ }
+ for deployment_model in ("gpt-3.5-turbo-16k", "gpt-4o")
+ ]
+ router: Final = Router(model_list=model_list, enable_pre_call_checks=True, num_retries=0)
+ without_json_mode: Final = [d for d in router.model_list if d["model_info"]["id"] == "gpt-3.5-turbo-16k"]
+
+ filtered: Final = router._pre_call_checks(
+ model="mixed-json-mode",
+ healthy_deployments=without_json_mode,
+ messages=[{"role": "user", "content": "hi"}],
+ request_kwargs={"response_format": {"type": "json_object"}},
+ )
+
+ assert filtered == []
+
+
+def test_completion_uses_context_window_fallback_when_the_small_deployment_also_lacks_the_param(monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setattr(litellm, "drop_params", False)
+ router: Final = Router(
+ model_list=[
+ {
+ "model_name": "small",
+ "litellm_params": {"model": "openai/gpt-3.5-turbo-16k", "api_key": "my-fake-key"},
+ "model_info": {"id": "small-id", "max_input_tokens": 5},
+ },
+ {
+ "model_name": "big",
+ "litellm_params": {"model": "openai/gpt-4o", "api_key": "my-fake-key"},
+ "model_info": {"id": "big-id"},
+ },
+ ],
+ enable_pre_call_checks=True,
+ context_window_fallbacks=[{"small": ["big"]}],
+ num_retries=0,
+ )
+
+ response: Final = router.completion(
+ model="small",
+ messages=[{"role": "user", "content": "hi " * 50}],
+ response_format={"type": "json_object"},
+ mock_response="served by the fallback",
+ )
+
+ assert response._hidden_params["model_id"] == "big-id"
+
+
+ ("deployment_params", "request_kwargs"),
+ [
+ ({}, {"allowed_openai_params": ["response_format"]}),
+ ({}, {"drop_params": True}),
+ ({}, {"additional_drop_params": ["response_format"]}),
+ ({"drop_params": True}, {}),
+ ({"allowed_openai_params": ["response_format"]}, {}),
+ ],
+ ids=["request-allowlist", "request-drop", "request-additional-drop", "deployment-drop", "deployment-allowlist"],
+)
+def test_pre_call_checks_prefers_a_deployment_that_takes_the_param_over_dropping_it(
+ monkeypatch: pytest.MonkeyPatch, deployment_params: Mapping[str, object], request_kwargs: Mapping[str, object]
+):
+ monkeypatch.setattr(litellm, "drop_params", False)
+ model_list: Final = [
+ {
+ "model_name": "mixed-json-mode",
+ "litellm_params": {"model": "openai/gpt-3.5-turbo-16k", "api_key": "my-fake-key", **deployment_params},
+ "model_info": {"id": "gpt-3.5-turbo-16k", "max_input_tokens": 100},
+ },
+ {
+ "model_name": "mixed-json-mode",
+ "litellm_params": {"model": "openai/gpt-4o", "api_key": "my-fake-key"},
+ "model_info": {"id": "gpt-4o", "max_input_tokens": 100},
+ },
+ ]
+ router: Final = Router(model_list=model_list, enable_pre_call_checks=True, num_retries=0)
+
+ filtered: Final = router._pre_call_checks(
+ model="mixed-json-mode",
+ healthy_deployments=model_list,
+ messages=[{"role": "user", "content": "hi"}],
+ request_kwargs={"response_format": {"type": "json_object"}, **request_kwargs},
+ )
+
+ assert [d["model_info"]["id"] for d in filtered] == ["gpt-4o"]
+
+
+def test_pre_call_checks_drops_the_param_when_the_capable_deployment_is_outside_the_region(monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setattr(litellm, "drop_params", False)
+ model_list: Final = [
+ {
+ "model_name": "regional-json-mode",
+ "litellm_params": {"model": "openai/gpt-3.5-turbo-16k", "api_key": "my-fake-key", "region_name": "eu"},
+ "model_info": {"id": "eu-without-json-mode", "max_input_tokens": 100},
+ },
+ {
+ "model_name": "regional-json-mode",
+ "litellm_params": {"model": "openai/gpt-4o", "api_key": "my-fake-key", "region_name": "us"},
+ "model_info": {"id": "us-with-json-mode", "max_input_tokens": 100},
+ },
+ ]
+ router: Final = Router(model_list=model_list, enable_pre_call_checks=True, num_retries=0)
+
+ filtered: Final = router._pre_call_checks(
+ model="regional-json-mode",
+ healthy_deployments=model_list,
+ messages=[{"role": "user", "content": "hi"}],
+ request_kwargs={"response_format": {"type": "json_object"}, "drop_params": True, "allowed_model_region": "eu"},
+ )
+
+ assert [d["model_info"]["id"] for d in filtered] == ["eu-without-json-mode"]
+
+
+def test_pre_call_checks_filters_an_authenticating_provider_deployment_that_lacks_the_param(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+):
+ monkeypatch.setattr(litellm, "drop_params", False)
+ monkeypatch.setenv("GITHUB_COPILOT_TOKEN_DIR", str(tmp_path))
+ (tmp_path / "api-key.json").write_text(json.dumps({"token": "tid=test", "expires_at": 4102444800}))
+ model_list: Final = [
+ {
+ "model_name": "mixed-json-mode",
+ "litellm_params": {"model": "github_copilot/gpt-4"},
+ "model_info": {"id": "copilot-gpt-4", "max_input_tokens": 100},
+ },
+ {
+ "model_name": "mixed-json-mode",
+ "litellm_params": {"model": "openai/gpt-4o", "api_key": "my-fake-key"},
+ "model_info": {"id": "gpt-4o", "max_input_tokens": 100},
+ },
+ ]
+ router: Final = Router(model_list=model_list, enable_pre_call_checks=True, num_retries=0)
+
+ filtered: Final = router._pre_call_checks(
+ model="mixed-json-mode",
+ healthy_deployments=model_list,
+ messages=[{"role": "user", "content": "hi"}],
+ request_kwargs={"response_format": {"type": "json_object"}},
+ )
+
+ assert [d["model_info"]["id"] for d in filtered] == ["gpt-4o"]
+
+
+def test_pre_call_checks_answers_400_when_the_group_name_lists_no_deployments(monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setattr(litellm, "drop_params", False)
+ model_list: Final = [
+ {
+ "model_name": "no-json-mode",
+ "litellm_params": {"model": "openai/gpt-3.5-turbo-16k", "api_key": "my-fake-key"},
+ "model_info": {"id": "only", "max_input_tokens": 100},
+ }
+ ]
+ router: Final = Router(model_list=model_list, enable_pre_call_checks=True, num_retries=0)
+
+ with pytest.raises(litellm.UnsupportedParamsError):
+ router._pre_call_checks(
+ model="team-public-name",
+ healthy_deployments=model_list,
+ messages=[{"role": "user", "content": "hi"}],
+ request_kwargs={"response_format": {"type": "json_object"}},
+ )
+
+
+def test_pre_call_checks_lets_a_request_setting_replace_the_deployment_setting(monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setattr(litellm, "drop_params", False)
+ model_list: Final = [
+ {
+ "model_name": "no-json-mode",
+ "litellm_params": {"model": "openai/gpt-3.5-turbo-16k", "api_key": "my-fake-key", "drop_params": True},
+ "model_info": {"id": "drops-it", "max_input_tokens": 100},
+ },
+ {
+ "model_name": "no-json-mode",
+ "litellm_params": {
+ "model": "openai/gpt-4",
+ "api_key": "my-fake-key",
+ "allowed_openai_params": ["response_format"],
+ },
+ "model_info": {"id": "allows-it", "max_input_tokens": 100},
+ },
+ ]
+ router: Final = Router(model_list=model_list, enable_pre_call_checks=True, num_retries=0)
+
+ filtered: Final = router._pre_call_checks(
+ model="no-json-mode",
+ healthy_deployments=model_list,
+ messages=[{"role": "user", "content": "hi"}],
+ request_kwargs={"response_format": {"type": "json_object"}, "drop_params": False},
+ )
+
+ assert [d["model_info"]["id"] for d in filtered] == ["allows-it"]
+
+
+async def _select_team_json_deployment(router: Router, entrypoint: str, selection: Mapping[str, object]) -> object:
+ if entrypoint == "async":
+ return await router.async_get_available_deployment(**selection)
+ if entrypoint == "sync":
+ return router.get_available_deployment(**selection)
+ return router.get_available_deployment_for_pass_through(**selection)
+
+
[email protected]("entrypoint", ["sync", "async", "pass-through"])
+ ("deployment_models", "cooled_down", "expected_error"),
+ [
+ pytest.param(("gpt-3.5-turbo-16k", "gpt-4"), (), litellm.UnsupportedParamsError, id="none-takes-it"),
+ pytest.param(("gpt-3.5-turbo-16k", "gpt-4o"), ("gpt-4o",), RouterRateLimitError, id="capable-cooling-down"),
+ ],
+)
+async def test_team_public_model_name_answers_400_only_when_no_team_deployment_takes_the_param(
+ monkeypatch: pytest.MonkeyPatch,
+ entrypoint: str,
+ deployment_models: tuple[str, str],
+ cooled_down: tuple[str, ...],
+ expected_error: type[Exception],
+):
+ monkeypatch.setattr(litellm, "drop_params", False)
+ router: Final = Router(
+ model_list=[
+ {
+ "model_name": f"team-json-{deployment_model}",
+ "litellm_params": {
+ "model": f"openai/{deployment_model}",
+ "api_key": "my-fake-key",
+ "use_in_pass_through": True,
+ },
+ "model_info": {
+ "id": deployment_model,
+ "max_input_tokens": 100,
+ "team_id": "json-team",
+ "team_public_model_name": "team-json",
+ },
+ }
+ for deployment_model in deployment_models
+ ],
+ enable_pre_call_checks=True,
+ num_retries=0,
+ )
+ _cool_down(router, *cooled_down)
+ selection: Final = {
+ "model": "team-json",
+ "messages": [{"role": "user", "content": "hi"}],
+ "request_kwargs": {
+ "metadata": {"user_api_key_team_id": "json-team"},
+ "response_format": {"type": "json_object"},
+ },
+ }
+
+ with pytest.raises(expected_error):
+ await _select_team_json_deployment(router, entrypoint, selection)
+
+
+def test_pre_call_checks_ignores_an_image_response_format_string(monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setattr(litellm, "drop_params", False)
+ model_list: Final = [
+ {
+ "model_name": "image-model",
+ "litellm_params": {"model": "openai/gpt-3.5-turbo-16k", "api_key": "my-fake-key"},
+ "model_info": {"id": "only", "max_input_tokens": 100},
+ }
+ ]
+ router: Final = Router(model_list=model_list, enable_pre_call_checks=True, num_retries=0)
+
+ filtered: Final = router._pre_call_checks(
+ model="image-model",
+ healthy_deployments=model_list,
+ messages=[{"role": "user", "content": "prompt"}],
+ request_kwargs={"response_format": "b64_json"},
+ )
+
+ assert [d["model_info"]["id"] for d in filtered] == ["only"]