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(auto-router): stop the embedding model's context window from failing long requests (#35956)

Abhimanyu Kapurc76882b51b61
diff --git a/litellm/constants.py b/litellm/constants.py
index 0c7316455d6..75f12190b3e 100644
--- a/litellm/constants.py
+++ b/litellm/constants.py
@@ -91,6 +91,8 @@ DEFAULT_MCP_SEMANTIC_FILTER_SIMILARITY_THRESHOLD: Final = float(
)
MAX_MCP_SEMANTIC_FILTER_TOOLS_HEADER_LENGTH: Final = int(os.getenv("MAX_MCP_SEMANTIC_FILTER_TOOLS_HEADER_LENGTH", 150))
+DEFAULT_AUTO_ROUTER_MAX_INPUT_CHARS: Final = 2000
+
# Semantic Guard Defaults
DEFAULT_SEMANTIC_GUARD_EMBEDDING_MODEL: Final = str(
os.getenv("DEFAULT_SEMANTIC_GUARD_EMBEDDING_MODEL", "text-embedding-3-small")
diff --git a/litellm/router.py b/litellm/router.py
index 8b93de34944..c4a16521fa7 100644
--- a/litellm/router.py
+++ b/litellm/router.py
@@ -42,6 +42,7 @@ from litellm.caching.caching import (
RedisClusterCache,
)
from litellm.constants import (
+ DEFAULT_AUTO_ROUTER_MAX_INPUT_CHARS,
DEFAULT_HEALTH_CHECK_INTERVAL,
DEFAULT_HEALTH_CHECK_STALENESS_MULTIPLIER,
DEFAULT_MAX_LRU_CACHE_SIZE,
@@ -7605,6 +7606,8 @@ class Router:
"auto_router_embedding_model is required for auto-router deployments. Please set it in the litellm_params"
)
+ max_input_chars: Final[int | None] = deployment.litellm_params.auto_router_max_input_chars
+
autor_router: Final[AutoRouter] = AutoRouter(
model_name=deployment.model_name,
auto_router_config_path=auto_router_config_path,
@@ -7612,6 +7615,7 @@ class Router:
default_model=default_model,
embedding_model=embedding_model,
litellm_router_instance=self,
+ max_input_chars=(max_input_chars if max_input_chars is not None else DEFAULT_AUTO_ROUTER_MAX_INPUT_CHARS),
)
self._register_pre_routing_strategy(
registry=self.auto_routers,
diff --git a/litellm/router_strategy/auto_router/auto_router.py b/litellm/router_strategy/auto_router/auto_router.py
index 693a28fd5fa..20c0ece46b6 100644
--- a/litellm/router_strategy/auto_router/auto_router.py
+++ b/litellm/router_strategy/auto_router/auto_router.py
@@ -5,9 +5,11 @@ Auto-Routing Strategy that works with a Semantic Router Config
from typing import TYPE_CHECKING, Any, Final, Optional
from litellm._logging import verbose_router_logger
+from litellm.constants import DEFAULT_AUTO_ROUTER_MAX_INPUT_CHARS
from litellm.integrations.custom_logger import CustomLogger
if TYPE_CHECKING:
+ from semantic_router.routers import SemanticRouter
from semantic_router.routers.base import Route
from litellm.router import Router
@@ -16,6 +18,7 @@ else:
Router = Any
PreRoutingHookResponse = Any
Route = Any
+ SemanticRouter = Any
class AutoRouter(CustomLogger):
@@ -29,6 +32,7 @@ class AutoRouter(CustomLogger):
litellm_router_instance: "Router",
auto_router_config_path: str | None = None,
auto_router_config: str | None = None,
+ max_input_chars: int = DEFAULT_AUTO_ROUTER_MAX_INPUT_CHARS,
):
"""
Auto-Router class that uses a semantic router to route requests to the appropriate model.
@@ -40,6 +44,9 @@ class AutoRouter(CustomLogger):
default_model: The default model to use if no route is found.
embedding_model: The embedding model to use for the auto-router.
litellm_router_instance: The instance of the LiteLLM Router.
+ max_input_chars: Longest prompt, in characters, handed to the embedding model. Longer
+ prompts are cut to this length so an embedding context window far smaller than the
+ routed model's never fails the request.
"""
from semantic_router.routers import SemanticRouter
@@ -50,6 +57,7 @@ class AutoRouter(CustomLogger):
self.routelayer: SemanticRouter | None = None
self.default_model = default_model
self.embedding_model: str = embedding_model
+ self.max_input_chars: int = max_input_chars
self.litellm_router_instance: Router = litellm_router_instance
def _load_semantic_routing_routes(self) -> list[Route]:
@@ -119,7 +127,6 @@ class AutoRouter(CustomLogger):
Used for the litellm auto-router to modify the request before the routing decision is made.
"""
from semantic_router.routers import SemanticRouter
- from semantic_router.schema import RouteChoice
from litellm.router_strategy.auto_router.litellm_encoder import (
LiteLLMRouterEncoder,
@@ -140,20 +147,39 @@ class AutoRouter(CustomLogger):
encoder=LiteLLMRouterEncoder(
litellm_router_instance=self.litellm_router_instance,
model_name=self.embedding_model,
+ max_input_chars=self.max_input_chars,
),
auto_sync=self.auto_sync_value,
)
self.routelayer = routelayer
message_content: Final = self._extract_text_from_messages(messages)
- route_choice: Final[RouteChoice | list[RouteChoice] | None] = routelayer(text=message_content)
- verbose_router_logger.debug("route_choice: %s", route_choice)
- if isinstance(route_choice, RouteChoice):
- model = route_choice.name or self.default_model
- elif isinstance(route_choice, list):
- model = route_choice[0].name or self.default_model
+ route_name: Final = self._matched_route_name(routelayer, message_content)
return PreRoutingHookResponse(
- model=model,
+ model=route_name or self.default_model,
messages=messages,
)
+
+ def _matched_route_name(self, routelayer: "SemanticRouter", text: str) -> str | None:
+ """Name of the route `text` matches, or None when nothing matched or the match failed.
+
+ The route layer embeds `text` to compare it against the routes, and that embedding call can
+ fail (context limit, timeout, provider error). Choosing a model is a routing decision, so a
+ failure here falls back to the default model rather than failing the user's request.
+ """
+ from semantic_router.schema import RouteChoice
+
+ try:
+ route_choice: Final = routelayer(text=text)
+ except Exception as e: # noqa: BLE001 -- the embedding call behind the route layer can fail many ways (context limit, timeout, provider/network error); none of them may fail the request
+ verbose_router_logger.warning(
+ "AutoRouter: semantic routing failed (%s), falling back to default model %s", e, self.default_model
+ )
+ return None
+ verbose_router_logger.debug("route_choice: %s", route_choice)
+ if isinstance(route_choice, RouteChoice):
+ return route_choice.name
+ if isinstance(route_choice, list) and route_choice:
+ return route_choice[0].name
+ return None
diff --git a/litellm/router_strategy/auto_router/litellm_encoder.py b/litellm/router_strategy/auto_router/litellm_encoder.py
index 80de9d34b83..1b34785b6fe 100644
--- a/litellm/router_strategy/auto_router/litellm_encoder.py
+++ b/litellm/router_strategy/auto_router/litellm_encoder.py
@@ -5,6 +5,7 @@ from semantic_router.encoders import DenseEncoder
from semantic_router.encoders.base import AsymmetricDenseMixin
import litellm
+from litellm._logging import verbose_router_logger
if TYPE_CHECKING:
from litellm.router import Router
@@ -50,6 +51,7 @@ class LiteLLMRouterEncoder(CustomDenseEncoder, AsymmetricDenseMixin):
litellm_router_instance: "Router",
model_name: str,
score_threshold: float | None = None,
+ max_input_chars: int = 0,
):
"""Initialize the LiteLLMEncoder.
@@ -60,6 +62,13 @@ class LiteLLMRouterEncoder(CustomDenseEncoder, AsymmetricDenseMixin):
:type model_name: str
:param score_threshold: The score threshold for the embeddings.
:type score_threshold: float
+ :param max_input_chars: Longest doc, in characters, sent to the embedding model; anything
+ longer is cut to this length. Opt-in, defaulting to 0 (send docs whole), because a
+ caller that has to see the entire text to be correct must not be cut silently: a
+ semantic guard that inspects only a prefix can be walked past with a benign opener.
+ Callers that only rank text against short utterances, such as the auto-router, pass a
+ limit so the encoder's context window cannot fail their request.
+ :type max_input_chars: int
"""
super().__init__(
name=model_name,
@@ -67,6 +76,23 @@ class LiteLLMRouterEncoder(CustomDenseEncoder, AsymmetricDenseMixin):
)
self.model_name = model_name
self.litellm_router_instance = litellm_router_instance
+ self.max_input_chars = max_input_chars
+
+ def _clamp(self, docs: list[str]) -> list[str]: # mutable-ok: embedding() takes `input: str | list`
+ """Cut every doc to `max_input_chars`, keeping the head, or return them whole when unset.
+
+ The head carries the ask often enough to place it against a route, and a cut prompt still
+ routes where an over-long one just errors out.
+ """
+ limit: Final = self.max_input_chars
+ if limit <= 0:
+ return docs
+ clamped: Final = [doc[:limit] for doc in docs] # mutable-ok: embedding() takes `input: str | list`
+ if clamped != docs:
+ verbose_router_logger.debug(
+ "LiteLLMRouterEncoder: cut input to %s chars for embedding model %s", limit, self.model_name
+ )
+ return clamped
def __call__(self, docs: list[Any], **kwargs) -> list[list[float]]:
"""Encode a list of text documents into embeddings using LiteLLM.
@@ -86,7 +112,9 @@ class LiteLLMRouterEncoder(CustomDenseEncoder, AsymmetricDenseMixin):
if self.litellm_router_instance is None:
raise ValueError("litellm_router_instance is not set")
try:
- embeds: Final = self.litellm_router_instance.embedding(input=docs, model=self.model_name, **kwargs)
+ embeds: Final = self.litellm_router_instance.embedding(
+ input=self._clamp(docs), model=self.model_name, **kwargs
+ )
return litellm_to_list(embeds)
except Exception as e:
raise ValueError(f"{self.type.capitalize()} API call failed. Error: {e}") from e
@@ -95,7 +123,9 @@ class LiteLLMRouterEncoder(CustomDenseEncoder, AsymmetricDenseMixin):
if self.litellm_router_instance is None:
raise ValueError("litellm_router_instance is not set")
try:
- embeds: Final = self.litellm_router_instance.embedding(input=docs, model=self.model_name, **kwargs)
+ embeds: Final = self.litellm_router_instance.embedding(
+ input=self._clamp(docs), model=self.model_name, **kwargs
+ )
return litellm_to_list(embeds)
except Exception as e:
raise ValueError(f"{self.type.capitalize()} API call failed. Error: {e}") from e
@@ -104,7 +134,9 @@ class LiteLLMRouterEncoder(CustomDenseEncoder, AsymmetricDenseMixin):
if self.litellm_router_instance is None:
raise ValueError("litellm_router_instance is not set")
try:
- embeds: Final = await self.litellm_router_instance.aembedding(input=docs, model=self.model_name, **kwargs)
+ embeds: Final = await self.litellm_router_instance.aembedding(
+ input=self._clamp(docs), model=self.model_name, **kwargs
+ )
return litellm_to_list(embeds)
except Exception as e:
raise ValueError(f"{self.type.capitalize()} API call failed. Error: {e}") from e
@@ -113,7 +145,9 @@ class LiteLLMRouterEncoder(CustomDenseEncoder, AsymmetricDenseMixin):
if self.litellm_router_instance is None:
raise ValueError("litellm_router_instance is not set")
try:
- embeds: Final = await self.litellm_router_instance.aembedding(input=docs, model=self.model_name, **kwargs)
+ embeds: Final = await self.litellm_router_instance.aembedding(
+ input=self._clamp(docs), model=self.model_name, **kwargs
+ )
return litellm_to_list(embeds)
except Exception as e:
raise ValueError(f"{self.type.capitalize()} API call failed. Error: {e}") from e
diff --git a/litellm/router_utils/auto_router_model_naming.py b/litellm/router_utils/auto_router_model_naming.py
index 55482fb5543..f17e09da5f9 100644
--- a/litellm/router_utils/auto_router_model_naming.py
+++ b/litellm/router_utils/auto_router_model_naming.py
@@ -23,6 +23,7 @@ STRATEGY_ROUTER_PARAM_FIELDS: Final[frozenset[str]] = frozenset(
"auto_router_config_path",
"auto_router_default_model",
"auto_router_embedding_model",
+ "auto_router_max_input_chars",
"complexity_router_config",
"complexity_router_default_model",
"adaptive_router_config",
diff --git a/litellm/types/router.py b/litellm/types/router.py
index 08780064162..83757daa4dd 100644
--- a/litellm/types/router.py
+++ b/litellm/types/router.py
@@ -259,6 +259,7 @@ class GenericLiteLLMParams(CredentialLiteLLMParams, CustomPricingLiteLLMParams):
auto_router_config: str | None = None
auto_router_default_model: str | None = None
auto_router_embedding_model: str | None = None
+ auto_router_max_input_chars: int | None = None
# complexity-router params
complexity_router_config: dict | None = None
diff --git a/litellm/types/utils.py b/litellm/types/utils.py
index 8371f98222b..c52674ede40 100644
--- a/litellm/types/utils.py
+++ b/litellm/types/utils.py
@@ -3493,6 +3493,7 @@ all_litellm_params = (
"auto_router_config",
"auto_router_default_model",
"auto_router_embedding_model",
+ "auto_router_max_input_chars",
"complexity_router_config",
"complexity_router_default_model",
"adaptive_router_config",
diff --git a/tests/test_litellm/router_strategy/test_auto_router.py b/tests/test_litellm/router_strategy/test_auto_router.py
index cb46a4ae553..b73485e6019 100644
--- a/tests/test_litellm/router_strategy/test_auto_router.py
+++ b/tests/test_litellm/router_strategy/test_auto_router.py
@@ -1,7 +1,8 @@
import asyncio
+import json
import os
import sys
-from typing import Any, Dict, List, Optional
+from typing import Any, Dict, Final, List, Optional
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -316,3 +317,165 @@ class TestAutoRouter:
# Assert
assert result is None
+
+
+semantic_router = pytest.importorskip("semantic_router", reason="auto-router needs the semantic-router extra")
+
+ROUTER_CONFIG: Final = json.dumps(
+ {
+ "routes": [
+ {
+ "name": "code-model",
+ "description": "coding asks",
+ "utterances": ["fix this stack trace", "refactor this function"],
+ "score_threshold": 0.5,
+ }
+ ]
+ }
+)
+
+
+class FailingRouteLayer:
+ """Route layer whose embedding call fails, as it does when the prompt exceeds the encoder's window."""
+
+ def __call__(self, text: str) -> Any:
+ raise ValueError(
+ "Internal_litellm_router API call failed. Error: litellm.InternalServerError: "
+ "input is too large to process. increase the physical batch size"
+ )
+
+
+class FixedRouteLayer:
+ """Route layer that returns whatever the test tells it to, recording the text it was asked about."""
+
+ def __init__(self, route_choice: Any) -> None:
+ self.route_choice = route_choice
+ self.seen_text: str | None = None
+
+ def __call__(self, text: str) -> Any:
+ self.seen_text = text
+ return self.route_choice
+
+
+class StubEmbeddingRouter:
+ """Stands in for the LiteLLM Router when the route index has to be built for real."""
+
+ def embedding(self, input: List[str], model: str, **kwargs: Any) -> Any:
+ import litellm
+
+ return litellm.EmbeddingResponse(
+ data=[{"embedding": [0.1, 0.2], "index": i, "object": "embedding"} for i in range(len(input))]
+ )
+
+
+def _auto_router(routelayer: Any, litellm_router_instance: Any = None, **kwargs: Any) -> AutoRouter:
+ auto_router: Final = AutoRouter(
+ model_name="my-auto-router",
+ auto_router_config=ROUTER_CONFIG,
+ default_model="fallback-model",
+ embedding_model="text-embedding-3-small",
+ litellm_router_instance=litellm_router_instance or MagicMock(),
+ **kwargs,
+ )
+ auto_router.routelayer = routelayer
+ return auto_router
+
+
+class TestAutoRouterAlwaysResolvesARoutableModel:
+ """The hook returns the alias's default model instead of failing or leaking the alias downstream."""
+
+ @pytest.mark.asyncio
+ async def test_should_fall_back_to_default_model_when_the_embedding_call_fails(self):
+ auto_router: Final = _auto_router(FailingRouteLayer())
+
+ result: Final = await auto_router.async_pre_routing_hook(
+ model="my-auto-router",
+ request_kwargs={},
+ messages=[{"role": "user", "content": "a" * 100_000}],
+ )
+
+ assert result is not None
+ assert result.model == "fallback-model"
+
+ @pytest.mark.asyncio
+ async def test_should_fall_back_to_default_model_when_no_route_matches(self):
+ auto_router: Final = _auto_router(FixedRouteLayer(None))
+
+ result: Final = await auto_router.async_pre_routing_hook(
+ model="my-auto-router",
+ request_kwargs={},
+ messages=[{"role": "user", "content": "nothing like any route"}],
+ )
+
+ assert result is not None
+ # Leaving "my-auto-router" here fails downstream with "Unmapped LLM provider".
+ assert result.model == "fallback-model"
+
+ @pytest.mark.asyncio
+ async def test_should_fall_back_to_default_model_when_the_route_layer_returns_an_empty_list(self):
+ auto_router: Final = _auto_router(FixedRouteLayer([]))
+
+ result: Final = await auto_router.async_pre_routing_hook(
+ model="my-auto-router",
+ request_kwargs={},
+ messages=[{"role": "user", "content": "nothing like any route"}],
+ )
+
+ assert result is not None
+ assert result.model == "fallback-model"
+
+ @pytest.mark.asyncio
+ async def test_should_route_to_the_first_choice_when_the_route_layer_returns_a_populated_list(self):
+ from semantic_router.schema import RouteChoice
+
+ auto_router: Final = _auto_router(
+ FixedRouteLayer([RouteChoice(name="code-model"), RouteChoice(name="chat-model")])
+ )
+
+ result: Final = await auto_router.async_pre_routing_hook(
+ model="my-auto-router",
+ request_kwargs={},
+ messages=[{"role": "user", "content": "fix this stack trace"}],
+ )
+
+ assert result is not None
+ assert result.model == "code-model"
+
+ @pytest.mark.asyncio
+ async def test_should_still_route_to_the_matched_route_when_one_matches(self):
+ from semantic_router.schema import RouteChoice
+
+ layer: Final = FixedRouteLayer(RouteChoice(name="code-model"))
+ auto_router: Final = _auto_router(layer)
+
+ result: Final = await auto_router.async_pre_routing_hook(
+ model="my-auto-router",
+ request_kwargs={},
+ messages=[{"role": "user", "content": "fix this stack trace"}],
+ )
+
+ assert result is not None
+ assert result.model == "code-model"
+ assert layer.seen_text == "fix this stack trace"
+
+
+class TestAutoRouterEmbeddingInputCap:
+ """The cap configured on the deployment is what the encoder enforces."""
+
+ def test_should_default_the_cap_to_the_shared_constant(self):
+ from litellm.constants import DEFAULT_AUTO_ROUTER_MAX_INPUT_CHARS
+
+ assert _auto_router(FixedRouteLayer(None)).max_input_chars == DEFAULT_AUTO_ROUTER_MAX_INPUT_CHARS
+
+ @pytest.mark.asyncio
+ async def test_should_build_its_encoder_with_the_configured_cap(self):
+ auto_router: Final = _auto_router(None, litellm_router_instance=StubEmbeddingRouter(), max_input_chars=777)
+
+ await auto_router.async_pre_routing_hook(
+ model="my-auto-router",
+ request_kwargs={},
+ messages=[{"role": "user", "content": "fix this stack trace"}],
+ )
+
+ assert auto_router.routelayer is not None
+ assert auto_router.routelayer.encoder.max_input_chars == 777
diff --git a/tests/test_litellm/router_strategy/test_litellm_encoder.py b/tests/test_litellm/router_strategy/test_litellm_encoder.py
new file mode 100644
index 00000000000..6c934e57832
--- /dev/null
+++ b/tests/test_litellm/router_strategy/test_litellm_encoder.py
@@ -0,0 +1,134 @@
+"""Tests for litellm/router_strategy/auto_router/litellm_encoder.py"""
+
+import os
+import sys
+from typing import Any, Final
+
+import pytest
+
+sys.path.insert(0, os.path.abspath("../../.."))
+
+import litellm
+from litellm.constants import DEFAULT_AUTO_ROUTER_MAX_INPUT_CHARS
+from litellm.router_strategy.auto_router.litellm_encoder import LiteLLMRouterEncoder
+
+
+class RecordingRouter:
+ """Stand-in for the LiteLLM Router that records what reached the embedding call.
+
+ Injected through the encoder's constructor so the assertion is on the real code path
+ rather than on a patched attribute.
+ """
+
+ def __init__(self) -> None:
+ self.embedded_inputs: list[list[str]] = []
+
+ def _response(self, input: list[str]) -> litellm.EmbeddingResponse:
+ self.embedded_inputs.append(list(input))
+ return litellm.EmbeddingResponse(
+ data=[{"embedding": [0.1, 0.2], "index": i, "object": "embedding"} for i in range(len(input))]
+ )
+
+ def embedding(self, input: list[str], model: str, **kwargs: Any) -> litellm.EmbeddingResponse:
+ return self._response(input)
+
+ async def aembedding(self, input: list[str], model: str, **kwargs: Any) -> litellm.EmbeddingResponse:
+ return self._response(input)
+
+
+def _encoder(router: RecordingRouter, **kwargs: Any) -> LiteLLMRouterEncoder:
+ return LiteLLMRouterEncoder(
+ litellm_router_instance=router, # pyright: ignore[reportArgumentType] # test double stands in for Router
+ model_name="text-embedding-3-small",
+ **kwargs,
+ )
+
+
+class TestSendsDocsWholeUnlessAskedNotTo:
+ """Cutting is opt-in: a caller that must see the whole text is never cut behind its back.
+
+ The semantic guard and the MCP tool filter build this encoder without a limit. If a default
+ limit ever creeps back in, a prompt-injection payload placed after a benign opener would be
+ invisible to the guard while the full message still reaches the model.
+ """
+
+ def test_should_send_a_long_doc_whole_when_no_cap_is_configured(self):
+ router: Final = RecordingRouter()
+ long_doc: Final = "x" * 50_000
+
+ _encoder(router).encode_queries([long_doc])
+
+ assert router.embedded_inputs == [[long_doc]]
+
+ @pytest.mark.asyncio
+ async def test_should_send_a_long_doc_whole_when_no_cap_is_configured_async(self):
+ router: Final = RecordingRouter()
+ long_doc: Final = "x" * 50_000
+
+ await _encoder(router).aencode_queries([long_doc])
+
+ assert router.embedded_inputs == [[long_doc]]
+
+ def test_should_send_a_long_doc_whole_when_the_cap_is_not_positive(self):
+ router: Final = RecordingRouter()
+ long_doc: Final = "x" * 50_000
+
+ _encoder(router, max_input_chars=0).encode_queries([long_doc])
+
+ assert router.embedded_inputs == [[long_doc]]
+
+
+class TestEmbeddingInputCap:
+ """With a cap configured, an embedding model's context window cannot fail the caller's request."""
+
+ def test_should_cut_a_long_doc_to_the_cap_on_sync_encode(self):
+ router: Final = RecordingRouter()
+
+ _encoder(router, max_input_chars=DEFAULT_AUTO_ROUTER_MAX_INPUT_CHARS).encode_queries(["x" * 50_000])
+
+ assert router.embedded_inputs == [["x" * DEFAULT_AUTO_ROUTER_MAX_INPUT_CHARS]]
+
+ @pytest.mark.asyncio
+ async def test_should_cut_a_long_doc_to_the_cap_on_async_encode(self):
+ router: Final = RecordingRouter()
+
+ await _encoder(router, max_input_chars=DEFAULT_AUTO_ROUTER_MAX_INPUT_CHARS).aencode_queries(["x" * 50_000])
+
+ assert router.embedded_inputs == [["x" * DEFAULT_AUTO_ROUTER_MAX_INPUT_CHARS]]
+
+ def test_should_cut_documents_as_well_as_queries(self):
+ router: Final = RecordingRouter()
+
+ _encoder(router, max_input_chars=100).encode_documents(["y" * 9_000])
+
+ assert router.embedded_inputs == [["y" * 100]]
+
+ @pytest.mark.asyncio
+ async def test_should_cut_documents_as_well_as_queries_async(self):
+ router: Final = RecordingRouter()
+
+ await _encoder(router, max_input_chars=100).aencode_documents(["y" * 9_000])
+
+ assert router.embedded_inputs == [["y" * 100]]
+
+ def test_should_leave_docs_within_the_cap_untouched(self):
+ router: Final = RecordingRouter()
+ docs: Final = ["a short prompt", "b" * 100]
+
+ _encoder(router, max_input_chars=100).encode_queries(docs)
+
+ assert router.embedded_inputs == [docs]
+
+ def test_should_cut_each_doc_in_a_batch_independently(self):
+ router: Final = RecordingRouter()
+
+ _encoder(router, max_input_chars=100).encode_queries(["short", "z" * 5_000])
+
+ assert router.embedded_inputs == [["short", "z" * 100]]
+
+ def test_should_keep_the_head_of_the_doc(self):
+ router: Final = RecordingRouter()
+
+ _encoder(router, max_input_chars=20).encode_queries(["route me please, then a huge pasted file"])
+
+ assert router.embedded_inputs == [["route me please, the"]]
diff --git a/tests/test_litellm/test_router.py b/tests/test_litellm/test_router.py
index d61f083609b..4dec574b9f3 100644
--- a/tests/test_litellm/test_router.py
+++ b/tests/test_litellm/test_router.py
@@ -7288,3 +7288,49 @@ def test_pre_call_checks_keeps_deployment_when_provider_is_unresolvable(monkeypa
)
assert len(result) == 1
+
+
+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
diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.ts
index ded3f54e46b..86de0df30bc 100644
--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts
+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts
@@ -26712,6 +26712,8 @@ export interface components {
auto_router_default_model?: string | null;
/** Auto Router Embedding Model */
auto_router_embedding_model?: string | null;
+ /** Auto Router Max Input Chars */
+ auto_router_max_input_chars?: number | null;
/** Aws Access Key Id */
aws_access_key_id?: string | null;
/** Aws Bedrock Project Id */
@@ -35287,6 +35289,8 @@ export interface components {
auto_router_default_model?: string | null;
/** Auto Router Embedding Model */
auto_router_embedding_model?: string | null;
+ /** Auto Router Max Input Chars */
+ auto_router_max_input_chars?: number | null;
/** Aws Access Key Id */
aws_access_key_id?: string | null;
/** Aws Bedrock Project Id */