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
@@ -7,7 +7,14 @@
|
|||||||
"Bash(python:*)",
|
"Bash(python:*)",
|
||||||
"mcp__plugin_context7_context7__resolve-library-id",
|
"mcp__plugin_context7_context7__resolve-library-id",
|
||||||
"mcp__plugin_context7_context7__query-docs",
|
"mcp__plugin_context7_context7__query-docs",
|
||||||
"Bash(git add:*)"
|
"Bash(git add:*)",
|
||||||
|
"Bash(git commit:*)",
|
||||||
|
"WebSearch",
|
||||||
|
"mcp__bocha-mcp__bocha_web_search",
|
||||||
|
"Bash(pip show:*)",
|
||||||
|
"mcp__bocha-mcp__bocha_ai_search",
|
||||||
|
"Bash(git remote add:*)",
|
||||||
|
"Bash(git push:*)"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,313 @@
|
|||||||
|
# 催收 RAG 评估系统
|
||||||
|
|
||||||
|
> 基于 RAGAs 框架的多 RAG 系统检索质量评估工具
|
||||||
|
|
||||||
|
[](https://www.python.org/downloads/)
|
||||||
|
[](LICENSE)
|
||||||
|
|
||||||
|
## 📋 项目简介
|
||||||
|
|
||||||
|
本项目是一个专门用于评估和对比不同 RAG(Retrieval-Augmented Generation)系统在催收 FAQ 场景下检索质量的工具。通过使用 RAGAs 评估框架,可以自动化地测试和分析多个 RAG 系统的性能表现。
|
||||||
|
|
||||||
|
**核心功能**:
|
||||||
|
- 🎯 使用 RAGAs 框架自动评估 RAG 系统性能
|
||||||
|
- 📊 支持多个 RAG 系统的对比分析(Coze、KBS、ZHT、ZHTv2)
|
||||||
|
- 📈 生成详细的评估报告和可视化结果
|
||||||
|
- 🔧 管理测试集和验证结果
|
||||||
|
- 🤖 使用 LLM 智能精修测试集 ground_truth
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🚀 快速开始
|
||||||
|
|
||||||
|
### 环境要求
|
||||||
|
|
||||||
|
- Python 3.9+
|
||||||
|
- pip 或 poetry
|
||||||
|
|
||||||
|
### 安装依赖
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 克隆仓库
|
||||||
|
git clone http://fn.maiplan.site:8418/hughhuang/cuishou-rag-v2.git
|
||||||
|
cd cuishou-rag-v2
|
||||||
|
|
||||||
|
# 安装依赖
|
||||||
|
pip install -r requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
### 基础使用
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 运行评估(示例)
|
||||||
|
python src/evaluate.py --system coze --test-set data/test_sets/ragas_test_cases_v3.1.json
|
||||||
|
|
||||||
|
# 生成报告
|
||||||
|
python src/generate_report.py --input-dir data/test_sets
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📊 测试集版本
|
||||||
|
|
||||||
|
本项目包含多个版本的测试集,推荐使用最新的 v3.1 版本:
|
||||||
|
|
||||||
|
| 版本 | 生成方式 | Ground Truth 特点 | 推荐度 |
|
||||||
|
|------|---------|-------------------|--------|
|
||||||
|
| **v2.0** | 人工编写 | 简洁摘要,但部分信息不完整 | ⭐⭐⭐ |
|
||||||
|
| **v3.0** | 自动匹配 | FAQ 原文完整,但包含噪音 | ⭐⭐ |
|
||||||
|
| **v3.1** | LLM 精修 | 准确且完整,去除不相关内容 | ⭐⭐⭐⭐⭐ |
|
||||||
|
|
||||||
|
**推荐使用**: `data/test_sets/ragas_test_cases_v3.1.json`
|
||||||
|
|
||||||
|
### 测试集统计
|
||||||
|
|
||||||
|
- **总测试用例**: 15 个
|
||||||
|
- **正向用例**: 10 个(测试正确检索能力)
|
||||||
|
- **负向用例**: 5 个(测试拒答能力)
|
||||||
|
- **问题类型**: 简单检索、复杂检索、多跳检索、模糊查询、流程类、比较类、数值类等
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🛠️ 核心功能
|
||||||
|
|
||||||
|
### 1. 测试集管理
|
||||||
|
|
||||||
|
- **v2.0**: 人工编写的基础测试集
|
||||||
|
- **v3.1**: 使用 LLM(Kimi-K2)精修的高质量测试集
|
||||||
|
- **FAQ 数据**: 280 条催收相关 FAQ
|
||||||
|
|
||||||
|
### 2. RAG 系统评估
|
||||||
|
|
||||||
|
支持评估以下 RAG 系统:
|
||||||
|
- **Coze**: 扣子平台 RAG 系统
|
||||||
|
- **KBS**: 知识库系统
|
||||||
|
- **ZHT**: 智慧通 RAG 系统
|
||||||
|
- **ZHTv2**: 智慧通 v2 版本
|
||||||
|
|
||||||
|
### 3. LLM 精修工具
|
||||||
|
|
||||||
|
使用 LLM 智能选择最相关的 FAQ 作为 ground_truth:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 配置 API
|
||||||
|
cp .env.example .env
|
||||||
|
# 编辑 .env 填入您的 API 配置
|
||||||
|
|
||||||
|
# 运行精修
|
||||||
|
python tmp/refine_with_llm.py
|
||||||
|
```
|
||||||
|
|
||||||
|
详细使用说明请查看:[LLM 精修指南](docs/LLM_REFINE_GUIDE.md)
|
||||||
|
|
||||||
|
### 4. 评估报告生成
|
||||||
|
|
||||||
|
- 生成详细的评估指标
|
||||||
|
- 可视化对比分析
|
||||||
|
- 导出 Excel/PDF 报告
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📁 项目结构
|
||||||
|
|
||||||
|
```
|
||||||
|
cuishou-rag-v2/
|
||||||
|
├── .claude/ # Claude Code 配置
|
||||||
|
├── data/ # 数据目录
|
||||||
|
│ ├── raw/ # 原始文档
|
||||||
|
│ │ ├── faq_data.json # FAQ 原文(280条)
|
||||||
|
│ │ └── 催收Q&A汇总版-20250917更新版.faq.xlsx
|
||||||
|
│ └── test_sets/ # 测试集和验证结果
|
||||||
|
│ ├── ragas_test_cases_v2.json # v2.0 测试集
|
||||||
|
│ ├── ragas_test_cases_v3.1.json # v3.1 测试集(推荐)
|
||||||
|
│ ├── coze-*.json # Coze 系统验证结果
|
||||||
|
│ ├── kbs-*.json # KBS 系统验证结果
|
||||||
|
│ ├── zht-*.json # ZHT 系统验证结果
|
||||||
|
│ └── zhtv2-*.json # ZHTv2 系统验证结果
|
||||||
|
├── docs/ # 项目文档
|
||||||
|
│ ├── LLM_REFINE_GUIDE.md # LLM 精修使用指南
|
||||||
|
│ ├── SESSION_SUMMARY_2025-01-07.md # 工作总结
|
||||||
|
│ └── progress/ # 进度追踪
|
||||||
|
│ └── TODO.md # 待办事项
|
||||||
|
├── src/ # 源代码(待开发)
|
||||||
|
│ ├── evaluators/ # 评估器
|
||||||
|
│ ├── analyzers/ # 分析器
|
||||||
|
│ └── reporters/ # 报告生成器
|
||||||
|
├── tests/ # 测试代码(待开发)
|
||||||
|
├── tmp/ # 临时脚本和工具
|
||||||
|
│ ├── refine_with_llm.py # LLM 精修脚本
|
||||||
|
│ ├── verify_ground_truth.py # ground_truth 验证脚本
|
||||||
|
│ └── generate_v3_ground_truth.py # v3.0 生成脚本
|
||||||
|
├── .env.example # API 配置模板
|
||||||
|
├── .gitignore # Git 忽略规则
|
||||||
|
├── CLAUDE.md # 项目说明(Claude Code)
|
||||||
|
├── README.md # 本文件
|
||||||
|
└── requirements.txt # Python 依赖
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📖 文档
|
||||||
|
|
||||||
|
- **[LLM 精修指南](docs/LLM_REFINE_GUIDE.md)**: 如何使用 LLM 精修测试集
|
||||||
|
- **[工作总结](docs/SESSION_SUMMARY_2025-01-07.md)**: 项目初始化和测试集精修总结
|
||||||
|
- **[版本对比](tmp/v2_vs_v3_comparison.md)**: v2.0 vs v3.0 vs v3.1 详细对比
|
||||||
|
- **[验证报告](tmp/ground_truth_verification_report.md)**: v2.0 ground_truth 验证报告
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🎯 使用场景
|
||||||
|
|
||||||
|
### 1. RAG 系统性能评估
|
||||||
|
|
||||||
|
评估单个 RAG 系统在催收 FAQ 场景下的表现:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python src/evaluate.py --system coze --test-set data/test_sets/ragas_test_cases_v3.1.json
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 多系统对比分析
|
||||||
|
|
||||||
|
对比多个 RAG 系统的性能差异:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python src/compare_systems.py --systems coze,kbs,zht,zhtv2 --test-set data/test_sets/ragas_test_cases_v3.1.json
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 测试集质量验证
|
||||||
|
|
||||||
|
验证 ground_truth 的准确性:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python tmp/verify_ground_truth.py
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. LLM 精修测试集
|
||||||
|
|
||||||
|
使用 LLM 智能优化 ground_truth:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. 配置 API
|
||||||
|
cp .env.example .env
|
||||||
|
# 编辑 .env 填入配置
|
||||||
|
|
||||||
|
# 2. 运行精修
|
||||||
|
python tmp/refine_with_llm.py
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔧 开发指南
|
||||||
|
|
||||||
|
### 代码规范
|
||||||
|
|
||||||
|
- **风格指南**: PEP 8
|
||||||
|
- **代码格式化**: Black (line-length=100)
|
||||||
|
- **代码检查**: Flake8
|
||||||
|
- **类型检查**: mypy(可选)
|
||||||
|
|
||||||
|
### Git 提交规范
|
||||||
|
|
||||||
|
遵循约定式提交(Conventional Commits):
|
||||||
|
|
||||||
|
- `feat`: 新功能
|
||||||
|
- `fix`: 修复 bug
|
||||||
|
- `docs`: 文档变更
|
||||||
|
- `refactor`: 重构
|
||||||
|
- `test`: 测试相关
|
||||||
|
- `chore`: 构建/工具配置
|
||||||
|
|
||||||
|
示例:
|
||||||
|
```bash
|
||||||
|
git commit -m "feat: 添加 RAG 系统评估功能"
|
||||||
|
git commit -m "fix: 修复 ground_truth 验证逻辑"
|
||||||
|
git commit -m "docs: 更新 README 使用说明"
|
||||||
|
```
|
||||||
|
|
||||||
|
### 运行测试
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 运行所有测试
|
||||||
|
pytest tests/
|
||||||
|
|
||||||
|
# 运行特定测试
|
||||||
|
pytest tests/test_evaluators.py
|
||||||
|
|
||||||
|
# 查看覆盖率
|
||||||
|
pytest --cov=src tests/
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📊 评估指标
|
||||||
|
|
||||||
|
本项目使用 RAGAs 框架的以下评估指标:
|
||||||
|
|
||||||
|
- **Faithfulness**: 答案忠实度(是否基于检索内容)
|
||||||
|
- **Answer Relevancy**: 答案相关性
|
||||||
|
- **Context Precision**: 上下文精确度
|
||||||
|
- **Context Recall**: 上下文召回率
|
||||||
|
- **Answer Correctness**: 答案正确性
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🤝 贡献指南
|
||||||
|
|
||||||
|
欢迎贡献!请遵循以下步骤:
|
||||||
|
|
||||||
|
1. Fork 本仓库
|
||||||
|
2. 创建特性分支 (`git checkout -b feature/AmazingFeature`)
|
||||||
|
3. 提交更改 (`git commit -m 'feat: Add some AmazingFeature'`)
|
||||||
|
4. 推送到分支 (`git push origin feature/AmazingFeature`)
|
||||||
|
5. 开启 Pull Request
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📝 更新日志
|
||||||
|
|
||||||
|
### v1.0.0 (2025-01-07)
|
||||||
|
|
||||||
|
**初始版本**
|
||||||
|
- ✅ 完成测试集 v2.0、v3.0、v3.1 版本
|
||||||
|
- ✅ 实现 LLM 精修工具
|
||||||
|
- ✅ 添加 ground_truth 验证脚本
|
||||||
|
- ✅ 生成完整项目文档
|
||||||
|
- ✅ 初始化 Git 仓库
|
||||||
|
|
||||||
|
**测试集改进**
|
||||||
|
- v3.1 相比 v3.0:平均每用例从 5 个 FAQ 降至 1-2 个
|
||||||
|
- 去除不相关内容,保留 FAQ 原文完整性
|
||||||
|
- 使用 Kimi-K2-zhths 模型进行语义理解
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📄 许可证
|
||||||
|
|
||||||
|
本项目采用 MIT 许可证 - 详见 [LICENSE](LICENSE) 文件
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 👥 维护者
|
||||||
|
|
||||||
|
- **Hugh Huang** - *Initial work* - hughhuang@webank.com
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🙏 致谢
|
||||||
|
|
||||||
|
- [RAGAs](https://github.com/explodinggradients/ragas) - RAG 评估框架
|
||||||
|
- [OpenAI](https://openai.com/) - LLM API
|
||||||
|
- [Moonshot AI](https://www.moonshot.cn/) - Kimi-K2 模型
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📞 联系方式
|
||||||
|
|
||||||
|
如有问题或建议,请通过以下方式联系:
|
||||||
|
|
||||||
|
- 📧 Email: hughhuang@webank.com
|
||||||
|
- 🔗 项目地址: http://fn.maiplan.site:8418/hughhuang/cuishou-rag-v2
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**最后更新**: 2025-01-07
|
||||||
@@ -0,0 +1,668 @@
|
|||||||
|
# 架构设计文档
|
||||||
|
|
||||||
|
**项目**: 催收 RAG 评估系统
|
||||||
|
**版本**: v1.0.0
|
||||||
|
**日期**: 2025-01-07
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 目录
|
||||||
|
|
||||||
|
1. [系统概述](#系统概述)
|
||||||
|
2. [架构设计](#架构设计)
|
||||||
|
3. [核心模块](#核心模块)
|
||||||
|
4. [数据流](#数据流)
|
||||||
|
5. [技术选型](#技术选型)
|
||||||
|
6. [扩展性设计](#扩展性设计)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 系统概述
|
||||||
|
|
||||||
|
### 项目目标
|
||||||
|
|
||||||
|
构建一个自动化的 RAG 系统评估平台,用于:
|
||||||
|
- 评估多个 RAG 系统在催收 FAQ 场景下的检索质量
|
||||||
|
- 对比不同系统的性能差异
|
||||||
|
- 生成详细的评估报告和可视化分析
|
||||||
|
- 管理和优化测试集质量
|
||||||
|
|
||||||
|
### 核心价值
|
||||||
|
|
||||||
|
1. **自动化评估**: 使用 RAGAs 框架自动化评估流程
|
||||||
|
2. **多系统对比**: 支持同时评估多个 RAG 系统
|
||||||
|
3. **智能测试集**: 使用 LLM 智能优化 ground_truth
|
||||||
|
4. **可视化分析**: 生成直观的评估报告
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 架构设计
|
||||||
|
|
||||||
|
### 整体架构
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────────────────────────┐
|
||||||
|
│ 用户界面层 │
|
||||||
|
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
|
||||||
|
│ │ CLI 工具 │ │ Web 界面 │ │ API 接口 │ │ 报告生成 │ │
|
||||||
|
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
|
||||||
|
└─────────────────────────────────────────────────────────────┘
|
||||||
|
↓
|
||||||
|
┌─────────────────────────────────────────────────────────────┐
|
||||||
|
│ 业务逻辑层 │
|
||||||
|
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
|
||||||
|
│ │ 评估引擎 │ │ 分析引擎 │ │ 对比引擎 │ │ 精修引擎 │ │
|
||||||
|
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
|
||||||
|
└─────────────────────────────────────────────────────────────┘
|
||||||
|
↓
|
||||||
|
┌─────────────────────────────────────────────────────────────┐
|
||||||
|
│ 数据访问层 │
|
||||||
|
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
|
||||||
|
│ │ 测试集 │ │ FAQ 库 │ │ 验证结果 │ │ 评估报告 │ │
|
||||||
|
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
|
||||||
|
└─────────────────────────────────────────────────────────────┘
|
||||||
|
↓
|
||||||
|
┌─────────────────────────────────────────────────────────────┐
|
||||||
|
│ 外部服务层 │
|
||||||
|
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
|
||||||
|
│ │ RAG 系统 │ │ LLM API │ │ RAGAs │ │ 可视化 │ │
|
||||||
|
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
|
||||||
|
└─────────────────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### 分层说明
|
||||||
|
|
||||||
|
#### 1. 用户界面层
|
||||||
|
- **CLI 工具**: 命令行评估和管理工具
|
||||||
|
- **Web 界面**: 可视化管理和查看(待开发)
|
||||||
|
- **API 接口**: RESTful API(待开发)
|
||||||
|
- **报告生成**: 生成 PDF/Excel 报告
|
||||||
|
|
||||||
|
#### 2. 业务逻辑层
|
||||||
|
- **评估引擎**: 使用 RAGAs 评估 RAG 系统
|
||||||
|
- **分析引擎**: 分析评估结果,生成指标
|
||||||
|
- **对比引擎**: 对比多个系统的性能
|
||||||
|
- **精修引擎**: 使用 LLM 优化测试集
|
||||||
|
|
||||||
|
#### 3. 数据访问层
|
||||||
|
- **测试集管理**: 管理多版本测试集
|
||||||
|
- **FAQ 库**: 存储和查询 FAQ 数据
|
||||||
|
- **验证结果**: 存储各系统的验证结果
|
||||||
|
- **评估报告**: 存储历史评估报告
|
||||||
|
|
||||||
|
#### 4. 外部服务层
|
||||||
|
- **RAG 系统**: 被评估的 RAG 系统(Coze、KBS、ZHT、ZHTv2)
|
||||||
|
- **LLM API**: OpenAI 兼容的 LLM 服务
|
||||||
|
- **RAGAs**: RAG 评估框架
|
||||||
|
- **可视化**: Matplotlib、Plotly 等
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 核心模块
|
||||||
|
|
||||||
|
### 1. 评估模块 (Evaluators)
|
||||||
|
|
||||||
|
#### 职责
|
||||||
|
- 调用 RAGAs 框架进行评估
|
||||||
|
- 计算各项评估指标
|
||||||
|
- 生成评估结果
|
||||||
|
|
||||||
|
#### 核心类
|
||||||
|
|
||||||
|
```python
|
||||||
|
class RAGEvaluator:
|
||||||
|
"""RAG 系统评估器"""
|
||||||
|
|
||||||
|
def __init__(self, system_name: str, test_set: TestSet):
|
||||||
|
self.system_name = system_name
|
||||||
|
self.test_set = test_set
|
||||||
|
|
||||||
|
def evaluate(self) -> EvaluationResult:
|
||||||
|
"""执行评估"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def calculate_metrics(self) -> Dict[str, float]:
|
||||||
|
"""计算评估指标"""
|
||||||
|
pass
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 评估指标
|
||||||
|
|
||||||
|
- **Faithfulness**: 答案忠实度
|
||||||
|
- **Answer Relevancy**: 答案相关性
|
||||||
|
- **Context Precision**: 上下文精确度
|
||||||
|
- **Context Recall**: 上下文召回率
|
||||||
|
- **Answer Correctness**: 答案正确性
|
||||||
|
|
||||||
|
### 2. 分析模块 (Analyzers)
|
||||||
|
|
||||||
|
#### 职责
|
||||||
|
- 分析评估结果
|
||||||
|
- 生成统计数据
|
||||||
|
- 识别问题和改进点
|
||||||
|
|
||||||
|
#### 核心类
|
||||||
|
|
||||||
|
```python
|
||||||
|
class ResultAnalyzer:
|
||||||
|
"""评估结果分析器"""
|
||||||
|
|
||||||
|
def analyze(self, results: List[EvaluationResult]) -> AnalysisReport:
|
||||||
|
"""分析评估结果"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def identify_issues(self) -> List[Issue]:
|
||||||
|
"""识别问题"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def generate_insights(self) -> List[Insight]:
|
||||||
|
"""生成洞察"""
|
||||||
|
pass
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 对比模块 (Comparators)
|
||||||
|
|
||||||
|
#### 职责
|
||||||
|
- 对比多个系统的评估结果
|
||||||
|
- 生成对比报告
|
||||||
|
- 可视化对比数据
|
||||||
|
|
||||||
|
#### 核心类
|
||||||
|
|
||||||
|
```python
|
||||||
|
class SystemComparator:
|
||||||
|
"""系统对比器"""
|
||||||
|
|
||||||
|
def compare(self, results: Dict[str, EvaluationResult]) -> ComparisonReport:
|
||||||
|
"""对比多个系统"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def rank_systems(self) -> List[Tuple[str, float]]:
|
||||||
|
"""系统排名"""
|
||||||
|
pass
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 精修模块 (Refiners)
|
||||||
|
|
||||||
|
#### 职责
|
||||||
|
- 使用 LLM 精修 ground_truth
|
||||||
|
- 验证测试集质量
|
||||||
|
- 生成新版本测试集
|
||||||
|
|
||||||
|
#### 核心类
|
||||||
|
|
||||||
|
```python
|
||||||
|
class LLMRefiner:
|
||||||
|
"""LLM 精修器"""
|
||||||
|
|
||||||
|
def __init__(self, llm_client: OpenAI):
|
||||||
|
self.llm_client = llm_client
|
||||||
|
|
||||||
|
def refine_ground_truth(self, question: str, faqs: List[FAQ]) -> str:
|
||||||
|
"""精修 ground_truth"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def validate_quality(self, test_case: TestCase) -> bool:
|
||||||
|
"""验证质量"""
|
||||||
|
pass
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. 报告模块 (Reporters)
|
||||||
|
|
||||||
|
#### 职责
|
||||||
|
- 生成评估报告
|
||||||
|
- 可视化数据
|
||||||
|
- 导出多种格式
|
||||||
|
|
||||||
|
#### 核心类
|
||||||
|
|
||||||
|
```python
|
||||||
|
class ReportGenerator:
|
||||||
|
"""报告生成器"""
|
||||||
|
|
||||||
|
def generate_html_report(self, results: EvaluationResult) -> str:
|
||||||
|
"""生成 HTML 报告"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def generate_pdf_report(self, results: EvaluationResult) -> bytes:
|
||||||
|
"""生成 PDF 报告"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def generate_excel_report(self, results: EvaluationResult) -> bytes:
|
||||||
|
"""生成 Excel 报告"""
|
||||||
|
pass
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 数据流
|
||||||
|
|
||||||
|
### 评估流程
|
||||||
|
|
||||||
|
```
|
||||||
|
┌──────────┐
|
||||||
|
│ 测试集 │
|
||||||
|
└────┬─────┘
|
||||||
|
│
|
||||||
|
↓
|
||||||
|
┌──────────┐ ┌──────────┐
|
||||||
|
│ RAG 系统 │────→│ 获取答案 │
|
||||||
|
└──────────┘ └────┬─────┘
|
||||||
|
│
|
||||||
|
↓
|
||||||
|
┌──────────┐
|
||||||
|
│ RAGAs │
|
||||||
|
│ 评估引擎 │
|
||||||
|
└────┬─────┘
|
||||||
|
│
|
||||||
|
↓
|
||||||
|
┌──────────┐
|
||||||
|
│ 评估结果 │
|
||||||
|
└────┬─────┘
|
||||||
|
│
|
||||||
|
↓
|
||||||
|
┌──────────┐
|
||||||
|
│ 分析报告 │
|
||||||
|
└──────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### 精修流程
|
||||||
|
|
||||||
|
```
|
||||||
|
┌──────────┐
|
||||||
|
│ 测试问题 │
|
||||||
|
└────┬─────┘
|
||||||
|
│
|
||||||
|
↓
|
||||||
|
┌──────────┐ ┌──────────┐
|
||||||
|
│ FAQ 库 │────→│ 候选 FAQ │
|
||||||
|
└──────────┘ └────┬─────┘
|
||||||
|
│
|
||||||
|
↓
|
||||||
|
┌──────────┐
|
||||||
|
│ LLM API │
|
||||||
|
│ 语义分析 │
|
||||||
|
└────┬─────┘
|
||||||
|
│
|
||||||
|
↓
|
||||||
|
┌──────────┐
|
||||||
|
│ 选择最相 │
|
||||||
|
│ 关的 FAQ │
|
||||||
|
└────┬─────┘
|
||||||
|
│
|
||||||
|
↓
|
||||||
|
┌──────────┐
|
||||||
|
│ 精修后的 │
|
||||||
|
│ 测试集 │
|
||||||
|
└──────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 技术选型
|
||||||
|
|
||||||
|
### 编程语言
|
||||||
|
- **Python 3.9+**: 主要开发语言
|
||||||
|
- 理由: 丰富的数据处理和 AI 库生态
|
||||||
|
|
||||||
|
### 核心框架
|
||||||
|
|
||||||
|
#### RAGAs
|
||||||
|
- **用途**: RAG 系统评估
|
||||||
|
- **版本**: 0.1.0+
|
||||||
|
- **理由**: 专门为 RAG 评估设计,指标全面
|
||||||
|
|
||||||
|
#### Pandas
|
||||||
|
- **用途**: 数据处理和分析
|
||||||
|
- **版本**: 2.0.0+
|
||||||
|
- **理由**: 强大的数据处理能力
|
||||||
|
|
||||||
|
#### OpenAI SDK
|
||||||
|
- **用途**: LLM API 调用
|
||||||
|
- **版本**: 1.0.0+
|
||||||
|
- **理由**: 兼容多种 LLM 服务
|
||||||
|
|
||||||
|
### 数据存储
|
||||||
|
|
||||||
|
#### JSON
|
||||||
|
- **用途**: 测试集和验证结果
|
||||||
|
- **理由**:
|
||||||
|
- 人类可读
|
||||||
|
- 易于版本控制
|
||||||
|
- 灵活的数据结构
|
||||||
|
|
||||||
|
#### Excel
|
||||||
|
- **用途**: 原始 FAQ 文档
|
||||||
|
- **理由**:
|
||||||
|
- 业务人员熟悉
|
||||||
|
- 易于编辑和维护
|
||||||
|
|
||||||
|
### 可视化
|
||||||
|
|
||||||
|
#### Matplotlib
|
||||||
|
- **用途**: 基础图表
|
||||||
|
- **理由**: 成熟稳定,文档丰富
|
||||||
|
|
||||||
|
#### Plotly
|
||||||
|
- **用途**: 交互式可视化
|
||||||
|
- **理由**: 交互性强,适合 Web 展示
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 扩展性设计
|
||||||
|
|
||||||
|
### 1. 插件化架构
|
||||||
|
|
||||||
|
#### RAG 系统适配器
|
||||||
|
|
||||||
|
```python
|
||||||
|
class RAGSystemAdapter(ABC):
|
||||||
|
"""RAG 系统适配器基类"""
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def query(self, question: str) -> RAGResponse:
|
||||||
|
"""查询 RAG 系统"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def get_context(self, question: str) -> List[str]:
|
||||||
|
"""获取检索上下文"""
|
||||||
|
pass
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 实现示例
|
||||||
|
|
||||||
|
```python
|
||||||
|
class CozeAdapter(RAGSystemAdapter):
|
||||||
|
"""Coze 系统适配器"""
|
||||||
|
|
||||||
|
def query(self, question: str) -> RAGResponse:
|
||||||
|
# 调用 Coze API
|
||||||
|
pass
|
||||||
|
|
||||||
|
def get_context(self, question: str) -> List[str]:
|
||||||
|
# 获取 Coze 检索结果
|
||||||
|
pass
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 配置化设计
|
||||||
|
|
||||||
|
#### 评估配置
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# config/evaluation.yaml
|
||||||
|
evaluation:
|
||||||
|
metrics:
|
||||||
|
- faithfulness
|
||||||
|
- answer_relevancy
|
||||||
|
- context_precision
|
||||||
|
- context_recall
|
||||||
|
|
||||||
|
thresholds:
|
||||||
|
faithfulness: 0.8
|
||||||
|
answer_relevancy: 0.7
|
||||||
|
|
||||||
|
batch_size: 10
|
||||||
|
timeout: 30
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 系统配置
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# config/systems.yaml
|
||||||
|
systems:
|
||||||
|
coze:
|
||||||
|
api_url: "https://api.coze.com"
|
||||||
|
api_key: "${COZE_API_KEY}"
|
||||||
|
timeout: 10
|
||||||
|
|
||||||
|
kbs:
|
||||||
|
api_url: "https://api.kbs.com"
|
||||||
|
api_key: "${KBS_API_KEY}"
|
||||||
|
timeout: 10
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 模块化设计
|
||||||
|
|
||||||
|
#### 目录结构
|
||||||
|
|
||||||
|
```
|
||||||
|
src/
|
||||||
|
├── evaluators/ # 评估器
|
||||||
|
│ ├── base.py # 基类
|
||||||
|
│ ├── ragas.py # RAGAs 评估器
|
||||||
|
│ └── custom.py # 自定义评估器
|
||||||
|
├── analyzers/ # 分析器
|
||||||
|
│ ├── base.py
|
||||||
|
│ ├── statistical.py # 统计分析
|
||||||
|
│ └── semantic.py # 语义分析
|
||||||
|
├── reporters/ # 报告生成器
|
||||||
|
│ ├── base.py
|
||||||
|
│ ├── html.py
|
||||||
|
│ ├── pdf.py
|
||||||
|
│ └── excel.py
|
||||||
|
├── adapters/ # RAG 系统适配器
|
||||||
|
│ ├── base.py
|
||||||
|
│ ├── coze.py
|
||||||
|
│ ├── kbs.py
|
||||||
|
│ └── zht.py
|
||||||
|
└── utils/ # 工具函数
|
||||||
|
├── config.py # 配置管理
|
||||||
|
├── logger.py # 日志
|
||||||
|
└── metrics.py # 指标计算
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 可扩展的评估指标
|
||||||
|
|
||||||
|
#### 自定义指标
|
||||||
|
|
||||||
|
```python
|
||||||
|
class CustomMetric(Metric):
|
||||||
|
"""自定义评估指标"""
|
||||||
|
|
||||||
|
def __init__(self, name: str, weight: float = 1.0):
|
||||||
|
self.name = name
|
||||||
|
self.weight = weight
|
||||||
|
|
||||||
|
def calculate(self, question: str, answer: str,
|
||||||
|
ground_truth: str, context: List[str]) -> float:
|
||||||
|
"""计算指标值"""
|
||||||
|
pass
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. 多版本测试集管理
|
||||||
|
|
||||||
|
#### 版本管理
|
||||||
|
|
||||||
|
```python
|
||||||
|
class TestSetManager:
|
||||||
|
"""测试集管理器"""
|
||||||
|
|
||||||
|
def load_version(self, version: str) -> TestSet:
|
||||||
|
"""加载指定版本"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def create_version(self, base_version: str,
|
||||||
|
modifications: List[Modification]) -> TestSet:
|
||||||
|
"""创建新版本"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def compare_versions(self, v1: str, v2: str) -> VersionDiff:
|
||||||
|
"""对比版本差异"""
|
||||||
|
pass
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 性能优化
|
||||||
|
|
||||||
|
### 1. 批量评估
|
||||||
|
|
||||||
|
```python
|
||||||
|
class BatchEvaluator:
|
||||||
|
"""批量评估器"""
|
||||||
|
|
||||||
|
def evaluate_batch(self, test_cases: List[TestCase],
|
||||||
|
batch_size: int = 10) -> List[EvaluationResult]:
|
||||||
|
"""批量评估"""
|
||||||
|
pass
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 缓存机制
|
||||||
|
|
||||||
|
```python
|
||||||
|
class CachedRAGAdapter:
|
||||||
|
"""带缓存的 RAG 适配器"""
|
||||||
|
|
||||||
|
def __init__(self, adapter: RAGSystemAdapter, cache_ttl: int = 3600):
|
||||||
|
self.adapter = adapter
|
||||||
|
self.cache = {}
|
||||||
|
self.cache_ttl = cache_ttl
|
||||||
|
|
||||||
|
def query(self, question: str) -> RAGResponse:
|
||||||
|
"""查询(带缓存)"""
|
||||||
|
if question in self.cache:
|
||||||
|
return self.cache[question]
|
||||||
|
|
||||||
|
result = self.adapter.query(question)
|
||||||
|
self.cache[question] = result
|
||||||
|
return result
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 并发处理
|
||||||
|
|
||||||
|
```python
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
|
||||||
|
class ParallelEvaluator:
|
||||||
|
"""并行评估器"""
|
||||||
|
|
||||||
|
def evaluate_parallel(self, test_cases: List[TestCase],
|
||||||
|
max_workers: int = 4) -> List[EvaluationResult]:
|
||||||
|
"""并行评估"""
|
||||||
|
with ThreadPoolExecutor(max_workers=max_workers) as executor:
|
||||||
|
futures = [executor.submit(self.evaluate_single, tc)
|
||||||
|
for tc in test_cases]
|
||||||
|
return [f.result() for f in futures]
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 安全性设计
|
||||||
|
|
||||||
|
### 1. API 密钥管理
|
||||||
|
|
||||||
|
- 使用环境变量存储敏感信息
|
||||||
|
- 支持 `.env` 文件配置
|
||||||
|
- 不在代码中硬编码密钥
|
||||||
|
|
||||||
|
### 2. 数据隐私
|
||||||
|
|
||||||
|
- 测试集不包含真实用户数据
|
||||||
|
- 评估结果脱敏处理
|
||||||
|
- 支持本地部署
|
||||||
|
|
||||||
|
### 3. 访问控制
|
||||||
|
|
||||||
|
- API 接口需要认证
|
||||||
|
- 支持角色权限管理
|
||||||
|
- 审计日志记录
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 监控和日志
|
||||||
|
|
||||||
|
### 1. 日志系统
|
||||||
|
|
||||||
|
```python
|
||||||
|
import logging
|
||||||
|
|
||||||
|
logger = logging.getLogger('rag_evaluation')
|
||||||
|
logger.setLevel(logging.INFO)
|
||||||
|
|
||||||
|
# 文件日志
|
||||||
|
file_handler = logging.FileHandler('logs/evaluation.log')
|
||||||
|
file_handler.setFormatter(
|
||||||
|
logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
||||||
|
)
|
||||||
|
logger.addHandler(file_handler)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 性能监控
|
||||||
|
|
||||||
|
```python
|
||||||
|
import time
|
||||||
|
from functools import wraps
|
||||||
|
|
||||||
|
def monitor_performance(func):
|
||||||
|
"""性能监控装饰器"""
|
||||||
|
@wraps(func)
|
||||||
|
def wrapper(*args, **kwargs):
|
||||||
|
start_time = time.time()
|
||||||
|
result = func(*args, **kwargs)
|
||||||
|
end_time = time.time()
|
||||||
|
|
||||||
|
logger.info(f"{func.__name__} took {end_time - start_time:.2f}s")
|
||||||
|
return result
|
||||||
|
|
||||||
|
return wrapper
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 未来规划
|
||||||
|
|
||||||
|
### 短期(1-3 个月)
|
||||||
|
|
||||||
|
1. **完善核心功能**
|
||||||
|
- 实现评估引擎
|
||||||
|
- 实现分析引擎
|
||||||
|
- 实现报告生成
|
||||||
|
|
||||||
|
2. **扩展测试集**
|
||||||
|
- 从 15 个用例扩展到 50+
|
||||||
|
- 覆盖更多问题类型
|
||||||
|
|
||||||
|
3. **优化性能**
|
||||||
|
- 实现批量评估
|
||||||
|
- 添加缓存机制
|
||||||
|
|
||||||
|
### 中期(3-6 个月)
|
||||||
|
|
||||||
|
1. **Web 界面**
|
||||||
|
- 可视化管理界面
|
||||||
|
- 实时评估监控
|
||||||
|
- 交互式报告
|
||||||
|
|
||||||
|
2. **API 服务**
|
||||||
|
- RESTful API
|
||||||
|
- WebSocket 实时推送
|
||||||
|
- API 文档
|
||||||
|
|
||||||
|
3. **自动化流程**
|
||||||
|
- CI/CD 集成
|
||||||
|
- 定时评估任务
|
||||||
|
- 自动报告生成
|
||||||
|
|
||||||
|
### 长期(6-12 个月)
|
||||||
|
|
||||||
|
1. **智能化**
|
||||||
|
- 自动发现问题
|
||||||
|
- 智能推荐改进
|
||||||
|
- 自适应测试集
|
||||||
|
|
||||||
|
2. **平台化**
|
||||||
|
- 多租户支持
|
||||||
|
- 权限管理
|
||||||
|
- 数据分析平台
|
||||||
|
|
||||||
|
3. **生态建设**
|
||||||
|
- 插件市场
|
||||||
|
- 社区贡献
|
||||||
|
- 最佳实践分享
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**文档版本**: v1.0.0
|
||||||
|
**最后更新**: 2025-01-07
|
||||||
|
**维护者**: Hugh Huang
|
||||||
@@ -0,0 +1,634 @@
|
|||||||
|
# 开发指南
|
||||||
|
|
||||||
|
**项目**: 催收 RAG 评估系统
|
||||||
|
**版本**: v1.0.0
|
||||||
|
**日期**: 2025-01-07
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 目录
|
||||||
|
|
||||||
|
1. [开发环境搭建](#开发环境搭建)
|
||||||
|
2. [代码规范](#代码规范)
|
||||||
|
3. [开发流程](#开发流程)
|
||||||
|
4. [测试指南](#测试指南)
|
||||||
|
5. [常见问题](#常见问题)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 开发环境搭建
|
||||||
|
|
||||||
|
### 1. 系统要求
|
||||||
|
|
||||||
|
- **操作系统**: Windows 10+, macOS 10.15+, Linux
|
||||||
|
- **Python**: 3.9+
|
||||||
|
- **Git**: 2.0+
|
||||||
|
- **编辑器**: VS Code / PyCharm(推荐)
|
||||||
|
|
||||||
|
### 2. 克隆项目
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone http://fn.maiplan.site:8418/hughhuang/cuishou-rag-v2.git
|
||||||
|
cd cuishou-rag-v2
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 创建虚拟环境
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 使用 venv
|
||||||
|
python -m venv venv
|
||||||
|
|
||||||
|
# 激活虚拟环境
|
||||||
|
# Windows
|
||||||
|
venv\Scripts\activate
|
||||||
|
# macOS/Linux
|
||||||
|
source venv/bin/activate
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 安装依赖
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 安装项目依赖
|
||||||
|
pip install -r requirements.txt
|
||||||
|
|
||||||
|
# 安装开发依赖
|
||||||
|
pip install black flake8 pytest pytest-cov mypy
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. 配置环境变量
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 复制配置模板
|
||||||
|
cp .env.example .env
|
||||||
|
|
||||||
|
# 编辑 .env 文件,填入您的配置
|
||||||
|
# OPENAI_API_BASE=https://api.openai.com/v1
|
||||||
|
# OPENAI_API_KEY=your-api-key
|
||||||
|
# OPENAI_MODEL=gpt-4o-mini
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6. 验证安装
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 运行测试(待开发)
|
||||||
|
pytest tests/
|
||||||
|
|
||||||
|
# 检查代码格式
|
||||||
|
black --check src/ tests/
|
||||||
|
flake8 src/ tests/
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 代码规范
|
||||||
|
|
||||||
|
### 1. Python 风格指南
|
||||||
|
|
||||||
|
遵循 **PEP 8** 规范:
|
||||||
|
|
||||||
|
#### 命名规范
|
||||||
|
|
||||||
|
```python
|
||||||
|
# 类名:大驼峰
|
||||||
|
class RAGEvaluator:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# 函数名:小写+下划线
|
||||||
|
def evaluate_system():
|
||||||
|
pass
|
||||||
|
|
||||||
|
# 常量:大写+下划线
|
||||||
|
MAX_RETRY_COUNT = 3
|
||||||
|
|
||||||
|
# 私有变量:前缀下划线
|
||||||
|
_internal_cache = {}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 代码格式
|
||||||
|
|
||||||
|
```python
|
||||||
|
# 使用 Black 格式化(line-length=100)
|
||||||
|
# 安装:pip install black
|
||||||
|
# 运行:black src/ tests/
|
||||||
|
|
||||||
|
# 示例
|
||||||
|
def long_function_name(
|
||||||
|
parameter_one: str,
|
||||||
|
parameter_two: int,
|
||||||
|
parameter_three: Optional[Dict[str, Any]] = None,
|
||||||
|
) -> Tuple[str, int]:
|
||||||
|
"""函数文档字符串
|
||||||
|
|
||||||
|
Args:
|
||||||
|
parameter_one: 参数说明
|
||||||
|
parameter_two: 参数说明
|
||||||
|
parameter_three: 可选参数说明
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
返回值说明
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 文档字符串
|
||||||
|
|
||||||
|
使用 **Google 风格** 文档字符串:
|
||||||
|
|
||||||
|
```python
|
||||||
|
def evaluate_rag_system(
|
||||||
|
system_name: str,
|
||||||
|
test_set: TestSet,
|
||||||
|
metrics: List[str]
|
||||||
|
) -> EvaluationResult:
|
||||||
|
"""评估 RAG 系统性能
|
||||||
|
|
||||||
|
对指定的 RAG 系统使用给定的测试集进行评估,计算指定的评估指标。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
system_name: RAG 系统名称(如 'coze', 'kbs')
|
||||||
|
test_set: 测试集对象
|
||||||
|
metrics: 要计算的评估指标列表
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
EvaluationResult: 包含所有评估指标的结果对象
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValueError: 如果 system_name 不支持
|
||||||
|
ConnectionError: 如果无法连接到 RAG 系统
|
||||||
|
|
||||||
|
Example:
|
||||||
|
>>> test_set = load_test_set('v3.1')
|
||||||
|
>>> result = evaluate_rag_system('coze', test_set, ['faithfulness'])
|
||||||
|
>>> print(result.metrics['faithfulness'])
|
||||||
|
0.85
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 类型注解
|
||||||
|
|
||||||
|
使用 **类型注解** 提高代码可读性:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from typing import List, Dict, Optional, Tuple, Union
|
||||||
|
|
||||||
|
def process_results(
|
||||||
|
results: List[EvaluationResult],
|
||||||
|
threshold: float = 0.8
|
||||||
|
) -> Dict[str, Union[float, int]]:
|
||||||
|
"""处理评估结果"""
|
||||||
|
pass
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 错误处理
|
||||||
|
|
||||||
|
```python
|
||||||
|
# 使用具体的异常类型
|
||||||
|
try:
|
||||||
|
result = evaluate_system(system_name)
|
||||||
|
except ConnectionError as e:
|
||||||
|
logger.error(f"Failed to connect to {system_name}: {e}")
|
||||||
|
raise
|
||||||
|
except ValueError as e:
|
||||||
|
logger.warning(f"Invalid parameter: {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
# 自定义异常
|
||||||
|
class EvaluationError(Exception):
|
||||||
|
"""评估过程中的错误"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
class InvalidTestSetError(EvaluationError):
|
||||||
|
"""无效的测试集"""
|
||||||
|
pass
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. 日志记录
|
||||||
|
|
||||||
|
```python
|
||||||
|
import logging
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
def evaluate_system(system_name: str) -> EvaluationResult:
|
||||||
|
"""评估系统"""
|
||||||
|
logger.info(f"Starting evaluation for {system_name}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
result = _do_evaluation(system_name)
|
||||||
|
logger.info(f"Evaluation completed: {result.summary()}")
|
||||||
|
return result
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Evaluation failed: {e}", exc_info=True)
|
||||||
|
raise
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 开发流程
|
||||||
|
|
||||||
|
### 1. Git 工作流
|
||||||
|
|
||||||
|
#### 分支策略
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 主分支
|
||||||
|
master # 生产环境代码
|
||||||
|
|
||||||
|
# 功能分支
|
||||||
|
feature/xxx # 新功能开发
|
||||||
|
fix/xxx # Bug 修复
|
||||||
|
hotfix/xxx # 紧急修复
|
||||||
|
docs/xxx # 文档更新
|
||||||
|
refactor/xxx # 代码重构
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 开发流程
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. 创建功能分支
|
||||||
|
git checkout -b feature/add-evaluation-engine
|
||||||
|
|
||||||
|
# 2. 开发并提交
|
||||||
|
git add .
|
||||||
|
git commit -m "feat: 添加评估引擎核心功能"
|
||||||
|
|
||||||
|
# 3. 推送到远程
|
||||||
|
git push origin feature/add-evaluation-engine
|
||||||
|
|
||||||
|
# 4. 创建 Pull Request
|
||||||
|
# 在 GitLab/GitHub 上创建 PR
|
||||||
|
|
||||||
|
# 5. 代码审查通过后合并
|
||||||
|
git checkout master
|
||||||
|
git merge feature/add-evaluation-engine
|
||||||
|
git push origin master
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 提交规范
|
||||||
|
|
||||||
|
遵循 **约定式提交(Conventional Commits)**:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 格式
|
||||||
|
<type>(<scope>): <subject>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<footer>
|
||||||
|
|
||||||
|
# 类型(type)
|
||||||
|
feat: 新功能
|
||||||
|
fix: Bug 修复
|
||||||
|
docs: 文档更新
|
||||||
|
style: 代码格式(不影响功能)
|
||||||
|
refactor: 重构
|
||||||
|
test: 测试相关
|
||||||
|
chore: 构建/工具配置
|
||||||
|
|
||||||
|
# 示例
|
||||||
|
feat(evaluator): 添加 RAGAs 评估器
|
||||||
|
|
||||||
|
实现基于 RAGAs 框架的评估器,支持以下指标:
|
||||||
|
- Faithfulness
|
||||||
|
- Answer Relevancy
|
||||||
|
- Context Precision
|
||||||
|
|
||||||
|
Closes #123
|
||||||
|
|
||||||
|
# 简短提交
|
||||||
|
fix: 修复测试集加载错误
|
||||||
|
docs: 更新 README 安装说明
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 代码审查清单
|
||||||
|
|
||||||
|
提交 PR 前检查:
|
||||||
|
|
||||||
|
- [ ] 代码符合 PEP 8 规范
|
||||||
|
- [ ] 添加了必要的文档字符串
|
||||||
|
- [ ] 添加了类型注解
|
||||||
|
- [ ] 编写了单元测试
|
||||||
|
- [ ] 所有测试通过
|
||||||
|
- [ ] 更新了相关文档
|
||||||
|
- [ ] 提交信息符合规范
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 测试指南
|
||||||
|
|
||||||
|
### 1. 测试结构
|
||||||
|
|
||||||
|
```
|
||||||
|
tests/
|
||||||
|
├── __init__.py
|
||||||
|
├── conftest.py # pytest 配置和 fixtures
|
||||||
|
├── test_evaluators/ # 评估器测试
|
||||||
|
│ ├── test_ragas.py
|
||||||
|
│ └── test_custom.py
|
||||||
|
├── test_analyzers/ # 分析器测试
|
||||||
|
│ └── test_statistical.py
|
||||||
|
├── test_reporters/ # 报告生成器测试
|
||||||
|
│ └── test_html.py
|
||||||
|
└── test_utils/ # 工具函数测试
|
||||||
|
└── test_metrics.py
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 编写测试
|
||||||
|
|
||||||
|
#### 单元测试示例
|
||||||
|
|
||||||
|
```python
|
||||||
|
# tests/test_evaluators/test_ragas.py
|
||||||
|
import pytest
|
||||||
|
from src.evaluators.ragas import RAGEvaluator
|
||||||
|
from src.models import TestSet, TestCase
|
||||||
|
|
||||||
|
class TestRAGEvaluator:
|
||||||
|
"""RAG 评估器测试"""
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def test_set(self):
|
||||||
|
"""测试集 fixture"""
|
||||||
|
return TestSet(
|
||||||
|
version="3.1",
|
||||||
|
cases=[
|
||||||
|
TestCase(
|
||||||
|
question_id="q001",
|
||||||
|
question="签约流程是什么?",
|
||||||
|
ground_truth="...",
|
||||||
|
category="positive"
|
||||||
|
)
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def evaluator(self, test_set):
|
||||||
|
"""评估器 fixture"""
|
||||||
|
return RAGEvaluator(system_name="coze", test_set=test_set)
|
||||||
|
|
||||||
|
def test_evaluate_returns_result(self, evaluator):
|
||||||
|
"""测试评估返回结果"""
|
||||||
|
result = evaluator.evaluate()
|
||||||
|
assert result is not None
|
||||||
|
assert hasattr(result, 'metrics')
|
||||||
|
|
||||||
|
def test_calculate_metrics(self, evaluator):
|
||||||
|
"""测试指标计算"""
|
||||||
|
metrics = evaluator.calculate_metrics()
|
||||||
|
assert 'faithfulness' in metrics
|
||||||
|
assert 0 <= metrics['faithfulness'] <= 1
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("metric_name,expected_range", [
|
||||||
|
("faithfulness", (0, 1)),
|
||||||
|
("answer_relevancy", (0, 1)),
|
||||||
|
])
|
||||||
|
def test_metric_ranges(self, evaluator, metric_name, expected_range):
|
||||||
|
"""测试指标范围"""
|
||||||
|
metrics = evaluator.calculate_metrics()
|
||||||
|
value = metrics[metric_name]
|
||||||
|
assert expected_range[0] <= value <= expected_range[1]
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Mock 外部依赖
|
||||||
|
|
||||||
|
```python
|
||||||
|
from unittest.mock import Mock, patch
|
||||||
|
|
||||||
|
def test_llm_refiner_with_mock():
|
||||||
|
"""测试 LLM 精修器(使用 mock)"""
|
||||||
|
# Mock LLM 客户端
|
||||||
|
mock_client = Mock()
|
||||||
|
mock_client.chat.completions.create.return_value = Mock(
|
||||||
|
choices=[Mock(message=Mock(content='{"selected_faqs": [...]}'))]
|
||||||
|
)
|
||||||
|
|
||||||
|
refiner = LLMRefiner(llm_client=mock_client)
|
||||||
|
result = refiner.refine_ground_truth("问题", [])
|
||||||
|
|
||||||
|
assert result is not None
|
||||||
|
mock_client.chat.completions.create.assert_called_once()
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 运行测试
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 运行所有测试
|
||||||
|
pytest
|
||||||
|
|
||||||
|
# 运行特定文件
|
||||||
|
pytest tests/test_evaluators/test_ragas.py
|
||||||
|
|
||||||
|
# 运行特定测试
|
||||||
|
pytest tests/test_evaluators/test_ragas.py::TestRAGEvaluator::test_evaluate_returns_result
|
||||||
|
|
||||||
|
# 查看覆盖率
|
||||||
|
pytest --cov=src --cov-report=html
|
||||||
|
|
||||||
|
# 详细输出
|
||||||
|
pytest -v
|
||||||
|
|
||||||
|
# 显示 print 输出
|
||||||
|
pytest -s
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 测试覆盖率要求
|
||||||
|
|
||||||
|
- **核心逻辑**: 80%+
|
||||||
|
- **工具函数**: 70%+
|
||||||
|
- **整体覆盖率**: 75%+
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 常见问题
|
||||||
|
|
||||||
|
### 1. 环境问题
|
||||||
|
|
||||||
|
#### Q: pip install 失败
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 升级 pip
|
||||||
|
python -m pip install --upgrade pip
|
||||||
|
|
||||||
|
# 使用国内镜像
|
||||||
|
pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Q: 虚拟环境激活失败(Windows)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 如果提示权限错误,以管理员身份运行 PowerShell
|
||||||
|
Set-ExecutionPolicy RemoteSigned
|
||||||
|
|
||||||
|
# 然后激活
|
||||||
|
venv\Scripts\activate
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 代码格式问题
|
||||||
|
|
||||||
|
#### Q: Black 和 Flake8 冲突
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 在 .flake8 配置文件中忽略 Black 格式化的规则
|
||||||
|
[flake8]
|
||||||
|
max-line-length = 100
|
||||||
|
extend-ignore = E203, W503
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Q: 如何自动格式化
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# VS Code 配置(.vscode/settings.json)
|
||||||
|
{
|
||||||
|
"python.formatting.provider": "black",
|
||||||
|
"python.formatting.blackArgs": ["--line-length", "100"],
|
||||||
|
"editor.formatOnSave": true
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 测试问题
|
||||||
|
|
||||||
|
#### Q: 测试运行很慢
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 并行运行测试
|
||||||
|
pip install pytest-xdist
|
||||||
|
pytest -n auto
|
||||||
|
|
||||||
|
# 只运行失败的测试
|
||||||
|
pytest --lf
|
||||||
|
|
||||||
|
# 跳过慢速测试
|
||||||
|
pytest -m "not slow"
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Q: Mock 不生效
|
||||||
|
|
||||||
|
```python
|
||||||
|
# 确保 patch 路径正确
|
||||||
|
# 错误:patch('openai.OpenAI')
|
||||||
|
# 正确:patch('src.refiners.llm.OpenAI')
|
||||||
|
|
||||||
|
# 使用 where 参数
|
||||||
|
from src.refiners import llm
|
||||||
|
with patch.object(llm, 'OpenAI') as mock:
|
||||||
|
pass
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. Git 问题
|
||||||
|
|
||||||
|
#### Q: 提交信息写错了
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 修改最后一次提交
|
||||||
|
git commit --amend -m "正确的提交信息"
|
||||||
|
|
||||||
|
# 如果已经推送,需要强制推送(谨慎使用)
|
||||||
|
git push --force-with-lease
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Q: 合并冲突
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. 拉取最新代码
|
||||||
|
git pull origin master
|
||||||
|
|
||||||
|
# 2. 解决冲突
|
||||||
|
# 编辑冲突文件,保留需要的代码
|
||||||
|
|
||||||
|
# 3. 标记为已解决
|
||||||
|
git add .
|
||||||
|
git commit -m "fix: 解决合并冲突"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 开发工具推荐
|
||||||
|
|
||||||
|
### VS Code 扩展
|
||||||
|
|
||||||
|
- **Python**: 官方 Python 扩展
|
||||||
|
- **Pylance**: 类型检查和智能提示
|
||||||
|
- **Black Formatter**: 代码格式化
|
||||||
|
- **autoDocstring**: 自动生成文档字符串
|
||||||
|
- **GitLens**: Git 增强工具
|
||||||
|
|
||||||
|
### PyCharm 配置
|
||||||
|
|
||||||
|
```python
|
||||||
|
# 设置 Black 为格式化工具
|
||||||
|
# File -> Settings -> Tools -> Black
|
||||||
|
# 勾选 "On code reformat" 和 "On save"
|
||||||
|
|
||||||
|
# 设置 pytest 为测试运行器
|
||||||
|
# File -> Settings -> Tools -> Python Integrated Tools
|
||||||
|
# Default test runner: pytest
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 最佳实践
|
||||||
|
|
||||||
|
### 1. 代码组织
|
||||||
|
|
||||||
|
```python
|
||||||
|
# 好的做法
|
||||||
|
from src.evaluators import RAGEvaluator
|
||||||
|
from src.models import TestSet
|
||||||
|
|
||||||
|
evaluator = RAGEvaluator(system_name="coze", test_set=test_set)
|
||||||
|
result = evaluator.evaluate()
|
||||||
|
|
||||||
|
# 避免
|
||||||
|
from src.evaluators.ragas import RAGEvaluator, calculate_metrics, process_results
|
||||||
|
# 太多导入,不清晰
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 错误处理
|
||||||
|
|
||||||
|
```python
|
||||||
|
# 好的做法
|
||||||
|
try:
|
||||||
|
result = evaluate_system(system_name)
|
||||||
|
except ConnectionError:
|
||||||
|
logger.error(f"Failed to connect to {system_name}")
|
||||||
|
raise
|
||||||
|
except ValueError as e:
|
||||||
|
logger.warning(f"Invalid parameter: {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
# 避免
|
||||||
|
try:
|
||||||
|
result = evaluate_system(system_name)
|
||||||
|
except Exception:
|
||||||
|
pass # 吞掉所有异常
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 配置管理
|
||||||
|
|
||||||
|
```python
|
||||||
|
# 好的做法
|
||||||
|
from src.utils.config import load_config
|
||||||
|
|
||||||
|
config = load_config()
|
||||||
|
api_key = config.get('openai_api_key')
|
||||||
|
|
||||||
|
# 避免
|
||||||
|
api_key = "sk-xxxxx" # 硬编码
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 参考资源
|
||||||
|
|
||||||
|
- **Python 官方文档**: https://docs.python.org/3/
|
||||||
|
- **PEP 8 风格指南**: https://pep8.org/
|
||||||
|
- **pytest 文档**: https://docs.pytest.org/
|
||||||
|
- **Black 文档**: https://black.readthedocs.io/
|
||||||
|
- **RAGAs 文档**: https://docs.ragas.io/
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**文档版本**: v1.0.0
|
||||||
|
**最后更新**: 2025-01-07
|
||||||
|
**维护者**: Hugh Huang
|
||||||
@@ -0,0 +1,299 @@
|
|||||||
|
# 工作总结 - RAG评估测试集精修完成
|
||||||
|
|
||||||
|
**日期**: 2025-01-07
|
||||||
|
**工作主题**: 催收RAG评估系统测试集ground_truth验证与精修
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📋 任务完成清单
|
||||||
|
|
||||||
|
### ✅ 已完成任务
|
||||||
|
|
||||||
|
1. **验证v2.0测试集ground_truth准确性**
|
||||||
|
- 随机抽取5个代表性测试用例
|
||||||
|
- 对比FAQ原文验证ground准确性
|
||||||
|
- 发现2个用例存在问题(q003、q007)
|
||||||
|
- 生成详细验证报告
|
||||||
|
|
||||||
|
2. **生成v3.0测试集(FAQ完整版)**
|
||||||
|
- 创建自动匹配脚本,从280条FAQ中查找相关内容
|
||||||
|
- 为每个问题生成包含多个FAQ的完整ground_truth
|
||||||
|
- 保留FAQ原文,不做摘要或简化
|
||||||
|
|
||||||
|
3. **创建LLM精修系统**
|
||||||
|
- 编写`refine_with_llm.py`脚本
|
||||||
|
- 支持OpenAI兼容的API(用户使用Kimi-K2模型)
|
||||||
|
- 实现LLM语义理解和智能FAQ选择
|
||||||
|
- 生成v3.1精修版本
|
||||||
|
|
||||||
|
4. **文档和配置**
|
||||||
|
- 创建项目配置文件(.env.example, .gitignore, requirements.txt)
|
||||||
|
- 编写LLM精修使用指南
|
||||||
|
- 生成v2 vs v3对比报告
|
||||||
|
- 初始化Git仓库并提交代码
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📊 测试集版本对比
|
||||||
|
|
||||||
|
### 版本演进
|
||||||
|
|
||||||
|
| 版本 | 生成方式 | Ground Truth特点 | 优势 | 劣势 |
|
||||||
|
|------|---------|-----------------|------|------|
|
||||||
|
| **v2.0** | 人工编写 | 简洁摘要 | 简洁清晰 | 信息不完整(q003、q007) |
|
||||||
|
| **v3.0** | 自动匹配 | FAQ原文(5个候选) | 信息完整 | 包含太多不相关内容 |
|
||||||
|
| **v3.1** | LLM精修 | FAQ原文(1-2个最相关) | 准确且完整 | 需要LLM API |
|
||||||
|
|
||||||
|
### 关键改进示例
|
||||||
|
|
||||||
|
#### q001: 签约流程
|
||||||
|
- **v2.0**: 精确摘要(3个平台流程)
|
||||||
|
- **v3.0**: 包含5个FAQ,其中3个不相关(催收流程、和解方案、科创贷)
|
||||||
|
- **v3.1**: ✅ 只保留【签约流程】1个FAQ
|
||||||
|
|
||||||
|
#### q003: 法人变更担保责任
|
||||||
|
- **v2.0**: ❌ 只包含"未结清借据"情况
|
||||||
|
- **v3.0**: 包含5个FAQ,但有噪音
|
||||||
|
- **v3.1**: ✅ 完整包含两种情况(未结清+已结清)
|
||||||
|
|
||||||
|
#### q004: 还款按钮找不到
|
||||||
|
- **v2.0**: 手动还款操作流程
|
||||||
|
- **v3.0**: ❌ 完全找不到相关FAQ
|
||||||
|
- **v3.1**: ✅ LLM找到【新个贷怎么还款】
|
||||||
|
|
||||||
|
#### q007: 利率和罚息
|
||||||
|
- **v2.0**: ❌ 只回答利率,未回答罚息
|
||||||
|
- **v3.0**: 包含多个不相关FAQ
|
||||||
|
- **v3.1**: ✅ 完整回答利率计算+罚息计算
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🎯 v3.1质量分析
|
||||||
|
|
||||||
|
### FAQ数量分布
|
||||||
|
|
||||||
|
正向用例(10个)的FAQ分布:
|
||||||
|
- 平均每个用例: 1-2个FAQ
|
||||||
|
- 最少: 1个FAQ(q001, q003, q006)
|
||||||
|
- 最多: 2个FAQ(q002, q005, q007)
|
||||||
|
|
||||||
|
### 覆盖的问题类型
|
||||||
|
|
||||||
|
1. **简单检索** (q001): ✅ 精确匹配
|
||||||
|
2. **复杂检索** (q002): ✅ 语义理解准确
|
||||||
|
3. **多跳检索** (q003): ✅ 完整覆盖多场景
|
||||||
|
4. **模糊查询** (q004): ✅ 推断意图正确
|
||||||
|
5. **流程类** (q005): ✅ 操作步骤完整
|
||||||
|
6. **比较类** (q006): ✅ 准确提取对比信息
|
||||||
|
7. **数值类** (q007): ✅ 包含完整计算方法
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📁 生成文件清单
|
||||||
|
|
||||||
|
### 数据文件
|
||||||
|
- `data/raw/faq_data.json` - FAQ原文(280条)
|
||||||
|
- `data/test_sets/ragas_test_cases_v2.json` - 初始测试集
|
||||||
|
- `data/test_sets/ragas_test_cases_v3.1.json` - **LLM精修版(推荐使用)**
|
||||||
|
|
||||||
|
### 工具脚本
|
||||||
|
- `tmp/generate_v3_ground_truth.py` - v3.0生成脚本
|
||||||
|
- `tmp/refine_with_llm.py` - LLM精修脚本
|
||||||
|
- `tmp/verify_ground_truth.py` - ground_truth验证脚本
|
||||||
|
- `tmp/analyze_v31.py` - v3.1统计分析脚本
|
||||||
|
|
||||||
|
### 文档
|
||||||
|
- `CLAUDE.md` - 项目说明和开发规范
|
||||||
|
- `docs/LLM_REFINE_GUIDE.md` - LLM精修使用指南
|
||||||
|
- `tmp/ground_truth_verification_report.md` - v2验证报告
|
||||||
|
- `tmp/v2_vs_v3_comparison.md` - 版本对比分析
|
||||||
|
|
||||||
|
### 配置文件
|
||||||
|
- `.env.example` - API配置模板
|
||||||
|
- `.gitignore` - Git忽略规则
|
||||||
|
- `requirements.txt` - Python依赖
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 💻 技术实现
|
||||||
|
|
||||||
|
### LLM精修流程
|
||||||
|
|
||||||
|
```
|
||||||
|
用户问题
|
||||||
|
↓
|
||||||
|
关键词匹配 → 30个候选FAQ
|
||||||
|
↓
|
||||||
|
发送给LLM (Kimi-K2-zhths)
|
||||||
|
↓
|
||||||
|
LLM语义分析
|
||||||
|
↓
|
||||||
|
选择1-2个最相关FAQ
|
||||||
|
↓
|
||||||
|
保留FAQ原文作为ground_truth
|
||||||
|
↓
|
||||||
|
生成v3.1测试集
|
||||||
|
```
|
||||||
|
|
||||||
|
### LLM Prompt设计
|
||||||
|
|
||||||
|
关键指令:
|
||||||
|
1. 分析用户问题的真实意图
|
||||||
|
2. 从候选FAQ中选择最相关的(通常1-2个)
|
||||||
|
3. 保留FAQ原文,不做任何修改或摘要
|
||||||
|
4. 如果都不相关,返回"无相关内容"
|
||||||
|
|
||||||
|
### 使用的模型
|
||||||
|
|
||||||
|
- **模型**: Kimi-K2-zhths
|
||||||
|
- **Temperature**: 0.1(低随机性,稳定输出)
|
||||||
|
- **候选FAQ数**: 30(提高命中率)
|
||||||
|
- **选择数量**: 1-2个(去噪)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🚀 后续建议
|
||||||
|
|
||||||
|
### 短期(1周内)
|
||||||
|
|
||||||
|
1. **使用v3.1进行RAG评估**
|
||||||
|
```bash
|
||||||
|
python src/evaluate.py --test-set data/test_sets/ragas_test_cases_v3.1.json
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **人工抽查验证**
|
||||||
|
- 随机抽查5个测试用例
|
||||||
|
- 验证ground_truth的准确性
|
||||||
|
- 记录发现的问题
|
||||||
|
|
||||||
|
3. **生成评估报告**
|
||||||
|
- 对比不同RAG系统(Coze、KBS、ZHT、ZHTv2)
|
||||||
|
- 使用v3.1作为ground_truth
|
||||||
|
- 生成可视化分析报告
|
||||||
|
|
||||||
|
### 中期(2-4周)
|
||||||
|
|
||||||
|
1. **扩展测试集**
|
||||||
|
- 从15个用例扩展到50+个
|
||||||
|
- 覆盖更多问题类型
|
||||||
|
- 添加边界情况测试
|
||||||
|
|
||||||
|
2. **优化LLM精修**
|
||||||
|
- 尝试不同模型(GPT-4、Claude等)
|
||||||
|
- 优化prompt设计
|
||||||
|
- 添加FAQ相关性评分
|
||||||
|
|
||||||
|
3. **建立评估基准**
|
||||||
|
- 确定各指标的合格标准
|
||||||
|
- 建立自动化评估流程
|
||||||
|
- 集成到CI/CD
|
||||||
|
|
||||||
|
### 长期(1-3月)
|
||||||
|
|
||||||
|
1. **构建评估平台**
|
||||||
|
- Web界面管理测试集
|
||||||
|
- 可视化评估结果
|
||||||
|
- 支持A/B测试
|
||||||
|
|
||||||
|
2. **持续优化**
|
||||||
|
- 收集评估反馈
|
||||||
|
- 迭代ground_truth质量
|
||||||
|
- 扩展到更多业务场景
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📝 关键决策记录
|
||||||
|
|
||||||
|
### 为什么使用LLM精修而非人工?
|
||||||
|
|
||||||
|
**决策**: 使用LLM(Kimi-K2)进行精修
|
||||||
|
|
||||||
|
**理由**:
|
||||||
|
1. **效率**: 15个用例,LLM精修约2-3分钟,人工需2-3小时
|
||||||
|
2. **语义理解**: LLM能理解问题意图,避免关键词匹配的误判
|
||||||
|
3. **一致性**: LLM输出稳定,避免人工判断的主观性
|
||||||
|
4. **可扩展**: 未来扩展到50+用例时,LLM优势更明显
|
||||||
|
|
||||||
|
**权衡**:
|
||||||
|
- 成本: 约几元钱API费用
|
||||||
|
- 依赖: 需要外部API服务
|
||||||
|
- 可控性: 需要人工抽查验证
|
||||||
|
|
||||||
|
### 为什么保留FAQ原文而非摘要?
|
||||||
|
|
||||||
|
**决策**: v3.x版本保留FAQ原文,不做摘要
|
||||||
|
|
||||||
|
**理由**:
|
||||||
|
1. **完整性**: 避免遗漏重要信息
|
||||||
|
2. **可验证**: 可以追溯来源
|
||||||
|
3. **评估准确**: RAG系统评估需要完整的ground_truth
|
||||||
|
4. **灵活性**: RAG系统可以自己生成摘要
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🎓 经验总结
|
||||||
|
|
||||||
|
### 成功经验
|
||||||
|
|
||||||
|
1. **渐进式改进**: v2 → v3.0 → v3.1,每步都有明确目标
|
||||||
|
2. **工具链完善**: 验证、生成、精修、分析脚本齐全
|
||||||
|
3. **文档完整**: 每个版本都有详细说明和使用指南
|
||||||
|
4. **Git版本管理**: 清晰的commit message,方便追溯
|
||||||
|
|
||||||
|
### 遇到的问题
|
||||||
|
|
||||||
|
1. **v3.0包含太多不相关FAQ**
|
||||||
|
- 原因: 关键词匹配过于宽松
|
||||||
|
- 解决: 使用LLM语义理解
|
||||||
|
|
||||||
|
2. **Windows编码问题**
|
||||||
|
- 原因: 控制台GBK编码无法显示UTF-8
|
||||||
|
- 解决: 使用文件输出或改用英文输出
|
||||||
|
|
||||||
|
3. **q004找不到相关FAQ**
|
||||||
|
- 原因: FAQ中没有"找不到按钮"的表述
|
||||||
|
- 解决: LLM通过语义理解找到"怎么还款"相关内容
|
||||||
|
|
||||||
|
### 改进建议
|
||||||
|
|
||||||
|
1. **建立FAQ质量标准**: 确保FAQ覆盖常见问题
|
||||||
|
2. **添加FAQ分类标签**: 便于按类型检索
|
||||||
|
3. **建立人工审核流程**: LLM输出后人工抽查
|
||||||
|
4. **添加评估指标**: 相关性、完整性、准确性等
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📊 Git提交信息
|
||||||
|
|
||||||
|
```
|
||||||
|
commit f10d549
|
||||||
|
feat: 初始化催收RAG评估系统并完成测试集精修
|
||||||
|
|
||||||
|
- 测试集版本演进: v2.0 → v3.0 → v3.1
|
||||||
|
- 核心文件: 15个测试用例,280条FAQ
|
||||||
|
- 工具脚本: 生成、验证、精修、分析
|
||||||
|
- LLM模型: Kimi-K2-zhths
|
||||||
|
- 改进效果: 平均每用例从5个FAQ降至1-2个
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ✅ 总结
|
||||||
|
|
||||||
|
本次工作成功完成了催收RAG评估系统测试集的精修,从v2.0的人工摘要版本,经过v3.0的自动匹配版本,最终使用LLM生成了v3.1精修版本。
|
||||||
|
|
||||||
|
**核心成果**:
|
||||||
|
- ✅ 验证了v2.0的问题并提出改进方案
|
||||||
|
- ✅ 生成了基于FAQ原文的完整版本
|
||||||
|
- ✅ 使用LLM实现了智能FAQ选择
|
||||||
|
- ✅ 去除了v3.0中的不相关内容
|
||||||
|
- ✅ 保留了FAQ的完整性和准确性
|
||||||
|
- ✅ 建立了可复用的精修流程
|
||||||
|
|
||||||
|
**推荐使用**: `data/test_sets/ragas_test_cases_v3.1.json`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**生成时间**: 2025-01-07
|
||||||
|
**维护者**: Claude Code
|
||||||
|
**项目**: 催收RAG评估系统
|
||||||
@@ -0,0 +1,242 @@
|
|||||||
|
# 项目待办事项
|
||||||
|
|
||||||
|
**项目**: 催收 RAG 评估系统
|
||||||
|
**最后更新**: 2025-01-07
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🎯 当前状态
|
||||||
|
|
||||||
|
**项目阶段**: 初始化完成,进入开发阶段
|
||||||
|
**版本**: v1.0.0
|
||||||
|
**测试集版本**: v3.1(LLM 精修版)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ✅ 最近完成(2025-01-07)
|
||||||
|
|
||||||
|
### 测试集精修
|
||||||
|
- [x] 验证 v2.0 测试集 ground_truth 准确性
|
||||||
|
- [x] 生成 v3.0 测试集(FAQ 完整版)
|
||||||
|
- [x] 使用 LLM(Kimi-K2)精修生成 v3.1 版本
|
||||||
|
- [x] 对比分析 v2.0、v3.0、v3.1 版本差异
|
||||||
|
|
||||||
|
### 工具开发
|
||||||
|
- [x] 创建 LLM 精修脚本(`tmp/refine_with_llm.py`)
|
||||||
|
- [x] 创建 ground_truth 验证脚本(`tmp/verify_ground_truth.py`)
|
||||||
|
- [x] 创建 v3.0 生成脚本(`tmp/generate_v3_ground_truth.py`)
|
||||||
|
|
||||||
|
### 文档完善
|
||||||
|
- [x] 创建 README.md
|
||||||
|
- [x] 创建 ARCHITECTURE.md(架构设计文档)
|
||||||
|
- [x] 创建 DEVELOPMENT_GUIDE.md(开发指南)
|
||||||
|
- [x] 创建 LLM_REFINE_GUIDE.md(LLM 精修指南)
|
||||||
|
- [x] 创建 SESSION_SUMMARY_2025-01-07.md(工作总结)
|
||||||
|
|
||||||
|
### 项目配置
|
||||||
|
- [x] 创建 .env.example(API 配置模板)
|
||||||
|
- [x] 创建 .gitignore
|
||||||
|
- [x] 创建 requirements.txt
|
||||||
|
- [x] 初始化 Git 仓库并推送到远程
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🚀 进行中
|
||||||
|
|
||||||
|
### 核心功能开发
|
||||||
|
- [ ] 实现评估引擎(Evaluators)
|
||||||
|
- [ ] RAGAs 评估器
|
||||||
|
- [ ] 自定义评估器
|
||||||
|
- [ ] 批量评估功能
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📋 待办事项
|
||||||
|
|
||||||
|
### 高优先级(本周)
|
||||||
|
|
||||||
|
#### 1. 评估引擎开发
|
||||||
|
- [ ] 设计评估器接口
|
||||||
|
- [ ] 实现 RAGAs 评估器
|
||||||
|
- [ ] 实现 RAG 系统适配器
|
||||||
|
- [ ] Coze 适配器
|
||||||
|
- [ ] KBS 适配器
|
||||||
|
- [ ] ZHT 适配器
|
||||||
|
- [ ] ZHTv2 适配器
|
||||||
|
- [ ] 编写单元测试
|
||||||
|
|
||||||
|
#### 2. 数据处理
|
||||||
|
- [ ] 实现测试集加载器
|
||||||
|
- [ ] 实现 FAQ 数据管理
|
||||||
|
- [ ] 实现验证结果解析器
|
||||||
|
|
||||||
|
#### 3. 基础工具
|
||||||
|
- [ ] 配置管理模块
|
||||||
|
- [ ] 日志系统
|
||||||
|
- [ ] 错误处理机制
|
||||||
|
|
||||||
|
### 中优先级(本月)
|
||||||
|
|
||||||
|
#### 4. 分析引擎
|
||||||
|
- [ ] 统计分析器
|
||||||
|
- [ ] 语义分析器
|
||||||
|
- [ ] 问题识别器
|
||||||
|
|
||||||
|
#### 5. 报告生成
|
||||||
|
- [ ] HTML 报告生成器
|
||||||
|
- [ ] Excel 报告生成器
|
||||||
|
- [ ] 可视化图表生成
|
||||||
|
|
||||||
|
#### 6. CLI 工具
|
||||||
|
- [ ] 评估命令
|
||||||
|
- [ ] 对比命令
|
||||||
|
- [ ] 报告生成命令
|
||||||
|
|
||||||
|
### 低优先级(下月)
|
||||||
|
|
||||||
|
#### 7. 高级功能
|
||||||
|
- [ ] 批量评估
|
||||||
|
- [ ] 并行处理
|
||||||
|
- [ ] 缓存机制
|
||||||
|
- [ ] 性能优化
|
||||||
|
|
||||||
|
#### 8. Web 界面(可选)
|
||||||
|
- [ ] 前端框架选型
|
||||||
|
- [ ] API 接口设计
|
||||||
|
- [ ] 可视化管理界面
|
||||||
|
|
||||||
|
#### 9. 测试集扩展
|
||||||
|
- [ ] 从 15 个用例扩展到 50+
|
||||||
|
- [ ] 添加更多问题类型
|
||||||
|
- [ ] 添加边界情况测试
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🐛 已知问题
|
||||||
|
|
||||||
|
### 测试集相关
|
||||||
|
- [ ] q004(还款按钮)的 ground_truth 可能需要进一步验证
|
||||||
|
- [ ] 负向用例(q011-q015)需要补充更多样本
|
||||||
|
|
||||||
|
### 工具脚本
|
||||||
|
- [ ] Windows 控制台编码问题(已通过文件输出解决)
|
||||||
|
- [ ] LLM 精修脚本需要添加重试机制
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 💡 改进建议
|
||||||
|
|
||||||
|
### 测试集质量
|
||||||
|
- [ ] 建立 FAQ 质量标准
|
||||||
|
- [ ] 添加 FAQ 分类标签
|
||||||
|
- [ ] 建立人工审核流程
|
||||||
|
- [ ] 添加评估指标(相关性、完整性、准确性)
|
||||||
|
|
||||||
|
### 开发流程
|
||||||
|
- [ ] 设置 CI/CD 流程
|
||||||
|
- [ ] 添加代码质量检查(Black、Flake8)
|
||||||
|
- [ ] 添加自动化测试
|
||||||
|
- [ ] 添加代码覆盖率报告
|
||||||
|
|
||||||
|
### 文档完善
|
||||||
|
- [ ] 添加 API 文档
|
||||||
|
- [ ] 添加使用示例
|
||||||
|
- [ ] 添加常见问题 FAQ
|
||||||
|
- [ ] 添加贡献指南
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📅 里程碑
|
||||||
|
|
||||||
|
### v1.0.0 - 初始化(已完成 ✅)
|
||||||
|
- [x] 项目结构搭建
|
||||||
|
- [x] 测试集精修(v3.1)
|
||||||
|
- [x] 基础文档完善
|
||||||
|
- [x] Git 仓库初始化
|
||||||
|
|
||||||
|
### v1.1.0 - 核心功能(预计 2 周)
|
||||||
|
- [ ] 评估引擎实现
|
||||||
|
- [ ] RAG 系统适配器
|
||||||
|
- [ ] 基础 CLI 工具
|
||||||
|
- [ ] 单元测试覆盖
|
||||||
|
|
||||||
|
### v1.2.0 - 分析报告(预计 1 个月)
|
||||||
|
- [ ] 分析引擎实现
|
||||||
|
- [ ] 报告生成器
|
||||||
|
- [ ] 可视化图表
|
||||||
|
- [ ] 完整评估流程
|
||||||
|
|
||||||
|
### v2.0.0 - 平台化(预计 3 个月)
|
||||||
|
- [ ] Web 界面
|
||||||
|
- [ ] API 服务
|
||||||
|
- [ ] 自动化流程
|
||||||
|
- [ ] 性能优化
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📊 进度追踪
|
||||||
|
|
||||||
|
### 整体进度
|
||||||
|
- **项目初始化**: 100% ✅
|
||||||
|
- **核心功能开发**: 0%
|
||||||
|
- **测试覆盖**: 0%
|
||||||
|
- **文档完善**: 80%
|
||||||
|
|
||||||
|
### 模块进度
|
||||||
|
| 模块 | 进度 | 状态 |
|
||||||
|
|------|------|------|
|
||||||
|
| 测试集管理 | 100% | ✅ 完成 |
|
||||||
|
| 评估引擎 | 0% | 📝 待开发 |
|
||||||
|
| 分析引擎 | 0% | 📝 待开发 |
|
||||||
|
| 报告生成 | 0% | 📝 待开发 |
|
||||||
|
| CLI 工具 | 0% | 📝 待开发 |
|
||||||
|
| Web 界面 | 0% | 📝 待开发 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🎓 学习资源
|
||||||
|
|
||||||
|
### 必读文档
|
||||||
|
- [ ] RAGAs 官方文档
|
||||||
|
- [ ] LangChain 文档
|
||||||
|
- [ ] Pandas 数据处理
|
||||||
|
- [ ] Matplotlib 可视化
|
||||||
|
|
||||||
|
### 推荐阅读
|
||||||
|
- [ ] RAG 系统评估最佳实践
|
||||||
|
- [ ] Python 测试驱动开发
|
||||||
|
- [ ] 软件架构设计模式
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📝 备注
|
||||||
|
|
||||||
|
### 技术债务
|
||||||
|
- 临时脚本(`tmp/`)需要重构为正式模块
|
||||||
|
- 需要添加配置文件验证
|
||||||
|
- 需要添加错误处理和日志
|
||||||
|
|
||||||
|
### 决策记录
|
||||||
|
- 使用 JSON 存储测试集(便于版本控制)
|
||||||
|
- 使用 LLM 精修 ground_truth(提高质量)
|
||||||
|
- 采用插件化架构(便于扩展)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🤝 协作
|
||||||
|
|
||||||
|
### 需要支持
|
||||||
|
- [ ] RAG 系统 API 文档
|
||||||
|
- [ ] 测试环境访问权限
|
||||||
|
- [ ] 评估指标定义确认
|
||||||
|
|
||||||
|
### 待讨论
|
||||||
|
- [ ] 评估指标的权重分配
|
||||||
|
- [ ] 测试集扩展的优先级
|
||||||
|
- [ ] Web 界面的必要性
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**维护者**: Hugh Huang
|
||||||
|
**联系方式**: hughhuang@webank.com
|
||||||
|
**项目地址**: http://fn.maiplan.site:8418/hughhuang/cuishou-rag-v2
|
||||||
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