Initial commit

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
hughhuang(黄健铭)andClaude Sonnet 4.5 committed 2026-01-16 16:01:39 +08:00
commit 4ecf7b351d
143 files changed
+24156

No files matched your search

+82
View File
@@ -0,0 +1,82 @@
# RAG Evaluation Framework - 文档中心
欢迎来到RAG评估框架的文档中心!
## 文档结构
```
docs/
├── guides/ # 使用指南
├── summaries/ # 阶段总结
├── testing/ # 测试文档
└── api/ # API文档(待完善)
```
## 快速导航
### 使用指南 (guides/)
- **[getting-started.md](guides/getting-started.md)** - 快速开始指南
- 安装依赖
- 配置系统
- 第一个示例
- **[run-guide.md](guides/run-guide.md)** - 运行指南
- 运行示例
- 常见问题
- 故障排除
### 阶段总结 (summaries/)
- **[PHASE1_SUMMARY.md](summaries/PHASE1_SUMMARY.md)** - Phase 1总结
- 测评集生成
- 文档处理
- 采样策略
- **[PHASE2_SUMMARY.md](summaries/PHASE2_SUMMARY.md)** - Phase 2总结
- 评估执行引擎
- RAG集成
- 指标计算
### 测试文档 (testing/)
- **[TESTING_SUMMARY.md](testing/TESTING_SUMMARY.md)** - 测试总结
- 测试框架
- 测试用例
- 改进建议
### API文档 (api/)
*待完善*
## 按主题浏览
### 新手入门
1. 阅读 [主项目README](../README.md)
2. 跟随 [快速开始指南](guides/getting-started.md)
3. 运行 [示例代码](guides/run-guide.md)
### 功能实现
- Phase 1功能: [PHASE1_SUMMARY.md](summaries/PHASE1_SUMMARY.md)
- Phase 2功能: [PHASE2_SUMMARY.md](summaries/PHASE2_SUMMARY.md)
### 测试和调试
- [测试框架说明](testing/TESTING_SUMMARY.md)
- [运行测试](guides/run-guide.md#运行测试)
## 贡献文档
如果您想改进文档,请:
1. 编辑相应的markdown文件
2. 保持结构清晰
3. 添加示例代码
4. 更新本README(如果需要)
## 文档状态
- ✅ 基础文档完成
- ✅ 使用指南完成
- ✅ 阶段总结完成
- ⏳ API文档待补充
- ⏳ 视频教程待制作
+465
View File
@@ -0,0 +1,465 @@
# 文件加载模块调试指南
## 📋 模块概述
文件加载模块负责从各种文件格式中加载文档内容,是 RAG 评估框架的基础组件。
### 核心组件
1. **document_loader.py** - 文档加载器
2. **sampling.py** - 采样策略
3. **generator.py** - 测评集生成器
4. **validator.py** - 测评集验证器
## 🎯 调试入口点
### 主要入口函数
```python
# 1. 加载单个文件
from rag_evaluation.testset.document_loader import TextLoader, MarkdownLoader
loader = TextLoader("path/to/file.txt")
documents = loader.load()
# 2. 批量加载文件
from rag_evaluation.testset.document_loader import load_documents
documents = load_documents([
"file1.txt",
"file2.md",
"file3.markdown"
])
# 3. 文档采样
from rag_evaluation.testset.sampling import SamplingStrategy
from rag_evaluation.core.config import TestsetConfig
config = TestsetConfig()
sampler = SamplingStrategy(config)
sampled_docs = sampler.sample_documents(documents)
# 4. 文档分块
from rag_evaluation.testset.sampling import DocumentChunker
chunker = DocumentChunker(chunk_size=1000, chunk_overlap=200)
chunks = chunker.chunk_documents(documents)
```
## 🔍 关键代码位置
### 1. 文档加载器 (document_loader.py)
**核心类:**
- `Document` (第 10-15 行) - 文档数据结构
- `DocumentLoader` (第 18-36 行) - 基础加载器
- `TextLoader` (第 39-53 行) - 文本文件加载器
- `MarkdownLoader` (第 56-70 行) - Markdown 文件加载器
**关键方法:**
- `load()` - 加载文档内容
- `get_file_size()` - 获取文件大小
- `get_file_extension()` - 获取文件扩展名
**入口函数:**
- `load_documents()` (第 73-100 行) - 批量加载文档
### 2. 采样策略 (sampling.py)
**核心类:**
- `SamplingStrategy` (第 11-66 行) - 采样策略
- `DocumentChunker` (第 69-133 行) - 文档分块器
**关键方法:**
- `get_sampling_rate()` (第 22-39 行) - 计算采样率
- `sample_documents()` (第 41-66 行) - 执行采样
- `chunk_document()` (第 83-115 行) - 分块单个文档
- `chunk_documents()` (第 117-133 行) - 批量分块
## 🧪 测试文件
### test_document_loader.py
**测试类:**
1. `TestDocument` - 测试 Document 类
2. `TestDocumentLoader` - 测试基础加载器
3. `TestTextLoader` - 测试文本加载器
4. `TestMarkdownLoader` - 测试 Markdown 加载器
5. `TestLoadDocuments` - 测试批量加载
**运行测试:**
```bash
cd rag_evaluation
python -m pytest tests/test_document_loader.py -v
```
### test_sampling.py
**运行测试:**
```bash
cd rag_evaluation
python -m pytest tests/test_sampling.py -v
```
## 🐛 调试步骤
### 步骤 1: 准备测试数据
创建测试文件:
```bash
cd rag_evaluation
# 创建测试目录
mkdir -p test_data
# 创建测试文件
echo "这是一个测试文本文件" > test_data/test.txt
echo "# 测试 Markdown\n\n这是测试内容" > test_data/test.md
```
### 步骤 2: 创建调试脚本
创建 `debug_loader.py`:
```python
import sys
import os
sys.path.insert(0, os.path.dirname(__file__))
from testset.document_loader import load_documents
from testset.sampling import SamplingStrategy, DocumentChunker
from core.config import TestsetConfig
def debug_document_loading():
"""调试文档加载"""
print("=" * 60)
print("调试: 文档加载")
print("=" * 60)
# 1. 加载文档
file_paths = [
"test_data/test.txt",
"test_data/test.md"
]
print(f"\n加载文件: {file_paths}")
try:
documents = load_documents(file_paths)
print(f"✓ 成功加载 {len(documents)} 个文档")
for i, doc in enumerate(documents):
print(f"\n文档 {i+1}:")
print(f" - 来源: {doc.metadata.get('source')}")
print(f" - 类型: {doc.metadata.get('file_type')}")
print(f" - 大小: {doc.metadata.get('file_size')} 字节")
print(f" - 内容长度: {len(doc.page_content)} 字符")
print(f" - 内容预览: {doc.page_content[:100]}...")
except Exception as e:
print(f"✗ 加载失败: {e}")
import traceback
traceback.print_exc()
return None
return documents
def debug_sampling(documents):
"""调试采样策略"""
print("\n" + "=" * 60)
print("调试: 采样策略")
print("=" * 60)
config = TestsetConfig()
sampler = SamplingStrategy(config)
print(f"\n采样配置:")
print(f" - 小文件阈值: {config.sampling_strategy['small_file_threshold_mb']} MB")
print(f" - 中文件阈值: {config.sampling_strategy['medium_file_threshold_mb']} MB")
print(f" - 小文件采样率: {config.sampling_strategy['small_file_sampling_rate']}")
print(f" - 中文件采样率: {config.sampling_strategy['medium_file_sampling_rate']}")
print(f" - 大文件采样率: {config.sampling_strategy['large_file_sampling_rate']}")
try:
sampled_docs = sampler.sample_documents(documents)
print(f"\n✓ 采样完成: {len(sampled_docs)}/{len(documents)} 文档")
for i, doc in enumerate(sampled_docs):
file_size = doc.metadata.get('file_size', 0)
sampling_rate = sampler.get_sampling_rate(file_size)
print(f" 文档 {i+1}: 采样率 = {sampling_rate:.2f}")
except Exception as e:
print(f"✗ 采样失败: {e}")
import traceback
traceback.print_exc()
return None
return sampled_docs
def debug_chunking(documents):
"""调试文档分块"""
print("\n" + "=" * 60)
print("调试: 文档分块")
print("=" * 60)
chunker = DocumentChunker(chunk_size=100, chunk_overlap=20)
print(f"\n分块配置:")
print(f" - 块大小: {chunker.chunk_size} 字符")
print(f" - 重叠大小: {chunker.chunk_overlap} 字符")
try:
chunks = chunker.chunk_documents(documents)
print(f"\n✓ 分块完成: {len(chunks)} 个块")
for i, chunk in enumerate(chunks[:5]): # 只显示前5个
print(f"\n 块 {i+1}:")
print(f" - 来源: {chunk.metadata.get('source')}")
print(f" - 块索引: {chunk.metadata.get('chunk_index')}")
print(f" - 起始位置: {chunk.metadata.get('chunk_start')}")
print(f" - 结束位置: {chunk.metadata.get('chunk_end')}")
print(f" - 内容长度: {len(chunk.page_content)} 字符")
print(f" - 内容预览: {chunk.page_content[:50]}...")
if len(chunks) > 5:
print(f"\n ... 还有 {len(chunks) - 5} 个块")
except Exception as e:
print(f"✗ 分块失败: {e}")
import traceback
traceback.print_exc()
return None
return chunks
def main():
"""主函数"""
print("\n" + "=" * 60)
print("文件加载模块调试")
print("=" * 60)
# 1. 调试文档加载
documents = debug_document_loading()
if not documents:
print("\n调试终止: 文档加载失败")
return
# 2. 调试采样
sampled_docs = debug_sampling(documents)
if not sampled_docs:
print("\n调试终止: 采样失败")
return
# 3. 调试分块
chunks = debug_chunking(sampled_docs)
if not chunks:
print("\n调试终止: 分块失败")
return
print("\n" + "=" * 60)
print("调试完成!")
print("=" * 60)
print(f"\n总结:")
print(f" - 加载文档: {len(documents)} 个")
print(f" - 采样后: {len(sampled_docs)} 个")
print(f" - 分块后: {len(chunks)} 个")
print()
if __name__ == '__main__':
main()
```
### 步骤 3: 运行调试脚本
```bash
cd rag_evaluation
python debug_loader.py
```
### 步骤 4: 使用 Python 调试器
使用 pdb 进行交互式调试:
```python
# 在代码中添加断点
import pdb; pdb.set_trace()
# 或使用 IPython
from IPython import embed; embed()
```
使用 VS Code 调试:
1. 创建 `.vscode/launch.json`:
```json
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug Document Loader",
"type": "debugpy",
"request": "launch",
"program": "${workspaceFolder}/rag_evaluation/debug_loader.py",
"console": "integratedTerminal",
"cwd": "${workspaceFolder}/rag_evaluation"
}
]
}
```
2. 在代码中设置断点
3. 按 F5 开始调试
## 🔧 常见问题排查
### 问题 1: FileNotFoundError
**症状:** 文件找不到
**排查:**
```python
from pathlib import Path
file_path = "test_data/test.txt"
path = Path(file_path)
print(f"文件路径: {path}")
print(f"绝对路径: {path.absolute()}")
print(f"文件存在: {path.exists()}")
print(f"是文件: {path.is_file()}")
```
### 问题 2: UnicodeDecodeError
**症状:** 编码错误
**排查:**
```python
# 检测文件编码
import chardet
with open(file_path, 'rb') as f:
raw_data = f.read()
result = chardet.detect(raw_data)
print(f"检测到的编码: {result['encoding']}")
print(f"置信度: {result['confidence']}")
```
### 问题 3: 采样率计算错误
**症状:** 采样结果不符合预期
**排查:**
```python
from utils.helpers import calculate_file_size_mb
file_size_bytes = 1024 * 1024 * 5 # 5MB
file_size_mb = calculate_file_size_mb(file_size_bytes)
print(f"文件大小: {file_size_bytes} 字节")
print(f"文件大小: {file_size_mb} MB")
sampler = SamplingStrategy(config)
sampling_rate = sampler.get_sampling_rate(file_size_bytes)
print(f"采样率: {sampling_rate}")
```
### 问题 4: 分块重叠错误
**症状:** 分块边界不正确
**排查:**
```python
chunker = DocumentChunker(chunk_size=100, chunk_overlap=20)
# 测试小文档
test_content = "A" * 250 # 250个字符
test_doc = Document(content=test_content, metadata={})
chunks = chunker.chunk_document(test_doc)
print(f"原始长度: {len(test_content)}")
print(f"块数量: {len(chunks)}")
for i, chunk in enumerate(chunks):
start = chunk.metadata['chunk_start']
end = chunk.metadata['chunk_end']
print(f"块 {i}: [{start}:{end}] 长度={len(chunk.page_content)}")
```
## 📊 性能分析
### 使用 cProfile
```python
import cProfile
import pstats
profiler = cProfile.Profile()
profiler.enable()
# 执行要分析的代码
documents = load_documents(file_paths)
profiler.disable()
stats = pstats.Stats(profiler)
stats.sort_stats('cumulative')
stats.print_stats(20) # 显示前20个最耗时的函数
```
### 使用 memory_profiler
```bash
pip install memory-profiler
# 在函数上添加装饰器
@profile
def load_documents(file_paths):
...
# 运行
python -m memory_profiler debug_loader.py
```
## 📝 日志配置
添加详细日志:
```python
import logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('debug_loader.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
# 在代码中添加日志
logger.debug(f"加载文件: {file_path}")
logger.info(f"成功加载 {len(documents)} 个文档")
logger.warning(f"文件大小超过阈值: {file_size_mb} MB")
logger.error(f"加载失败: {e}")
```
## 🎓 下一步
调试完文件加载模块后,可以继续调试:
1. **测评集生成器** (`generator.py`)
2. **测评集验证器** (`validator.py`)
3. **评估执行引擎** (`evaluation/executor.py`)
4. **指标计算器** (`evaluation/metrics.py`)
## 📚 参考资料
- 测试文件: `tests/test_document_loader.py`
- 测试文件: `tests/test_sampling.py`
- 配置文件: `core/config.py`
- 工具函数: `utils/helpers.py`
+251
View File
@@ -0,0 +1,251 @@
# 文件加载模块调试准备完成
## ✅ 已完成的准备工作
### 1. 文档准备
- ✅ 创建了详细的调试指南: `docs/debug_guide_loader.md`
- ✅ 创建了可执行的调试脚本: `debug_loader.py`
- ✅ 自动生成测试数据文件
### 2. 调试脚本功能
调试脚本 `debug_loader.py` 包含以下功能:
1. **文档加载测试**
- 加载文本文件 (.txt)
- 加载 Markdown 文件 (.md)
- 显示文档元数据和内容预览
2. **采样策略测试**
- 显示采样配置
- 执行文档采样
- 显示每个文档的采样率
3. **文档分块测试**
- 配置分块参数
- 执行文档分块
- 显示分块结果和元数据
### 3. 测试结果
运行 `python debug_loader.py` 的结果:
```
✓ 成功加载 2 个文档
- test.txt (110 字符)
- test.md (147 字符)
✓ 采样完成: 2/2 文档
- 采样率均为 1.00 (小文件)
✓ 分块完成: 4 个块
- 块大小: 100 字符
- 重叠大小: 20 字符
```
## 🎯 关键代码入口点
### 主要模块
1. **document_loader.py**
- `Document` 类 - 文档数据结构
- `DocumentLoader` - 基础加载器
- `TextLoader` - 文本加载器
- `MarkdownLoader` - Markdown 加载器
- `load_documents()` - 批量加载入口函数 ⭐
2. **sampling.py**
- `SamplingStrategy` - 采样策略
- `get_sampling_rate()` - 计算采样率
- `sample_documents()` - 执行采样 ⭐
- `DocumentChunker` - 文档分块器
- `chunk_document()` - 分块单个文档
- `chunk_documents()` - 批量分块 ⭐
### 关键入口函数
```python
# 1. 加载文档 (最常用的入口)
from rag_evaluation.testset.document_loader import load_documents
documents = load_documents(file_paths)
# 2. 采样文档
from rag_evaluation.testset.sampling import SamplingStrategy
from rag_evaluation.core.config import TestsetConfig
config = TestsetConfig()
sampler = SamplingStrategy(config)
sampled_docs = sampler.sample_documents(documents)
# 3. 分块文档
from rag_evaluation.testset.sampling import DocumentChunker
chunker = DocumentChunker(chunk_size=1000, chunk_overlap=200)
chunks = chunker.chunk_documents(documents)
```
## 🔍 调试建议
### 1. 从简单到复杂
建议按以下顺序调试:
1. **单个文件加载** - 测试 `TextLoader` 和 `MarkdownLoader`
2. **批量文件加载** - 测试 `load_documents()`
3. **采样策略** - 测试不同文件大小的采样
4. **文档分块** - 测试分块逻辑和边界
### 2. 使用断点调试
在以下位置设置断点:
```python
# document_loader.py
def load(self): # 第 42 行 (TextLoader)
with open(self.file_path, 'r', encoding='utf-8') as f:
content = f.read() # 在这里设置断点
# sampling.py
def get_sampling_rate(self, file_size_bytes: int): # 第 22 行
file_size_mb = calculate_file_size_mb(file_size_bytes) # 在这里设置断点
def chunk_document(self, document: Document): # 第 83 行
while start < len(content): # 在这里设置断点
```
### 3. 添加日志
在关键位置添加日志输出:
```python
import logging
logger = logging.getLogger(__name__)
# 在 load() 方法中
logger.debug(f"Loading file: {self.file_path}")
logger.info(f"Loaded {len(content)} characters")
# 在 sample_documents() 方法中
logger.debug(f"Sampling rate for {doc.metadata['source']}: {sampling_rate}")
# 在 chunk_document() 方法中
logger.debug(f"Creating chunk {chunk_index}: [{start}:{end}]")
```
### 4. 测试边界情况
测试以下场景:
- ✅ 空文件
- ✅ 超大文件 (>10MB)
- ✅ Unicode 字符
- ✅ 特殊字符文件名
- ✅ 不存在的文件
- ✅ 无权限的文件
## 📊 性能监控
### 使用 cProfile
```python
import cProfile
import pstats
profiler = cProfile.Profile()
profiler.enable()
# 执行加载
documents = load_documents(file_paths)
profiler.disable()
stats = pstats.Stats(profiler)
stats.sort_stats('cumulative')
stats.print_stats(10)
```
### 使用 time 模块
```python
import time
start = time.time()
documents = load_documents(file_paths)
elapsed = time.time() - start
print(f"加载耗时: {elapsed:.2f} 秒")
print(f"平均每个文件: {elapsed/len(file_paths):.2f} 秒")
```
## 🐛 常见问题
### 问题 1: 文件编码错误
**解决方案:**
```python
# 尝试不同编码
encodings = ['utf-8', 'gbk', 'gb2312', 'latin-1']
for encoding in encodings:
try:
with open(file_path, 'r', encoding=encoding) as f:
content = f.read()
break
except UnicodeDecodeError:
continue
```
### 问题 2: 文件路径问题
**解决方案:**
```python
from pathlib import Path
# 使用绝对路径
file_path = Path(file_path).absolute()
# 检查文件是否存在
if not file_path.exists():
raise FileNotFoundError(f"File not found: {file_path}")
```
### 问题 3: 分块边界错误
**解决方案:**
```python
# 确保最后一个块不会超出文档长度
end = min(start + self.chunk_size, len(content))
```
## 📝 下一步
完成文件加载模块调试后,可以继续:
1. **测评集生成器** (`testset/generator.py`)
- 集成 RAGAS TestsetGenerator
- 生成问题和答案
2. **评估执行引擎** (`evaluation/executor.py`)
- RAG 系统集成
- 指标计算
3. **报告生成** (`report/generator.py`)
- 结果聚合
- 报告生成
## 🎓 参考资料
- 调试指南: `docs/debug_guide_loader.md`
- 调试脚本: `debug_loader.py`
- 测试文件: `tests/test_document_loader.py`
- 测试文件: `tests/test_sampling.py`
- 配置文件: `core/config.py`
## 📞 需要帮助?
如果遇到问题,可以:
1. 查看测试文件了解预期行为
2. 运行单元测试: `pytest tests/test_document_loader.py -v`
3. 查看日志输出
4. 使用调试器逐步执行
祝调试顺利! 🚀
@@ -0,0 +1,186 @@
# Quick Start Guide
## Phase 1 MVP - Testset Generation
This guide will help you get started with the RAG Evaluation Framework Phase 1 (MVP).
### Prerequisites
- Python 3.8+
- MySQL 5.7+ or 8.0+
- pip
### Installation
1. **Install dependencies**:
```bash
cd rag_evaluation
pip install -r requirements.txt
```
2. **Set up environment variables**:
```bash
cp .env.example .env
# Edit .env and add your API keys and database password
```
3. **Configure the framework**:
```bash
cp config.example.yaml config.yaml
# Edit config.yaml to customize settings
```
4. **Initialize database**:
```sql
-- Create database
CREATE DATABASE rag_evaluation CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;
-- Run schema initialization (will be done automatically by example.py)
```
### Usage
#### Run the example
```bash
python example.py
```
This will:
1. Initialize the database schema
2. Create a sample document
3. Generate a testset with 15 questions
4. Save the testset to JSON file
5. Demonstrate loading the testset
#### Generate testset for your knowledge base
```python
from rag_evaluation.core.config import Config
from rag_evaluation.testset.generator import TestsetGenerator
# Load configuration
config = Config.from_file("config.yaml")
# Create generator
generator = TestsetGenerator(config)
# Generate testset
testset = generator.generate(
knowledge_base_id="your-kb-id",
file_paths=[
"/path/to/doc1.txt",
"/path/to/doc2.md",
],
test_size=50, # Number of questions
name="My Testset"
)
# Save testset
file_path = generator.save_testset(testset)
print(f"Testset saved to: {file_path}")
```
### Configuration
#### LLM Configuration
```yaml
llm:
generator_model: "claude-3-sonnet-20240229"
generator_api_base: "https://api.anthropic.com"
generator_api_key: "${ANTHROPIC_API_KEY}"
evaluator_model: "gpt-4"
evaluator_api_base: "https://api.openai.com/v1"
evaluator_api_key: "${OPENAI_API_KEY}"
```
#### Testset Configuration
```yaml
testset:
default_size: 15 # Default number of questions
question_distribution:
simple: 0.4 # 40% simple questions
reasoning: 0.4 # 40% reasoning questions
multi_context: 0.2 # 20% multi-context questions
```
#### Sampling Strategy
```yaml
testset:
sampling_strategy:
small_file_threshold_mb: 1.0 # Files < 1MB
medium_file_threshold_mb: 10.0 # Files < 10MB
small_file_sampling_rate: 1.0 # 100% sampling
medium_file_sampling_rate: 0.4 # 40% sampling
large_file_sampling_rate: 0.15 # 15% sampling
```
### Project Structure
```
rag_evaluation/
├── core/ # Core configuration
│ └── config.py # Configuration management
├── testset/ # Testset generation
│ ├── document_loader.py # Document loading
│ ├── sampling.py # Sampling strategy
│ └── generator.py # Testset generator
├── storage/ # Data storage
│ ├── database.py # Database operations
│ └── schema.sql # Database schema
├── utils/ # Utilities
│ └── helpers.py # Helper functions
├── data/ # Data directory (created automatically)
│ ├── testsets/ # Generated testsets
│ ├── reports/ # Evaluation reports
│ └── cache/ # Cache files
├── config.example.yaml # Example configuration
├── .env.example # Example environment variables
├── requirements.txt # Python dependencies
└── example.py # Usage example
```
### Next Steps
Phase 1 (MVP) provides testset generation. The following phases will add:
- **Phase 2**: Evaluation execution engine (RAG integration, metrics calculation)
- **Phase 3**: Report generation (HTML/JSON reports, insights, recommendations)
- **Phase 4**: API service
- **Phase 5**: CI/CD integration
### Troubleshooting
#### Database connection error
Make sure MySQL is running and credentials in config.yaml are correct:
```yaml
database:
host: "localhost"
port: 3306
user: "root"
password: "${DB_PASSWORD}"
```
#### Import errors
Make sure you're in the correct directory and dependencies are installed:
```bash
cd rag_evaluation
pip install -r requirements.txt
```
#### File not found errors
Check that file paths are absolute or relative to the current working directory.
### Support
For issues and questions, please refer to:
- OpenSpec documentation: `openspec/changes/add-rag-evaluation-framework/`
- Design document: `openspec/changes/add-rag-evaluation-framework/design.md`
- Tasks: `openspec/changes/add-rag-evaluation-framework/tasks.md`
+147
View File
@@ -0,0 +1,147 @@
# 快速运行指南
## 问题已修复!
之前的模块导入错误已经修复。现在可以直接运行示例了。
## 三种运行方式
### 方式1: 直接运行 (推荐)
```bash
cd rag_evaluation
python example.py # Phase 1 - 测评集生成
python example_phase2.py # Phase 2 - 评估执行
```
### 方式2: 使用run脚本
```bash
cd rag_evaluation
python run.py example.py
python run.py example_phase2.py
```
### 方式3: 测试框架
```bash
cd rag_evaluation
python test_framework.py
```
## 如果遇到问题
### 问题1: ModuleNotFoundError
**解决方案**: 确保你在`rag_evaluation`目录下运行,或使用`run.py`脚本。
### 问题2: 依赖未安装
**解决方案**:
```bash
cd rag_evaluation
pip install -r requirements.txt
```
### 问题3: 数据库连接失败
**解决方案**:
1. 确保MySQL正在运行
2. 创建数据库: `CREATE DATABASE rag_evaluation;`
3. 更新`config.example.yaml`中的数据库配置
4. 复制配置: `cp config.example.yaml config.yaml`
## 当前功能
### Phase 1: 测评集生成 ✅
- 加载文档(TXT, Markdown)
- 智能分块
- 分层采样
- 生成测评集
- JSON持久化
### Phase 2: 评估执行 ✅
- Mock RAG系统
- 7个评估指标
- 数据库存储
- 结果汇总
## 示例输出
### Phase 1 输出示例:
```
Loading configuration...
Initializing database...
Database schema initialized successfully
Generating testset...
Created sample file: ./data/sample_docs/sample.txt
Testset generated:
ID: ts-abc123
Name: Example Testset
Questions: 15
Saving testset...
Testset saved to: ./data/testsets/ts-abc123.json
✅ Example completed successfully!
```
### Phase 2 输出示例:
```
============================================================
RAG Evaluation Framework - Phase 2 Example
============================================================
[1/6] Loading configuration...
✓ Configuration loaded
[2/6] Initializing database...
✓ Database schema initialized
[3/6] Generating testset...
✓ Testset generated: ts-xyz789
[4/6] Setting up RAG system...
✓ Mock RAG system initialized
[5/6] Executing evaluation...
✓ Evaluation completed: eval-def456
[6/6] Evaluation Results
------------------------------------------------------------
📊 Overall Score: 75.50/100
📈 Retrieval Metrics:
- Context Recall: 0.800
- Context Precision: 0.750
- MRR: 0.850
- NDCG: 0.780
📝 Generation Metrics:
- Faithfulness: 0.720
- Answer Relevancy: 0.680
- Correctness: 0.650
✅ Phase 2 Example Completed Successfully!
```
## 下一步
1. **安装依赖**: `pip install -r requirements.txt`
2. **运行Phase 1**: `python example.py`
3. **运行Phase 2**: `python example_phase2.py`
4. **查看生成的文件**:
- 测评集: `./data/testsets/*.json`
- 数据库: `rag_evaluation` 数据库
## 需要帮助?
查看详细文档:
- `README.md` - 项目概述
- `QUICKSTART.md` - 快速开始
- `PHASE1_SUMMARY.md` - Phase 1详情
- `PHASE2_SUMMARY.md` - Phase 2详情
- `TESTING_SUMMARY.md` - 测试说明
+168
View File
@@ -0,0 +1,168 @@
# Phase 3 完成总结
## 完成时间
2026-01-15
## 完成的任务
### 3.2.4 实现报告可视化(图表和趋势图)
- ✅ 创建了 `report/visualizer.py` 模块
- ✅ 实现了 HTML 报告生成功能
- ✅ 实现了多种图表类型:
- 指标雷达图 (Radar Chart)
- 指标对比柱状图 (Bar Chart)
- 通过率饼图 (Pie Chart)
- ✅ 实现了趋势图生成功能
- ✅ 使用 Plotly 库进行可视化
- ✅ 支持自定义样式和主题
### 3.3.1 实现评估历史数据存储
- ✅ 创建了 `storage/history.py` 模块
- ✅ 实现了 `HistoryManager` 类
- ✅ 实现了以下功能:
- `save_evaluation_history()` - 保存评估历史记录
- `get_history_by_knowledge_base()` - 获取知识库历史
- `get_history_by_evaluation()` - 获取特定评估的历史
- `get_metric_trend()` - 获取指标趋势数据
- `get_all_metrics_trend()` - 获取所有指标趋势
- `get_latest_metrics()` - 获取最新指标值
- `delete_old_history()` - 清理旧历史记录
### 3.3.2 实现趋势对比分析
- ✅ 创建了 `storage/trend_analyzer.py` 模块
- ✅ 实现了 `TrendAnalyzer` 类
- ✅ 实现了以下功能:
- `compare_with_baseline()` - 与基线对比
- `analyze_trend()` - 分析单个指标趋势
- `analyze_all_trends()` - 分析所有指标趋势
- `generate_trend_summary()` - 生成趋势摘要
### 3.3.3 实现性能回归检测
- ✅ 实现了 `detect_regression()` 方法
- ✅ 支持自定义回归阈值
- ✅ 自动计算回归严重程度 (critical/high/medium/low)
- ✅ 按严重程度排序回归问题
### 3.3.4 编写趋势分析的单元测试
- ✅ 创建了 `tests/test_visualizer.py` (6个测试用例)
- ✅ 创建了 `tests/test_trend_analyzer.py` (17个测试用例)
- ✅ 所有测试通过
- ✅ 测试覆盖率良好
## 新增文件
1. `rag_evaluation/report/visualizer.py` - 报告可视化模块
2. `rag_evaluation/storage/history.py` - 历史数据管理模块
3. `rag_evaluation/storage/trend_analyzer.py` - 趋势分析模块
4. `rag_evaluation/tests/test_visualizer.py` - 可视化测试
5. `rag_evaluation/tests/test_trend_analyzer.py` - 趋势分析测试
6. `rag_evaluation/example_phase3.py` - Phase 3 功能演示
## 更新的文件
1. `rag_evaluation/report/__init__.py` - 添加 ReportVisualizer 导出
2. `rag_evaluation/storage/__init__.py` - 添加 HistoryManager 和 TrendAnalyzer 导出
3. `rag_evaluation/requirements.txt` - 添加 plotly 依赖
4. `openspec/changes/add-rag-evaluation-framework/tasks.md` - 更新任务状态
## 技术亮点
### 1. 报告可视化
- 使用 Plotly 生成交互式图表
- 响应式 HTML 设计,支持移动端
- 美观的渐变色主题
- 自动生成多层级报告结构
### 2. 历史数据管理
- 高效的数据库查询设计
- 支持按知识库、评估ID、指标名称查询
- 自动生成业务流水号和系统流水号
- 支持历史数据清理
### 3. 趋势分析
- 使用线性回归计算趋势方向
- 基于标准差的异常检测
- 智能的回归严重程度评估
- 全面的趋势摘要生成
### 4. 测试覆盖
- 单元测试覆盖所有核心功能
- 使用 Mock 对象隔离依赖
- 测试边界条件和异常情况
## 依赖项
新增依赖:
- plotly>=5.18.0 - 用于数据可视化
## 使用示例
### 生成 HTML 报告
```python
from report.visualizer import ReportVisualizer
visualizer = ReportVisualizer()
visualizer.generate_html_report(
summary,
results,
'report.html',
include_charts=True
)
```
### 保存历史数据
```python
from storage.history import HistoryManager
history_manager = HistoryManager(db_manager)
history_manager.save_evaluation_history(summary)
```
### 趋势分析
```python
from storage.trend_analyzer import TrendAnalyzer
analyzer = TrendAnalyzer(history_manager)
trend = analyzer.analyze_trend(knowledge_base_id, 'context_recall', days=30)
```
### 回归检测
```python
regressions = analyzer.detect_regression(
knowledge_base_id,
current_metrics,
threshold_pct=5.0
)
```
## 测试结果
### 可视化测试
```
tests/test_visualizer.py::TestReportVisualizer::test_create_trend_chart PASSED
tests/test_visualizer.py::TestReportVisualizer::test_create_trend_chart_empty_data PASSED
tests/test_visualizer.py::TestReportVisualizer::test_generate_html_report PASSED
tests/test_visualizer.py::TestReportVisualizer::test_generate_html_report_without_charts PASSED
tests/test_visualizer.py::TestReportVisualizer::test_score_to_grade PASSED
tests/test_visualizer.py::TestReportVisualizer::test_translate_metric_name PASSED
6 passed
```
### 趋势分析测试
```
tests/test_trend_analyzer.py - 17 passed
```
## 下一步
Phase 4: API和用户界面
- 4.1 API设计
- 4.2 CLI工具(可选)
## 备注
- HTML 报告已成功生成并包含交互式图表
- 所有核心功能已实现并通过测试
- 代码质量良好,遵循项目规范
- 文档完整,易于使用和维护
@@ -0,0 +1,230 @@
# Phase 1 Implementation Summary
## 完成状态
✅ **Phase 1 (MVP) - 基础设施和测评集生成** 已完成
### 已实现功能
#### 1. 项目结构 (Phase 1.1)
- ✅ 完整的项目目录结构
- ✅ 模块化设计(core, testset, storage, utils等)
- ✅ 最小依赖原则(requirements.txt)
- ✅ 配置管理系统(config.py)
- ✅ 示例配置文件(config.example.yaml)
- ✅ 环境变量模板(.env.example)
#### 2. 数据存储 (Phase 1.2)
- ✅ MySQL数据库schema(符合规范)
- knowledge_bases表
- testsets表
- evaluations表
- evaluation_results表
- evaluation_summaries表
- evaluation_history表
- ✅ 数据库连接管理器(DatabaseManager)
- ✅ 自动schema初始化
#### 3. 文档处理 (Phase 1.2)
- ✅ 文档加载器(DocumentLoader)
- 支持TXT文件
- 支持Markdown文件
- 可扩展架构
- ✅ 文档分块器(DocumentChunker)
- 可配置chunk大小和重叠
- 保留元数据
- ✅ 智能采样策略(SamplingStrategy)
- 基于文件大小的分层采样
- 小文件100%,中文件40%,大文件15%
#### 4. 测评集生成 (Phase 1.3)
- ✅ 测评集生成器(TestsetGenerator)
- 集成采样和分块策略
- 支持自定义问题数量
- 问题类型分布(simple/reasoning/multi_context)
- ✅ JSON持久化存储
- 标准化testset格式
- 包含完整元数据
- 支持加载和保存
#### 5. 工具和示例
- ✅ ID生成工具(generate_id, generate_biz_seq, generate_sys_seq)
- ✅ 时间处理工具
- ✅ 文件大小计算工具
- ✅ 完整使用示例(example.py)
- ✅ 快速开始指南(QUICKSTART.md)
## 项目结构
```
rag_evaluation/
├── core/
│ ├── __init__.py
│ └── config.py # 配置管理
├── testset/
│ ├── __init__.py
│ ├── document_loader.py # 文档加载
│ ├── sampling.py # 采样策略
│ └── generator.py # 测评集生成
├── storage/
│ ├── __init__.py
│ ├── database.py # 数据库操作
│ └── schema.sql # 数据库schema
├── utils/
│ ├── __init__.py
│ └── helpers.py # 工具函数
├── evaluation/ # Phase 2
├── report/ # Phase 3
├── api/ # Phase 4
├── tests/ # Phase 6
├── __init__.py
├── example.py # 使用示例
├── requirements.txt # 依赖
├── config.example.yaml # 配置示例
├── .env.example # 环境变量示例
├── README.md # 项目文档
└── QUICKSTART.md # 快速开始
```
## 关键设计决策
### 1. 最小依赖原则
只包含Phase 1必需的依赖:
- ragas: 测评集生成
- langchain: 文档处理
- pymysql: 数据库连接
- pyyaml: 配置管理
- python-dotenv: 环境变量
### 2. 配置灵活性
- LLM配置支持api_base、api_key和model
- 所有参数可配置(采样率、问题分布等)
- 支持环境变量替换
### 3. 数据库规范
严格遵循您的表结构规范:
- utf8mb4_bin编码
- 32位varchar主键
- biz_seq和sys_seq流水号
- create_time和update_time时间字段
- 下划线命名法
- 索引数量≤5个
### 4. 模块化设计
- 清晰的职责分离
- 可独立测试
- 易于扩展
## 使用方法
### 基本使用
```python
from rag_evaluation.core.config import Config
from rag_evaluation.testset.generator import TestsetGenerator
# 加载配置
config = Config.from_file("config.yaml")
# 创建生成器
generator = TestsetGenerator(config)
# 生成测评集
testset = generator.generate(
knowledge_base_id="kb-001",
file_paths=["/path/to/doc1.txt"],
test_size=15
)
# 保存测评集
file_path = generator.save_testset(testset)
```
### 运行示例
```bash
cd rag_evaluation
python example.py
```
## 待实现功能(后续Phase)
### Phase 2: 评估执行引擎
- RAG系统接口适配器
- 指标计算器(Recall, Precision, MRR, Faithfulness等)
- 并行执行
- 结果缓存
### Phase 3: 报告生成
- HTML报告生成
- JSON报告生成
- 数据可视化
- 改进建议生成
- 历史趋势分析
### Phase 4: API服务
- REST API
- 异步任务执行
- 认证授权
### Phase 5: CI/CD集成
- 回归测试支持
- 自动化触发
- 性能回归检测
### Phase 6: 测试和优化
- 单元测试
- 集成测试
- 性能优化
- 文档完善
## 注意事项
### 当前限制
1. **RAGAS集成**: 当前使用占位符问题,需要集成真实的RAGAS TestsetGenerator
2. **文档格式**: 仅支持TXT和Markdown,需要添加PDF、DOCX等
3. **采样策略**: 当前为简单实现,需要更智能的分层采样
4. **错误处理**: 需要添加更完善的异常处理和日志
### 下一步行动
1. **测试Phase 1功能**:
```bash
python example.py
```
2. **集成真实RAGAS**:
- 安装完整RAGAS依赖
- 配置LLM API
- 替换占位符实现
3. **开始Phase 2**:
- 实现RAG接口适配器
- 实现指标计算器
- 实现评估执行引擎
## 验证清单
- [x] 项目结构创建完成
- [x] 配置系统实现
- [x] 数据库schema创建
- [x] 文档加载器实现
- [x] 采样策略实现
- [x] 测评集生成器实现
- [x] JSON持久化实现
- [x] 示例代码创建
- [x] 文档编写完成
- [ ] 单元测试(Phase 6)
- [ ] 集成测试(Phase 6)
- [ ] 真实RAGAS集成(需要API配置)
## 总结
Phase 1 (MVP)已成功实现,提供了:
- 完整的项目基础设施
- 可配置的测评集生成系统
- 规范的数据库设计
- 清晰的使用示例
框架已准备好进入Phase 2(评估执行引擎)的开发。
@@ -0,0 +1,299 @@
# Phase 2 Implementation Summary
## 完成状态
✅ **Phase 2 - 评估执行引擎** 已完成核心功能!
### 已实现功能
#### 1. RAG系统集成 (Phase 2.1)
- ✅ RAG检索接口适配器
- 抽象基类 `RAGRetriever`
- HTTP实现 `HTTPRAGRetriever`
- Mock实现 `MockRAGRetriever`
- ✅ RAG生成接口适配器
- 抽象基类 `RAGGenerator`
- HTTP实现 `HTTPRAGGenerator`
- Mock实现 `MockRAGGenerator`
- ✅ RAG评估适配器 `RAGEvaluationAdapter`
- 统一的评估接口
- 时间测量(检索和生成)
- 结果封装
#### 2. 指标计算 (Phase 2.2)
- ✅ 检索指标
- **Context Recall**: 召回率计算
- **Context Precision**: 精确率计算
- **MRR**: 平均倒数排名
- **NDCG**: 归一化折损累计增益
- ✅ 生成指标
- **Faithfulness**: 忠实度评估
- **Answer Relevancy**: 答案相关性
- **Correctness**: 正确性评估
- ✅ 统一的指标计算器 `MetricsCalculator`
#### 3. 评估流程编排 (Phase 2.3)
- ✅ 评估执行器 `EvaluationExecutor`
- 完整的评估流程
- 数据库集成
- 状态管理
- ✅ 评估任务管理
- 创建评估任务
- 状态跟踪(pending/running/completed/failed)
- 进度查询
- ✅ 结果存储
- 详细结果存储(每个问题)
- 汇总统计
- 整体评分计算
- ✅ 错误处理
- 异常捕获
- 失败记录
- 状态更新
## 新增文件
```
rag_evaluation/evaluation/
├── __init__.py # 模块导出
├── rag_adapter.py # RAG接口适配器
├── metrics.py # 指标计算
└── executor.py # 评估执行器
example_phase2.py # Phase 2完整示例
```
## 关键特性
### 1. 灵活的RAG集成
支持多种RAG系统集成方式:
```python
# HTTP API集成
retriever = HTTPRAGRetriever(
endpoint="http://your-rag-api/retrieve",
api_key="your-api-key"
)
# Mock测试
retriever = MockRAGRetriever(documents=your_docs)
# 自定义实现
class CustomRetriever(RAGRetriever):
def retrieve(self, query, top_k=5):
# Your implementation
pass
```
### 2. 完整的指标体系
7个核心指标,覆盖检索和生成两个维度:
| 维度 | 指标 | 说明 |
|------|------|------|
| 检索 | Context Recall | 相关文档召回率 |
| 检索 | Context Precision | 检索精确率 |
| 检索 | MRR | 首个相关文档排名 |
| 检索 | NDCG | 排序质量 |
| 生成 | Faithfulness | 答案忠实度 |
| 生成 | Answer Relevancy | 答案相关性 |
| 生成 | Correctness | 答案正确性 |
### 3. 自动化评估流程
```python
# 创建评估器
executor = EvaluationExecutor(config, rag_adapter, db_manager)
# 执行评估
evaluation_id = executor.execute_evaluation(
testset_id=testset['id'],
knowledge_base_id="kb-001",
testset=testset
)
# 查询结果
summary = executor.get_evaluation_summary(evaluation_id)
results = executor.get_evaluation_results(evaluation_id)
```
### 4. 数据库持久化
所有评估数据自动保存到MySQL:
- `evaluations`: 评估任务
- `evaluation_results`: 详细结果
- `evaluation_summaries`: 汇总统计
## 使用示例
### 基本使用
```python
from rag_evaluation.core.config import Config
from rag_evaluation.evaluation import (
MockRAGRetriever,
MockRAGGenerator,
RAGEvaluationAdapter,
EvaluationExecutor
)
# 1. 配置
config = Config.from_file("config.yaml")
# 2. 创建RAG适配器
retriever = MockRAGRetriever()
generator = MockRAGGenerator()
rag_adapter = RAGEvaluationAdapter(retriever, generator)
# 3. 执行评估
executor = EvaluationExecutor(config, rag_adapter)
evaluation_id = executor.execute_evaluation(
testset_id="ts-001",
knowledge_base_id="kb-001",
testset=testset
)
# 4. 查看结果
summary = executor.get_evaluation_summary(evaluation_id)
print(f"Overall Score: {summary['overall_score']:.2f}/100")
```
### 运行示例
```bash
cd rag_evaluation
python example_phase2.py
```
输出示例:
```
============================================================
RAG Evaluation Framework - Phase 2 Example
============================================================
[1/6] Loading configuration...
✓ Configuration loaded
[2/6] Initializing database...
✓ Database schema initialized
[3/6] Generating testset...
✓ Testset generated: ts-abc123
- Questions: 5
- Saved to: ./data/testsets/ts-abc123.json
[4/6] Setting up RAG system...
✓ Mock RAG system initialized
- Retriever: MockRAGRetriever
- Generator: MockRAGGenerator
[5/6] Executing evaluation...
✓ Evaluation completed: eval-xyz789
[6/6] Evaluation Results
------------------------------------------------------------
📊 Overall Score: 75.50/100
📈 Retrieval Metrics:
- Context Recall: 0.800
- Context Precision: 0.750
- MRR: 0.850
- NDCG: 0.780
📝 Generation Metrics:
- Faithfulness: 0.720
- Answer Relevancy: 0.680
- Correctness: 0.650
📋 Statistics:
- Total Questions: 5
- Failed Questions: 0
✅ Phase 2 Example Completed Successfully!
```
## 任务完成情况
**Phase 2.1 RAG系统集成**: 4/4 ✅
- [x] RAG检索接口适配器
- [x] RAG生成接口适配器
- [x] 日志记录
- [x] Mock实现
**Phase 2.2 指标计算**: 2/4 ✅
- [x] 检索指标(4个)
- [x] 生成指标(3个)
- [ ] 并行化(Phase 6优化)
- [ ] 单元测试(Phase 6)
**Phase 2.3 评估流程编排**: 3/5 ✅
- [x] 评估任务调度器
- [x] 进度跟踪和状态管理
- [x] 错误处理和重试
- [ ] 结果缓存(Phase 6优化)
- [ ] 端到端测试(Phase 6)
**总体完成度**: 9/13 任务 (69%)
## 当前限制
1. **指标实现**: 当前使用简单的启发式算法,需要集成真实的RAGAS指标
2. **并行化**: 评估是串行执行,可以优化为并行
3. **缓存**: 暂未实现结果缓存机制
4. **测试**: 缺少单元测试和集成测试
## 下一步
### Phase 3: 报告生成
- 数据聚合和统计分析
- Executive Summary生成
- 详细指标分析
- 改进建议生成
- HTML/JSON报告输出
- 历史趋势分析
### 或者: 完善Phase 2
- 集成真实RAGAS指标
- 实现并行评估
- 添加结果缓存
- 编写测试套件
## 项目统计
**Phase 1 + Phase 2**:
- **代码文件**: 12个Python模块
- **配置文件**: 3个
- **文档文件**: 5个
- **示例文件**: 2个
- **数据库表**: 6张
- **代码行数**: ~2500行
- **已完成任务**: 19/72 (26%)
## 验证清单
- [x] RAG接口适配器实现
- [x] 7个指标计算实现
- [x] 评估执行器实现
- [x] 数据库集成
- [x] 状态管理
- [x] 错误处理
- [x] Phase 2示例
- [ ] 单元测试(Phase 6)
- [ ] 集成测试(Phase 6)
- [ ] 性能优化(Phase 6)
## 总结
Phase 2成功实现了完整的评估执行引擎,包括:
- 灵活的RAG系统集成
- 完整的7个评估指标
- 自动化的评估流程
- 数据库持久化存储
框架现在可以:
1. 生成测评集(Phase 1)
2. 执行RAG评估(Phase 2)
3. 存储评估结果
下一步可以进入Phase 3实现报告生成,或者先完善和测试Phase 1-2的功能。
@@ -0,0 +1,248 @@
# Phase 1-2 完善和测试总结
## 完成的改进
### 1. 修复的问题
#### 问题1: 模块导入错误
**问题**: `__init__.py`引用了不存在的`evaluator`模块
**修复**: 更新导入,只导出实际存在的模块
```python
# 修复前
from rag_evaluation.core.evaluator import Evaluator # 不存在
# 修复后
from rag_evaluation.testset.generator import TestsetGenerator
from rag_evaluation.storage.database import DatabaseManager
```
#### 问题2: Windows编码问题
**问题**: Unicode字符在Windows命令行显示错误
**修复**: 在测试脚本中设置UTF-8编码
```python
if sys.platform == 'win32':
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
```
#### 问题3: 模块路径问题
**问题**: 测试脚本无法导入rag_evaluation模块
**修复**: 添加父目录到sys.path
```python
sys.path.insert(0, str(Path(__file__).parent.parent))
```
### 2. 新增功能
#### 配置验证
为`TestsetConfig`添加了`validate()`方法:
- 验证`default_size`为正数
- 验证问题分布总和为1.0
- 验证采样率在0-1之间
#### 测试框架
创建了完整的测试脚本`test_framework.py`:
- Phase 1测试(6个测试用例)
- Phase 2测试(3个测试用例)
- 自动化测试流程
#### 安装脚本
创建了`setup.py`用于:
- 自动安装依赖
- 验证安装
- 提供下一步指导
### 3. 新增文件
```
rag_evaluation/
├── test_framework.py # 测试脚本
├── setup.py # 安装脚本
└── core/
└── config.py # 添加了validate()方法
```
## 测试覆盖
### Phase 1 测试用例
1. **配置加载测试**
- 默认配置创建
- 从YAML文件加载
- 配置参数验证
2. **文档加载测试**
- TextLoader功能
- MarkdownLoader功能
- 批量加载功能
- 文件大小获取
3. **采样和分块测试**
- 采样率计算(小/中/大文件)
- 文档分块功能
- 元数据保留
4. **测评集生成测试**
- 测评集生成
- 问题类型分布
- JSON保存
- JSON加载
- 数据一致性验证
5. **数据库操作测试**
- 连接测试(需要MySQL)
- Schema初始化
6. **工具函数测试**
- ID生成(唯一性)
- 业务流水号生成
- 系统流水号生成
- 时间格式化
- 文件大小计算
### Phase 2 测试用例
1. **RAG适配器测试**
- MockRAGRetriever功能
- MockRAGGenerator功能
- RAGEvaluationAdapter集成
- 时间测量
2. **指标计算测试**
- 7个指标计算
- MetricsCalculator集成
- 指标完整性验证
3. **评估执行器测试**
- 需要数据库连接
- 完整评估流程
## 使用指南
### 1. 安装依赖
```bash
cd rag_evaluation
python setup.py
```
### 2. 运行测试
```bash
python test_framework.py
```
### 3. 运行示例
```bash
# Phase 1示例
python example.py
# Phase 2示例
python example_phase2.py
```
## 测试结果
### 不需要依赖的测试
- ✓ 配置结构验证
- ✓ 文件路径处理
- ✓ ID生成逻辑
- ✓ 时间格式化
### 需要依赖的测试
- ⏳ 文档加载(需要langchain)
- ⏳ 测评集生成(需要ragas)
- ⏳ 数据库操作(需要pymysql + MySQL)
- ⏳ RAG评估(需要requests)
## 已知限制
### 1. 依赖要求
框架需要以下依赖才能完整运行:
```
ragas>=0.1.0
langchain>=0.1.0
pymysql>=1.1.0
pyyaml>=6.0
python-dotenv>=1.0.0
requests>=2.31.0
```
### 2. 数据库要求
- 需要MySQL 5.7+或8.0+
- 需要创建数据库: `rag_evaluation`
- 需要配置正确的连接信息
### 3. RAGAS集成
当前使用占位符实现,需要:
- 配置LLM API密钥
- 集成真实的RAGAS TestsetGenerator
- 集成真实的RAGAS指标计算
## 改进建议
### 短期改进
1. **添加单元测试**: 使用pytest编写正式的单元测试
2. **Mock数据库**: 使用sqlite或mock对象进行测试
3. **CI/CD集成**: 添加GitHub Actions自动测试
4. **文档完善**: 添加API文档和更多示例
### 中期改进
1. **真实RAGAS集成**: 替换占位符实现
2. **并行评估**: 实现多线程/多进程评估
3. **结果缓存**: 避免重复评估
4. **性能优化**: 优化大文件处理
### 长期改进
1. **Web界面**: 提供可视化界面
2. **实时监控**: 评估进度实时显示
3. **分布式评估**: 支持分布式执行
4. **插件系统**: 支持自定义指标和适配器
## 验证清单
- [x] 修复模块导入错误
- [x] 修复Windows编码问题
- [x] 添加配置验证
- [x] 创建测试框架
- [x] 创建安装脚本
- [x] 更新文档
- [ ] 添加单元测试(pytest)
- [ ] 集成真实RAGAS
- [ ] 性能测试
- [ ] 压力测试
## 下一步行动
### 选项1: 继续完善Phase 1-2
1. 安装依赖: `python setup.py`
2. 运行测试: `python test_framework.py`
3. 修复发现的问题
4. 添加更多测试用例
### 选项2: 开始Phase 3
1. 实现报告数据聚合
2. 实现HTML报告生成
3. 实现JSON报告生成
4. 实现改进建议生成
### 选项3: 集成真实RAGAS
1. 配置LLM API密钥
2. 集成RAGAS TestsetGenerator
3. 集成RAGAS指标计算
4. 测试真实评估流程
## 总结
Phase 1-2的完善工作已完成:
- ✅ 修复了关键bug
- ✅ 添加了配置验证
- ✅ 创建了测试框架
- ✅ 创建了安装脚本
- ✅ 改进了错误处理
框架现在更加健壮和易用,可以选择:
1. 继续完善和测试
2. 开始Phase 3开发
3. 集成真实RAGAS进行端到端测试