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
fix(router): enforce context-window pre-call checks for Responses API input (#33706)
devin-ai-integration[bot]010b20072d20
diff --git a/litellm/router.py b/litellm/router.pyindex b1a5405ebf1..0b1471dc527 100644--- a/litellm/router.py+++ b/litellm/router.py@@ -4461,6 +4461,7 @@ class Router:model=model,request_kwargs=kwargs,messages=kwargs.get("messages", None),+ input=kwargs.get("input", None),specific_deployment=kwargs.pop("specific_deployment", None),)except Exception as e:@@ -4608,6 +4609,7 @@ class Router:deployment = self.get_available_deployment(model=model,messages=kwargs.get("messages", None),+ input=kwargs.get("input", None),specific_deployment=kwargs.pop("specific_deployment", None),request_kwargs=kwargs,)@@ -10002,11 +10004,44 @@ class Router:client = self.cache.get_cache(key=cache_key, parent_otel_span=parent_otel_span)return client+ def _count_pre_call_check_tokens(+ self,+ messages: list[dict[str, str]] | None,+ input: str | list | None,+ instructions: str | None = None,+ ) -> int:+ """+ Count input tokens for context-window pre-call checks.++ Chat Completions send `messages`; the Responses API sends `input` (a string or+ a list of Responses input items) plus an optional `instructions` system prompt.+ The Responses payload is normalized to chat messages via the shared+ LiteLLMCompletionResponsesConfig transform so the same token_counter path covers+ both API surfaces and `instructions` tokens are included in the count.+ """+ if messages is not None:+ return litellm.token_counter(messages=messages)+ if input is not None:+ from openai.types.responses.response_create_params import ResponseInputParam++ from litellm.responses.litellm_completion_transformation.transformation import (+ LiteLLMCompletionResponsesConfig,+ )++ typed_input = cast(str | ResponseInputParam, input) # cast-ok: str | list matches transform input+ input_messages = LiteLLMCompletionResponsesConfig.transform_responses_api_input_to_messages(+ input=typed_input,+ responses_api_request={"instructions": instructions} if instructions is not None else {},+ )+ return litellm.token_counter(messages=cast(list, input_messages)) # cast-ok: transformed chat messages+ raise ValueError("Either messages or input must be provided to count tokens")+def _pre_call_checks(self,model: str,healthy_deployments: List,- messages: List[Dict[str, str]],+ messages: list[dict[str, str]] | None = None,+ input: str | list | None = None,request_kwargs: Optional[dict] = None,):"""@@ -10036,6 +10071,10 @@ class Router:_rate_limit_error = Falseparent_otel_span = _get_parent_otel_span_from_kwargs(request_kwargs)+ raw_instructions = request_kwargs.get("instructions") if request_kwargs else None+ instructions = raw_instructions if isinstance(raw_instructions, str) else None+ has_countable_input = messages is not None or input is not None+## get model group RPM ##dt = get_utc_datetime()current_minute = dt.strftime("%H-%M")@@ -10058,10 +10097,12 @@ class Router:_deployment_model = base_model or _litellm_params.get("model", None)max_input_tokens = model_info.get("max_input_tokens") if isinstance(model_info, dict) else None- if isinstance(max_input_tokens, int):+ if isinstance(max_input_tokens, int) and has_countable_input:if input_tokens is None:try:- input_tokens = litellm.token_counter(messages=messages)+ input_tokens = self._count_pre_call_check_tokens(+ messages=messages, input=input, instructions=instructions+ )except Exception as e:verbose_router_logger.error("litellm.router.py::_pre_call_checks: failed to count tokens. Returning initial list of deployments. Got - {}".format(@@ -10526,11 +10567,12 @@ class Router:parent_otel_span=parent_otel_span,)- if self.enable_pre_call_checks and messages is not None:+ if self.enable_pre_call_checks and (messages is not None or input is not None):healthy_deployments = self._pre_call_checks(model=model,healthy_deployments=cast(List[Dict], healthy_deployments),messages=messages,+ input=input,request_kwargs=request_kwargs,)# check if user wants to do tag based routing@@ -11041,11 +11083,12 @@ class Router:healthy_deployments = self._filter_blocked_deployments(healthy_deployments)# filter pre-call checks- if self.enable_pre_call_checks and messages is not None:+ if self.enable_pre_call_checks and (messages is not None or input is not None):healthy_deployments = self._pre_call_checks(model=model,healthy_deployments=healthy_deployments,messages=messages,+ input=input,request_kwargs=request_kwargs,)@@ -11195,11 +11238,12 @@ class Router:pass_through_deployments = self._filter_blocked_deployments(pass_through_deployments)# 5. Apply pre-call checks (if enabled)- if self.enable_pre_call_checks and messages is not None:+ if self.enable_pre_call_checks and (messages is not None or input is not None):pass_through_deployments = self._pre_call_checks(model=model,healthy_deployments=pass_through_deployments,messages=messages,+ input=input,request_kwargs=request_kwargs,)diff --git a/tests/test_litellm/test_router.py b/tests/test_litellm/test_router.pyindex 55c09e6cac4..76a6e3c1bbe 100644--- a/tests/test_litellm/test_router.py+++ b/tests/test_litellm/test_router.py@@ -2864,6 +2864,185 @@ def test_pre_call_checks_counts_once_and_filters_on_max_input_tokens(monkeypatchassert calls == [1]+def test_pre_call_checks_counts_tokens_from_responses_input_string(monkeypatch):+ """+ Responses API calls pass `input` (str) instead of `messages`. Context-window+ checks must count tokens from `input` and filter deployments over the limit. Uses+ the real token_counter so the transform + counting path is a true regression guard.+ """+ router = litellm.Router(+ model_list=[+ {"model_name": "m", "litellm_params": {"model": "gpt-3.5-turbo"}},+ ],+ enable_pre_call_checks=True,+ )+ monkeypatch.setattr(+ router, "get_router_model_info", lambda **kwargs: {"max_input_tokens": 1}+ )++ deployments = [+ {"litellm_params": {"model": "gpt-3.5-turbo"}, "model_info": {"id": "d1"}},+ ]+ with pytest.raises(litellm.ContextWindowExceededError):+ router._pre_call_checks(+ model="m",+ healthy_deployments=deployments,+ input="a very long prompt that exceeds the tiny context window",+ )+++def test_pre_call_checks_counts_tokens_from_responses_input_list(monkeypatch):+ """+ Responses API `input` can be a list of input items. It must be normalized to+ chat messages and counted so oversized requests are filtered out. Uses the real+ token_counter (no mock) so the transform + counting path is a true regression guard.+ """+ router = litellm.Router(+ model_list=[+ {"model_name": "m", "litellm_params": {"model": "gpt-3.5-turbo"}},+ ],+ enable_pre_call_checks=True,+ )+ monkeypatch.setattr(+ router, "get_router_model_info", lambda **kwargs: {"max_input_tokens": 1}+ )++ deployments = [+ {"litellm_params": {"model": "gpt-3.5-turbo"}, "model_info": {"id": "d1"}},+ ]+ with pytest.raises(litellm.ContextWindowExceededError):+ router._pre_call_checks(+ model="m",+ healthy_deployments=deployments,+ input=[+ {"role": "user", "content": "count these tokens against the one token limit please"},+ ],+ )+++def test_pre_call_checks_counts_responses_instructions_tokens(monkeypatch):+ """+ Responses API `instructions` become a system message the model receives, so their+ tokens must be counted too. A request whose `input` alone fits under the limit but+ whose `input` + `instructions` exceeds it must be filtered (regression for the+ context-window check under-filtering when instructions were ignored).+ """+ router = litellm.Router(+ model_list=[+ {"model_name": "m", "litellm_params": {"model": "gpt-3.5-turbo"}},+ ],+ enable_pre_call_checks=True,+ )++ deployments = [+ {"litellm_params": {"model": "gpt-3.5-turbo"}, "model_info": {"id": "d1"}},+ ]++ short_input = "hi"+ long_instructions = "you are a helpful assistant. " * 20++ input_only_tokens = router._count_pre_call_check_tokens(messages=None, input=short_input)+ with_instructions_tokens = router._count_pre_call_check_tokens(+ messages=None, input=short_input, instructions=long_instructions+ )+ assert with_instructions_tokens > input_only_tokens++ monkeypatch.setattr(+ router, "get_router_model_info", lambda **kwargs: {"max_input_tokens": input_only_tokens}+ )+ with pytest.raises(litellm.ContextWindowExceededError):+ router._pre_call_checks(+ model="m",+ healthy_deployments=deployments,+ input=short_input,+ request_kwargs={"instructions": long_instructions},+ )+++def test_count_pre_call_check_tokens_across_api_surfaces():+ """+ _count_pre_call_check_tokens must count tokens from chat `messages`, a Responses+ API string `input`, and a Responses API list `input`, and raise when given neither.+ """+ router = litellm.Router(+ model_list=[+ {"model_name": "m", "litellm_params": {"model": "gpt-3.5-turbo"}},+ ],+ )++ messages_tokens = router._count_pre_call_check_tokens(+ messages=[{"role": "user", "content": "hello world"}], input=None+ )+ string_input_tokens = router._count_pre_call_check_tokens(messages=None, input="hello world")+ list_input_tokens = router._count_pre_call_check_tokens(+ messages=None, input=[{"role": "user", "content": "hello world"}]+ )++ assert messages_tokens > 0+ assert string_input_tokens > 0+ assert list_input_tokens > 0++ with pytest.raises(ValueError):+ router._count_pre_call_check_tokens(messages=None, input=None)+++def test_pre_call_checks_no_messages_or_input_does_not_crash(monkeypatch):+ """+ When neither messages nor input is provided (e.g. endpoints without prompt text),+ token counting is skipped gracefully and all deployments are returned.+ """+ router = litellm.Router(+ model_list=[+ {"model_name": "m", "litellm_params": {"model": "gpt-3.5-turbo"}},+ ],+ enable_pre_call_checks=True,+ )+ monkeypatch.setattr(+ router, "get_router_model_info", lambda **kwargs: {"max_input_tokens": 5}+ )++ counted: list[dict] = []+ original = router._count_pre_call_check_tokens+ monkeypatch.setattr(+ router,+ "_count_pre_call_check_tokens",+ lambda **kwargs: counted.append(kwargs) or original(**kwargs),+ )++ deployments = [+ {"litellm_params": {"model": "gpt-3.5-turbo"}, "model_info": {"id": "d1"}},+ ]+ result = router._pre_call_checks(model="m", healthy_deployments=deployments)+ assert len(result) == 1+ assert counted == [] # token counting skipped entirely, so no misleading error is logged+++async def test_aresponses_enforces_context_window_pre_call_check():+ """+ End-to-end router regression: a Responses API call whose `input` exceeds the+ deployment's max_input_tokens must be filtered by the pre-call check, raising+ ContextWindowExceededError instead of being silently routed. This guards the+ wiring that forwards `input` from the generic-call path into deployment selection+ (the deployment uses mock_response, so the check must trip before any real call).+ """+ router = litellm.Router(+ model_list=[+ {+ "model_name": "small-ctx",+ "litellm_params": {"model": "gpt-3.5-turbo", "mock_response": "hi"},+ "model_info": {"max_input_tokens": 5},+ }+ ],+ enable_pre_call_checks=True,+ )+ with pytest.raises(litellm.ContextWindowExceededError):+ await router.aresponses(+ model="small-ctx",+ input="this responses input is definitely much longer than five tokens for sure",+ )++def test_get_deployment_model_info_base_model_flow():"""Test that get_deployment_model_info correctly handles the base model flow"""from unittest.mock import patch