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(passthrough): honor the zero fallback and aggregate-only TPM usage
Yuneng Jiang9c48ad41ace5
diff --git a/litellm/proxy/hooks/parallel_request_limiter_v3.py b/litellm/proxy/hooks/parallel_request_limiter_v3.pyindex 81d46247507..f72492881b3 100644--- a/litellm/proxy/hooks/parallel_request_limiter_v3.py+++ b/litellm/proxy/hooks/parallel_request_limiter_v3.py@@ -2671,6 +2671,35 @@ class _PROXY_MaxParallelRequestsHandler_v3(CustomLogger):return total_tokens+ @staticmethod+ def _aggregate_only_total_tokens(usage: Union[Usage, dict, None]) -> int:+ """Total for usage that carries no input/output split, else 0.++ A source that can only report one number for the whole request (a+ pass-through target pricing its own multi-model call) charges that+ number under every ``token_rate_limit_type``. Splitting it is+ impossible, and reading 0 out of it would leave the window+ uncharged, which is how pass-through traffic slips past a TPM limit+ it is supposed to share.+ """+ if isinstance(usage, Usage):+ prompt_tokens, completion_tokens, total_tokens = (+ usage.prompt_tokens or 0,+ usage.completion_tokens or 0,+ usage.total_tokens or 0,+ )+ elif isinstance(usage, dict):+ prompt_tokens, completion_tokens, total_tokens = (+ usage.get("prompt_tokens") or 0,+ usage.get("completion_tokens") or 0,+ usage.get("total_tokens") or 0,+ )+ else:+ return 0+ if prompt_tokens or completion_tokens:+ return 0+ return total_tokens+async def _execute_token_increment_script(self,pipeline_operations: List["RedisPipelineIncrementOperation"],@@ -3107,6 +3136,8 @@ class _PROXY_MaxParallelRequestsHandler_v3(CustomLogger):if isinstance(_combined_usage, Usage):_usage = _combined_usagetotal_tokens = self._get_total_tokens_from_usage(usage=_usage, rate_limit_type=rate_limit_type)+ if total_tokens == 0:+ total_tokens = self._aggregate_only_total_tokens(usage=_usage)reserved_tokens = self._get_reserved_tokens_from_kwargs(kwargs=kwargs,diff --git a/litellm/proxy/pass_through_endpoints/success_handler.py b/litellm/proxy/pass_through_endpoints/success_handler.pyindex 84a956f0c29..20ed84c8636 100644--- a/litellm/proxy/pass_through_endpoints/success_handler.py+++ b/litellm/proxy/pass_through_endpoints/success_handler.py@@ -30,7 +30,7 @@ from .llm_provider_handlers.gemini_passthrough_logging_handler import (from .llm_provider_handlers.vertex_passthrough_logging_handler import (VertexPassthroughLoggingHandler,)-from .upstream_usage_headers import upstream_reported_cost+from .upstream_usage_headers import has_upstream_reported_usagecohere_passthrough_logging_handler = CoherePassthroughLoggingHandler()@@ -450,15 +450,17 @@ class PassThroughEndpointLogging:Only set the cost per request if it's set in the passthrough logging payload.If it's not set, don't set it in the logging object.- An upstream that priced the request itself always wins: ``cost_per_request``+ An upstream that prices its own requests always wins: ``cost_per_request``is a flat per-request estimate for targets LiteLLM cannot price, and itdefaults to 0.0 on every config-defined endpoint, so honoring it here- would zero out the real cost the upstream reported.+ would zero out the real cost the upstream reported. That holds even when+ the reported value was unusable, where the contract records 0 rather+ than billing an estimate the upstream just contradicted."""########################################################## Check if cost per request is set#########################################################- if upstream_reported_cost(logging_obj) is not None:+ if has_upstream_reported_usage(logging_obj):return kwargsif passthrough_logging_payload.get("cost_per_request") is not None:diff --git a/litellm/proxy/pass_through_endpoints/upstream_usage_headers.py b/litellm/proxy/pass_through_endpoints/upstream_usage_headers.pyindex e147dcb9547..6ee2514b4a0 100644--- a/litellm/proxy/pass_through_endpoints/upstream_usage_headers.py+++ b/litellm/proxy/pass_through_endpoints/upstream_usage_headers.py@@ -126,9 +126,11 @@ def apply_upstream_reported_usage(return reported-def upstream_reported_cost(logging_obj: LiteLLMLoggingObj) -> float | None:- """The cost the upstream reported for this request, if it reported one."""- reported = logging_obj.model_call_details.get(UPSTREAM_REPORTED_USAGE_KEY)- if not isinstance(reported, UpstreamReportedUsage):- return None- return reported.response_cost+def has_upstream_reported_usage(logging_obj: LiteLLMLoggingObj) -> bool:+ """Whether the upstream spoke this contract on the request's response.++ True even when the value it sent was unusable: a target that reports its+ own totals owns the cost for the request, and a header we could not parse+ means zero, never a fallback to someone else's estimate.+ """+ return isinstance(logging_obj.model_call_details.get(UPSTREAM_REPORTED_USAGE_KEY), UpstreamReportedUsage)diff --git a/tests/test_litellm/proxy/hooks/test_parallel_request_limiter_v3.py b/tests/test_litellm/proxy/hooks/test_parallel_request_limiter_v3.pyindex 27b1c025fbb..9337050b61c 100644--- a/tests/test_litellm/proxy/hooks/test_parallel_request_limiter_v3.py+++ b/tests/test_litellm/proxy/hooks/test_parallel_request_limiter_v3.py@@ -4702,3 +4702,89 @@ async def test_async_log_success_event_counts_passthrough_reported_tokens(monkeyassert any("team-fil" in op["key"] for op in token_operations), ("team TPM window must be charged so pass-through shares the team's limit")++[email protected]("rate_limit_type", ["input", "output", "total"])+async def test_aggregate_only_usage_charges_tpm_under_every_limit_type(+ monkeypatch, rate_limit_type+):+ """+ A pass-through target reports one total for the whole request and cannot+ split it into prompt/completion. Reading a split out of it yields 0, which+ left the TPM window uncharged under input- or output-token limiting and let+ pass-through traffic run past a limit it is supposed to share.+ """+ monkeypatch.setenv("LITELLM_RATE_LIMIT_WINDOW_SIZE", "60")++ _api_key = hash_token("sk-aggregate-only")+ parallel_request_handler = _PROXY_MaxParallelRequestsHandler(+ internal_usage_cache=InternalUsageCache(DualCache())+ )+ monkeypatch.setattr(+ parallel_request_handler, "get_rate_limit_type", lambda: rate_limit_type+ )++ captured_operations = []++ async def mock_increment_pipeline(increment_list, **kwargs):+ captured_operations.extend(increment_list)+ return True++ monkeypatch.setattr(+ parallel_request_handler.internal_usage_cache.dual_cache,+ "async_increment_cache_pipeline",+ mock_increment_pipeline,+ )++ await parallel_request_handler.async_log_success_event(+ kwargs={+ "standard_logging_object": {"metadata": {"user_api_key_hash": _api_key}},+ "combined_usage_object": Usage(total_tokens=1874),+ },+ response_obj={"response": "upstream body was never parsed"},+ start_time=datetime.now(),+ end_time=datetime.now(),+ )++ token_operations = [op for op in captured_operations if op["key"].endswith(":tokens")]+ assert token_operations, f"aggregate usage should charge TPM under {rate_limit_type}"+ assert all(op["increment_value"] == 1874 for op in token_operations)+++async def test_split_usage_still_respects_the_configured_limit_type(monkeypatch):+ """The aggregate fallback must not hijack usage that does carry a split."""+ monkeypatch.setenv("LITELLM_RATE_LIMIT_WINDOW_SIZE", "60")++ _api_key = hash_token("sk-split-usage")+ parallel_request_handler = _PROXY_MaxParallelRequestsHandler(+ internal_usage_cache=InternalUsageCache(DualCache())+ )+ monkeypatch.setattr(parallel_request_handler, "get_rate_limit_type", lambda: "output")++ captured_operations = []++ async def mock_increment_pipeline(increment_list, **kwargs):+ captured_operations.extend(increment_list)+ return True++ monkeypatch.setattr(+ parallel_request_handler.internal_usage_cache.dual_cache,+ "async_increment_cache_pipeline",+ mock_increment_pipeline,+ )++ await parallel_request_handler.async_log_success_event(+ kwargs={"standard_logging_object": {"metadata": {"user_api_key_hash": _api_key}}},+ response_obj=ModelResponse(+ model="gpt-4o",+ usage=Usage(prompt_tokens=100, completion_tokens=7, total_tokens=107),+ ),+ start_time=datetime.now(),+ end_time=datetime.now(),+ )++ token_operations = [op for op in captured_operations if op["key"].endswith(":tokens")]+ assert token_operations+ assert all(op["increment_value"] == 7 for op in token_operations)diff --git a/tests/test_litellm/proxy/pass_through_endpoints/test_pass_through_endpoints.py b/tests/test_litellm/proxy/pass_through_endpoints/test_pass_through_endpoints.pyindex 60340cfa47b..9bddeda0723 100644--- a/tests/test_litellm/proxy/pass_through_endpoints/test_pass_through_endpoints.py+++ b/tests/test_litellm/proxy/pass_through_endpoints/test_pass_through_endpoints.py@@ -4860,3 +4860,20 @@ async def test_configured_cost_per_request_still_applies_without_usage_headers()assert len(payloads) == 1assert payloads[0]["response_cost"] == 0.25+++async def test_unusable_upstream_cost_records_zero_not_the_flat_estimate():+ """+ A target that speaks this contract owns the cost for the request. When the+ value it sends is unusable the contract records 0, rather than falling back+ to a flat cost_per_request the upstream just contradicted.+ """+ payloads, _ = await _run_upstream_reporting_passthrough(+ {"x-litellm-response-cost": "not-a-number", "x-litellm-total-tokens": "1874"},+ cost_per_request=0.05,+ )++ assert len(payloads) == 1+ assert payloads[0]["response_cost"] == 0.0+ assert payloads[0]["total_tokens"] == 1874