Initial commit
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
commit
4ecf7b351d
143 files changed
+24156
No files matched your search
@@ -0,0 +1,78 @@
|
||||
"""
|
||||
Evaluation module for RAG systems
|
||||
"""
|
||||
|
||||
from .rag_adapter import (
|
||||
RAGRetriever,
|
||||
RAGGenerator,
|
||||
HTTPRAGRetriever,
|
||||
HTTPRAGGenerator,
|
||||
MockRAGRetriever,
|
||||
MockRAGGenerator,
|
||||
RAGEvaluationAdapter,
|
||||
RetryConfig,
|
||||
retry_with_exponential_backoff
|
||||
)
|
||||
|
||||
from .metrics import (
|
||||
Metric,
|
||||
ContextRecall,
|
||||
ContextPrecision,
|
||||
MRR,
|
||||
NDCG,
|
||||
Faithfulness,
|
||||
AnswerRelevancy,
|
||||
Correctness,
|
||||
MetricsCalculator
|
||||
)
|
||||
|
||||
from .executor import EvaluationExecutor
|
||||
|
||||
from .parallel_executor import (
|
||||
ParallelExecutor,
|
||||
ParallelConfig,
|
||||
BatchEvaluator
|
||||
)
|
||||
|
||||
from .cache import (
|
||||
CacheKey,
|
||||
EvaluationCache,
|
||||
CachedEvaluationExecutor
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
# RAG Adapters
|
||||
"RAGRetriever",
|
||||
"RAGGenerator",
|
||||
"HTTPRAGRetriever",
|
||||
"HTTPRAGGenerator",
|
||||
"MockRAGRetriever",
|
||||
"MockRAGGenerator",
|
||||
"RAGEvaluationAdapter",
|
||||
"RetryConfig",
|
||||
"retry_with_exponential_backoff",
|
||||
|
||||
# Metrics
|
||||
"Metric",
|
||||
"ContextRecall",
|
||||
"ContextPrecision",
|
||||
"MRR",
|
||||
"NDCG",
|
||||
"Faithfulness",
|
||||
"AnswerRelevancy",
|
||||
"Correctness",
|
||||
"MetricsCalculator",
|
||||
|
||||
# Executor
|
||||
"EvaluationExecutor",
|
||||
|
||||
# Parallel Execution
|
||||
"ParallelExecutor",
|
||||
"ParallelConfig",
|
||||
"BatchEvaluator",
|
||||
|
||||
# Cache
|
||||
"CacheKey",
|
||||
"EvaluationCache",
|
||||
"CachedEvaluationExecutor",
|
||||
]
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,399 @@
|
||||
"""
|
||||
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
|
||||
@@ -0,0 +1,438 @@
|
||||
"""
|
||||
Evaluation executor for RAG systems
|
||||
"""
|
||||
|
||||
from typing import List, Dict, Any, Optional
|
||||
from datetime import datetime
|
||||
import json
|
||||
|
||||
from ..core.config import Config
|
||||
from ..storage.database import DatabaseManager
|
||||
from ..utils.helpers import generate_id, generate_biz_seq, generate_sys_seq, format_datetime
|
||||
from .rag_adapter import RAGEvaluationAdapter
|
||||
from .metrics import MetricsCalculator
|
||||
from .parallel_executor import ParallelExecutor, ParallelConfig, BatchEvaluator, parallel_evaluator_wrapper
|
||||
|
||||
|
||||
class EvaluationExecutor:
|
||||
"""Executor for RAG evaluation tasks"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: Config,
|
||||
rag_adapter: RAGEvaluationAdapter,
|
||||
db_manager: Optional[DatabaseManager] = None
|
||||
):
|
||||
"""
|
||||
Initialize evaluation executor
|
||||
|
||||
Args:
|
||||
config: Configuration object
|
||||
rag_adapter: RAG evaluation adapter
|
||||
db_manager: Database manager (optional)
|
||||
"""
|
||||
self.config = config
|
||||
self.rag_adapter = rag_adapter
|
||||
self.db_manager = db_manager or DatabaseManager(config.database)
|
||||
self.metrics_calculator = MetricsCalculator()
|
||||
|
||||
def execute_evaluation(
|
||||
self,
|
||||
testset_id: str,
|
||||
knowledge_base_id: str,
|
||||
testset: Dict[str, Any]
|
||||
) -> str:
|
||||
"""
|
||||
Execute evaluation for a testset
|
||||
|
||||
Args:
|
||||
testset_id: Testset ID
|
||||
knowledge_base_id: Knowledge base ID
|
||||
testset: Testset dictionary
|
||||
|
||||
Returns:
|
||||
Evaluation ID
|
||||
"""
|
||||
# Create evaluation record
|
||||
evaluation_id = generate_id("eval")
|
||||
biz_seq = generate_biz_seq("EVAL")
|
||||
sys_seq = generate_sys_seq("EVAL")
|
||||
|
||||
# Insert evaluation record
|
||||
sql = """
|
||||
INSERT INTO evaluations (
|
||||
id, biz_seq, sys_seq, knowledge_base_id, testset_id,
|
||||
status, started_at, create_time
|
||||
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
||||
"""
|
||||
|
||||
now = datetime.now()
|
||||
self.db_manager.execute_update(
|
||||
sql,
|
||||
(
|
||||
evaluation_id, biz_seq, sys_seq, knowledge_base_id, testset_id,
|
||||
'running', now, now
|
||||
)
|
||||
)
|
||||
|
||||
try:
|
||||
# Execute evaluation for each question
|
||||
questions = testset.get('questions', [])
|
||||
results = []
|
||||
|
||||
for question_data in questions:
|
||||
result = self._evaluate_question(
|
||||
evaluation_id=evaluation_id,
|
||||
question_data=question_data
|
||||
)
|
||||
results.append(result)
|
||||
|
||||
# Calculate summary
|
||||
self._save_summary(evaluation_id, results)
|
||||
|
||||
# Update evaluation status
|
||||
self._update_evaluation_status(evaluation_id, 'completed')
|
||||
|
||||
except Exception as e:
|
||||
# Update evaluation status to failed
|
||||
self._update_evaluation_status(evaluation_id, 'failed', str(e))
|
||||
raise
|
||||
|
||||
return evaluation_id
|
||||
|
||||
def execute_evaluation_parallel(
|
||||
self,
|
||||
testset_id: str,
|
||||
knowledge_base_id: str,
|
||||
testset: Dict[str, Any],
|
||||
parallel_config: Optional[ParallelConfig] = None
|
||||
) -> str:
|
||||
"""
|
||||
Execute evaluation in parallel for better performance
|
||||
|
||||
Args:
|
||||
testset_id: Testset ID
|
||||
knowledge_base_id: Knowledge base ID
|
||||
testset: Testset dictionary
|
||||
parallel_config: Parallel execution config (optional)
|
||||
|
||||
Returns:
|
||||
Evaluation ID
|
||||
"""
|
||||
# Create evaluation record
|
||||
evaluation_id = generate_id("eval")
|
||||
biz_seq = generate_biz_seq("EVAL")
|
||||
sys_seq = generate_sys_seq("EVAL")
|
||||
|
||||
# Insert evaluation record
|
||||
sql = """
|
||||
INSERT INTO evaluations (
|
||||
id, biz_seq, sys_seq, knowledge_base_id, testset_id,
|
||||
status, started_at, create_time
|
||||
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
||||
"""
|
||||
|
||||
now = datetime.now()
|
||||
self.db_manager.execute_update(
|
||||
sql,
|
||||
(
|
||||
evaluation_id, biz_seq, sys_seq, knowledge_base_id, testset_id,
|
||||
'running', now, now
|
||||
)
|
||||
)
|
||||
|
||||
try:
|
||||
# Create parallel config
|
||||
if parallel_config is None:
|
||||
parallel_config = ParallelConfig(
|
||||
max_workers=self.config.evaluation.parallel_workers
|
||||
)
|
||||
|
||||
batch_evaluator = BatchEvaluator(parallel_config)
|
||||
|
||||
# Define evaluation function
|
||||
def evaluate_single_question(question_data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Evaluate a single question"""
|
||||
return self._evaluate_question(
|
||||
evaluation_id=evaluation_id,
|
||||
question_data=question_data
|
||||
)
|
||||
|
||||
# Execute evaluation in parallel
|
||||
questions = testset.get('questions', [])
|
||||
results = batch_evaluator.evaluate_questions_batch(
|
||||
questions=questions,
|
||||
evaluation_func=evaluate_single_question
|
||||
)
|
||||
|
||||
# Check for errors
|
||||
successful_results = [r for r in results if r.get('metrics') is not None]
|
||||
failed_count = len(results) - len(successful_results)
|
||||
|
||||
if failed_count > 0:
|
||||
print(f"Warning: {failed_count} questions failed to evaluate")
|
||||
|
||||
# Calculate summary
|
||||
self._save_summary(evaluation_id, successful_results)
|
||||
|
||||
# Update evaluation status
|
||||
self._update_evaluation_status(evaluation_id, 'completed')
|
||||
|
||||
except Exception as e:
|
||||
# Update evaluation status to failed
|
||||
self._update_evaluation_status(evaluation_id, 'failed', str(e))
|
||||
raise
|
||||
|
||||
return evaluation_id
|
||||
|
||||
def _evaluate_question(
|
||||
self,
|
||||
evaluation_id: str,
|
||||
question_data: Dict[str, Any]
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Evaluate a single question
|
||||
|
||||
Args:
|
||||
evaluation_id: Evaluation ID
|
||||
question_data: Question data from testset
|
||||
|
||||
Returns:
|
||||
Evaluation result
|
||||
"""
|
||||
question_text = question_data['question']
|
||||
question_index = question_data['index']
|
||||
ground_truth = question_data.get('ground_truth', )
|
||||
|
||||
# Execute RAG pipeline
|
||||
rag_result = self.rag_adapter.evaluate_question(question_text)
|
||||
|
||||
# Extract ground truth
|
||||
ground_truth_answer = ground_truth.get('answer', '')
|
||||
ground_truth_contexts = ground_truth.get('context', [])
|
||||
|
||||
# Calculate metrics
|
||||
retrieved_context_texts = rag_result['context_texts']
|
||||
generated_answer = rag_result['generated_answer']
|
||||
|
||||
metrics = self.metrics_calculator.calculate_all(
|
||||
question=question_text,
|
||||
retrieved_contexts=retrieved_context_texts,
|
||||
generated_answer=generated_answer,
|
||||
ground_truth_contexts=ground_truth_contexts,
|
||||
ground_truth_answer=ground_truth_answer
|
||||
)
|
||||
|
||||
# Save result to database
|
||||
result_id = generate_id("result")
|
||||
biz_seq = generate_biz_seq("RESULT")
|
||||
sys_seq = generate_sys_seq("RESULT")
|
||||
|
||||
sql = """
|
||||
INSERT INTO evaluation_results (
|
||||
id, biz_seq, sys_seq, evaluation_id, question_index, question_text,
|
||||
context_recall, context_precision, mrr, ndcg,
|
||||
faithfulness, answer_relevancy, correctness,
|
||||
retrieved_contexts, generated_answer, ground_truth_answer, ground_truth_context,
|
||||
retrieval_time_ms, generation_time_ms, create_time
|
||||
) VALUES (
|
||||
%s, %s, %s, %s, %s, %s,
|
||||
%s, %s, %s, %s,
|
||||
%s, %s, %s,
|
||||
%s, %s, %s, %s,
|
||||
%s, %s, %s
|
||||
)
|
||||
"""
|
||||
|
||||
now = datetime.now()
|
||||
self.db_manager.execute_update(
|
||||
sql,
|
||||
(
|
||||
result_id, biz_seq, sys_seq, evaluation_id, question_index, question_text,
|
||||
metrics['context_recall'], metrics['context_precision'],
|
||||
metrics['mrr'], metrics['ndcg'],
|
||||
metrics['faithfulness'], metrics['answer_relevancy'], metrics['correctness'],
|
||||
json.dumps(rag_result['retrieved_contexts']),
|
||||
generated_answer, ground_truth_answer,
|
||||
json.dumps(ground_truth_contexts),
|
||||
rag_result['retrieval_time_ms'], rag_result['generation_time_ms'],
|
||||
now
|
||||
)
|
||||
)
|
||||
|
||||
return {
|
||||
'result_id': result_id,
|
||||
'question_index': question_index,
|
||||
'metrics': metrics
|
||||
}
|
||||
|
||||
def _save_summary(self, evaluation_id: str, results: List[Dict[str, Any]]):
|
||||
"""
|
||||
Save evaluation summary
|
||||
|
||||
Args:
|
||||
evaluation_id: Evaluation ID
|
||||
results: List of evaluation results
|
||||
"""
|
||||
if not results:
|
||||
return
|
||||
|
||||
# Calculate averages
|
||||
total = len(results)
|
||||
failed = sum(1 for r in results if not r.get('metrics'))
|
||||
|
||||
avg_metrics = {
|
||||
'context_recall': 0.0,
|
||||
'context_precision': 0.0,
|
||||
'mrr': 0.0,
|
||||
'ndcg': 0.0,
|
||||
'faithfulness': 0.0,
|
||||
'answer_relevancy': 0.0,
|
||||
'correctness': 0.0
|
||||
}
|
||||
|
||||
for result in results:
|
||||
metrics = result.get('metrics', {})
|
||||
for key in avg_metrics:
|
||||
avg_metrics[key] += metrics.get(key, 0.0)
|
||||
|
||||
for key in avg_metrics:
|
||||
avg_metrics[key] /= total
|
||||
|
||||
# Calculate overall score (weighted average)
|
||||
overall_score = (
|
||||
avg_metrics['context_recall'] * 0.15 +
|
||||
avg_metrics['context_precision'] * 0.15 +
|
||||
avg_metrics['faithfulness'] * 0.25 +
|
||||
avg_metrics['answer_relevancy'] * 0.25 +
|
||||
avg_metrics['correctness'] * 0.20
|
||||
) * 100
|
||||
|
||||
# Save summary
|
||||
summary_id = generate_id("summary")
|
||||
biz_seq = generate_biz_seq("SUMMARY")
|
||||
sys_seq = generate_sys_seq("SUMMARY")
|
||||
|
||||
sql = """
|
||||
INSERT INTO evaluation_summaries (
|
||||
id, biz_seq, sys_seq, evaluation_id,
|
||||
avg_context_recall, avg_context_precision, avg_mrr, avg_ndcg,
|
||||
avg_faithfulness, avg_answer_relevancy, avg_correctness,
|
||||
overall_score, total_questions, failed_questions, create_time
|
||||
) VALUES (
|
||||
%s, %s, %s, %s,
|
||||
%s, %s, %s, %s,
|
||||
%s, %s, %s,
|
||||
%s, %s, %s, %s
|
||||
)
|
||||
"""
|
||||
|
||||
now = datetime.now()
|
||||
self.db_manager.execute_update(
|
||||
sql,
|
||||
(
|
||||
summary_id, biz_seq, sys_seq, evaluation_id,
|
||||
avg_metrics['context_recall'], avg_metrics['context_precision'],
|
||||
avg_metrics['mrr'], avg_metrics['ndcg'],
|
||||
avg_metrics['faithfulness'], avg_metrics['answer_relevancy'],
|
||||
avg_metrics['correctness'],
|
||||
overall_score, total, failed, now
|
||||
)
|
||||
)
|
||||
|
||||
def _update_evaluation_status(
|
||||
self,
|
||||
evaluation_id: str,
|
||||
status: str,
|
||||
error_message: Optional[str] = None
|
||||
):
|
||||
"""
|
||||
Update evaluation status
|
||||
|
||||
Args:
|
||||
evaluation_id: Evaluation ID
|
||||
status: New status
|
||||
error_message: Optional error message
|
||||
"""
|
||||
if status == 'completed':
|
||||
sql = """
|
||||
UPDATE evaluations
|
||||
SET status = %s, completed_at = %s
|
||||
WHERE id = %s
|
||||
"""
|
||||
self.db_manager.execute_update(sql, (status, datetime.now(), evaluation_id))
|
||||
elif status == 'failed':
|
||||
sql = """
|
||||
UPDATE evaluations
|
||||
SET status = %s, error_message = %s, completed_at = %s
|
||||
WHERE id = %s
|
||||
"""
|
||||
self.db_manager.execute_update(
|
||||
sql,
|
||||
(status, error_message, datetime.now(), evaluation_id)
|
||||
)
|
||||
|
||||
def get_evaluation_status(self, evaluation_id: str) -> Dict[str, Any]:
|
||||
"""
|
||||
Get evaluation status
|
||||
|
||||
Args:
|
||||
evaluation_id: Evaluation ID
|
||||
|
||||
Returns:
|
||||
Evaluation status dictionary
|
||||
"""
|
||||
sql = """
|
||||
SELECT id, status, started_at, completed_at, error_message
|
||||
FROM evaluations
|
||||
WHERE id = %s
|
||||
"""
|
||||
|
||||
results = self.db_manager.execute_query(sql, (evaluation_id,))
|
||||
|
||||
if not results:
|
||||
raise ValueError(f"Evaluation not found: {evaluation_id}")
|
||||
|
||||
return results[0]
|
||||
|
||||
def get_evaluation_results(self, evaluation_id: str) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Get evaluation results
|
||||
|
||||
Args:
|
||||
evaluation_id: Evaluation ID
|
||||
|
||||
Returns:
|
||||
List of evaluation results
|
||||
"""
|
||||
sql = """
|
||||
SELECT *
|
||||
FROM evaluation_results
|
||||
WHERE evaluation_id = %s
|
||||
ORDER BY question_index
|
||||
"""
|
||||
|
||||
return self.db_manager.execute_query(sql, (evaluation_id,))
|
||||
|
||||
def get_evaluation_summary(self, evaluation_id: str) -> Dict[str, Any]:
|
||||
"""
|
||||
Get evaluation summary
|
||||
|
||||
Args:
|
||||
evaluation_id: Evaluation ID
|
||||
|
||||
Returns:
|
||||
Evaluation summary dictionary
|
||||
"""
|
||||
sql = """
|
||||
SELECT *
|
||||
FROM evaluation_summaries
|
||||
WHERE evaluation_id = %s
|
||||
"""
|
||||
|
||||
results = self.db_manager.execute_query(sql, (evaluation_id,))
|
||||
|
||||
if not results:
|
||||
raise ValueError(f"Evaluation summary not found: {evaluation_id}")
|
||||
|
||||
return results[0]
|
||||
@@ -0,0 +1,414 @@
|
||||
"""
|
||||
Metrics calculation for RAG evaluation
|
||||
"""
|
||||
|
||||
from typing import List, Dict, Any, Optional, Set
|
||||
from abc import ABC, abstractmethod
|
||||
import re
|
||||
|
||||
|
||||
def _tokenize(text: str) -> Set[str]:
|
||||
"""
|
||||
Tokenize text supporting both Chinese and English
|
||||
|
||||
For Chinese: Extract individual characters
|
||||
For English: Split by whitespace and punctuation
|
||||
For mixed: Combine both approaches
|
||||
|
||||
Args:
|
||||
text: Input text
|
||||
|
||||
Returns:
|
||||
Set of tokens
|
||||
"""
|
||||
if not text:
|
||||
return set()
|
||||
|
||||
text = text.lower()
|
||||
|
||||
# For Chinese or mixed content, extract characters
|
||||
# Match Chinese characters
|
||||
chinese_chars = set(re.findall(r'[\u4e00-\u9fff]', text))
|
||||
|
||||
# For English and other languages, split by non-word characters
|
||||
# This handles English words and numbers
|
||||
english_words = set(re.findall(r'\b\w+\b', text))
|
||||
|
||||
# Combine both
|
||||
return chinese_chars | english_words
|
||||
|
||||
|
||||
class Metric(ABC):
|
||||
"""Abstract base class for metrics"""
|
||||
|
||||
@abstractmethod
|
||||
def calculate(self, **kwargs) -> float:
|
||||
"""
|
||||
Calculate metric score
|
||||
|
||||
Returns:
|
||||
Metric score (0.0 to 1.0)
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
class ContextRecall(Metric):
|
||||
"""
|
||||
Context Recall: Measures how many relevant contexts were retrieved
|
||||
|
||||
Formula: |retrieved ∩ ground_truth| / |ground_truth|
|
||||
"""
|
||||
|
||||
def calculate(
|
||||
self,
|
||||
retrieved_contexts: List[str],
|
||||
ground_truth_contexts: List[str]
|
||||
) -> float:
|
||||
"""
|
||||
Calculate context recall
|
||||
|
||||
Args:
|
||||
retrieved_contexts: List of retrieved context IDs/texts
|
||||
ground_truth_contexts: List of ground truth context IDs/texts
|
||||
|
||||
Returns:
|
||||
Recall score (0.0 to 1.0)
|
||||
"""
|
||||
if not ground_truth_contexts:
|
||||
return 0.0
|
||||
|
||||
# Convert to sets for intersection
|
||||
retrieved_set = set(retrieved_contexts)
|
||||
ground_truth_set = set(ground_truth_contexts)
|
||||
|
||||
# Calculate intersection
|
||||
intersection = retrieved_set & ground_truth_set
|
||||
|
||||
recall = len(intersection) / len(ground_truth_set)
|
||||
return recall
|
||||
|
||||
|
||||
class ContextPrecision(Metric):
|
||||
"""
|
||||
Context Precision: Measures how many retrieved contexts are relevant
|
||||
|
||||
Formula: |retrieved ∩ ground_truth| / |retrieved|
|
||||
"""
|
||||
|
||||
def calculate(
|
||||
self,
|
||||
retrieved_contexts: List[str],
|
||||
ground_truth_contexts: List[str]
|
||||
) -> float:
|
||||
"""
|
||||
Calculate context precision
|
||||
|
||||
Args:
|
||||
retrieved_contexts: List of retrieved context IDs/texts
|
||||
ground_truth_contexts: List of ground truth context IDs/texts
|
||||
|
||||
Returns:
|
||||
Precision score (0.0 to 1.0)
|
||||
"""
|
||||
if not retrieved_contexts:
|
||||
return 0.0
|
||||
|
||||
# Convert to sets for intersection
|
||||
retrieved_set = set(retrieved_contexts)
|
||||
ground_truth_set = set(ground_truth_contexts)
|
||||
|
||||
# Calculate intersection
|
||||
intersection = retrieved_set & ground_truth_set
|
||||
|
||||
precision = len(intersection) / len(retrieved_set)
|
||||
return precision
|
||||
|
||||
|
||||
class MRR(Metric):
|
||||
"""
|
||||
Mean Reciprocal Rank: Measures the rank of the first relevant context
|
||||
|
||||
Formula: 1 / rank_of_first_relevant_context
|
||||
"""
|
||||
|
||||
def calculate(
|
||||
self,
|
||||
retrieved_contexts: List[str],
|
||||
ground_truth_contexts: List[str]
|
||||
) -> float:
|
||||
"""
|
||||
Calculate MRR
|
||||
|
||||
Args:
|
||||
retrieved_contexts: Ordered list of retrieved context IDs/texts
|
||||
ground_truth_contexts: List of ground truth context IDs/texts
|
||||
|
||||
Returns:
|
||||
MRR score (0.0 to 1.0)
|
||||
"""
|
||||
if not retrieved_contexts or not ground_truth_contexts:
|
||||
return 0.0
|
||||
|
||||
ground_truth_set = set(ground_truth_contexts)
|
||||
|
||||
# Find rank of first relevant context
|
||||
for rank, context in enumerate(retrieved_contexts, start=1):
|
||||
if context in ground_truth_set:
|
||||
return 1.0 / rank
|
||||
|
||||
return 0.0
|
||||
|
||||
|
||||
class NDCG(Metric):
|
||||
"""
|
||||
Normalized Discounted Cumulative Gain
|
||||
|
||||
Measures ranking quality with position discount
|
||||
"""
|
||||
|
||||
def calculate(
|
||||
self,
|
||||
retrieved_contexts: List[str],
|
||||
ground_truth_contexts: List[str],
|
||||
k: Optional[int] = None
|
||||
) -> float:
|
||||
"""
|
||||
Calculate NDCG@k
|
||||
|
||||
Args:
|
||||
retrieved_contexts: Ordered list of retrieved context IDs/texts
|
||||
ground_truth_contexts: List of ground truth context IDs/texts
|
||||
k: Cut-off rank (if None, use all retrieved contexts)
|
||||
|
||||
Returns:
|
||||
NDCG score (0.0 to 1.0)
|
||||
"""
|
||||
if not retrieved_contexts or not ground_truth_contexts:
|
||||
return 0.0
|
||||
|
||||
if k is None:
|
||||
k = len(retrieved_contexts)
|
||||
|
||||
ground_truth_set = set(ground_truth_contexts)
|
||||
|
||||
# Calculate DCG
|
||||
dcg = 0.0
|
||||
for i, context in enumerate(retrieved_contexts[:k], start=1):
|
||||
relevance = 1.0 if context in ground_truth_set else 0.0
|
||||
dcg += relevance / (i + 1) # log2(i+1) simplified
|
||||
|
||||
# Calculate IDCG (ideal DCG)
|
||||
# IDCG should consider at most k relevant documents at top positions
|
||||
idcg = 0.0
|
||||
max_relevant = min(len(ground_truth_contexts), k)
|
||||
for i in range(1, max_relevant + 1):
|
||||
idcg += 1.0 / (i + 1)
|
||||
|
||||
if idcg == 0.0:
|
||||
return 0.0
|
||||
|
||||
ndcg = dcg / idcg
|
||||
return ndcg
|
||||
|
||||
|
||||
class Faithfulness(Metric):
|
||||
"""
|
||||
Faithfulness: Measures if the answer is faithful to the contexts
|
||||
|
||||
Uses RAGAS faithfulness metric
|
||||
"""
|
||||
|
||||
def calculate(
|
||||
self,
|
||||
question: str,
|
||||
answer: str,
|
||||
contexts: List[str]
|
||||
) -> float:
|
||||
"""
|
||||
Calculate faithfulness score
|
||||
|
||||
Args:
|
||||
question: Question text
|
||||
answer: Generated answer
|
||||
contexts: Retrieved contexts
|
||||
|
||||
Returns:
|
||||
Faithfulness score (0.0 to 1.0)
|
||||
"""
|
||||
# TODO: Integrate with RAGAS faithfulness metric
|
||||
# For now, simple heuristic: check if answer contains context keywords
|
||||
|
||||
if not answer or not contexts:
|
||||
return 0.0
|
||||
|
||||
# Tokenize answer and contexts
|
||||
answer_tokens = _tokenize(answer)
|
||||
context_text = ' '.join(contexts)
|
||||
context_tokens = _tokenize(context_text)
|
||||
|
||||
if not answer_tokens:
|
||||
return 0.0
|
||||
|
||||
overlap = answer_tokens & context_tokens
|
||||
faithfulness = len(overlap) / len(answer_tokens)
|
||||
|
||||
return min(faithfulness, 1.0)
|
||||
|
||||
|
||||
class AnswerRelevancy(Metric):
|
||||
"""
|
||||
Answer Relevancy: Measures if the answer is relevant to the question
|
||||
|
||||
Uses RAGAS answer relevancy metric
|
||||
"""
|
||||
|
||||
def calculate(
|
||||
self,
|
||||
question: str,
|
||||
answer: str
|
||||
) -> float:
|
||||
"""
|
||||
Calculate answer relevancy score
|
||||
|
||||
Args:
|
||||
question: Question text
|
||||
answer: Generated answer
|
||||
|
||||
Returns:
|
||||
Relevancy score (0.0 to 1.0)
|
||||
"""
|
||||
# TODO: Integrate with RAGAS answer relevancy metric
|
||||
# For now, simple heuristic: check keyword overlap
|
||||
|
||||
if not question or not answer:
|
||||
return 0.0
|
||||
|
||||
# Tokenize question and answer
|
||||
question_tokens = _tokenize(question)
|
||||
answer_tokens = _tokenize(answer)
|
||||
|
||||
if not question_tokens:
|
||||
return 0.0
|
||||
|
||||
# Calculate overlap
|
||||
overlap = question_tokens & answer_tokens
|
||||
relevancy = len(overlap) / len(question_tokens)
|
||||
|
||||
return min(relevancy, 1.0)
|
||||
|
||||
|
||||
class Correctness(Metric):
|
||||
"""
|
||||
Correctness: Measures if the answer is correct compared to ground truth
|
||||
|
||||
Uses RAGAS correctness metric
|
||||
"""
|
||||
|
||||
def calculate(
|
||||
self,
|
||||
answer: str,
|
||||
ground_truth_answer: str
|
||||
) -> float:
|
||||
"""
|
||||
Calculate correctness score
|
||||
|
||||
Args:
|
||||
answer: Generated answer
|
||||
ground_truth_answer: Ground truth answer
|
||||
|
||||
Returns:
|
||||
Correctness score (0.0 to 1.0)
|
||||
"""
|
||||
# TODO: Integrate with RAGAS correctness metric
|
||||
# For now, simple heuristic: word overlap
|
||||
|
||||
if not answer or not ground_truth_answer:
|
||||
return 0.0
|
||||
|
||||
# Tokenize answers
|
||||
answer_tokens = _tokenize(answer)
|
||||
ground_truth_tokens = _tokenize(ground_truth_answer)
|
||||
|
||||
if not ground_truth_tokens:
|
||||
return 0.0
|
||||
|
||||
overlap = answer_tokens & ground_truth_tokens
|
||||
correctness = len(overlap) / len(ground_truth_tokens)
|
||||
|
||||
return min(correctness, 1.0)
|
||||
|
||||
|
||||
class MetricsCalculator:
|
||||
"""Calculator for all evaluation metrics"""
|
||||
|
||||
def __init__(self):
|
||||
self.context_recall = ContextRecall()
|
||||
self.context_precision = ContextPrecision()
|
||||
self.mrr = MRR()
|
||||
self.ndcg = NDCG()
|
||||
self.faithfulness = Faithfulness()
|
||||
self.answer_relevancy = AnswerRelevancy()
|
||||
self.correctness = Correctness()
|
||||
|
||||
def calculate_all(
|
||||
self,
|
||||
question: str,
|
||||
retrieved_contexts: List[str],
|
||||
generated_answer: str,
|
||||
ground_truth_contexts: List[str],
|
||||
ground_truth_answer: str
|
||||
) -> Dict[str, float]:
|
||||
"""
|
||||
Calculate all metrics
|
||||
|
||||
Args:
|
||||
question: Question text
|
||||
retrieved_contexts: Retrieved context IDs/texts
|
||||
generated_answer: Generated answer
|
||||
ground_truth_contexts: Ground truth context IDs/texts
|
||||
ground_truth_answer: Ground truth answer
|
||||
|
||||
Returns:
|
||||
Dictionary of metric scores
|
||||
"""
|
||||
metrics = {}
|
||||
|
||||
# Retrieval metrics
|
||||
metrics['context_recall'] = self.context_recall.calculate(
|
||||
retrieved_contexts=retrieved_contexts,
|
||||
ground_truth_contexts=ground_truth_contexts
|
||||
)
|
||||
|
||||
metrics['context_precision'] = self.context_precision.calculate(
|
||||
retrieved_contexts=retrieved_contexts,
|
||||
ground_truth_contexts=ground_truth_contexts
|
||||
)
|
||||
|
||||
metrics['mrr'] = self.mrr.calculate(
|
||||
retrieved_contexts=retrieved_contexts,
|
||||
ground_truth_contexts=ground_truth_contexts
|
||||
)
|
||||
|
||||
metrics['ndcg'] = self.ndcg.calculate(
|
||||
retrieved_contexts=retrieved_contexts,
|
||||
ground_truth_contexts=ground_truth_contexts
|
||||
)
|
||||
|
||||
# Generation metrics
|
||||
metrics['faithfulness'] = self.faithfulness.calculate(
|
||||
question=question,
|
||||
answer=generated_answer,
|
||||
contexts=retrieved_contexts
|
||||
)
|
||||
|
||||
metrics['answer_relevancy'] = self.answer_relevancy.calculate(
|
||||
question=question,
|
||||
answer=generated_answer
|
||||
)
|
||||
|
||||
metrics['correctness'] = self.correctness.calculate(
|
||||
answer=generated_answer,
|
||||
ground_truth_answer=ground_truth_answer
|
||||
)
|
||||
|
||||
return metrics
|
||||
@@ -0,0 +1,372 @@
|
||||
"""
|
||||
Parallel execution module for RAG evaluation
|
||||
"""
|
||||
|
||||
from typing import List, Dict, Any, Optional, Callable
|
||||
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor, as_completed
|
||||
import threading
|
||||
from dataclasses import dataclass
|
||||
import time
|
||||
|
||||
|
||||
@dataclass
|
||||
class ParallelConfig:
|
||||
"""并行执行配置"""
|
||||
max_workers: int = 5 # 最大工作线程数
|
||||
use_processes: bool = False # 是否使用进程池(默认使用线程池)
|
||||
chunk_size: int = 1 # 每个任务处理的问题数量
|
||||
|
||||
|
||||
class ParallelExecutor:
|
||||
"""并行执行器,用于加速RAG评估"""
|
||||
|
||||
def __init__(self, config: ParallelConfig):
|
||||
"""
|
||||
初始化并行执行器
|
||||
|
||||
Args:
|
||||
config: 并行配置
|
||||
"""
|
||||
self.config = config
|
||||
self._lock = threading.Lock()
|
||||
self._results = []
|
||||
self._errors = []
|
||||
|
||||
def execute_tasks(
|
||||
self,
|
||||
tasks: List[Any],
|
||||
task_func: Callable,
|
||||
task_desc: str = "task"
|
||||
) -> List[Any]:
|
||||
"""
|
||||
并行执行任务列表
|
||||
|
||||
Args:
|
||||
tasks: 任务列表
|
||||
task_func: 任务执行函数,接收单个任务作为参数
|
||||
task_desc: 任务描述(用于日志)
|
||||
|
||||
Returns:
|
||||
结果列表
|
||||
"""
|
||||
if not tasks:
|
||||
return []
|
||||
|
||||
results = []
|
||||
errors = []
|
||||
|
||||
# 选择执行器类型
|
||||
executor_class = ProcessPoolExecutor if self.config.use_processes else ThreadPoolExecutor
|
||||
|
||||
with executor_class(max_workers=self.config.max_workers) as executor:
|
||||
# 提交所有任务
|
||||
future_to_task = {
|
||||
executor.submit(task_func, task): task
|
||||
for task in tasks
|
||||
}
|
||||
|
||||
# 收集结果
|
||||
for future in as_completed(future_to_task):
|
||||
task = future_to_task[future]
|
||||
try:
|
||||
result = future.result()
|
||||
results.append(result)
|
||||
except Exception as e:
|
||||
error_msg = f"Error processing {task_desc}: {str(e)}"
|
||||
errors.append({
|
||||
'task': task,
|
||||
'error': error_msg
|
||||
})
|
||||
|
||||
if errors:
|
||||
# 记录错误但不中断执行
|
||||
print(f"Warnings: {len(errors)} tasks failed:")
|
||||
for error in errors[:3]: # 只显示前3个错误
|
||||
print(f" - {error['error']}")
|
||||
|
||||
return results
|
||||
|
||||
def execute_evaluation_batch(
|
||||
self,
|
||||
evaluation_items: List[Dict[str, Any]],
|
||||
evaluate_func: Callable
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
批量并行执行评估任务
|
||||
|
||||
Args:
|
||||
evaluation_items: 评估项目列表,每个项目包含问题索引和问题数据
|
||||
evaluate_func: 评估函数
|
||||
|
||||
Returns:
|
||||
评估结果列表
|
||||
"""
|
||||
if not evaluation_items:
|
||||
return []
|
||||
|
||||
# 如果任务数量较少,使用串行执行
|
||||
if len(evaluation_items) <= 3:
|
||||
return [evaluate_func(item) for item in evaluation_items]
|
||||
|
||||
# 并行执行
|
||||
return self.execute_tasks(
|
||||
tasks=evaluation_items,
|
||||
task_func=evaluate_func,
|
||||
task_desc="evaluation"
|
||||
)
|
||||
|
||||
def execute_with_progress(
|
||||
self,
|
||||
tasks: List[Any],
|
||||
task_func: Callable,
|
||||
task_desc: str = "task",
|
||||
progress_callback: Optional[Callable] = None
|
||||
) -> List[Any]:
|
||||
"""
|
||||
带进度回调的并行执行
|
||||
|
||||
Args:
|
||||
tasks: 任务列表
|
||||
task_func: 任务执行函数
|
||||
task_desc: 任务描述
|
||||
progress_callback: 进度回调函数(current, total)
|
||||
|
||||
Returns:
|
||||
结果列表
|
||||
"""
|
||||
if not tasks:
|
||||
return []
|
||||
|
||||
total = len(tasks)
|
||||
completed = 0
|
||||
results = []
|
||||
errors = []
|
||||
|
||||
executor_class = ProcessPoolExecutor if self.config.use_processes else ThreadPoolExecutor
|
||||
|
||||
with executor_class(max_workers=self.config.max_workers) as executor:
|
||||
future_to_index = {
|
||||
executor.submit(task_func, task): idx
|
||||
for idx, task in enumerate(tasks)
|
||||
}
|
||||
|
||||
for future in as_completed(future_to_index):
|
||||
try:
|
||||
result = future.result()
|
||||
results.append(result)
|
||||
completed += 1
|
||||
|
||||
# 调用进度回调
|
||||
if progress_callback:
|
||||
progress_callback(completed, total)
|
||||
|
||||
except Exception as e:
|
||||
errors.append(str(e))
|
||||
completed += 1
|
||||
|
||||
if progress_callback:
|
||||
progress_callback(completed, total)
|
||||
|
||||
return results
|
||||
|
||||
|
||||
class BatchEvaluator:
|
||||
"""批量评估器,优化大量评估任务的执行"""
|
||||
|
||||
def __init__(self, parallel_config: Optional[ParallelConfig] = None):
|
||||
"""
|
||||
初始化批量评估器
|
||||
|
||||
Args:
|
||||
parallel_config: 并行配置(可选)
|
||||
"""
|
||||
self.config = parallel_config or ParallelConfig()
|
||||
self.executor = ParallelExecutor(self.config)
|
||||
|
||||
def evaluate_questions_batch(
|
||||
self,
|
||||
questions: List[Dict[str, Any]],
|
||||
evaluation_func: Callable,
|
||||
batch_size: Optional[int] = None
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
批量评估问题
|
||||
|
||||
Args:
|
||||
questions: 问题列表
|
||||
evaluation_func: 单个问题的评估函数
|
||||
batch_size: 批次大小(如果为None,使用配置中的chunk_size)
|
||||
|
||||
Returns:
|
||||
评估结果列表
|
||||
"""
|
||||
if not questions:
|
||||
return []
|
||||
|
||||
batch_size = batch_size or self.config.chunk_size
|
||||
|
||||
# 如果问题数量小于等于批次大小,直接并行执行
|
||||
if len(questions) <= batch_size:
|
||||
results = self.executor.execute_tasks(
|
||||
tasks=questions,
|
||||
task_func=evaluation_func,
|
||||
task_desc="question evaluation"
|
||||
)
|
||||
return results
|
||||
|
||||
# 分批执行
|
||||
all_results = []
|
||||
for i in range(0, len(questions), batch_size):
|
||||
batch = questions[i:i + batch_size]
|
||||
batch_results = self.executor.execute_tasks(
|
||||
tasks=batch,
|
||||
task_func=evaluation_func,
|
||||
task_desc=f"batch {i // batch_size + 1}"
|
||||
)
|
||||
all_results.extend(batch_results)
|
||||
|
||||
return all_results
|
||||
|
||||
def evaluate_with_retry(
|
||||
self,
|
||||
questions: List[Dict[str, Any]],
|
||||
evaluation_func: Callable,
|
||||
max_retries: int = 3
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
带重试机制的批量评估
|
||||
|
||||
Args:
|
||||
questions: 问题列表
|
||||
evaluation_func: 评估函数
|
||||
max_retries: 最大重试次数
|
||||
|
||||
Returns:
|
||||
评估结果列表
|
||||
"""
|
||||
results = []
|
||||
failed_items = []
|
||||
|
||||
# 首次尝试
|
||||
for question in questions:
|
||||
try:
|
||||
result = evaluation_func(question)
|
||||
results.append(result)
|
||||
except Exception as e:
|
||||
failed_items.append((question, e))
|
||||
|
||||
# 重试失败的项目
|
||||
for attempt in range(max_retries):
|
||||
if not failed_items:
|
||||
break
|
||||
|
||||
next_failed = []
|
||||
for question, original_error in failed_items:
|
||||
try:
|
||||
result = evaluation_func(question)
|
||||
results.append(result)
|
||||
except Exception as e:
|
||||
next_failed.append((question, e))
|
||||
|
||||
failed_items = next_failed
|
||||
|
||||
# 记录仍然失败的项目
|
||||
if failed_items:
|
||||
print(f"Warning: {len(failed_items)} items failed after {max_retries} retries")
|
||||
|
||||
return results
|
||||
|
||||
|
||||
def parallel_evaluator_wrapper(evaluation_id: str, question_data: Dict[str, Any],
|
||||
rag_adapter, metrics_calculator, db_manager):
|
||||
"""
|
||||
包装函数,用于进程池执行单个问题的评估
|
||||
|
||||
Args:
|
||||
evaluation_id: 评估ID
|
||||
question_data: 问题数据
|
||||
rag_adapter: RAG适配器
|
||||
metrics_calculator: 指标计算器
|
||||
db_manager: 数据库管理器
|
||||
|
||||
Returns:
|
||||
评估结果
|
||||
"""
|
||||
try:
|
||||
question_text = question_data['question']
|
||||
question_index = question_data['index']
|
||||
ground_truth = question_data.get('ground_truth', {})
|
||||
|
||||
# 执行RAG查询
|
||||
rag_result = rag_adapter.evaluate_question(question_text)
|
||||
|
||||
# 提取ground truth
|
||||
ground_truth_answer = ground_truth.get('answer', '')
|
||||
ground_truth_contexts = ground_truth.get('context', [])
|
||||
|
||||
# 计算指标
|
||||
retrieved_context_texts = rag_result['context_texts']
|
||||
generated_answer = rag_result['generated_answer']
|
||||
|
||||
metrics = metrics_calculator.calculate_all(
|
||||
question=question_text,
|
||||
retrieved_contexts=retrieved_context_texts,
|
||||
generated_answer=generated_answer,
|
||||
ground_truth_contexts=ground_truth_contexts,
|
||||
ground_truth_answer=ground_truth_answer
|
||||
)
|
||||
|
||||
# 保存到数据库
|
||||
from ..utils.helpers import generate_id, generate_biz_seq, generate_sys_seq
|
||||
result_id = generate_id("result")
|
||||
biz_seq = generate_biz_seq("RESULT")
|
||||
sys_seq = generate_sys_seq("RESULT")
|
||||
|
||||
sql = """
|
||||
INSERT INTO evaluation_results (
|
||||
id, biz_seq, sys_seq, evaluation_id, question_index, question_text,
|
||||
context_recall, context_precision, mrr, ndcg,
|
||||
faithfulness, answer_relevancy, correctness,
|
||||
retrieved_contexts, generated_answer, ground_truth_answer, ground_truth_context,
|
||||
retrieval_time_ms, generation_time_ms, create_time
|
||||
) VALUES (
|
||||
%s, %s, %s, %s, %s, %s,
|
||||
%s, %s, %s, %s,
|
||||
%s, %s, %s,
|
||||
%s, %s, %s, %s,
|
||||
%s, %s, %s
|
||||
)
|
||||
"""
|
||||
|
||||
import json
|
||||
from datetime import datetime
|
||||
|
||||
now = datetime.now()
|
||||
db_manager.execute_update(
|
||||
sql,
|
||||
(
|
||||
result_id, biz_seq, sys_seq, evaluation_id, question_index, question_text,
|
||||
metrics['context_recall'], metrics['context_precision'],
|
||||
metrics['mrr'], metrics['ndcg'],
|
||||
metrics['faithfulness'], metrics['answer_relevancy'], metrics['correctness'],
|
||||
json.dumps(rag_result['retrieved_contexts']),
|
||||
generated_answer, ground_truth_answer,
|
||||
json.dumps(ground_truth_contexts),
|
||||
rag_result['retrieval_time_ms'], rag_result['generation_time_ms'],
|
||||
now
|
||||
)
|
||||
)
|
||||
|
||||
return {
|
||||
'result_id': result_id,
|
||||
'question_index': question_index,
|
||||
'metrics': metrics
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
# 返回错误信息
|
||||
return {
|
||||
'question_index': question_data.get('index', -1),
|
||||
'error': str(e),
|
||||
'metrics': None
|
||||
}
|
||||
@@ -0,0 +1,479 @@
|
||||
"""
|
||||
RAG system interface adapters
|
||||
"""
|
||||
|
||||
from typing import List, Dict, Any, Optional, Callable
|
||||
from abc import ABC, abstractmethod
|
||||
import time
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
|
||||
# 配置日志
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class RetryConfig:
|
||||
"""重试配置"""
|
||||
max_retries: int = 3
|
||||
initial_delay: float = 1.0 # 初始延迟(秒)
|
||||
max_delay: float = 60.0 # 最大延迟(秒)
|
||||
exponential_base: float = 2.0 # 指数退避基数
|
||||
timeout: int = 30 # 请求超时(秒)
|
||||
|
||||
|
||||
def retry_with_exponential_backoff(
|
||||
func: Callable,
|
||||
retry_config: RetryConfig,
|
||||
*args,
|
||||
**kwargs
|
||||
) -> Any:
|
||||
"""
|
||||
使用指数退避策略重试函数
|
||||
|
||||
Args:
|
||||
func: 要重试的函数
|
||||
retry_config: 重试配置
|
||||
*args: 函数参数
|
||||
**kwargs: 函数关键字参数
|
||||
|
||||
Returns:
|
||||
函数返回值
|
||||
|
||||
Raises:
|
||||
最后一次尝试的异常
|
||||
"""
|
||||
last_exception = None
|
||||
delay = retry_config.initial_delay
|
||||
|
||||
for attempt in range(retry_config.max_retries + 1):
|
||||
try:
|
||||
return func(*args, **kwargs)
|
||||
except Exception as e:
|
||||
last_exception = e
|
||||
if attempt < retry_config.max_retries:
|
||||
logger.warning(
|
||||
f"Attempt {attempt + 1}/{retry_config.max_retries + 1} failed: {e}. "
|
||||
f"Retrying in {delay:.1f}s..."
|
||||
)
|
||||
time.sleep(delay)
|
||||
delay = min(delay * retry_config.exponential_base, retry_config.max_delay)
|
||||
else:
|
||||
logger.error(f"All {retry_config.max_retries + 1} attempts failed: {e}")
|
||||
|
||||
raise last_exception
|
||||
|
||||
|
||||
class RAGRetriever(ABC):
|
||||
"""Abstract base class for RAG retrieval interface"""
|
||||
|
||||
@abstractmethod
|
||||
def retrieve(self, query: str, top_k: int = 5) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Retrieve relevant contexts for a query
|
||||
|
||||
Args:
|
||||
query: Query text
|
||||
top_k: Number of contexts to retrieve
|
||||
|
||||
Returns:
|
||||
List of retrieved contexts with metadata
|
||||
Each context should have:
|
||||
- content: str (the text content)
|
||||
- score: float (relevance score)
|
||||
- metadata: dict (source, chunk_id, etc.)
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
class RAGGenerator(ABC):
|
||||
"""Abstract base class for RAG generation interface"""
|
||||
|
||||
@abstractmethod
|
||||
def generate(self, query: str, contexts: List[str]) -> str:
|
||||
"""
|
||||
Generate answer based on query and contexts
|
||||
|
||||
Args:
|
||||
query: Query text
|
||||
contexts: List of context strings
|
||||
|
||||
Returns:
|
||||
Generated answer text
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
class HTTPRAGRetriever(RAGRetriever):
|
||||
"""HTTP-based RAG retriever with retry and timeout support"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
endpoint: str,
|
||||
api_key: Optional[str] = None,
|
||||
retry_config: Optional[RetryConfig] = None
|
||||
):
|
||||
"""
|
||||
Initialize HTTP RAG retriever
|
||||
|
||||
Args:
|
||||
endpoint: RAG retrieval API endpoint
|
||||
api_key: Optional API key for authentication
|
||||
retry_config: Optional retry configuration
|
||||
"""
|
||||
self.endpoint = endpoint
|
||||
self.api_key = api_key
|
||||
self.retry_config = retry_config or RetryConfig()
|
||||
self._stats = {
|
||||
'total_requests': 0,
|
||||
'successful_requests': 0,
|
||||
'failed_requests': 0,
|
||||
'total_latency_ms': 0
|
||||
}
|
||||
|
||||
def retrieve(self, query: str, top_k: int = 5) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Retrieve contexts via HTTP API with retry
|
||||
|
||||
Args:
|
||||
query: Query text
|
||||
top_k: Number of contexts to retrieve
|
||||
|
||||
Returns:
|
||||
List of retrieved contexts
|
||||
"""
|
||||
self._stats['total_requests'] += 1
|
||||
|
||||
def _do_retrieve():
|
||||
import requests
|
||||
|
||||
headers = {}
|
||||
if self.api_key:
|
||||
headers['Authorization'] = f'Bearer {self.api_key}'
|
||||
|
||||
logger.info(f"Retrieving contexts for query: {query[:50]}...")
|
||||
start_time = time.time()
|
||||
|
||||
response = requests.post(
|
||||
self.endpoint,
|
||||
json={'query': query, 'top_k': top_k},
|
||||
headers=headers,
|
||||
timeout=self.retry_config.timeout
|
||||
)
|
||||
response.raise_for_status()
|
||||
|
||||
latency_ms = int((time.time() - start_time) * 1000)
|
||||
self._stats['total_latency_ms'] += latency_ms
|
||||
logger.info(f"Retrieval completed in {latency_ms}ms")
|
||||
|
||||
data = response.json()
|
||||
contexts = data.get('contexts', [])
|
||||
|
||||
self._stats['successful_requests'] += 1
|
||||
return contexts
|
||||
|
||||
try:
|
||||
return retry_with_exponential_backoff(
|
||||
_do_retrieve,
|
||||
self.retry_config
|
||||
)
|
||||
except Exception as e:
|
||||
self._stats['failed_requests'] += 1
|
||||
logger.error(f"Retrieval failed after all retries: {e}")
|
||||
return []
|
||||
|
||||
def get_stats(self) -> Dict[str, Any]:
|
||||
"""
|
||||
获取统计信息
|
||||
|
||||
Returns:
|
||||
统计信息字典
|
||||
"""
|
||||
stats = self._stats.copy()
|
||||
if stats['successful_requests'] > 0:
|
||||
stats['avg_latency_ms'] = stats['total_latency_ms'] / stats['successful_requests']
|
||||
else:
|
||||
stats['avg_latency_ms'] = 0
|
||||
return stats
|
||||
|
||||
|
||||
class HTTPRAGGenerator(RAGGenerator):
|
||||
"""HTTP-based RAG generator with retry and timeout support"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
endpoint: str,
|
||||
api_key: Optional[str] = None,
|
||||
retry_config: Optional[RetryConfig] = None
|
||||
):
|
||||
"""
|
||||
Initialize HTTP RAG generator
|
||||
|
||||
Args:
|
||||
endpoint: RAG generation API endpoint
|
||||
api_key: Optional API key for authentication
|
||||
retry_config: Optional retry configuration
|
||||
"""
|
||||
self.endpoint = endpoint
|
||||
self.api_key = api_key
|
||||
self.retry_config = retry_config or RetryConfig(timeout=60) # 生成需要更长超时
|
||||
self._stats = {
|
||||
'total_requests': 0,
|
||||
'successful_requests': 0,
|
||||
'failed_requests': 0,
|
||||
'total_latency_ms': 0
|
||||
}
|
||||
|
||||
def generate(self, query: str, contexts: List[str]) -> str:
|
||||
"""
|
||||
Generate answer via HTTP API with retry
|
||||
|
||||
Args:
|
||||
query: Query text
|
||||
contexts: List of context strings
|
||||
|
||||
Returns:
|
||||
Generated answer
|
||||
"""
|
||||
self._stats['total_requests'] += 1
|
||||
|
||||
def _do_generate():
|
||||
import requests
|
||||
|
||||
headers = {}
|
||||
if self.api_key:
|
||||
headers['Authorization'] = f'Bearer {self.api_key}'
|
||||
|
||||
logger.info(f"Generating answer for query: {query[:50]}...")
|
||||
start_time = time.time()
|
||||
|
||||
response = requests.post(
|
||||
self.endpoint,
|
||||
json={'query': query, 'contexts': contexts},
|
||||
headers=headers,
|
||||
timeout=self.retry_config.timeout
|
||||
)
|
||||
response.raise_for_status()
|
||||
|
||||
latency_ms = int((time.time() - start_time) * 1000)
|
||||
self._stats['total_latency_ms'] += latency_ms
|
||||
logger.info(f"Generation completed in {latency_ms}ms")
|
||||
|
||||
data = response.json()
|
||||
answer = data.get('answer', '')
|
||||
|
||||
self._stats['successful_requests'] += 1
|
||||
return answer
|
||||
|
||||
try:
|
||||
return retry_with_exponential_backoff(
|
||||
_do_generate,
|
||||
self.retry_config
|
||||
)
|
||||
except Exception as e:
|
||||
self._stats['failed_requests'] += 1
|
||||
logger.error(f"Generation failed after all retries: {e}")
|
||||
return ""
|
||||
|
||||
def get_stats(self) -> Dict[str, Any]:
|
||||
"""
|
||||
获取统计信息
|
||||
|
||||
Returns:
|
||||
统计信息字典
|
||||
"""
|
||||
stats = self._stats.copy()
|
||||
if stats['successful_requests'] > 0:
|
||||
stats['avg_latency_ms'] = stats['total_latency_ms'] / stats['successful_requests']
|
||||
else:
|
||||
stats['avg_latency_ms'] = 0
|
||||
return stats
|
||||
|
||||
|
||||
class MockRAGRetriever(RAGRetriever):
|
||||
"""Mock RAG retriever for testing"""
|
||||
|
||||
def __init__(self, documents: Optional[List[str]] = None):
|
||||
"""
|
||||
Initialize mock retriever
|
||||
|
||||
Args:
|
||||
documents: Optional list of documents to retrieve from
|
||||
"""
|
||||
self.documents = documents or [
|
||||
"This is a sample document about RAG systems.",
|
||||
"RAG combines retrieval and generation for better answers.",
|
||||
"Evaluation is important for RAG system quality."
|
||||
]
|
||||
|
||||
def retrieve(self, query: str, top_k: int = 5) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Mock retrieval - returns first top_k documents
|
||||
|
||||
Args:
|
||||
query: Query text (not used in mock)
|
||||
top_k: Number of contexts to retrieve
|
||||
|
||||
Returns:
|
||||
List of mock contexts
|
||||
"""
|
||||
contexts = []
|
||||
for i, doc in enumerate(self.documents[:top_k]):
|
||||
contexts.append({
|
||||
'content': doc,
|
||||
'score': 1.0 - (i * 0.1), # Decreasing scores
|
||||
'metadata': {
|
||||
'source': f'mock_doc_{i}',
|
||||
'chunk_id': i
|
||||
}
|
||||
})
|
||||
return contexts
|
||||
|
||||
|
||||
class MockRAGGenerator(RAGGenerator):
|
||||
"""Mock RAG generator for testing"""
|
||||
|
||||
def generate(self, query: str, contexts: List[str]) -> str:
|
||||
"""
|
||||
Mock generation - returns simple concatenation
|
||||
|
||||
Args:
|
||||
query: Query text
|
||||
contexts: List of context strings
|
||||
|
||||
Returns:
|
||||
Mock generated answer
|
||||
"""
|
||||
if not contexts:
|
||||
return f"Mock answer for: {query}"
|
||||
|
||||
# Simple mock: combine query and first context
|
||||
return f"Based on the context, the answer to '{query}' is: {contexts[0][:100]}..."
|
||||
|
||||
|
||||
class RAGEvaluationAdapter:
|
||||
"""Adapter for RAG system evaluation with performance monitoring"""
|
||||
|
||||
def __init__(self, retriever: RAGRetriever, generator: RAGGenerator):
|
||||
"""
|
||||
Initialize RAG evaluation adapter
|
||||
|
||||
Args:
|
||||
retriever: RAG retriever instance
|
||||
generator: RAG generator instance
|
||||
"""
|
||||
self.retriever = retriever
|
||||
self.generator = generator
|
||||
self._stats = {
|
||||
'total_evaluations': 0,
|
||||
'successful_evaluations': 0,
|
||||
'failed_evaluations': 0,
|
||||
'total_retrieval_time_ms': 0,
|
||||
'total_generation_time_ms': 0
|
||||
}
|
||||
|
||||
def evaluate_question(self, question: str, top_k: int = 5) -> Dict[str, Any]:
|
||||
"""
|
||||
Evaluate a single question through RAG pipeline
|
||||
|
||||
Args:
|
||||
question: Question text
|
||||
top_k: Number of contexts to retrieve
|
||||
|
||||
Returns:
|
||||
Dictionary with retrieval and generation results
|
||||
"""
|
||||
self._stats['total_evaluations'] += 1
|
||||
|
||||
try:
|
||||
# Measure retrieval time
|
||||
retrieval_start = time.time()
|
||||
retrieved_contexts = self.retriever.retrieve(question, top_k)
|
||||
retrieval_time_ms = int((time.time() - retrieval_start) * 1000)
|
||||
self._stats['total_retrieval_time_ms'] += retrieval_time_ms
|
||||
|
||||
# Extract context texts
|
||||
context_texts = [ctx['content'] for ctx in retrieved_contexts]
|
||||
|
||||
# Measure generation time
|
||||
generation_start = time.time()
|
||||
generated_answer = self.generator.generate(question, context_texts)
|
||||
generation_time_ms = int((time.time() - generation_start) * 1000)
|
||||
self._stats['total_generation_time_ms'] += generation_time_ms
|
||||
|
||||
self._stats['successful_evaluations'] += 1
|
||||
|
||||
logger.info(
|
||||
f"Evaluation completed - Retrieval: {retrieval_time_ms}ms, "
|
||||
f"Generation: {generation_time_ms}ms"
|
||||
)
|
||||
|
||||
return {
|
||||
'question': question,
|
||||
'retrieved_contexts': retrieved_contexts,
|
||||
'context_texts': context_texts,
|
||||
'generated_answer': generated_answer,
|
||||
'retrieval_time_ms': retrieval_time_ms,
|
||||
'generation_time_ms': generation_time_ms
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
self._stats['failed_evaluations'] += 1
|
||||
logger.error(f"Evaluation failed for question '{question[:50]}...': {e}")
|
||||
raise
|
||||
|
||||
def get_stats(self) -> Dict[str, Any]:
|
||||
"""
|
||||
获取评估统计信息
|
||||
|
||||
Returns:
|
||||
统计信息字典
|
||||
"""
|
||||
stats = self._stats.copy()
|
||||
|
||||
if stats['successful_evaluations'] > 0:
|
||||
stats['avg_retrieval_time_ms'] = (
|
||||
stats['total_retrieval_time_ms'] / stats['successful_evaluations']
|
||||
)
|
||||
stats['avg_generation_time_ms'] = (
|
||||
stats['total_generation_time_ms'] / stats['successful_evaluations']
|
||||
)
|
||||
stats['avg_total_time_ms'] = (
|
||||
stats['avg_retrieval_time_ms'] + stats['avg_generation_time_ms']
|
||||
)
|
||||
else:
|
||||
stats['avg_retrieval_time_ms'] = 0
|
||||
stats['avg_generation_time_ms'] = 0
|
||||
stats['avg_total_time_ms'] = 0
|
||||
|
||||
# 添加子组件统计
|
||||
if hasattr(self.retriever, 'get_stats'):
|
||||
stats['retriever_stats'] = self.retriever.get_stats()
|
||||
if hasattr(self.generator, 'get_stats'):
|
||||
stats['generator_stats'] = self.generator.get_stats()
|
||||
|
||||
return stats
|
||||
|
||||
def reset_stats(self) -> None:
|
||||
"""重置统计信息"""
|
||||
self._stats = {
|
||||
'total_evaluations': 0,
|
||||
'successful_evaluations': 0,
|
||||
'failed_evaluations': 0,
|
||||
'total_retrieval_time_ms': 0,
|
||||
'total_generation_time_ms': 0
|
||||
}
|
||||
if hasattr(self.retriever, '_stats'):
|
||||
self.retriever._stats = {
|
||||
'total_requests': 0,
|
||||
'successful_requests': 0,
|
||||
'failed_requests': 0,
|
||||
'total_latency_ms': 0
|
||||
}
|
||||
if hasattr(self.generator, '_stats'):
|
||||
self.generator._stats = {
|
||||
'total_requests': 0,
|
||||
'successful_requests': 0,
|
||||
'failed_requests': 0,
|
||||
'total_latency_ms': 0
|
||||
}
|
||||
Reference in new issue
Block a user