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 :test_count_tokens_caching

Sameer Kankute777ae4f53030
diff --git a/tests/test_litellm/test_utils_custom.py b/tests/test_litellm/test_utils_custom.py
index 292da4132b9..3e924e9c719 100644
--- a/tests/test_litellm/test_utils_custom.py
+++ b/tests/test_litellm/test_utils_custom.py
@@ -1,4 +1,5 @@
import pytest
+import sys
from unittest.mock import MagicMock, patch, AsyncMock
from litellm.proxy.utils import count_tokens_with_anthropic_api, _anthropic_async_clients
@@ -14,29 +15,31 @@ async def test_count_tokens_caching():
messages = [{"role": "user", "content": "hello"}]
model = "claude-3-opus-20240229"
- # Mock anthropic
- with patch("anthropic.AsyncAnthropic") as mock_cls:
- mock_client = MagicMock()
- mock_cls.return_value = mock_client
-
- # Mock response
- mock_response = MagicMock()
- mock_response.input_tokens = 10
-
- # Setup async return for count_tokens
- mock_client.beta.messages.count_tokens = AsyncMock(return_value=mock_response)
-
+ # Create a mock anthropic module
+ mock_anthropic = MagicMock()
+ mock_client = MagicMock()
+ mock_anthropic.AsyncAnthropic.return_value = mock_client
+
+ # Mock response
+ mock_response = MagicMock()
+ mock_response.input_tokens = 10
+
+ # Setup async return for count_tokens
+ mock_client.beta.messages.count_tokens = AsyncMock(return_value=mock_response)
+
+ # Patch sys.modules to ensure our mock is used when anthropic is imported
+ with patch.dict(sys.modules, {"anthropic": mock_anthropic}):
# First call
with patch.dict("os.environ", {"ANTHROPIC_API_KEY": api_key}):
await count_tokens_with_anthropic_api(model, messages)
assert api_key in _anthropic_async_clients
assert _anthropic_async_clients[api_key] == mock_client
- mock_cls.assert_called_once() # Should be called once
+ mock_anthropic.AsyncAnthropic.assert_called_once() # Should be called once
# Second call
with patch.dict("os.environ", {"ANTHROPIC_API_KEY": api_key}):
await count_tokens_with_anthropic_api(model, messages)
# Should still be called once (cached)
- mock_cls.assert_called_once()
+ mock_anthropic.AsyncAnthropic.assert_called_once()