285 lines
8.9 KiB
Python
285 lines
8.9 KiB
Python
"""
|
||||
|
|
可配置 RAGAs 评估器:支持通过参数启用/禁用特定指标
|
|||
|
|
"""
|
|||
|
|
import asyncio
|
|||
|
|
import time
|
|||
|
|
from typing import Dict, List, Optional, Set
|
|||
|
|
from ragas.dataset_schema import SingleTurnSample
|
|||
|
|
from ragas.metrics import (
|
|||
|
|
LLMContextPrecisionWithReference,
|
|||
|
|
LLMContextRecall,
|
|||
|
|
Faithfulness,
|
|||
|
|
ResponseRelevancy,
|
|||
|
|
AnswerCorrectness,
|
|||
|
|
SemanticSimilarity
|
|||
|
|
)
|
|||
|
|
from src.utils.llm_config import get_evaluator_llm, get_evaluator_embeddings
|
|||
|
|
from src.utils.evaluation_logger import EvaluationLogger
|
|||
|
|
|
|||
|
|
|
|||
|
|
class ConfigurableRAGAsEvaluator:
|
|||
|
|
"""可配置的 RAGAs 评估器,支持启用/禁用特定指标"""
|
|||
|
|
|
|||
|
|
# 所有可用的指标
|
|||
|
|
AVAILABLE_METRICS = {
|
|||
|
|
'context_precision': LLMContextPrecisionWithReference,
|
|||
|
|
'context_recall': LLMContextRecall,
|
|||
|
|
'faithfulness': Faithfulness,
|
|||
|
|
'answer_relevance': ResponseRelevancy,
|
|||
|
|
'answer_correctness': AnswerCorrectness
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
def __init__(
|
|||
|
|
self,
|
|||
|
|
logger: Optional[EvaluationLogger] = None,
|
|||
|
|
enable_parallel: bool = True,
|
|||
|
|
disabled_metrics: Optional[Set[str]] = None,
|
|||
|
|
enabled_metrics: Optional[Set[str]] = None
|
|||
|
|
):
|
|||
|
|
"""
|
|||
|
|
初始化可配置评估器
|
|||
|
|
|
|||
|
|
Args:
|
|||
|
|
logger: 评估日志记录器(可选)
|
|||
|
|
enable_parallel: 是否启用并行评估(默认 True)
|
|||
|
|
disabled_metrics: 要禁用的指标集合(如 {'answer_correctness'})
|
|||
|
|
enabled_metrics: 要启用的指标集合(如果提供,只启用这些指标)
|
|||
|
|
|
|||
|
|
注意:
|
|||
|
|
- 如果同时指定 enabled_metrics 和 disabled_metrics,优先使用 enabled_metrics
|
|||
|
|
- 如果都未指定,默认启用所有指标
|
|||
|
|
"""
|
|||
|
|
self.logger = logger
|
|||
|
|
self.enable_parallel = enable_parallel
|
|||
|
|
|
|||
|
|
# 确定要启用的指标
|
|||
|
|
if enabled_metrics is not None:
|
|||
|
|
# 只启用指定的指标
|
|||
|
|
metrics_to_use = enabled_metrics
|
|||
|
|
elif disabled_metrics is not None:
|
|||
|
|
# 启用所有指标,除了禁用的
|
|||
|
|
metrics_to_use = set(self.AVAILABLE_METRICS.keys()) - disabled_metrics
|
|||
|
|
else:
|
|||
|
|
# 默认启用所有指标
|
|||
|
|
metrics_to_use = set(self.AVAILABLE_METRICS.keys())
|
|||
|
|
|
|||
|
|
# 从 .env 获取 LLM 和 Embedding
|
|||
|
|
self.llm = get_evaluator_llm()
|
|||
|
|
self.embeddings = get_evaluator_embeddings()
|
|||
|
|
|
|||
|
|
# 初始化评估指标
|
|||
|
|
self.metrics = {}
|
|||
|
|
for metric_name in metrics_to_use:
|
|||
|
|
if metric_name not in self.AVAILABLE_METRICS:
|
|||
|
|
print(f"⚠️ 未知的指标: {metric_name},已跳过")
|
|||
|
|
continue
|
|||
|
|
|
|||
|
|
metric_class = self.AVAILABLE_METRICS[metric_name]
|
|||
|
|
|
|||
|
|
# AnswerCorrectness 需要额外的 answer_similarity 参数
|
|||
|
|
if metric_name == 'answer_correctness':
|
|||
|
|
answer_similarity = SemanticSimilarity(embeddings=self.embeddings)
|
|||
|
|
self.metrics[metric_name] = metric_class(
|
|||
|
|
llm=self.llm,
|
|||
|
|
embeddings=self.embeddings,
|
|||
|
|
answer_similarity=answer_similarity
|
|||
|
|
)
|
|||
|
|
# ResponseRelevancy 需要 embeddings 参数
|
|||
|
|
elif metric_name == 'answer_relevance':
|
|||
|
|
self.metrics[metric_name] = metric_class(
|
|||
|
|
llm=self.llm,
|
|||
|
|
embeddings=self.embeddings
|
|||
|
|
)
|
|||
|
|
else:
|
|||
|
|
self.metrics[metric_name] = metric_class(llm=self.llm)
|
|||
|
|
|
|||
|
|
print(f"已启用的指标: {', '.join(self.metrics.keys())}")
|
|||
|
|
if disabled_metrics:
|
|||
|
|
print(f"已禁用的指标: {', '.join(disabled_metrics)}")
|
|||
|
|
|
|||
|
|
async def _evaluate_single_metric(
|
|||
|
|
self,
|
|||
|
|
metric_name: str,
|
|||
|
|
metric,
|
|||
|
|
sample: SingleTurnSample,
|
|||
|
|
question_id: str
|
|||
|
|
) -> tuple:
|
|||
|
|
"""
|
|||
|
|
评估单个指标(用于并行执行)
|
|||
|
|
|
|||
|
|
Args:
|
|||
|
|
metric_name: 指标名称
|
|||
|
|
metric: 指标对象
|
|||
|
|
sample: RAGAs 样本
|
|||
|
|
question_id: 问题ID
|
|||
|
|
|
|||
|
|
Returns:
|
|||
|
|
(指标名称, 得分, 耗时, 错误)
|
|||
|
|
"""
|
|||
|
|
metric_start_time = time.time()
|
|||
|
|
|
|||
|
|
try:
|
|||
|
|
# 执行评估
|
|||
|
|
score = await metric.single_turn_ascore(sample)
|
|||
|
|
score = float(score) if score is not None else 0.0
|
|||
|
|
duration = time.time() - metric_start_time
|
|||
|
|
|
|||
|
|
# 记录指标评估结果
|
|||
|
|
if self.logger:
|
|||
|
|
self.logger.log_metric_evaluation(
|
|||
|
|
metric_name=metric_name,
|
|||
|
|
score=score,
|
|||
|
|
llm_calls=None,
|
|||
|
|
embedding_calls=None,
|
|||
|
|
duration=duration
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
return (metric_name, score, duration, None)
|
|||
|
|
|
|||
|
|
except Exception as e:
|
|||
|
|
duration = time.time() - metric_start_time
|
|||
|
|
|
|||
|
|
# 记录错误
|
|||
|
|
if self.logger:
|
|||
|
|
self.logger.log_metric_error(metric_name, e)
|
|||
|
|
else:
|
|||
|
|
print(f"Error evaluating {metric_name} for {question_id}: {e}")
|
|||
|
|
|
|||
|
|
return (metric_name, None, duration, str(e))
|
|||
|
|
|
|||
|
|
async def evaluate_single(self, sample_data: Dict) -> Dict[str, float]:
|
|||
|
|
"""
|
|||
|
|
评估单个样本(支持并行)
|
|||
|
|
|
|||
|
|
Args:
|
|||
|
|
sample_data: 样本数据(RAGAs 格式)
|
|||
|
|
|
|||
|
|
Returns:
|
|||
|
|
各指标得分字典
|
|||
|
|
"""
|
|||
|
|
question_id = sample_data.get('question_id', 'unknown')
|
|||
|
|
|
|||
|
|
# 记录问题开始
|
|||
|
|
if self.logger:
|
|||
|
|
self.logger.log_question_start(question_id, sample_data)
|
|||
|
|
|
|||
|
|
question_start_time = time.time()
|
|||
|
|
|
|||
|
|
# 创建 SingleTurnSample
|
|||
|
|
sample = SingleTurnSample(
|
|||
|
|
user_input=sample_data['user_input'],
|
|||
|
|
response=sample_data['response'],
|
|||
|
|
reference=sample_data['reference'],
|
|||
|
|
retrieved_contexts=sample_data['retrieved_contexts']
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
if self.enable_parallel:
|
|||
|
|
# 并行执行所有指标
|
|||
|
|
results = await self._evaluate_parallel(sample, question_id)
|
|||
|
|
else:
|
|||
|
|
# 串行执行
|
|||
|
|
results = await self._evaluate_sequential(sample, question_id)
|
|||
|
|
|
|||
|
|
# 记录问题完成
|
|||
|
|
if self.logger:
|
|||
|
|
question_duration = time.time() - question_start_time
|
|||
|
|
self.logger.log_question_complete(question_id, results, question_duration)
|
|||
|
|
|
|||
|
|
return results
|
|||
|
|
|
|||
|
|
async def _evaluate_parallel(
|
|||
|
|
self,
|
|||
|
|
sample: SingleTurnSample,
|
|||
|
|
question_id: str
|
|||
|
|
) -> Dict[str, float]:
|
|||
|
|
"""
|
|||
|
|
并行评估所有指标
|
|||
|
|
|
|||
|
|
Args:
|
|||
|
|
sample: RAGAs 样本
|
|||
|
|
question_id: 问题ID
|
|||
|
|
|
|||
|
|
Returns:
|
|||
|
|
各指标得分字典
|
|||
|
|
"""
|
|||
|
|
# 创建所有评估任务
|
|||
|
|
tasks = [
|
|||
|
|
self._evaluate_single_metric(name, metric, sample, question_id)
|
|||
|
|
for name, metric in self.metrics.items()
|
|||
|
|
]
|
|||
|
|
|
|||
|
|
# 并行执行所有任务
|
|||
|
|
results_list = await asyncio.gather(*tasks)
|
|||
|
|
|
|||
|
|
# 转换为字典
|
|||
|
|
results = {}
|
|||
|
|
for metric_name, score, duration, error in results_list:
|
|||
|
|
results[metric_name] = score
|
|||
|
|
if error:
|
|||
|
|
print(f" ⚠️ {metric_name}: 失败 ({error})")
|
|||
|
|
else:
|
|||
|
|
print(f" ✅ {metric_name}: {score:.4f} (耗时 {duration:.2f}秒)")
|
|||
|
|
|
|||
|
|
return results
|
|||
|
|
|
|||
|
|
async def _evaluate_sequential(
|
|||
|
|
self,
|
|||
|
|
sample: SingleTurnSample,
|
|||
|
|
question_id: str
|
|||
|
|
) -> Dict[str, float]:
|
|||
|
|
"""
|
|||
|
|
串行评估所有指标
|
|||
|
|
|
|||
|
|
Args:
|
|||
|
|
sample: RAGAs 样本
|
|||
|
|
question_id: 问题ID
|
|||
|
|
|
|||
|
|
Returns:
|
|||
|
|
各指标得分字典
|
|||
|
|
"""
|
|||
|
|
results = {}
|
|||
|
|
|
|||
|
|
for metric_name, metric in self.metrics.items():
|
|||
|
|
metric_name, score, duration, error = await self._evaluate_single_metric(
|
|||
|
|
metric_name, metric, sample, question_id
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
results[metric_name] = score
|
|||
|
|
if error:
|
|||
|
|
print(f" ❌ {metric_name}: 失败 ({error})")
|
|||
|
|
else:
|
|||
|
|
print(f" ✅ {metric_name}: {score:.4f} (耗时 {duration:.2f}秒)")
|
|||
|
|
|
|||
|
|
return results
|
|||
|
|
|
|||
|
|
async def evaluate_batch(self, samples: List[Dict]) -> List[Dict]:
|
|||
|
|
"""
|
|||
|
|
批量评估样本
|
|||
|
|
|
|||
|
|
Args:
|
|||
|
|
samples: 样本列表
|
|||
|
|
|
|||
|
|
Returns:
|
|||
|
|
评估结果列表
|
|||
|
|
"""
|
|||
|
|
results = []
|
|||
|
|
|
|||
|
|
for i, sample in enumerate(samples):
|
|||
|
|
mode = "并行" if self.enable_parallel else "串行"
|
|||
|
|
if not self.logger:
|
|||
|
|
print(f"\n[{mode}模式] 评估样本 {i+1}/{len(samples)}: {sample.get('question_id')}")
|
|||
|
|
|
|||
|
|
# 评估单个样本
|
|||
|
|
scores = await self.evaluate_single(sample)
|
|||
|
|
|
|||
|
|
# 合并结果
|
|||
|
|
result = {
|
|||
|
|
'question_id': sample.get('question_id'),
|
|||
|
|
'category': sample.get('category'),
|
|||
|
|
'type': sample.get('type'),
|
|||
|
|
'scores': scores
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
results.append(result)
|
|||
|
|
|
|||
|
|
return results
|