docs: 完善项目文档体系
## 新增文档 ### 核心文档 - README.md: 项目主要说明文档,包含快速开始、功能介绍、使用指南 - docs/ARCHITECTURE.md: 架构设计文档,详细说明系统架构和技术选型 - docs/DEVELOPMENT_GUIDE.md: 开发指南,包含环境搭建、代码规范、测试指南 - docs/progress/TODO.md: 项目待办事项和进度追踪 ### 工作总结 - docs/SESSION_SUMMARY_2025-01-07.md: 测试集精修工作总结 ## 新增代码模块 ### 评估器模块 - src/evaluators/ragas_evaluator.py: RAGAs评估器实现 - src/evaluators/batch_evaluator.py: 批量评估器 ### 报告模块 - src/reporters/json_reporter.py: JSON格式报告生成器 ### 转换器模块 - src/transformers/data_converter.py: 数据格式转换器 ### 工具模块 - src/utils/llm_config.py: LLM配置管理 ## 文档特点 - 📖 完整的项目说明和快速开始指南 - 🏗️ 详细的架构设计和技术选型说明 - 👨💻 实用的开发指南和最佳实践 - 📋 清晰的待办事项和进度追踪 - 🎯 明确的里程碑和优先级 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f10d5492a1
commit
7fe9a7241e
16 files changed
+3023
-1
No files matched your search
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,123 @@
|
||||
"""
|
||||
批量评估管理器:管理多系统批量评估流程
|
||||
"""
|
||||
import asyncio
|
||||
from typing import Dict, List
|
||||
from datetime import datetime
|
||||
from src.transformers.data_converter import DataConverter
|
||||
from src.evaluators.ragas_evaluator import RAGAsEvaluator
|
||||
|
||||
|
||||
class BatchEvaluator:
|
||||
"""管理多系统批量评估流程"""
|
||||
|
||||
def __init__(self, systems: List[str], test_set_path: str, llm, embeddings):
|
||||
"""
|
||||
初始化批量评估器
|
||||
|
||||
Args:
|
||||
systems: 系统名称列表
|
||||
test_set_path: 测试集路径
|
||||
llm: 评估用 LLM
|
||||
embeddings: Embedding 模型
|
||||
"""
|
||||
self.systems = systems
|
||||
self.test_set_path = test_set_path
|
||||
self.converter = DataConverter(test_set_path)
|
||||
self.ragas_evaluator = RAGAsEvaluator(llm, embeddings)
|
||||
|
||||
async def evaluate_single_system(self, system: str) -> Dict:
|
||||
"""
|
||||
评估单个系统
|
||||
|
||||
Args:
|
||||
system: 系统名称
|
||||
|
||||
Returns:
|
||||
评估结果字典
|
||||
"""
|
||||
print(f"\n{'='*80}")
|
||||
print(f"Evaluating system: {system.upper()}")
|
||||
print(f"{'='*80}")
|
||||
|
||||
# 加载并转换数据
|
||||
print(f"[1/3] Loading and converting data...")
|
||||
positive_cases, negative_cases = self.converter.merge_data_for_system(system)
|
||||
|
||||
print(f" - Positive cases: {len(positive_cases)}")
|
||||
print(f" - Negative cases: {len(negative_cases)}")
|
||||
|
||||
# 评估正向用例
|
||||
print(f"\n[2/3] Evaluating positive cases...")
|
||||
positive_results = await self.ragas_evaluator.evaluate_batch(positive_cases)
|
||||
|
||||
# 评估负向用例
|
||||
print(f"\n[3/3] Evaluating negative cases...")
|
||||
negative_results = await self.ragas_evaluator.evaluate_batch(negative_cases)
|
||||
|
||||
# 聚合结果
|
||||
result = {
|
||||
'system': system,
|
||||
'timestamp': datetime.now().isoformat(),
|
||||
'positive_cases': {
|
||||
'count': len(positive_cases),
|
||||
'results': positive_results
|
||||
},
|
||||
'negative_cases': {
|
||||
'count': len(negative_cases),
|
||||
'results': negative_results
|
||||
}
|
||||
}
|
||||
|
||||
print(f"\n[DONE] System {system} evaluation completed!")
|
||||
|
||||
return result
|
||||
|
||||
async def evaluate_all_systems(self) -> Dict:
|
||||
"""
|
||||
评估所有系统
|
||||
|
||||
Returns:
|
||||
所有系统的评估结果
|
||||
"""
|
||||
print(f"\n{'='*80}")
|
||||
print(f"Starting batch evaluation for {len(self.systems)} systems")
|
||||
print(f"Systems: {', '.join(self.systems)}")
|
||||
print(f"{'='*80}")
|
||||
|
||||
all_results = {}
|
||||
|
||||
for system in self.systems:
|
||||
try:
|
||||
result = await self.evaluate_single_system(system)
|
||||
all_results[system] = result
|
||||
except Exception as e:
|
||||
print(f"\nError evaluating system {system}: {e}")
|
||||
all_results[system] = {
|
||||
'system': system,
|
||||
'error': str(e),
|
||||
'timestamp': datetime.now().isoformat()
|
||||
}
|
||||
|
||||
return {
|
||||
'metadata': {
|
||||
'version': '1.0',
|
||||
'evaluation_date': datetime.now().isoformat(),
|
||||
'test_set': self.test_set_path,
|
||||
'systems': self.systems
|
||||
},
|
||||
'results': all_results
|
||||
}
|
||||
|
||||
def aggregate_results(self, all_results: Dict) -> Dict:
|
||||
"""
|
||||
聚合评估结果
|
||||
|
||||
Args:
|
||||
all_results: 所有系统的评估结果
|
||||
|
||||
Returns:
|
||||
聚合后的结果
|
||||
"""
|
||||
# 这个方法将在 JSONReporter 中实现
|
||||
pass
|
||||
@@ -0,0 +1,112 @@
|
||||
"""
|
||||
RAGAs 评估器:使用 RAGAs 框架进行评估
|
||||
"""
|
||||
import asyncio
|
||||
from typing import Dict, List
|
||||
from ragas.dataset_schema import SingleTurnSample
|
||||
from ragas.metrics import (
|
||||
LLMContextPrecisionWithReference,
|
||||
LLMContextRecall,
|
||||
Faithfulness,
|
||||
ResponseRelevancy,
|
||||
AnswerCorrectness
|
||||
)
|
||||
|
||||
|
||||
class RAGAsEvaluator:
|
||||
"""使用 RAGAs 框架进行评估"""
|
||||
|
||||
def __init__(self, llm, embeddings):
|
||||
"""
|
||||
初始化评估器
|
||||
|
||||
Args:
|
||||
llm: RAGAs 兼容的 LLM
|
||||
embeddings: Embedding 模型
|
||||
"""
|
||||
self.llm = llm
|
||||
embeddings = embeddings
|
||||
|
||||
# 初始化评估指标
|
||||
self.metrics = {
|
||||
'context_precision': LLMContextPrecisionWithReference(llm=llm),
|
||||
'context_recall': LLMContextRecall(llm=llm),
|
||||
'faithfulness': Faithfulness(llm=llm),
|
||||
'answer_relevance': ResponseRelevancy(llm=llm, embeddings=embeddings),
|
||||
'answer_correctness': AnswerCorrectness(llm=llm, embeddings=embeddings)
|
||||
}
|
||||
|
||||
async def evaluate_single(self, sample_data: Dict) -> Dict[str, float]:
|
||||
"""
|
||||
评估单个样本
|
||||
|
||||
Args:
|
||||
sample_data: 样本数据(RAGAs 格式)
|
||||
|
||||
Returns:
|
||||
各指标得分字典
|
||||
"""
|
||||
# 创建 SingleTurnSample
|
||||
sample = SingleTurnSample(
|
||||
user_input=sample_data['user_input'],
|
||||
response=sample_data['response'],
|
||||
reference=sample_data['reference'],
|
||||
retrieved_contexts=sample_data['retrieved_contexts']
|
||||
)
|
||||
|
||||
# 评估各指标
|
||||
results = {}
|
||||
for metric_name, metric in self.metrics.items():
|
||||
try:
|
||||
score = await metric.single_turn_ascore(sample)
|
||||
results[metric_name] = float(score) if score is not None else 0.0
|
||||
except Exception as e:
|
||||
print(f"Error evaluating {metric_name} for {sample_data.get('question_id')}: {e}")
|
||||
results[metric_name] = 0.0
|
||||
|
||||
return results
|
||||
|
||||
async def evaluate_batch(self, samples: List[Dict]) -> List[Dict]:
|
||||
"""
|
||||
批量评估样本
|
||||
|
||||
Args:
|
||||
samples: 样本列表
|
||||
|
||||
Returns:
|
||||
评估结果列表
|
||||
"""
|
||||
results = []
|
||||
|
||||
for i, sample in enumerate(samples):
|
||||
print(f"Evaluating sample {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
|
||||
|
||||
def separate_positive_negative(self, samples: List[Dict]) -> tuple:
|
||||
"""
|
||||
分离正向和负向用例
|
||||
|
||||
Args:
|
||||
samples: 样本列表
|
||||
|
||||
Returns:
|
||||
(正向用例, 负向用例)
|
||||
"""
|
||||
positive = [s for s in samples if s.get('category') == 'positive']
|
||||
negative = [s for s in samples if s.get('category') == 'negative']
|
||||
|
||||
return positive, negative
|
||||
Whitespace-only changes.
@@ -0,0 +1,269 @@
|
||||
"""
|
||||
JSON 报告生成器:生成 JSON 格式评估报告
|
||||
"""
|
||||
import json
|
||||
from typing import Dict, List
|
||||
from pathlib import Path
|
||||
import numpy as np
|
||||
|
||||
|
||||
class JSONReporter:
|
||||
"""生成 JSON 格式评估报告"""
|
||||
|
||||
def calculate_statistics(self, scores: List[float]) -> Dict:
|
||||
"""
|
||||
计算统计信息
|
||||
|
||||
Args:
|
||||
scores: 分数列表
|
||||
|
||||
Returns:
|
||||
统计信息字典
|
||||
"""
|
||||
if not scores:
|
||||
return {
|
||||
'mean': 0.0,
|
||||
'median': 0.0,
|
||||
'std': 0.0,
|
||||
'min': 0.0,
|
||||
'max': 0.0,
|
||||
'count': 0
|
||||
}
|
||||
|
||||
return {
|
||||
'mean': round(float(np.mean(scores)), 4),
|
||||
'median': round(float(np.median(scores)), 4),
|
||||
'std': round(float(np.std(scores)), 4),
|
||||
'min': round(float(np.min(scores)), 4),
|
||||
'max': round(float(np.max(scores)), 4),
|
||||
'count': len(scores)
|
||||
}
|
||||
|
||||
def aggregate_metric_scores(self, results: List[Dict], metric_name: str) -> Dict:
|
||||
"""
|
||||
聚合单个指标的分数
|
||||
|
||||
Args:
|
||||
results: 评估结果列表
|
||||
metric_name: 指标名称
|
||||
|
||||
Returns:
|
||||
聚合后的指标统计
|
||||
"""
|
||||
scores = []
|
||||
per_question = {}
|
||||
|
||||
for result in results:
|
||||
qid = result.get('question_id')
|
||||
score = result.get('scores', {}).get(metric_name, 0.0)
|
||||
scores.append(score)
|
||||
per_question[qid] = score
|
||||
|
||||
stats = self.calculate_statistics(scores)
|
||||
stats['per_question'] = per_question
|
||||
|
||||
return stats
|
||||
|
||||
def process_system_results(self, system_result: Dict) -> Dict:
|
||||
"""
|
||||
处理单个系统的评估结果
|
||||
|
||||
Args:
|
||||
system_result: 系统评估结果
|
||||
|
||||
Returns:
|
||||
处理后的结果
|
||||
"""
|
||||
if 'error' in system_result:
|
||||
return system_result
|
||||
|
||||
# 处理正向用例
|
||||
positive_results = system_result.get('positive_cases', {}).get('results', [])
|
||||
positive_metrics = {}
|
||||
|
||||
for metric_name in ['context_precision', 'context_recall', 'faithfulness',
|
||||
'answer_relevance', 'answer_correctness']:
|
||||
positive_metrics[metric_name] = self.aggregate_metric_scores(
|
||||
positive_results, metric_name
|
||||
)
|
||||
|
||||
# 处理负向用例
|
||||
negative_results = system_result.get('negative_cases', {}).get('results', [])
|
||||
negative_metrics = {}
|
||||
|
||||
# 负向用例只评估部分指标
|
||||
for metric_name in ['faithfulness']:
|
||||
negative_metrics[metric_name] = self.aggregate_metric_scores(
|
||||
negative_results, metric_name
|
||||
)
|
||||
|
||||
# 计算拒绝率(自定义指标)
|
||||
rejection_count = sum(
|
||||
1 for r in negative_results
|
||||
if '无法' in r.get('scores', {}).get('response', '') or
|
||||
'不相关' in r.get('scores', {}).get('response', '')
|
||||
)
|
||||
rejection_rate = rejection_count / len(negative_results) if negative_results else 0.0
|
||||
|
||||
negative_metrics['rejection_rate'] = {
|
||||
'value': round(rejection_rate, 4),
|
||||
'count': rejection_count,
|
||||
'total': len(negative_results)
|
||||
}
|
||||
|
||||
# 计算整体得分(正向用例的平均分)
|
||||
overall_scores = []
|
||||
for metric_stats in positive_metrics.values():
|
||||
overall_scores.append(metric_stats['mean'])
|
||||
|
||||
overall_score = round(np.mean(overall_scores), 4) if overall_scores else 0.0
|
||||
|
||||
return {
|
||||
'system': system_result.get('system'),
|
||||
'timestamp': system_result.get('timestamp'),
|
||||
'positive_cases': positive_metrics,
|
||||
'negative_cases': negative_metrics,
|
||||
'overall_score': overall_score
|
||||
}
|
||||
|
||||
def compare_systems(self, processed_results: Dict) -> Dict:
|
||||
"""
|
||||
对比多个系统
|
||||
|
||||
Args:
|
||||
processed_results: 处理后的结果
|
||||
|
||||
Returns:
|
||||
对比结果
|
||||
"""
|
||||
# 找出每个指标的最佳系统
|
||||
best_performer = {}
|
||||
metrics = ['context_precision', 'context_recall', 'faithfulness',
|
||||
'answer_relevance', 'answer_correctness']
|
||||
|
||||
for metric in metrics:
|
||||
best_system = None
|
||||
best_score = -1
|
||||
|
||||
for system, result in processed_results.items():
|
||||
if 'error' in result:
|
||||
continue
|
||||
|
||||
score = result.get('positive_cases', {}).get(metric, {}).get('mean', 0.0)
|
||||
if score > best_score:
|
||||
best_score = score
|
||||
best_system = system
|
||||
|
||||
best_performer[metric] = best_system
|
||||
|
||||
# 系统排名(基于 overall_score)
|
||||
system_scores = []
|
||||
for system, result in processed_results.items():
|
||||
if 'error' not in result:
|
||||
system_scores.append((system, result.get('overall_score', 0.0)))
|
||||
|
||||
system_scores.sort(key=lambda x: x[1], reverse=True)
|
||||
ranking = [s[0] for s in system_scores]
|
||||
|
||||
return {
|
||||
'best_performer': best_performer,
|
||||
'ranking': ranking,
|
||||
'scores': {s: score for s, score in system_scores}
|
||||
}
|
||||
|
||||
def analyze_by_question_type(self, all_results: Dict) -> Dict:
|
||||
"""
|
||||
按问题类型分析
|
||||
|
||||
Args:
|
||||
all_results: 所有系统的原始评估结果
|
||||
|
||||
Returns:
|
||||
按问题类型的分析结果
|
||||
"""
|
||||
type_analysis = {}
|
||||
|
||||
for system, system_result in all_results.items():
|
||||
if 'error' in system_result:
|
||||
continue
|
||||
|
||||
positive_results = system_result.get('positive_cases', {}).get('results', [])
|
||||
|
||||
for result in positive_results:
|
||||
q_type = result.get('type', 'unknown')
|
||||
if q_type not in type_analysis:
|
||||
type_analysis[q_type] = {}
|
||||
|
||||
# 计算该问题类型的平均分
|
||||
scores = result.get('scores', {})
|
||||
avg_score = np.mean(list(scores.values())) if scores else 0.0
|
||||
|
||||
type_analysis[q_type][system] = round(avg_score, 4)
|
||||
|
||||
return type_analysis
|
||||
|
||||
def generate_report(self, all_results: Dict, output_path: str):
|
||||
"""
|
||||
生成完整的 JSON 报告
|
||||
|
||||
Args:
|
||||
all_results: 所有系统的评估结果
|
||||
output_path: 输出文件路径
|
||||
"""
|
||||
print(f"\n{'='*80}")
|
||||
print(f"Generating JSON report...")
|
||||
print(f"{'='*80}")
|
||||
|
||||
# 处理每个系统的结果
|
||||
processed_results = {}
|
||||
for system, result in all_results.get('results', {}).items():
|
||||
processed_results[system] = self.process_system_results(result)
|
||||
|
||||
# 系统对比
|
||||
comparison = self.compare_systems(processed_results)
|
||||
|
||||
# 按问题类型分析
|
||||
type_analysis = self.analyze_by_question_type(all_results.get('results', {}))
|
||||
|
||||
# 构建最终报告
|
||||
report = {
|
||||
'metadata': all_results.get('metadata', {}),
|
||||
'results': processed_results,
|
||||
'comparison': comparison,
|
||||
'analysis_by_question_type': type_analysis
|
||||
}
|
||||
|
||||
# 保存报告
|
||||
output_file = Path(output_path)
|
||||
output_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
with open(output_file, 'w', encoding='utf-8') as f:
|
||||
json.dump(report, f, ensure_ascii=False, indent=2)
|
||||
|
||||
print(f"\n[SUCCESS] Report saved to: {output_path}")
|
||||
|
||||
# 打印摘要
|
||||
self.print_summary(report)
|
||||
|
||||
def print_summary(self, report: Dict):
|
||||
"""打印评估摘要"""
|
||||
print(f"\n{'='*80}")
|
||||
print(f"Evaluation Summary")
|
||||
print(f"{'='*80}")
|
||||
|
||||
results = report.get('results', {})
|
||||
comparison = report.get('comparison', {})
|
||||
|
||||
# 打印系统排名
|
||||
print(f"\nSystem Ranking (by overall score):")
|
||||
for i, system in enumerate(comparison.get('ranking', []), 1):
|
||||
score = comparison.get('scores', {}).get(system, 0.0)
|
||||
print(f" {i}. {system:8s}: {score:.4f}")
|
||||
|
||||
# 打印各指标最佳系统
|
||||
print(f"\nBest Performer by Metric:")
|
||||
for metric, system in comparison.get('best_performer', {}).items():
|
||||
score = results.get(system, {}).get('positive_cases', {}).get(metric, {}).get('mean', 0.0)
|
||||
print(f" {metric:20s}: {system:8s} ({score:.4f})")
|
||||
|
||||
print(f"\n{'='*80}")
|
||||
Whitespace-only changes.
@@ -0,0 +1,243 @@
|
||||
"""
|
||||
数据转换器:将测试集和验证结果转换为 RAGAs 格式
|
||||
"""
|
||||
import json
|
||||
from typing import Dict, List, Tuple
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class DataConverter:
|
||||
"""将测试集和验证结果转换为 RAGAs 格式"""
|
||||
|
||||
def __init__(self, test_set_path: str):
|
||||
"""
|
||||
初始化数据转换器
|
||||
|
||||
Args:
|
||||
test_set_path: 测试集文件路径
|
||||
"""
|
||||
self.test_set_path = test_set_path
|
||||
self.test_cases = self.load_test_cases()
|
||||
|
||||
def load_test_cases(self) -> Dict:
|
||||
"""加载测试集"""
|
||||
with open(self.test_set_path, 'r', encoding='utf-8') as f:
|
||||
return json.load(f)
|
||||
|
||||
def load_validation_results(self, system: str, data_dir: str = 'data/test_sets') -> List[Dict]:
|
||||
"""
|
||||
加载验证结果
|
||||
|
||||
Args:
|
||||
system: 系统名称 (coze/kbs/zht/zhtv2)
|
||||
data_dir: 数据目录
|
||||
|
||||
Returns:
|
||||
验证结果列表
|
||||
"""
|
||||
# 优先使用 excel 格式数据
|
||||
file_path = Path(data_dir) / f'{system}-excel-raw-data.json'
|
||||
|
||||
if not file_path.exists():
|
||||
# 尝试 text 格式
|
||||
file_path = Path(data_dir) / f'{system}-text-raw-data.json'
|
||||
|
||||
if not file_path.exists():
|
||||
raise FileNotFoundError(f"Cannot find validation data for system: {system}")
|
||||
|
||||
with open(file_path, 'r', encoding='utf-8') as f:
|
||||
data = json.load(f)
|
||||
|
||||
# KBS 系统特殊处理:数据在 data 字段下
|
||||
if system == 'kbs' and isinstance(data, dict) and 'data' in data:
|
||||
return data['data']
|
||||
|
||||
# 其他系统直接返回列表
|
||||
return data if isinstance(data, list) else []
|
||||
|
||||
def extract_retrieved_contexts(self, validation_result: Dict, system: str) -> List[str]:
|
||||
"""
|
||||
提取检索上下文
|
||||
|
||||
Args:
|
||||
validation_result: 验证结果
|
||||
system: 系统名称
|
||||
|
||||
Returns:
|
||||
检索上下文列表
|
||||
"""
|
||||
retrieved_contexts = []
|
||||
|
||||
# KBS 系统特殊处理
|
||||
if system == 'kbs':
|
||||
# KBS 的检索上下文在 response.data[].fileSource 中
|
||||
response_data = validation_result.get('response', {})
|
||||
data_list = response_data.get('data', [])
|
||||
|
||||
for item in data_list:
|
||||
# 尝试从 fileSource 提取
|
||||
file_source = item.get('fileSource', '')
|
||||
if file_source:
|
||||
try:
|
||||
# fileSource 是 JSON 字符串
|
||||
source_data = json.loads(file_source)
|
||||
# 提取 references 中的内容
|
||||
references = source_data.get('references', [])
|
||||
for ref in references:
|
||||
paragraphs = ref.get('paragraphs', [])
|
||||
for para in paragraphs:
|
||||
content = para.get('content', '')
|
||||
if content:
|
||||
retrieved_contexts.append(content)
|
||||
except (json.JSONDecodeError, AttributeError):
|
||||
pass
|
||||
|
||||
# 其他系统(Coze/ZHT/ZHTv2)
|
||||
else:
|
||||
if 'knowledge_retrieval' in validation_result:
|
||||
kr = validation_result['knowledge_retrieval']
|
||||
if kr and 'retrieved_slices' in kr:
|
||||
slices = kr['retrieved_slices']
|
||||
if slices:
|
||||
for slice_data in slices:
|
||||
content = slice_data.get('content', '')
|
||||
if isinstance(content, str) and content.startswith('{'):
|
||||
try:
|
||||
content_json = json.loads(content)
|
||||
# 提取答案字段
|
||||
if '答案' in content_json:
|
||||
retrieved_contexts.append(content_json['答案'])
|
||||
elif 'answer' in content_json:
|
||||
retrieved_contexts.append(content_json['answer'])
|
||||
else:
|
||||
# 如果没有答案字段,使用整个内容
|
||||
retrieved_contexts.append(content)
|
||||
except json.JSONDecodeError:
|
||||
retrieved_contexts.append(content)
|
||||
else:
|
||||
retrieved_contexts.append(content)
|
||||
|
||||
return retrieved_contexts
|
||||
|
||||
def convert_to_ragas_format(
|
||||
self,
|
||||
test_case: Dict,
|
||||
validation_result: Dict,
|
||||
system: str
|
||||
) -> Dict:
|
||||
"""
|
||||
转换为 RAGAs 格式
|
||||
|
||||
Args:
|
||||
test_case: 测试用例
|
||||
validation_result: 验证结果
|
||||
system: 系统名称
|
||||
|
||||
Returns:
|
||||
RAGAs 格式的数据
|
||||
"""
|
||||
# KBS 系统特殊处理
|
||||
if system == 'kbs':
|
||||
response_data = validation_result.get('response', {})
|
||||
data_list = response_data.get('data', [])
|
||||
|
||||
if not data_list:
|
||||
# 如果没有 data,返回空响应
|
||||
return {
|
||||
'question_id': validation_result.get('question_id', ''),
|
||||
'user_input': validation_result.get('title', ''),
|
||||
'response': '',
|
||||
'reference': test_case.get('ground_truth', ''),
|
||||
'retrieved_contexts': [],
|
||||
'category': test_case.get('category', ''),
|
||||
'type': test_case.get('type', ''),
|
||||
'metadata': {
|
||||
'system': system,
|
||||
'test_type': test_case.get('type', ''),
|
||||
}
|
||||
}
|
||||
|
||||
# 提取第一个问题的数据
|
||||
first_item = data_list[0]
|
||||
question = first_item.get('question', '')
|
||||
answer = first_item.get('content', '')
|
||||
|
||||
# 提取检索上下文
|
||||
retrieved_contexts = self.extract_retrieved_contexts(validation_result, system)
|
||||
|
||||
return {
|
||||
'question_id': validation_result.get('question_id', ''),
|
||||
'user_input': question,
|
||||
'response': answer,
|
||||
'reference': test_case.get('ground_truth', ''),
|
||||
'retrieved_contexts': retrieved_contexts,
|
||||
'category': test_case.get('category', ''),
|
||||
'type': test_case.get('type', ''),
|
||||
'metadata': {
|
||||
'system': system,
|
||||
'test_type': test_case.get('type', ''),
|
||||
}
|
||||
}
|
||||
|
||||
# 其他系统(Coze/ZHT/ZHTv2)
|
||||
else:
|
||||
# 提取检索上下文
|
||||
retrieved_contexts = self.extract_retrieved_contexts(validation_result, system)
|
||||
|
||||
return {
|
||||
'question_id': validation_result.get('question_id', ''),
|
||||
'user_input': validation_result.get('question', ''),
|
||||
'response': validation_result.get('answer', ''),
|
||||
'reference': test_case.get('ground_truth', ''),
|
||||
'retrieved_contexts': retrieved_contexts,
|
||||
'category': test_case.get('category', ''),
|
||||
'type': test_case.get('type', ''),
|
||||
'metadata': {
|
||||
'system': system,
|
||||
'test_type': test_case.get('type', ''),
|
||||
}
|
||||
}
|
||||
|
||||
def merge_data_for_system(self, system: str, data_dir: str = 'data/test_sets') -> Tuple[List[Dict], List[Dict]]:
|
||||
"""
|
||||
合并测试集和验证结果,并分离正负向用例
|
||||
|
||||
Args:
|
||||
system: 系统名称
|
||||
data_dir: 数据目录
|
||||
|
||||
Returns:
|
||||
(正向用例列表, 负向用例列表)
|
||||
"""
|
||||
# 加载验证结果
|
||||
validation_results = self.load_validation_results(system, data_dir)
|
||||
|
||||
# 创建 question_id 到测试用例的映射
|
||||
test_case_map = {
|
||||
case['question_id']: case
|
||||
for case in self.test_cases.get('test_cases', [])
|
||||
}
|
||||
|
||||
positive_cases = []
|
||||
negative_cases = []
|
||||
|
||||
for result in validation_results:
|
||||
qid = result.get('question_id', '')
|
||||
|
||||
# 跳过测试集中没有的用例
|
||||
if qid not in test_case_map:
|
||||
print(f"Warning: {qid} not in test cases, skipping")
|
||||
continue
|
||||
|
||||
test_case = test_case_map[qid]
|
||||
|
||||
# 转换为 RAGAs 格式
|
||||
ragas_sample = self.convert_to_ragas_format(test_case, result, system)
|
||||
|
||||
# 根据类别分离
|
||||
if test_case.get('category') == 'positive':
|
||||
positive_cases.append(ragas_sample)
|
||||
elif test_case.get('category') == 'negative':
|
||||
negative_cases.append(ragas_sample)
|
||||
|
||||
return positive_cases, negative_cases
|
||||
Whitespace-only changes.
@@ -0,0 +1,112 @@
|
||||
"""
|
||||
LLM 配置模块:初始化评估所需的 LLM 和 Embedding 模型
|
||||
"""
|
||||
import os
|
||||
from typing import Dict
|
||||
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
|
||||
from ragas.llms import LangchainLLMWrapper
|
||||
|
||||
|
||||
def get_evaluator_llm(model: str = "gpt-4o-mini", temperature: float = 0.0):
|
||||
"""
|
||||
获取评估用 LLM
|
||||
|
||||
Args:
|
||||
model: 模型名称,默认 gpt-4o-mini(平衡成本和质量)
|
||||
temperature: 温度参数,默认 0.0(确保评估一致性)
|
||||
|
||||
Returns:
|
||||
RAGAs 兼容的 LLM 包装器
|
||||
"""
|
||||
# 检查 API key
|
||||
if not os.getenv('OPENAI_API_KEY'):
|
||||
raise ValueError(
|
||||
"OPENAI_API_KEY not found in environment variables. "
|
||||
"Please set it before running evaluation."
|
||||
)
|
||||
|
||||
# 初始化 LangChain LLM
|
||||
llm = ChatOpenAI(
|
||||
model=model,
|
||||
temperature=temperature,
|
||||
timeout=30,
|
||||
max_retries=3
|
||||
)
|
||||
|
||||
# 包装为 RAGAs 兼容格式
|
||||
return LangchainLLMWrapper(llm)
|
||||
|
||||
|
||||
def get_evaluator_embeddings(model: str = "text-embedding-3-small"):
|
||||
"""
|
||||
获取评估用 Embedding 模型
|
||||
|
||||
Args:
|
||||
model: Embedding 模型名称
|
||||
|
||||
Returns:
|
||||
OpenAI Embeddings 实例
|
||||
"""
|
||||
# 检查 API key
|
||||
if not os.getenv('OPENAI_API_KEY'):
|
||||
raise ValueError(
|
||||
"OPENAI_API_KEY not found in environment variables. "
|
||||
"Please set it before running evaluation."
|
||||
)
|
||||
|
||||
return OpenAIEmbeddings(model=model)
|
||||
|
||||
|
||||
def estimate_cost(num_samples: int, num_metrics: int = 5) -> Dict[str, float]:
|
||||
"""
|
||||
估算评估成本
|
||||
|
||||
Args:
|
||||
num_samples: 样本数量
|
||||
num_metrics: 指标数量
|
||||
|
||||
Returns:
|
||||
成本估算字典
|
||||
"""
|
||||
# 每个指标的平均 token 消耗(估算)
|
||||
tokens_per_metric = {
|
||||
'context_precision': 500,
|
||||
'context_recall': 800,
|
||||
'faithfulness': 700,
|
||||
'answer_relevance': 600, # + embedding
|
||||
'answer_correctness': 900, # + embedding
|
||||
}
|
||||
|
||||
# GPT-4o-mini 定价(2025年1月)
|
||||
# Input: $0.150 / 1M tokens
|
||||
# Output: $0.600 / 1M tokens
|
||||
input_price_per_1m = 0.150
|
||||
output_price_per_1m = 0.600
|
||||
|
||||
# Embedding 定价
|
||||
# text-embedding-3-small: $0.020 / 1M tokens
|
||||
embedding_price_per_1m = 0.020
|
||||
|
||||
# 估算总 token 消耗
|
||||
total_tokens = sum(tokens_per_metric.values()) * num_samples
|
||||
# 假设 input:output = 3:1
|
||||
input_tokens = total_tokens * 0.75
|
||||
output_tokens = total_tokens * 0.25
|
||||
|
||||
# LLM 成本
|
||||
llm_cost = (input_tokens / 1_000_000 * input_price_per_1m +
|
||||
output_tokens / 1_000_000 * output_price_per_1m)
|
||||
|
||||
# Embedding 成本(answer_relevance 和 answer_correctness 各需要 2 次)
|
||||
embedding_tokens = num_samples * 2 * 2 * 500 # 估算每次 500 tokens
|
||||
embedding_cost = embedding_tokens / 1_000_000 * embedding_price_per_1m
|
||||
|
||||
total_cost = llm_cost + embedding_cost
|
||||
|
||||
return {
|
||||
'total_cost': round(total_cost, 4),
|
||||
'llm_cost': round(llm_cost, 4),
|
||||
'embedding_cost': round(embedding_cost, 4),
|
||||
'total_tokens': int(total_tokens),
|
||||
'cost_per_sample': round(total_cost / num_samples, 6) if num_samples > 0 else 0
|
||||
}
|
||||
Reference in new issue
Block a user