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(proxy): only estimate failed-request input tokens for call types whose input is countable
mateo-berri3a4d3a01af14
diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.pyindex 5bfc1c2d1e1..1465e76d01f 100644--- a/litellm/proxy/utils.py+++ b/litellm/proxy/utils.py@@ -449,6 +449,35 @@ def _estimate_dispatched_failure_usage(model: str, request_input: object, systemreturn Usage(prompt_tokens=input_tokens, completion_tokens=0, total_tokens=input_tokens)+_INPUT_ESTIMABLE_CALL_TYPES: Final = frozenset(+ call_type.value+ for call_type in (+ CallTypes.completion,+ CallTypes.acompletion,+ CallTypes.text_completion,+ CallTypes.atext_completion,+ CallTypes.anthropic_messages,+ CallTypes.aanthropic_messages,+ CallTypes.responses,+ CallTypes.aresponses,+ CallTypes.embedding,+ CallTypes.aembedding,+ CallTypes.moderation,+ CallTypes.amoderation,+ CallTypes.image_generation,+ CallTypes.aimage_generation,+ CallTypes.speech,+ CallTypes.aspeech,+ CallTypes.rerank,+ CallTypes.arerank,+ CallTypes.generate_content,+ CallTypes.agenerate_content,+ CallTypes.generate_content_stream,+ CallTypes.agenerate_content_stream,+ )+)++def _failure_usage_to_lift(model_call_details: Mapping[str, object], dispatched: bool) -> tuple[object, object] | None:"""A stream that broke mid-flight still billed the provider for the chunksalready delivered; the streaming handler stashes that recovered usage and@@ -461,6 +490,8 @@ def _failure_usage_to_lift(model_call_details: Mapping[str, object], dispatched:return recovered_usage, model_call_details.get("response_cost")if not dispatched or model_call_details.get(LITELLM_LOGGING_NO_UPSTREAM_LLM_CALL):return None+ if str(model_call_details.get("call_type")) not in _INPUT_ESTIMABLE_CALL_TYPES:+ return Noneoptional_params: Final = model_call_details.get("optional_params")system_input: Final = ((optional_params.get("system") or optional_params.get("instructions"))diff --git a/tests/test_litellm/proxy/test_proxy_utils.py b/tests/test_litellm/proxy/test_proxy_utils.pyindex 0455a806c0b..96e2c74e5d4 100644--- a/tests/test_litellm/proxy/test_proxy_utils.py+++ b/tests/test_litellm/proxy/test_proxy_utils.py@@ -517,6 +517,7 @@ class TestPostCallFailureHookEstimatesDispatchedInputTokens:"first_api_call_start_time": datetime.now(),"model": "gpt-3.5-turbo","messages": [{"role": "user", "content": "count these input tokens please"}],+ "call_type": "acompletion",}),"metadata": {},@@ -582,6 +583,7 @@ class TestPostCallFailureHookEstimatesDispatchedInputTokens:"first_api_call_start_time": datetime.now(),"model": "gpt-3.5-turbo","messages": [{"role": "user", "content": "mid-stream failure"}],+ "call_type": "acompletion","combined_usage_object": recovered_usage,"response_cost": 3.5e-05,}@@ -605,6 +607,7 @@ class TestPostCallFailureHookEstimatesDispatchedInputTokens:"first_api_call_start_time": datetime.now(),"model": "gpt-3.5-turbo","messages": "a plain text-completion prompt string",+ "call_type": "atext_completion",}),"metadata": {},@@ -616,7 +619,7 @@ class TestPostCallFailureHookEstimatesDispatchedInputTokens:assert estimated.prompt_tokens > 0assert estimated.completion_tokens == 0- def _dispatched_request_data(self, messages, optional_params):+ def _dispatched_request_data(self, messages, optional_params, call_type="acompletion"):from datetime import datetimereturn {@@ -626,11 +629,34 @@ class TestPostCallFailureHookEstimatesDispatchedInputTokens:"model": "gpt-3.5-turbo","messages": messages,"optional_params": optional_params,+ "call_type": call_type,}),"metadata": {},}+ @pytest.mark.asyncio+ async def test_embedding_string_list_input_counted_in_estimate(self):+ import litellm as litellm_module+ from litellm.types.utils import Usage++ embedding_input = ["first embedding text", "second embedding text"]+ request_data = self._dispatched_request_data(embedding_input, {}, call_type="aembedding")+ await self._run(request_data)++ estimated = request_data["combined_usage_object"]+ assert isinstance(estimated, Usage)+ expected = litellm_module.token_counter(model="gpt-3.5-turbo", text="".join(embedding_input))+ assert estimated.prompt_tokens == expected++ @pytest.mark.asyncio+ async def test_transcription_checksum_not_estimated(self):+ request_data = self._dispatched_request_data("a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6", {}, call_type="atranscription")+ await self._run(request_data)++ assert "combined_usage_object" not in request_data+ assert "response_cost" not in request_data+@pytest.mark.asyncioasync def test_anthropic_system_prompt_counted_in_estimate(self):import litellm as litellm_module