## 主要更新 ### 1. 模型配置修复 - 解决 Embeddings 与阿里云 DashScope API 兼容性问题 - 创建自定义 CustomOpenAIEmbeddings 包装器 - 修复 AnswerCorrectness 指标初始化(添加 SemanticSimilarity) - 所有 5 个 RAGAs 评估指标测试通过 ### 2. 日志记录功能 - 实现 EvaluationLogger 评估日志记录器 - 支持 JSON Lines 格式输出 - 记录评估过程详细信息(问题、指标、耗时、错误) - 集成到评估器和批量评估器 - 添加 --no-logging 参数支持 ### 3. 验证和测试脚本 - verify_model.py: 模型 API 验证脚本 - final_verification.py: RAGAs 评估流程验证 - test_logging.py: 日志功能测试 - test_embedding_fix.py: Embedding 修复测试 ### 4. 文档更新 - WORK_SUMMARY.md: 完整的工作总结文档 - LOGGING_GUIDE.md: 日志功能使用指南 - TODO.md: 更新进度追踪到 v2.0.0 ## 技术亮点 - CustomOpenAIEmbeddings: 直接调用 OpenAI 客户端,绕过 LangChain tokenization - 日志系统: JSON Lines 格式,UTF-8 编码,支持中文 - 错误处理: 不影响评估流程,详细记录错误信息 ## 验证结果 - 模型 API 验证: 4/6 测试通过 - RAGAs 评估验证: 5/5 指标成功 - 日志功能验证: 所有功能正常 ## 系统状态 - 版本: v2.0.0 - 状态: 🟢 可用 - 核心功能: 100% 完成 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
147 lines
4.8 KiB
Python
147 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())
|