Decorator Pattern
Why Decorator Pattern for LLM?
Key LLM Use Cases
1. Response Caching Strategy
import functools
import hashlib
import json
from typing import Dict, Any, Optional
class LLMCache:
def __init__(self, max_size: int = 1000, ttl: int = 3600):
self.cache: Dict[str, Dict[str, Any]] = {}
self.max_size = max_size
self.ttl = ttl # Time to live in seconds
def _generate_key(self, *args, **kwargs) -> str:
"""Generate cache key from function arguments"""
key_data = {'args': str(args), 'kwargs': kwargs}
return hashlib.md5(json.dumps(key_data, sort_keys=True).encode()).hexdigest()
def get(self, key: str) -> Optional[Any]:
"""Get cached value if exists and not expired"""
if key in self.cache:
entry = self.cache[key]
if time.time() - entry['timestamp'] < self.ttl:
return entry['value']
else:
del self.cache[key] # Remove expired entry
return None
def set(self, key: str, value: Any):
"""Set cache value with timestamp"""
if len(self.cache) >= self.max_size:
# Remove oldest entry
oldest_key = min(self.cache.keys(), key=lambda k: self.cache[k]['timestamp'])
del self.cache[oldest_key]
self.cache[key] = {
'value': value,
'timestamp': time.time()
}
def cache_llm_response(cache_instance: Optional[LLMCache] = None):
"""Decorator to cache LLM responses"""
if cache_instance is None:
cache_instance = LLMCache()
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
# Generate cache key
cache_key = cache_instance._generate_key(*args, **kwargs)
# Check cache first
cached_result = cache_instance.get(cache_key)
if cached_result is not None:
print(f"π― Cache hit! Saved API call")
return cached_result
# Call original function
print(f"π Making API call...")
result = func(*args, **kwargs)
# Store in cache
cache_instance.set(cache_key, result)
print(f"πΎ Response cached")
return result
wrapper.cache = cache_instance # Expose cache for debugging
return wrapper
return decorator
# Usage example
@cache_llm_response()
def call_llm(prompt: str, model: str = "gpt-4") -> str:
# Simulate expensive LLM API call
time.sleep(2) # Simulate network delay
return f"Response to: {prompt[:50]}..."2. Retry and Resilience Decorator
3. Cost Tracking Decorator
4. Performance Monitoring Decorator
Implementation Advantages
1. Separation of Concerns
2. Composability
3. Transparency
4. Configuration Flexibility
Real-World Impact
π Interactive Implementation
Last updated