Files
litellm/litellm/caching/llm_caching_handler.py
T
Marc AbramowitzandGitHub 2f3f076079 Fix pytest event loop warning (#10512)
Fixes: GH-9641

This is a Cursor-generated fix for the following warning from pytest:

```
litellm/caching/llm_caching_handler.py:17
  /Users/abramowi/Code/OpenSource/litellm/litellm/caching/llm_caching_handler.py:17: DeprecationWarning: There is no current event loop
    event_loop = asyncio.get_event_loop()
```

Cursor prompt:

  Fix this pytest warning
  ```
  litellm/caching/llm_caching_handler.py:17
    /Users/abramowi/Code/OpenSource/litellm/litellm/caching/llm_caching_handler.py:17: DeprecationWarning: There is no current event loop
      event_loop = asyncio.get_event_loop()
  ```

Fixes https://github.com/BerriAI/litellm/issues/9641
2025-05-02 19:43:18 -07:00

40 lines
1.3 KiB
Python

"""
Add the event loop to the cache key, to prevent event loop closed errors.
"""
import asyncio
from .in_memory_cache import InMemoryCache
class LLMClientCache(InMemoryCache):
def update_cache_key_with_event_loop(self, key):
"""
Add the event loop to the cache key, to prevent event loop closed errors.
If none, use the key as is.
"""
try:
event_loop = asyncio.get_running_loop()
stringified_event_loop = str(id(event_loop))
return f"{key}-{stringified_event_loop}"
except RuntimeError: # handle no current running event loop
return key
def set_cache(self, key, value, **kwargs):
key = self.update_cache_key_with_event_loop(key)
return super().set_cache(key, value, **kwargs)
async def async_set_cache(self, key, value, **kwargs):
key = self.update_cache_key_with_event_loop(key)
return await super().async_set_cache(key, value, **kwargs)
def get_cache(self, key, **kwargs):
key = self.update_cache_key_with_event_loop(key)
return super().get_cache(key, **kwargs)
async def async_get_cache(self, key, **kwargs):
key = self.update_cache_key_with_event_loop(key)
return await super().async_get_cache(key, **kwargs)