The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
Merge remote-tracking branch 'origin/litellm_internal_staging' into litellm_retry_policy_503
ryan-crabbe-berri2de21d06956b
diff --cc litellm/types/router.pyindex e0952d9dd02,7ebd50f1328..6ed9b3efd03--- a/litellm/types/router.py+++ b/litellm/types/router.py@@@ -89,13 -98,26 +98,27 @@@ class RetryPolicy(BaseModel)https://docs.litellm.ai/docs/exception_mapping"""- BadRequestErrorRetries: Optional[int] = None- AuthenticationErrorRetries: Optional[int] = None- TimeoutErrorRetries: Optional[int] = None- RateLimitErrorRetries: Optional[int] = None- ContentPolicyViolationErrorRetries: Optional[int] = None- InternalServerErrorRetries: Optional[int] = None- ServiceUnavailableErrorRetries: Optional[int] = None+ BadRequestErrorRetries: int | None = None+ AuthenticationErrorRetries: int | None = None+ TimeoutErrorRetries: int | None = None+ RateLimitErrorRetries: int | None = None+ ContentPolicyViolationErrorRetries: int | None = None+ InternalServerErrorRetries: int | None = None++ ServiceUnavailableErrorRetries: int | None = None+++ OptionalPreCallChecks = list[+ Literal[+ "prompt_caching",+ "router_budget_limiting",+ "responses_api_deployment_check",+ "deployment_affinity",+ "session_affinity",+ "forward_client_headers_by_model_group",+ "enforce_model_rate_limits",+ "encrypted_content_affinity",+ ]+ ]class UpdateRouterConfig(BaseModel):diff --cc tests/test_litellm/test_router.pyindex c98be9c7d80,5fc96bcfbb1..cb3baf042dd--- a/tests/test_litellm/test_router.py+++ b/tests/test_litellm/test_router.py@@@ -6576,32 -8493,4403 +8493,4434 @@@ def test_model_info_is_active_for_envirmodel_info_is_active_for_environment(model_info={"supported_environments": ["production"]})+ def test_pre_call_checks_uses_deployment_model_when_model_info_lookup_raises(monkeypatch):+ """+ The supported-params check must run against the deployment's own+ provider-qualified model. Resolving the per-deployment model only after the+ model-info lookup leaves it unset whenever that lookup raises (an+ unregistered custom model), so the check falls back to the bare model group+ name and the request dies with 'LLM Provider NOT provided'.+ """+ monkeypatch.setattr(litellm, "drop_params", False)++ router = litellm.Router(+ model_list=[+ {+ "model_name": "custom-alias",+ "litellm_params": {"model": "hosted_vllm/not-in-the-catalog"},+ }+ ],+ enable_pre_call_checks=True,+ )++ def _raise_unmapped(**kwargs):+ raise ValueError("This model isn't mapped yet")++ monkeypatch.setattr(router, "get_router_model_info", _raise_unmapped)++ seen: list[tuple] = []+ original_get_supported_openai_params = litellm.get_supported_openai_params++ def _record(model, custom_llm_provider=None, **kwargs):+ seen.append((model, custom_llm_provider))+ return original_get_supported_openai_params(model=model, custom_llm_provider=custom_llm_provider, **kwargs)++ monkeypatch.setattr(litellm, "get_supported_openai_params", _record)++ deployments = [+ {+ "litellm_params": {"model": "hosted_vllm/not-in-the-catalog"},+ "model_info": {"id": "d1"},+ }+ ]+ result = router._pre_call_checks(+ model="custom-alias",+ healthy_deployments=deployments,+ messages=[{"role": "user", "content": "hi"}],+ request_kwargs={},+ )++ assert len(result) == 1+ assert seen == [("not-in-the-catalog", "hosted_vllm")]+++ def test_pre_call_checks_keeps_deployment_when_provider_is_unresolvable(monkeypatch):+ """+ Pre-call checks filter deployments; they must never be the thing that fails+ a request. A deployment whose provider cannot be resolved simply skips the+ supported-params check instead of raising out of deployment selection.+ """+ monkeypatch.setattr(litellm, "drop_params", False)++ router = litellm.Router(+ model_list=[+ {+ "model_name": "custom-alias",+ "litellm_params": {"model": "gpt-3.5-turbo"},+ }+ ],+ enable_pre_call_checks=True,+ )++ def _raise_no_provider(**kwargs):+ raise litellm.BadRequestError(+ message="LLM Provider NOT provided.",+ model="custom-alias",+ llm_provider="",+ )++ monkeypatch.setattr(litellm, "get_llm_provider", _raise_no_provider)++ deployments = [+ {+ "litellm_params": {"model": "some-unresolvable-model"},+ "model_info": {"id": "d1"},+ }+ ]+ result = router._pre_call_checks(+ model="custom-alias",+ healthy_deployments=deployments,+ messages=[{"role": "user", "content": "hi"}],+ request_kwargs={},+ )++ assert len(result) == 1+++ class TestUpsertDeploymentRollback:+ """+ Regression tests: `upsert_deployment` pops the previous deployment before+ re-adding the edited one. When the re-add raises under+ `ignore_invalid_deployments=True`, the pop must be rolled back so this pod+ keeps serving the previous configuration instead of silently dropping a live+ deployment (the "Error upserting deployment" drop behind the access-group+ reload 500 in the 2-replica e2e suite).+ """++ def test_failed_upsert_keeps_previous_deployment_serving(self):+ from litellm.types.router import Deployment, LiteLLM_Params, ModelInfo++ router = litellm.Router(+ model_list=[+ {+ "model_name": "prod-model",+ "litellm_params": {"model": "gpt-4o", "api_key": "sk-old"},+ "model_info": {"id": "prod-1", "db_model": True},+ }+ ],+ ignore_invalid_deployments=True,+ )++ result = router.upsert_deployment(+ deployment=Deployment(+ model_name="prod-model",+ litellm_params=LiteLLM_Params(model="auto_router/broken"),+ model_info=ModelInfo(id="prod-1", db_model=True),+ )+ )++ assert result is None+ restored = router.get_deployment(model_id="prod-1")+ assert restored is not None+ assert restored.litellm_params.model == "gpt-4o"+ assert [model["model_name"] for model in router.model_list] == ["prod-model"]++ def test_failed_fresh_add_returns_none_without_restore(self):+ from litellm.types.router import Deployment, LiteLLM_Params, ModelInfo++ router = litellm.Router(model_list=[], ignore_invalid_deployments=True)++ result = router.upsert_deployment(+ deployment=Deployment(+ model_name="fresh-router",+ litellm_params=LiteLLM_Params(model="auto_router/broken"),+ model_info=ModelInfo(id="fresh-1", db_model=True),+ )+ )++ assert result is None+ assert router.get_deployment(model_id="fresh-1") is None+ assert router.model_list == []++ def test_restore_re_adds_popped_deployment(self):+ router = litellm.Router(+ model_list=[+ {+ "model_name": "prod-model",+ "litellm_params": {"model": "gpt-4o", "api_key": "sk-old"},+ "model_info": {"id": "prod-1", "db_model": True},+ }+ ],+ ignore_invalid_deployments=True,+ )+ previous = router.get_deployment(model_id="prod-1")+ router.delete_deployment(id="prod-1")+ assert router.has_model_id("prod-1") is False++ router._restore_deployment_after_failed_upsert(+ previous_deployment=previous, model_id="prod-1"+ )++ restored = router.get_deployment(model_id="prod-1")+ assert restored is not None+ assert restored.litellm_params.model == "gpt-4o"++ router._restore_deployment_after_failed_upsert(+ previous_deployment=previous, model_id="prod-1"+ )+ assert len(router.model_list) == 1++ router._restore_deployment_after_failed_upsert(+ previous_deployment=None, model_id="prod-1"+ )+ assert len(router.model_list) == 1+++ class TestUpsertDeploymentRename:+ """+ Issue #38360: renaming a model wrote the new `model_name` to the db, but the reload's+ `upsert_deployment` compared only `litellm_params` and `model_info`. A rename with no+ other edit therefore compared equal and the router kept the old name until a restart,+ so `/model/info` and `/v1/models` served the stale name and the new one was unroutable.+ """++ @staticmethod+ def _router() -> "litellm.Router":+ return litellm.Router(+ model_list=[+ {+ "model_name": "old-name",+ "litellm_params": {"model": "openai/gpt-4o", "api_key": "sk-test"},+ "model_info": {"id": "rename-1", "db_model": True},+ }+ ]+ )++ @staticmethod+ def _deployment(model_name: str, tpm: int | None = None):+ from litellm.types.router import Deployment, LiteLLM_Params, ModelInfo++ return Deployment(+ model_name=model_name,+ litellm_params=LiteLLM_Params(model="openai/gpt-4o", api_key="sk-test", tpm=tpm),+ model_info=ModelInfo(id="rename-1", db_model=True),+ )++ def test_rename_only_updates_the_router(self):+ router = self._router()++ assert router.upsert_deployment(deployment=self._deployment("new-name")) is not None++ assert [model["model_name"] for model in router.model_list] == ["new-name"]+ renamed = router.get_deployment(model_id="rename-1")+ assert renamed is not None+ assert renamed.model_name == "new-name"++ def test_rename_only_makes_the_new_name_routable(self):+ router = self._router()++ router.upsert_deployment(deployment=self._deployment("new-name"))++ assert router.get_model_ids(model_name="new-name") == ["rename-1"]+ assert router.get_model_ids(model_name="old-name") == []++ def test_rename_alongside_another_edit_still_updates(self):+ router = self._router()++ router.upsert_deployment(deployment=self._deployment("new-name", tpm=1234))++ assert router.get_model_ids(model_name="new-name") == ["rename-1"]+ renamed = router.get_deployment(model_id="rename-1")+ assert renamed is not None+ assert renamed.litellm_params.tpm == 1234++ def test_unchanged_deployment_is_still_a_no_op(self):+ router = self._router()++ assert router.upsert_deployment(deployment=self._deployment("old-name")) is None+ assert [model["model_name"] for model in router.model_list] == ["old-name"]+++ class TestConsumedRequestTagsStamp:+ """Issue #36621: when a request's tags select a tagged pre-routing strategy, those+ tags are consumed by the selection; the hook must stamp the rewritten model group so+ tag filtering skips request-body tags there, and must clear the stamp on every+ re-entry (fallbacks reuse the same request_kwargs) so it cannot leak elsewhere."""++ class _RewriteStrategy:+ def __init__(self, rewrite_to: str):+ self.rewrite_to = rewrite_to++ async def async_pre_routing_hook(+ self, model, request_kwargs, messages=None, input=None, specific_deployment=False+ ):+ from litellm.types.router import PreRoutingHookResponse++ return PreRoutingHookResponse(model=self.rewrite_to, messages=messages)++ @classmethod+ def _router(cls, marker_tags=("route",)) -> "litellm.Router":+ from litellm.types.router import TaggedPreRoutingStrategy++ router = litellm.Router(+ model_list=[+ {"model_name": "gpt4o", "litellm_params": {"model": "openai/gpt-4o"}},+ {"model_name": "gemini-flash", "litellm_params": {"model": "gemini/gemini-3.6-flash"}},+ ],+ enable_tag_filtering=True,+ )+ router.auto_routers = {+ "gpt4o": [TaggedPreRoutingStrategy(tags=marker_tags, strategy=cls._RewriteStrategy("gemini-flash"))]+ }+ return router++ @pytest.mark.asyncio+ async def test_stamps_the_rewritten_group_when_request_tags_selected_the_router(self):+ from litellm.constants import CONSUMED_REQUEST_TAGS_METADATA_KEY+ from litellm.types.router import ConsumedRequestTagsStamp++ router = self._router()+ request_kwargs = {"metadata": {"tags": ["route"]}}++ await router.async_pre_routing_hook(model="gpt4o", request_kwargs=request_kwargs)++ assert request_kwargs["metadata"][CONSUMED_REQUEST_TAGS_METADATA_KEY] == ConsumedRequestTagsStamp(+ model_group="gemini-flash", tags=("route",)+ )++ @pytest.mark.asyncio+ async def test_stamps_into_litellm_metadata_when_the_request_uses_that_bucket(self):+ from litellm.constants import CONSUMED_REQUEST_TAGS_METADATA_KEY+ from litellm.types.router import ConsumedRequestTagsStamp++ router = self._router()+ request_kwargs = {"litellm_metadata": {"tags": ["route"]}}++ await router.async_pre_routing_hook(model="gpt4o", request_kwargs=request_kwargs)++ assert request_kwargs["litellm_metadata"][CONSUMED_REQUEST_TAGS_METADATA_KEY] == ConsumedRequestTagsStamp(+ model_group="gemini-flash", tags=("route",)+ )++ @pytest.mark.asyncio+ async def test_fallback_reentry_with_a_plain_group_clears_the_stale_stamp(self):+ from litellm.constants import CONSUMED_REQUEST_TAGS_METADATA_KEY++ router = self._router()+ request_kwargs = {"metadata": {"tags": ["route"]}}++ await router.async_pre_routing_hook(model="gpt4o", request_kwargs=request_kwargs)+ await router.async_pre_routing_hook(model="gemini-flash", request_kwargs=request_kwargs)++ assert CONSUMED_REQUEST_TAGS_METADATA_KEY not in request_kwargs["metadata"]++ @pytest.mark.asyncio+ async def test_no_stamp_when_the_request_is_untagged(self):+ from litellm.constants import CONSUMED_REQUEST_TAGS_METADATA_KEY++ router = self._router()+ request_kwargs = {"metadata": {}}++ await router.async_pre_routing_hook(model="gpt4o", request_kwargs=request_kwargs)++ assert CONSUMED_REQUEST_TAGS_METADATA_KEY not in request_kwargs["metadata"]++ @pytest.mark.asyncio+ async def test_no_stamp_when_the_selected_strategy_carries_no_tags(self):+ from litellm.constants import CONSUMED_REQUEST_TAGS_METADATA_KEY++ router = self._router(marker_tags=())+ request_kwargs = {"metadata": {"tags": ["route"]}}++ await router.async_pre_routing_hook(model="gpt4o", request_kwargs=request_kwargs)++ assert CONSUMED_REQUEST_TAGS_METADATA_KEY not in request_kwargs["metadata"]+++ class TestClaudeCodeSubagentSessionRouterBinding:+ class _RewriteStrategy:+ def __init__(self, routed_model: str = "cheap-model") -> None:+ self.routed_model = routed_model++ async def async_pre_routing_hook(+ self, model, request_kwargs, messages=None, input=None, specific_deployment=False+ ):+ from litellm.types.router import PreRoutingHookResponse++ return PreRoutingHookResponse(+ model=self.routed_model,+ messages=messages,+ routing_decision={+ "router_model_name": "smart-router",+ "router_type": "complexity",+ "routed_model": self.routed_model,+ "cause": "heuristic_scorer",+ },+ )++ @classmethod+ def _router(+ cls,+ cheap_response: str = "cheap response",+ fallbacks: list[dict[str, list[str]]] | None = None,+ ) -> "litellm.Router":+ from litellm.types.router import TaggedPreRoutingStrategy++ router = litellm.Router(+ model_list=[+ {+ "model_name": "cheap-model",+ "litellm_params": {"model": "openai/gpt-4o-mini", "mock_response": cheap_response},+ },+ {+ "model_name": "expensive-model",+ "litellm_params": {"model": "openai/gpt-4o", "mock_response": "expensive response"},+ },+ ],+ fallbacks=fallbacks,+ num_retries=0,+ )+ router.complexity_routers = {+ "smart-router": (TaggedPreRoutingStrategy(tags=(), strategy=cls._RewriteStrategy()),),+ "premium-router": (TaggedPreRoutingStrategy(tags=(), strategy=cls._RewriteStrategy("expensive-model")),),+ }+ return router++ @staticmethod+ def _request_kwargs(+ *,+ key_hash: str = "key-hash-a",+ app: str = "cli",+ agent_id: str | None = None,+ fallback_depth: int | None = None,+ ) -> dict:+ headers = {+ "X-Claude-Code-Session-Id": "session-1234",+ "x-app": app,+ **({"x-claude-code-agent-id": agent_id} if agent_id is not None else {}),+ }+ return {+ "metadata": {"user_api_key_hash": key_hash},+ "proxy_server_request": {"headers": headers},+ **({"fallback_depth": fallback_depth} if fallback_depth is not None else {}),+ }++ @pytest.mark.asyncio+ async def test_subagent_concrete_model_uses_the_main_sessions_router(self):+ router = self._router()++ await router.acompletion(+ model="smart-router",+ messages=[{"role": "user", "content": "main turn"}],+ **self._request_kwargs(),+ )+ subagent_kwargs = self._request_kwargs(agent_id="agent-1234")++ response = await router.acompletion(+ model="expensive-model",+ messages=[{"role": "user", "content": "subagent turn"}],+ **subagent_kwargs,+ )++ assert response.choices[0].message.content == "cheap response"+ assert subagent_kwargs["metadata"]["model_group"] == "smart-router"+ assert subagent_kwargs["metadata"]["routing_decision"]["router_model_name"] == "smart-router"++ @pytest.mark.asyncio+ async def test_main_thread_side_calls_to_a_plain_model_keep_the_session_router(self):+ router = self._router()++ await router.async_pre_routing_hook(model="smart-router", request_kwargs=self._request_kwargs())+ await router.async_pre_routing_hook(model="expensive-model", request_kwargs=self._request_kwargs())++ response = await router.async_pre_routing_hook(+ model="expensive-model",+ request_kwargs=self._request_kwargs(agent_id="agent-1234"),+ )++ assert response is not None+ assert response.model == "cheap-model"++ @pytest.mark.asyncio+ async def test_redis_cleanup_failure_does_not_reject_a_subagent_request(self):+ from litellm.caching.caching import RedisCache++ router = self._router()+ del router.complexity_routers["smart-router"]+ redis_cache = MagicMock(spec=RedisCache)+ redis_cache.async_get_cache = AsyncMock(return_value="smart-router")+ redis_cache.async_delete_cache = AsyncMock(side_effect=ConnectionError("redis unavailable"))+ router._update_redis_cache(cache=redis_cache)++ response = await router.async_pre_routing_hook(+ model="expensive-model",+ request_kwargs=self._request_kwargs(agent_id="agent-1234"),+ )++ assert response is None+ redis_cache.async_delete_cache.assert_awaited_once()++ @pytest.mark.asyncio+ async def test_redis_read_failure_does_not_reject_a_subagent_request(self):+ from litellm.caching.caching import RedisCache++ router = self._router()+ request_kwargs = self._request_kwargs(agent_id="agent-1234")+ cache_key = router._claude_code_session_router_cache_key(request_kwargs)+ assert cache_key is not None+ await router._claude_code_session_router_cache.in_memory_cache.async_set_cache(+ cache_key,+ "smart-router",+ )+ redis_cache = MagicMock(spec=RedisCache)+ redis_cache.async_get_cache = AsyncMock(side_effect=Exception("Redis circuit breaker is open"))+ router._update_redis_cache(cache=redis_cache)++ response = await router.async_pre_routing_hook(+ model="expensive-model",+ request_kwargs=request_kwargs,+ )++ assert response is None+ assert "model_group" not in request_kwargs["metadata"]+ redis_cache.async_get_cache.assert_awaited_once()++ @pytest.mark.asyncio+ async def test_redis_write_failures_do_not_reject_main_or_subagent_requests(self):+ from litellm.caching.caching import RedisCache++ router = self._router()+ redis_cache = MagicMock(spec=RedisCache)+ redis_cache.async_get_cache = AsyncMock(return_value="smart-router")+ redis_cache.async_set_cache = AsyncMock(side_effect=Exception("redis unavailable"))+ router._update_redis_cache(cache=redis_cache)++ main_response = await router.async_pre_routing_hook(+ model="smart-router",+ request_kwargs=self._request_kwargs(),+ )+ subagent_response = await router.async_pre_routing_hook(+ model="expensive-model",+ request_kwargs=self._request_kwargs(agent_id="agent-1234"),+ )++ assert main_response is not None+ assert main_response.model == "cheap-model"+ assert subagent_response is not None+ assert subagent_response.model == "cheap-model"+ assert redis_cache.async_set_cache.await_count == 2++ @pytest.mark.asyncio+ async def test_subagents_follow_the_main_threads_latest_router_across_workers(self):+ from types import SimpleNamespace++ from litellm.caching.caching import RedisCache++ shared_binding = SimpleNamespace(value=None)+ shared_redis = MagicMock(spec=RedisCache)+ shared_redis.async_get_cache = AsyncMock(side_effect=lambda key, **_: shared_binding.value)+ shared_redis.async_set_cache = AsyncMock(+ side_effect=lambda key, value, **_: setattr(shared_binding, "value", value)+ )+ main_worker, subagent_worker = self._router(), self._router()+ main_worker._update_redis_cache(cache=shared_redis)+ subagent_worker._update_redis_cache(cache=shared_redis)++ await main_worker.async_pre_routing_hook(model="smart-router", request_kwargs=self._request_kwargs())+ first = await subagent_worker.async_pre_routing_hook(+ model="expensive-model",+ request_kwargs=self._request_kwargs(agent_id="agent-1234"),+ )+ await main_worker.async_pre_routing_hook(model="premium-router", request_kwargs=self._request_kwargs())+ second = await subagent_worker.async_pre_routing_hook(+ model="expensive-model",+ request_kwargs=self._request_kwargs(agent_id="agent-1234"),+ )++ assert first is not None+ assert first.model == "cheap-model"+ assert second is not None+ assert second.model == "expensive-model"+ assert shared_binding.value == "premium-router"++ @pytest.mark.asyncio+ async def test_no_pre_routing_strategies_means_no_session_cache_traffic(self):+ from litellm.caching.caching import RedisCache++ router = self._router()+ router.complexity_routers.clear()+ redis_cache = MagicMock(spec=RedisCache)+ redis_cache.async_get_cache = AsyncMock(return_value=None)+ redis_cache.async_set_cache = AsyncMock()+ redis_cache.async_delete_cache = AsyncMock()+ router._update_redis_cache(cache=redis_cache)++ for request_kwargs in (self._request_kwargs(), self._request_kwargs(agent_id="agent-1234")):+ response = await router.async_pre_routing_hook(model="expensive-model", request_kwargs=request_kwargs)+ assert response is None++ redis_cache.async_get_cache.assert_not_awaited()+ redis_cache.async_set_cache.assert_not_awaited()+ redis_cache.async_delete_cache.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_session_bindings_do_not_evict_router_rate_limit_state(self):+ router = self._router()+ assert router._update_usage(deployment_id="deployment-id", parent_otel_span=None) == 1++ for session_index in range(201):+ request_kwargs = self._request_kwargs()+ request_kwargs["proxy_server_request"]["headers"]["X-Claude-Code-Session-Id"] = (+ f"session-{session_index:04d}"+ )+ await router.async_pre_routing_hook(model="smart-router", request_kwargs=request_kwargs)++ assert router._update_usage(deployment_id="deployment-id", parent_otel_span=None) == 2++ @pytest.mark.asyncio+ async def test_background_and_fallback_requests_do_not_clear_the_session_router(self):+ router = self._router()++ await router.async_pre_routing_hook(model="smart-router", request_kwargs=self._request_kwargs())+ await router.async_pre_routing_hook(+ model="expensive-model",+ request_kwargs=self._request_kwargs(app="cli-bg"),+ )+ await router.async_pre_routing_hook(+ model="expensive-model",+ request_kwargs=self._request_kwargs(fallback_depth=1),+ )++ response = await router.async_pre_routing_hook(+ model="expensive-model",+ request_kwargs=self._request_kwargs(agent_id="agent-1234"),+ )++ assert response is not None+ assert response.model == "cheap-model"++ @pytest.mark.asyncio+ async def test_subagent_fallback_does_not_reapply_the_session_router(self):+ router = self._router()++ await router.async_pre_routing_hook(model="smart-router", request_kwargs=self._request_kwargs())++ response = await router.async_pre_routing_hook(+ model="expensive-model",+ request_kwargs=self._request_kwargs(agent_id="agent-1234", fallback_depth=1),+ )++ assert response is None++ @pytest.mark.asyncio+ async def test_subagent_can_fallback_to_its_original_requested_model(self):+ router = self._router(+ cheap_response="litellm.RateLimitError",+ fallbacks=[{"cheap-model": ["expensive-model"]}],+ )++ await router.acompletion(+ model="smart-router",+ messages=[{"role": "user", "content": "main turn"}],+ **self._request_kwargs(),+ )+ subagent_kwargs = self._request_kwargs(agent_id="agent-1234")++ response = await router.acompletion(+ model="expensive-model",+ messages=[{"role": "user", "content": "subagent turn"}],+ **subagent_kwargs,+ )++ assert response.choices[0].message.content == "expensive response"+ assert subagent_kwargs["metadata"]["routing_decision"]["routed_model"] == "cheap-model"++ @pytest.mark.asyncio+ async def test_subagent_can_use_the_bound_router_name_fallback(self):+ router = self._router(+ cheap_response="litellm.RateLimitError",+ fallbacks=[{"smart-router": ["expensive-model"]}],+ )++ await router.acompletion(+ model="smart-router",+ messages=[{"role": "user", "content": "main turn"}],+ **self._request_kwargs(),+ )++ response = await router.acompletion(+ model="expensive-model",+ messages=[{"role": "user", "content": "subagent turn"}],+ **self._request_kwargs(agent_id="agent-1234"),+ )++ assert response.choices[0].message.content == "expensive response"++ @pytest.mark.asyncio+ async def test_anthropic_subagent_four_fallback_hops_use_each_current_model_chain(self):+ from litellm.types.router import TaggedPreRoutingStrategy++ failing_groups = ("cheap-model", "fallback-1", "fallback-2", "fallback-3")+ router = litellm.Router(+ model_list=[+ *(+ {+ "model_name": group,+ "litellm_params": {+ "model": "anthropic/claude-3-haiku-20240307",+ "mock_response": "litellm.RateLimitError",+ },+ }+ for group in failing_groups+ ),+ {+ "model_name": "requested-model",+ "litellm_params": {+ "model": "anthropic/claude-3-haiku-20240307",+ "mock_response": "requested response",+ },+ },+ {+ "model_name": "fallback-4",+ "litellm_params": {+ "model": "anthropic/claude-3-haiku-20240307",+ "mock_response": "fourth fallback response",+ },+ },+ ],+ fallbacks=[+ {"smart-router": ["fallback-1"]},+ {"fallback-1": ["fallback-2"]},+ {"fallback-2": ["fallback-3"]},+ {"fallback-3": ["fallback-4"]},+ ],+ num_retries=0,+ max_fallbacks=4,+ )+ router.complexity_routers = {+ "smart-router": (TaggedPreRoutingStrategy(tags=(), strategy=self._RewriteStrategy()),)+ }+ main_kwargs = self._request_kwargs()+ main_kwargs["litellm_metadata"] = main_kwargs.pop("metadata")+ await router.async_pre_routing_hook(model="smart-router", request_kwargs=main_kwargs)+ subagent_kwargs = self._request_kwargs(agent_id="agent-1234")+ subagent_kwargs["litellm_metadata"] = subagent_kwargs.pop("metadata")++ response = await router.aanthropic_messages(+ model="requested-model",+ messages=[{"role": "user", "content": "subagent turn"}],+ max_tokens=64,+ **subagent_kwargs,+ )++ assert response["content"][0]["text"] == "fourth fallback response"++ @pytest.mark.asyncio+ async def test_session_router_binding_is_scoped_to_the_authenticated_key(self):+ router = self._router()++ await router.async_pre_routing_hook(model="smart-router", request_kwargs=self._request_kwargs())++ response = await router.async_pre_routing_hook(+ model="expensive-model",+ request_kwargs=self._request_kwargs(key_hash="key-hash-b", agent_id="agent-1234"),+ )++ assert response is None+++ class TestAutoRouterMaxInputCharsWiring:+ """`auto_router_max_input_chars` on the deployment has to reach the AutoRouter that embeds prompts.++ Without it the cap silently reverts to the default, so an operator whose embedding model has a+ 512-token window cannot lower it and every long prompt falls back to the default model instead+ of being routed.+ """++ @staticmethod+ def _router(**extra_params) -> "litellm.Router":+ pytest.importorskip("semantic_router", reason="auto-router needs the semantic-router extra")+ return litellm.Router(+ model_list=[+ {"model_name": "gpt-4o", "litellm_params": {"model": "gpt-4o"}},+ {+ "model_name": "my-auto-router",+ "litellm_params": {+ "model": "auto_router/my-auto-router",+ "auto_router_config": json.dumps(+ {"routes": [{"name": "gpt-4o", "utterances": ["write me code"]}]}+ ),+ "auto_router_default_model": "gpt-4o",+ "auto_router_embedding_model": "text-embedding-3-small",+ **extra_params,+ },+ },+ ]+ )++ @staticmethod+ def _registered_auto_router(router: "litellm.Router"):+ return router.auto_routers["my-auto-router"][0].strategy++ def test_should_pass_the_configured_cap_to_the_auto_router(self):+ router = self._router(auto_router_max_input_chars=512)++ assert self._registered_auto_router(router).max_input_chars == 512++ def test_should_fall_back_to_the_shared_default_when_the_deployment_omits_it(self):+ from litellm.constants import DEFAULT_AUTO_ROUTER_MAX_INPUT_CHARS++ router = self._router()++ assert self._registered_auto_router(router).max_input_chars == DEFAULT_AUTO_ROUTER_MAX_INPUT_CHARS+++ class TestTaggedAutoRouterOnSharedModelName:+ """A tagged auto-router marker sharing its model_name with a plain deployment must not+ capture requests whose tags don't match it when tag filtering is enabled (#36620)."""++ class _FixedRouteLayer:+ def __call__(self, text: str):+ from semantic_router.schema import RouteChoice++ return RouteChoice(name="gemini-flash")++ @classmethod+ def _router(cls, marker_tags, include_plain_sibling: bool, enable_tag_filtering: bool) -> "litellm.Router":+ pytest.importorskip("semantic_router", reason="auto-router needs the semantic-router extra")+ marker = {+ "model_name": "gpt4o",+ "litellm_params": {+ "model": "auto_router/gpt4o-router",+ "auto_router_config": json.dumps(+ {"routes": [{"name": "gemini-flash", "utterances": ["capital city questions"]}]}+ ),+ "auto_router_default_model": "gemini-flash",+ "auto_router_embedding_model": "text-embedding-3-small",+ **({"tags": marker_tags} if marker_tags else {}),+ },+ }+ plain = {"model_name": "gpt4o", "litellm_params": {"model": "openai/gpt-4o"}}+ tier = {"model_name": "gemini-flash", "litellm_params": {"model": "gemini/gemini-3.6-flash"}}+ router = litellm.Router(+ model_list=[plain, marker, tier] if include_plain_sibling else [marker, tier],+ enable_tag_filtering=enable_tag_filtering,+ )+ router.auto_routers["gpt4o"][0].strategy.routelayer = cls._FixedRouteLayer()+ return router++ @staticmethod+ async def _hook_response(router: "litellm.Router", request_kwargs: dict):+ return await router.async_pre_routing_hook(+ model="gpt4o",+ request_kwargs=request_kwargs,+ messages=[{"role": "user", "content": "What is the capital of France?"}],+ )++ @pytest.mark.asyncio+ async def test_untagged_request_bypasses_the_tagged_marker_when_a_plain_deployment_shares_the_name(self):+ router = self._router(marker_tags=["route"], include_plain_sibling=True, enable_tag_filtering=True)++ assert await self._hook_response(router, {}) is None++ @pytest.mark.asyncio+ async def test_request_tagged_for_the_marker_is_still_semantically_routed(self):+ router = self._router(marker_tags=["route"], include_plain_sibling=True, enable_tag_filtering=True)++ response = await self._hook_response(router, {"metadata": {"tags": ["route"]}})++ assert response is not None+ assert response.model == "gemini-flash"++ @pytest.mark.asyncio+ async def test_request_level_tag_filtering_from_key_settings_bypasses_the_marker(self):+ router = self._router(marker_tags=["route"], include_plain_sibling=True, enable_tag_filtering=False)++ assert await self._hook_response(router, {"enable_tag_filtering": True}) is None++ @pytest.mark.asyncio+ async def test_globally_disabled_filtering_still_lets_the_marker_capture_untagged_requests(self):+ router = self._router(marker_tags=["route"], include_plain_sibling=True, enable_tag_filtering=False)++ response = await self._hook_response(router, {})++ assert response is not None+ assert response.model == "gemini-flash"++ @pytest.mark.asyncio+ async def test_marker_only_alias_still_captures_untagged_requests(self):+ router = self._router(marker_tags=["route"], include_plain_sibling=False, enable_tag_filtering=True)++ response = await self._hook_response(router, {})++ assert response is not None+ assert response.model == "gemini-flash"++ @pytest.mark.asyncio+ async def test_untagged_marker_sharing_the_name_still_captures_untagged_requests(self):+ router = self._router(marker_tags=None, include_plain_sibling=True, enable_tag_filtering=True)++ response = await self._hook_response(router, {})++ assert response is not None+ assert response.model == "gemini-flash"++ @pytest.mark.asyncio+ async def test_untagged_selection_never_lands_on_the_marker_deployment(self):+ router = self._router(marker_tags=["route"], include_plain_sibling=True, enable_tag_filtering=True)++ for _ in range(20):+ deployment = await router.async_get_available_deployment(+ model="gpt4o",+ request_kwargs={},+ messages=[{"role": "user", "content": "What is the capital of France?"}],+ )+ assert deployment["litellm_params"]["model"] == "openai/gpt-4o"++ def test_deployment_without_litellm_params_mapping_is_not_a_marker(self):+ assert litellm.Router._is_strategy_marker_deployment({"model_name": "gpt4o"}) is False++ def test_model_name_has_plain_deployments_reflects_the_pool(self):+ mixed = self._router(marker_tags=["route"], include_plain_sibling=True, enable_tag_filtering=True)+ marker_only = self._router(marker_tags=["route"], include_plain_sibling=False, enable_tag_filtering=True)++ assert mixed._model_name_has_plain_deployments("gpt4o") is True+ assert marker_only._model_name_has_plain_deployments("gpt4o") is False+++ class TestAutoRouterSharedModelNameConnectionParams:+ """A plain deployment sharing its model_name with an `auto_router/` marker must not have+ its api_base and api_key grafted onto the routed tier's outbound call (#36619)."""++ PLAIN_API_BASE = "https://plain-sibling.openai.example/v1"+ PLAIN_API_KEY = "sk-plain-sibling-secret"++ class _FixedRouteLayer:+ def __call__(self, text: str):+ from semantic_router.schema import RouteChoice++ return RouteChoice(name="gemini-flash")++ @classmethod+ def _router(cls, plain_entry_first: bool) -> "litellm.Router":+ pytest.importorskip("semantic_router", reason="auto-router needs the semantic-router extra")+ plain = {+ "model_name": "gpt4o",+ "litellm_params": {+ "model": "openai/gpt-4o",+ "api_key": cls.PLAIN_API_KEY,+ "api_base": cls.PLAIN_API_BASE,+ },+ }+ marker = {+ "model_name": "gpt4o",+ "litellm_params": {+ "model": "auto_router/gpt4o-router",+ "auto_router_config": json.dumps(+ {"routes": [{"name": "gemini-flash", "utterances": ["capital city questions"]}]}+ ),+ "auto_router_default_model": "gemini-flash",+ "auto_router_embedding_model": "text-embedding-3-small",+ "drop_params": True,+ },+ }+ tier = {+ "model_name": "gemini-flash",+ "litellm_params": {"model": "gemini/gemini-3.6-flash", "api_key": "sk-tier-key"},+ }+ shared_name_entries = [plain, marker] if plain_entry_first else [marker, plain]+ router = litellm.Router(model_list=[*shared_name_entries, tier])+ router.auto_routers["gpt4o"][0].strategy.routelayer = cls._FixedRouteLayer()+ return router++ @staticmethod+ def _gemini_response() -> httpx.Response:+ return httpx.Response(+ status_code=200,+ json={+ "candidates": [+ {"content": {"parts": [{"text": "Paris"}], "role": "model"}, "finishReason": "STOP"}+ ],+ "usageMetadata": {"promptTokenCount": 5, "candidatesTokenCount": 1, "totalTokenCount": 6},+ "modelVersion": "gemini-3.6-flash",+ },+ request=httpx.Request("POST", "https://generativelanguage.googleapis.com"),+ )++ @pytest.mark.parametrize(+ "plain_entry_first", [True, False], ids=["plain_entry_first", "marker_entry_first"]+ )+ async def test_routed_tier_call_goes_out_on_its_own_endpoint_and_credentials(self, plain_entry_first):+ """The outbound provider request for the routed tier hits the tier's own Gemini host+ with the tier's own key, never the plain sibling's api_base or api_key."""+ from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler++ router = self._router(plain_entry_first)++ with patch.object(+ AsyncHTTPHandler, "post", new_callable=AsyncMock, return_value=self._gemini_response()+ ) as mock_post:+ await router.acompletion(+ model="gpt4o",+ messages=[{"role": "user", "content": "What is the capital of France?"}],+ )++ call = mock_post.call_args+ outbound_url = str(call.kwargs["url"] if "url" in call.kwargs else call.args[0])+ outbound_headers = dict(call.kwargs.get("headers") or {})++ assert "generativelanguage.googleapis.com" in outbound_url+ assert "gemini-3.6-flash" in outbound_url+ assert self.PLAIN_API_BASE not in outbound_url+ assert self.PLAIN_API_KEY not in outbound_url+ assert self.PLAIN_API_KEY not in json.dumps(outbound_headers)+++ class TestGetAllowedFailsFromPolicy:+ def _make_router(self, **policy_kwargs) -> litellm.Router:+ from litellm.types.router import AllowedFailsPolicy++ return litellm.Router(+ model_list=[{"model_name": "gpt-4", "litellm_params": {"model": "gpt-4", "api_key": "fake"}}],+ allowed_fails_policy=AllowedFailsPolicy(**policy_kwargs),+ )++ def test_no_policy_returns_none(self):+ router = litellm.Router(+ model_list=[{"model_name": "gpt-4", "litellm_params": {"model": "gpt-4", "api_key": "fake"}}],+ )+ assert router.get_allowed_fails_from_policy(litellm.RateLimitError("429", "openai", "gpt-4")) is None++ def test_internal_server_error_allowed_fails(self):+ router = self._make_router(InternalServerErrorAllowedFails=7)+ exc = litellm.InternalServerError("500", "openai", "gpt-4")+ assert router.get_allowed_fails_from_policy(exc) == 7++ def test_service_unavailable_error_allowed_fails(self):+ router = self._make_router(ServiceUnavailableErrorAllowedFails=4)+ exc = litellm.ServiceUnavailableError("503", "openai", "gpt-4")+ assert router.get_allowed_fails_from_policy(exc) == 4++ def test_bad_gateway_error_allowed_fails(self):+ router = self._make_router(BadGatewayErrorAllowedFails=2)+ exc = litellm.BadGatewayError("502", "openai", "gpt-4")+ assert router.get_allowed_fails_from_policy(exc) == 2++ def test_not_found_error_allowed_fails(self):+ router = self._make_router(NotFoundErrorAllowedFails=1)+ exc = litellm.NotFoundError("404", "openai", "gpt-4")+ assert router.get_allowed_fails_from_policy(exc) == 1++ def test_unmatched_exception_returns_none(self):+ router = self._make_router(InternalServerErrorAllowedFails=5)+ exc = litellm.RateLimitError("429", "openai", "gpt-4")+ assert router.get_allowed_fails_from_policy(exc) is None+++ class _LogCapture(logging.Handler):+ def __init__(self, level):+ super().__init__(level=level)+ self._level = level+ self.messages = []++ def emit(self, record):+ if record.levelno == self._level:+ self.messages.append(record.getMessage())+++ class _FallbackAttemptRecorder(CustomLogger):+ def __init__(self):+ super().__init__()+ self.failed_targets = []+ self.breadcrumbs_per_target = []++ async def log_failure_fallback_event(self, original_model_group, kwargs, original_exception):+ self.failed_targets.append(kwargs.get("model"))+ self.breadcrumbs_per_target.append(kwargs.get("metadata", {}).get("previous_models", ()))+++ def _cyclic_fallback_router(num_retries=0):+ groups = ["group-a", "group-b", "group-c", "group-d"]+ return litellm.Router(+ model_list=[+ {+ "model_name": group,+ "litellm_params": {+ "model": "openai/gpt-4o-mini",+ "api_key": "sk-fake",+ "mock_response": "litellm.InternalServerError",+ },+ }+ for group in groups+ ],+ fallbacks=[+ {"group-a": ["group-b", "group-c"]},+ {"group-b": ["group-a", "group-c"]},+ {"group-c": ["group-d"]},+ {"group-d": ["group-b", "group-a"]},+ ],+ num_retries=num_retries,+ )+++ async def _drive_cyclic_fallback(router, capture, recorder=None, **request_kwargs):+ router_logger = logging.getLogger("LiteLLM Router")+ previous_level = router_logger.level+ router_logger.setLevel(capture.level)+ router_logger.addHandler(capture)+ if recorder is not None:+ litellm.callbacks.append(recorder)+ try:+ with pytest.raises(litellm.InternalServerError):+ await router.acompletion(+ model="group-a", messages=[{"role": "user", "content": "hi"}], **request_kwargs+ )+ finally:+ router_logger.removeHandler(capture)+ router_logger.setLevel(previous_level)+ if recorder is not None:+ litellm.callbacks.remove(recorder)+++ @pytest.mark.asyncio+ async def test_cyclic_fallback_graph_does_not_amplify_one_request():+ """A fallback graph whose entries loop back on each other is easy to build by accident,+ and every group in the loop fails identically on a deterministic error, so the walk must+ not revisit a group and must not re-emit a growing chained traceback at each level. Left+ unbounded, one request blocks the event loop long enough for health probes to fail."""+ recorder = _FallbackAttemptRecorder()+ capture = _LogCapture(logging.ERROR)++ await _drive_cyclic_fallback(_cyclic_fallback_router(), capture, recorder)++ assert sorted(set(recorder.failed_targets)) == ["group-b", "group-c", "group-d"]+ assert len(recorder.failed_targets) == len(set(recorder.failed_targets))+ assert not any("Traceback (most recent call last)" in message for message in capture.messages)+ assert sum(len(message) for message in capture.messages) < 5_000+++ @pytest.mark.asyncio+ async def test_retry_breadcrumbs_do_not_carry_the_walk_state():+ """log_retry copies every kwarg into previous_models, which reaches spend logs and+ logging callbacks. The set of already-attempted groups is router-internal walk state+ with no diagnostic value there, and it is the one entry that is not a plain scalar.+ A retry has to be configured for the walk state to reach log_retry at all."""+ router = _cyclic_fallback_router(num_retries=1)+ capture = _LogCapture(logging.ERROR)+ recorder = _FallbackAttemptRecorder()++ await _drive_cyclic_fallback(router, capture, recorder)++ breadcrumbs = [breadcrumb for hop in recorder.breadcrumbs_per_target for breadcrumb in hop]+ assert breadcrumbs, "no retry breadcrumbs were recorded"+ assert any(+ "fallback_depth" in breadcrumb for breadcrumb in breadcrumbs+ ), "no breadcrumb carried router walk state, so this test cannot see the leak"+ for breadcrumb in breadcrumbs:+ assert "attempted_targets" not in breadcrumb+++ _BREADCRUMB_CREDENTIAL_CANARY = "Bearer sk-ant-oat01-RETRY-BREADCRUMB-CANARY-doNotShip"+++ @pytest.mark.parametrize(+ "container_key, request_kwargs",+ [+ (+ "provider_specific_header",+ {+ "provider_specific_header": {+ "custom_llm_provider": "openai",+ "extra_headers": {"authorization": _BREADCRUMB_CREDENTIAL_CANARY},+ }+ },+ ),+ (+ "extra_headers",+ {"extra_headers": {"authorization": _BREADCRUMB_CREDENTIAL_CANARY}},+ ),+ (+ "api_key",+ {"api_key": _BREADCRUMB_CREDENTIAL_CANARY},+ ),+ ],+ )+ @pytest.mark.asyncio+ async def test_retry_breadcrumbs_never_carry_a_forwarded_credential(container_key, request_kwargs):+ """log_retry copies kwargs into previous_models, which reaches spend logs and logging callbacks.+ Any of these kwargs can carry a client's forwarded Authorization token or a provider key, and a+ breadcrumb has no diagnostic use for the raw secret. A denylist of key names is always one new+ credential kwarg behind, so log_retry scrubs credential-named values by pattern instead: the+ container still reaches the breadcrumb, but the raw secret never does, whatever key holds it."""+ router = _cyclic_fallback_router(num_retries=1)+ capture = _LogCapture(logging.ERROR)+ metadata = {}++ await _drive_cyclic_fallback(router, capture, metadata=metadata, **request_kwargs)++ breadcrumbs = metadata["previous_models"]+ assert breadcrumbs, "no retry breadcrumbs were recorded"+ dumped = json.dumps(breadcrumbs, default=str)+ assert container_key in dumped, "the credential-bearing kwarg never reached the breadcrumb, so this test cannot see the leak"+ assert _BREADCRUMB_CREDENTIAL_CANARY not in dumped+++ def _always_failing_router(num_retries):+ return litellm.Router(+ model_list=[+ {+ "model_name": "broken-group",+ "litellm_params": {+ "model": "openai/gpt-4o-mini",+ "api_key": "sk-fake",+ "mock_response": "litellm.InternalServerError",+ },+ }+ ],+ num_retries=num_retries,+ )+++ async def _fail_one_proxy_shaped_request(router, request_marker):+ """The proxy hands the router a metadata dict and a proxy_server_request whose body is a+ shallow copy of the request, so body["metadata"] is the very same dict the router later+ stamps previous_models onto."""+ metadata = {"request_marker": request_marker}+ with pytest.raises(litellm.InternalServerError):+ await router.acompletion(+ model="broken-group",+ messages=[{"role": "user", "content": "hi"}],+ metadata=metadata,+ proxy_server_request={+ "url": "http://localhost:4000/v1/chat/completions",+ "method": "POST",+ "headers": {},+ "body": {"model": "broken-group", "metadata": metadata},+ },+ )+ return metadata["previous_models"]+++ def _nested_breadcrumb_lists(node):+ if isinstance(node, dict):+ return [v for k, v in node.items() if k == "previous_models"] + [+ found for v in node.values() for found in _nested_breadcrumb_lists(v)+ ]+ if isinstance(node, (list, tuple)):+ return [found for item in node for found in _nested_breadcrumb_lists(item)]+ return []+++ @pytest.mark.asyncio+ async def test_retry_breadcrumbs_stay_per_request_and_flat_across_failing_requests():+ """Every failed attempt appends a breadcrumb to metadata["previous_models"], and the proxy's+ request snapshot aliases that same metadata dict. Kept on the Router and copied wholesale,+ each breadcrumb embedded every earlier one from every earlier request, so the breadcrumb+ tree, and with it the debug repr of the kwargs, roughly doubled on each failed attempt until+ a single-worker proxy spent minutes in the redaction regex and stopped answering."""+ router = _always_failing_router(num_retries=2)++ breadcrumbs_per_request = [+ await _fail_one_proxy_shaped_request(router, f"request-{request_number}") for request_number in range(1, 7)+ ]++ for request_number, breadcrumbs in enumerate(breadcrumbs_per_request, start=1):+ assert len(breadcrumbs) == 3, "one initial attempt plus two retries failed, each leaving one breadcrumb"+ assert {breadcrumb["metadata"]["request_marker"] for breadcrumb in breadcrumbs} == {f"request-{request_number}"}+ for breadcrumb in breadcrumbs:+ assert _nested_breadcrumb_lists(breadcrumb) == []+ assert len({len(repr(breadcrumbs)) for breadcrumbs in breadcrumbs_per_request}) == 1+++ @pytest.mark.asyncio+ async def test_retry_breadcrumbs_keep_only_the_last_four_attempts():+ router = _always_failing_router(num_retries=6)++ breadcrumbs = await _fail_one_proxy_shaped_request(router, "request-1")++ assert len(breadcrumbs) == 4+ assert [breadcrumb["metadata"]["attempted_retries"] for breadcrumb in breadcrumbs] == [3, 4, 5, 6]+++ @pytest.mark.asyncio+ async def test_fallback_traceback_stays_available_at_debug_level():+ """Dropping the stack from the ERROR line is only safe because the fallback path still+ emits it once per level at DEBUG, which is what an operator needs to diagnose why every+ fallback failed. This pins that remaining debug traceback."""+ capture = _LogCapture(logging.DEBUG)++ await _drive_cyclic_fallback(_cyclic_fallback_router(), capture)++ assert any("Traceback (most recent call last)" in message for message in capture.messages)+++ @pytest.mark.asyncio+ async def test_fallback_failure_detail_from_upstream_is_bounded():+ """The detail each level records about the level below it is attacker-influenced, since+ it carries whatever the upstream error said. It has to be bounded on its own, so a walk+ over several groups cannot compound one large message into the log or into the message+ handed back to the caller."""+ huge_message = "z" * 50_000+ capture = _LogCapture(logging.ERROR)++ await _drive_cyclic_fallback(+ _cyclic_fallback_router(),+ capture,+ mock_response=litellm.InternalServerError(+ message=huge_message, llm_provider="openai", model="group-a"+ ),+ )++ assert capture.messages, "the fallback failure path did not log at ERROR"+ assert huge_message not in "".join(capture.messages)+ assert max(len(message) for message in capture.messages) < 5_000+++ def test_stamp_or_clear_metadata_key_writes_and_clears_both_buckets():+ request_kwargs = {"metadata": {}}+ litellm.Router._stamp_or_clear_metadata_key(request_kwargs=request_kwargs, key="probe", value=7)+ assert request_kwargs["metadata"]["probe"] == 7++ stale_kwargs = {"metadata": {"probe": 7}, "litellm_metadata": {"probe": 7}}+ litellm.Router._stamp_or_clear_metadata_key(request_kwargs=stale_kwargs, key="probe", value=None)+ assert "probe" not in stale_kwargs["metadata"]+ assert "probe" not in stale_kwargs["litellm_metadata"]+++ @pytest.mark.parametrize(+ "complexity_router_config,expect_callback",+ [+ ({"tiers": {"SIMPLE": "gpt-4o"}}, True),+ ({"tiers": {"SIMPLE": "gpt-4o"}, "deployment_affinity": False}, False),+ ({"tiers": {"SIMPLE": "gpt-4o"}, "deployment_affinity": False, "session_affinity": True}, True),+ ],+ )+ def test_complexity_router_registers_affinity_callback_for_deployment_pin(complexity_router_config, expect_callback):+ """The marker the complexity router stamps is inert unless a DeploymentAffinityCheck is+ registered to read it, so deployment_affinity has to pull the callback in, and its default-on+ means a bare config registers one. Opting out must skip the callback entirely rather than+ register a filter that can never fire, including when session_affinity is on, since the two+ pins are independent."""+ from litellm.router_utils.pre_call_checks.deployment_affinity_check import (+ DeploymentAffinityCheck,+ )++ router = litellm.Router(+ model_list=[+ {"model_name": "gpt-4o", "litellm_params": {"model": "gpt-4o"}},+ {+ "model_name": "my-complexity-router",+ "litellm_params": {+ "model": "auto_router/complexity_router",+ "complexity_router_config": complexity_router_config,+ },+ },+ ]+ )+ try:+ registered = any(isinstance(cb, DeploymentAffinityCheck) for cb in router.optional_callbacks or [])+ assert registered is expect_callback+ finally:+ for cb in router.optional_callbacks or []:+ litellm.logging_callback_manager.remove_callback_from_all_lists(cb)+++ def test_ensure_deployment_affinity_callback_is_idempotent():+ from litellm.router_utils.pre_call_checks.deployment_affinity_check import (+ DeploymentAffinityCheck,+ )++ router = litellm.Router(model_list=[])+ try:+ router._ensure_deployment_affinity_callback()+ router._ensure_deployment_affinity_callback()+ affinity_callbacks = [+ cb for cb in router.optional_callbacks or [] if isinstance(cb, DeploymentAffinityCheck)+ ]+ assert len(affinity_callbacks) == 1+ finally:+ for cb in router.optional_callbacks or []:+ litellm.logging_callback_manager.remove_callback_from_all_lists(cb)+++ def test_get_router_model_info_does_not_wipe_cached_pricing():+ """A Deployment's model_info declares the mirrored pricing fields with None defaults;+ merging it must not write those Nones into the lru_cache'd dict get_model_info() owns,+ or /model/info loses built-in prices for every model a worker serves."""+ from litellm.types.router import Deployment, LiteLLM_Params, ModelInfo++ litellm.get_model_info.cache_clear()+ expected = copy.deepcopy(litellm.get_model_info(model="anthropic/claude-sonnet-4-5"))++ router = litellm.Router(model_list=[])+ merged = router.get_router_model_info(+ deployment=Deployment(+ model_name="sonnet",+ litellm_params=LiteLLM_Params(model="claude-sonnet-4-5", custom_llm_provider="anthropic"),+ model_info=ModelInfo(id="sonnet-1"),+ ),+ received_model_name="sonnet",+ )++ assert litellm.get_model_info(model="anthropic/claude-sonnet-4-5") == expected+ for field in ("input_cost_per_token", "output_cost_per_token", "cache_read_input_token_cost"):+ assert merged[field] == expected[field]+++ def test_get_router_model_info_keeps_explicit_pricing_overrides():+ from litellm.types.router import Deployment, LiteLLM_Params, ModelInfo++ litellm.get_model_info.cache_clear()+ router = litellm.Router(model_list=[])+ merged = router.get_router_model_info(+ deployment=Deployment(+ model_name="sonnet",+ litellm_params=LiteLLM_Params(model="claude-sonnet-4-5", custom_llm_provider="anthropic"),+ model_info=ModelInfo(id="sonnet-1", input_cost_per_token=1e-08),+ ),+ received_model_name="sonnet",+ )++ assert merged["input_cost_per_token"] == 1e-08+ assert litellm.get_model_info(model="anthropic/claude-sonnet-4-5")["input_cost_per_token"] != 1e-08+++ class TestModelGroupAliasReachesPreRoutingStrategies:+ """A `model_group_alias` whose target is a strategy router must dispatch exactly like the+ router's own model_name. The four strategy registries are keyed by the marker deployment's+ model_name, so the alias has to be resolved before the pre-routing hook looks anything up,+ and a group that resolves only to markers is not callable at all (LIT-4664)."""++ MARKER_TIMEOUT = 42.0+ REGISTRY_NAMES = ("auto_routers", "complexity_routers", "adaptive_routers", "quality_routers")++ class _RewriteStrategy:+ async def async_pre_routing_hook(+ self, model, request_kwargs, messages=None, input=None, specific_deployment=False+ ):+ from litellm.types.router import PreRoutingHookResponse++ return PreRoutingHookResponse(model="gemini-flash", messages=messages)++ @classmethod+ def _router(cls, registry_name: str | None) -> "litellm.Router":+ from litellm.types.router import TaggedPreRoutingStrategy++ tiers = dict.fromkeys(("SIMPLE", "MEDIUM", "COMPLEX", "REASONING"), "gemini-flash")+ router = litellm.Router(+ model_list=[+ {+ "model_name": "smart-route",+ "litellm_params": {+ "model": "auto_router/complexity_router",+ "complexity_router_config": {"tiers": tiers},+ "complexity_router_default_model": "gemini-flash",+ "timeout": cls.MARKER_TIMEOUT,+ },+ },+ {+ "model_name": "gemini-flash",+ "litellm_params": {"model": "gemini/gemini-3.6-flash", "mock_response": "routed by the tier"},+ },+ ],+ model_group_alias={"smart-alias": "smart-route"},+ )+ for name in cls.REGISTRY_NAMES:+ setattr(router, name, {})+ if registry_name is not None:+ setattr(+ router,+ registry_name,+ {"smart-route": [TaggedPreRoutingStrategy(tags=(), strategy=cls._RewriteStrategy())]},+ )+ return router++ @staticmethod+ def _messages() -> list[dict[str, str]]:+ return [{"role": "user", "content": "What is the capital of France?"}]++ @pytest.mark.parametrize("registry_name", REGISTRY_NAMES)+ @pytest.mark.asyncio+ async def test_alias_dispatches_to_the_strategy_registered_under_the_target(self, registry_name):+ router = self._router(registry_name)+ request_kwargs = {"metadata": {}}++ response = await router.async_pre_routing_hook(+ model="smart-alias", request_kwargs=request_kwargs, messages=self._messages()+ )++ assert response is not None+ assert response.model == "gemini-flash"++ @pytest.mark.asyncio+ async def test_alias_call_still_forwards_the_marker_own_params_to_the_routed_tier(self):+ router = self._router("auto_routers")+ request_kwargs = {"metadata": {}}++ await router.async_pre_routing_hook(+ model="smart-alias", request_kwargs=request_kwargs, messages=self._messages()+ )++ assert request_kwargs["timeout"] == self.MARKER_TIMEOUT++ @pytest.mark.asyncio+ async def test_alias_deployment_selection_lands_on_the_tier_never_the_marker(self):+ router = self._router("auto_routers")++ deployment = await router.async_get_available_deployment(+ model="smart-alias", request_kwargs={"metadata": {}}, messages=self._messages()+ )++ assert deployment["litellm_params"]["model"] == "gemini/gemini-3.6-flash"++ @pytest.mark.asyncio+ async def test_alias_call_completes_and_still_bills_the_name_the_caller_sent(self):+ router = self._router("auto_routers")+ metadata: dict = {}++ response = await router.acompletion(+ model="smart-alias", messages=self._messages(), metadata=metadata+ )++ assert response.choices[0].message.content == "routed by the tier"+ assert metadata["model_group"] == "smart-alias"+ assert metadata["model_group_alias"] == "smart-alias"++ def test_a_group_of_only_markers_is_not_a_callable_model(self):+ router = self._router(None)++ with pytest.raises(litellm.BadRequestError, match="strategy router marker"):+ router.get_available_deployment(+ model="smart-route", messages=self._messages(), request_kwargs={"metadata": {}}+ )+++ @pytest.mark.usefixtures("local_model_cost_map")+ class TestAzureBaseModelFallbackLogging:+ """When an azure deployment has no base_model but its model name is a known+ azure key in the cost map, get_router_model_info resolves it via the+ fallback, so it must not log the per-request 'Could not identify azure+ model' ERROR. The ERROR must remain for genuinely unmappable deployment+ names. Issue #33172."""++ def _router_with_azure_deployment(self, deployment_model: str):+ return litellm.Router(+ model_list=[+ {+ "model_name": "my-group",+ "litellm_params": {+ "model": deployment_model,+ "api_key": "fake-key",+ "api_base": "https://fake.openai.azure.com",+ },+ "model_info": {"id": "azure-base-model-test-id"},+ }+ ]+ )++ def test_map_known_deployment_name_resolves_without_error_log(self):+ router = self._router_with_azure_deployment("azure/gpt-4o")++ with patch(+ "litellm.router.verbose_router_logger.error"+ ) as mock_error:+ model_info = router.get_router_model_info(+ deployment=None, received_model_name="my-group", id="azure-base-model-test-id"+ )++ assert not any(+ "Could not identify azure model" in str(call)+ for call in mock_error.call_args_list+ ), f"unexpected error log: {mock_error.call_args_list}"+ # the fallback resolution must actually surface the map values+ assert model_info["max_input_tokens"] == litellm.model_cost["azure/gpt-4o"]["max_input_tokens"]+ assert model_info["input_cost_per_token"] == litellm.model_cost["azure/gpt-4o"]["input_cost_per_token"]++ def test_unmappable_deployment_name_still_logs_error(self):+ router = self._router_with_azure_deployment("azure/my-custom-deployment-name")++ with patch(+ "litellm.router.verbose_router_logger.error"+ ) as mock_error:+ model_info = router.get_router_model_info(+ deployment=None, received_model_name="my-group", id="azure-base-model-test-id"+ )++ assert any(+ "Could not identify azure model" in str(call)+ for call in mock_error.call_args_list+ ), "expected the error log for an unmappable azure deployment name"+ # unmappable names resolve to a zeroed stub — unchanged behavior+ assert model_info.get("max_input_tokens") is None++ def test_explicit_base_model_still_wins(self):+ router = litellm.Router(+ model_list=[+ {+ "model_name": "my-group",+ "litellm_params": {+ "model": "azure/some-deployment",+ "api_key": "fake-key",+ "api_base": "https://fake.openai.azure.com",+ },+ "model_info": {+ "id": "azure-base-model-test-id",+ "base_model": "azure/gpt-4o-mini",+ },+ }+ ]+ )++ model_info = router.get_router_model_info(+ deployment=None, received_model_name="my-group", id="azure-base-model-test-id"+ )+ assert model_info["max_input_tokens"] == litellm.model_cost["azure/gpt-4o-mini"]["max_input_tokens"]++ def test_model_group_info_intersects_supported_reasoning_efforts():+ router = litellm.Router(+ model_list=[+ {+ "model_name": "smart-group",+ "litellm_params": {"model": "anthropic/opus-like"},+ "model_info": {"id": "opus-like-deployment"},+ },+ {+ "model_name": "smart-group",+ "litellm_params": {"model": "openai/mini-like"},+ "model_info": {"id": "mini-like-deployment"},+ },+ ]+ )++ def _model_info(model_id: str, model_name: str):+ if model_id == "opus-like-deployment":+ return {+ "key": model_name,+ "litellm_provider": "anthropic",+ "mode": "chat",+ "supports_reasoning": True,+ "supports_xhigh_reasoning_effort": True,+ "supports_max_reasoning_effort": True,+ }+ return {+ "key": model_name,+ "litellm_provider": "openai",+ "mode": "chat",+ "supports_reasoning": True,+ "supports_none_reasoning_effort": False,+ "supports_minimal_reasoning_effort": True,+ "supports_xhigh_reasoning_effort": False,+ }++ with patch.object(router, "get_deployment_model_info", side_effect=_model_info):+ result = router._set_model_group_info(+ model_group="smart-group",+ user_facing_model_group_name="smart-group",+ )++ assert result is not None+ # opus-like offers all seven levels, mini-like lacks none/xhigh/max; only the common set survives,+ # so the group never advertises an effort routing could hand to a deployment that rejects it.+ assert result.supported_reasoning_efforts == ("minimal", "low", "medium", "high")+++ def test_model_group_info_reasoning_efforts_are_unknown_when_any_deployment_is_off_the_map():+ """The router fills every ModelInfo key, so a deployment absent from the model map arrives with+ supports_reasoning None rather than with the key missing. Its synthesized entry carries no mode,+ which is what separates it from a mapped non-reasoning model, and nothing being known about it is+ no evidence that the unknown deployment accepts levels its mapped sibling supports. The group+ therefore reports unknown instead of advertising a value routing might send to either one."""+ router = litellm.Router(+ model_list=[+ {+ "model_name": "smart-group",+ "litellm_params": {"model": "anthropic/opus-like"},+ "model_info": {"id": "opus-like-deployment"},+ },+ {+ "model_name": "smart-group",+ "litellm_params": {"model": "openai/unmapped-model"},+ "model_info": {"id": "unmapped-deployment"},+ },+ ]+ )++ def _model_info(model_id: str, model_name: str):+ if model_id == "opus-like-deployment":+ return {+ "key": model_name,+ "litellm_provider": "anthropic",+ "mode": "chat",+ "supports_reasoning": True,+ "supports_max_reasoning_effort": True,+ }+ return {"key": model_name, "litellm_provider": "openai", "mode": None, "supports_reasoning": None}++ with patch.object(router, "get_deployment_model_info", side_effect=_model_info):+ result = router._set_model_group_info(+ model_group="smart-group",+ user_facing_model_group_name="smart-group",+ )++ assert result is not None+ assert result.supported_reasoning_efforts is None++++ def test_model_group_info_surfaces_supports_parallel_function_calling(local_model_cost_map):+ """``/model_group/info`` folds each deployment's registry flags into the group; a deployment whose+ registry entry declares parallel function calling must flip the group to True instead of False."""+ router = litellm.Router(+ model_list=[+ {+ "model_name": "glm-group",+ "litellm_params": {"model": "together_ai/zai-org/GLM-5.3-Flash", "api_key": "fake-key"},+ }+ ]+ )++ result = router._set_model_group_info(model_group="glm-group", user_facing_model_group_name="glm-group")++ assert result is not None+ assert result.supports_parallel_function_calling is True+++ def test_model_group_info_reasoning_efforts_empty_on_a_mapped_non_reasoning_deployment():+ """A group mixing a reasoning model with one the map knows is not a reasoning model shares no+ level, so it advertises none and the picker offers nothing rather than a level routing would+ hand to a deployment that rejects it."""+ router = litellm.Router(+ model_list=[+ {+ "model_name": "mixed-group",+ "litellm_params": {"model": "anthropic/opus-like"},+ "model_info": {"id": "opus-like-deployment"},+ },+ {+ "model_name": "mixed-group",+ "litellm_params": {"model": "openai/plain-chat"},+ "model_info": {"id": "plain-chat-deployment"},+ },+ ]+ )++ def _model_info(model_id: str, model_name: str):+ if model_id == "opus-like-deployment":+ return {+ "key": model_name,+ "litellm_provider": "anthropic",+ "mode": "chat",+ "supports_reasoning": True,+ "supports_max_reasoning_effort": True,+ }+ return {"key": model_name, "litellm_provider": "openai", "mode": "chat", "supports_reasoning": None}++ with patch.object(router, "get_deployment_model_info", side_effect=_model_info):+ result = router._set_model_group_info(+ model_group="mixed-group",+ user_facing_model_group_name="mixed-group",+ )++ assert result is not None+ assert result.supported_reasoning_efforts == ()+++ def test_model_group_info_reasoning_efforts_ignore_a_value_declared_in_model_info():+ """The group's levels are computed from its deployments, so a value an operator left in one+ deployment's model_info must not seed them. Seeding let the first deployment read narrow the+ whole group while the same value on any other deployment was silently ignored."""+ router = litellm.Router(+ model_list=[+ {+ "model_name": "declared-group",+ "litellm_params": {"model": "openai/first-reasoner"},+ "model_info": {"id": "first-deployment"},+ },+ {+ "model_name": "declared-group",+ "litellm_params": {"model": "openai/second-reasoner"},+ "model_info": {"id": "second-deployment"},+ },+ ]+ )++ def _model_info(model_id: str, model_name: str):+ info = {+ "key": model_name,+ "litellm_provider": "openai",+ "mode": "chat",+ "supports_reasoning": True,+ "supports_none_reasoning_effort": True,+ }+ if model_id == "first-deployment":+ info["supported_reasoning_efforts"] = ("high",)+ return info++ with patch.object(router, "get_deployment_model_info", side_effect=_model_info):+ result = router._set_model_group_info(+ model_group="declared-group",+ user_facing_model_group_name="declared-group",+ )++ assert result is not None+ assert result.supported_reasoning_efforts == ("none", "minimal", "low", "medium", "high")+++ def test_model_group_info_survives_a_junk_typed_operator_effort_value():+ """A deployment's registered model_info reads back with whatever the operator wrote under any+ key, so a wrong-typed supported_reasoning_efforts must not fail the group's info. Only the+ constructor's trailing override keeps the junk away from ModelGroupInfo validation."""+ router = litellm.Router(+ model_list=[+ {+ "model_name": "junk-declared-group",+ "litellm_params": {"model": "openai/lone-reasoner"},+ "model_info": {"id": "junk-deployment"},+ },+ ]+ )++ def _model_info(model_id: str, model_name: str):+ return {+ "key": model_name,+ "litellm_provider": "openai",+ "mode": "chat",+ "supports_reasoning": True,+ "supports_none_reasoning_effort": True,+ "supported_reasoning_efforts": "high",+ }++ with patch.object(router, "get_deployment_model_info", side_effect=_model_info):+ result = router._set_model_group_info(+ model_group="junk-declared-group",+ user_facing_model_group_name="junk-declared-group",+ )++ assert result is not None+ assert result.supported_reasoning_efforts == ("none", "minimal", "low", "medium", "high")+++ def test_model_group_info_reasoning_efforts_are_unknown_for_an_operator_declared_mode():+ """A deployment is registered in the cost map under its own id with whatever model_info the+ operator wrote, so a mode they set themselves reads back exactly like one the map supplied. Only+ a mode the map supplied marks the deployment as known. An off-map deployment carrying an+ operator mode remains unknown and must keep the whole group's level support unknown."""+ from litellm.router_utils.reasoning_effort_capability import resolve_supported_reasoning_efforts++ mapped_model = "openai/gpt-5.6-sol"+ expected = resolve_supported_reasoning_efforts(+ litellm.get_model_info(model=mapped_model),+ deployment_is_mapped=True,+ )+ assert expected++ router = litellm.Router(+ model_list=[+ {+ "model_name": "smart-group",+ "litellm_params": {"model": mapped_model, "api_key": "sk-fake"},+ "model_info": {"id": "mapped-deployment"},+ },+ {+ "model_name": "smart-group",+ "litellm_params": {"model": "openai/a-model-the-map-never-heard-of", "api_key": "sk-fake"},+ "model_info": {"id": "off-map-deployment", "mode": "chat"},+ },+ ]+ )++ result = router._set_model_group_info(+ model_group="smart-group",+ user_facing_model_group_name="smart-group",+ )++ assert result is not None+ assert result.supported_reasoning_efforts is None+++ class TestAddDeploymentApiBaseProviderResolution:+ def test_bare_model_with_known_api_base_initializes(self):+ router = litellm.Router(+ model_list=[+ {+ "model_name": "groq-pinned",+ "litellm_params": {+ "model": "llama-3.3-70b-versatile",+ "api_base": "https://api.groq.com/openai/v1",+ "api_key": "fake-key",+ },+ },+ {+ "model_name": "deepseek-pinned",+ "litellm_params": {+ "model": "deepseek-chat",+ "api_base": "https://api.deepseek.com/v1",+ "api_key": "fake-key",+ },+ },+ ]+ )++ model_list = router.get_model_list()+ assert model_list is not None+ assert {m["model_name"] for m in model_list} == {"groq-pinned", "deepseek-pinned"}++ def test_bare_model_with_unknown_api_base_still_raises(self):+ with pytest.raises(litellm.BadRequestError, match="LLM Provider NOT provided"):+ litellm.Router(+ model_list=[+ {+ "model_name": "mystery",+ "litellm_params": {+ "model": "some-unknown-model",+ "api_base": "https://llm.internal.example.com/v1",+ "api_key": "fake-key",+ },+ }+ ]+ )++ def test_explicit_custom_llm_provider_beats_api_base_endpoint_match(self):+ router = litellm.Router(+ model_list=[+ {+ "model_name": "openai-via-gateway",+ "litellm_params": {+ "model": "gpt-3.5-turbo",+ "custom_llm_provider": "openai",+ "api_base": "https://api.groq.com/openai/v1",+ "api_key": "fake-key",+ },+ }+ ]+ )++ deployment = router.get_deployment_by_model_group_name("openai-via-gateway")+ assert deployment is not None+ assert deployment.litellm_params.custom_llm_provider == "openai"++ # =====================================================================+ # anthropic_messages mid-stream-fallback helpers, added for #24004+ # (mid-stream fallback not supported for anthropic_messages route type).+ #+ # anthropic_messages goes through _ageneric_api_call_with_fallbacks rather+ # than _acompletion, so its returned iterator was never wrapped by the chat+ # completions fallback handler: an SSE `event: error` frame from a native+ # Anthropic/Bedrock passthrough passed through to the client silently, and a+ # MidStreamFallbackError raised by the completion-bridge path's+ # CustomStreamWrapper (e.g. a Vertex AI transport drop) propagated+ # unhandled.+ #+ # Targets the helpers introduced on Router:+ # - _aanthropic_messages_streaming_iterator+ # - _aanthropic_messages_fallback_attempt+ # - _aanthropic_messages_with_streaming_fallbacks+ # - _dispatch_generic_call_type+ # =====================================================================+++ async def _anthropic_messages_empty_generator():+ return+ yield # pragma: no cover - makes this an async generator+++ def _anthropic_messages_make_wrapper() -> FallbackAwareAnthropicMessagesStream:+ """A minimal wrapper for tests that call _aanthropic_messages_fallback_attempt+ directly, bypassing _aanthropic_messages_streaming_iterator."""+ return FallbackAwareAnthropicMessagesStream(_anthropic_messages_empty_generator(), object())+++ def _anthropic_messages_make_router() -> Router:+ return Router(+ model_list=[+ {+ "model_name": "primary",+ "litellm_params": {+ "model": "anthropic/claude-sonnet-4-5",+ "api_key": "sk-test",+ },+ },+ {+ "model_name": "fallback",+ "litellm_params": {+ "model": "bedrock/anthropic.claude-sonnet-4-5",+ },+ },+ ]+ )+++ class _AnthropicMessagesFakeByteStream:+ """Minimal AsyncIterator[bytes], carrying _hidden_params like+ AnthropicMessagesStreamingResponse does."""++ def __init__(self, chunks: list) -> None:+ self._chunks = list(chunks)+ self._hidden_params = {"additional_headers": {"x-amzn-requestid": "req-1"}}+ self.closed = False++ def __aiter__(self):+ return self++ async def __anext__(self) -> bytes:+ if not self._chunks:+ raise StopAsyncIteration+ return self._chunks.pop(0)++ async def aclose(self) -> None:+ self.closed = True+++ class _AnthropicMessagesRaisingByteStream:+ """Simulates the completion-bridge path: no error SSE chunk is ever+ yielded, the underlying CustomStreamWrapper raises MidStreamFallbackError+ directly out of the iterator instead (a Vertex AI transport drop)."""++ def __init__(self, chunks: list, error: Exception) -> None:+ self._chunks = list(chunks)+ self._error = error+ self._hidden_params: dict = {}+ self.closed = False++ def __aiter__(self):+ return self++ async def __anext__(self) -> bytes:+ if self._chunks:+ return self._chunks.pop(0)+ raise self._error++ async def aclose(self) -> None:+ self.closed = True+++ class _AnthropicMessagesFallbackByteStream:+ def __init__(self, chunks: list, hidden_params: dict | None = None) -> None:+ self._chunks = list(chunks)+ self._hidden_params = hidden_params if hidden_params is not None else {}++ def __aiter__(self):+ return self++ async def __anext__(self) -> bytes:+ if not self._chunks:+ raise StopAsyncIteration+ return self._chunks.pop(0)+++ def _anthropic_messages_overloaded_error_chunk() -> bytes:+ return (+ b"event: error\n"+ b'data: {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}\n\n'+ )+++ def _anthropic_messages_invalid_request_error_chunk() -> bytes:+ return (+ b"event: error\n"+ b'data: {"type": "error", "error": {"type": "invalid_request_error", "message": "bad request"}}\n\n'+ )+++ def _anthropic_messages_rate_limit_error_chunk() -> bytes:+ return (+ b"event: error\n"+ b'data: {"type": "error", "error": {"type": "rate_limit_error", "message": "Too many requests"}}\n\n'+ )+++ def _anthropic_messages_content_chunk(text: str = "hi") -> bytes:+ payload = f'{{"type": "content_block_delta", "delta": {{"type": "text_delta", "text": "{text}"}}}}'+ return f"event: content_block_delta\ndata: {payload}\n\n".encode()+++ def _anthropic_messages_message_start_chunk() -> bytes:+ """A lifecycle/bookkeeping frame Anthropic sends before any real content -+ routinely the very first event before an overload error."""+ return b'event: message_start\ndata: {"type": "message_start", "message": {"id": "msg_1"}}\n\n'+++ def _anthropic_messages_ping_chunk() -> bytes:+ return b'event: ping\ndata: {"type": "ping"}\n\n'+++ # -------- _aanthropic_messages_streaming_iterator (passthrough) --------+++ @pytest.mark.asyncio+ async def test_anthropic_messages_streaming_iterator_passthrough():+ """Without any error chunk, the wrapper forwards every chunk unchanged+ and carries the source iterator's _hidden_params through (so response+ headers like Bedrock's request-id keep flowing to the client)."""+ router = _anthropic_messages_make_router()+ source = _AnthropicMessagesFakeByteStream(+ [_anthropic_messages_content_chunk("hi"), _anthropic_messages_content_chunk(" there")]+ )++ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source, initial_kwargs={"model": "primary"}+ )++ collected = [chunk async for chunk in wrapped]+ assert collected == [_anthropic_messages_content_chunk("hi"), _anthropic_messages_content_chunk(" there")]+ assert wrapped._hidden_params["additional_headers"]["x-amzn-requestid"] == "req-1"+++ @pytest.mark.asyncio+ async def test_anthropic_messages_streaming_iterator_flushes_buffered_lifecycle_frames_in_order():+ """Regression: lifecycle frames held back to guard against a mid-stream+ fallback must still reach the client, in order, once real content+ arrives - buffering them for the fallback-safety check must not silently+ drop them on the happy path."""+ router = _anthropic_messages_make_router()+ message_stop = b'event: message_stop\ndata: {"type": "message_stop"}\n\n'+ source = _AnthropicMessagesFakeByteStream(+ [_anthropic_messages_message_start_chunk(), _anthropic_messages_content_chunk("hi"), message_stop]+ )++ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source, initial_kwargs={"model": "primary"}+ )++ collected = [chunk async for chunk in wrapped]+ assert collected == [_anthropic_messages_message_start_chunk(), _anthropic_messages_content_chunk("hi"), message_stop]+++ @pytest.mark.asyncio+ async def test_anthropic_messages_streaming_iterator_flushes_buffered_frames_on_stream_end():+ """Regression: if the primary stream ends with only lifecycle frames and+ no content and no error, the buffered frames must still reach the+ client rather than being silently swallowed."""+ router = _anthropic_messages_make_router()+ message_stop = b'event: message_stop\ndata: {"type": "message_stop"}\n\n'+ source = _AnthropicMessagesFakeByteStream([_anthropic_messages_message_start_chunk(), message_stop])++ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source, initial_kwargs={"model": "primary"}+ )++ collected = [chunk async for chunk in wrapped]+ assert collected == [_anthropic_messages_message_start_chunk(), message_stop]++ with pytest.raises(StopAsyncIteration):+ await wrapped.__anext__()+++ @pytest.mark.asyncio+ async def test_anthropic_messages_content_coalesced_with_error_in_one_physical_chunk_skips_fallback():+ """Greptile review round: transport-level buffering can coalesce a real+ content_block_delta and a following retriable error into ONE physical+ read from the source iterator. Since the whole chunk (content and error+ together) is forwarded to the client atomically, the client genuinely+ receives the content - so no fallback must be attempted, exactly as if+ the two events had arrived as separate reads."""+ router = _anthropic_messages_make_router()+ coalesced_chunk = _anthropic_messages_content_chunk("partial") + _anthropic_messages_overloaded_error_chunk()+ source = _AnthropicMessagesFakeByteStream([coalesced_chunk])++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(return_value=_AnthropicMessagesFallbackByteStream([])),+ ) as mock_fallback:+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source,+ initial_kwargs={"model": "primary"},+ )+ collected = [chunk async for chunk in wrapped]++ assert collected == [coalesced_chunk]+ mock_fallback.assert_not_awaited()+++ @pytest.mark.asyncio+ async def test_anthropic_messages_ping_behind_buffered_lifecycle_frame_is_dropped():+ """Bugbot regression: a `ping` keepalive behind buffered lifecycle frames+ carries no content and is dropped outright rather than buffered -+ otherwise a slow-starting connection sending many pings could grow the+ pre-content buffer without bound."""+ router = _anthropic_messages_make_router()+ source = _AnthropicMessagesFakeByteStream(+ [+ _anthropic_messages_message_start_chunk(),+ _anthropic_messages_ping_chunk(),+ _anthropic_messages_content_chunk("hi"),+ ]+ )++ wrapped = await router._aanthropic_messages_streaming_iterator(response=source, initial_kwargs={"model": "primary"})+ collected = [chunk async for chunk in wrapped]++ assert collected == [_anthropic_messages_message_start_chunk(), _anthropic_messages_content_chunk("hi")]+++ @pytest.mark.asyncio+ async def test_anthropic_messages_leading_ping_keepalive_is_forwarded_live():+ """A `ping` that no lifecycle frame precedes is how a hold-back turn keeps+ its connection alive (AgenticAnthropicStreamingIterator), so it must reach+ the client at once rather than wait behind the pre-content buffer."""+ router = _anthropic_messages_make_router()+ content_released = asyncio.Event()++ async def source():+ yield _anthropic_messages_ping_chunk()+ await content_released.wait()+ yield _anthropic_messages_message_start_chunk()+ yield _anthropic_messages_content_chunk("hi")++ wrapped = await router._aanthropic_messages_streaming_iterator(response=source(), initial_kwargs={"model": "primary"})++ assert await asyncio.wait_for(wrapped.__anext__(), timeout=1) == _anthropic_messages_ping_chunk()+ content_released.set()+ assert [chunk async for chunk in wrapped] == [+ _anthropic_messages_message_start_chunk(),+ _anthropic_messages_content_chunk("hi"),+ ]+++ @pytest.mark.asyncio+ async def test_anthropic_messages_leading_ping_does_not_disqualify_fallback():+ """A live-forwarded leading `ping` commits nothing: a retriable error after+ it still falls back, and the fallback's own lifecycle follows the ping cleanly."""+ router = _anthropic_messages_make_router()+ source = _AnthropicMessagesFakeByteStream(+ [_anthropic_messages_ping_chunk(), _anthropic_messages_overloaded_error_chunk()]+ )+ fallback_message_start = b'event: message_start\ndata: {"type": "message_start", "message": {"id": "msg_2"}}\n\n'+ fallback_stream = _AnthropicMessagesFallbackByteStream(+ [fallback_message_start, _anthropic_messages_content_chunk("fallback answer")]+ )++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(return_value=fallback_stream),+ ):+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source,+ initial_kwargs={"model": "primary"},+ )+ collected = [chunk async for chunk in wrapped]++ assert collected == [+ _anthropic_messages_ping_chunk(),+ fallback_message_start,+ _anthropic_messages_content_chunk("fallback answer"),+ ]+++ @pytest.mark.asyncio+ async def test_anthropic_messages_hold_back_retrieval_failure_reaches_client_without_fallback():+ """The hold-back iterator's own retrieval-failure frame is the gateway's verdict, not a+ provider failure: a configured fallback stays untouched and the client reads the error+ right after the live keepalive."""+ router = _anthropic_messages_make_router()+ source = _AnthropicMessagesFakeByteStream(+ [_anthropic_messages_ping_chunk(), SERVER_FULFILLED_TOOL_LEAK_ERROR_SSE_BYTES]+ )+ fallback = AsyncMock(+ return_value=_AnthropicMessagesFallbackByteStream([_anthropic_messages_content_chunk("fallback answer")])+ )++ with patch.object(router, "async_function_with_fallbacks_common_utils", new=fallback):+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source,+ initial_kwargs={"model": "primary"},+ )+ collected = [chunk async for chunk in wrapped]++ fallback.assert_not_called()+ assert collected == [_anthropic_messages_ping_chunk(), SERVER_FULFILLED_TOOL_LEAK_ERROR_SSE_BYTES]+++ @pytest.mark.asyncio+ async def test_anthropic_messages_pre_content_buffer_cap_forces_commit():+ """Bugbot regression: a hostile or pathological upstream that never emits+ real content or an error must not grow the pre-content lifecycle buffer+ without bound - hitting MAX_BUFFERED_PRE_CONTENT_ANTHROPIC_CHUNKS commits+ to the primary stream early, exactly as real content arriving would."""+ router = _anthropic_messages_make_router()+ lifecycle_chunk = _anthropic_messages_message_start_chunk()+ error_chunk = _anthropic_messages_overloaded_error_chunk()+ chunks = [lifecycle_chunk] * (MAX_BUFFERED_PRE_CONTENT_ANTHROPIC_CHUNKS + 5) + [error_chunk]+ source = _AnthropicMessagesFakeByteStream(chunks)++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(return_value=_AnthropicMessagesFallbackByteStream([])),+ ) as mock_fallback:+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source, initial_kwargs={"model": "primary"}+ )+ collected = [chunk async for chunk in wrapped]++ mock_fallback.assert_not_awaited()+ assert collected.count(lifecycle_chunk) == MAX_BUFFERED_PRE_CONTENT_ANTHROPIC_CHUNKS + 5+ assert collected[-1] == error_chunk+++ @pytest.mark.asyncio+ async def test_anthropic_messages_ping_coalesced_with_content_in_one_physical_chunk_is_forwarded():+ """Greptile/Bugbot regression: transport-level buffering can coalesce a+ `ping` keepalive and a real content_block_delta into ONE physical read.+ The pre-content ping-drop must only discard PURE ping frames - dropping+ the whole coalesced chunk would silently lose generated content."""+ router = _anthropic_messages_make_router()+ coalesced_chunk = _anthropic_messages_ping_chunk() + _anthropic_messages_content_chunk("hi")+ source = _AnthropicMessagesFakeByteStream([coalesced_chunk])++ wrapped = await router._aanthropic_messages_streaming_iterator(response=source, initial_kwargs={"model": "primary"})+ collected = [chunk async for chunk in wrapped]++ assert collected == [coalesced_chunk]+++ @pytest.mark.asyncio+ async def test_anthropic_messages_ping_coalesced_with_retriable_error_still_falls_back():+ """Greptile/Bugbot regression: a physical chunk coalescing a `ping` with a+ retriable `event: error` must not be discarded as a keepalive - the error+ inside it must still trigger the mid-stream fallback."""+ router = _anthropic_messages_make_router()+ coalesced_chunk = _anthropic_messages_ping_chunk() + _anthropic_messages_overloaded_error_chunk()+ source = _AnthropicMessagesFakeByteStream([coalesced_chunk])+ fallback_stream = _AnthropicMessagesFallbackByteStream([_anthropic_messages_content_chunk("fallback answer")])++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(return_value=fallback_stream),+ ) as mock_fallback:+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source, initial_kwargs={"model": "primary"}+ )+ collected = [chunk async for chunk in wrapped]++ mock_fallback.assert_awaited_once()+ assert collected == [_anthropic_messages_content_chunk("fallback answer")]+++ # -------- _aanthropic_messages_fallback_attempt --------+++ @pytest.mark.asyncio+ async def test_aanthropic_messages_fallback_attempt_yields_fallback_stream():+ """Direct-call regression: the fallback-attempt helper re-enters the+ Router's fallback chain and forwards whatever the fallback produces."""+ router = _anthropic_messages_make_router()+ fallback_stream = _AnthropicMessagesFallbackByteStream([_anthropic_messages_content_chunk("fallback answer")])+ error = MidStreamFallbackError(message="overloaded", model="primary", llm_provider="anthropic")++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(return_value=fallback_stream),+ ) as mock_fallback:+ collected = [+ chunk+ async for chunk in router._aanthropic_messages_fallback_attempt(+ error,+ {"model": "primary", "messages": [{"role": "user", "content": "hi"}]},+ _anthropic_messages_make_wrapper(),+ )+ ]++ assert collected == [_anthropic_messages_content_chunk("fallback answer")]+ mock_fallback.assert_awaited_once()+ assert mock_fallback.await_args.kwargs["e"] is error+++ @pytest.mark.asyncio+ async def test_aanthropic_messages_fallback_attempt_raises_original_exception_on_double_failure():+ """Direct-call regression: when the fallback attempt itself fails with a+ MidStreamFallbackError wrapping a real provider exception, that real+ exception must surface rather than the internal wrapper exception."""+ router = _anthropic_messages_make_router()+ error = MidStreamFallbackError(message="overloaded", model="primary", llm_provider="anthropic")+ original_exception = litellm.APIError(+ status_code=503, message="fallback also overloaded", llm_provider="bedrock", model="fallback"+ )+ fallback_failure = MidStreamFallbackError(+ message="fallback failed", model="fallback", llm_provider="bedrock", original_exception=original_exception+ )++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(side_effect=fallback_failure),+ ):+ with pytest.raises(litellm.APIError) as exc_info:+ async for _ in router._aanthropic_messages_fallback_attempt(+ error, {"model": "primary"}, _anthropic_messages_make_wrapper()+ ):+ pass++ assert exc_info.value is original_exception+++ @pytest.mark.asyncio+ async def test_aanthropic_messages_fallback_attempt_yields_non_streaming_fallback_response():+ """Bugbot regression: a fallback that resolves to a non-streaming+ response (no __aiter__, e.g. an agentic tool-use interception loop) must+ be synthesized into a valid SSE byte sequence, not yielded as a raw dict+ into a byte stream - the generator is typed AsyncGenerator[bytes, None]+ and every item reaching the client must be a real SSE frame."""+ router = _anthropic_messages_make_router()+ error = MidStreamFallbackError(message="overloaded", model="primary", llm_provider="anthropic")+ non_streaming_response = {"id": "msg_1", "type": "message", "content": [{"type": "text", "text": "hi"}]}++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(return_value=non_streaming_response),+ ):+ collected = [+ item+ async for item in router._aanthropic_messages_fallback_attempt(+ error, {"model": "primary"}, _anthropic_messages_make_wrapper()+ )+ ]++ assert all(isinstance(item, bytes) for item in collected)+ event_types = [item.split(b"\n")[0].removeprefix(b"event: ") for item in collected]+ assert event_types == [+ b"message_start",+ b"content_block_start",+ b"content_block_delta",+ b"content_block_stop",+ b"message_delta",+ b"message_stop",+ ]+ assert b'"text": "hi"' in collected[2]+++ @pytest.mark.asyncio+ async def test_aanthropic_messages_fallback_attempt_reraises_plain_exception_on_double_failure():+ """Direct-call regression: when the fallback attempt fails with a plain+ exception (not a MidStreamFallbackError), that exception itself must+ propagate unchanged."""+ router = _anthropic_messages_make_router()+ error = MidStreamFallbackError(message="overloaded", model="primary", llm_provider="anthropic")+ fallback_failure = ValueError("no healthy deployments")++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(side_effect=fallback_failure),+ ):+ with pytest.raises(ValueError, match="no healthy deployments") as exc_info:+ async for _ in router._aanthropic_messages_fallback_attempt(+ error, {"model": "primary"}, _anthropic_messages_make_wrapper()+ ):+ pass++ assert exc_info.value is fallback_failure+++ # -------- _aanthropic_messages_with_streaming_fallbacks --------+++ @pytest.mark.asyncio+ async def test_aanthropic_messages_with_streaming_fallbacks_non_streaming_passthrough():+ """A non-streaming response (plain dict) is returned unchanged, never wrapped."""+ router = _anthropic_messages_make_router()+ plain_response = {"id": "msg_1", "type": "message"}++ async def fake_original(**_kwargs):+ return plain_response++ with patch.object(+ router,+ "_ageneric_api_call_with_fallbacks",+ new=AsyncMock(return_value=plain_response),+ ):+ out = await router._aanthropic_messages_with_streaming_fallbacks(+ original_function=fake_original,+ model="primary",+ stream=False,+ )+ assert out is plain_response+++ @pytest.mark.asyncio+ async def test_aanthropic_messages_with_streaming_fallbacks_wraps_streaming_iterator():+ """A streaming response is wrapped via _aanthropic_messages_streaming_iterator."""+ router = _anthropic_messages_make_router()+ streaming_iter = _AnthropicMessagesFakeByteStream([_anthropic_messages_content_chunk()])+ wrapped_marker = object()++ async def fake_original(**_kwargs):+ return streaming_iter++ with (+ patch.object(+ router,+ "_ageneric_api_call_with_fallbacks",+ new=AsyncMock(return_value=streaming_iter),+ ),+ patch.object(+ router,+ "_aanthropic_messages_streaming_iterator",+ new=AsyncMock(return_value=wrapped_marker),+ ) as mock_wrap,+ ):+ out = await router._aanthropic_messages_with_streaming_fallbacks(+ original_function=fake_original,+ model="primary",+ stream=True,+ )+ assert out is wrapped_marker+ mock_wrap.assert_awaited_once()+++ # -------- mid-stream error handling --------+++ @pytest.mark.asyncio+ async def test_anthropic_messages_fallback_on_pre_first_chunk_error_event():+ """Regression for #24004: a retriable SSE `event: error` frame+ (overloaded_error/internal_server_error) that arrives before any real+ content must trigger the router's fallback chain instead of passing+ through to the client silently."""+ router = _anthropic_messages_make_router()+ source = _AnthropicMessagesFakeByteStream([_anthropic_messages_overloaded_error_chunk()])+ fallback_stream = _AnthropicMessagesFallbackByteStream([_anthropic_messages_content_chunk("fallback answer")])++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(return_value=fallback_stream),+ ) as mock_fallback:+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source,+ initial_kwargs={"model": "primary", "messages": [{"role": "user", "content": "hi"}]},+ )+ collected = [chunk async for chunk in wrapped]++ assert collected == [_anthropic_messages_content_chunk("fallback answer")]+ mock_fallback.assert_awaited_once()+ raised = mock_fallback.await_args.kwargs["e"]+ assert isinstance(raised, MidStreamFallbackError)+ assert raised.status_code == 503+ assert raised.is_pre_first_chunk is True+ assert source.closed is True+++ @pytest.mark.asyncio+ async def test_anthropic_messages_mid_stream_error_preserves_real_status_code():+ """Bugbot regression: the MidStreamFallbackError raised for a detected SSE+ `event: error` frame must carry the error's REAL parsed status code+ (via original_exception), not silently default to 503 for every error+ type - a rate_limit_error (429) must surface as 429, not 503."""+ router = _anthropic_messages_make_router()+ source = _AnthropicMessagesFakeByteStream([_anthropic_messages_rate_limit_error_chunk()])+ fallback_stream = _AnthropicMessagesFallbackByteStream([_anthropic_messages_content_chunk("fallback answer")])++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(return_value=fallback_stream),+ ) as mock_fallback:+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source,+ initial_kwargs={"model": "primary", "messages": [{"role": "user", "content": "hi"}]},+ )+ [chunk async for chunk in wrapped]++ raised = mock_fallback.await_args.kwargs["e"]+ assert isinstance(raised, MidStreamFallbackError)+ assert raised.status_code == 429+ assert raised.original_exception is not None+ assert raised.original_exception.status_code == 429+ assert raised.original_exception.llm_provider == "anthropic"+++ def test_merge_fallback_hidden_params_direct_call():+ """Direct-call regression: merge_fallback_hidden_params combines the+ fallback's hidden params/headers with whatever was already present,+ with the fallback's values winning on key collisions."""+ wrapper = FallbackAwareAnthropicMessagesStream(+ _anthropic_messages_empty_generator(),+ _AnthropicMessagesFakeByteStream([]), # carries {"additional_headers": {"x-amzn-requestid": "req-1"}}+ )+ wrapper.merge_fallback_hidden_params(+ {"model_id": "fallback-deployment"},+ {"x-amzn-requestid": "req-2", "x-fallback-only": "yes"},+ )+ assert wrapper._hidden_params["model_id"] == "fallback-deployment"+ assert wrapper._hidden_params["additional_headers"] == {+ "x-amzn-requestid": "req-2",+ "x-fallback-only": "yes",+ }+++ def test_anthropic_stream_should_drop_pre_content_ping_direct_call():+ ping = _anthropic_messages_ping_chunk()+ content = _anthropic_messages_content_chunk("hi")+ assert _anthropic_stream_should_drop_pre_content_ping(ping, has_generated_content=False) is True+ assert _anthropic_stream_should_drop_pre_content_ping(ping, has_generated_content=True) is False+ assert _anthropic_stream_should_drop_pre_content_ping(content, has_generated_content=False) is False+++ def test_anthropic_stream_forwards_ping_live_direct_call():+ ping = _anthropic_messages_ping_chunk()+ content = _anthropic_messages_content_chunk("hi")+ assert _anthropic_stream_forwards_ping_live(ping, has_generated_content=False, buffered_chunk_count=0) is True+ assert _anthropic_stream_forwards_ping_live(ping, has_generated_content=False, buffered_chunk_count=1) is False+ assert _anthropic_stream_forwards_ping_live(ping, has_generated_content=True, buffered_chunk_count=0) is False+ assert _anthropic_stream_forwards_ping_live(content, has_generated_content=False, buffered_chunk_count=0) is False+++ def test_anthropic_stream_error_is_gateway_verdict_direct_call():+ assert _anthropic_stream_error_is_gateway_verdict(SERVER_FULFILLED_TOOL_LEAK_ERROR_SSE_BYTES) is True+ assert _anthropic_stream_error_is_gateway_verdict(_anthropic_messages_overloaded_error_chunk()) is False+ assert _anthropic_stream_error_is_gateway_verdict(_anthropic_messages_ping_chunk()) is False+++ def test_fallback_aware_stream_reports_withheld_output_of_its_current_source():+ """The proxy's cancel-refund guard reads this flag off the router wrapper, so it+ must reflect the stream actually being drained: the primary, then the fallback."""++ class _HoldingBack:+ _hidden_params = {"additional_headers": {}}+ has_buffered_provider_output = True++ wrapper = FallbackAwareAnthropicMessagesStream(_anthropic_messages_empty_generator(), _HoldingBack())+ assert wrapper.has_buffered_provider_output is True++ wrapper.adopt_fallback_source(_AnthropicMessagesFakeByteStream([]))+ assert wrapper.has_buffered_provider_output is False+++ def test_is_retriable_anthropic_status_direct_call():+ assert _is_retriable_anthropic_status(429) is True+ assert _is_retriable_anthropic_status(503) is True+ assert _is_retriable_anthropic_status(500) is True+ assert _is_retriable_anthropic_status(400) is False+ assert _is_retriable_anthropic_status(404) is False+++ def test_anthropic_stream_should_decline_fallback_direct_call():+ pre_first_chunk_error = MidStreamFallbackError(+ message="overloaded", model="primary", llm_provider="anthropic", is_pre_first_chunk=True+ )+ post_first_chunk_error = MidStreamFallbackError(+ message="overloaded", model="primary", llm_provider="anthropic", is_pre_first_chunk=False+ )+ assert _anthropic_stream_should_decline_fallback(False, pre_first_chunk_error) is False+ assert _anthropic_stream_should_decline_fallback(True, pre_first_chunk_error) is True+ assert _anthropic_stream_should_decline_fallback(False, post_first_chunk_error) is True+++ def test_anthropic_stream_commits_now_direct_call():+ content = _anthropic_messages_content_chunk("hi")+ lifecycle_chunk = _anthropic_messages_message_start_chunk()+ assert _anthropic_stream_commits_now(content, has_generated_content=False, buffered_chunk_count=0) is True+ assert _anthropic_stream_commits_now(content, has_generated_content=True, buffered_chunk_count=0) is False+ assert (+ _anthropic_stream_commits_now(+ lifecycle_chunk,+ has_generated_content=False,+ buffered_chunk_count=MAX_BUFFERED_PRE_CONTENT_ANTHROPIC_CHUNKS,+ )+ is True+ )+ assert (+ _anthropic_stream_commits_now(+ lifecycle_chunk,+ has_generated_content=False,+ buffered_chunk_count=MAX_BUFFERED_PRE_CONTENT_ANTHROPIC_CHUNKS - 1,+ )+ is False+ )+++ @pytest.mark.asyncio+ async def test_anthropic_messages_fallback_merges_fallback_hidden_params():+ """Bugbot regression: after a successful mid-stream fallback, the+ wrapper's _hidden_params must reflect the FALLBACK deployment's own+ provider headers (e.g. a different Bedrock request-id), not stay+ frozen on the primary's - raw bytes can't carry per-item _hidden_params+ the way a ModelResponseStream/ResponsesAPI event can, so the wrapper+ itself is the only place left to expose them."""+ router = _anthropic_messages_make_router()+ source = _AnthropicMessagesFakeByteStream(+ [_anthropic_messages_overloaded_error_chunk()]+ ) # carries x-amzn-requestid: req-1+ fallback_stream = _AnthropicMessagesFallbackByteStream(+ [_anthropic_messages_content_chunk("fallback answer")],+ hidden_params={"additional_headers": {"x-amzn-requestid": "req-2", "x-fallback-only": "yes"}},+ )++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(return_value=fallback_stream),+ ):+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source,+ initial_kwargs={"model": "primary"},+ )+ _ = [chunk async for chunk in wrapped]++ headers = wrapped._hidden_params["additional_headers"]+ assert headers["x-amzn-requestid"] == "req-2"+ assert headers["x-fallback-only"] == "yes"+++ @pytest.mark.asyncio+ async def test_aanthropic_messages_with_streaming_fallbacks_deep_copies_nested_metadata():+ """Bugbot regression: a shallow .copy() of kwargs still shares the+ nested litellm_metadata/metadata dict objects with the primary attempt.+ _update_kwargs_with_deployment mutates that dict in place with+ deployment-specific fields, which must not leak into the fallback+ request's metadata."""+ router = _anthropic_messages_make_router()+ primary_metadata = {"model_group": "primary"}+ streaming_iter_kwargs = {}++ async def fake_original(**_kwargs):+ # Simulate _update_kwargs_with_deployment mutating the primary's+ # litellm_metadata in place, as the real helper does.+ primary_metadata["deployment"] = "primary-deployment-object"+ return _AnthropicMessagesFakeByteStream([_anthropic_messages_content_chunk("hi")])++ with patch.object(+ router,+ "_aanthropic_messages_streaming_iterator",+ new=AsyncMock(side_effect=lambda **kwargs: streaming_iter_kwargs.update(kwargs) or "wrapped"),+ ):+ with patch.object(+ router,+ "_ageneric_api_call_with_fallbacks",+ new=AsyncMock(side_effect=fake_original),+ ):+ await router._aanthropic_messages_with_streaming_fallbacks(+ original_function=fake_original,+ model="primary",+ stream=True,+ litellm_metadata=primary_metadata,+ )++ fallback_kwargs = streaming_iter_kwargs["initial_kwargs"]+ assert fallback_kwargs["litellm_metadata"] is not primary_metadata+ assert "deployment" not in fallback_kwargs["litellm_metadata"]+++ @pytest.mark.asyncio+ async def test_aanthropic_messages_with_streaming_fallbacks_deep_copies_metadata_field():+ """Same regression as above for the (separate) `metadata` kwarg some+ call sites use instead of `litellm_metadata`."""+ router = _anthropic_messages_make_router()+ primary_metadata = {"tag": "primary"}+ streaming_iter_kwargs = {}++ async def fake_original(**_kwargs):+ primary_metadata["deployment"] = "primary-deployment-object"+ return _AnthropicMessagesFakeByteStream([_anthropic_messages_content_chunk("hi")])++ with patch.object(+ router,+ "_aanthropic_messages_streaming_iterator",+ new=AsyncMock(side_effect=lambda **kwargs: streaming_iter_kwargs.update(kwargs) or "wrapped"),+ ):+ with patch.object(+ router,+ "_ageneric_api_call_with_fallbacks",+ new=AsyncMock(side_effect=fake_original),+ ):+ await router._aanthropic_messages_with_streaming_fallbacks(+ original_function=fake_original,+ model="primary",+ stream=True,+ metadata=primary_metadata,+ )++ fallback_kwargs = streaming_iter_kwargs["initial_kwargs"]+ assert fallback_kwargs["metadata"] is not primary_metadata+ assert "deployment" not in fallback_kwargs["metadata"]+++ @pytest.mark.asyncio+ async def test_anthropic_messages_fallback_triggers_after_lifecycle_only_frame():+ """Regression: Anthropic routinely sends a message_start lifecycle frame+ before an overload error even fires. A lifecycle-only frame (no real+ content) must not disqualify the fallback attempt, and must not reach+ the client either - forwarding it and then appending the fallback's own+ message_start would produce two overlapping message lifecycles on one+ SSE stream. The primary's buffered lifecycle frame is discarded and the+ client sees only the fallback's own, single, clean lifecycle."""+ router = _anthropic_messages_make_router()+ source = _AnthropicMessagesFakeByteStream(+ [_anthropic_messages_message_start_chunk(), _anthropic_messages_overloaded_error_chunk()]+ )+ fallback_message_start = b'event: message_start\ndata: {"type": "message_start", "message": {"id": "msg_2"}}\n\n'+ fallback_stream = _AnthropicMessagesFallbackByteStream(+ [fallback_message_start, _anthropic_messages_content_chunk("fallback answer")]+ )++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(return_value=fallback_stream),+ ) as mock_fallback:+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source,+ initial_kwargs={"model": "primary"},+ )+ collected = [chunk async for chunk in wrapped]++ assert collected == [fallback_message_start, _anthropic_messages_content_chunk("fallback answer")]+ assert collected.count(_anthropic_messages_message_start_chunk()) == 0, (+ "the primary's message_start must never reach the client"+ )+ assert sum(1 for c in collected if c.startswith(b"event: message_start")) == 1, (+ "exactly one message_start must reach the client"+ )+ mock_fallback.assert_awaited_once()+ raised = mock_fallback.await_args.kwargs["e"]+ assert raised.is_pre_first_chunk is True+++ @pytest.mark.asyncio+ async def test_anthropic_messages_raised_error_after_real_content_does_not_restart_stream():+ """Regression: a MidStreamFallbackError raised directly by the source+ iterator (the completion-bridge path's CustomStreamWrapper, e.g. a+ transport drop) must not trigger a fallback once real content already+ reached the client - that would append a second, overlapping message+ lifecycle onto the same SSE stream. The original exception must+ propagate to the caller instead."""+ router = _anthropic_messages_make_router()+ content = _anthropic_messages_content_chunk("partial answer")+ original_exception = litellm.APIError(+ status_code=503,+ message="stream reset",+ llm_provider="vertex_ai",+ model="primary",+ )+ raised_error = MidStreamFallbackError(+ message="stream reset",+ model="primary",+ llm_provider="vertex_ai",+ original_exception=original_exception,+ is_pre_first_chunk=False,+ )+ source = _AnthropicMessagesRaisingByteStream([content], raised_error)++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(),+ ) as mock_fallback:+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source,+ initial_kwargs={"model": "primary"},+ )+ collected = []++ async def _consume():+ async for chunk in wrapped:+ collected.append(chunk)++ with pytest.raises(litellm.APIError) as exc_info:+ await _consume()++ assert collected == [content]+ assert exc_info.value is original_exception+ mock_fallback.assert_not_awaited()+++ @pytest.mark.asyncio+ async def test_anthropic_messages_fallback_also_catches_raised_midstream_error():+ """Regression for the completion-bridge path (deployments with no native+ /v1/messages endpoint): its CustomStreamWrapper raises+ MidStreamFallbackError directly (e.g. on a Vertex AI transport drop)+ instead of yielding an SSE error chunk - the wrapper must catch that too."""+ router = _anthropic_messages_make_router()+ raised_error = MidStreamFallbackError(+ message="stream reset",+ model="primary",+ llm_provider="vertex_ai",+ is_pre_first_chunk=True,+ )+ source = _AnthropicMessagesRaisingByteStream([], raised_error)+ fallback_stream = _AnthropicMessagesFallbackByteStream([_anthropic_messages_content_chunk("fallback answer")])++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(return_value=fallback_stream),+ ) as mock_fallback:+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source,+ initial_kwargs={"model": "primary"},+ )+ collected = [chunk async for chunk in wrapped]++ assert collected == [_anthropic_messages_content_chunk("fallback answer")]+ mock_fallback.assert_awaited_once()+ assert mock_fallback.await_args.kwargs["e"] is raised_error+++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "raised_error",+ [+ BedrockError(status_code=503, message='serviceUnavailableException {"message": "Service unavailable"}'),+ BedrockError(status_code=500, message='internalServerException {"message": "Internal error"}'),+ BedrockError(status_code=429, message='throttlingException {"message": "Too many requests"}'),+ httpx.ReadError("connection reset by upstream"),+ ],+ ids=["503", "500", "429", "transport-drop"],+ )+ async def test_anthropic_messages_raised_provider_error_before_content_triggers_fallback(raised_error):+ """A retriable raise before content falls over exactly like a detected SSE error event."""+ router = _anthropic_messages_make_router()+ source = _AnthropicMessagesRaisingByteStream([_anthropic_messages_message_start_chunk()], raised_error)+ fallback_stream = _AnthropicMessagesFallbackByteStream([_anthropic_messages_content_chunk("fallback answer")])++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(return_value=fallback_stream),+ ) as mock_fallback:+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source,+ initial_kwargs={"model": "primary"},+ )+ collected = [chunk async for chunk in wrapped]++ assert collected == [_anthropic_messages_content_chunk("fallback answer")]+ mock_fallback.assert_awaited_once()+ converted = mock_fallback.await_args.kwargs["e"]+ assert isinstance(converted, MidStreamFallbackError)+ assert converted.original_exception is raised_error+ assert converted.is_pre_first_chunk is True+ assert source.closed is True+++ class _AnthropicMessagesStringStatusError(Exception):+ def __init__(self):+ super().__init__("bad request")+ self.status_code = "400"+++ class _AnthropicMessagesResponseOnlyStatusError(Exception):+ def __init__(self):+ super().__init__("bad request")+ self.response = SimpleNamespace(status_code=400)+++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "raised_error",+ [+ BedrockError(status_code=400, message='validationException {"message": "Malformed input"}'),+ BedrockError(status_code=424, message='modelStreamErrorException {"message": "Model stream error"}'),+ _AnthropicMessagesStringStatusError(),+ _AnthropicMessagesResponseOnlyStatusError(),+ ],+ ids=["400", "424", "str-400", "response-only-400"],+ )+ async def test_anthropic_messages_raised_non_retriable_provider_error_propagates_unchanged(raised_error):+ """A raised client error reaches the caller as the same exception, nothing flushed, no fallback."""+ router = _anthropic_messages_make_router()+ source = _AnthropicMessagesRaisingByteStream([_anthropic_messages_message_start_chunk()], raised_error)++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(),+ ) as mock_fallback:+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source,+ initial_kwargs={"model": "primary"},+ )+ collected = []++ async def _consume():+ async for chunk in wrapped:+ collected.append(chunk)++ with pytest.raises(type(raised_error)) as exc_info:+ await _consume()++ assert collected == []+ assert exc_info.value is raised_error+ mock_fallback.assert_not_awaited()+++ @pytest.mark.asyncio+ async def test_anthropic_messages_raised_provider_error_after_content_propagates_unchanged():+ """A raise after content propagates unchanged even when its status is retriable."""+ router = _anthropic_messages_make_router()+ content = _anthropic_messages_content_chunk("partial answer")+ raised_error = BedrockError(+ status_code=503, message='serviceUnavailableException {"message": "Service unavailable"}'+ )+ source = _AnthropicMessagesRaisingByteStream([content], raised_error)++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(),+ ) as mock_fallback:+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source,+ initial_kwargs={"model": "primary"},+ )+ collected = []++ async def _consume():+ async for chunk in wrapped:+ collected.append(chunk)++ with pytest.raises(BedrockError) as exc_info:+ await _consume()++ assert collected == [content]+ assert exc_info.value is raised_error+ mock_fallback.assert_not_awaited()+++ @pytest.mark.parametrize(+ "error, expected_status",+ [+ (BedrockError(status_code=503, message="unavailable"), 503),+ (_AnthropicMessagesStringStatusError(), 400),+ (_AnthropicMessagesResponseOnlyStatusError(), 400),+ (httpx.ReadError("connection reset by upstream"), None),+ ],+ ids=["int", "digit-str", "response-only", "none"],+ )+ def test_anthropic_stream_raised_error_status_reads_every_status_shape(error, expected_status):+ assert _anthropic_stream_raised_error_status(error) == expected_status+++ @pytest.mark.parametrize(+ "error, has_generated_content, converts",+ [+ (BedrockError(status_code=503, message="unavailable"), False, True),+ (httpx.ReadError("connection reset by upstream"), False, True),+ (BedrockError(status_code=400, message="malformed"), False, False),+ (BedrockError(status_code=503, message="unavailable"), True, False),+ ],+ ids=["retriable", "no-status", "client-error", "after-content"],+ )+ def test_anthropic_stream_fallback_error_for_raised_gates_like_a_detected_error_event(+ error, has_generated_content, converts+ ):+ converted = _anthropic_stream_fallback_error_for_raised(error, "primary", has_generated_content)+ if not converts:+ assert converted is None+ return+ assert isinstance(converted, MidStreamFallbackError)+ assert converted.original_exception is error+ assert converted.is_pre_first_chunk is True+ assert converted.llm_provider == "anthropic"+++ @pytest.mark.asyncio+ async def test_aanthropic_messages_recover_stream_error_flushes_buffered_frames_before_declining():+ router = _anthropic_messages_make_router()+ original = BedrockError(status_code=503, message="unavailable")+ declined = MidStreamFallbackError(+ message="unavailable",+ model="primary",+ llm_provider="anthropic",+ original_exception=original,+ is_pre_first_chunk=False,+ )+ buffered = (_anthropic_messages_message_start_chunk(),)+ flushed = []++ async def drain(recovery) -> None:+ async for chunk in recovery:+ flushed.append(chunk)++ with patch.object(router, "_aanthropic_messages_fallback_attempt") as mock_attempt:+ recovery = router._aanthropic_messages_recover_stream_error(+ declined, True, buffered, "primary", {"model": "primary"}, _anthropic_messages_make_wrapper()+ )+ with pytest.raises(BedrockError) as exc_info:+ await drain(recovery)+ assert flushed == list(buffered)+ assert exc_info.value is original+ mock_attempt.assert_not_called()+++ @pytest.mark.asyncio+ async def test_aanthropic_messages_recover_stream_error_hands_converted_raise_to_fallback_attempt():+ router = _anthropic_messages_make_router()+ raised = BedrockError(status_code=503, message="unavailable")+ handed_over = []++ async def fake_attempt(fallback_error, initial_kwargs, wrapper):+ handed_over.append(fallback_error)+ yield b"fallback"++ with patch.object(router, "_aanthropic_messages_fallback_attempt", new=fake_attempt):+ recovery = router._aanthropic_messages_recover_stream_error(+ raised, False, (), "primary", {"model": "primary"}, _anthropic_messages_make_wrapper()+ )+ collected = [chunk async for chunk in recovery]+ assert collected == [b"fallback"]+ assert len(handed_over) == 1+ assert isinstance(handed_over[0], MidStreamFallbackError)+ assert handed_over[0].original_exception is raised+++ @pytest.mark.asyncio+ async def test_anthropic_messages_non_retriable_client_error_skips_fallback():+ """A 4xx (non-429) error type (e.g. invalid_request_error) is a client+ error a fallback attempt cannot fix, so it must be forwarded to the+ client as-is rather than burning a fallback attempt."""+ router = _anthropic_messages_make_router()+ error_chunk = _anthropic_messages_invalid_request_error_chunk()+ source = _AnthropicMessagesFakeByteStream([error_chunk])++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(),+ ) as mock_fallback:+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source,+ initial_kwargs={"model": "primary"},+ )+ collected = [chunk async for chunk in wrapped]++ assert collected == [error_chunk]+ mock_fallback.assert_not_awaited()+++ @pytest.mark.asyncio+ async def test_anthropic_messages_post_first_chunk_error_skips_fallback():+ """Once content has already reached the caller, retrying would start a+ second, overlapping Anthropic message lifecycle on the same SSE stream -+ the error must be forwarded instead of triggering an invisible retry."""+ router = _anthropic_messages_make_router()+ content = _anthropic_messages_content_chunk("partial answer")+ error_chunk = _anthropic_messages_overloaded_error_chunk()+ source = _AnthropicMessagesFakeByteStream([content, error_chunk])++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(),+ ) as mock_fallback:+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source,+ initial_kwargs={"model": "primary"},+ )+ collected = [chunk async for chunk in wrapped]++ assert collected == [content, error_chunk]+ mock_fallback.assert_not_awaited()+++ @pytest.mark.asyncio+ async def test_anthropic_messages_non_retriable_error_flushes_buffered_lifecycle_frames():+ """A non-retriable error arriving while lifecycle frames are still+ buffered (no content seen yet) must flush those buffered frames before+ forwarding the error, so the client still sees the whole primary+ attempt rather than losing the buffered message_start silently."""+ router = _anthropic_messages_make_router()+ error_chunk = _anthropic_messages_invalid_request_error_chunk()+ source = _AnthropicMessagesFakeByteStream([_anthropic_messages_message_start_chunk(), error_chunk])++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(),+ ) as mock_fallback:+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source,+ initial_kwargs={"model": "primary"},+ )+ collected = [chunk async for chunk in wrapped]++ assert collected == [_anthropic_messages_message_start_chunk(), error_chunk]+ mock_fallback.assert_not_awaited()+++ @pytest.mark.asyncio+ async def test_anthropic_messages_raised_error_declined_flushes_buffered_lifecycle_frames():+ """When a raised MidStreamFallbackError is declined (source says content+ was not pre-first-chunk) while lifecycle frames are still buffered, they+ must be flushed to the client before the exception propagates."""+ router = _anthropic_messages_make_router()+ raised_error = MidStreamFallbackError(+ message="stream reset",+ model="primary",+ llm_provider="vertex_ai",+ is_pre_first_chunk=False,+ )+ source = _AnthropicMessagesRaisingByteStream([_anthropic_messages_message_start_chunk()], raised_error)++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(),+ ) as mock_fallback:+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source,+ initial_kwargs={"model": "primary"},+ )+ collected = []++ async def _consume():+ async for chunk in wrapped:+ collected.append(chunk)++ with pytest.raises(MidStreamFallbackError) as exc_info:+ await _consume()++ assert collected == [_anthropic_messages_message_start_chunk()]+ assert exc_info.value is raised_error+ mock_fallback.assert_not_awaited()+++ @pytest.mark.asyncio+ async def test_anthropic_messages_raised_error_without_original_exception_reraises_itself():+ """When a declined MidStreamFallbackError carries no original_exception,+ the bare exception itself must propagate rather than being swallowed."""+ router = _anthropic_messages_make_router()+ content = _anthropic_messages_content_chunk("partial answer")+ raised_error = MidStreamFallbackError(+ message="stream reset",+ model="primary",+ llm_provider="vertex_ai",+ is_pre_first_chunk=False,+ )+ source = _AnthropicMessagesRaisingByteStream([content], raised_error)++ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source,+ initial_kwargs={"model": "primary"},+ )+ collected = []++ async def _consume():+ async for chunk in wrapped:+ collected.append(chunk)++ with pytest.raises(MidStreamFallbackError) as exc_info:+ await _consume()++ assert collected == [content]+ assert exc_info.value is raised_error+++ @pytest.mark.asyncio+ async def test_anthropic_messages_fallback_also_failing_raises_original_exception():+ """If the fallback attempt itself fails with a MidStreamFallbackError+ wrapping a real provider exception, the client must see that real+ exception, not the internal MidStreamFallbackError."""+ router = _anthropic_messages_make_router()+ source = _AnthropicMessagesFakeByteStream([_anthropic_messages_overloaded_error_chunk()])+ original_exception = litellm.APIError(+ status_code=503,+ message="fallback also overloaded",+ llm_provider="bedrock",+ model="fallback",+ )+ fallback_failure = MidStreamFallbackError(+ message="fallback failed",+ model="fallback",+ llm_provider="bedrock",+ original_exception=original_exception,+ )++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(side_effect=fallback_failure),+ ):+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source,+ initial_kwargs={"model": "primary"},+ )+ with pytest.raises(litellm.APIError) as exc_info:+ async for _ in wrapped:+ pass++ assert exc_info.value is original_exception+++ # -------- _dispatch_generic_call_type --------+++ @pytest.mark.asyncio+ async def test_dispatch_generic_call_type_routes_anthropic_messages_through_streaming_fallbacks():+ router = _anthropic_messages_make_router()++ async def fake_original(**_kwargs):+ return {"id": "msg_1"}++ with patch.object(+ router,+ "_aanthropic_messages_with_streaming_fallbacks",+ new=AsyncMock(return_value="anthropic-result"),+ ) as mock_anthropic:+ out = await router._dispatch_generic_call_type(+ call_type="anthropic_messages",+ original_function=fake_original,+ model="primary",+ )+ assert out == "anthropic-result"+ mock_anthropic.assert_awaited_once()+++ @pytest.mark.asyncio+ async def test_dispatch_generic_call_type_other_call_types_use_generic_fallback():+ router = _anthropic_messages_make_router()++ async def fake_original(**_kwargs):+ return {"id": "file_1"}++ with patch.object(+ router,+ "_ageneric_api_call_with_fallbacks",+ new=AsyncMock(return_value="generic-result"),+ ) as mock_generic:+ out = await router._dispatch_generic_call_type(+ call_type="afile_delete",+ original_function=fake_original,+ model="primary",+ )+ assert out == "generic-result"+ mock_generic.assert_awaited_once()+++ @pytest.mark.asyncio+ async def test_factory_function_anthropic_messages_uses_streaming_fallback_dispatch():+ """anthropic_messages must be wired through the mid-stream-fallback-aware+ path rather than the bare generic dispatch every other call type without+ special handling uses."""+ router = _anthropic_messages_make_router()+ wrapped = router.factory_function(litellm.anthropic_messages, call_type="anthropic_messages")+ assert callable(wrapped)++ with patch.object(+ router,+ "_aanthropic_messages_with_streaming_fallbacks",+ new=AsyncMock(return_value="ok"),+ ) as mock_anthropic:+ result = await wrapped(model="primary")+ assert result == "ok"+ mock_anthropic.assert_awaited_once()+++ @pytest.mark.asyncio+ async def test_async_function_with_fallbacks_stamps_zero_attempted_fallbacks():+ """A request served by the primary model group records attempted_fallbacks=0 and+ the requested model group in metadata, mirroring the x-litellm-attempted-fallbacks header."""+ router = litellm.Router(+ model_list=[+ {+ "model_name": "gpt-3.5-turbo",+ "litellm_params": {"model": "gpt-3.5-turbo", "mock_response": "hi"},+ }+ ]+ )+ metadata = {}++ await router.acompletion(+ model="gpt-3.5-turbo",+ messages=[{"role": "user", "content": "hey"}],+ metadata=metadata,+ )++ assert metadata["attempted_fallbacks"] == 0+ assert metadata["original_model_group"] == "gpt-3.5-turbo"+++ @pytest.mark.asyncio+ async def test_async_function_with_fallbacks_stamps_route_bucket_not_litellm_metadata():+ """A chat completion carrying both metadata buckets gets stamped in the route's bucket+ (metadata), matching where run_async_fallback rewrites, so the two never diverge."""+ router = litellm.Router(+ model_list=[+ {+ "model_name": "gpt-3.5-turbo",+ "litellm_params": {"model": "gpt-3.5-turbo", "mock_response": "hi"},+ }+ ]+ )+ metadata = {}+ litellm_metadata = {"client_key": "client_value"}++ await router.acompletion(+ model="gpt-3.5-turbo",+ messages=[{"role": "user", "content": "hey"}],+ metadata=metadata,+ litellm_metadata=litellm_metadata,+ )++ assert metadata["attempted_fallbacks"] == 0+ assert metadata["original_model_group"] == "gpt-3.5-turbo"+ assert litellm_metadata["client_key"] == "client_value"+ assert "attempted_fallbacks" not in litellm_metadata+ assert "original_model_group" not in litellm_metadata+++ @pytest.mark.asyncio+ async def test_async_function_with_fallbacks_overrides_client_supplied_stamp_values():+ """Client-supplied attempted_fallbacks and original_model_group are replaced on entry,+ so a reused metadata dict or a spoofed value cannot leak stale attribution into logs."""+ router = litellm.Router(+ model_list=[+ {+ "model_name": "gpt-3.5-turbo",+ "litellm_params": {"model": "gpt-3.5-turbo", "mock_response": "hi"},+ }+ ]+ )+ metadata = {"attempted_fallbacks": 99, "original_model_group": "stale-group"}++ await router.acompletion(+ model="gpt-3.5-turbo",+ messages=[{"role": "user", "content": "hey"}],+ metadata=metadata,+ )++ assert metadata["attempted_fallbacks"] == 0+ assert metadata["original_model_group"] == "gpt-3.5-turbo"+++ @pytest.mark.asyncio+ async def test_async_function_with_fallbacks_stamps_despite_forged_reentry_params():+ """A client injecting fallback_depth or a JSON-shaped attempted_targets via request+ litellm params cannot skip the entry stamp; only the router's own in-process+ AttemptedFallbackTargets instance marks a genuine re-entrant hop."""+ router = litellm.Router(+ model_list=[+ {+ "model_name": "gpt-3.5-turbo",+ "litellm_params": {"model": "gpt-3.5-turbo", "mock_response": "hi"},+ }+ ]+ )+ metadata = {"attempted_fallbacks": 99, "original_model_group": "spoofed-group"}++ await router.acompletion(+ model="gpt-3.5-turbo",+ messages=[{"role": "user", "content": "hey"}],+ metadata=metadata,+ fallback_depth=3,+ attempted_targets={"keys": ["spoofed-group"]},+ )++ assert metadata["attempted_fallbacks"] == 0+ assert metadata["original_model_group"] == "gpt-3.5-turbo"+++ @pytest.mark.asyncio+ async def test_async_function_with_fallbacks_skips_stamp_on_genuine_reentrant_hop():+ """A re-entrant hop carrying the router's own AttemptedFallbackTargets instance keeps+ the per-hop metadata that run_async_fallback wrote instead of resetting it to zero."""+ from litellm.router_utils.fallback_event_handlers import AttemptedFallbackTargets++ router = litellm.Router(+ model_list=[+ {+ "model_name": "gpt-3.5-turbo",+ "litellm_params": {"model": "gpt-3.5-turbo", "mock_response": "hi"},+ }+ ]+ )+ metadata = {"attempted_fallbacks": 1, "original_model_group": "prod-chat"}++ await router.acompletion(+ model="gpt-3.5-turbo",+ messages=[{"role": "user", "content": "hey"}],+ metadata=metadata,+ attempted_targets=AttemptedFallbackTargets(keys=frozenset(("prod-chat",))),+ )++ assert metadata["attempted_fallbacks"] == 1+ assert metadata["original_model_group"] == "prod-chat"+++ def _record_router_acompletion_kwargs(router: litellm.Router) -> list:+ """Spy on router._acompletion, recording each call's kwargs while delegating through."""+ records = []+ original_acompletion = router._acompletion++ @functools.wraps(original_acompletion)+ async def _spy(*args, **spy_kwargs):+ records.append(spy_kwargs)+ return await original_acompletion(*args, **spy_kwargs)++ router._acompletion = _spy+ return records+++ @pytest.mark.asyncio+ async def test_async_function_with_fallbacks_scrubs_spoofed_values_from_sibling_bucket():+ """Spend logs read a truthy litellm_metadata dict in preference to metadata, so spoofed+ stamp keys planted in the bucket the route does not own are removed on entry, in place,+ before they can flow into the spend log row."""+ router = litellm.Router(+ model_list=[+ {+ "model_name": "gpt-3.5-turbo",+ "litellm_params": {"model": "gpt-3.5-turbo", "mock_response": "hi"},+ }+ ]+ )+ metadata = {}+ litellm_metadata = {+ "attempted_fallbacks": 99,+ "original_model_group": "spoofed-group",+ "client_key": "client_value",+ }+ downstream_calls = _record_router_acompletion_kwargs(router)++ await router.acompletion(+ model="gpt-3.5-turbo",+ messages=[{"role": "user", "content": "hey"}],+ metadata=metadata,+ litellm_metadata=litellm_metadata,+ )++ assert len(downstream_calls) == 1+ downstream_sibling = downstream_calls[0]["litellm_metadata"]+ assert "attempted_fallbacks" not in downstream_sibling+ assert "original_model_group" not in downstream_sibling+ assert downstream_sibling["client_key"] == "client_value"+ assert "attempted_fallbacks" not in litellm_metadata+ assert "original_model_group" not in litellm_metadata+ assert litellm_metadata["client_key"] == "client_value"+ assert metadata["attempted_fallbacks"] == 0+ assert metadata["original_model_group"] == "gpt-3.5-turbo"+++ @pytest.mark.asyncio+ async def test_async_function_with_fallbacks_scrubs_sibling_bucket_in_place():+ """Everything below the router resolves the bucket by key presence, so the scrub edits+ the caller's dict object like every other router bucket write. Rebinding kwargs to a+ scrubbed copy detaches the proxy's request_data write-backs (guardrail telemetry, retry+ accounting) from the object the spend row is built from."""+ router = litellm.Router(+ model_list=[+ {+ "model_name": "gpt-3.5-turbo",+ "litellm_params": {"model": "gpt-3.5-turbo", "mock_response": "hi"},+ }+ ]+ )+ litellm_metadata = {+ "attempted_fallbacks": 7,+ "original_model_group": "planted-group",+ "client_key": "client_value",+ }+ caller_snapshot = copy.deepcopy(litellm_metadata)+ downstream_calls = _record_router_acompletion_kwargs(router)++ await router.acompletion(+ model="gpt-3.5-turbo",+ messages=[{"role": "user", "content": "hey"}],+ metadata={},+ litellm_metadata=litellm_metadata,+ )++ assert len(downstream_calls) == 1+ assert downstream_calls[0]["litellm_metadata"] is litellm_metadata+ assert "attempted_fallbacks" not in litellm_metadata+ assert "original_model_group" not in litellm_metadata+ assert litellm_metadata["client_key"] == caller_snapshot["client_key"]+++ @pytest.mark.asyncio+ async def test_async_function_with_fallbacks_stamps_aliased_buckets_on_every_call():+ """One dict object passed as both metadata and litellm_metadata: the first call's own+ stamp puts the reserved keys into the shared object, so the second call enters the+ scrub with them present. Scrubbing in place keeps the stamp and the bucket on the same+ object; a scrubbed copy would leave the spend reader's preferred bucket unstamped."""+ router = litellm.Router(+ model_list=[+ {+ "model_name": "chat-group",+ "litellm_params": {"model": "gpt-3.5-turbo", "mock_response": "hi"},+ }+ ]+ )+ shared_metadata = {"team": "alpha"}+ downstream_calls = _record_router_acompletion_kwargs(router)++ for _ in range(3):+ await router.acompletion(+ model="chat-group",+ messages=[{"role": "user", "content": "hey"}],+ metadata=shared_metadata,+ litellm_metadata=shared_metadata,+ )++ assert len(downstream_calls) == 3+ for call_kwargs in downstream_calls:+ assert call_kwargs["litellm_metadata"] is shared_metadata+ assert call_kwargs["metadata"] is shared_metadata+ assert call_kwargs["litellm_metadata"]["attempted_fallbacks"] == 0+ assert call_kwargs["litellm_metadata"]["original_model_group"] == "chat-group"+++ @pytest.mark.asyncio+ async def test_async_function_with_fallbacks_passes_clean_sibling_bucket_through_unchanged():+ """A sibling bucket carrying no reserved stamp keys is forwarded downstream as the+ caller's own object with no copy made, matching pre-scrub behavior. Retry accounting+ stamped into that bucket downstream predates the scrub and is out of its scope."""+ router = litellm.Router(+ model_list=[+ {+ "model_name": "gpt-3.5-turbo",+ "litellm_params": {"model": "gpt-3.5-turbo", "mock_response": "hi"},+ }+ ]+ )+ litellm_metadata = {"client_key": "client_value"}+ downstream_calls = _record_router_acompletion_kwargs(router)++ await router.acompletion(+ model="gpt-3.5-turbo",+ messages=[{"role": "user", "content": "hey"}],+ metadata={},+ litellm_metadata=litellm_metadata,+ )++ assert len(downstream_calls) == 1+ assert downstream_calls[0]["litellm_metadata"] is litellm_metadata+ assert litellm_metadata["client_key"] == "client_value"+ assert "attempted_fallbacks" not in litellm_metadata+ assert "original_model_group" not in litellm_metadata+++ @pytest.mark.asyncio+ async def test_run_async_fallback_keeps_caller_metadata_keys_on_the_wire(monkeypatch):+ """Under enable_preview_features, add_openai_metadata forwards only the first 16+ string pairs of request metadata to the provider body, so the fallback hop must+ spread caller keys before the router's own stamps: a stamp inserted first evicts+ the caller's 16th key from the wire while the internal stamp rides in its place."""+ monkeypatch.setattr(litellm, "enable_preview_features", True)+ caller_metadata = {f"user_key_{i}": f"value_{i}" for i in range(16)}+ router = litellm.Router(+ model_list=[+ {+ "model_name": "primary-group",+ "litellm_params": {"model": "gpt-3.5-turbo", "api_key": "sk-test"},+ },+ {+ "model_name": "fallback-group",+ "litellm_params": {"model": "gpt-3.5-turbo", "api_key": "sk-test"},+ },+ ],+ fallbacks=[{"primary-group": ["fallback-group"]}],+ num_retries=0,+ )++ wire_bodies = []++ def _respond(request: httpx.Request) -> httpx.Response:+ wire_bodies.append(json.loads(request.content))+ return httpx.Response(+ 200,+ json={+ "id": "chatcmpl-wire",+ "object": "chat.completion",+ "created": 1,+ "model": "gpt-3.5-turbo",+ "choices": [{"index": 0, "message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}],+ "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},+ },+ )++ client = openai.AsyncOpenAI(+ api_key="sk-test",+ http_client=httpx.AsyncClient(transport=httpx.MockTransport(_respond)),+ )++ await router.acompletion(+ model="primary-group",+ messages=[{"role": "user", "content": "hey"}],+ metadata=dict(caller_metadata),+ mock_testing_fallbacks=True,+ client=client,+ )++ assert len(wire_bodies) == 1+ assert wire_bodies[0]["metadata"] == caller_metadata++ wire_bodies.clear()+ small_metadata = {"team": "alpha", "env": "prod"}+ await router.acompletion(+ model="primary-group",+ messages=[{"role": "user", "content": "hey again"}],+ metadata=dict(small_metadata),+ mock_testing_fallbacks=True,+ client=client,+ )++ assert len(wire_bodies) == 1+ small_wire = wire_bodies[0]["metadata"]+ assert {k: small_wire[k] for k in small_metadata} == small_metadata+ assert small_wire["original_model_group"] == "primary-group"+ assert small_wire["model_group"] == "fallback-group"+++ @pytest.mark.asyncio+ async def test_run_async_fallback_two_hop_chain_reports_entry_group_and_hop_count():+ """A two-hop fallback chain stamps attempted_fallbacks=2 on the final leg and keeps+ original_model_group at the group requested on entry: a later hop's stamp appends+ after caller keys without overriding the value stamped by an earlier hop."""+ router = litellm.Router(+ model_list=[+ {+ "model_name": "group-a",+ "litellm_params": {"model": "gpt-3.5-turbo", "mock_response": "litellm.InternalServerError"},+ },+ {+ "model_name": "group-b",+ "litellm_params": {"model": "gpt-3.5-turbo", "mock_response": "litellm.InternalServerError"},+ },+ {+ "model_name": "group-c",+ "litellm_params": {"model": "gpt-3.5-turbo", "mock_response": "ok"},+ },+ ],+ fallbacks=[{"group-a": ["group-b"]}, {"group-b": ["group-c"]}],+ num_retries=0,+ )+ metadata = {}+ leg_records = []+ original_acompletion = router._acompletion++ @functools.wraps(original_acompletion)+ async def _spy(*args, **spy_kwargs):+ leg_records.append((spy_kwargs.get("model"), copy.deepcopy(spy_kwargs.get("metadata"))))+ return await original_acompletion(*args, **spy_kwargs)++ router._acompletion = _spy++ await router.acompletion(+ model="group-a",+ messages=[{"role": "user", "content": "hey"}],+ metadata=metadata,+ )++ assert [model for model, _ in leg_records] == ["group-a", "group-b", "group-c"]+ hop_one_metadata = leg_records[1][1]+ assert hop_one_metadata["attempted_fallbacks"] == 1+ assert hop_one_metadata["original_model_group"] == "group-a"+ assert hop_one_metadata["model_group"] == "group-b"+ hop_two_metadata = leg_records[2][1]+ assert hop_two_metadata["attempted_fallbacks"] == 2+ assert hop_two_metadata["original_model_group"] == "group-a"+ assert hop_two_metadata["model_group"] == "group-c"+ assert metadata["attempted_fallbacks"] == 0+ assert metadata["original_model_group"] == "group-a"+++ def _permission_denied_error() -> litellm.PermissionDeniedError:+ return litellm.PermissionDeniedError(+ message="OpenrouterException - this key has no access to the model",+ llm_provider="openrouter",+ model="openrouter/openai/gpt-4o",+ response=httpx.Response(status_code=403, request=httpx.Request(method="POST", url="https://openrouter.ai")),+ )+++ def test_permission_denied_error_is_not_retried_against_a_single_deployment():+ router = litellm.Router(+ model_list=[+ {"model_name": "gpt-4o", "litellm_params": {"model": "openrouter/openai/gpt-4o", "api_key": "sk-test"}},+ ]+ )++ with pytest.raises(litellm.PermissionDeniedError):+ router.should_retry_this_error(+ error=_permission_denied_error(),+ healthy_deployments=router.model_list,+ all_deployments=router.model_list,+ )+++ def test_permission_denied_error_is_retried_when_other_deployments_exist():+ router = litellm.Router(+ model_list=[+ {"model_name": "gpt-4o", "litellm_params": {"model": "openrouter/openai/gpt-4o", "api_key": "sk-test"}},+ {"model_name": "gpt-4o", "litellm_params": {"model": "openai/gpt-4o", "api_key": "sk-test"}},+ ]+ )++ assert (+ router.should_retry_this_error(+ error=_permission_denied_error(),+ healthy_deployments=router.model_list,+ all_deployments=router.model_list,+ )+ is True+ )+++ class _AllowlistFallbackAccessCheck:+ def __init__(self, allowed_models: frozenset[str]):+ self.allowed_models = allowed_models+ self.checked_models = []++ async def __call__(self, *, model, request_kwargs, llm_router):+ self.checked_models.append(model)+ return model in self.allowed_models+++ def _router_with_failing_primary(fallback_access_check) -> Router:+ return Router(+ model_list=[+ {+ "model_name": "primary",+ "litellm_params": {+ "model": "openai/primary",+ "api_key": "k",+ "mock_response": Exception("primary is down"),+ },+ },+ {+ "model_name": "secret-fallback",+ "litellm_params": {+ "model": "openai/secret",+ "api_key": "k",+ "mock_response": "served by secret-fallback",+ },+ },+ ],+ fallbacks=[{"primary": ["secret-fallback"]}],+ num_retries=0,+ fallback_access_check=fallback_access_check,+ )+++ @pytest.mark.asyncio+ async def test_fallback_access_check_blocks_config_fallback_the_caller_cannot_use():+ access_check = _AllowlistFallbackAccessCheck(allowed_models=frozenset())+ router = _router_with_failing_primary(access_check)++ with pytest.raises(Exception, match="primary is down"):+ await router.acompletion(model="primary", messages=[{"role": "user", "content": "hi"}])++ assert access_check.checked_models == ["secret-fallback"]+++ @pytest.mark.asyncio+ async def test_fallback_access_check_lets_an_authorized_config_fallback_through():+ router = _router_with_failing_primary(_AllowlistFallbackAccessCheck(allowed_models=frozenset({"secret-fallback"})))++ response = await router.acompletion(model="primary", messages=[{"role": "user", "content": "hi"}])++ assert response.choices[0].message.content == "served by secret-fallback"+++ @pytest.mark.asyncio+ async def test_router_without_fallback_access_check_attempts_every_config_fallback():+ router = _router_with_failing_primary(None)++ response = await router.acompletion(model="primary", messages=[{"role": "user", "content": "hi"}])++ assert response.choices[0].message.content == "served by secret-fallback"+++ def _resolution_router() -> Router:+ return Router(+ model_list=[+ {"model_name": "pinned", "litellm_params": {"model": "openai/gpt-4o", "api_key": "sk-test"}},+ {"model_name": "pooled", "litellm_params": {"model": "openai/gpt-4o-mini", "api_key": "sk-test"}},+ {"model_name": "pooled", "litellm_params": {"model": "anthropic/claude-haiku-4-5", "api_key": "sk-test"}},+ {"model_name": "bedrock/*", "litellm_params": {"model": "bedrock/*", "api_key": "sk-test"}},+ ],+ model_group_alias={"nickname": "pinned"},+ )+++ @pytest.mark.parametrize(+ "model_name,expected",+ [+ ("pinned", ("openai/gpt-4o",)),+ ("nickname", ("openai/gpt-4o",)),+ ("pooled", ("openai/gpt-4o-mini", "anthropic/claude-haiku-4-5")),+ ("bedrock/anthropic.claude-3-5-sonnet", ("bedrock/anthropic.claude-3-5-sonnet",)),+ ("never-configured", ()),+ ],+ ids=["exact-name", "model-group-alias", "every-member-of-a-pool", "wildcard-expands", "resolves-to-nothing"],+ )+ def test_resolved_litellm_models_answers_through_every_channel_a_request_uses(+ model_name: str, expected: tuple[str, ...]+ ) -> None:+ """A caller comparing two names by what serves them needs each channel the request path+ composes, since the deployment name an admin picked carries no information on its own.++ `resolves-to-nothing` is the contract that keeps the fallback out of here: an empty+ result is not "the call fails", so what to do about it stays each caller's policy.+ """+ assert set(_resolution_router().resolved_litellm_models(model_name)) == set(expected)+++ class TestTierParamsTheTargetAccepts:+ """A tier's litellm_params are applied to every request that tier routes, so one the target+ cannot take raised UnsupportedParamsError before the request left the proxy, turning the whole+ tier into a 400."""++ @pytest.fixture(autouse=True)+ def force_local_model_cost(self, monkeypatch):+ from litellm.litellm_core_utils.get_model_cost_map import GetModelCostMap++ monkeypatch.setattr(litellm, "model_cost", GetModelCostMap.load_local_model_cost_map())++ @staticmethod+ def _router(model: str) -> litellm.Router:+ return litellm.Router(+ model_list=[{"model_name": "tiered", "litellm_params": {"model": model, "api_key": "sk-x"}}]+ )++ def test_drops_a_param_no_deployment_declares(self):+ router = self._router("novita/moonshotai/kimi-k3")++ accepted = router._tier_params_the_target_accepts("tiered", {"reasoning_effort": "max"}, {})++ assert accepted == {}++ def test_keeps_a_param_the_deployment_declares(self):+ router = self._router("fireworks_ai/kimi-k3")++ accepted = router._tier_params_the_target_accepts("tiered", {"reasoning_effort": "max"}, {})++ assert accepted == {"reasoning_effort": "max"}++ @pytest.mark.parametrize(+ "control, value",+ [+ ("api_base", "https://example.invalid"),+ ("api_key", "sk-tier"),+ ("base_url", "https://example.invalid"),+ ("timeout", 30),+ ("default_headers", {"x-tier": "1"}),+ ("organization", "org-tier"),+ ("deployment_id", "dep-tier"),+ ],+ )+ def test_keeps_credentials_and_transport_controls(self, control, value):+ """These are not chat completion params, so get_optional_params never compares them against+ a provider's supported list. Filtering on "is this an OpenAI param" would discard the+ configuration the request needs while never touching what the provider would reject."""+ router = self._router("novita/moonshotai/kimi-k3")++ accepted = router._tier_params_the_target_accepts("tiered", {control: value, "reasoning_effort": "max"}, {})++ assert accepted == {control: value}++ @pytest.mark.parametrize(+ "control, value",+ [+ ("additional_drop_params", ["seed"]),+ ("drop_params", True),+ ("allowed_openai_params", ["seed"]),+ ("api_version", "2024-02-01"),+ ("metadata", {"tier": "complex"}),+ ],+ )+ def test_keeps_litellm_controls_the_provider_never_lists(self, control, value):+ """No provider lists a litellm control among its supported params, so "no deployment+ declares it" means litellm consumes it, not that the target refuses it. Dropping+ drop_params or additional_drop_params would silently disable the operator's sanitization."""+ router = self._router("novita/moonshotai/kimi-k3")++ accepted = router._tier_params_the_target_accepts("tiered", {control: value, "reasoning_effort": "max"}, {})++ assert accepted == {control: value}++ def test_tier_allowlist_protects_the_param_it_names(self):+ """allowed_openai_params is the documented escape hatch for an incomplete supported-params+ list, and request-time validation extends the supported list with it, so a param the tier+ both sets and allowlists would never 400 and must not be dropped."""+ router = self._router("novita/moonshotai/kimi-k3")++ accepted = router._tier_params_the_target_accepts(+ "tiered", {"reasoning_effort": "max", "allowed_openai_params": ["reasoning_effort"]}, {}+ )++ assert accepted == {"reasoning_effort": "max", "allowed_openai_params": ["reasoning_effort"]}++ def test_request_allowlist_protects_the_param_it_names(self):+ router = self._router("novita/moonshotai/kimi-k3")++ accepted = router._tier_params_the_target_accepts(+ "tiered", {"reasoning_effort": "max"}, {"allowed_openai_params": ["reasoning_effort"]}+ )++ assert accepted == {"reasoning_effort": "max"}++ def test_allowlist_protects_only_the_params_it_names(self):+ router = self._router("novita/moonshotai/kimi-k3")++ accepted = router._tier_params_the_target_accepts(+ "tiered", {"reasoning_effort": "max", "allowed_openai_params": ["seed"]}, {}+ )++ assert accepted == {"allowed_openai_params": ["seed"]}++ def test_declared_param_allowlist_ignores_malformed_declarations(self):+ """A str is iterable, so without the type guard a YAML scalar mistake like+ allowed_openai_params: reasoning_effort would allowlist single characters."""+ assert litellm.Router._declared_param_allowlist({"allowed_openai_params": ["reasoning_effort", 3]}) == frozenset(+ {"reasoning_effort"}+ )+ assert litellm.Router._declared_param_allowlist({"allowed_openai_params": "reasoning_effort"}) == frozenset()+ assert litellm.Router._declared_param_allowlist({}) == frozenset()++ def test_deployment_accepts_param_honors_deployment_allowlist(self):+ deployment = {+ "model_name": "x",+ "litellm_params": {"model": "novita/moonshotai/kimi-k3", "allowed_openai_params": ["reasoning_effort"]},+ }++ assert litellm.Router._deployment_accepts_param(deployment, "x", "reasoning_effort") is True++ def test_keeps_a_token_ceiling_the_provider_spells_differently(self):+ """petals lists max_tokens but not max_completion_tokens. A tier ceiling in the unsupported+ spelling is a cost bound: dropping it would let a caller's larger max_tokens through where+ today the mismatch fails loudly."""+ router = self._router("petals/petals-team/StableBeluga2")++ accepted = router._tier_params_the_target_accepts(+ "tiered", {"max_completion_tokens": 100, "reasoning_effort": "max"}, {}+ )++ assert accepted == {"max_completion_tokens": 100}++ def test_keeps_extra_headers_even_when_the_provider_omits_it(self):+ """Several providers leave extra_headers out of their supported params, so the filter would+ drop it. Headers carry auth and tenancy, so sending fewer than the operator configured is+ worse than the error they already get."""+ router = self._router("ai21/jamba-1.5-mini")++ accepted = router._tier_params_the_target_accepts(+ "tiered", {"extra_headers": {"x-tenant": "acme"}, "reasoning_effort": "max"}, {}+ )++ assert accepted == {"extra_headers": {"x-tenant": "acme"}}++ def test_keeps_a_param_any_deployment_in_the_group_declares(self):+ """Routing has not picked a deployment yet, so one capable member keeps the param alive."""+ router = litellm.Router(+ model_list=[+ {"model_name": "tiered", "litellm_params": {"model": "novita/moonshotai/kimi-k3", "api_key": "k"}},+ {"model_name": "tiered", "litellm_params": {"model": "fireworks_ai/kimi-k3", "api_key": "k"}},+ ]+ )++ accepted = router._tier_params_the_target_accepts("tiered", {"reasoning_effort": "max"}, {})++ assert accepted == {"reasoning_effort": "max"}++ def test_deployment_accepts_param_honors_base_model(self):+ """An azure deployment named after the deployment rather than the model carries the real+ model in base_model, and request-time mapping resolves capability through it, so the filter+ has to ask the same question or it drops a param the deployment accepts."""+ by_model_info = {+ "model_name": "x",+ "litellm_params": {"model": "azure/my-gpt5-deploy"},+ "model_info": {"base_model": "azure/gpt-5"},+ }+ by_litellm_params = {+ "model_name": "x",+ "litellm_params": {"model": "azure/my-gpt5-deploy", "base_model": "azure/gpt-5"},+ }+ without_hint = {"model_name": "x", "litellm_params": {"model": "azure/my-gpt5-deploy"}}++ assert litellm.Router._deployment_accepts_param(by_model_info, "x", "reasoning_effort") is True+ assert litellm.Router._deployment_accepts_param(by_litellm_params, "x", "reasoning_effort") is True+ assert litellm.Router._deployment_accepts_param(without_hint, "x", "reasoning_effort") is False++ def test_deployment_accepts_param_reads_the_provider(self):+ deployment = {"model_name": "x", "litellm_params": {"model": "fireworks_ai/kimi-k3"}}++ assert litellm.Router._deployment_accepts_param(deployment, "x", "reasoning_effort") is True++ def test_deployment_accepts_param_is_false_when_the_provider_omits_it(self):+ deployment = {"model_name": "x", "litellm_params": {"model": "novita/moonshotai/kimi-k3"}}++ assert litellm.Router._deployment_accepts_param(deployment, "x", "reasoning_effort") is False++ @pytest.mark.parametrize(+ "deployment",+ [{"model_name": "x"}, {"model_name": "x", "litellm_params": {}}, {"model_name": "x", "litellm_params": {"model": "not-a-real-provider/nope"}}],+ )+ def test_deployment_accepts_param_fails_open(self, deployment):+ """An unresolvable deployment must not be the reason a param is dropped."""+ assert litellm.Router._deployment_accepts_param(deployment, "x", "reasoning_effort") is True++ @pytest.mark.parametrize(+ "litellm_params",+ [+ {"model": "github_copilot/gpt-4o"},+ {"model": "chatgpt/gpt-5"},+ {"model": "gpt-4o", "custom_llm_provider": "github_copilot"},+ ],+ )+ def test_deployment_accepts_param_never_asks_a_provider_whose_lookup_authenticates(+ self, litellm_params, monkeypatch+ ):+ """Resolving github_copilot or chatgpt runs their OAuth device flow, so a capability+ question asked from the routing path can freeze the event loop for minutes waiting on a+ human. The deployment counts as accepting everything, and the lookup is never made: an+ exception-based sentinel cannot prove that, because the filter swallows exceptions into+ the same keep answer."""+ lookups: list = []++ def _record(*args, **kwargs):+ lookups.append((args, kwargs))+ raise RuntimeError("provider resolution must not run for an authenticating provider")++ monkeypatch.setattr(litellm, "get_llm_provider", _record)+ deployment = {"model_name": "x", "litellm_params": litellm_params}++ assert litellm.Router._deployment_accepts_param(deployment, "x", "reasoning_effort") is True+ assert lookups == []++ def test_keeps_everything_for_an_unknown_group(self):+ """An unresolvable target must never narrow what the request already did."""+ router = self._router("fireworks_ai/kimi-k3")++ accepted = router._tier_params_the_target_accepts("no-such-group", {"reasoning_effort": "max"}, {})++ assert accepted == {"reasoning_effort": "max"}+++ class TestRequestReasoningEffortOverride:+ def test_drop_effort_from_nested_carrier_preserves_other_nested_values(self):+ params: dict[str, object] = {"output_config": {"effort": "high", "format": "json"}}++ litellm.Router._pop_effort_from_nested_carrier(params, "output_config")++ assert params == {"output_config": {"format": "json"}}++ @pytest.mark.parametrize("metadata_key", ["metadata", "litellm_metadata"])+ def test_is_classifier_internal_call_recognizes_both_metadata_carriers(self, metadata_key):+ kwargs = {metadata_key: {"internal_call_origin": "autorouter_classifier"}}++ assert litellm.Router._is_classifier_internal_call(kwargs) is True+ assert litellm.Router._is_classifier_internal_call({metadata_key: {}}) is False++ def test_removes_every_deployment_native_effort_carrier_without_mutating_shared_config(self):+ extra_body: dict[str, object] = {+ "reasoning_effort": "high",+ "thinking": {"type": "enabled"},+ "output_config": {"effort": "high", "format": "json"},+ "reasoning": {"effort": "high", "summary": "detailed"},+ "provider_option": True,+ }+ deployment_params: dict[str, object] = {+ "model": "bedrock/converse/anthropic.claude-3-7-sonnet",+ "thinking": {"type": "enabled", "budget_tokens": 2048},+ "output_config": {"effort": "high", "format": {"type": "json_schema"}},+ "reasoning": {"effort": "high", "summary": "auto"},+ "extra_body": extra_body,+ }++ sanitized = litellm.Router._deployment_params_with_request_reasoning_override(+ deployment_params, {"reasoning_effort": "low"}+ )++ assert sanitized == {+ "model": "bedrock/converse/anthropic.claude-3-7-sonnet",+ "output_config": {"format": {"type": "json_schema"}},+ "reasoning": {"summary": "auto"},+ "extra_body": {+ "output_config": {"format": "json"},+ "reasoning": {"summary": "detailed"},+ "provider_option": True,+ },+ }+ assert deployment_params["thinking"] == {"type": "enabled", "budget_tokens": 2048}+ assert deployment_params["output_config"] == {"effort": "high", "format": {"type": "json_schema"}}+ assert extra_body["reasoning_effort"] == "high"++ @pytest.mark.parametrize("request_kwargs", [{}, {"reasoning_effort": None}])+ def test_omitted_override_preserves_deployment_defaults(self, request_kwargs):+ deployment_params = {+ "model": "deepseek/deepseek-reasoner",+ "thinking": {"type": "enabled"},+ "output_config": {"effort": "high"},+ }++ assert (+ litellm.Router._deployment_params_with_request_reasoning_override(deployment_params, request_kwargs)+ == deployment_params+ )++ @pytest.mark.asyncio+ async def test_280_concurrent_overrides_never_mutate_or_leak_through_shared_deployment_params(self):+ deployment_params = {+ "model": "fireworks_ai/accounts/fireworks/models/kimi-k2-thinking",+ "thinking": {"type": "enabled"},+ "output_config": {"effort": "high", "format": "json"},+ "extra_body": {"reasoning_effort": "high", "tenant": "shared"},+ }+ efforts = ("none", "minimal", "low", "medium", "high", "xhigh", "max")++ results = await asyncio.gather(+ *(+ asyncio.to_thread(+ litellm.Router._deployment_params_with_request_reasoning_override,+ deployment_params,+ {"reasoning_effort": efforts[index % len(efforts)]},+ )+ for index in range(280)+ )+ )++ assert all("thinking" not in result for result in results)+ assert all(result["output_config"] == {"format": "json"} for result in results)+ assert all(result["extra_body"] == {"tenant": "shared"} for result in results)+ assert deployment_params["thinking"] == {"type": "enabled"}+ assert deployment_params["output_config"] == {"effort": "high", "format": "json"}+ assert deployment_params["extra_body"] == {"reasoning_effort": "high", "tenant": "shared"}++ @pytest.mark.parametrize(+ ("metadata", "should_drop"),+ [({"internal_call_origin": "autorouter_classifier"}, True), ({}, False)],+ ids=["classifier", "ordinary-request"],+ )+ def test_only_classifier_calls_drop_effort_for_an_unsupported_fallback(self, metadata, should_drop):+ router = litellm.Router(model_list=[])+ body: dict[str, object] = {"model": "classifier", "reasoning_effort": "low"}+ kwargs: dict[str, object] = {+ "reasoning_effort": "low",+ "metadata": metadata,+ "proxy_server_request": {"body": body},+ }+ deployment: DeploymentTypedDict = {+ "model_name": "fallback",+ "litellm_params": {"model": "openai/gpt-4o-mini"},+ }++ router._drop_unsupported_classifier_reasoning_effort(deployment, "fallback", kwargs)++ assert ("reasoning_effort" not in kwargs) is should_drop+ assert ("reasoning_effort" not in body) is should_drop+++ class TestPreRoutingTierDrivesFallbacks:+ """#38832: a complexity/auto router picks a tier behind the router name, but fallback+ lookup stayed on the router name, so the tier's configured chain never ran and a+ provider failure on the tier's first hop was returned to the client."""++ class _TierRouter(litellm.Router):+ async def async_pre_routing_hook(+ self, model, request_kwargs, messages=None, input=None, specific_deployment=False+ ):+ from litellm.types.router import PreRoutingHookResponse++ if model == "smart-router":+ return PreRoutingHookResponse(model="tier1", messages=messages)+ return None++ @classmethod+ def _router(cls, fallbacks) -> "litellm.Router":+ return cls._TierRouter(+ model_list=[+ {+ "model_name": "smart-router",+ "litellm_params": {"model": "openai/gpt-4o-mini", "api_key": "sk-x"},+ },+ {+ "model_name": "tier1",+ "litellm_params": {+ "model": "openai/gpt-4o-mini",+ "api_key": "sk-x",+ "mock_response": "litellm.RateLimitError",+ },+ },+ {+ "model_name": "backup-a",+ "litellm_params": {+ "model": "openai/gpt-4o-mini",+ "api_key": "sk-x",+ "mock_response": "from backup-a",+ },+ },+ {+ "model_name": "backup-b",+ "litellm_params": {+ "model": "openai/gpt-4o-mini",+ "api_key": "sk-x",+ "mock_response": "from backup-b",+ },+ },+ {+ "model_name": "failing-backup",+ "litellm_params": {+ "model": "openai/gpt-4o-mini",+ "api_key": "sk-x",+ "mock_response": "litellm.RateLimitError",+ },+ },+ {+ "model_name": "plain",+ "litellm_params": {+ "model": "openai/gpt-4o-mini",+ "api_key": "sk-x",+ "mock_response": "litellm.RateLimitError",+ },+ },+ ],+ fallbacks=fallbacks,+ num_retries=0,+ )++ @pytest.mark.asyncio+ async def test_the_selected_tier_fallback_chain_runs(self):+ router = self._router([{"tier1": ["backup-a"]}])++ response = await router.acompletion(+ model="smart-router", messages=[{"role": "user", "content": "hi"}]+ )++ assert response.choices[0].message.content == "from backup-a"++ @pytest.mark.asyncio+ async def test_a_chain_keyed_on_the_router_name_is_not_used(self):+ """The router name has no chain of its own, so nothing should rescue this call."""+ router = self._router([{"tier2": ["backup-a"]}])++ with pytest.raises(litellm.RateLimitError):+ await router.acompletion(model="smart-router", messages=[{"role": "user", "content": "hi"}])++ @pytest.mark.asyncio+ async def test_a_chain_keyed_on_the_router_name_rescues_when_no_tier_chain_exists(self):+ """The documented contract: configs keyed on the requested name keep working behind auto-routers."""+ router = self._router([{"smart-router": ["backup-a"]}])++ response = await router.acompletion(model="smart-router", messages=[{"role": "user", "content": "hi"}])++ assert response.choices[0].message.content == "from backup-a"++ @pytest.mark.asyncio+ async def test_the_tier_chain_wins_over_the_router_name_chain(self):+ router = self._router([{"tier1": ["backup-a"]}, {"smart-router": ["backup-b"]}])++ response = await router.acompletion(model="smart-router", messages=[{"role": "user", "content": "hi"}])++ assert response.choices[0].message.content == "from backup-a"++ @pytest.mark.asyncio+ async def test_a_request_without_a_pre_routing_hook_still_uses_its_own_group(self):+ router = self._router([{"tier1": ["backup-a"]}])++ response = await router.acompletion(+ model="tier1", messages=[{"role": "user", "content": "hi"}]+ )++ assert response.choices[0].message.content == "from backup-a"++ @pytest.mark.asyncio+ async def test_a_caller_cannot_pick_the_chain_by_sending_the_selection(self):+ """The metadata bucket carries caller-supplied keys, so only the hook may set the tier."""+ router = self._router([{"tier1": ["backup-a"]}])++ with pytest.raises(litellm.RateLimitError):+ await router.acompletion(+ model="plain",+ messages=[{"role": "user", "content": "hi"}],+ metadata={"pre_routing_selected_model": "tier1"},+ )++ @pytest.mark.asyncio+ async def test_each_fallback_hop_resolves_its_own_chain(self):+ """The second hop must key off the group it is running, not the tier that failed."""+ router = self._router([{"tier1": ["failing-backup"]}, {"failing-backup": ["backup-b"]}])++ response = await router.acompletion(model="smart-router", messages=[{"role": "user", "content": "hi"}])++ assert response.choices[0].message.content == "from backup-b"+++ @pytest.mark.asyncio+ async def test_prompt_management_factory_marks_injection_for_every_deployment(monkeypatch):+ """The factory stamps a provisional deployment's model_info into kwargs before the+ prompt pass runs, then routes on the returned model, so any deployment can end up+ billed. An injection recorded there must carry the every-deployment sentinel, never+ the provisional deployment's id, or a differently-billed deployment loses the credit."""+ import time++ from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLogging++ router = litellm.Router(+ model_list=[+ {+ "model_name": "cached-claude",+ "litellm_params": {+ "model": "anthropic_cache_control_hook/claude-sonnet-5",+ "prompt_id": "cache-points",+ },+ "model_info": {"id": "provisional-dep"},+ }+ ]+ )+ captured: dict = {}++ async def _capture_acompletion(**kwargs):+ captured.update(kwargs)+ return litellm.ModelResponse()++ monkeypatch.setattr(litellm, "acompletion", _capture_acompletion)+ logging_obj = LiteLLMLogging(+ model="cached-claude",+ messages=[{"role": "user", "content": "hi"}],+ stream=False,+ call_type="acompletion",+ start_time=time.time(),+ litellm_call_id="lit-6445",+ function_id="f",+ )+ await router.acompletion(+ model="cached-claude",+ messages=[+ {"role": "system", "content": "a static system prompt"},+ {"role": "user", "content": "hi"},+ ],+ cache_control_injection_points=[{"location": "message", "role": "system"}],+ litellm_logging_obj=logging_obj,+ )+ bucket = captured.get("litellm_metadata") or captured["metadata"]+ assert captured["model_info"]["id"] == "provisional-dep"+ assert bucket["litellm_gateway_injected_cache"] == ""++++[email protected]("policy_retries,expected_calls", [(0, 1), (1, 2)])+async def test_router_retry_policy_service_unavailable_retries(policy_retries, expected_calls):+ from litellm.types.router import RetryPolicy++ router = litellm.Router(+ model_list=[+ {+ "model_name": "gpt-5.6",+ "litellm_params": {"model": "openai/gpt-5.6", "api_key": "fake-key"},+ }+ ],+ retry_policy=RetryPolicy(ServiceUnavailableErrorRetries=policy_retries),+ disable_cooldowns=True,+ )++ error = litellm.ServiceUnavailableError(+ message="model is down",+ llm_provider="openai",+ model="gpt-5.6",+ )+ with patch.object(litellm, "acompletion", AsyncMock(side_effect=error)) as mock_acompletion:+ with pytest.raises(litellm.ServiceUnavailableError):+ await router.acompletion(+ model="gpt-5.6",+ messages=[{"role": "user", "content": "hi"}],+ )++ assert mock_acompletion.call_count == expected_callsdiff --cc ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/components/ModelRetrySettingsTab.tsxindex a9e0b8eb051,bfcedc2bbb0..9d6501c97ba--- a/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/components/ModelRetrySettingsTab.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/components/ModelRetrySettingsTab.tsx@@@ -30,9 -34,10 +34,11 @@@ const retryPolicyMap: Record<string, st"RateLimitError (429)": "RateLimitErrorRetries","ContentPolicyViolationError (400)": "ContentPolicyViolationErrorRetries","InternalServerError (500)": "InternalServerErrorRetries",+ "ServiceUnavailableError (503)": "ServiceUnavailableErrorRetries",};+ const isValidRetryCount = (value: number) => Number.isFinite(value) && Number.isInteger(value) && value >= 0;+const ModelRetrySettingsTab = ({selectedModelGroup,setSelectedModelGroup,