146 lines
4.8 KiB
Python
146 lines
4.8 KiB
Python
#!/usr/bin/env python
|
|||
|
|
# -*- coding: utf-8 -*-
|
||
|
|
"""
|
||
|
|
最终验证:测试完整的 RAGAs 评估流程
|
||
|
|
"""
|
||
|
|
import sys
|
||
|
|
import os
|
||
|
|
|
||
|
|
# 设置 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__))))
|
||
|
|
|
||
|
|
import asyncio
|
||
|
|
from dotenv import load_dotenv
|
||
|
|
from src.utils.llm_config import get_evaluator_llm, get_evaluator_embeddings
|
||
|
|
from ragas.dataset_schema import SingleTurnSample
|
||
|
|
from ragas.metrics import (
|
||
|
|
LLMContextPrecisionWithReference,
|
||
|
|
LLMContextRecall,
|
||
|
|
Faithfulness,
|
||
|
|
ResponseRelevancy,
|
||
|
|
AnswerCorrectness,
|
||
|
|
SemanticSimilarity
|
||
|
|
)
|
||
|
|
|
||
|
|
load_dotenv()
|
||
|
|
|
||
|
|
|
||
|
|
async def test_ragas_evaluation():
|
||
|
|
"""测试完整的 RAGAs 评估流程"""
|
||
|
|
print("=" * 80)
|
||
|
|
print("RAGAs 完整评估流程测试")
|
||
|
|
print("=" * 80)
|
||
|
|
|
||
|
|
try:
|
||
|
|
# 1. 初始化 LLM 和 Embeddings
|
||
|
|
print("\n步骤 1: 初始化 LLM 和 Embeddings...")
|
||
|
|
llm = get_evaluator_llm()
|
||
|
|
embeddings = get_evaluator_embeddings()
|
||
|
|
print("✅ LLM 和 Embeddings 初始化成功")
|
||
|
|
|
||
|
|
# 2. 初始化评估指标
|
||
|
|
print("\n步骤 2: 初始化评估指标...")
|
||
|
|
|
||
|
|
# 创建 AnswerSimilarity 用于 AnswerCorrectness
|
||
|
|
answer_similarity = SemanticSimilarity(embeddings=embeddings)
|
||
|
|
|
||
|
|
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,
|
||
|
|
answer_similarity=answer_similarity
|
||
|
|
)
|
||
|
|
}
|
||
|
|
print("✅ 评估指标初始化成功")
|
||
|
|
print(f" - 共 {len(metrics)} 个指标")
|
||
|
|
|
||
|
|
# 3. 创建测试样本
|
||
|
|
print("\n步骤 3: 创建测试样本...")
|
||
|
|
sample = SingleTurnSample(
|
||
|
|
user_input="什么是催收业务?",
|
||
|
|
response="催收业务是指金融机构或专业催收公司对逾期未还款项进行追讨的业务活动。",
|
||
|
|
reference="催收业务是金融领域中针对逾期债务进行追讨和管理的服务。",
|
||
|
|
retrieved_contexts=[
|
||
|
|
"催收业务主要包括电话催收、上门催收、法律催收等方式。",
|
||
|
|
"催收需要遵守相关法律法规,不得采用暴力、威胁等非法手段。"
|
||
|
|
]
|
||
|
|
)
|
||
|
|
print("✅ 测试样本创建成功")
|
||
|
|
|
||
|
|
# 4. 执行评估
|
||
|
|
print("\n步骤 4: 执行评估...")
|
||
|
|
results = {}
|
||
|
|
|
||
|
|
for metric_name, metric in metrics.items():
|
||
|
|
print(f"\n 评估指标: {metric_name}")
|
||
|
|
try:
|
||
|
|
score = await metric.single_turn_ascore(sample)
|
||
|
|
results[metric_name] = float(score) if score is not None else 0.0
|
||
|
|
print(f" ✅ {metric_name}: {results[metric_name]:.4f}")
|
||
|
|
except Exception as e:
|
||
|
|
print(f" ❌ {metric_name} 失败: {e}")
|
||
|
|
results[metric_name] = None
|
||
|
|
|
||
|
|
# 5. 汇总结果
|
||
|
|
print("\n" + "=" * 80)
|
||
|
|
print("评估结果汇总")
|
||
|
|
print("=" * 80)
|
||
|
|
|
||
|
|
for metric_name, score in results.items():
|
||
|
|
if score is not None:
|
||
|
|
print(f"{metric_name}: {score:.4f}")
|
||
|
|
else:
|
||
|
|
print(f"{metric_name}: 失败")
|
||
|
|
|
||
|
|
# 检查是否所有指标都成功
|
||
|
|
success_count = sum(1 for score in results.values() if score is not None)
|
||
|
|
total_count = len(results)
|
||
|
|
|
||
|
|
print("\n" + "=" * 80)
|
||
|
|
print(f"成功: {success_count}/{total_count} 个指标")
|
||
|
|
print("=" * 80)
|
||
|
|
|
||
|
|
if success_count == total_count:
|
||
|
|
print("\n🎉 所有评估指标测试通过!")
|
||
|
|
return True
|
||
|
|
else:
|
||
|
|
print(f"\n⚠️ 有 {total_count - success_count} 个指标失败")
|
||
|
|
return False
|
||
|
|
|
||
|
|
except Exception as e:
|
||
|
|
print(f"\n❌ 测试失败!")
|
||
|
|
print(f"错误: {e}")
|
||
|
|
import traceback
|
||
|
|
traceback.print_exc()
|
||
|
|
return False
|
||
|
|
|
||
|
|
|
||
|
|
async def main():
|
||
|
|
"""主函数"""
|
||
|
|
print("\n" + "=" * 80)
|
||
|
|
print("RAGAs 评估系统最终验证")
|
||
|
|
print("=" * 80)
|
||
|
|
|
||
|
|
success = await test_ragas_evaluation()
|
||
|
|
|
||
|
|
if success:
|
||
|
|
print("\n✅ 验证通过! RAGAs 评估系统已准备就绪")
|
||
|
|
print("\n下一步:")
|
||
|
|
print(" 1. 运行完整评估: python scripts/evaluate_single_system.py --system coze")
|
||
|
|
print(" 2. 查看评估报告: data/results/")
|
||
|
|
else:
|
||
|
|
print("\n❌ 验证失败,请检查配置")
|
||
|
|
|
||
|
|
|
||
|
|
if __name__ == '__main__':
|
||
|
|
asyncio.run(main())
|