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(budget_reservation): merge staging and cover count_tokens routes in the mapped test
mateo-berri31bd00dad9e7
diff --cc litellm/proxy/spend_tracking/budget_reservation.pyindex 7b62fd44d09,152f3befa15..31d7d236657--- a/litellm/proxy/spend_tracking/budget_reservation.py+++ b/litellm/proxy/spend_tracking/budget_reservation.py@@@ -144,16 -173,6 +173,23 @@@ def _raise_counter_budget_exceeded)- _UNBILLED_ROUTES: Final[frozenset[str]] = frozenset({"/models", "/v1/models", "/utils/token_counter"})++_UNBILLED_ROUTES: Final[frozenset[str]] = frozenset(++ {++ "/models",++ "/v1/models",++ "/utils/token_counter",++ "/responses/input_tokens",++ "/v1/responses/input_tokens",++ "/openai/v1/responses/input_tokens",++ }++)+_UNBILLED_ROUTE_SUFFIXES: Final[tuple[str, ...]] = ("/v1/messages/count_tokens", ":countTokens")+++def _is_unbilled_route(route: str) -> bool:- """Routes that never emit a cost-tracking callback. Reserving budget for them- is a permanent leak: nothing ever reconciles or releases the reservation."""+ return route in _UNBILLED_ROUTES or route.endswith(_UNBILLED_ROUTE_SUFFIXES)++async def reserve_budget_for_request(request_body: dict,route: str,diff --cc tests/test_litellm/proxy/spend_tracking/test_budget_reservation.pyindex 00000000000,c7de8c943ad..9935dbceb7dmode 000000,100644..100644--- a/tests/test_litellm/proxy/spend_tracking/test_budget_reservation.py+++ b/tests/test_litellm/proxy/spend_tracking/test_budget_reservation.py@@@ -1,0 -1,77 +1,130 @@@+ from typing import Final++ import pytest+++import litellm.proxy.proxy_server as proxy_server+ from litellm.caching import DualCache+ from litellm.proxy._types import UserAPIKeyAuth+ from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache+ from litellm.proxy.spend_tracking.budget_reservation import estimate_request_max_cost, reserve_budget_for_request+ from litellm.proxy.utils import ProxyLogging++ TOKEN_COUNTING_ROUTES: Final = (+ "/responses/input_tokens",+ "/v1/responses/input_tokens",+ "/openai/v1/responses/input_tokens",+ "/utils/token_counter",++ "/v1/messages/count_tokens",++ "/v1beta/models/gemini-3.8-flash:countTokens",++ "/models/gemini-3.8-flash:countTokens",+ )+++ def _budgeted_token() -> UserAPIKeyAuth:+ return UserAPIKeyAuth(api_key="sk-test", token="hashed-token", max_budget=100.0, spend=0.0)+++ async def _reserve(route: str) -> dict | None:+ return await reserve_budget_for_request(+ request_body={"model": "gpt-4o", "input": "hello"},+ route=route,+ llm_router=None,+ valid_token=_budgeted_token(),+ team_object=None,+ user_object=None,+ prisma_client=None,+ user_api_key_cache=UserApiKeyCache(),+ proxy_logging_obj=ProxyLogging(user_api_key_cache=DualCache()),+ )+++ @pytest.mark.asyncio+ @pytest.mark.parametrize("route", TOKEN_COUNTING_ROUTES)+ async def test_token_counting_routes_are_exempt_from_budget_reservation(route):+ assert await _reserve(route) is None+++ @pytest.mark.asyncio+ async def test_non_exempt_llm_route_still_reserves_budget():+ reservation: Final = await _reserve("/v1/responses")++ assert reservation is not None+ assert reservation["reserved_cost"] > 0++++ANTHROPIC_MESSAGES: Final = [{"role": "user", "content": "hello!!!"}]++COUNT_TOKENS_REQUESTS: Final = (++ ("/v1/messages/count_tokens", {"model": "claude-sonnet-5", "messages": ANTHROPIC_MESSAGES}),++ ("/v1beta/models/gemini-3.8-flash:countTokens", {"contents": [{"role": "user", "parts": [{"text": "hello!!!"}]}]}),++)++TINY_BUDGET_KEY_TOKEN: Final = "hashed-count-tokens-key"++++++def spend_counter_cache(monkeypatch: pytest.MonkeyPatch) -> DualCache:++ cache: Final = DualCache()++ monkeypatch.setattr(proxy_server, "spend_counter_cache", cache)++ monkeypatch.setattr(proxy_server, "prisma_client", None)++ return cache++++++async def _reserve_for_tiny_budget_key(route: str, request_body: dict) -> dict | None:++ return await reserve_budget_for_request(++ request_body=request_body,++ route=route,++ llm_router=None,++ valid_token=UserAPIKeyAuth(token=TINY_BUDGET_KEY_TOKEN, max_budget=0.01, spend=0.0),++ team_object=None,++ user_object=None,++ prisma_client=None,++ user_api_key_cache=UserApiKeyCache(),++ proxy_logging_obj=ProxyLogging(user_api_key_cache=DualCache()),++ )++++[email protected](("route", "request_body"), COUNT_TOKENS_REQUESTS)++async def test_repeated_token_counting_never_touches_a_tiny_budget(++ spend_counter_cache: DualCache, route: str, request_body: dict++):++ counter_key: Final = f"spend:key:{TINY_BUDGET_KEY_TOKEN}"++++ assert await _reserve_for_tiny_budget_key(route, request_body) is None++ assert await _reserve_for_tiny_budget_key(route, request_body) is None++ assert spend_counter_cache.in_memory_cache.get_cache(key=counter_key) is None++++ completion: Final = await _reserve_for_tiny_budget_key(++ "/v1/messages", {"model": "claude-sonnet-5", "max_tokens": 16, "messages": ANTHROPIC_MESSAGES}++ )++ assert completion is not None++ assert completion["reserved_cost"] > 0++ assert spend_counter_cache.in_memory_cache.get_cache(key=counter_key) == pytest.approx(completion["reserved_cost"])+++++ BEDROCK_SONNET: Final = "us.anthropic.claude-sonnet-4-6"+ CONVERSE_BODY: Final = {+ "messages": [{"role": "user", "content": [{"text": "Reply with one word: pong"}]}],+ "inferenceConfig": {"maxTokens": 5},+ }+ INVOKE_BODY: Final = {+ "anthropic_version": "bedrock-2023-05-31",+ "max_tokens": 5,+ "messages": [{"role": "user", "content": "Reply with one word: pong"}],+ }+++ def test_bedrock_converse_body_reserves_the_prompt_not_the_context_window():+ converse_cost: Final = estimate_request_max_cost(+ request_body=CONVERSE_BODY,+ route=f"/bedrock/model/{BEDROCK_SONNET}/converse",+ llm_router=None,+ input_token_counts={},+ )+ invoke_cost: Final = estimate_request_max_cost(+ request_body=INVOKE_BODY,+ route=f"/bedrock/model/{BEDROCK_SONNET}/invoke",+ llm_router=None,+ input_token_counts={},+ )+ assert converse_cost is not None and invoke_cost is not None+ assert invoke_cost < converse_cost < 2 * invoke_cost