Cache
CacheInterface
Bases: ABC
Abstract base class defining the interface for cache implementations.
This class provides a standard interface that all cache implementations must follow. It supports basic cache operations like get, set and key checking.
get
abstractmethod
Retrieve a value from the cache by key.
Args: key: The key to look up in the cache.
Returns: The cached value associated with the key.
set
abstractmethod
Store a value in the cache with the given key.
Args: key: The key to store the value under. value: The value to cache.
has_key
abstractmethod
Check if a key exists in the cache.
Args: key: The key to check for.
Returns: True if the key exists in the cache, False otherwise.
DiskCacheBackend
Bases: CacheInterface
A cache implementation that stores data on disk using the diskcache library.
This cache backend persists data to disk, allowing it to survive between program runs. It implements the CacheInterface for use with Ragas caching functionality.
Args: cache_dir (str, optional): Directory where cache files will be stored. Defaults to ".cache".
Source code in src/ragas/cache.py
get
Retrieve a value from the disk cache by key.
Args: key: The key to look up in the cache.
Returns: The cached value associated with the key, or None if not found.
set
Store a value in the disk cache with the given key.
Args: key: The key to store the value under. value: The value to cache.
has_key
Check if a key exists in the disk cache.
Args: key: The key to check for.
Returns: True if the key exists in the cache, False otherwise.
cache_identity
What distinguishes obj's outputs from another instance's (#72).
Cached methods are wrapped as bound methods, so self never reaches
the key. Without this, two wrappers for different models sharing one cache
backend returned each other's responses (or embeddings).
Source code in src/ragas/cache.py
cacher
cacher(
cache_backend: Optional[CacheInterface] = None,
identity: Optional[Callable[[], Any]] = None,
)
Decorator that adds caching functionality to a function.
This decorator can be applied to both synchronous and asynchronous functions to cache their results. If no cache backend is provided, the original function is returned unchanged.
Args:
cache_backend (Optional[CacheInterface]): The cache backend to use for storing results.
If None, caching is disabled.
identity (Optional[Callable[[], Any]]): Called on every lookup; its result
is part of the key. Pass lambda: cache_identity(self) when wrapping
a bound method so instances configured differently (model, provider,
endpoint, sampling args) never share entries.
Returns: Callable: A decorated function that implements caching behavior.