Files
auto-ragas/rag_evaluation/evaluation/cache.py
T
2026-01-16 16:01:39 +08:00

400 lines
11 KiB
Python

"""
Evaluation result cache management
"""
from typing import Dict, Any, Optional, List
from pathlib import Path
import json
import hashlib
import pickle
from datetime import datetime, timedelta
import threading
class CacheKey:
"""缓存键生成器"""
@staticmethod
def generate_question_key(
question: str,
rag_config: Optional[Dict[str, Any]] = None,
retrieval_params: Optional[Dict[str, Any]] = None
) -> str:
"""
为单个问题生成缓存键
Args:
question: 问题文本
rag_config: RAG配置(可选)
retrieval_params: 检索参数(可选)
Returns:
缓存键(MD5哈希)
"""
# 创建规范化数据
data = {
'question': question.strip().lower(),
'rag_config': rag_config or {},
'retrieval_params': retrieval_params or {}
}
# 序列化为JSON
data_str = json.dumps(data, sort_keys=True)
# 生成MD5哈希
return hashlib.md5(data_str.encode('utf-8')).hexdigest()
@staticmethod
def generate_testset_key(
testset_id: str,
knowledge_base_id: str,
evaluation_config: Optional[Dict[str, Any]] = None
) -> str:
"""
为测评集评估生成缓存键
Args:
testset_id: 测评集ID
knowledge_base_id: 知识库ID
evaluation_config: 评估配置(可选)
Returns:
缓存键
"""
data = {
'testset_id': testset_id,
'knowledge_base_id': knowledge_base_id,
'evaluation_config': evaluation_config or {}
}
data_str = json.dumps(data, sort_keys=True)
return hashlib.md5(data_str.encode('utf-8')).hexdigest()
class EvaluationCache:
"""评估结果缓存管理器"""
def __init__(self, cache_dir: str, ttl_seconds: int = 86400):
"""
初始化缓存管理器
Args:
cache_dir: 缓存目录
ttl_seconds: 缓存过期时间(秒),默认24小时
"""
self.cache_dir = Path(cache_dir)
self.cache_dir.mkdir(parents=True, exist_ok=True)
self.ttl_seconds = ttl_seconds
self._lock = threading.Lock()
def _get_cache_path(self, cache_key: str) -> Path:
"""获取缓存文件路径"""
return self.cache_dir / f"{cache_key}.cache"
def get(self, cache_key: str) -> Optional[Dict[str, Any]]:
"""
从缓存获取结果
Args:
cache_key: 缓存键
Returns:
缓存的结果,如果不存在或已过期则返回None
"""
cache_path = self._get_cache_path(cache_key)
if not cache_path.exists():
return None
try:
with open(cache_path, 'rb') as f:
cache_data = pickle.load(f)
# 检查是否过期
cached_at = cache_data.get('cached_at')
if cached_at:
cache_age = (datetime.now() - cached_at).total_seconds()
if cache_age > self.ttl_seconds:
# 缓存已过期,删除文件
cache_path.unlink()
return None
return cache_data.get('data')
except (pickle.PickleError, EOFError, KeyError):
# 缓存文件损坏,删除并返回None
if cache_path.exists():
cache_path.unlink()
return None
def set(self, cache_key: str, data: Dict[str, Any]) -> None:
"""
将结果存入缓存
Args:
cache_key: 缓存键
data: 要缓存的数据
"""
cache_path = self._get_cache_path(cache_key)
cache_data = {
'cached_at': datetime.now(),
'data': data
}
with self._lock:
try:
with open(cache_path, 'wb') as f:
pickle.dump(cache_data, f)
except (IOError, pickle.PickleError) as e:
print(f"Warning: Failed to write cache: {e}")
def delete(self, cache_key: str) -> bool:
"""
删除缓存
Args:
cache_key: 缓存键
Returns:
是否成功删除
"""
cache_path = self._get_cache_path(cache_key)
if cache_path.exists():
try:
cache_path.unlink()
return True
except IOError:
return False
return False
def clear(self) -> int:
"""
清空所有缓存
Returns:
删除的缓存文件数量
"""
count = 0
for cache_file in self.cache_dir.glob("*.cache"):
try:
cache_file.unlink()
count += 1
except IOError:
pass
return count
def clear_expired(self) -> int:
"""
清理过期的缓存
Returns:
删除的缓存文件数量
"""
count = 0
now = datetime.now()
for cache_file in self.cache_dir.glob("*.cache"):
try:
with open(cache_file, 'rb') as f:
cache_data = pickle.load(f)
cached_at = cache_data.get('cached_at')
if cached_at:
cache_age = (now - cached_at).total_seconds()
if cache_age > self.ttl_seconds:
cache_file.unlink()
count += 1
except (pickle.PickleError, EOFError, IOError):
# 损坏的文件也删除
try:
cache_file.unlink()
count += 1
except IOError:
pass
return count
def get_stats(self) -> Dict[str, Any]:
"""
获取缓存统计信息
Returns:
统计信息字典
"""
total_files = 0
total_size = 0
expired_files = 0
now = datetime.now()
for cache_file in self.cache_dir.glob("*.cache"):
total_files += 1
total_size += cache_file.stat().st_size
try:
with open(cache_file, 'rb') as f:
cache_data = pickle.load(f)
cached_at = cache_data.get('cached_at')
if cached_at:
cache_age = (now - cached_at).total_seconds()
if cache_age > self.ttl_seconds:
expired_files += 1
except (pickle.PickleError, EOFError):
pass
return {
'total_files': total_files,
'total_size_bytes': total_size,
'total_size_mb': total_size / (1024 * 1024),
'expired_files': expired_files,
'active_files': total_files - expired_files,
'ttl_seconds': self.ttl_seconds
}
class CachedEvaluationExecutor:
"""带缓存的评估执行器装饰器"""
def __init__(
self,
cache: EvaluationCache,
rag_config: Optional[Dict[str, Any]] = None,
retrieval_params: Optional[Dict[str, Any]] = None
):
"""
初始化缓存执行器
Args:
cache: 缓存管理器
rag_config: RAG配置
retrieval_params: 检索参数
"""
self.cache = cache
self.rag_config = rag_config or {}
self.retrieval_params = retrieval_params or {}
self._cache_hits = 0
self._cache_misses = 0
def evaluate_question(
self,
question: str,
evaluation_func: callable
) -> Dict[str, Any]:
"""
评估问题(带缓存)
Args:
question: 问题文本
evaluation_func: 评估函数(缓存未命中时调用)
Returns:
评估结果
"""
# 生成缓存键
cache_key = CacheKey.generate_question_key(
question=question,
rag_config=self.rag_config,
retrieval_params=self.retrieval_params
)
# 尝试从缓存获取
cached_result = self.cache.get(cache_key)
if cached_result is not None:
self._cache_hits += 1
return cached_result
# 缓存未命中,执行评估
self._cache_misses += 1
result = evaluation_func(question)
# 存入缓存
self.cache.set(cache_key, result)
return result
def evaluate_batch(
self,
questions: List[str],
evaluation_func: callable
) -> List[Dict[str, Any]]:
"""
批量评估问题(带缓存)
Args:
questions: 问题列表
evaluation_func: 评估函数
Returns:
评估结果列表
"""
results = []
questions_to_eval = []
indices_to_eval = []
# 第一遍:检查缓存
for i, question in enumerate(questions):
cache_key = CacheKey.generate_question_key(
question=question,
rag_config=self.rag_config,
retrieval_params=self.retrieval_params
)
cached_result = self.cache.get(cache_key)
if cached_result is not None:
self._cache_hits += 1
results.append((i, cached_result))
else:
self._cache_misses += 1
questions_to_eval.append(question)
indices_to_eval.append(i)
# 第二遍:评估未缓存的问题
if questions_to_eval:
eval_results = evaluation_func(questions_to_eval)
for question, result in zip(questions_to_eval, eval_results):
# 存入缓存
cache_key = CacheKey.generate_question_key(
question=question,
rag_config=self.rag_config,
retrieval_params=self.retrieval_params
)
self.cache.set(cache_key, result)
# 添加到结果列表
for idx, result in zip(indices_to_eval, eval_results):
results.append((idx, result))
# 按原始顺序排序
results.sort(key=lambda x: x[0])
return [result for _, result in results]
def get_cache_stats(self) -> Dict[str, Any]:
"""
获取缓存统计信息
Returns:
统计信息字典
"""
stats = self.cache.get_stats()
stats['cache_hits'] = self._cache_hits
stats['cache_misses'] = self._cache_misses
total_requests = self._cache_hits + self._cache_misses
if total_requests > 0:
stats['hit_rate'] = self._cache_hits / total_requests
else:
stats['hit_rate'] = 0.0
return stats
def reset_stats(self) -> None:
"""重置统计信息"""
self._cache_hits = 0
self._cache_misses = 0