Skip to content

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

fix(router): accept fenced Fuse classifier verdicts

Tin Chi Lo9352d2486396
diff --git a/litellm/router_strategy/complexity_router/capability_classifier.py b/litellm/router_strategy/complexity_router/capability_classifier.py
index 66ed9c36ed8..21046ff3421 100644
--- a/litellm/router_strategy/complexity_router/capability_classifier.py
+++ b/litellm/router_strategy/complexity_router/capability_classifier.py
@@ -202,10 +202,15 @@ def capability_classifier_system_prompt(mode: Literal["json_schema", "json_objec
)
-def parse_capability_classifier_verdict(content: str) -> CapabilityClassifierVerdict:
- """Parse raw JSON or the fenced JSON shape tolerated by Switchyard."""
+def unwrap_classifier_json(content: str) -> str:
+ """Remove the optional Markdown fence without repairing or weakening verdict JSON."""
text: Final = content.strip()
if not text.startswith("```"):
- return CapabilityClassifierVerdict.model_validate_json(text)
+ return text
unfenced: Final = text.removeprefix("```").removeprefix("json").lstrip("\n\r")
- return CapabilityClassifierVerdict.model_validate_json(unfenced.removesuffix("```").strip())
+ return unfenced.removesuffix("```").strip()
+
+
+def parse_capability_classifier_verdict(content: str) -> CapabilityClassifierVerdict:
+ """Parse raw JSON or the fenced JSON shape tolerated by Switchyard."""
+ return CapabilityClassifierVerdict.model_validate_json(unwrap_classifier_json(content))
diff --git a/litellm/router_strategy/complexity_router/complexity_router.py b/litellm/router_strategy/complexity_router/complexity_router.py
index 53e872d3e3b..d19cdfaa899 100644
--- a/litellm/router_strategy/complexity_router/complexity_router.py
+++ b/litellm/router_strategy/complexity_router/complexity_router.py
@@ -81,6 +81,7 @@ from .capability_classifier import (
capability_classifier_response_format,
capability_classifier_system_prompt,
parse_capability_classifier_verdict,
+ unwrap_classifier_json,
)
from .classification_rubrics import BUSINESS_TIER_CRITERIA, calibration_examples_section
from .config import (
@@ -2370,7 +2371,7 @@ class ComplexityRouter(CustomLogger):
messages_for_call, request_kwargs, encrypted_task=encrypted, max_output_tokens=v2.max_output_tokens
)
try:
- verdict: Final = LLMV2Verdict.model_validate_json(content)
+ verdict: Final = LLMV2Verdict.model_validate_json(unwrap_classifier_json(content))
except ValidationError:
return self._classifier_failure_outcome("Invalid LLM V2 forecast", prompt, system_prompt)._replace(
classifier_cost=classifier_cost
diff --git a/tests/test_litellm/router_strategy/test_llm_v2.py b/tests/test_litellm/router_strategy/test_llm_v2.py
index 407d3a398c9..5447c8b43ce 100644
--- a/tests/test_litellm/router_strategy/test_llm_v2.py
+++ b/tests/test_litellm/router_strategy/test_llm_v2.py
@@ -222,6 +222,27 @@ async def test_json_object_mode_supplies_schema_in_prompt() -> None:
assert '"required"' in sent["messages"][0]["content"]
[email protected]("mode", ("json_schema", "json_object"))
[email protected]("fence", ("```json", "```"))
+async def test_fenced_forecast_routes_by_validated_probabilities(mode: str, fence: str) -> None:
+ base: Final = _config().llm_v2_config
+ assert base is not None
+ config: Final = _config(llm_v2_config={**base.model_dump(), "response_format": mode})
+ content: Final = f" {fence}\n{_verdict().model_dump_json()}\n``` "
+ router, client = _router(content, config)
+ result: Final = await router.async_pre_routing_hook(
+ model="v2-router", messages=[{"role": "user", "content": "Fix nested behavior"}], request_kwargs={}
+ )
+ assert result is not None and result.model == "efficient"
+ assert result.routing_decision is not None
+ assert result.routing_decision["cause"] == "llm_v2_classifier"
+ assert result.routing_decision["classifier_efficient_p_solve"] == 0.9
+ assert result.routing_decision["classifier_capable_p_solve"] == 0.92
+ assert result.routing_decision["classifier_cost"] == 0.001
+ client.acompletion.assert_awaited_once()
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize("user_agent", ("claude-cli/2.1.233", "curl/8.7.1"))
@pytest.mark.parametrize("metadata_key", ("metadata", "litellm_metadata"))
@@ -280,7 +301,9 @@ async def test_routing_metadata_preserves_exact_forecasts_and_redaction(
@pytest.mark.asyncio
[email protected]("content", ["", "not json", '{"tier":"SIMPLE"}', '{"forecasts":{}}'])
+ "content", ["", "not json", '{"tier":"SIMPLE"}', '{"forecasts":{}}', '```json\n{"forecasts":{}}\n```']
+)
async def test_invalid_output_falls_back_to_capable_and_preserves_paid_call_cost(content: str) -> None:
router, client = _router(content)
result: Final = await router.async_pre_routing_hook(