Implementation:Explodinggradients Ragas CacheInterface And DiskCacheBackend
| Knowledge Sources | |
|---|---|
| Domains | Caching, Performance |
| Last Updated | 2026-02-10 00:00 GMT |
Overview
Caching framework providing an abstract CacheInterface and a concrete DiskCacheBackend for persisting LLM call results to disk.
Description
The caching module defines CacheInterface (abstract base) and DiskCacheBackend (disk-based via diskcache library). The cacher decorator adds transparent caching to sync/async functions, generating SHA256 cache keys from function name and arguments. This avoids redundant LLM calls during evaluation.
Usage
Use DiskCacheBackend to cache LLM responses across runs. Wrap functions with the cacher decorator to enable automatic caching.
Code Reference
Source Location
- Repository: Explodinggradients_Ragas
- File: src/ragas/cache.py
- Lines: 16-249
Signature
class CacheInterface(ABC):
@abstractmethod
def get(self, key: str) -> Any:
...
@abstractmethod
def set(self, key: str, value: Any) -> None:
...
@abstractmethod
def has_key(self, key: str) -> bool:
...
class DiskCacheBackend(CacheInterface):
def __init__(self, cache_dir: str = ".cache") -> None:
...
def cacher(cache_backend: Optional[CacheInterface]) -> Callable:
...
Import
from ragas.cache import CacheInterface, DiskCacheBackend, cacher
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| cache_dir | str | No | Directory for disk cache storage (default ".cache") |
| key | str | Yes | Cache key for get/set operations |
| value | Any | Yes (for set) | Value to cache |
Outputs
| Name | Type | Description |
|---|---|---|
| get returns | Any | Cached value |
| has_key returns | bool | Whether key exists in cache |
| cacher returns | Callable | Decorated function with caching |
Usage Examples
from ragas.cache import DiskCacheBackend
# Create a disk cache
cache = DiskCacheBackend(cache_dir=".ragas_cache")
# Store and retrieve values
cache.set("my_key", {"result": 0.95})
if cache.has_key("my_key"):
result = cache.get("my_key")
print(result) # {"result": 0.95}