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
perf(budget_reservation): tokenize each request once, off the event loop for large prompts (#37683)
devin-ai-integration[bot]ebdbb317b37a
diff --git a/litellm/proxy/spend_tracking/budget_reservation.py b/litellm/proxy/spend_tracking/budget_reservation.pyindex 17074ec967b..ce6c9330620 100644--- a/litellm/proxy/spend_tracking/budget_reservation.py+++ b/litellm/proxy/spend_tracking/budget_reservation.py@@ -5,6 +5,7 @@ import jsonfrom collections.abc import Mapping, Sequencefrom dataclasses import dataclassfrom datetime import datetime, timedelta, timezone+from types import MappingProxyTypefrom typing import Any, Final, NoReturn, castfrom fastapi import HTTPException, status@@ -182,11 +183,18 @@ async def reserve_budget_for_request(if not counters:return None+ input_token_counts: Final = await count_request_input_tokens(+ request_body=request_body,+ route=route,+ llm_router=llm_router,+ )+current_spend_by_counter_key: Final[dict[str, float]] = {}reservation_cost = estimate_request_max_cost(request_body=request_body,route=route,llm_router=llm_router,+ input_token_counts=input_token_counts,)# estimate_request_max_cost still returns None when the model is unknown# to the cost map (no token-priced cost fields, e.g. image/audio routes).@@ -245,7 +253,12 @@ async def reserve_budget_for_request(if not applied_entries:return None- input_cost: Final = estimate_request_input_cost(request_body=request_body, route=route, llm_router=llm_router)+ input_cost: Final = estimate_request_input_cost(+ request_body=request_body,+ route=route,+ llm_router=llm_router,+ input_token_counts=input_token_counts,+ )return {"reserved_cost": reservation_cost,"entries": applied_entries,@@ -907,20 +920,17 @@ def estimate_request_max_cost(request_body: dict,route: str,llm_router: Router | None,+ input_token_counts: Mapping[str, int] | None = None,) -> float | None:- model: Final = get_model_from_request(request_body, route, llm_router=llm_router)- if model is None:- return None-- models: Final = [model] if isinstance(model, str) else modelestimates = [_estimate_request_max_cost_for_model(request_body=request_body,route=route,model=model_name,llm_router=llm_router,+ input_tokens=(input_token_counts or {}).get(model_name),)- for model_name in models+ for model_name in _get_request_models(request_body=request_body, route=route, llm_router=llm_router)]estimates = [estimate for estimate in estimates if estimate is not None]if not estimates:@@ -932,6 +942,7 @@ def estimate_request_input_cost(request_body: dict,route: str,llm_router: Router | None,+ input_token_counts: Mapping[str, int] | None = None,) -> float | None:"""Cost of the request's input tokens alone.@@ -940,19 +951,15 @@ def estimate_request_input_cost(cancelled in-flight request has already incurred. A cancelled reservation isreconciled to this instead of being refunded to zero."""- model: Final = get_model_from_request(request_body, route, llm_router=llm_router)- if model is None:- return None-- models: Final = [model] if isinstance(model, str) else modelestimates = [_estimate_request_input_cost_for_model(request_body=request_body,route=route,model=model_name,llm_router=llm_router,+ input_tokens=(input_token_counts or {}).get(model_name),)- for model_name in models+ for model_name in _get_request_models(request_body=request_body, route=route, llm_router=llm_router)]estimates = [estimate for estimate in estimates if estimate is not None]if not estimates:@@ -965,6 +972,7 @@ def _estimate_request_input_cost_for_model(route: str,model: str,llm_router: Router | None,+ input_tokens: int | None = None,) -> float | None:estimates: Final = [_input_cost_for_cost_info(@@ -972,6 +980,7 @@ def _estimate_request_input_cost_for_model(route=route,model=model,model_info=model_info,+ input_tokens=input_tokens,)for model_info in _get_model_cost_infos(model=model, llm_router=llm_router)]@@ -984,24 +993,26 @@ def _input_cost_for_cost_info(route: str,model: str,model_info: Mapping[str, object],+ input_tokens: int | None = None,) -> float | None:- input_tokens: Final = _estimate_input_tokens(+ estimated_input_tokens: Final = _estimate_input_tokens(request_body=request_body,route=route,model=model,model_info=model_info,+ input_tokens=input_tokens,)- if input_tokens is None:+ if estimated_input_tokens is None:return Nonetiered_pricing: Final = model_info.get("tiered_pricing")if isinstance(tiered_pricing, list) and tiered_pricing:- tier: Final = select_tier_for_input(tiered_pricing=tiered_pricing, input_tokens=input_tokens)+ tier: Final = select_tier_for_input(tiered_pricing=tiered_pricing, input_tokens=estimated_input_tokens)if tier is not None:- return input_tokens * tier_rate(tier, "input_cost_per_token")+ return estimated_input_tokens * tier_rate(tier, "input_cost_per_token")input_cost_per_token: Final = _to_float(model_info.get("input_cost_per_token"))if input_cost_per_token is None:return None- return input_tokens * input_cost_per_token+ return estimated_input_tokens * input_cost_per_tokendef _estimate_request_max_cost_for_model(@@ -1009,6 +1020,7 @@ def _estimate_request_max_cost_for_model(route: str,model: str,llm_router: Router | None,+ input_tokens: int | None = None,) -> float | None:estimates: Final = [_max_cost_for_cost_info(@@ -1016,6 +1028,7 @@ def _estimate_request_max_cost_for_model(route=route,model=model,model_info=model_info,+ input_tokens=input_tokens,)for model_info in _get_model_cost_infos(model=model, llm_router=llm_router)]@@ -1028,6 +1041,7 @@ def _max_cost_for_cost_info(route: str,model: str,model_info: Mapping[str, object],+ input_tokens: int | None = None,) -> float | None:image_cost: Final = _estimate_image_generation_cost(request_body=request_body,@@ -1036,30 +1050,31 @@ def _max_cost_for_cost_info(if image_cost is not None:return image_cost- input_tokens: Final = _estimate_input_tokens(+ estimated_input_tokens: Final = _estimate_input_tokens(request_body=request_body,route=route,model=model,model_info=model_info,+ input_tokens=input_tokens,)output_tokens: Final = _estimate_output_tokens(request_body=request_body,route=route,model_info=model_info,)- if input_tokens is None or output_tokens is None:+ if estimated_input_tokens is None or output_tokens is None:return Noneoutput_multiplier: Final = _get_output_multiplier(request_body=request_body)tiered_pricing: Final = model_info.get("tiered_pricing")if isinstance(tiered_pricing, list) and tiered_pricing:- tier: Final = select_tier_for_input(tiered_pricing=tiered_pricing, input_tokens=input_tokens)+ tier: Final = select_tier_for_input(tiered_pricing=tiered_pricing, input_tokens=estimated_input_tokens)if tier is not None:output_rate = max(tier_rate(tier, "output_cost_per_token"),tier_rate(tier, "output_cost_per_reasoning_token"),)- return (input_tokens * tier_rate(tier, "input_cost_per_token")) + (+ return (estimated_input_tokens * tier_rate(tier, "input_cost_per_token")) + (output_tokens * output_multiplier * output_rate)@@ -1068,8 +1083,8 @@ def _max_cost_for_cost_info(output_cost_per_reasoning_token: Final = _to_float(model_info.get("output_cost_per_reasoning_token"))cost = 0.0if input_cost_per_token is not None:- cost += input_tokens * input_cost_per_token- elif input_tokens > 0:+ cost += estimated_input_tokens * input_cost_per_token+ elif estimated_input_tokens > 0:return None# The reasoning-token share is unknown before the request runs, so reserve every@@ -1192,12 +1207,70 @@ def _get_deployment_tiered_pricing_tables(]-def _estimate_input_tokens(+def _get_request_models(request_body: dict,route: str,- model: str,- model_info: Mapping[str, object],-) -> int | None:+ llm_router: Router | None,+) -> Sequence[str]:+ model: Final = get_model_from_request(request_body, route, llm_router=llm_router)+ if model is None:+ return ()+ return (model,) if isinstance(model, str) else tuple(model)+++TOKENIZE_OFF_EVENT_LOOP_MIN_CHARS: Final = 30_000+++async def count_request_input_tokens(+ request_body: dict,+ route: str,+ llm_router: Router | None,+) -> Mapping[str, int]:+ """Input-token count per candidate model, counted once per request.++ Tokenizing is the reservation path's dominant CPU cost and is O(prompt), so+ counting a large prompt inline stalls every other request on the worker.+ Large prompts are counted in a worker thread, and the counts are reused by+ both the max-cost and the input-cost estimate.+ """+ models: Final = _get_request_models(request_body=request_body, route=route, llm_router=llm_router)+ if not models:+ return MappingProxyType({})+ if _approximate_input_size(request_body) < TOKENIZE_OFF_EVENT_LOOP_MIN_CHARS:+ return _count_input_tokens_for_models(request_body=request_body, models=models)+ return await asyncio.to_thread(+ _count_input_tokens_for_models,+ request_body=request_body,+ models=models,+ )+++def _count_input_tokens_for_models(+ request_body: dict,+ models: Sequence[str],+) -> Mapping[str, int]:+ return MappingProxyType(+ {+ model: tokens+ for model in models+ if (tokens := _count_input_tokens(request_body=request_body, model=model)) is not None+ }+ )+++_INPUT_SIZE_FIELDS: Final = ("messages", "prompt", "input", "query", "documents", "tools", "tool_choice")+++def _approximate_input_size(request_body: dict) -> int:+ """Length of the request's input text, a cheap stand-in for tokenizing cost.++ Every field _count_input_tokens hands the tokenizer is sized here, and+ rendering rather than walking keeps mapping keys in the total, which a tool+ schema's property names are."""+ return sum(len(str(request_body.get(field, ""))) for field in _INPUT_SIZE_FIELDS)+++def _count_input_tokens(request_body: dict, model: str) -> int | None:try:if "messages" in request_body:return litellm.token_counter(@@ -1219,6 +1292,21 @@ def _estimate_input_tokens(return query_tokens + document_tokensexcept Exception:verbose_proxy_logger.debug("Unable to count input tokens for budget reservation", exc_info=True)+ return None+++def _estimate_input_tokens(+ request_body: dict,+ route: str,+ model: str,+ model_info: Mapping[str, object],+ input_tokens: int | None = None,+) -> int | None:+ counted: Final = (+ input_tokens if input_tokens is not None else _count_input_tokens(request_body=request_body, model=model)+ )+ if counted is not None:+ return countedmax_input_tokens: Final = _to_int(model_info.get("max_input_tokens"))if max_input_tokens is not None:diff --git a/tests/test_litellm/proxy/test_budget_reservation.py b/tests/test_litellm/proxy/test_budget_reservation.pyindex 34adb4d2091..133b53bb18d 100644--- a/tests/test_litellm/proxy/test_budget_reservation.py+++ b/tests/test_litellm/proxy/test_budget_reservation.py@@ -1,4 +1,6 @@import asyncio+import threading+from collections.abc import Mappingfrom datetime import datetime, timedelta, timezonefrom unittest.mock import AsyncMock, MagicMock, patch@@ -19,6 +21,8 @@ from litellm.proxy._types import ()from litellm.proxy.common_request_processing import ProxyBaseLLMRequestProcessingfrom litellm.proxy.spend_tracking.budget_reservation import (+ TOKENIZE_OFF_EVENT_LOOP_MIN_CHARS,+ _approximate_input_size,estimate_request_max_cost,get_budget_window_start,invalidate_budget_reservation_counters,@@ -2583,3 +2587,255 @@ async def test_streaming_slow_path_processes_and_yields_chunk(spend_counter_statassert received == [{"content": "hi"}]streaming_logging_obj.async_post_call_streaming_hook.assert_awaited_once()+++def _tiered_router() -> Router:+ return Router(+ model_list=[+ {+ "model_name": "dashscope/qwen3-max",+ "litellm_params": {"model": "dashscope/qwen3-max", "api_key": "sk-fake"},+ "model_info": {+ "max_input_tokens": 258048,+ "max_output_tokens": 65536,+ "tiered_pricing": [+ {+ "input_cost_per_token": 1.2e-06,+ "output_cost_per_token": 6e-06,+ "range": [0, 32000],+ },+ {+ "input_cost_per_token": 2.4e-06,+ "output_cost_per_token": 1.2e-05,+ "range": [32000, 128000],+ },+ ],+ },+ }+ ]+ )+++def _body_with_content_size(model: str, content_chars: int) -> dict:+ return {+ "model": model,+ "messages": [{"role": "user", "content": "token " * (content_chars // 6)}],+ "max_tokens": 10,+ }+++async def test_reservation_tokenizes_the_prompt_once(spend_counter_state):+ """Tokenizing is the reservation path's dominant CPU cost, so a request is+ tokenized once no matter how many cost estimates and pricing candidates it+ is priced against. The max-cost and input-cost estimates each used to+ re-tokenize the prompt, once per tiered-pricing candidate."""+ _, key_cache = spend_counter_state+ proxy_logging_obj = ProxyLogging(user_api_key_cache=key_cache)+ valid_token = UserAPIKeyAuth(+ token="key-tokenize-once", spend=0.0, max_budget=100.0+ )+ request_body = _body_with_content_size("dashscope/qwen3-max", 600)+ real_token_counter = litellm.token_counter+ calls = []++ def counting_token_counter(**kwargs):+ calls.append(kwargs)+ return real_token_counter(**kwargs)++ with patch.object(litellm, "token_counter", counting_token_counter):+ reservation = await reserve_budget_for_request(+ request_body=request_body,+ route="/chat/completions",+ llm_router=_tiered_router(),+ valid_token=valid_token,+ team_object=None,+ user_object=None,+ prisma_client=None,+ user_api_key_cache=key_cache,+ proxy_logging_obj=proxy_logging_obj,+ )++ assert reservation is not None+ assert reservation["reserved_cost"] > 0+ assert reservation["input_cost"] > 0+ assert len(calls) == 1+++async def test_large_prompt_is_tokenized_off_the_event_loop(spend_counter_state):+ """Counting a large prompt inline blocks the event loop for the whole count,+ stalling every other request the worker is serving."""+ _, key_cache = spend_counter_state+ proxy_logging_obj = ProxyLogging(user_api_key_cache=key_cache)+ valid_token = UserAPIKeyAuth(token="key-offloaded", spend=0.0, max_budget=100.0)+ request_body = _body_with_content_size(+ "gpt-4o-mini", TOKENIZE_OFF_EVENT_LOOP_MIN_CHARS + 6000+ )+ threads = []++ def recording_token_counter(**kwargs):+ threads.append(threading.current_thread())+ return 1000++ with patch.object(litellm, "token_counter", recording_token_counter):+ reservation = await reserve_budget_for_request(+ request_body=request_body,+ route="/chat/completions",+ llm_router=None,+ valid_token=valid_token,+ team_object=None,+ user_object=None,+ prisma_client=None,+ user_api_key_cache=key_cache,+ proxy_logging_obj=proxy_logging_obj,+ )++ assert reservation is not None+ assert threads+ assert all(thread is not threading.main_thread() for thread in threads)+++def _values_only_size(value: object) -> int:+ """The keys-ignoring walk the fixture below is sized to defeat"""+ if isinstance(value, Mapping):+ return sum(_values_only_size(item) for item in value.values())+ if isinstance(value, (list, tuple)):+ return sum(_values_only_size(item) for item in value)+ return len(value) if isinstance(value, str) else 0+++_TOOL_PROPERTY_NAME_PREFIX = "service_metric_name_segment_" * 3+++def _key_heavy_tool(index: int) -> dict:+ return {+ "type": "function",+ "function": {+ "name": f"lookup_service_metric_{index}",+ "parameters": {+ "type": "object",+ "properties": {+ f"{_TOOL_PROPERTY_NAME_PREFIX}{index}_{field}": {"type": "string"}+ for field in range(24)+ },+ },+ },+ }+++def _body_with_key_heavy_tool_schema(model: str) -> dict:+ """A tool schema whose bulk is property names rather than property values"""+ return {+ "model": model,+ "messages": [{"role": "user", "content": "which service is slow?"}],+ "tools": [_key_heavy_tool(index) for index in range(24)],+ "max_tokens": 10,+ }+++async def test_large_tool_schema_is_tokenized_off_the_event_loop(spend_counter_state):+ """Tool-schema property names are tokenized like any other text. Sizing a+ request by its values alone hides a large schema below the threshold, so it+ gets counted inline and stalls the loop the threshold exists to spare."""+ body = _body_with_key_heavy_tool_schema("gpt-4o-mini")+ assert _values_only_size(body["tools"]) < TOKENIZE_OFF_EVENT_LOOP_MIN_CHARS+ assert _approximate_input_size(body) >= TOKENIZE_OFF_EVENT_LOOP_MIN_CHARS++ _, key_cache = spend_counter_state+ proxy_logging_obj = ProxyLogging(user_api_key_cache=key_cache)+ valid_token = UserAPIKeyAuth(token="key-tool-schema", spend=0.0, max_budget=100.0)+ threads = []++ def recording_token_counter(**kwargs):+ threads.append(threading.current_thread())+ return 1000++ with patch.object(litellm, "token_counter", recording_token_counter):+ reservation = await reserve_budget_for_request(+ request_body=body,+ route="/chat/completions",+ llm_router=None,+ valid_token=valid_token,+ team_object=None,+ user_object=None,+ prisma_client=None,+ user_api_key_cache=key_cache,+ proxy_logging_obj=proxy_logging_obj,+ )++ assert reservation is not None+ assert threads+ assert all(thread is not threading.main_thread() for thread in threads)+++async def test_large_tool_choice_is_tokenized_off_the_event_loop(spend_counter_state):+ """tool_choice is handed to the tokenizer alongside the messages, so a+ request is only sized correctly if the heuristic covers it too."""+ body = {+ "model": "gpt-4o-mini",+ "messages": [{"role": "user", "content": "which service is slow?"}],+ "tool_choice": {+ "type": "function",+ "function": {"name": "lookup_" + "service_metric_" * 3000},+ },+ "max_tokens": 10,+ }+ assert _approximate_input_size(body) >= TOKENIZE_OFF_EVENT_LOOP_MIN_CHARS++ _, key_cache = spend_counter_state+ proxy_logging_obj = ProxyLogging(user_api_key_cache=key_cache)+ valid_token = UserAPIKeyAuth(token="key-tool-choice", spend=0.0, max_budget=100.0)+ threads = []++ def recording_token_counter(**kwargs):+ threads.append(threading.current_thread())+ return 1000++ with patch.object(litellm, "token_counter", recording_token_counter):+ reservation = await reserve_budget_for_request(+ request_body=body,+ route="/chat/completions",+ llm_router=None,+ valid_token=valid_token,+ team_object=None,+ user_object=None,+ prisma_client=None,+ user_api_key_cache=key_cache,+ proxy_logging_obj=proxy_logging_obj,+ )++ assert reservation is not None+ assert threads+ assert all(thread is not threading.main_thread() for thread in threads)+++async def test_small_prompt_is_tokenized_inline(spend_counter_state):+ """A thread hand-off costs more than counting a small prompt"""+ _, key_cache = spend_counter_state+ proxy_logging_obj = ProxyLogging(user_api_key_cache=key_cache)+ valid_token = UserAPIKeyAuth(token="key-inline", spend=0.0, max_budget=100.0)+ threads = []++ def recording_token_counter(**kwargs):+ threads.append(threading.current_thread())+ return 10++ with patch.object(litellm, "token_counter", recording_token_counter):+ reservation = await reserve_budget_for_request(+ request_body=_request_body(),+ route="/chat/completions",+ llm_router=None,+ valid_token=valid_token,+ team_object=None,+ user_object=None,+ prisma_client=None,+ user_api_key_cache=key_cache,+ proxy_logging_obj=proxy_logging_obj,+ )++ assert reservation is not None+ assert threads == [threading.main_thread()]