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(token_counter): stop large token counts from blocking the proxy event loop (#37697)

devin-ai-integration[bot]8c42d8b97bae
diff --git a/litellm/constants.py b/litellm/constants.py
index cf77e7c55db..774df63de17 100644
--- a/litellm/constants.py
+++ b/litellm/constants.py
@@ -3,7 +3,7 @@ import sys
from types import MappingProxyType
from typing import Final, Literal
-from litellm.litellm_core_utils.env_utils import get_env_int, get_env_int_or_none
+from litellm.litellm_core_utils.env_utils import get_env_int, get_env_int_in_range, get_env_int_or_none
DEFAULT_HEALTH_CHECK_PROMPT: Final = str(os.getenv("DEFAULT_HEALTH_CHECK_PROMPT", "test from litellm"))
AZURE_DEFAULT_RESPONSES_API_VERSION: Final = str(os.getenv("AZURE_DEFAULT_RESPONSES_API_VERSION", "preview"))
@@ -325,6 +325,17 @@ DEFAULT_MOCK_RESPONSE_PROMPT_TOKEN_COUNT: Final = int(os.getenv("DEFAULT_MOCK_RE
DEFAULT_MOCK_RESPONSE_COMPLETION_TOKEN_COUNT: Final = int(os.getenv("DEFAULT_MOCK_RESPONSE_COMPLETION_TOKEN_COUNT", 20))
MAX_SHORT_SIDE_FOR_IMAGE_HIGH_RES: Final = int(os.getenv("MAX_SHORT_SIDE_FOR_IMAGE_HIGH_RES", 768))
MAX_LONG_SIDE_FOR_IMAGE_HIGH_RES: Final = int(os.getenv("MAX_LONG_SIDE_FOR_IMAGE_HIGH_RES", 2000))
+# tiktoken's BPE merge loop is quadratic in the length of a single regex piece, so a long run of one
+# repeated character (dot leaders, whitespace, zero-padded base64) can take minutes on a multi-MB payload.
+# Encoding in chunks makes the cost linear, at a drift of at most ~1 token per chunk boundary. The upper
+# bound keeps a misconfigured chunk size from restoring the quadratic cost this exists to remove.
+TIKTOKEN_ENCODE_MAX_CHUNK_SIZE_CHARS: Final = 4096
+TIKTOKEN_ENCODE_CHUNK_SIZE_CHARS: Final = get_env_int_in_range(
+ "TIKTOKEN_ENCODE_CHUNK_SIZE_CHARS",
+ default=1024,
+ minimum=1,
+ maximum=TIKTOKEN_ENCODE_MAX_CHUNK_SIZE_CHARS,
+)
MAX_TILE_WIDTH: Final = int(os.getenv("MAX_TILE_WIDTH", 512))
MAX_TILE_HEIGHT: Final = int(os.getenv("MAX_TILE_HEIGHT", 512))
OPENAI_FILE_SEARCH_COST_PER_1K_CALLS: Final = float(os.getenv("OPENAI_FILE_SEARCH_COST_PER_1K_CALLS", 2.5 / 1000))
diff --git a/litellm/litellm_core_utils/env_utils.py b/litellm/litellm_core_utils/env_utils.py
index af0520eaf31..d641884b4cd 100644
--- a/litellm/litellm_core_utils/env_utils.py
+++ b/litellm/litellm_core_utils/env_utils.py
@@ -2,6 +2,7 @@
Utility helpers for reading and parsing environment variables.
"""
+import logging
import os
from typing import Final
@@ -22,6 +23,26 @@ def get_env_int(env_var: str, default: int) -> int:
return default
+def get_env_int_in_range(env_var: str, default: int, minimum: int, maximum: int) -> int:
+ """Parse an environment variable as an integer constrained to ``[minimum, maximum]``.
+
+ Values outside the range fall back to the default and warn, so a misconfigured knob can
+ neither crash the caller nor silently change the meaning of what it computes.
+ """
+ value: Final = get_env_int(env_var, default)
+ if minimum <= value <= maximum:
+ return value
+ logging.getLogger("LiteLLM").warning(
+ "%s=%s is outside the supported range [%s, %s]. Falling back to %s.",
+ env_var,
+ value,
+ minimum,
+ maximum,
+ default,
+ )
+ return default
+
+
def get_env_int_or_none(env_var: str) -> int | None:
"""Parse an environment variable as an integer, returning None when it is unset or unusable.
diff --git a/litellm/litellm_core_utils/token_counter.py b/litellm/litellm_core_utils/token_counter.py
index 17f3dea72ec..858b078d626 100644
--- a/litellm/litellm_core_utils/token_counter.py
+++ b/litellm/litellm_core_utils/token_counter.py
@@ -19,6 +19,7 @@ from litellm.constants import (
MAX_SHORT_SIDE_FOR_IMAGE_HIGH_RES,
MAX_TILE_HEIGHT,
MAX_TILE_WIDTH,
+ TIKTOKEN_ENCODE_CHUNK_SIZE_CHARS,
)
from litellm.litellm_core_utils.default_encoding import encoding as default_encoding
from litellm.litellm_core_utils.url_utils import safe_get
@@ -305,6 +306,16 @@ Type for a function that counts tokens in a string.
"""
+def _get_tiktoken_count_function(
+ encode_length: Callable[[str], int],
+ chunk_size: int = TIKTOKEN_ENCODE_CHUNK_SIZE_CHARS,
+) -> TokenCounterFunction:
+ def count_tokens(text: str) -> int:
+ return sum(encode_length(text[start : start + chunk_size]) for start in range(0, len(text), chunk_size))
+
+ return count_tokens
+
+
class _MessageCountParams:
"""
A class to hold the parameters for counting tokens in messages.
@@ -531,6 +542,7 @@ def _get_count_function(
enc: Final = tokenizer_json["tokenizer"].encode(text)
return len(enc.ids)
+ return count_tokens
elif tokenizer_json["type"] == "openai_tokenizer":
model_to_use: Final = _fix_model_name(model)
try:
@@ -542,17 +554,18 @@ def _get_count_function(
print_verbose("Warning: model not found. Using cl100k_base encoding.")
encoding = tiktoken.get_encoding("cl100k_base")
- def count_tokens(text: str) -> int:
+ def encode_length(text: str) -> int:
return len(encoding.encode(text, disallowed_special=()))
+ return _get_tiktoken_count_function(encode_length)
else:
raise ValueError("Unsupported tokenizer type")
else:
- def count_tokens(text: str) -> int:
+ def encode_length(text: str) -> int:
return len(default_encoding.encode(text, disallowed_special=()))
- return count_tokens
+ return _get_tiktoken_count_function(encode_length)
def _fix_model_name(model: str) -> str:
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index 711775ee0cf..4b97cade7f0 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -253,6 +253,7 @@ from litellm.exceptions import RejectedRequestError
from litellm.integrations.custom_guardrail import ModifyResponseException
from litellm.integrations.custom_logger import CustomLogger
from litellm.integrations.SlackAlerting.slack_alerting import SlackAlerting
+from litellm.litellm_core_utils.asyncify import asyncify
from litellm.litellm_core_utils.core_helpers import (
_get_parent_otel_span_from_kwargs,
get_litellm_metadata_from_kwargs,
@@ -11925,8 +11926,6 @@ async def token_counter(request: TokenCountRequest, call_endpoint: bool = False)
Returns:
TokenCountResponse
"""
- from litellm import token_counter
-
global llm_router
prompt: Final = request.prompt
@@ -12010,7 +12009,7 @@ async def token_counter(request: TokenCountRequest, call_endpoint: bool = False)
_tokenizer_used: Final = litellm.utils._select_tokenizer(model=model_to_use, custom_tokenizer=custom_tokenizer)
tokenizer_used: Final = str(_tokenizer_used["type"])
- total_tokens: Final = token_counter(
+ total_tokens: Final = await asyncify(litellm.token_counter)(
model=model_to_use,
text=prompt,
messages=messages,
diff --git a/litellm/router.py b/litellm/router.py
index 1521c798677..e9eeab53934 100644
--- a/litellm/router.py
+++ b/litellm/router.py
@@ -52,7 +52,7 @@ from litellm.constants import (
SESSION_DEPLOYMENT_AFFINITY_TTL_METADATA_KEY,
)
from litellm.integrations.custom_logger import CustomLogger
-from litellm.litellm_core_utils.asyncify import run_async_function
+from litellm.litellm_core_utils.asyncify import asyncify, run_async_function
from litellm.litellm_core_utils.core_helpers import (
_get_parent_otel_span_from_kwargs,
coerce_token_limit,
@@ -10575,6 +10575,64 @@ class Router:
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 _deployment_max_input_tokens(self, model: str, deployment: Mapping[str, object]) -> int | None:
+ """The deployment's declared context window, or None when it declares none or cannot be resolved."""
+ try:
+ model_info: Final = self.get_router_model_info(
+ deployment=cast(dict, deployment), # cast-ok: router deployments are plain dicts
+ received_model_name=model,
+ )
+ except Exception as e: # noqa: BLE001 # best-effort: an unmappable deployment must not hide the others
+ verbose_router_logger.debug(
+ "litellm.router.py::_deployment_max_input_tokens: skipping deployment. Got - %s", e
+ )
+ return None
+ max_input_tokens: Final = model_info.get("max_input_tokens")
+ return max_input_tokens if isinstance(max_input_tokens, int) else None
+
+ def _pre_call_checks_need_token_count(
+ self, model: str, healthy_deployments: Sequence[Mapping[str, object]]
+ ) -> bool:
+ """Whether any healthy deployment declares a context window that a token count could exceed.
+
+ Resolves each deployment the way ``_pre_call_checks`` does, so one unmappable deployment
+ cannot hide a later one that does declare a limit.
+ """
+ return any(
+ self._deployment_max_input_tokens(model, deployment) is not None for deployment in healthy_deployments
+ )
+
+ async def _acount_pre_call_check_tokens(
+ self,
+ model: str,
+ healthy_deployments: Sequence[Mapping[str, object]],
+ messages: Sequence[Mapping[str, str]] | None,
+ input: str | Sequence[object] | None,
+ request_kwargs: Mapping[str, object] | None,
+ ) -> int | None:
+ """Count input tokens off the event loop, so a multi-MB prompt cannot stall the proxy.
+
+ Returns None when no deployment limits its context window, and when counting fails. The
+ caller pairs this with ``skip_inline_token_count`` so neither case puts the count back on
+ the loop: a failed count leaves the deployments unfiltered, exactly as before.
+ """
+ if messages is None and input is None:
+ return None
+ raw_instructions: Final = request_kwargs.get("instructions") if request_kwargs else None
+ try:
+ if not self._pre_call_checks_need_token_count(model, healthy_deployments):
+ return None
+ return await asyncify(self._count_pre_call_check_tokens)(
+ messages=cast(list[dict[str, str]] | None, messages), # cast-ok: forwarded to the sync counter
+ input=cast(str | list | None, input), # cast-ok: forwarded to the sync counter
+ instructions=raw_instructions if isinstance(raw_instructions, str) else None,
+ )
+ except Exception as e: # noqa: BLE001 # best-effort: an uncountable prompt must not fail the request
+ verbose_router_logger.error(
+ "litellm.router.py::_acount_pre_call_check_tokens: failed to count tokens. Got - %s", e
+ )
+ return None
+
def _pre_call_checks(
self,
model: str,
@@ -10582,6 +10640,8 @@ class Router:
messages: list[dict[str, str]] | None = None,
input: str | list | None = None,
request_kwargs: dict | None = None,
+ input_token_count: int | None = None,
+ skip_inline_token_count: bool = False,
):
"""
Filter out model in model group, if:
@@ -10603,7 +10663,9 @@ class Router:
# Token counting (tiktoken) is the dominant on-loop cost for large prompts.
# Only count when a deployment actually declares max_input_tokens, and count
# at most once; for model groups with no context-window limit it is skipped.
- input_tokens: int | None = None
+ # Async callers pass the count in, already computed off the event loop, and set
+ # skip_inline_token_count so a failed off-loop count is not retried back on the loop.
+ input_tokens: int | None = input_token_count
_context_window_error = False
_potential_error_str = ""
@@ -10638,6 +10700,8 @@ class Router:
max_input_tokens = model_info.get("max_input_tokens") if isinstance(model_info, dict) else None
if isinstance(max_input_tokens, int) and has_countable_input:
if input_tokens is None:
+ if skip_inline_token_count:
+ return _returned_deployments
try:
input_tokens = self._count_pre_call_check_tokens(
messages=messages, input=input, instructions=instructions
@@ -11120,12 +11184,21 @@ class Router:
)
if self.enable_pre_call_checks and (messages is not None or input is not None):
+ deployments_to_check: Final = cast(list[dict], healthy_deployments)
healthy_deployments = self._pre_call_checks(
model=model,
- healthy_deployments=cast(list[dict], healthy_deployments),
+ healthy_deployments=deployments_to_check,
messages=messages,
input=input,
request_kwargs=request_kwargs,
+ input_token_count=await self._acount_pre_call_check_tokens(
+ model=model,
+ healthy_deployments=deployments_to_check,
+ messages=messages,
+ input=input,
+ request_kwargs=request_kwargs,
+ ),
+ skip_inline_token_count=True,
)
# check if user wants to do tag based routing
healthy_deployments = await get_deployments_for_tag(
diff --git a/tests/test_litellm/litellm_core_utils/test_token_counter.py b/tests/test_litellm/litellm_core_utils/test_token_counter.py
index 74aa5fa823a..3c33ee13c3f 100644
--- a/tests/test_litellm/litellm_core_utils/test_token_counter.py
+++ b/tests/test_litellm/litellm_core_utils/test_token_counter.py
@@ -1,5 +1,6 @@
#### What this tests ####
# This tests litellm.token_counter.token_counter() function
+import importlib
import os
import sys
import time
@@ -7,6 +8,7 @@ import traceback
from unittest.mock import MagicMock
import pytest
+import tiktoken
sys.path.insert(
0, os.path.abspath("../../..")
@@ -16,6 +18,8 @@ from unittest.mock import AsyncMock, MagicMock, patch
import litellm
from litellm import create_pretrained_tokenizer, decode, encode, get_modified_max_tokens
from litellm import token_counter as token_counter_old
+import litellm.constants
+from litellm.litellm_core_utils.token_counter import _get_tiktoken_count_function
from litellm.litellm_core_utils.token_counter import token_counter as token_counter_new
from tests.large_text import text
from tests.test_litellm.litellm_core_utils.messages_with_counts import (
@@ -54,6 +58,73 @@ def test_token_counter_basic():
)
+def test_token_counter_large_repeated_text_is_fast():
+ messages = [{"role": "user", "content": [{"type": "text", "text": "A" * 1024 * 1024}]}]
+
+ start_time = time.perf_counter()
+ tokens = token_counter_new(model="us.anthropic.claude-sonnet-4-6", messages=messages)
+ elapsed = time.perf_counter() - start_time
+
+ assert elapsed < 2, f"Token counting took too long: {elapsed:.2f}s"
+ assert tokens > 0
+
+
+ "text",
+ [
+ "Short text",
+ "This is a normal message with punctuation, numbers, and a few words.",
+ ],
+)
+def test_token_counter_short_text_matches_tiktoken(text):
+ encoding = tiktoken.get_encoding("cl100k_base")
+ expected = len(encoding.encode(text, disallowed_special=()))
+
+ assert token_counter_new(model="us.anthropic.claude-sonnet-4-6", text=text) == expected
+
+
+def test_token_counter_text_over_chunk_boundary_stays_close_to_tiktoken():
+ text = ("The quick brown fox jumps over the lazy dog. " * 30)[:1025]
+ encoding = tiktoken.get_encoding("cl100k_base")
+ expected = len(encoding.encode(text, disallowed_special=()))
+
+ actual = token_counter_new(model="us.anthropic.claude-sonnet-4-6", text=text)
+
+ assert abs(actual - expected) <= 4
+
+
+ "configured",
+ ["0", "-1", "-1024", "not-an-int", "", " ", "999999999", "inf", "1e9"],
+)
+def test_invalid_chunk_size_config_stays_usable(monkeypatch, configured):
+ """A misconfigured chunk size must not raise, count zero, or restore the quadratic encode cost."""
+ monkeypatch.setenv("TIKTOKEN_ENCODE_CHUNK_SIZE_CHARS", configured)
+ try:
+ reloaded = importlib.reload(litellm.constants)
+ chunk_size = reloaded.TIKTOKEN_ENCODE_CHUNK_SIZE_CHARS
+ assert 1 <= chunk_size <= reloaded.TIKTOKEN_ENCODE_MAX_CHUNK_SIZE_CHARS
+
+ encoding = tiktoken.get_encoding("cl100k_base")
+ count_tokens = _get_tiktoken_count_function(
+ lambda text: len(encoding.encode(text, disallowed_special=())),
+ chunk_size=chunk_size,
+ )
+ assert count_tokens("The quick brown fox jumps over the lazy dog. " * 40) > 0
+ finally:
+ monkeypatch.delenv("TIKTOKEN_ENCODE_CHUNK_SIZE_CHARS")
+ importlib.reload(litellm.constants)
+
+
+def test_valid_chunk_size_config_is_honoured(monkeypatch):
+ monkeypatch.setenv("TIKTOKEN_ENCODE_CHUNK_SIZE_CHARS", "2048")
+ try:
+ assert importlib.reload(litellm.constants).TIKTOKEN_ENCODE_CHUNK_SIZE_CHARS == 2048
+ finally:
+ monkeypatch.delenv("TIKTOKEN_ENCODE_CHUNK_SIZE_CHARS")
+ importlib.reload(litellm.constants)
+
+
def test_token_counter_with_prefix():
messages = [
{"role": "user", "content": "Who won the world cup in 2022?"},
diff --git a/tests/test_litellm/proxy/proxy_server/test_routes_utils.py b/tests/test_litellm/proxy/proxy_server/test_routes_utils.py
index c6070437d35..f39192b171b 100644
--- a/tests/test_litellm/proxy/proxy_server/test_routes_utils.py
+++ b/tests/test_litellm/proxy/proxy_server/test_routes_utils.py
@@ -8,6 +8,7 @@ Pins (PR2):
from __future__ import annotations
+import asyncio
from unittest.mock import AsyncMock, MagicMock
import pytest
@@ -56,6 +57,31 @@ def test_token_counter_happy_path(client, auth_as, patched_token_counter):
}
+def test_token_counter_counts_off_the_event_loop(client, auth_as, patched_token_counter, monkeypatch):
+ """
+ A large prompt must not stall the proxy: the count runs in a worker thread, where there
+ is no running event loop, rather than on the loop serving other requests.
+ """
+ counted_off_loop = []
+
+ def recording_counter(**kwargs):
+ try:
+ asyncio.get_running_loop()
+ counted_off_loop.append(False)
+ except RuntimeError:
+ counted_off_loop.append(True)
+ return 7
+
+ monkeypatch.setattr(litellm, "token_counter", recording_counter)
+
+ with auth_as():
+ response = client.post("/utils/token_counter", json={"model": "gpt-4", "prompt": "Hi there"})
+
+ assert response.status_code == 200
+ assert response.json()["total_tokens"] == 7
+ assert counted_off_loop == [True]
+
+
def test_token_counter_missing_input_returns_400(
client, auth_as, patched_token_counter
):
diff --git a/tests/test_litellm/test_router.py b/tests/test_litellm/test_router.py
index 65debae9a16..4a06a5dfb2e 100644
--- a/tests/test_litellm/test_router.py
+++ b/tests/test_litellm/test_router.py
@@ -4,6 +4,7 @@ import json
import logging
import os
import sys
+import threading
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -3344,6 +3345,277 @@ def test_pre_call_checks_counts_once_and_filters_on_max_input_tokens(monkeypatch
assert calls == [1]
+def test_pre_call_checks_uses_precounted_tokens(monkeypatch):
+ """
+ An async caller counts off the event loop and passes the result in. _pre_call_checks
+ must filter on that count instead of re-counting on the loop.
+ """
+ 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}
+ )
+
+ calls = []
+ monkeypatch.setattr(
+ litellm, "token_counter", lambda *a, **k: calls.append(1) or 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,
+ messages=[{"role": "user", "content": "hi"}],
+ input_token_count=1000,
+ )
+
+ assert calls == []
+
+
+async def test_async_get_healthy_deployments_counts_tokens_off_the_event_loop(monkeypatch):
+ """
+ The async deployment path must hand _pre_call_checks a count taken in a worker thread,
+ so a multi-MB prompt never blocks the proxy during deployment selection.
+ """
+ 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_000_000}
+ )
+
+ counting_threads = []
+ monkeypatch.setattr(
+ litellm,
+ "token_counter",
+ lambda *a, **k: counting_threads.append(threading.current_thread()) or 42,
+ )
+
+ counts_passed_in = []
+ original_pre_call_checks = router._pre_call_checks
+
+ def spy(**kwargs):
+ counts_passed_in.append(kwargs.get("input_token_count"))
+ return original_pre_call_checks(**kwargs)
+
+ monkeypatch.setattr(router, "_pre_call_checks", spy)
+
+ result = await router.async_get_healthy_deployments(
+ model="m",
+ request_kwargs={},
+ messages=[{"role": "user", "content": "hi"}],
+ input=None,
+ specific_deployment=False,
+ parent_otel_span=None,
+ )
+
+ assert len(result) == 1
+ assert counts_passed_in == [42]
+ assert len(counting_threads) == 1
+ assert counting_threads[0] is not threading.current_thread()
+
+
+ "model_info,expected",
+ [
+ ({"max_input_tokens": 100}, True),
+ ({"max_input_tokens": None}, False),
+ ({}, False),
+ ],
+)
+def test_pre_call_checks_need_token_count(monkeypatch, model_info, expected):
+ """Only a deployment that declares an integer context window makes a token count worth taking."""
+ 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: model_info)
+
+ deployments = [
+ {"litellm_params": {"model": "gpt-3.5-turbo"}, "model_info": {"id": "d1"}},
+ ]
+ assert router._pre_call_checks_need_token_count("m", deployments) is expected
+
+
+def test_deployment_max_input_tokens_survives_an_unmappable_deployment(monkeypatch):
+ """
+ _pre_call_checks skips a deployment it cannot resolve and carries on. The off-loop
+ pre-count must do the same, or an unmapped first deployment hides the limit declared by
+ a later one and the count lands back on the event loop.
+ """
+ router = litellm.Router(
+ model_list=[
+ {"model_name": "m", "litellm_params": {"model": "gpt-3.5-turbo"}},
+ ],
+ enable_pre_call_checks=True,
+ )
+
+ def flaky_model_info(deployment, received_model_name, id=None):
+ if deployment["model_info"]["id"] == "unmapped":
+ raise ValueError("This model isn't mapped yet.")
+ return {"max_input_tokens": 100}
+
+ monkeypatch.setattr(router, "get_router_model_info", flaky_model_info)
+
+ unmapped = {"litellm_params": {"model": "gpt-3.5-turbo"}, "model_info": {"id": "unmapped"}}
+ mapped = {"litellm_params": {"model": "gpt-3.5-turbo"}, "model_info": {"id": "mapped"}}
+
+ assert router._deployment_max_input_tokens("m", unmapped) is None
+ assert router._deployment_max_input_tokens("m", mapped) == 100
+ assert router._pre_call_checks_need_token_count("m", [unmapped, mapped]) is True
+
+
+def test_pre_call_checks_does_not_recount_inline_after_an_off_loop_failure(monkeypatch):
+ """
+ When the off-loop count failed there is nothing left to filter on, so _pre_call_checks must
+ return the deployments unfiltered rather than repeating the count on the event loop.
+ """
+ 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}
+ )
+
+ calls = []
+ monkeypatch.setattr(
+ litellm, "token_counter", lambda *a, **k: calls.append(1) or 1000
+ )
+
+ deployments = [
+ {"litellm_params": {"model": "gpt-3.5-turbo"}, "model_info": {"id": "d1"}},
+ ]
+ result = router._pre_call_checks(
+ model="m",
+ healthy_deployments=deployments,
+ messages=[{"role": "user", "content": "hi"}],
+ input_token_count=None,
+ skip_inline_token_count=True,
+ )
+
+ assert calls == []
+ assert len(result) == 1
+
+
+async def test_async_get_healthy_deployments_never_recounts_on_the_loop(monkeypatch):
+ """
+ An off-loop count that raises must not send the same work back onto the event loop through
+ _pre_call_checks' inline fallback.
+ """
+ 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}
+ )
+
+ counting_threads = []
+
+ def exploding_counter(*args, **kwargs):
+ counting_threads.append(threading.current_thread())
+ raise ValueError("Invalid content item type: image")
+
+ monkeypatch.setattr(litellm, "token_counter", exploding_counter)
+
+ result = await router.async_get_healthy_deployments(
+ model="m",
+ request_kwargs={},
+ messages=[{"role": "user", "content": "hi"}],
+ input=None,
+ specific_deployment=False,
+ parent_otel_span=None,
+ )
+
+ assert len(result) == 1
+ assert len(counting_threads) == 1
+ assert counting_threads[0] is not threading.current_thread()
+
+
+async def test_acount_pre_call_check_tokens_leaves_the_event_loop_free(monkeypatch):
+ """
+ A multi-MB prompt must not stall the proxy: a competing coroutine has to get
+ scheduled while the router's context-window count is in flight.
+ """
+ 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}
+ )
+
+ deployments = [
+ {"litellm_params": {"model": "gpt-3.5-turbo"}, "model_info": {"id": "d1"}},
+ ]
+ ran = []
+
+ async def competitor():
+ ran.append("competitor")
+
+ task = asyncio.create_task(competitor())
+ count = await router._acount_pre_call_check_tokens(
+ model="m",
+ healthy_deployments=deployments,
+ messages=[{"role": "user", "content": "A" * 512 * 1024}],
+ input=None,
+ request_kwargs=None,
+ )
+ ran.append("count")
+ await task
+
+ assert count is not None and count > 0
+ assert ran == ["competitor", "count"]
+
+
+async def test_acount_pre_call_check_tokens_skips_without_max_input_tokens(monkeypatch):
+ """No deployment limits its context window, so there is nothing to count."""
+ 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: {})
+
+ calls = []
+ monkeypatch.setattr(
+ litellm, "token_counter", lambda *a, **k: calls.append(1) or 1000
+ )
+
+ count = await router._acount_pre_call_check_tokens(
+ model="m",
+ healthy_deployments=[
+ {"litellm_params": {"model": "gpt-3.5-turbo"}, "model_info": {"id": "d1"}},
+ ],
+ messages=[{"role": "user", "content": "hi"}],
+ input=None,
+ request_kwargs=None,
+ )
+
+ assert count is None
+ assert calls == []
+
+
def test_pre_call_checks_counts_tokens_from_responses_input_string(monkeypatch):
"""
Responses API calls pass `input` (str) instead of `messages`. Context-window