feat: 实现性能优化和可配置指标功能 (v2.1.0)

## 主要功能

### 并行评估优化 ⚡
- 实现指标并行执行,提升评估速度 1.25-1.42x
- 创建 ParallelRAGAsEvaluator 并行评估器
- 使用 asyncio.gather() 实现真正的并行

### 可配置指标功能 🎛️
- 支持通过参数启用/禁用特定评估指标
- 创建 ConfigurableRAGAsEvaluator 可配置评估器
- 灵活控制评估速度和质量(2.6-8x 加速)

### 交互式批处理脚本 🖥️
- 更新 evaluate_all_types_advanced.bat 支持优化选项
- 添加 3 种评估模式:完整/快速/极速
- 自动时间预估功能

## 性能提升

| 场景 | 原版 | 优化后 | 节省 |
|------|------|--------|------|
| 单问题 | 8.3分钟 | 1-3分钟 | 5-7分钟 |
| 15问题 | 125分钟 | 15-48分钟 | 77-110分钟 |
| 8系统×15问题 | 16.7小时 | 2-6.4小时 | 10-14.7小时 |

## 新增文件

**核心代码**:
- src/evaluators/parallel_ragas_evaluator.py - 并行评估器
- src/evaluators/configurable_evaluator.py - 可配置评估器

**测试脚本**:
- scripts/test_single_evaluation.py - 单系统评估测试
- scripts/test_report_save.py - 报告保存测试
- scripts/test_parallel_performance.py - 性能对比测试
- scripts/evaluate_single_system_parallel.py - 并行评估脚本
- scripts/evaluate_with_config.py - 可配置评估脚本
- scripts/evaluate_all_types.bat - 基础批处理脚本
- scripts/evaluate_all_types_advanced.bat - 增强批处理脚本(v2)

**文档**:
- docs/PERFORMANCE_ANALYSIS.md - 性能分析
- docs/METRICS_EXPLANATION.md - 指标说明
- docs/PARALLEL_OPTIMIZATION.md - 并行优化方案
- docs/PARALLEL_QUICK_START.md - 并行优化快速开始
- docs/DISABLE_METRICS_GUIDE.md - 禁用指标指南
- docs/OPTIMIZATION_SUMMARY.md - 优化功能总结
- docs/SINGLE_EVALUATION_TEST.md - 单系统测试报告

## 使用方法

### 批处理脚本(推荐)
```bash
scripts\evaluate_all_types_advanced.bat
```

### 命令行脚本
```bash
# 快速评估(禁用 answer_correctness)
python scripts/evaluate_with_config.py --system zht-excel --disable answer_correctness

# 极速评估(仅3个核心指标)
python scripts/evaluate_with_config.py --system zht-excel \
  --enable context_precision faithfulness answer_relevance

# 并行评估
python scripts/evaluate_single_system_parallel.py --system zht-excel
```

## 技术亮点

- 使用 asyncio.gather() 实现指标并行执行
- 支持通过参数灵活配置评估指标
- 保留完整的日志记录功能
- 向后兼容原有评估脚本

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
hughhuangandClaude Sonnet 4.5 committed 2026-01-08 08:45:43 +08:00
1 parent 9eb2e9c837
commit eb0897a31b
17 files changed
+4731 -148

No files matched your search

+298
View File
@@ -0,0 +1,298 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
单系统评估测试 - 验证结果保存功能
测试流程:
1. 构造单个验证数据
2. 运行单系统评估
3. 验证结果文件是否正确保存
"""
import sys
import os
import json
import shutil
from pathlib import Path
from datetime import datetime
# 设置 Windows 控制台编码为 UTF-8
if sys.platform == 'win32':
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
# 添加项目根目录到 Python 路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
def create_test_data():
"""创建测试数据文件"""
print("=" * 80)
print("步骤 1: 创建测试数据")
print("=" * 80)
# 构造单个测试数据
test_data = [{
"question_id": "q001",
"question": "签约流程是什么?",
"test_type": "简单检索",
"category": "positive",
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"logid": "test_log_id_001",
"performance": {
"total_time_ms": 5000,
"first_response_time_ms": 2000,
"knowledge_retrieval_time_ms": 1500,
"total_tokens": 1000
},
"answer": "PC端签约流程:在还款申请里面→选择到期还款→选择变更还款计划→提交就可以了。",
"knowledge_retrieval": {
"dataset_id": "test_dataset",
"query": "签约流程是什么?",
"parameters": {
"top_k": 10,
"min_score": 0.5
},
"retrieved_slices": [
{
"index": 0,
"score": 0.95,
"content": "{\"分类\":\"产品知识\",\"答案\":\"PC端签约流程:在还款申请里面→选择到期还款→选择变更还款计划→提交就可以了\",\"问题\":\"签约流程\"}",
"meta": {
"document": {"id": "test_doc_001"},
"slice_id": "test_slice_001"
}
}
]
}
}]
# 保存测试数据文件(使用 -excel 后缀以匹配系统名)
test_data_path = Path("data/test_sets/test-single-excel-raw-data.json")
test_data_path.parent.mkdir(parents=True, exist_ok=True)
with open(test_data_path, 'w', encoding='utf-8') as f:
json.dump(test_data, f, ensure_ascii=False, indent=2)
print(f"✅ 测试数据已创建: {test_data_path}")
print(f" 数据条目数: {len(test_data)}")
print(f" 问题ID: {test_data[0]['question_id']}")
print(f" 问题: {test_data[0]['question']}")
print()
return test_data_path
def run_evaluation(system_name: str):
"""运行单系统评估"""
import asyncio
from src.evaluators.batch_evaluator import BatchEvaluator
from src.reporters.json_reporter import JSONReporter
print("=" * 80)
print("步骤 2: 运行单系统评估")
print("=" * 80)
# 测试集路径
test_set_path = "data/test_sets/ragas_test_cases_v3.1.json"
print(f"系统名称: {system_name}")
print(f"测试集路径: {test_set_path}")
print(f"开始时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print()
# 创建批评估器
evaluator = BatchEvaluator(
systems=[system_name],
test_set_path=test_set_path,
enable_logging=True
)
# 运行评估(异步)
print("正在运行评估...")
result = asyncio.run(evaluator.evaluate_single_system(system_name))
print()
print("✅ 评估完成")
print(f" 结束时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print()
# 保存结果到文件
print("=" * 80)
print("保存评估结果")
print("=" * 80)
# 创建完整的结果结构
full_result = {
'metadata': {
'version': '1.0',
'evaluation_date': datetime.now().isoformat(),
'test_set': test_set_path,
'systems': [system_name]
},
'results': {
system_name: result
}
}
# 使用 JSONReporter 保存结果
reporter = JSONReporter()
output_path = f'data/results/{system_name}_test_{datetime.now().strftime("%Y%m%d_%H%M%S")}.json'
reporter.generate_report(all_results=full_result, output_path=output_path)
print(f"✅ 结果已保存到: {output_path}")
print()
return full_result
def verify_output_files(system_name: str):
"""验证输出文件"""
print("=" * 80)
print("步骤 3: 验证输出文件")
print("=" * 80)
# 定义要检查的文件
results_dir = Path("data/results")
logs_dir = Path("logs")
files_to_check = []
# 查找结果文件
if results_dir.exists():
result_files = list(results_dir.glob(f"{system_name}_*.json"))
files_to_check.extend(result_files)
# 查找日志文件
if logs_dir.exists():
log_files = list(logs_dir.glob(f"{system_name}_*.log"))
files_to_check.extend(log_files)
if not files_to_check:
print("❌ 未找到任何输出文件")
return False
print(f"找到 {len(files_to_check)} 个文件:")
print()
all_valid = True
for file_path in sorted(files_to_check):
exists = file_path.exists()
size_kb = file_path.stat().st_size / 1024 if exists else 0
status = "✅" if exists and size_kb > 0 else "❌"
print(f"{status} {file_path}")
print(f" 大小: {size_kb:.2f} KB")
# 如果是JSON文件,验证内容
if file_path.suffix == '.json' and exists and size_kb > 0:
try:
with open(file_path, 'r', encoding='utf-8') as f:
data = json.load(f)
print(f" 格式: JSON ✅")
# 检查必要字段
if 'metadata' in data:
print(f" metadata 字段: ✅")
if 'results' in data:
print(f" results 字段: ✅")
if system_name in data['results']:
print(f" {system_name} 结果: ✅")
result = data['results'][system_name]
if 'overall_score' in result:
print(f" overall_score: {result['overall_score']:.4f}")
if 'comparison' in data:
print(f" comparison 字段: ✅")
except json.JSONDecodeError as e:
print(f" ❌ JSON 解析失败: {e}")
all_valid = False
except Exception as e:
print(f" ❌ 验证失败: {e}")
all_valid = False
print()
return all_valid
def cleanup_test_data():
"""清理测试数据"""
print("=" * 80)
print("步骤 4: 清理测试数据")
print("=" * 80)
test_data_path = Path("data/test_sets/test-single-excel-raw-data.json")
if test_data_path.exists():
test_data_path.unlink()
print(f"✅ 已删除测试数据: {test_data_path}")
else:
print(f"⚠️ 测试数据不存在: {test_data_path}")
print()
def main():
"""主函数"""
print()
print("╔" + "=" * 78 + "╗")
print("║" + " " * 20 + "单系统评估测试" + " " * 44 + "║")
print("╚" + "=" * 78 + "╝")
print()
# 测试系统名称
test_system = "test-single-excel"
try:
# 步骤1: 创建测试数据
test_data_path = create_test_data()
# 步骤2: 运行评估
result = run_evaluation(test_system)
# 步骤3: 验证输出
success = verify_output_files(test_system)
# 步骤4: 清理测试数据
cleanup_test_data()
# 总结
print("=" * 80)
print("测试总结")
print("=" * 80)
if success:
print("✅ 所有测试通过!")
print()
print("评估结果已正确保存到文件:")
print(f" - 结果文件: data/results/{test_system}_*.json")
print(f" - 日志文件: logs/{test_system}_*.log")
else:
print("❌ 测试失败,请检查错误信息")
return 1
print("=" * 80)
print()
return 0
except Exception as e:
print()
print("=" * 80)
print("❌ 测试过程中发生错误")
print("=" * 80)
print(f"错误类型: {type(e).__name__}")
print(f"错误信息: {e}")
print()
import traceback
traceback.print_exc()
return 1
if __name__ == '__main__':
exit_code = main()
input("\n按 Enter 键退出...")
sys.exit(exit_code)