Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

Merge remote-tracking branch 'origin/litellm_internal_staging' into litellm_non_reasoning_tier

moe-berric7b80f19664e
diff --cc tests/test_litellm/router_strategy/test_complexity_router.py
index 2732694ab7e,565e77b0ae0..9f925499f1a
--- a/tests/test_litellm/router_strategy/test_complexity_router.py
+++ b/tests/test_litellm/router_strategy/test_complexity_router.py
@@@ -13197,180 -13286,377 +13287,555 @@@ class TestClassifierVision
ClassifierLLMConfig(model="clf", vision={"enabled": True, "max_images": 0})
+ class TestMaxTokensFromTierModel:
+ """The auto-router replaces the caller's output ceiling with the tier model's own, so one
+ client-side value no longer starves a bigger tier or gets rejected by a smaller one."""
+
+ COMPLEX_PROMPT: Final = (
+ "Design a distributed rate limiter with Redis, sharding and failover. Analyze the consistency "
+ "tradeoffs and implement the algorithm step by step with tests."
+ )
+ SMALL: Final = {
+ "model_name": "small",
+ "litellm_params": {"model": "anthropic/claude-haiku-4-5", "api_key": "k"},
+ "model_info": {"max_output_tokens": 8192},
+ }
+
+ @staticmethod
+ def _router(
+ tier_litellm_params: dict | None = None,
+ max_tokens_from_tier_model: bool | None = None,
+ simple_deployments: list[dict] | None = None,
+ extra_config: dict | None = None,
+ ) -> Router:
+ simple_tier: dict = {"model_name": "small"}
+ if tier_litellm_params:
+ simple_tier["litellm_params"] = tier_litellm_params
+ config: dict = {
+ "tiers": {"SIMPLE": simple_tier, "MEDIUM": "big", "COMPLEX": "big", "REASONING": "big"},
+ **(extra_config or {}),
+ }
+ if max_tokens_from_tier_model is not None:
+ config["max_tokens_from_tier_model"] = max_tokens_from_tier_model
+ return Router(
+ model_list=[
+ {
+ "model_name": "smart-router",
+ "litellm_params": {"model": "auto_router/complexity_router", "complexity_router_config": config},
+ },
+ *(simple_deployments or [TestMaxTokensFromTierModel.SMALL]),
+ {
+ "model_name": "big",
+ "litellm_params": {"model": "anthropic/claude-sonnet-5", "api_key": "k"},
+ "model_info": {"max_output_tokens": 64000},
+ },
+ ]
+ )
+
+ @staticmethod
+ async def _routed(router: Router, prompt: str = "hi", **request_kwargs) -> dict:
+ """Drive the real routing entry point and return the request kwargs it leaves behind."""
+ deployment = await router.async_get_available_deployment(
+ model="smart-router", request_kwargs=request_kwargs, messages=[{"role": "user", "content": prompt}]
+ )
+ return {"model": deployment["litellm_params"]["model"], **request_kwargs}
+
+ @staticmethod
+ async def _routed_responses(router: Router, prompt: str = "hi", **request_kwargs) -> dict:
+ """The Responses surface hands the router `input` both as the prompt argument and inside the
+ request kwargs, so the hook sees the same shape the real call carries."""
+ routed: dict = {"input": prompt, **request_kwargs}
+ deployment = await router.async_get_available_deployment(
+ model="smart-router", request_kwargs=routed, input=prompt
+ )
+ return {"model": deployment["litellm_params"]["model"], **routed}
+
+ @pytest.mark.asyncio
+ async def test_client_ceiling_is_replaced_by_the_routed_tier_models_ceiling(self):
+ router = self._router()
+
+ simple = await self._routed(router, max_tokens=8192)
+ complex_ = await self._routed(router, self.COMPLEX_PROMPT, max_tokens=8192)
+
+ assert (simple["model"], simple["max_tokens"]) == ("anthropic/claude-haiku-4-5", 8192)
+ assert (complex_["model"], complex_["max_tokens"]) == ("anthropic/claude-sonnet-5", 64000)
+ assert "max_output_tokens" not in complex_
+
+ @pytest.mark.asyncio
+ async def test_every_client_carrier_of_the_ceiling_is_replaced(self):
+ sent = await self._routed(self._router(), self.COMPLEX_PROMPT, max_completion_tokens=8192)
+
+ assert sent["max_tokens"] == 64000
+ assert "max_completion_tokens" not in sent
+
+ @pytest.mark.asyncio
+ async def test_responses_surface_gets_the_ceiling_under_its_own_name(self):
+ sent = await self._routed_responses(self._router(), self.COMPLEX_PROMPT, max_output_tokens=8192)
+
+ assert (sent["model"], sent["max_output_tokens"]) == ("anthropic/claude-sonnet-5", 64000)
+ assert "max_tokens" not in sent
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "tier_params, responses_call",
+ [
+ ({"max_tokens": 4321}, False),
+ ({"max_tokens": 4321}, True),
+ ({"max_completion_tokens": 4321}, False),
+ ({"max_completion_tokens": 4321}, True),
+ ({"max_output_tokens": 4321}, False),
+ ],
+ )
+ async def test_operators_own_tier_ceiling_wins_under_the_surface_name(self, tier_params, responses_call):
+ router = self._router(tier_litellm_params=tier_params)
+ if responses_call:
+ sent = await self._routed_responses(router, max_output_tokens=8192)
+ else:
+ sent = await self._routed(router, max_tokens=8192)
+
+ surface_key = "max_output_tokens" if responses_call else "max_tokens"
+ assert sent[surface_key] == 4321
+ assert not (OUTPUT_TOKEN_CEILING_PARAMS - {surface_key}) & sent.keys()
+
+ @pytest.mark.asyncio
+ async def test_opting_out_forwards_the_client_value_unchanged(self):
+ sent = await self._routed(self._router(max_tokens_from_tier_model=False), self.COMPLEX_PROMPT, max_tokens=8192)
+
+ assert sent["max_tokens"] == 8192
+
+ @pytest.mark.asyncio
+ async def test_a_tier_model_with_an_unknown_ceiling_keeps_the_client_value(self):
+ unmapped: dict = {"model_name": "small", "litellm_params": {"model": "openai/not-in-any-map", "api_key": "k"}}
+
+ sent = await self._routed(self._router(simple_deployments=[self.SMALL, unmapped]), max_tokens=4000)
+
+ assert sent["max_tokens"] == 4000
+
+ @pytest.mark.asyncio
+ async def test_a_multi_deployment_tier_model_uses_its_smallest_ceiling(self):
+ smaller: dict = {
+ **self.SMALL,
+ "litellm_params": {**self.SMALL["litellm_params"], "api_key": "k2"},
+ "model_info": {"max_output_tokens": 4096},
+ }
+
+ sent = await self._routed(self._router(simple_deployments=[self.SMALL, smaller]), max_tokens=100000)
+
+ assert sent["max_tokens"] == 4096
+
+ @pytest.mark.asyncio
+ async def test_ceiling_falls_back_to_the_cost_map(self, monkeypatch):
+ monkeypatch.setitem(
+ litellm.model_cost,
+ "auto-cap-probe-model",
+ {"litellm_provider": "openai", "mode": "chat", "max_output_tokens": 4242, "max_input_tokens": 100000},
+ )
+ mapped_only: dict = {
+ "model_name": "small",
+ "litellm_params": {"model": "openai/auto-cap-probe-model", "api_key": "k"},
+ }
+
+ sent = await self._routed(self._router(simple_deployments=[mapped_only]), max_tokens=8192)
+
+ assert sent["max_tokens"] == 4242
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("client_kwargs", [{}, {"max_tokens": 0}], ids=["omitted", "zero"])
+ async def test_omitted_and_zero_are_replaced_like_any_other_value(self, client_kwargs):
+ sent = await self._routed(self._router(), self.COMPLEX_PROMPT, **client_kwargs)
+
+ assert sent["max_tokens"] == 64000
+
+ @pytest.mark.parametrize(
+ "tier_params, responses_call, expected",
+ [
+ ({"max_tokens": 1, "temperature": 0.2}, False, {"max_tokens": 1, "temperature": 0.2}),
+ ({"max_tokens": 1}, True, {"max_output_tokens": 1}),
+ ({"max_completion_tokens": 2}, False, {"max_tokens": 2}),
+ ({"max_completion_tokens": 2}, True, {"max_output_tokens": 2}),
+ ({"max_output_tokens": 3}, False, {"max_tokens": 3}),
+ ({"max_output_tokens": 3}, True, {"max_output_tokens": 3}),
+ ({"max_tokens": 1, "max_completion_tokens": 2, "max_output_tokens": 3}, False, {"max_tokens": 1}),
+ ({"max_tokens": 1, "max_completion_tokens": 2, "max_output_tokens": 3}, True, {"max_output_tokens": 3}),
+ ({"max_completion_tokens": 2, "max_output_tokens": 3}, False, {"max_tokens": 2}),
+ ({"reasoning_effort": "low"}, True, {"reasoning_effort": "low"}),
+ ],
+ )
+ def test_every_tier_alias_collapses_onto_the_surface_key(self, tier_params, responses_call, expected):
+ assert dict(Router._tier_ceiling_under_the_surface_name(tier_params, responses_call=responses_call)) == expected
+
+ @pytest.mark.asyncio
+ async def test_the_default_fallback_exit_carries_the_ceiling(self):
+ routed: dict = {"max_tokens": 8192}
+ deployment = await self._router().async_get_available_deployment(
+ model="smart-router", request_kwargs=routed, messages=[{"role": "system", "content": "be nice"}]
+ )
+
+ assert routed["metadata"]["routing_decision"]["cause"] == "default_fallback"
+ assert (deployment["litellm_params"]["model"], routed["max_tokens"]) == ("anthropic/claude-sonnet-5", 64000)
+
+ @pytest.mark.asyncio
+ async def test_the_plan_mode_exit_carries_the_ceiling(self):
+ routed: dict = {"max_tokens": 8192}
+ deployment = await self._router(
+ extra_config={"plan_mode_min_tier": "REASONING"}
+ ).async_get_available_deployment(
+ model="smart-router",
+ request_kwargs=routed,
+ messages=[
+ {"role": "user", "content": "plan the refactor"},
+ {"role": "system", "content": "Plan mode is active"},
+ ],
+ )
+
+ assert routed["metadata"]["routing_decision"]["cause"] == "plan_mode"
+ assert (deployment["litellm_params"]["model"], routed["max_tokens"]) == ("anthropic/claude-sonnet-5", 64000)
+
+ @pytest.mark.asyncio
+ async def test_a_default_model_landing_with_no_tier_still_gets_its_ceiling(self):
+ strategy = ComplexityRouter(
+ model_name="smart-router",
+ litellm_router_instance=self._router(),
+ complexity_router_config={"tiers": {"SIMPLE": "small"}, "default_model": "big"},
+ )
+
+ assert dict(strategy._litellm_params_for_model(None, "big")) == {"max_tokens": 64000}
+
+ @pytest.mark.asyncio
+ async def test_a_fallback_into_a_plain_group_gets_the_callers_ceiling_back(self):
+ """A model-group fallback re-enters routing with the same kwargs; a Sonnet-sized ceiling
+ must not ride onto the plain group the caller configured as the fallback."""
+ big: dict = {
+ "model_name": "big",
+ "litellm_params": {
+ "model": "anthropic/claude-sonnet-5",
+ "api_key": "k",
+ "mock_response": "litellm.InternalServerError",
+ },
+ "model_info": {"max_output_tokens": 64000},
+ }
+ plain: dict = {
+ "model_name": "plain",
+ "litellm_params": {"model": "anthropic/claude-haiku-4-5", "api_key": "k", "mock_response": "ok"},
+ }
+ router = Router(
+ model_list=[
+ {
+ "model_name": "smart-router",
+ "litellm_params": {
+ "model": "auto_router/complexity_router",
+ "complexity_router_config": {
+ "tiers": {"SIMPLE": "big", "MEDIUM": "big", "COMPLEX": "big", "REASONING": "big"}
+ },
+ },
+ },
+ big,
+ plain,
+ ],
+ fallbacks=[{"smart-router": ["plain"]}],
+ num_retries=0,
+ )
+ recorder = _OutputCeilingRecorder()
+ litellm.callbacks.append(recorder)
+ try:
+ await router.acompletion(
+ model="smart-router", messages=[{"role": "user", "content": self.COMPLEX_PROMPT}], max_tokens=8192
+ )
+ finally:
+ litellm.callbacks.remove(recorder)
+
+ assert recorder.seen == [("claude-sonnet-5", 64000), ("claude-haiku-4-5", 8192)]
+
+ @pytest.mark.asyncio
+ async def test_a_caller_seeded_stamp_cannot_inject_kwargs_on_a_plain_group(self):
+ """The stamp sits in a metadata bucket a caller can write; a planted one must yield
+ nothing but integer ceiling carriers, never a redirected api_base or credential."""
+ planted: dict = {
+ "api_base": "https://attacker.example",
+ "api_key": "stolen",
+ "max_tokens": "not-an-int",
+ "max_completion_tokens": True,
+ "max_output_tokens": 321,
+ }
+ routed: dict = {"max_tokens": 8192, "metadata": {"_client_output_ceiling": planted}}
+
+ await self._router().async_get_available_deployment(
+ model="big", request_kwargs=routed, messages=[{"role": "user", "content": "hi"}]
+ )
+
+ assert {k: v for k, v in routed.items() if k not in ("metadata", "model_info")} == {"max_output_tokens": 321}
+
+ @pytest.mark.asyncio
+ async def test_the_pass_through_routing_entry_point_pins_and_restores_the_same_way(self):
+ pass_through: dict = {**self.SMALL["litellm_params"], "use_in_pass_through": True}
+ small: dict = {**self.SMALL, "litellm_params": pass_through}
+ plain: dict = {**small, "model_name": "plain"}
+ router = self._router(simple_deployments=[small, plain])
+ for deployment in router.model_list:
+ deployment["litellm_params"]["use_in_pass_through"] = True
+ routed: dict = {"max_tokens": 8192}
+
+ deployment = await router.async_get_available_deployment_for_pass_through(
+ model="smart-router", request_kwargs=routed, messages=[{"role": "user", "content": self.COMPLEX_PROMPT}]
+ )
+ pinned = routed["max_tokens"]
+ await router.async_get_available_deployment_for_pass_through(
+ model="plain", request_kwargs=routed, messages=[{"role": "user", "content": "hi"}]
+ )
+
+ assert (deployment["litellm_params"]["model"], pinned, routed["max_tokens"]) == (
+ "anthropic/claude-sonnet-5",
+ 64000,
+ 8192,
+ )
+
+ @pytest.mark.asyncio
+ async def test_the_classifier_fallback_exit_carries_the_ceiling(self):
+ router = self._router(
+ extra_config={
+ "classifier_type": "llm",
+ "classifier_llm_config": {"model": "no-such-classifier", "timeout_ms": 400},
+ "classifier_fallback": "default_model",
+ "default_model": "big",
+ }
+ )
+ routed: dict = {"max_tokens": 8192}
+
+ deployment = await router.async_get_available_deployment(
+ model="smart-router", request_kwargs=routed, messages=[{"role": "user", "content": "hi"}]
+ )
+
+ assert routed["metadata"]["routing_decision"]["cause"] == "default_model_fallback"
+ assert (deployment["litellm_params"]["model"], routed["max_tokens"]) == ("anthropic/claude-sonnet-5", 64000)
+
+ @pytest.mark.parametrize(
+ "value, expected",
+ [(8192, 8192), ("8192", 8192), (100.9, 100), (0, 0), (-1, None), (True, None), ("x", None), (None, None)],
+ )
+ def test_a_client_cap_is_read_as_an_integer_or_ignored(self, value, expected):
+ assert as_output_cap(value) == expected
+
+ def test_restoring_the_callers_ceiling_reads_the_stamp_and_replaces_every_carrier(self):
+ stamped: dict = {"max_output_tokens": 500, "metadata": {"_client_output_ceiling": {"max_tokens": 8192}}}
+ Router._restore_client_ceiling_no_tier_pins(stamped)
+ assert {k: v for k, v in stamped.items() if k != "metadata"} == {"max_tokens": 8192}
+
+ coerced: dict = {
+ "max_tokens": 64000,
+ "metadata": {"_client_output_ceiling": {"max_tokens": "8192", "max_completion_tokens": 100.0}},
+ }
+ Router._restore_client_ceiling_no_tier_pins(coerced)
+ assert {k: v for k, v in coerced.items() if k != "metadata"} == {
+ "max_tokens": 8192,
+ "max_completion_tokens": 100,
+ }
+
+ unstamped: dict = {"max_tokens": 64000, "metadata": {}}
+ Router._restore_client_ceiling_no_tier_pins(unstamped)
+ assert unstamped["max_tokens"] == 64000
+
+ @pytest.mark.asyncio
+ async def test_pinning_stamps_the_callers_carriers_once(self):
+ router = self._router()
+ request_kwargs: dict = {"max_completion_tokens": 8192}
+
+ first = router._pin_tier_params_onto_request(
+ model="big", tier_litellm_params={"max_tokens": 64000}, request_kwargs=request_kwargs, responses_call=False
+ )
+ second = router._pin_tier_params_onto_request(
+ model="big", tier_litellm_params={"max_tokens": 32000}, request_kwargs=request_kwargs, responses_call=False
+ )
+ none = router._pin_tier_params_onto_request(
+ model="big", tier_litellm_params=None, request_kwargs=request_kwargs, responses_call=False
+ )
+
+ assert (first, second, none) == (True, True, False)
+ assert request_kwargs["max_tokens"] == 32000
+ assert request_kwargs["metadata"]["_client_output_ceiling"] == {"max_completion_tokens": 8192}
+
+
+ class _OutputCeilingRecorder(CustomLogger):
+ def __init__(self) -> None:
+ super().__init__()
+ self.seen: list[tuple[str, int | None]] = []
+
+ def log_pre_api_call(self, model, messages, kwargs):
+ self.seen.append((model, kwargs.get("optional_params", {}).get("max_tokens")))
++
+NON_REASONING_TIERS: Final = {
+ "NON_REASONING": "gpt-4o-mini",
+ "SIMPLE": "gpt-4o-mini",
+ "MEDIUM": "gpt-4o",
+ "COMPLEX": "claude-sonnet-4-20250514",
+ "REASONING": "o1-preview",
+}
+
+
+class TestNonReasoningTier:
+ """The opt-in fifth built-in tier below SIMPLE: inert unless enabled, reachable when it is."""
+
+ @staticmethod
+ def _router(mock_router_instance, **overrides) -> ComplexityRouter:
+ config: Final = {
+ "tiers": dict(NON_REASONING_TIERS),
+ "enable_non_reasoning_tier": True,
+ "classifier_type": "llm",
+ "classifier_llm_config": {"model": "haiku-classifier"},
+ **overrides,
+ }
+ return ComplexityRouter(
+ model_name="test-non-reasoning-router",
+ litellm_router_instance=mock_router_instance,
+ complexity_router_config=config,
+ )
+
+ def test_ladder_gains_a_rung_below_simple_only_when_enabled(self):
+ """Tier 0 sits at the bottom; anywhere else and escalation and the baseline shift."""
+ enabled: Final = ComplexityRouterConfig(
+ tiers=dict(NON_REASONING_TIERS),
+ enable_non_reasoning_tier=True,
+ classifier_type="llm",
+ classifier_llm_config={"model": "clf"},
+ )
+ assert enabled.tier_names() == ("NON_REASONING", "SIMPLE", "MEDIUM", "COMPLEX", "REASONING")
+ assert ComplexityRouterConfig().tier_names() == ("SIMPLE", "MEDIUM", "COMPLEX", "REASONING")
+
+ def test_default_router_is_unchanged_by_the_tier_existing(self):
+ """The enum grew a member, and nothing a four-tier router sends or resolves may change."""
+ default: Final = ComplexityRouterConfig()
+ assert default.enable_non_reasoning_tier is False
+ assert "NON_REASONING" not in DEFAULT_COMPLEXITY_CONFIG.tiers
+ assert default.classifier_wire_labels() == ("SIMPLE", "MEDIUM", "COMPLEX", "REASONING")
+ assert default.labeled_tiers() == TIER_SEVERITY_ORDER_LABELED
+ assert default.resolve_classified_tier("NON_REASONING") is None
+
+ @pytest.mark.parametrize("preset", tuple(ClassificationRubric))
+ def test_rubric_gains_the_bullet_only_when_enabled(self, preset):
+ """An unset toggle leaves every shipped rubric byte-identical; an enabled one adds a bullet."""
+ enabled: Final = ComplexityRouterConfig(
+ tiers=dict(NON_REASONING_TIERS),
+ enable_non_reasoning_tier=True,
+ classifier_type="llm",
+ classifier_llm_config={"model": "clf"},
+ )
+ on: Final = classification_system_prompt(3, None, enabled.labeled_tiers(), preset)
+ off: Final = classification_system_prompt(3, None, ComplexityRouterConfig().labeled_tiers(), preset)
+ assert "- NON_REASONING:" in on
+ assert "- NON_REASONING" not in off
+
+ def test_enabled_router_puts_the_tier_on_the_classifier_wire(self, mock_router_instance):
+ """The schema enum bounds what the classifier may return, whatever the rubric says."""
+ router: Final = self._router(mock_router_instance)
+ enum: Final = router._classifier_response_format["json_schema"]["schema"]["properties"]["tier"]["enum"]
+ assert enum == ["NON_REASONING", "SIMPLE", "MEDIUM", "COMPLEX", "REASONING"]
+
+ @pytest.mark.asyncio
+ async def test_classifier_verdict_routes_to_the_tier_model(self, mock_router_instance):
+ """The classifier names the tier and the request lands on that tier's model."""
+ mock_router_instance.acompletion = AsyncMock(return_value=_llm_response('{"tier": "NON_REASONING"}'))
+ router: Final = self._router(
+ mock_router_instance, tiers={**NON_REASONING_TIERS, "NON_REASONING": "cheap-relay"}
+ )
+ response = await router.async_pre_routing_hook(
+ model="test-non-reasoning-router",
+ request_kwargs={},
+ messages=[{"role": "user", "content": "here is the file, pass it along"}],
+ )
+ assert response.model == "cheap-relay"
+ assert response.routing_decision["tier"] == "NON_REASONING"
+ assert response.routing_decision["cause"] == "llm_classifier"
+
+ @pytest.mark.asyncio
+ async def test_a_four_tier_router_ignores_a_non_reasoning_verdict(
+ self, llm_complexity_router, mock_router_instance
+ ):
+ """Naming the tier at a router that never opted in falls back instead of routing there."""
+ mock_router_instance.acompletion = AsyncMock(return_value=_llm_response('{"tier": "NON_REASONING"}'))
+ outcome = await llm_complexity_router.aclassify("relay this")
+ assert outcome.tier != ComplexityTier.NON_REASONING
+ assert outcome.cause != "llm_classifier"
+
+ def test_escalation_walks_up_off_the_tier(self, mock_router_instance):
+ """Escalation is a built-in-ladder feature and the issue asks for it from the new tier."""
+ router: Final = self._router(mock_router_instance)
+ assert router._escalate_tier(ComplexityTier.NON_REASONING) == ComplexityTier.SIMPLE
+ assert router._escalate_tier(ComplexityTier.REASONING) == ComplexityTier.REASONING
+
+ def test_escalation_skips_the_tier_when_unconfigured(self, mock_router_instance):
+ """SIMPLE still escalates to MEDIUM, so escalation never routes below the caller's model."""
+ router: Final = self._router(
+ mock_router_instance,
+ tiers={"NON_REASONING": "cheap-relay", "SIMPLE": "gpt-4o-mini", "MEDIUM": "gpt-4o"},
+ )
+ assert router._escalate_tier(ComplexityTier.SIMPLE) == ComplexityTier.MEDIUM
+
+ def test_tier_zero_is_never_the_savings_baseline(self, mock_router_instance):
+ """Savings use the hardest configured tier; tier 0 winning would invert every figure."""
+ assert self._router(mock_router_instance)._hardest_tier_models() == ("o1-preview",)
+ cheap_only: Final = self._router(
+ mock_router_instance, tiers={"NON_REASONING": "cheap-relay", "SIMPLE": "gpt-4o-mini"}
+ )
+ assert cheap_only._hardest_tier_models() == ("gpt-4o-mini",)
+
+ def test_the_tier_gets_its_own_display_label(self, mock_router_instance):
+ """tier_labels covers the built-in tiers, so the new rung must be renameable like the rest."""
+ router: Final = self._router(mock_router_instance, tier_labels={"NON_REASONING": "Relay"})
+ assert router.config.classifier_wire_labels()[0] == "Relay"
+ assert router.config.resolve_classified_tier("relay") == ComplexityTier.NON_REASONING
+
+ @pytest.mark.parametrize(
+ "overrides, expected",
+ (
+ ({"classifier_type": "heuristic", "classifier_llm_config": None}, "requires classifier_type"),
+ ({"classifier_type": "heuristic_v2", "classifier_llm_config": None}, "requires classifier_type"),
+ ({"tiers": {"SIMPLE": "a", "MEDIUM": "b"}}, "at least one model"),
+ ),
+ ids=["heuristic", "heuristic_v2", "no_model"],
+ )
+ def test_unreachable_or_unroutable_configs_are_rejected(self, overrides, expected):
+ """Refused where it could do nothing: no scorer emits the tier, no pool routes it."""
+ config: Final = {
+ "tiers": dict(NON_REASONING_TIERS),
+ "enable_non_reasoning_tier": True,
+ "classifier_type": "llm",
+ "classifier_llm_config": {"model": "clf"},
+ **overrides,
+ }
+ with pytest.raises(ValidationError, match=expected):
+ ComplexityRouterConfig.model_validate(config)
+
+ def test_the_tier_cannot_be_configured_without_the_toggle(self):
+ """Silently ignoring the key would leave an operator paying for a pool nothing routes to."""
+ with pytest.raises(ValidationError, match="no request can route there"):
+ ComplexityRouterConfig(tiers={"NON_REASONING": "cheap", "SIMPLE": "a"})
+
+ def test_the_toggle_is_refused_alongside_a_custom_tier_set(self):
+ """A custom tier set replaces the built-in ladder, so both at once has no meaning."""
+ with pytest.raises(ValidationError, match="cannot be combined with tier_definitions"):
+ ComplexityRouterConfig(
+ enable_non_reasoning_tier=True,
+ classifier_type="llm",
+ classifier_llm_config={"model": "clf"},
+ tier_definitions=({"name": "lo", "description": "d"}, {"name": "hi", "description": "d"}),
+ tiers={"lo": "a", "hi": "b"},
+ fallback_tier="lo",
+ )
+
+ def test_heuristic_v2_predictions_never_reach_the_new_tier(self, mock_router_instance):
+ """The four-class artifact's 1-based index must keep mapping onto SIMPLE..REASONING."""
+ router: Final = ComplexityRouter(
+ model_name="v2-router",
+ litellm_router_instance=mock_router_instance,
+ complexity_router_config={
+ "tiers": {k: v for k, v in NON_REASONING_TIERS.items() if k != "NON_REASONING"},
+ "classifier_type": "heuristic_v2",
+ },
+ )
+ outcome = router._classify_with_heuristic_v2("implement a distributed rate limiter under concurrency")
+ assert outcome.tier in TIER_SEVERITY_ORDER
+ assert tuple(signal.split(":")[1].split("=")[0] for signal in outcome.signals[1:]) == (
+ "simple",
+ "medium",
+ "complex",
+ "reasoning",
+ )