Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
335 lines
9.5 KiB
Python
335 lines
9.5 KiB
Python
"""
|
||
Report generation module for RAG evaluation
|
||
"""
|
||
|
||
from typing import List, Dict, Any, Optional
|
||
from dataclasses import dataclass
|
||
from datetime import datetime
|
||
import statistics
|
||
|
||
|
||
@dataclass
|
||
class MetricStats:
|
||
"""指标统计信息"""
|
||
name: str
|
||
mean: float
|
||
median: float
|
||
std_dev: float
|
||
min: float
|
||
max: float
|
||
count: int
|
||
pass_rate: float # 通过率(基于阈值)
|
||
|
||
|
||
@dataclass
|
||
class EvaluationSummary:
|
||
"""评估摘要"""
|
||
evaluation_id: str
|
||
knowledge_base_id: str
|
||
testset_id: str
|
||
total_questions: int
|
||
successful_questions: int
|
||
failed_questions: int
|
||
overall_score: float # 0-100分
|
||
metric_stats: Dict[str, MetricStats]
|
||
avg_retrieval_time_ms: float
|
||
avg_generation_time_ms: float
|
||
created_at: datetime
|
||
|
||
|
||
class ResultAggregator:
|
||
"""评估结果聚合器"""
|
||
|
||
def __init__(self, metric_thresholds: Optional[Dict[str, float]] = None):
|
||
"""
|
||
初始化聚合器
|
||
|
||
Args:
|
||
metric_thresholds: 指标阈值字典,用于计算通过率
|
||
"""
|
||
self.metric_thresholds = metric_thresholds or {
|
||
'context_recall': 0.7,
|
||
'context_precision': 0.7,
|
||
'mrr': 0.6,
|
||
'ndcg': 0.7,
|
||
'faithfulness': 0.8,
|
||
'answer_relevancy': 0.7,
|
||
'correctness': 0.7
|
||
}
|
||
|
||
def aggregate_results(
|
||
self,
|
||
evaluation_id: str,
|
||
knowledge_base_id: str,
|
||
testset_id: str,
|
||
results: List[Dict[str, Any]]
|
||
) -> EvaluationSummary:
|
||
"""
|
||
聚合评估结果
|
||
|
||
Args:
|
||
evaluation_id: 评估ID
|
||
knowledge_base_id: 知识库ID
|
||
testset_id: 测评集ID
|
||
results: 评估结果列表
|
||
|
||
Returns:
|
||
评估摘要
|
||
"""
|
||
if not results:
|
||
raise ValueError("Results list cannot be empty")
|
||
|
||
# 统计成功和失败的问题
|
||
successful = [r for r in results if r.get('metrics') is not None]
|
||
failed = [r for r in results if r.get('metrics') is None]
|
||
|
||
# 计算每个指标的统计信息
|
||
metric_stats = self._calculate_metric_stats(successful)
|
||
|
||
# 计算整体评分(0-100)
|
||
overall_score = self._calculate_overall_score(metric_stats)
|
||
|
||
# 计算平均时间
|
||
avg_retrieval_time = statistics.mean(
|
||
[r.get('retrieval_time_ms', 0) for r in successful]
|
||
) if successful else 0
|
||
|
||
avg_generation_time = statistics.mean(
|
||
[r.get('generation_time_ms', 0) for r in successful]
|
||
) if successful else 0
|
||
|
||
return EvaluationSummary(
|
||
evaluation_id=evaluation_id,
|
||
knowledge_base_id=knowledge_base_id,
|
||
testset_id=testset_id,
|
||
total_questions=len(results),
|
||
successful_questions=len(successful),
|
||
failed_questions=len(failed),
|
||
overall_score=overall_score,
|
||
metric_stats=metric_stats,
|
||
avg_retrieval_time_ms=avg_retrieval_time,
|
||
avg_generation_time_ms=avg_generation_time,
|
||
created_at=datetime.now()
|
||
)
|
||
|
||
def _calculate_metric_stats(
|
||
self,
|
||
results: List[Dict[str, Any]]
|
||
) -> Dict[str, MetricStats]:
|
||
"""
|
||
计算每个指标的统计信息
|
||
|
||
Args:
|
||
results: 成功的评估结果列表
|
||
|
||
Returns:
|
||
指标统计字典
|
||
"""
|
||
if not results:
|
||
return {}
|
||
|
||
# 提取所有指标名称
|
||
metric_names = set()
|
||
for result in results:
|
||
if 'metrics' in result and result['metrics']:
|
||
metric_names.update(result['metrics'].keys())
|
||
|
||
# 计算每个指标的统计
|
||
metric_stats = {}
|
||
for metric_name in metric_names:
|
||
values = [
|
||
r['metrics'][metric_name]
|
||
for r in results
|
||
if 'metrics' in r and metric_name in r['metrics']
|
||
]
|
||
|
||
if values:
|
||
threshold = self.metric_thresholds.get(metric_name, 0.7)
|
||
pass_count = sum(1 for v in values if v >= threshold)
|
||
|
||
metric_stats[metric_name] = MetricStats(
|
||
name=metric_name,
|
||
mean=statistics.mean(values),
|
||
median=statistics.median(values),
|
||
std_dev=statistics.stdev(values) if len(values) > 1 else 0.0,
|
||
min=min(values),
|
||
max=max(values),
|
||
count=len(values),
|
||
pass_rate=pass_count / len(values)
|
||
)
|
||
|
||
return metric_stats
|
||
|
||
def _calculate_overall_score(
|
||
self,
|
||
metric_stats: Dict[str, MetricStats]
|
||
) -> float:
|
||
"""
|
||
计算整体评分(0-100)
|
||
|
||
使用加权平均,检索指标和生成指标各占50%
|
||
|
||
Args:
|
||
metric_stats: 指标统计字典
|
||
|
||
Returns:
|
||
整体评分(0-100)
|
||
"""
|
||
if not metric_stats:
|
||
return 0.0
|
||
|
||
# 定义指标权重
|
||
retrieval_metrics = ['context_recall', 'context_precision', 'mrr', 'ndcg']
|
||
generation_metrics = ['faithfulness', 'answer_relevancy', 'correctness']
|
||
|
||
# 计算检索指标平均分
|
||
retrieval_scores = [
|
||
metric_stats[m].mean
|
||
for m in retrieval_metrics
|
||
if m in metric_stats
|
||
]
|
||
retrieval_avg = statistics.mean(retrieval_scores) if retrieval_scores else 0.0
|
||
|
||
# 计算生成指标平均分
|
||
generation_scores = [
|
||
metric_stats[m].mean
|
||
for m in generation_metrics
|
||
if m in metric_stats
|
||
]
|
||
generation_avg = statistics.mean(generation_scores) if generation_scores else 0.0
|
||
|
||
# 加权平均(检索50%,生成50%)
|
||
overall = (retrieval_avg * 0.5 + generation_avg * 0.5) * 100
|
||
|
||
return round(overall, 2)
|
||
|
||
def group_by_source(
|
||
self,
|
||
results: List[Dict[str, Any]]
|
||
) -> Dict[str, List[Dict[str, Any]]]:
|
||
"""
|
||
按来源文件分组结果
|
||
|
||
Args:
|
||
results: 评估结果列表
|
||
|
||
Returns:
|
||
按来源分组的结果字典
|
||
"""
|
||
grouped = {}
|
||
|
||
for result in results:
|
||
# 从元数据中提取来源信息
|
||
source = result.get('metadata', {}).get('source', 'unknown')
|
||
|
||
if source not in grouped:
|
||
grouped[source] = []
|
||
|
||
grouped[source].append(result)
|
||
|
||
return grouped
|
||
|
||
def identify_failed_cases(
|
||
self,
|
||
results: List[Dict[str, Any]],
|
||
threshold: float = 0.5
|
||
) -> List[Dict[str, Any]]:
|
||
"""
|
||
识别失败案例(低于阈值的问题)
|
||
|
||
Args:
|
||
results: 评估结果列表
|
||
threshold: 失败阈值(默认0.5)
|
||
|
||
Returns:
|
||
失败案例列表
|
||
"""
|
||
failed_cases = []
|
||
|
||
for result in results:
|
||
if 'metrics' not in result or not result['metrics']:
|
||
# 完全失败的案例
|
||
failed_cases.append({
|
||
'question_index': result.get('question_index', -1),
|
||
'question': result.get('question_text', ''),
|
||
'reason': 'evaluation_failed',
|
||
'error': result.get('error', 'Unknown error'),
|
||
'metrics': None
|
||
})
|
||
continue
|
||
|
||
# 检查是否有指标低于阈值
|
||
metrics = result['metrics']
|
||
low_metrics = {
|
||
name: value
|
||
for name, value in metrics.items()
|
||
if value < threshold
|
||
}
|
||
|
||
if low_metrics:
|
||
failed_cases.append({
|
||
'question_index': result.get('question_index', -1),
|
||
'question': result.get('question_text', ''),
|
||
'reason': 'low_metrics',
|
||
'low_metrics': low_metrics,
|
||
'all_metrics': metrics,
|
||
'retrieved_contexts': result.get('retrieved_contexts', []),
|
||
'generated_answer': result.get('generated_answer', ''),
|
||
'ground_truth_answer': result.get('ground_truth_answer', '')
|
||
})
|
||
|
||
return failed_cases
|
||
|
||
def calculate_metric_distribution(
|
||
self,
|
||
results: List[Dict[str, Any]],
|
||
metric_name: str,
|
||
bins: int = 10
|
||
) -> Dict[str, Any]:
|
||
"""
|
||
计算指标分布
|
||
|
||
Args:
|
||
results: 评估结果列表
|
||
metric_name: 指标名称
|
||
bins: 分箱数量
|
||
|
||
Returns:
|
||
分布信息字典
|
||
"""
|
||
values = [
|
||
r['metrics'][metric_name]
|
||
for r in results
|
||
if 'metrics' in r and metric_name in r['metrics']
|
||
]
|
||
|
||
if not values:
|
||
return {
|
||
'metric': metric_name,
|
||
'count': 0,
|
||
'distribution': []
|
||
}
|
||
|
||
# 创建分箱
|
||
min_val = 0.0
|
||
max_val = 1.0
|
||
bin_width = (max_val - min_val) / bins
|
||
|
||
distribution = []
|
||
for i in range(bins):
|
||
bin_start = min_val + i * bin_width
|
||
bin_end = bin_start + bin_width
|
||
count = sum(1 for v in values if bin_start <= v < bin_end)
|
||
|
||
distribution.append({
|
||
'range': f'{bin_start:.2f}-{bin_end:.2f}',
|
||
'count': count,
|
||
'percentage': count / len(values) * 100
|
||
})
|
||
|
||
return {
|
||
'metric': metric_name,
|
||
'count': len(values),
|
||
'distribution': distribution
|
||
}
|