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): stop re-downloading a HuggingFace tokenizer after a failed download (#47586)

devin-ai-integration[bot]41890bdf6414
diff --git a/litellm/caching/in_memory_cache.py b/litellm/caching/in_memory_cache.py
index cb6426f64ff..1cc3e106aa0 100644
--- a/litellm/caching/in_memory_cache.py
+++ b/litellm/caching/in_memory_cache.py
@@ -95,7 +95,10 @@ class InMemoryCache(BaseCache):
"""
Check if a specific key is expired
"""
- return key in self.ttl_dict and self._clock() > self.ttl_dict[key]
+ try:
+ return self._clock() > self.ttl_dict[key]
+ except KeyError:
+ return False
def _cache_keys(self) -> tuple[str, ...]:
return tuple(self.cache_dict) # pyright: ignore[reportUnknownVariableType] # cache_dict is untyped legacy state
@@ -227,7 +230,10 @@ class InMemoryCache(BaseCache):
if key in self.cache_dict:
if self.evict_element_if_expired(key):
return None
- original_cached_response: Final = self.cache_dict[key]
+ try:
+ original_cached_response: Final = self.cache_dict[key]
+ except KeyError:
+ return None
try:
cached_response = json.loads(original_cached_response)
except Exception:
diff --git a/litellm/constants.py b/litellm/constants.py
index 1c1dfb9aa1c..6a503463a8c 100644
--- a/litellm/constants.py
+++ b/litellm/constants.py
@@ -156,6 +156,9 @@ DEFAULT_REPLICATE_POLLING_RETRIES: Final = get_env_int("DEFAULT_REPLICATE_POLLIN
DEFAULT_REPLICATE_POLLING_DELAY_SECONDS: Final = get_env_int("DEFAULT_REPLICATE_POLLING_DELAY_SECONDS", 1)
DEFAULT_IMAGE_TOKEN_COUNT: Final = get_env_int("DEFAULT_IMAGE_TOKEN_COUNT", 250)
HF_CONFIG_FETCH_TIMEOUT_SECONDS: Final = 10.0
+HUGGINGFACE_TOKENIZER_LOAD_RETRY_SECONDS: Final = get_env_int_in_range(
+ "HUGGINGFACE_TOKENIZER_LOAD_RETRY_SECONDS", 300, 1, 86400
+)
# Maximum wall-clock seconds a streaming response is allowed to run.
# Streams exceeding this duration are terminated with a Timeout error.
diff --git a/litellm/utils.py b/litellm/utils.py
index 897138a940c..379eddb3155 100644
--- a/litellm/utils.py
+++ b/litellm/utils.py
@@ -71,6 +71,7 @@ from litellm.constants import (
DEFAULT_TRIM_RATIO,
FUNCTION_DEFINITION_TOKEN_COUNT,
HF_CONFIG_FETCH_TIMEOUT_SECONDS,
+ HUGGINGFACE_TOKENIZER_LOAD_RETRY_SECONDS,
INITIAL_RETRY_DELAY,
JITTER,
MAX_RETRY_DELAY,
@@ -2597,19 +2598,14 @@ def _select_tokenizer_helper(model: str) -> SelectTokenizerResponse:
try:
result: Final = _return_huggingface_tokenizer(model)
- if result is not None:
+ if result is not None and not isinstance(result, _HuggingFaceTokenizerLoadFailure):
return result
except Exception as e:
from litellm.rust_bridge.fork_guard import ForkedAfterNativeRuntimeStarted, ProcessReservedForForking
if isinstance(e, (ForkedAfterNativeRuntimeStarted, ProcessReservedForForking)):
raise
- verbose_logger.warning(
- "Falling back to tiktoken for %s; token counts may be approximate. "
- "For Python Hugging Face tokenization, install tokenizers and huggingface-hub. Error: %s",
- json.dumps(redact_secrets(model)),
- json.dumps(redact_secrets(str(e))),
- )
+ _warn_huggingface_tokenizer_fallback(model, str(e))
# default - tiktoken
return _return_openai_tokenizer(model)
@@ -2649,15 +2645,41 @@ def huggingface_tokenizer_kind(model: str) -> HuggingFaceTokenizerKind | None:
return None
-def _return_huggingface_tokenizer(model: str) -> SelectTokenizerResponse | None:
+@dataclass(frozen=True, slots=True)
+class _HuggingFaceTokenizerLoadFailure:
+ reason: str
+
+
+def _warn_huggingface_tokenizer_fallback(model: str, reason: str) -> None:
+ verbose_logger.warning(
+ "Falling back to tiktoken for %s; token counts may be approximate. "
+ "For Python Hugging Face tokenization, install tokenizers and huggingface-hub. Error: %s",
+ json.dumps(redact_secrets(model)),
+ json.dumps(redact_secrets(reason)),
+ )
+
+
+def _return_huggingface_tokenizer(model: str) -> SelectTokenizerResponse | _HuggingFaceTokenizerLoadFailure | None:
kind: Final = huggingface_tokenizer_kind(model)
if kind is None:
return None
+ backend: Final = _huggingface_tokenizer_backend()
+ key: Final = _huggingface_tokenizer_failure_key(kind, backend)
with _BUNDLED_TOKENIZER_LOAD_LOCKS.get(kind, nullcontext()):
- tokenizer: Final = _load_huggingface_tokenizer(kind, _huggingface_tokenizer_backend())
+ cached_failure: Final = _HUGGINGFACE_TOKENIZER_LOAD_FAILURES.get_cache(key)
+ if isinstance(cached_failure, _HuggingFaceTokenizerLoadFailure):
+ return cached_failure
+ tokenizer: Final = _load_huggingface_tokenizer_recording_failure(kind, backend, key)
+ if isinstance(tokenizer, _HuggingFaceTokenizerLoadFailure):
+ _warn_huggingface_tokenizer_fallback(model, tokenizer.reason)
+ return tokenizer
return {"type": "huggingface_tokenizer", "tokenizer": tokenizer}
+def _huggingface_tokenizer_failure_key(kind: HuggingFaceTokenizerKind, backend: Decision) -> str:
+ return f"{kind}:{backend.name}"
+
+
@lru_cache(maxsize=DEFAULT_MAX_LRU_CACHE_SIZE)
def _load_huggingface_tokenizer(kind: HuggingFaceTokenizerKind, backend: Decision) -> HuggingFace:
"""One tokenizer per kind and backend; `backend` is the cache key, the dispatch re-derives it."""
@@ -2680,6 +2702,21 @@ def _load_huggingface_tokenizer(kind: HuggingFaceTokenizerKind, backend: Decisio
assert_never(kind)
+def _load_huggingface_tokenizer_recording_failure(
+ kind: HuggingFaceTokenizerKind, backend: Decision, key: str
+) -> HuggingFace | _HuggingFaceTokenizerLoadFailure:
+ try:
+ return _load_huggingface_tokenizer(kind, backend)
+ except Exception as error:
+ from litellm.rust_bridge.fork_guard import ForkedAfterNativeRuntimeStarted, ProcessReservedForForking
+
+ if isinstance(error, (ForkedAfterNativeRuntimeStarted, ProcessReservedForForking)):
+ raise
+ failure: Final = _HuggingFaceTokenizerLoadFailure(reason=str(error))
+ _HUGGINGFACE_TOKENIZER_LOAD_FAILURES.set_cache(key, failure, ttl=HUGGINGFACE_TOKENIZER_LOAD_RETRY_SECONDS)
+ return failure
+
+
def encode(model="", text="", custom_tokenizer: dict | None = None):
"""
Encodes the given text using the specified model.
@@ -8295,6 +8332,26 @@ def trim_messages(
from litellm.caching.in_memory_cache import InMemoryCache
+class _HuggingFaceTokenizerLoadFailureCache(Protocol):
+ def get_cache(self, key: str) -> object | None: ...
+
+ def set_cache(self, key: str, value: object, ttl: float | None = None) -> None: ...
+
+ def flush_cache(self) -> None: ...
+
+
+_HUGGINGFACE_TOKENIZER_LOAD_FAILURES: Final[_HuggingFaceTokenizerLoadFailureCache] = (
+ cast( # cast-ok: cache methods are untyped
+ _HuggingFaceTokenizerLoadFailureCache,
+ InMemoryCache(
+ max_size_in_memory=16,
+ default_ttl=HUGGINGFACE_TOKENIZER_LOAD_RETRY_SECONDS,
+ clock=lambda: time.monotonic(),
+ ),
+ )
+)
+
+
class AvailableModelsCache(InMemoryCache):
def __init__(self, ttl_seconds: int = 300, max_size: int = 1000):
super().__init__(ttl_seconds, max_size)
diff --git a/tests/unit/caching/test_in_memory_cache.py b/tests/unit/caching/test_in_memory_cache.py
index 214f4ecf301..75232476ecd 100644
--- a/tests/unit/caching/test_in_memory_cache.py
+++ b/tests/unit/caching/test_in_memory_cache.py
@@ -49,6 +49,47 @@ async def test_async_increment_delegates_to_locked_sync_path():
assert cache.get_cache("counter") == 5
+class _AnotherReaderExpiresTheEntryFirstCache(InMemoryCache):
+ other_reader_started = False
+ other_reader_result: object = "not run"
+
+ def evict_element_if_expired(self, key: str) -> bool:
+ if not self.other_reader_started:
+ self.other_reader_started = True
+ self.other_reader_result = self.get_cache(key)
+ return super().evict_element_if_expired(key)
+
+
+def test_get_cache_reads_an_entry_another_reader_just_expired_as_a_miss() -> None:
+ cache: Final = _AnotherReaderExpiresTheEntryFirstCache()
+ cache.set_cache("tokenizer_failure", "HF unavailable", ttl=-1)
+
+ assert cache.get_cache("tokenizer_failure") is None
+ assert cache.other_reader_result is None
+
+
+class _ClockThatLetsAnotherReaderRunFirst:
+ cache: InMemoryCache | None = None
+ other_reader_result: object = "not run"
+
+ def __call__(self) -> float:
+ cache: Final = self.cache
+ if cache is not None:
+ self.cache = None
+ self.other_reader_result = cache.get_cache("tokenizer_failure")
+ return 100.0
+
+
+def test_get_cache_reads_an_entry_another_reader_expires_during_the_expiry_check_as_a_miss() -> None:
+ clock: Final = _ClockThatLetsAnotherReaderRunFirst()
+ cache: Final = InMemoryCache(clock=clock)
+ cache.set_cache("tokenizer_failure", "HF unavailable", ttl=-1)
+ clock.cache = cache
+
+ assert cache.get_cache("tokenizer_failure") is None
+ assert clock.other_reader_result is None
+
+
def test_in_memory_openai_obj_cache():
from openai import OpenAI
diff --git a/tests/unit/litellm_core_utils/test_token_counter.py b/tests/unit/litellm_core_utils/test_token_counter.py
index 309cbd33131..194d7995735 100644
--- a/tests/unit/litellm_core_utils/test_token_counter.py
+++ b/tests/unit/litellm_core_utils/test_token_counter.py
@@ -14,7 +14,7 @@ from concurrent.futures import Future, ThreadPoolExecutor, wait
from itertools import accumulate, chain
from pathlib import Path
from typing import Final
-from unittest.mock import MagicMock
+from unittest.mock import MagicMock, sentinel
import anyio.to_thread
import pytest
@@ -27,7 +27,7 @@ import litellm
from litellm import decode, encode, get_modified_max_tokens
from litellm import token_counter as token_counter_old
import litellm.constants
-from litellm.constants import TOKEN_COUNTER_MAX_CONCURRENT_COUNTS
+from litellm.constants import HUGGINGFACE_TOKENIZER_LOAD_RETRY_SECONDS, TOKEN_COUNTER_MAX_CONCURRENT_COUNTS
from litellm.litellm_core_utils.asyncify import asyncify
from litellm.litellm_core_utils.token_counter import (
_encoding_count,
@@ -940,10 +940,17 @@ def test_token_counter():
import unittest
-from litellm.utils import _load_huggingface_tokenizer, _select_tokenizer_helper, claude_json_str, encoding
+from litellm.utils import (
+ _HUGGINGFACE_TOKENIZER_LOAD_FAILURES,
+ _load_huggingface_tokenizer,
+ _select_tokenizer_helper,
+ claude_json_str,
+ encoding,
+)
# Clear the cache at module load to ensure clean state
_load_huggingface_tokenizer.cache_clear()
+_HUGGINGFACE_TOKENIZER_LOAD_FAILURES.flush_cache()
class TestTokenizerSelection(unittest.TestCase):
@@ -955,6 +962,7 @@ class TestTokenizerSelection(unittest.TestCase):
--dist=loadscope (tests from same file run on same worker).
"""
_load_huggingface_tokenizer.cache_clear()
+ _HUGGINGFACE_TOKENIZER_LOAD_FAILURES.flush_cache()
@patch("litellm.utils.tokenizer_dispatch.from_pretrained")
def test_llama3_tokenizer_api_failure(self, mock_from_pretrained):
@@ -1038,6 +1046,69 @@ class TestTokenizerSelection(unittest.TestCase):
finally:
monkeypatch.undo()
+ @patch("litellm.utils.tokenizer_dispatch.from_pretrained")
+ def test_failed_huggingface_tokenizer_download_is_not_retried_on_every_count(
+ self, mock_from_pretrained: MagicMock
+ ):
+ _load_huggingface_tokenizer.cache_clear()
+ _HUGGINGFACE_TOKENIZER_LOAD_FAILURES.flush_cache()
+ try:
+ with patch("litellm.utils.time.monotonic", return_value=0.0):
+ mock_from_pretrained.side_effect = RuntimeError("HF unavailable")
+ model: Final = "databricks/databricks-meta-llama-3-3-70b-instruct"
+ text: Final = "Count the tokens for this message."
+ expected: Final = len(encoding.encode(text, disallowed_special=()))
+
+ first_count: Final = litellm.token_counter(model=model, text=text)
+ first_attempts: Final = mock_from_pretrained.call_count
+ second_count: Final = litellm.token_counter(model=model, text=text)
+
+ assert first_attempts > 0
+ assert mock_from_pretrained.call_count == first_attempts
+ assert first_count == expected
+ assert second_count == expected
+ finally:
+ _load_huggingface_tokenizer.cache_clear()
+ _HUGGINGFACE_TOKENIZER_LOAD_FAILURES.flush_cache()
+
+ @patch("litellm.utils.time.monotonic", return_value=299.0)
+ @patch("litellm.utils.tokenizer_dispatch.from_pretrained")
+ def test_failed_huggingface_tokenizer_download_is_retried_after_retry_window(
+ self, mock_from_pretrained: MagicMock, mock_monotonic: MagicMock
+ ):
+ _load_huggingface_tokenizer.cache_clear()
+ _HUGGINGFACE_TOKENIZER_LOAD_FAILURES.flush_cache()
+ try:
+ def from_pretrained_side_effect(_: str) -> object:
+ if mock_from_pretrained.call_count == 1:
+ mock_monotonic.return_value = 322.0
+ raise RuntimeError("HF unavailable")
+ return sentinel.tokenizer
+
+ mock_from_pretrained.side_effect = from_pretrained_side_effect
+ model: Final = "databricks/databricks-meta-llama-3-3-70b-instruct"
+
+ first_result: Final = _select_tokenizer_helper(model)
+ assert first_result["type"] == "openai_tokenizer"
+ mock_monotonic.return_value = 323.0
+ second_result: Final = _select_tokenizer_helper(model)
+ assert second_result["type"] == "openai_tokenizer", "tokenizer was retried at t=323"
+ assert mock_from_pretrained.call_count == 1
+
+ mock_monotonic.return_value = 322.0 + HUGGINGFACE_TOKENIZER_LOAD_RETRY_SECONDS - 1
+ third_result: Final = _select_tokenizer_helper(model)
+ assert third_result["type"] == "openai_tokenizer"
+ assert mock_from_pretrained.call_count == 1
+
+ mock_monotonic.return_value = 322.0 + HUGGINGFACE_TOKENIZER_LOAD_RETRY_SECONDS + 1
+ retried_result: Final = _select_tokenizer_helper(model)
+ assert retried_result["type"] == "huggingface_tokenizer"
+ assert retried_result["tokenizer"] is sentinel.tokenizer
+ assert mock_from_pretrained.call_count == 2
+ finally:
+ _load_huggingface_tokenizer.cache_clear()
+ _HUGGINGFACE_TOKENIZER_LOAD_FAILURES.flush_cache()
+
_CODE_SAMPLE: Final = " for item in items:\n total += item.price * item.quantity\n" * 20
@@ -1104,6 +1175,7 @@ def test_disable_hf_tokenizer_download_keeps_deepseek_v4_on_cl100k(monkeypatch:
def test_concurrent_first_deepseek_counts_share_one_loaded_tokenizer():
_load_huggingface_tokenizer.cache_clear()
+ _HUGGINGFACE_TOKENIZER_LOAD_FAILURES.flush_cache()
start: Final = threading.Barrier(8)
def first_tokenizer(_: int) -> object:
@@ -1116,6 +1188,44 @@ def test_concurrent_first_deepseek_counts_share_one_loaded_tokenizer():
assert len({id(tokenizer) for tokenizer in tokenizers}) == 1
+def test_remembered_tokenizer_failure_warns_once_instead_of_on_every_count(caplog: pytest.LogCaptureFixture):
+ _load_huggingface_tokenizer.cache_clear()
+ _HUGGINGFACE_TOKENIZER_LOAD_FAILURES.flush_cache()
+ model: Final = "databricks/databricks-meta-llama-3-3-70b-instruct"
+ try:
+ with (
+ patch("litellm.utils.tokenizer_dispatch.from_pretrained", side_effect=RuntimeError("HF unavailable")),
+ caplog.at_level("WARNING", logger="LiteLLM"),
+ ):
+ types: Final = tuple(_select_tokenizer_helper(model)["type"] for _ in range(3))
+ fallback_warnings: Final = [r for r in caplog.records if "token counts may be approximate" in r.getMessage()]
+ assert types == ("openai_tokenizer",) * 3
+ assert len(fallback_warnings) == 1
+ finally:
+ _load_huggingface_tokenizer.cache_clear()
+ _HUGGINGFACE_TOKENIZER_LOAD_FAILURES.flush_cache()
+
+
+def test_fork_guard_error_while_loading_a_tokenizer_is_raised_and_not_remembered():
+ from litellm.rust_bridge.fork_guard import ForkedAfterNativeRuntimeStarted
+
+ _load_huggingface_tokenizer.cache_clear()
+ _HUGGINGFACE_TOKENIZER_LOAD_FAILURES.flush_cache()
+ model: Final = "databricks/databricks-meta-llama-3-3-70b-instruct"
+ forked: Final = ForkedAfterNativeRuntimeStarted("native runtime started before fork")
+ try:
+ with patch("litellm.utils.tokenizer_dispatch.from_pretrained", side_effect=forked):
+ with pytest.raises(ForkedAfterNativeRuntimeStarted):
+ _select_tokenizer_helper(model)
+ with patch("litellm.utils.tokenizer_dispatch.from_pretrained", return_value=sentinel.tokenizer):
+ loaded: Final = _select_tokenizer_helper(model)
+ assert loaded["type"] == "huggingface_tokenizer"
+ assert loaded["tokenizer"] is sentinel.tokenizer
+ finally:
+ _load_huggingface_tokenizer.cache_clear()
+ _HUGGINGFACE_TOKENIZER_LOAD_FAILURES.flush_cache()
+
+
def test_token_counter_with_anthropic_tool_use():
"""
Test that _count_anthropic_content() correctly handles tool_use blocks.
diff --git a/tests/unit/litellm_core_utils/test_tokenizer.py b/tests/unit/litellm_core_utils/test_tokenizer.py
index 354c91920fc..61e797d7166 100644
--- a/tests/unit/litellm_core_utils/test_tokenizer.py
+++ b/tests/unit/litellm_core_utils/test_tokenizer.py
@@ -406,16 +406,26 @@ def test_huggingface_encoding_exposes_the_tokenizers_lookup_and_mutation_surface
@pytest.mark.parametrize("log_level", ["WARNING", "ERROR"])
def test_missing_python_tokenizer_warns_before_approximate_count(caplog, monkeypatch, log_level):
from unittest.mock import patch
- from litellm.utils import _load_huggingface_tokenizer, _select_tokenizer_helper
+
+ from litellm.utils import (
+ _HUGGINGFACE_TOKENIZER_LOAD_FAILURES,
+ _load_huggingface_tokenizer,
+ _select_tokenizer_helper,
+ )
monkeypatch.setenv("LITELLM_RUST", "false")
_load_huggingface_tokenizer.cache_clear()
- with caplog.at_level(log_level, logger="LiteLLM"), patch.dict(sys.modules, {"tokenizers": None}):
- result = _select_tokenizer_helper("llama-2")
- assert result["type"] == "openai_tokenizer"
- assert result["tokenizer"].encode("hello")
- assert ("token counts may be approximate" in caplog.text) is (log_level == "WARNING")
- assert ("install tokenizers" in caplog.text) is (log_level == "WARNING")
+ _HUGGINGFACE_TOKENIZER_LOAD_FAILURES.flush_cache()
+ try:
+ with caplog.at_level(log_level, logger="LiteLLM"), patch.dict(sys.modules, {"tokenizers": None}):
+ result = _select_tokenizer_helper("llama-2")
+ assert result["type"] == "openai_tokenizer"
+ assert result["tokenizer"].encode("hello")
+ assert ("token counts may be approximate" in caplog.text) is (log_level == "WARNING")
+ assert ("install tokenizers" in caplog.text) is (log_level == "WARNING")
+ finally:
+ _load_huggingface_tokenizer.cache_clear()
+ _HUGGINGFACE_TOKENIZER_LOAD_FAILURES.flush_cache()
@pytest.mark.parametrize("python_installed", [False, True])
@@ -471,10 +481,16 @@ def test_added_token_return_annotation_resolves_without_optional_import(python_i
def test_tokenizer_fallback_logs_safe_diagnostic_context(caplog, monkeypatch):
from types import SimpleNamespace
from unittest.mock import patch
- from litellm.utils import _load_huggingface_tokenizer, _select_tokenizer_helper
+
+ from litellm.utils import (
+ _HUGGINGFACE_TOKENIZER_LOAD_FAILURES,
+ _load_huggingface_tokenizer,
+ _select_tokenizer_helper,
+ )
monkeypatch.setenv("LITELLM_RUST", "false")
_load_huggingface_tokenizer.cache_clear()
+ _HUGGINGFACE_TOKENIZER_LOAD_FAILURES.flush_cache()
model = "llama-2\r\nforged-model\x1b[31m\u2028\u2029"
secret = "sk-" + "x" * 48
failure = OSError("download failed\r\nforged-error\x1b[31m api_key=" + secret)
@@ -483,18 +499,26 @@ def test_tokenizer_fallback_logs_safe_diagnostic_context(caplog, monkeypatch):
raise failure
dependency = SimpleNamespace(Tokenizer=SimpleNamespace(from_pretrained=fail_download))
- with caplog.at_level("WARNING", logger="LiteLLM"), patch.dict(sys.modules, {"tokenizers": dependency}):
- result = _select_tokenizer_helper(model)
- assert result["type"] == "openai_tokenizer"
- assert result["tokenizer"].encode("hello")
- message = next(record.getMessage() for record in caplog.records if "token counts may be approximate" in record.getMessage())
- assert "llama-2" in message
- assert "download failed" in message
- assert "forged-model" in message and "forged-error" in message
- assert message.isascii() and message.isprintable()
- assert secret not in message
- assert "REDACTED" in message
- assert "install tokenizers and huggingface-hub" in message
+ try:
+ with caplog.at_level("WARNING", logger="LiteLLM"), patch.dict(sys.modules, {"tokenizers": dependency}):
+ result = _select_tokenizer_helper(model)
+ assert result["type"] == "openai_tokenizer"
+ assert result["tokenizer"].encode("hello")
+ message = next(
+ record.getMessage()
+ for record in caplog.records
+ if "token counts may be approximate" in record.getMessage()
+ )
+ assert "llama-2" in message
+ assert "download failed" in message
+ assert "forged-model" in message and "forged-error" in message
+ assert message.isascii() and message.isprintable()
+ assert secret not in message
+ assert "REDACTED" in message
+ assert "install tokenizers and huggingface-hub" in message
+ finally:
+ _load_huggingface_tokenizer.cache_clear()
+ _HUGGINGFACE_TOKENIZER_LOAD_FAILURES.flush_cache()
@pytest.mark.parametrize("python_installed", [False, True])
diff --git a/tests/unit/llms/huggingface/chat/test_huggingface_chat_transformation.py b/tests/unit/llms/huggingface/chat/test_huggingface_chat_transformation.py
index 2f1b3764610..04c2ce153c6 100644
--- a/tests/unit/llms/huggingface/chat/test_huggingface_chat_transformation.py
+++ b/tests/unit/llms/huggingface/chat/test_huggingface_chat_transformation.py
@@ -10,6 +10,7 @@ import respx
import litellm
from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler, HTTPHandler
from litellm.llms.huggingface.common_utils import _fetch_inference_provider_mapping
+from litellm.utils import _HUGGINGFACE_TOKENIZER_LOAD_FAILURES, _load_huggingface_tokenizer
HUGGINGFACE_MODEL: Final = "meta-llama/Meta-Llama-3-8B-Instruct"
HUGGINGFACE_ROUTER_MODEL: Final = "meta-llama/Meta-Llama-3-8B-Instruct-Turbo"
@@ -83,9 +84,13 @@ def isolate_huggingface_environment(monkeypatch: pytest.MonkeyPatch) -> Iterator
monkeypatch.delenv("HF_API_BASE", raising=False)
monkeypatch.delenv("HUGGINGFACE_API_BASE", raising=False)
monkeypatch.delenv("HUGGINGFACE_API_KEY", raising=False)
+ _load_huggingface_tokenizer.cache_clear()
+ _HUGGINGFACE_TOKENIZER_LOAD_FAILURES.flush_cache()
_fetch_inference_provider_mapping.cache_clear()
yield
_fetch_inference_provider_mapping.cache_clear()
+ _load_huggingface_tokenizer.cache_clear()
+ _HUGGINGFACE_TOKENIZER_LOAD_FAILURES.flush_cache()
PROVIDER_MAPPING_RESPONSE = {