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,20 @@
|
||||
"""
|
||||
Report generation module
|
||||
"""
|
||||
|
||||
from .aggregator import (
|
||||
MetricStats,
|
||||
EvaluationSummary,
|
||||
ResultAggregator
|
||||
)
|
||||
|
||||
from .generator import ReportGenerator
|
||||
from .visualizer import ReportVisualizer
|
||||
|
||||
__all__ = [
|
||||
"MetricStats",
|
||||
"EvaluationSummary",
|
||||
"ResultAggregator",
|
||||
"ReportGenerator",
|
||||
"ReportVisualizer",
|
||||
]
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,334 @@
|
||||
"""
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
"""
|
||||
Report generator for RAG evaluation
|
||||
"""
|
||||
|
||||
from typing import Dict, Any, List
|
||||
from datetime import datetime
|
||||
import json
|
||||
|
||||
from .aggregator import EvaluationSummary, ResultAggregator
|
||||
|
||||
|
||||
class ReportGenerator:
|
||||
"""报告生成器"""
|
||||
|
||||
def __init__(self, aggregator: ResultAggregator):
|
||||
"""
|
||||
初始化报告生成器
|
||||
|
||||
Args:
|
||||
aggregator: 结果聚合器
|
||||
"""
|
||||
self.aggregator = aggregator
|
||||
|
||||
def generate_json_report(
|
||||
self,
|
||||
summary: EvaluationSummary,
|
||||
results: List[Dict[str, Any]],
|
||||
include_details: bool = True
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
生成JSON格式报告
|
||||
|
||||
Args:
|
||||
summary: 评估摘要
|
||||
results: 评估结果列表
|
||||
include_details: 是否包含详细结果
|
||||
|
||||
Returns:
|
||||
JSON报告字典
|
||||
"""
|
||||
report = {
|
||||
'report_version': '1.0',
|
||||
'generated_at': datetime.now().isoformat(),
|
||||
'evaluation_id': summary.evaluation_id,
|
||||
'knowledge_base_id': summary.knowledge_base_id,
|
||||
'testset_id': summary.testset_id,
|
||||
|
||||
# Executive Summary
|
||||
'executive_summary': self._generate_executive_summary(summary),
|
||||
|
||||
# 详细指标分析
|
||||
'metrics_analysis': self._generate_metrics_analysis(summary),
|
||||
|
||||
# 失败案例
|
||||
'failed_cases': self.aggregator.identify_failed_cases(results),
|
||||
|
||||
# 按来源分组
|
||||
'by_source': self._generate_source_breakdown(results)
|
||||
}
|
||||
|
||||
if include_details:
|
||||
report['detailed_results'] = results
|
||||
|
||||
return report
|
||||
|
||||
def _generate_executive_summary(
|
||||
self,
|
||||
summary: EvaluationSummary
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
生成执行摘要
|
||||
|
||||
Args:
|
||||
summary: 评估摘要
|
||||
|
||||
Returns:
|
||||
执行摘要字典
|
||||
"""
|
||||
# 识别Top 3问题
|
||||
top_issues = self._identify_top_issues(summary)
|
||||
|
||||
return {
|
||||
'overall_score': summary.overall_score,
|
||||
'grade': self._score_to_grade(summary.overall_score),
|
||||
'total_questions': summary.total_questions,
|
||||
'successful_questions': summary.successful_questions,
|
||||
'failed_questions': summary.failed_questions,
|
||||
'success_rate': summary.successful_questions / summary.total_questions * 100,
|
||||
'avg_retrieval_time_ms': summary.avg_retrieval_time_ms,
|
||||
'avg_generation_time_ms': summary.avg_generation_time_ms,
|
||||
'top_issues': top_issues,
|
||||
'recommendations': self._generate_recommendations(summary)
|
||||
}
|
||||
|
||||
def _generate_metrics_analysis(
|
||||
self,
|
||||
summary: EvaluationSummary
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
生成指标分析
|
||||
|
||||
Args:
|
||||
summary: 评估摘要
|
||||
|
||||
Returns:
|
||||
指标分析字典
|
||||
"""
|
||||
metrics_data = {}
|
||||
|
||||
for metric_name, stats in summary.metric_stats.items():
|
||||
metrics_data[metric_name] = {
|
||||
'mean': round(stats.mean, 3),
|
||||
'median': round(stats.median, 3),
|
||||
'std_dev': round(stats.std_dev, 3),
|
||||
'min': round(stats.min, 3),
|
||||
'max': round(stats.max, 3),
|
||||
'pass_rate': round(stats.pass_rate * 100, 1),
|
||||
'status': 'good' if stats.pass_rate >= 0.8 else 'warning' if stats.pass_rate >= 0.6 else 'poor'
|
||||
}
|
||||
|
||||
return metrics_data
|
||||
|
||||
def _generate_source_breakdown(
|
||||
self,
|
||||
results: List[Dict[str, Any]]
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
生成按来源的细分分析
|
||||
|
||||
Args:
|
||||
results: 评估结果列表
|
||||
|
||||
Returns:
|
||||
来源细分字典
|
||||
"""
|
||||
grouped = self.aggregator.group_by_source(results)
|
||||
breakdown = {}
|
||||
|
||||
for source, source_results in grouped.items():
|
||||
# 计算该来源的统计
|
||||
successful = [r for r in source_results if r.get('metrics')]
|
||||
|
||||
if successful:
|
||||
# 计算平均指标
|
||||
avg_metrics = {}
|
||||
for metric_name in successful[0].get('metrics', {}).keys():
|
||||
values = [r['metrics'][metric_name] for r in successful if metric_name in r['metrics']]
|
||||
if values:
|
||||
avg_metrics[metric_name] = round(sum(values) / len(values), 3)
|
||||
|
||||
breakdown[source] = {
|
||||
'total_questions': len(source_results),
|
||||
'successful_questions': len(successful),
|
||||
'avg_metrics': avg_metrics
|
||||
}
|
||||
|
||||
return breakdown
|
||||
|
||||
def _identify_top_issues(
|
||||
self,
|
||||
summary: EvaluationSummary
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
识别Top 3问题
|
||||
|
||||
Args:
|
||||
summary: 评估摘要
|
||||
|
||||
Returns:
|
||||
问题列表
|
||||
"""
|
||||
issues = []
|
||||
|
||||
# 检查每个指标
|
||||
for metric_name, stats in summary.metric_stats.items():
|
||||
if stats.pass_rate < 0.7: # 通过率低于70%
|
||||
issues.append({
|
||||
'metric': metric_name,
|
||||
'severity': 'high' if stats.pass_rate < 0.5 else 'medium',
|
||||
'pass_rate': round(stats.pass_rate * 100, 1),
|
||||
'mean_score': round(stats.mean, 3),
|
||||
'description': f'{metric_name}通过率仅为{stats.pass_rate*100:.1f}%'
|
||||
})
|
||||
|
||||
# 按严重程度和通过率排序
|
||||
issues.sort(key=lambda x: (x['severity'] == 'high', -x['pass_rate']), reverse=True)
|
||||
|
||||
return issues[:3] # 返回Top 3
|
||||
|
||||
def _generate_recommendations(
|
||||
self,
|
||||
summary: EvaluationSummary
|
||||
) -> List[str]:
|
||||
"""
|
||||
生成改进建议(基于规则)
|
||||
|
||||
Args:
|
||||
summary: 评估摘要
|
||||
|
||||
Returns:
|
||||
建议列表
|
||||
"""
|
||||
recommendations = []
|
||||
|
||||
# 检索指标建议
|
||||
if 'context_recall' in summary.metric_stats:
|
||||
recall_stats = summary.metric_stats['context_recall']
|
||||
if recall_stats.mean < 0.7:
|
||||
recommendations.append(
|
||||
"召回率较低,建议:1) 增加检索的top_k数量;2) 优化文档分块策略;3) 改进embedding模型"
|
||||
)
|
||||
|
||||
if 'context_precision' in summary.metric_stats:
|
||||
precision_stats = summary.metric_stats['context_precision']
|
||||
if precision_stats.mean < 0.7:
|
||||
recommendations.append(
|
||||
"精确率较低,建议:1) 优化检索算法;2) 调整相似度阈值;3) 改进查询重写策略"
|
||||
)
|
||||
|
||||
# 生成指标建议
|
||||
if 'faithfulness' in summary.metric_stats:
|
||||
faith_stats = summary.metric_stats['faithfulness']
|
||||
if faith_stats.mean < 0.8:
|
||||
recommendations.append(
|
||||
"忠实度较低,建议:1) 在prompt中强调基于上下文回答;2) 使用更强的LLM;3) 添加事实核查机制"
|
||||
)
|
||||
|
||||
if 'answer_relevancy' in summary.metric_stats:
|
||||
rel_stats = summary.metric_stats['answer_relevancy']
|
||||
if rel_stats.mean < 0.7:
|
||||
recommendations.append(
|
||||
"答案相关性较低,建议:1) 优化prompt模板;2) 改进问题理解;3) 调整生成参数"
|
||||
)
|
||||
|
||||
# 性能建议
|
||||
if summary.avg_retrieval_time_ms > 500:
|
||||
recommendations.append(
|
||||
f"检索时间较长({summary.avg_retrieval_time_ms:.0f}ms),建议:1) 优化向量索引;2) 使用缓存;3) 考虑并行检索"
|
||||
)
|
||||
|
||||
if summary.avg_generation_time_ms > 2000:
|
||||
recommendations.append(
|
||||
f"生成时间较长({summary.avg_generation_time_ms:.0f}ms),建议:1) 使用更快的模型;2) 减少生成长度;3) 启用流式输出"
|
||||
)
|
||||
|
||||
return recommendations[:5] # 最多返回5条建议
|
||||
|
||||
def _score_to_grade(self, score: float) -> str:
|
||||
"""
|
||||
将分数转换为等级
|
||||
|
||||
Args:
|
||||
score: 分数(0-100)
|
||||
|
||||
Returns:
|
||||
等级字符串
|
||||
"""
|
||||
if score >= 90:
|
||||
return 'A (优秀)'
|
||||
elif score >= 80:
|
||||
return 'B (良好)'
|
||||
elif score >= 70:
|
||||
return 'C (中等)'
|
||||
elif score >= 60:
|
||||
return 'D (及格)'
|
||||
else:
|
||||
return 'F (不及格)'
|
||||
|
||||
def save_report(
|
||||
self,
|
||||
report: Dict[str, Any],
|
||||
output_path: str
|
||||
) -> None:
|
||||
"""
|
||||
保存报告到文件
|
||||
|
||||
Args:
|
||||
report: 报告字典
|
||||
output_path: 输出路径
|
||||
"""
|
||||
with open(output_path, 'w', encoding='utf-8') as f:
|
||||
json.dump(report, f, ensure_ascii=False, indent=2)
|
||||
@@ -0,0 +1,675 @@
|
||||
"""
|
||||
Report visualization module for RAG evaluation
|
||||
"""
|
||||
|
||||
from typing import Dict, Any, List, Optional
|
||||
import json
|
||||
from pathlib import Path
|
||||
from datetime import datetime
|
||||
|
||||
try:
|
||||
import plotly.graph_objects as go
|
||||
from plotly.subplots import make_subplots
|
||||
PLOTLY_AVAILABLE = True
|
||||
except ImportError:
|
||||
PLOTLY_AVAILABLE = False
|
||||
|
||||
from .aggregator import EvaluationSummary
|
||||
|
||||
|
||||
class ReportVisualizer:
|
||||
"""报告可视化器"""
|
||||
|
||||
def __init__(self):
|
||||
"""初始化可视化器"""
|
||||
if not PLOTLY_AVAILABLE:
|
||||
raise ImportError(
|
||||
"Plotly is required for visualization. "
|
||||
"Install it with: pip install plotly"
|
||||
)
|
||||
|
||||
def generate_html_report(
|
||||
self,
|
||||
summary: EvaluationSummary,
|
||||
results: List[Dict[str, Any]],
|
||||
output_path: str,
|
||||
include_charts: bool = True
|
||||
) -> None:
|
||||
"""
|
||||
生成HTML格式报告
|
||||
|
||||
Args:
|
||||
summary: 评估摘要
|
||||
results: 评估结果列表
|
||||
output_path: 输出路径
|
||||
include_charts: 是否包含图表
|
||||
"""
|
||||
html_content = self._generate_html_content(
|
||||
summary, results, include_charts
|
||||
)
|
||||
|
||||
with open(output_path, 'w', encoding='utf-8') as f:
|
||||
f.write(html_content)
|
||||
|
||||
def _generate_html_content(
|
||||
self,
|
||||
summary: EvaluationSummary,
|
||||
results: List[Dict[str, Any]],
|
||||
include_charts: bool
|
||||
) -> str:
|
||||
"""
|
||||
生成HTML内容
|
||||
|
||||
Args:
|
||||
summary: 评估摘要
|
||||
results: 评估结果列表
|
||||
include_charts: 是否包含图表
|
||||
|
||||
Returns:
|
||||
HTML字符串
|
||||
"""
|
||||
# 生成图表
|
||||
charts_html = ""
|
||||
if include_charts:
|
||||
charts_html = self._generate_charts_html(summary, results)
|
||||
|
||||
# 生成完整HTML
|
||||
html = f"""
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>RAG评估报告 - {summary.evaluation_id}</title>
|
||||
<script src="https://cdn.plot.ly/plotly-2.27.0.min.js"></script>
|
||||
<style>
|
||||
{self._get_css_styles()}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<header>
|
||||
<h1>RAG评估报告</h1>
|
||||
<p class="subtitle">评估ID: {summary.evaluation_id}</p>
|
||||
<p class="timestamp">生成时间: {summary.created_at.strftime('%Y-%m-%d %H:%M:%S')}</p>
|
||||
</header>
|
||||
|
||||
{self._generate_executive_summary_html(summary)}
|
||||
{charts_html}
|
||||
{self._generate_metrics_table_html(summary)}
|
||||
{self._generate_failed_cases_html(results)}
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
return html
|
||||
|
||||
def _get_css_styles(self) -> str:
|
||||
"""获取CSS样式"""
|
||||
return """
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
||||
line-height: 1.6;
|
||||
color: #333;
|
||||
background-color: #f5f5f5;
|
||||
}
|
||||
|
||||
.container {
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
header {
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
padding: 30px;
|
||||
border-radius: 10px;
|
||||
margin-bottom: 30px;
|
||||
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
header h1 {
|
||||
font-size: 2.5em;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
font-size: 1.1em;
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.timestamp {
|
||||
font-size: 0.9em;
|
||||
opacity: 0.8;
|
||||
margin-top: 5px;
|
||||
}
|
||||
|
||||
.section {
|
||||
background: white;
|
||||
padding: 25px;
|
||||
margin-bottom: 25px;
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.section h2 {
|
||||
color: #667eea;
|
||||
margin-bottom: 20px;
|
||||
font-size: 1.8em;
|
||||
border-bottom: 2px solid #667eea;
|
||||
padding-bottom: 10px;
|
||||
}
|
||||
|
||||
.summary-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
|
||||
gap: 20px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.summary-card {
|
||||
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
|
||||
padding: 20px;
|
||||
border-radius: 8px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.summary-card.score {
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.summary-card h3 {
|
||||
font-size: 0.9em;
|
||||
margin-bottom: 10px;
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
.summary-card .value {
|
||||
font-size: 2.5em;
|
||||
font-weight: bold;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
|
||||
.summary-card .label {
|
||||
font-size: 0.9em;
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.grade {
|
||||
display: inline-block;
|
||||
padding: 5px 15px;
|
||||
border-radius: 20px;
|
||||
font-weight: bold;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.grade-A { background-color: #10b981; color: white; }
|
||||
.grade-B { background-color: #3b82f6; color: white; }
|
||||
.grade-C { background-color: #f59e0b; color: white; }
|
||||
.grade-D { background-color: #ef4444; color: white; }
|
||||
.grade-F { background-color: #991b1b; color: white; }
|
||||
|
||||
.recommendations {
|
||||
background-color: #fef3c7;
|
||||
border-left: 4px solid #f59e0b;
|
||||
padding: 15px;
|
||||
margin-top: 20px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
.recommendations h3 {
|
||||
color: #92400e;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.recommendations ul {
|
||||
list-style-position: inside;
|
||||
color: #78350f;
|
||||
}
|
||||
|
||||
.recommendations li {
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
margin-top: 15px;
|
||||
}
|
||||
|
||||
th, td {
|
||||
padding: 12px;
|
||||
text-align: left;
|
||||
border-bottom: 1px solid #e5e7eb;
|
||||
}
|
||||
|
||||
th {
|
||||
background-color: #f9fafb;
|
||||
font-weight: 600;
|
||||
color: #374151;
|
||||
}
|
||||
|
||||
tr:hover {
|
||||
background-color: #f9fafb;
|
||||
}
|
||||
|
||||
.status-badge {
|
||||
display: inline-block;
|
||||
padding: 4px 12px;
|
||||
border-radius: 12px;
|
||||
font-size: 0.85em;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.status-good { background-color: #d1fae5; color: #065f46; }
|
||||
.status-warning { background-color: #fed7aa; color: #92400e; }
|
||||
.status-poor { background-color: #fee2e2; color: #991b1b; }
|
||||
|
||||
.chart-container {
|
||||
margin: 20px 0;
|
||||
padding: 15px;
|
||||
background: white;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.failed-case {
|
||||
background-color: #fef2f2;
|
||||
border-left: 4px solid #ef4444;
|
||||
padding: 15px;
|
||||
margin-bottom: 15px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
.failed-case h4 {
|
||||
color: #991b1b;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.failed-case .question {
|
||||
font-weight: 600;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.failed-case .metrics {
|
||||
font-size: 0.9em;
|
||||
color: #7f1d1d;
|
||||
}
|
||||
"""
|
||||
|
||||
def _generate_executive_summary_html(
|
||||
self,
|
||||
summary: EvaluationSummary
|
||||
) -> str:
|
||||
"""生成执行摘要HTML"""
|
||||
grade = self._score_to_grade(summary.overall_score)
|
||||
grade_class = f"grade-{grade[0]}"
|
||||
|
||||
success_rate = (summary.successful_questions / summary.total_questions * 100
|
||||
if summary.total_questions > 0 else 0)
|
||||
|
||||
html = f"""
|
||||
<div class="section">
|
||||
<h2>执行摘要</h2>
|
||||
<div class="summary-grid">
|
||||
<div class="summary-card score">
|
||||
<h3>整体评分</h3>
|
||||
<div class="value">{summary.overall_score:.1f}</div>
|
||||
<div class="grade {grade_class}">{grade}</div>
|
||||
</div>
|
||||
<div class="summary-card">
|
||||
<h3>总问题数</h3>
|
||||
<div class="value">{summary.total_questions}</div>
|
||||
<div class="label">评估问题</div>
|
||||
</div>
|
||||
<div class="summary-card">
|
||||
<h3>成功率</h3>
|
||||
<div class="value">{success_rate:.1f}%</div>
|
||||
<div class="label">{summary.successful_questions}/{summary.total_questions} 成功</div>
|
||||
</div>
|
||||
<div class="summary-card">
|
||||
<h3>平均响应时间</h3>
|
||||
<div class="value">{summary.avg_retrieval_time_ms + summary.avg_generation_time_ms:.0f}ms</div>
|
||||
<div class="label">检索+生成</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
"""
|
||||
return html
|
||||
|
||||
def _generate_metrics_table_html(
|
||||
self,
|
||||
summary: EvaluationSummary
|
||||
) -> str:
|
||||
"""生成指标表格HTML"""
|
||||
rows = []
|
||||
for metric_name, stats in summary.metric_stats.items():
|
||||
status = 'good' if stats.pass_rate >= 0.8 else 'warning' if stats.pass_rate >= 0.6 else 'poor'
|
||||
status_text = '优秀' if status == 'good' else '警告' if status == 'warning' else '较差'
|
||||
|
||||
rows.append(f"""
|
||||
<tr>
|
||||
<td>{self._translate_metric_name(metric_name)}</td>
|
||||
<td>{stats.mean:.3f}</td>
|
||||
<td>{stats.median:.3f}</td>
|
||||
<td>{stats.std_dev:.3f}</td>
|
||||
<td>{stats.pass_rate * 100:.1f}%</td>
|
||||
<td><span class="status-badge status-{status}">{status_text}</span></td>
|
||||
</tr>
|
||||
""")
|
||||
|
||||
html = f"""
|
||||
<div class="section">
|
||||
<h2>指标详情</h2>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>指标</th>
|
||||
<th>平均值</th>
|
||||
<th>中位数</th>
|
||||
<th>标准差</th>
|
||||
<th>通过率</th>
|
||||
<th>状态</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{''.join(rows)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
"""
|
||||
return html
|
||||
|
||||
def _generate_failed_cases_html(
|
||||
self,
|
||||
results: List[Dict[str, Any]]
|
||||
) -> str:
|
||||
"""生成失败案例HTML"""
|
||||
from .aggregator import ResultAggregator
|
||||
|
||||
aggregator = ResultAggregator()
|
||||
failed_cases = aggregator.identify_failed_cases(results, threshold=0.5)
|
||||
|
||||
if not failed_cases:
|
||||
return """
|
||||
<div class="section">
|
||||
<h2>失败案例</h2>
|
||||
<p>没有失败案例,所有问题都表现良好!</p>
|
||||
</div>
|
||||
"""
|
||||
|
||||
cases_html = []
|
||||
for case in failed_cases[:10]: # 只显示前10个
|
||||
if case['reason'] == 'evaluation_failed':
|
||||
cases_html.append(f"""
|
||||
<div class="failed-case">
|
||||
<h4>问题 #{case['question_index']}</h4>
|
||||
<div class="question">{case['question']}</div>
|
||||
<div class="metrics">错误: {case['error']}</div>
|
||||
</div>
|
||||
""")
|
||||
else:
|
||||
low_metrics_str = ', '.join(
|
||||
f"{k}: {v:.3f}" for k, v in case['low_metrics'].items()
|
||||
)
|
||||
cases_html.append(f"""
|
||||
<div class="failed-case">
|
||||
<h4>问题 #{case['question_index']}</h4>
|
||||
<div class="question">{case['question']}</div>
|
||||
<div class="metrics">低分指标: {low_metrics_str}</div>
|
||||
</div>
|
||||
""")
|
||||
|
||||
html = f"""
|
||||
<div class="section">
|
||||
<h2>失败案例 (前10个)</h2>
|
||||
{''.join(cases_html)}
|
||||
</div>
|
||||
"""
|
||||
return html
|
||||
|
||||
def _generate_charts_html(
|
||||
self,
|
||||
summary: EvaluationSummary,
|
||||
results: List[Dict[str, Any]]
|
||||
) -> str:
|
||||
"""生成图表HTML"""
|
||||
charts = []
|
||||
|
||||
# 1. 指标雷达图
|
||||
radar_chart = self._create_metrics_radar_chart(summary)
|
||||
charts.append(f"""
|
||||
<div class="section">
|
||||
<h2>指标雷达图</h2>
|
||||
<div id="radar-chart" class="chart-container"></div>
|
||||
<script>
|
||||
{radar_chart}
|
||||
</script>
|
||||
</div>
|
||||
""")
|
||||
|
||||
# 2. 指标分布柱状图
|
||||
bar_chart = self._create_metrics_bar_chart(summary)
|
||||
charts.append(f"""
|
||||
<div class="section">
|
||||
<h2>指标对比</h2>
|
||||
<div id="bar-chart" class="chart-container"></div>
|
||||
<script>
|
||||
{bar_chart}
|
||||
</script>
|
||||
</div>
|
||||
""")
|
||||
|
||||
# 3. 通过率饼图
|
||||
pie_chart = self._create_pass_rate_pie_chart(summary)
|
||||
charts.append(f"""
|
||||
<div class="section">
|
||||
<h2>整体通过率</h2>
|
||||
<div id="pie-chart" class="chart-container"></div>
|
||||
<script>
|
||||
{pie_chart}
|
||||
</script>
|
||||
</div>
|
||||
""")
|
||||
|
||||
return '\n'.join(charts)
|
||||
|
||||
def _create_metrics_radar_chart(
|
||||
self,
|
||||
summary: EvaluationSummary
|
||||
) -> str:
|
||||
"""创建指标雷达图"""
|
||||
categories = []
|
||||
values = []
|
||||
|
||||
for metric_name, stats in summary.metric_stats.items():
|
||||
categories.append(self._translate_metric_name(metric_name))
|
||||
values.append(stats.mean)
|
||||
|
||||
# 闭合雷达图
|
||||
categories.append(categories[0])
|
||||
values.append(values[0])
|
||||
|
||||
data = {
|
||||
'type': 'scatterpolar',
|
||||
'r': values,
|
||||
'theta': categories,
|
||||
'fill': 'toself',
|
||||
'name': '指标得分'
|
||||
}
|
||||
|
||||
layout = {
|
||||
'polar': {
|
||||
'radialaxis': {
|
||||
'visible': True,
|
||||
'range': [0, 1]
|
||||
}
|
||||
},
|
||||
'showlegend': False
|
||||
}
|
||||
|
||||
return f"""
|
||||
var data = [{json.dumps(data)}];
|
||||
var layout = {json.dumps(layout)};
|
||||
Plotly.newPlot('radar-chart', data, layout);
|
||||
"""
|
||||
|
||||
def _create_metrics_bar_chart(
|
||||
self,
|
||||
summary: EvaluationSummary
|
||||
) -> str:
|
||||
"""创建指标柱状图"""
|
||||
categories = []
|
||||
means = []
|
||||
pass_rates = []
|
||||
|
||||
for metric_name, stats in summary.metric_stats.items():
|
||||
categories.append(self._translate_metric_name(metric_name))
|
||||
means.append(stats.mean)
|
||||
pass_rates.append(stats.pass_rate)
|
||||
|
||||
trace1 = {
|
||||
'x': categories,
|
||||
'y': means,
|
||||
'name': '平均得分',
|
||||
'type': 'bar',
|
||||
'marker': {'color': '#667eea'}
|
||||
}
|
||||
|
||||
trace2 = {
|
||||
'x': categories,
|
||||
'y': pass_rates,
|
||||
'name': '通过率',
|
||||
'type': 'bar',
|
||||
'marker': {'color': '#764ba2'}
|
||||
}
|
||||
|
||||
layout = {
|
||||
'barmode': 'group',
|
||||
'yaxis': {'range': [0, 1], 'title': '得分'},
|
||||
'xaxis': {'title': '指标'}
|
||||
}
|
||||
|
||||
return f"""
|
||||
var data = [{json.dumps(trace1)}, {json.dumps(trace2)}];
|
||||
var layout = {json.dumps(layout)};
|
||||
Plotly.newPlot('bar-chart', data, layout);
|
||||
"""
|
||||
|
||||
def _create_pass_rate_pie_chart(
|
||||
self,
|
||||
summary: EvaluationSummary
|
||||
) -> str:
|
||||
"""创建通过率饼图"""
|
||||
data = {
|
||||
'values': [summary.successful_questions, summary.failed_questions],
|
||||
'labels': ['成功', '失败'],
|
||||
'type': 'pie',
|
||||
'marker': {
|
||||
'colors': ['#10b981', '#ef4444']
|
||||
}
|
||||
}
|
||||
|
||||
layout = {
|
||||
'showlegend': True
|
||||
}
|
||||
|
||||
return f"""
|
||||
var data = [{json.dumps(data)}];
|
||||
var layout = {json.dumps(layout)};
|
||||
Plotly.newPlot('pie-chart', data, layout);
|
||||
"""
|
||||
|
||||
def create_trend_chart(
|
||||
self,
|
||||
history_data: List[Dict[str, Any]],
|
||||
output_path: str
|
||||
) -> None:
|
||||
"""
|
||||
创建趋势图
|
||||
|
||||
Args:
|
||||
history_data: 历史数据列表,每项包含 {timestamp, metrics}
|
||||
output_path: 输出路径
|
||||
"""
|
||||
if not history_data:
|
||||
raise ValueError("History data cannot be empty")
|
||||
|
||||
# 提取时间戳和指标
|
||||
timestamps = [item['timestamp'] for item in history_data]
|
||||
|
||||
# 获取所有指标名称
|
||||
metric_names = set()
|
||||
for item in history_data:
|
||||
metric_names.update(item['metrics'].keys())
|
||||
|
||||
# 创建子图
|
||||
fig = make_subplots(
|
||||
rows=len(metric_names),
|
||||
cols=1,
|
||||
subplot_titles=[self._translate_metric_name(m) for m in metric_names],
|
||||
vertical_spacing=0.05
|
||||
)
|
||||
|
||||
# 为每个指标添加趋势线
|
||||
for idx, metric_name in enumerate(sorted(metric_names), start=1):
|
||||
values = [
|
||||
item['metrics'].get(metric_name, None)
|
||||
for item in history_data
|
||||
]
|
||||
|
||||
fig.add_trace(
|
||||
go.Scatter(
|
||||
x=timestamps,
|
||||
y=values,
|
||||
mode='lines+markers',
|
||||
name=self._translate_metric_name(metric_name),
|
||||
line=dict(width=2),
|
||||
marker=dict(size=8)
|
||||
),
|
||||
row=idx,
|
||||
col=1
|
||||
)
|
||||
|
||||
# 更新布局
|
||||
fig.update_layout(
|
||||
height=300 * len(metric_names),
|
||||
title_text="评估指标历史趋势",
|
||||
showlegend=False
|
||||
)
|
||||
|
||||
# 保存为HTML
|
||||
fig.write_html(output_path)
|
||||
|
||||
def _translate_metric_name(self, metric_name: str) -> str:
|
||||
"""翻译指标名称为中文"""
|
||||
translations = {
|
||||
'context_recall': '上下文召回率',
|
||||
'context_precision': '上下文精确率',
|
||||
'mrr': '平均倒数排名',
|
||||
'ndcg': '归一化折损累计增益',
|
||||
'faithfulness': '忠实度',
|
||||
'answer_relevancy': '答案相关性',
|
||||
'correctness': '正确性'
|
||||
}
|
||||
return translations.get(metric_name, metric_name)
|
||||
|
||||
def _score_to_grade(self, score: float) -> str:
|
||||
"""将分数转换为等级"""
|
||||
if score >= 90:
|
||||
return 'A (优秀)'
|
||||
elif score >= 80:
|
||||
return 'B (良好)'
|
||||
elif score >= 70:
|
||||
return 'C (中等)'
|
||||
elif score >= 60:
|
||||
return 'D (及格)'
|
||||
else:
|
||||
return 'F (不及格)'
|
||||
Reference in new issue
Block a user