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 token counter to ignore unsupported keys like prefix (#11791) (#11954)

Amit Kumarb6f15ed64d67
diff --git a/litellm/litellm_core_utils/token_counter.py b/litellm/litellm_core_utils/token_counter.py
index 1eb4fc9016a..4df944edbaa 100644
--- a/litellm/litellm_core_utils/token_counter.py
+++ b/litellm/litellm_core_utils/token_counter.py
@@ -462,9 +462,8 @@ def _count_messages(
default_token_count,
)
else:
- raise ValueError(
- f"Unsupported type {type(value)} for key {key} in message {message}"
- )
+ # Skip unsupported keys instead of raising an error
+ continue
return num_tokens
diff --git a/tests/test_litellm/litellm_core_utils/test_token_counter.py b/tests/test_litellm/litellm_core_utils/test_token_counter.py
index b2d3bcd1305..71ee367bdec 100644
--- a/tests/test_litellm/litellm_core_utils/test_token_counter.py
+++ b/tests/test_litellm/litellm_core_utils/test_token_counter.py
@@ -54,6 +54,15 @@ def test_token_counter_basic():
)
+def test_token_counter_with_prefix():
+ messages = [
+ {"role": "user", "content": "Who won the world cup in 2022?"},
+ {"role": "assistant", "content": "Argentina", "prefix": True}
+ ]
+ tokens = token_counter(model="gpt-3.5-turbo", messages=messages)
+ assert tokens == 22 , f"Expected 22 tokens, got {tokens}"
+
+
def test_token_counter_normal_plus_function_calling():
messages = [
{"role": "system", "content": "System prompt"},