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(proxy): estimate image message tokens without fetching the image url

mateo-berri42ddc5c5359b
diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.py
index 1465e76d01f..c45b4ad17c0 100644
--- a/litellm/proxy/utils.py
+++ b/litellm/proxy/utils.py
@@ -430,7 +430,9 @@ def _count_request_input_tokens(model: str, request_input: object, system_input:
text_entries: Final = tuple(entry for entry in request_input if isinstance(entry, str))
if len(text_entries) == len(request_input):
return system_tokens + litellm.token_counter(model=model, text="".join(text_entries))
- return system_tokens + litellm.token_counter(model=model, messages=request_input)
+ return system_tokens + litellm.token_counter(
+ model=model, messages=request_input, use_default_image_token_count=True
+ )
def _estimate_dispatched_failure_usage(model: str, request_input: object, system_input: object) -> Usage | None:
diff --git a/tests/test_litellm/proxy/test_proxy_utils.py b/tests/test_litellm/proxy/test_proxy_utils.py
index 96e2c74e5d4..b70f93054d2 100644
--- a/tests/test_litellm/proxy/test_proxy_utils.py
+++ b/tests/test_litellm/proxy/test_proxy_utils.py
@@ -635,6 +635,34 @@ class TestPostCallFailureHookEstimatesDispatchedInputTokens:
"metadata": {},
}
+ @pytest.mark.asyncio
+ async def test_image_message_estimated_without_fetching_image(self):
+ import litellm as litellm_module
+ from litellm.types.utils import Usage
+
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "describe this image"},
+ {
+ "type": "image_url",
+ "image_url": {"url": "http://127.0.0.1:1/unreachable.png", "detail": "high"},
+ },
+ ],
+ }
+ ]
+ request_data = self._dispatched_request_data(messages, {})
+ 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", messages=messages, use_default_image_token_count=True
+ )
+ assert estimated.prompt_tokens == expected
+ assert estimated.prompt_tokens > 0
+
@pytest.mark.asyncio
async def test_embedding_string_list_input_counted_in_estimate(self):
import litellm as litellm_module