|
| 1 | +"""LLM caching configuration for the evaluator. |
| 2 | +
|
| 3 | +This module provides centralized caching setup for all LLM calls in the evaluator. |
| 4 | +Uses LiteLLM's built-in disk caching to reduce API costs and speed up repeated runs. |
| 5 | +""" |
| 6 | + |
| 7 | +import os |
| 8 | +import litellm |
| 9 | +from pathlib import Path |
| 10 | +from typing import Optional |
| 11 | + |
| 12 | +# ANSI color codes for terminal output |
| 13 | +class Colors: |
| 14 | + """ANSI color codes for terminal output.""" |
| 15 | + GREEN = '\033[92m' |
| 16 | + YELLOW = '\033[93m' |
| 17 | + BLUE = '\033[94m' |
| 18 | + RESET = '\033[0m' |
| 19 | + |
| 20 | + |
| 21 | +# Global flags to track cache state |
| 22 | +_cache_initialized = False |
| 23 | +_cache_disabled = False |
| 24 | + |
| 25 | + |
| 26 | +def disable_cache(verbose: bool = True) -> None: |
| 27 | + """Globally disable LLM caching. |
| 28 | + |
| 29 | + Call this BEFORE any init_cache() calls to prevent caching. |
| 30 | + Once disabled, init_cache() becomes a no-op. |
| 31 | + |
| 32 | + Args: |
| 33 | + verbose: Whether to print status message |
| 34 | + """ |
| 35 | + global _cache_disabled |
| 36 | + _cache_disabled = True |
| 37 | + if verbose: |
| 38 | + print(f"{Colors.YELLOW}⚠ LLM caching disabled globally{Colors.RESET}") |
| 39 | + |
| 40 | + |
| 41 | +def is_cache_disabled() -> bool: |
| 42 | + """Check if caching has been globally disabled.""" |
| 43 | + return _cache_disabled |
| 44 | + |
| 45 | + |
| 46 | +def get_cache_dir() -> Path: |
| 47 | + """Get the cache directory path. |
| 48 | + |
| 49 | + Returns: |
| 50 | + Path to the cache directory (defaults to .litellm_cache in project root) |
| 51 | + """ |
| 52 | + cache_dir = os.getenv("LITELLM_CACHE_DIR", ".litellm_cache") |
| 53 | + return Path(cache_dir) |
| 54 | + |
| 55 | + |
| 56 | +def init_cache( |
| 57 | + cache_type: str = "disk", |
| 58 | + cache_dir: Optional[str] = None, |
| 59 | + ttl: Optional[int] = None, |
| 60 | + verbose: bool = True |
| 61 | +) -> bool: |
| 62 | + """Initialize LiteLLM caching. |
| 63 | + |
| 64 | + This should be called once at startup. Subsequent calls are no-ops. |
| 65 | + If caching has been globally disabled via disable_cache() or the |
| 66 | + LITELLM_CACHE_DISABLED environment variable is set to "true", this is a no-op. |
| 67 | + |
| 68 | + Args: |
| 69 | + cache_type: Type of cache ("disk", "redis", "s3", or "local" for in-memory) |
| 70 | + cache_dir: Directory for disk cache (default: .litellm_cache) |
| 71 | + ttl: Time-to-live for cache entries in seconds (default: None = forever) |
| 72 | + verbose: Whether to print cache initialization status |
| 73 | + |
| 74 | + Returns: |
| 75 | + True if cache was initialized, False if already initialized or disabled |
| 76 | + """ |
| 77 | + global _cache_initialized, _cache_disabled |
| 78 | + |
| 79 | + # Check environment variable for cache disable |
| 80 | + env_disabled = os.getenv("LITELLM_CACHE_DISABLED", "").lower() in ("true", "1", "yes") |
| 81 | + if env_disabled and not _cache_disabled: |
| 82 | + _cache_disabled = True |
| 83 | + if verbose: |
| 84 | + print(f"{Colors.YELLOW}⚠ LLM caching disabled via LITELLM_CACHE_DISABLED{Colors.RESET}") |
| 85 | + |
| 86 | + # Respect global disable flag |
| 87 | + if _cache_disabled: |
| 88 | + return False |
| 89 | + |
| 90 | + if _cache_initialized: |
| 91 | + if verbose: |
| 92 | + print(f"{Colors.YELLOW}⚠ LLM cache already initialized{Colors.RESET}") |
| 93 | + return False |
| 94 | + |
| 95 | + # Set cache directory |
| 96 | + if cache_dir is None: |
| 97 | + cache_dir = str(get_cache_dir()) |
| 98 | + |
| 99 | + # Ensure cache directory exists for disk cache |
| 100 | + if cache_type == "disk": |
| 101 | + Path(cache_dir).mkdir(parents=True, exist_ok=True) |
| 102 | + |
| 103 | + # Configure LiteLLM cache |
| 104 | + cache_params = { |
| 105 | + "type": cache_type, |
| 106 | + } |
| 107 | + |
| 108 | + if cache_type == "disk": |
| 109 | + cache_params["disk_cache_dir"] = cache_dir |
| 110 | + |
| 111 | + if ttl is not None: |
| 112 | + cache_params["ttl"] = ttl |
| 113 | + |
| 114 | + # Initialize the cache |
| 115 | + litellm.cache = litellm.Cache(**cache_params) |
| 116 | + |
| 117 | + # Enable caching globally |
| 118 | + litellm.enable_cache() |
| 119 | + |
| 120 | + _cache_initialized = True |
| 121 | + |
| 122 | + if verbose: |
| 123 | + print(f"{Colors.GREEN}✓ LLM caching enabled{Colors.RESET}") |
| 124 | + print(f" Type: {cache_type}") |
| 125 | + if cache_type == "disk": |
| 126 | + print(f" Directory: {cache_dir}") |
| 127 | + if ttl: |
| 128 | + print(f" TTL: {ttl}s") |
| 129 | + |
| 130 | + return True |
| 131 | + |
| 132 | + |
| 133 | +def is_cache_enabled() -> bool: |
| 134 | + """Check if caching is currently enabled. |
| 135 | + |
| 136 | + Returns: |
| 137 | + True if caching is enabled |
| 138 | + """ |
| 139 | + return _cache_initialized and litellm.cache is not None |
| 140 | + |
| 141 | + |
| 142 | +def get_cache_stats() -> dict: |
| 143 | + """Get cache statistics (if available). |
| 144 | + |
| 145 | + Returns: |
| 146 | + Dictionary with cache statistics including disk cache info |
| 147 | + """ |
| 148 | + stats = { |
| 149 | + "initialized": _cache_initialized, |
| 150 | + } |
| 151 | + |
| 152 | + # Always check disk cache stats (even if not initialized in this process) |
| 153 | + cache_dir = get_cache_dir() |
| 154 | + if cache_dir.exists(): |
| 155 | + cache_files = list(cache_dir.glob("*")) |
| 156 | + stats["cache_dir"] = str(cache_dir) |
| 157 | + stats["cache_files"] = len(cache_files) |
| 158 | + stats["cache_size_bytes"] = sum(f.stat().st_size for f in cache_files if f.is_file()) |
| 159 | + stats["cache_size_mb"] = round(stats["cache_size_bytes"] / (1024 * 1024), 2) |
| 160 | + stats["has_cache"] = stats["cache_files"] > 0 |
| 161 | + else: |
| 162 | + stats["cache_dir"] = str(cache_dir) |
| 163 | + stats["cache_files"] = 0 |
| 164 | + stats["cache_size_mb"] = 0 |
| 165 | + stats["has_cache"] = False |
| 166 | + |
| 167 | + return stats |
| 168 | + |
| 169 | + |
| 170 | +def clear_cache(verbose: bool = True) -> bool: |
| 171 | + """Clear the LLM cache. |
| 172 | + |
| 173 | + Args: |
| 174 | + verbose: Whether to print status |
| 175 | + |
| 176 | + Returns: |
| 177 | + True if cache was cleared successfully |
| 178 | + """ |
| 179 | + import shutil |
| 180 | + |
| 181 | + cache_dir = get_cache_dir() |
| 182 | + |
| 183 | + if cache_dir.exists(): |
| 184 | + # Get stats before clearing |
| 185 | + files_count = len(list(cache_dir.glob("*"))) |
| 186 | + |
| 187 | + # Remove cache directory |
| 188 | + shutil.rmtree(cache_dir) |
| 189 | + cache_dir.mkdir(parents=True, exist_ok=True) |
| 190 | + |
| 191 | + if verbose: |
| 192 | + print(f"{Colors.GREEN}✓ Cache cleared ({files_count} files removed){Colors.RESET}") |
| 193 | + return True |
| 194 | + else: |
| 195 | + if verbose: |
| 196 | + print(f"{Colors.YELLOW}⚠ Cache directory does not exist{Colors.RESET}") |
| 197 | + return False |
| 198 | + |
| 199 | + |
| 200 | +def print_cache_status(): |
| 201 | + """Print current cache status to console.""" |
| 202 | + stats = get_cache_stats() |
| 203 | + |
| 204 | + print(f"\n{Colors.BLUE}=== LLM Cache Status ==={Colors.RESET}") |
| 205 | + print(f" Directory: {stats.get('cache_dir', 'N/A')}") |
| 206 | + print(f" Has cached data: {stats.get('has_cache', False)}") |
| 207 | + print(f" Files: {stats.get('cache_files', 0)}") |
| 208 | + print(f" Size: {stats.get('cache_size_mb', 0)} MB") |
| 209 | + print() |
0 commit comments