Initial commit
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
commit
4ecf7b351d
143 files changed
+24156
No files matched your search
@@ -0,0 +1,8 @@
|
||||
# RAG Evaluation Framework Environment Variables
|
||||
|
||||
# LLM API Keys
|
||||
ANTHROPIC_API_KEY=your_anthropic_api_key_here
|
||||
OPENAI_API_KEY=your_openai_api_key_here
|
||||
|
||||
# Database Configuration
|
||||
DB_PASSWORD=123456
|
||||
@@ -0,0 +1,8 @@
|
||||
# RAG Evaluation Framework Environment Variables
|
||||
|
||||
# LLM API Keys
|
||||
ANTHROPIC_API_KEY=your_anthropic_api_key_here
|
||||
OPENAI_API_KEY=your_openai_api_key_here
|
||||
|
||||
# Database Configuration
|
||||
DB_PASSWORD=your_database_password_here
|
||||
@@ -0,0 +1,158 @@
|
||||
# RAG Evaluation Framework
|
||||
|
||||
基于RAGAS的端到端RAG评估框架
|
||||
|
||||
## 功能特性
|
||||
|
||||
- **自动测评集生成**: 使用RAGAS从知识库自动生成评估问题
|
||||
- **多维度指标**: 检索指标(Recall, Precision, MRR, NDCG) + 生成指标(Faithfulness, Relevancy, Correctness)
|
||||
- **智能采样**: 大文件分层采样策略,控制评估成本
|
||||
- **评估报告**: HTML/JSON格式,包含汇总、详细分析、改进建议、历史趋势
|
||||
- **CI/CD集成**: 支持自动化评估和回归检测
|
||||
|
||||
## 项目结构
|
||||
|
||||
```
|
||||
rag_evaluation/
|
||||
├── core/ # 核心配置和评估器
|
||||
├── testset/ # 测评集生成
|
||||
├── evaluation/ # 评估执行引擎
|
||||
├── report/ # 报告生成
|
||||
├── storage/ # 数据存储(MySQL + JSON)
|
||||
├── api/ # REST API
|
||||
├── utils/ # 工具函数
|
||||
└── tests/ # 测试套件
|
||||
```
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 1. 安装依赖
|
||||
|
||||
```bash
|
||||
cd rag_evaluation
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
或使用安装脚本:
|
||||
```bash
|
||||
python setup.py
|
||||
```
|
||||
|
||||
### 2. 配置
|
||||
|
||||
复制并编辑配置文件:
|
||||
|
||||
```bash
|
||||
cp config.example.yaml config.yaml
|
||||
# 编辑 config.yaml 设置数据库连接和API密钥
|
||||
```
|
||||
|
||||
### 3. 运行示例
|
||||
|
||||
```bash
|
||||
# 方式1: 直接运行 (推荐)
|
||||
python example.py # Phase 1 - 测评集生成
|
||||
python example_phase2.py # Phase 2 - 评估执行
|
||||
|
||||
# 方式2: 使用run脚本
|
||||
python run.py example.py
|
||||
python run.py example_phase2.py
|
||||
|
||||
# 方式3: 运行测试
|
||||
python test_framework.py
|
||||
```
|
||||
|
||||
## 使用示例
|
||||
|
||||
### Phase 1: 测评集生成
|
||||
|
||||
```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", "/path/to/doc2.md"],
|
||||
test_size=15
|
||||
)
|
||||
|
||||
# 保存测评集
|
||||
file_path = generator.save_testset(testset)
|
||||
print(f"Testset saved to: {file_path}")
|
||||
```
|
||||
|
||||
### Phase 2: 评估执行
|
||||
|
||||
```python
|
||||
from rag_evaluation.evaluation import (
|
||||
MockRAGRetriever,
|
||||
MockRAGGenerator,
|
||||
RAGEvaluationAdapter,
|
||||
EvaluationExecutor
|
||||
)
|
||||
|
||||
# 设置RAG系统
|
||||
retriever = MockRAGRetriever()
|
||||
generator = MockRAGGenerator()
|
||||
rag_adapter = RAGEvaluationAdapter(retriever, generator)
|
||||
|
||||
# 执行评估
|
||||
executor = EvaluationExecutor(config, rag_adapter)
|
||||
evaluation_id = executor.execute_evaluation(
|
||||
testset_id=testset['id'],
|
||||
knowledge_base_id="kb-001",
|
||||
testset=testset
|
||||
)
|
||||
|
||||
# 查看结果
|
||||
summary = executor.get_evaluation_summary(evaluation_id)
|
||||
print(f"Overall Score: {summary['overall_score']:.2f}/100")
|
||||
```
|
||||
|
||||
## 开发状态
|
||||
|
||||
当前版本: v0.2.0 (Phase 2 完成)
|
||||
|
||||
**已完成**:
|
||||
- [x] Phase 1: 项目结构初始化
|
||||
- [x] Phase 1: 测评集生成
|
||||
- [x] Phase 2: 评估执行引擎
|
||||
- [ ] Phase 3: 报告生成 (待实施)
|
||||
- [ ] Phase 4: API服务 (待实施)
|
||||
- [ ] Phase 5: CI/CD集成 (待实施)
|
||||
|
||||
**功能统计**:
|
||||
- 7个评估指标 ✅
|
||||
- 智能采样策略 ✅
|
||||
- JSON持久化 ✅
|
||||
- MySQL数据库集成 ✅
|
||||
- Mock RAG系统 ✅
|
||||
|
||||
## 文档
|
||||
|
||||
详细文档请查看 [docs/](docs/) 目录:
|
||||
|
||||
### 使用指南
|
||||
- [快速开始](docs/guides/getting-started.md) - 5分钟快速上手
|
||||
- [运行指南](docs/guides/run-guide.md) - 运行示例和测试
|
||||
|
||||
### 阶段总结
|
||||
- [Phase 1总结](docs/summaries/PHASE1_SUMMARY.md) - 测评集生成
|
||||
- [Phase 2总结](docs/summaries/PHASE2_SUMMARY.md) - 评估执行引擎
|
||||
|
||||
### 测试文档
|
||||
- [测试总结](docs/testing/TESTING_SUMMARY.md) - 测试框架和用例
|
||||
|
||||
### 设计文档
|
||||
- [OpenSpec提案](../openspec/changes/add-rag-evaluation-framework/) - 完整的技术设计
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
@@ -0,0 +1,18 @@
|
||||
"""
|
||||
RAG Evaluation Framework
|
||||
|
||||
基于RAGAS的端到端RAG评估框架,提供:
|
||||
- 自动测评集生成
|
||||
- 多维度指标评估(检索+生成)
|
||||
- 评估报告生成
|
||||
- CI/CD集成支持
|
||||
"""
|
||||
|
||||
__version__ = "0.1.0"
|
||||
__author__ = "RAG Evaluation Team"
|
||||
|
||||
from rag_evaluation.core.config import Config
|
||||
from rag_evaluation.testset.generator import TestsetGenerator
|
||||
from rag_evaluation.storage.database import DatabaseManager
|
||||
|
||||
__all__ = ["Config", "TestsetGenerator", "DatabaseManager", "__version__"]
|
||||
Binary file not shown.
Binary file not shown.
Whitespace-only changes.
@@ -0,0 +1,61 @@
|
||||
# RAG Evaluation Framework Configuration
|
||||
|
||||
# LLM Configuration
|
||||
llm:
|
||||
# Generator LLM (for testset generation)
|
||||
generator_model: "claude-3-sonnet-20240229"
|
||||
generator_api_base: "https://api.anthropic.com"
|
||||
generator_api_key: "${ANTHROPIC_API_KEY}"
|
||||
|
||||
# Evaluator LLM (for metrics calculation)
|
||||
evaluator_model: "gpt-4"
|
||||
evaluator_api_base: "https://api.openai.com/v1"
|
||||
evaluator_api_key: "${OPENAI_API_KEY}"
|
||||
|
||||
# Common settings
|
||||
temperature: 0.7
|
||||
max_tokens: 2000
|
||||
|
||||
# Database Configuration
|
||||
database:
|
||||
host: "localhost"
|
||||
port: 3306
|
||||
database: "rag_evaluation"
|
||||
user: "root"
|
||||
password: "${DB_PASSWORD}"
|
||||
charset: "utf8mb4"
|
||||
|
||||
# Testset Generation Configuration
|
||||
testset:
|
||||
default_size: 15
|
||||
question_distribution:
|
||||
simple: 0.4
|
||||
reasoning: 0.4
|
||||
multi_context: 0.2
|
||||
sampling_strategy:
|
||||
small_file_threshold_mb: 1.0
|
||||
medium_file_threshold_mb: 10.0
|
||||
small_file_sampling_rate: 1.0
|
||||
medium_file_sampling_rate: 0.4
|
||||
large_file_sampling_rate: 0.15
|
||||
|
||||
# Evaluation Configuration
|
||||
evaluation:
|
||||
parallel_workers: 5
|
||||
timeout_seconds: 300
|
||||
retry_attempts: 3
|
||||
cache_enabled: true
|
||||
|
||||
# Metrics Thresholds
|
||||
metrics:
|
||||
context_recall_threshold: 0.7
|
||||
context_precision_threshold: 0.7
|
||||
faithfulness_threshold: 0.8
|
||||
answer_relevancy_threshold: 0.7
|
||||
correctness_threshold: 0.7
|
||||
|
||||
# Storage Configuration
|
||||
storage:
|
||||
testset_dir: "./data/testsets"
|
||||
report_dir: "./data/reports"
|
||||
cache_dir: "./data/cache"
|
||||
@@ -0,0 +1,61 @@
|
||||
# RAG Evaluation Framework Configuration
|
||||
|
||||
# LLM Configuration
|
||||
llm:
|
||||
# Generator LLM (for testset generation)
|
||||
generator_model: "glm-4.7"
|
||||
generator_api_base: "https://open.bigmodel.cn/api/paas/v4/"
|
||||
generator_api_key: "5495b0bc87464c2a88ef371381902b70.pZQIJHK6TUDufE7V"
|
||||
|
||||
# Evaluator LLM (for metrics calculation)
|
||||
evaluator_model: "glm-4.7"
|
||||
evaluator_api_base: "https://open.bigmodel.cn/api/paas/v4/"
|
||||
evaluator_api_key: "5495b0bc87464c2a88ef371381902b70.pZQIJHK6TUDufE7V"
|
||||
|
||||
# Common settings
|
||||
temperature: 0.7
|
||||
max_tokens: 2000
|
||||
|
||||
# Database Configuration
|
||||
database:
|
||||
host: "localhost"
|
||||
port: 3306
|
||||
database: "rag_evaluation"
|
||||
user: "root"
|
||||
password: "123456"
|
||||
charset: "utf8mb4"
|
||||
|
||||
# Testset Generation Configuration
|
||||
testset:
|
||||
default_size: 15
|
||||
question_distribution:
|
||||
simple: 0.4
|
||||
reasoning: 0.4
|
||||
multi_context: 0.2
|
||||
sampling_strategy:
|
||||
small_file_threshold_mb: 1.0
|
||||
medium_file_threshold_mb: 10.0
|
||||
small_file_sampling_rate: 1.0
|
||||
medium_file_sampling_rate: 0.4
|
||||
large_file_sampling_rate: 0.15
|
||||
|
||||
# Evaluation Configuration
|
||||
evaluation:
|
||||
parallel_workers: 5
|
||||
timeout_seconds: 300
|
||||
retry_attempts: 3
|
||||
cache_enabled: true
|
||||
|
||||
# Metrics Thresholds
|
||||
metrics:
|
||||
context_recall_threshold: 0.7
|
||||
context_precision_threshold: 0.7
|
||||
faithfulness_threshold: 0.8
|
||||
answer_relevancy_threshold: 0.7
|
||||
correctness_threshold: 0.7
|
||||
|
||||
# Storage Configuration
|
||||
storage:
|
||||
testset_dir: "./data/testsets"
|
||||
report_dir: "./data/reports"
|
||||
cache_dir: "./data/cache"
|
||||
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,160 @@
|
||||
"""
|
||||
Core configuration module for RAG Evaluation Framework
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Dict, Optional
|
||||
import yaml
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@dataclass
|
||||
class LLMConfig:
|
||||
"""LLM configuration"""
|
||||
generator_model: str = "claude-3-sonnet-20240229"
|
||||
generator_api_base: Optional[str] = None
|
||||
generator_api_key: Optional[str] = None
|
||||
|
||||
evaluator_model: str = "gpt-4"
|
||||
evaluator_api_base: Optional[str] = None
|
||||
evaluator_api_key: Optional[str] = None
|
||||
|
||||
temperature: float = 0.7
|
||||
max_tokens: int = 2000
|
||||
|
||||
|
||||
@dataclass
|
||||
class DatabaseConfig:
|
||||
"""Database configuration"""
|
||||
host: str = "localhost"
|
||||
port: int = 3306
|
||||
database: str = "rag_evaluation"
|
||||
user: str = "root"
|
||||
password: str = ""
|
||||
charset: str = "utf8mb4"
|
||||
pool_size: int = 10
|
||||
max_overflow: int = 20
|
||||
|
||||
|
||||
@dataclass
|
||||
class TestsetConfig:
|
||||
"""Testset generation configuration"""
|
||||
default_size: int = 15
|
||||
question_distribution: Dict[str, float] = field(default_factory=lambda: {
|
||||
"simple": 0.4,
|
||||
"reasoning": 0.4,
|
||||
"multi_context": 0.2
|
||||
})
|
||||
sampling_strategy: Dict[str, float] = field(default_factory=lambda: {
|
||||
"small_file_threshold_mb": 1.0,
|
||||
"medium_file_threshold_mb": 10.0,
|
||||
"small_file_sampling_rate": 1.0,
|
||||
"medium_file_sampling_rate": 0.4,
|
||||
"large_file_sampling_rate": 0.15
|
||||
})
|
||||
|
||||
def validate(self):
|
||||
"""Validate testset configuration"""
|
||||
# Validate default_size
|
||||
if self.default_size <= 0:
|
||||
raise ValueError("default_size must be positive")
|
||||
|
||||
# Validate question distribution
|
||||
dist_sum = sum(self.question_distribution.values())
|
||||
if not (0.99 <= dist_sum <= 1.01): # Allow small floating point errors
|
||||
raise ValueError(f"question_distribution must sum to 1.0, got {dist_sum}")
|
||||
|
||||
# Validate sampling rates
|
||||
for key in ['small_file_sampling_rate', 'medium_file_sampling_rate', 'large_file_sampling_rate']:
|
||||
rate = self.sampling_strategy.get(key, 0)
|
||||
if not (0 <= rate <= 1.0):
|
||||
raise ValueError(f"{key} must be between 0 and 1, got {rate}")
|
||||
|
||||
|
||||
@dataclass
|
||||
class EvaluationConfig:
|
||||
"""Evaluation execution configuration"""
|
||||
parallel_workers: int = 5
|
||||
timeout_seconds: int = 300
|
||||
retry_attempts: int = 3
|
||||
cache_enabled: bool = True
|
||||
|
||||
|
||||
@dataclass
|
||||
class MetricsConfig:
|
||||
"""Metrics thresholds configuration"""
|
||||
context_recall_threshold: float = 0.7
|
||||
context_precision_threshold: float = 0.7
|
||||
faithfulness_threshold: float = 0.8
|
||||
answer_relevancy_threshold: float = 0.7
|
||||
correctness_threshold: float = 0.7
|
||||
|
||||
|
||||
@dataclass
|
||||
class StorageConfig:
|
||||
"""Storage configuration"""
|
||||
testset_dir: str = "./data/testsets"
|
||||
report_dir: str = "./data/reports"
|
||||
cache_dir: str = "./data/cache"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Config:
|
||||
"""Main configuration class"""
|
||||
llm: LLMConfig = field(default_factory=LLMConfig)
|
||||
database: DatabaseConfig = field(default_factory=DatabaseConfig)
|
||||
testset: TestsetConfig = field(default_factory=TestsetConfig)
|
||||
evaluation: EvaluationConfig = field(default_factory=EvaluationConfig)
|
||||
metrics: MetricsConfig = field(default_factory=MetricsConfig)
|
||||
storage: StorageConfig = field(default_factory=StorageConfig)
|
||||
|
||||
@classmethod
|
||||
def from_file(cls, config_path: str) -> "Config":
|
||||
"""Load configuration from YAML file"""
|
||||
path = Path(config_path)
|
||||
if not path.exists():
|
||||
raise FileNotFoundError(f"Config file not found: {config_path}")
|
||||
|
||||
with open(path, 'r', encoding='utf-8') as f:
|
||||
config_dict = yaml.safe_load(f)
|
||||
|
||||
return cls.from_dict(config_dict)
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, config_dict: Dict) -> "Config":
|
||||
"""Create Config from dictionary"""
|
||||
llm_config = LLMConfig(**config_dict.get('llm', {}))
|
||||
db_config = DatabaseConfig(**config_dict.get('database', {}))
|
||||
print(config_dict.get('database', {}))
|
||||
testset_config = TestsetConfig(**config_dict.get('testset', {}))
|
||||
eval_config = EvaluationConfig(**config_dict.get('evaluation', {}))
|
||||
metrics_config = MetricsConfig(**config_dict.get('metrics', {}))
|
||||
storage_config = StorageConfig(**config_dict.get('storage', {}))
|
||||
|
||||
return cls(
|
||||
llm=llm_config,
|
||||
database=db_config,
|
||||
testset=testset_config,
|
||||
evaluation=eval_config,
|
||||
metrics=metrics_config,
|
||||
storage=storage_config
|
||||
)
|
||||
|
||||
def to_dict(self) -> Dict:
|
||||
"""Convert Config to dictionary"""
|
||||
return {
|
||||
'llm': self.llm.__dict__,
|
||||
'database': self.database.__dict__,
|
||||
'testset': self.testset.__dict__,
|
||||
'evaluation': self.evaluation.__dict__,
|
||||
'metrics': self.metrics.__dict__,
|
||||
'storage': self.storage.__dict__
|
||||
}
|
||||
|
||||
def save(self, config_path: str):
|
||||
"""Save configuration to YAML file"""
|
||||
path = Path(config_path)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
with open(path, 'w', encoding='utf-8') as f:
|
||||
yaml.dump(self.to_dict(), f, default_flow_style=False, allow_unicode=True)
|
||||
@@ -0,0 +1,19 @@
|
||||
|
||||
# RAG System Guide
|
||||
|
||||
## What is RAG?
|
||||
RAG (Retrieval-Augmented Generation) combines information retrieval with text generation.
|
||||
It retrieves relevant documents and uses them to generate accurate answers.
|
||||
|
||||
## Key Components
|
||||
1. Retriever: Finds relevant documents from a knowledge base
|
||||
2. Generator: Creates answers based on retrieved documents
|
||||
3. Knowledge Base: Collection of documents to search
|
||||
|
||||
## Evaluation Metrics
|
||||
- Context Recall: How well relevant documents are retrieved
|
||||
- Context Precision: How precise the retrieved documents are
|
||||
- Faithfulness: Whether answers are faithful to the context
|
||||
- Answer Relevancy: How relevant answers are to questions
|
||||
- Correctness: How correct answers are compared to ground truth
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
|
||||
# Sample Knowledge Base Document
|
||||
|
||||
This is a sample document for RAG evaluation.
|
||||
|
||||
## Section 1: Introduction
|
||||
RAG (Retrieval-Augmented Generation) systems combine retrieval and generation
|
||||
to provide accurate and contextual answers.
|
||||
|
||||
## Section 2: Evaluation
|
||||
Evaluating RAG systems requires measuring both retrieval quality and generation quality.
|
||||
|
||||
Key metrics include:
|
||||
- Context Recall: How well the system retrieves relevant context
|
||||
- Context Precision: How precise the retrieved context is
|
||||
- Faithfulness: Whether the generated answer is faithful to the context
|
||||
- Answer Relevancy: How relevant the answer is to the question
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
# Test Markdown
|
||||
|
||||
This is a markdown test document.
|
||||
@@ -0,0 +1 @@
|
||||
This is a test document for RAG evaluation.
|
||||
@@ -0,0 +1,206 @@
|
||||
{
|
||||
"id": "0aad10205c0b38604989a93045530799",
|
||||
"biz_seq": "TS2026011515243526FBF665",
|
||||
"sys_seq": "TS20260115152435A27DFA77",
|
||||
"knowledge_base_id": "kb-example-001",
|
||||
"name": "Example Testset",
|
||||
"created_at": "2026-01-15 15:24:35",
|
||||
"metadata": {
|
||||
"test_size": 15,
|
||||
"question_distribution": {
|
||||
"simple": 0.4,
|
||||
"reasoning": 0.4,
|
||||
"multi_context": 0.2
|
||||
},
|
||||
"sampling_strategy": {
|
||||
"small_file_threshold_mb": 1.0,
|
||||
"medium_file_threshold_mb": 10.0,
|
||||
"small_file_sampling_rate": 1.0,
|
||||
"medium_file_sampling_rate": 0.4,
|
||||
"large_file_sampling_rate": 0.15
|
||||
},
|
||||
"document_count": 1
|
||||
},
|
||||
"questions": [
|
||||
{
|
||||
"index": 0,
|
||||
"question": "Placeholder question 1",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 1",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 1,
|
||||
"question": "Placeholder question 2",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 2",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 2,
|
||||
"question": "Placeholder question 3",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 3",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 3,
|
||||
"question": "Placeholder question 4",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 4",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 4,
|
||||
"question": "Placeholder question 5",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 5",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 5,
|
||||
"question": "Placeholder question 6",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 6",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 6,
|
||||
"question": "Placeholder question 7",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 7",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 7,
|
||||
"question": "Placeholder question 8",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 8",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 8,
|
||||
"question": "Placeholder question 9",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 9",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 9,
|
||||
"question": "Placeholder question 10",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 10",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 10,
|
||||
"question": "Placeholder question 11",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 11",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 11,
|
||||
"question": "Placeholder question 12",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 12",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 12,
|
||||
"question": "Placeholder question 13",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 13",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 13,
|
||||
"question": "Placeholder question 14",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 14",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 14,
|
||||
"question": "Placeholder question 15",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 15",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
{
|
||||
"id": "0fda118547907d5e8477094c29dd4d82",
|
||||
"biz_seq": "TS20260115145109EA32C343",
|
||||
"sys_seq": "TS202601151451097F927305",
|
||||
"knowledge_base_id": "test-kb-001",
|
||||
"name": "Test Testset",
|
||||
"created_at": "2026-01-15 14:51:09",
|
||||
"metadata": {
|
||||
"test_size": 5,
|
||||
"question_distribution": {
|
||||
"simple": 0.4,
|
||||
"reasoning": 0.4,
|
||||
"multi_context": 0.2
|
||||
},
|
||||
"sampling_strategy": {
|
||||
"small_file_threshold_mb": 1.0,
|
||||
"medium_file_threshold_mb": 10.0,
|
||||
"small_file_sampling_rate": 1.0,
|
||||
"medium_file_sampling_rate": 0.4,
|
||||
"large_file_sampling_rate": 0.15
|
||||
},
|
||||
"document_count": 2
|
||||
},
|
||||
"questions": [
|
||||
{
|
||||
"index": 0,
|
||||
"question": "Placeholder question 1",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 1",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 1,
|
||||
"question": "Placeholder question 2",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 2",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 2,
|
||||
"question": "Placeholder question 3",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 3",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 3,
|
||||
"question": "Placeholder question 4",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 4",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 4,
|
||||
"question": "Placeholder question 5",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 5",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
{
|
||||
"id": "11769504dfe2cc1f24a119b460bdbb4c",
|
||||
"biz_seq": "TS2026011515225968AF592A",
|
||||
"sys_seq": "TS20260115152259C86CA735",
|
||||
"knowledge_base_id": "kb-example-001",
|
||||
"name": "Example Testset",
|
||||
"created_at": "2026-01-15 15:22:59",
|
||||
"metadata": {
|
||||
"test_size": 15,
|
||||
"question_distribution": {
|
||||
"simple": 0.4,
|
||||
"reasoning": 0.4,
|
||||
"multi_context": 0.2
|
||||
},
|
||||
"sampling_strategy": {
|
||||
"small_file_threshold_mb": 1.0,
|
||||
"medium_file_threshold_mb": 10.0,
|
||||
"small_file_sampling_rate": 1.0,
|
||||
"medium_file_sampling_rate": 0.4,
|
||||
"large_file_sampling_rate": 0.15
|
||||
},
|
||||
"document_count": 1
|
||||
},
|
||||
"questions": [
|
||||
{
|
||||
"index": 0,
|
||||
"question": "Placeholder question 1",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 1",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 1,
|
||||
"question": "Placeholder question 2",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 2",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 2,
|
||||
"question": "Placeholder question 3",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 3",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 3,
|
||||
"question": "Placeholder question 4",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 4",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 4,
|
||||
"question": "Placeholder question 5",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 5",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 5,
|
||||
"question": "Placeholder question 6",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 6",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 6,
|
||||
"question": "Placeholder question 7",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 7",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 7,
|
||||
"question": "Placeholder question 8",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 8",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 8,
|
||||
"question": "Placeholder question 9",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 9",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 9,
|
||||
"question": "Placeholder question 10",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 10",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 10,
|
||||
"question": "Placeholder question 11",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 11",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 11,
|
||||
"question": "Placeholder question 12",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 12",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 12,
|
||||
"question": "Placeholder question 13",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 13",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 13,
|
||||
"question": "Placeholder question 14",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 14",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 14,
|
||||
"question": "Placeholder question 15",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 15",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
{
|
||||
"id": "54c370578e100cf84424cbba1ce42204",
|
||||
"biz_seq": "TS20260115152450129036D8",
|
||||
"sys_seq": "TS20260115152450F914CC4E",
|
||||
"knowledge_base_id": "kb-example-001",
|
||||
"name": "Example Testset",
|
||||
"created_at": "2026-01-15 15:24:50",
|
||||
"metadata": {
|
||||
"test_size": 15,
|
||||
"question_distribution": {
|
||||
"simple": 0.4,
|
||||
"reasoning": 0.4,
|
||||
"multi_context": 0.2
|
||||
},
|
||||
"sampling_strategy": {
|
||||
"small_file_threshold_mb": 1.0,
|
||||
"medium_file_threshold_mb": 10.0,
|
||||
"small_file_sampling_rate": 1.0,
|
||||
"medium_file_sampling_rate": 0.4,
|
||||
"large_file_sampling_rate": 0.15
|
||||
},
|
||||
"document_count": 1
|
||||
},
|
||||
"questions": [
|
||||
{
|
||||
"index": 0,
|
||||
"question": "Placeholder question 1",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 1",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 1,
|
||||
"question": "Placeholder question 2",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 2",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 2,
|
||||
"question": "Placeholder question 3",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 3",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 3,
|
||||
"question": "Placeholder question 4",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 4",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 4,
|
||||
"question": "Placeholder question 5",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 5",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 5,
|
||||
"question": "Placeholder question 6",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 6",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 6,
|
||||
"question": "Placeholder question 7",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 7",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 7,
|
||||
"question": "Placeholder question 8",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 8",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 8,
|
||||
"question": "Placeholder question 9",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 9",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 9,
|
||||
"question": "Placeholder question 10",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 10",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 10,
|
||||
"question": "Placeholder question 11",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 11",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 11,
|
||||
"question": "Placeholder question 12",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 12",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 12,
|
||||
"question": "Placeholder question 13",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 13",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 13,
|
||||
"question": "Placeholder question 14",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 14",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 14,
|
||||
"question": "Placeholder question 15",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 15",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
{
|
||||
"id": "5524f4cd11a16b395d0ea11a1931a14c",
|
||||
"biz_seq": "TS202601151530487930FA7E",
|
||||
"sys_seq": "TS20260115153048728881CE",
|
||||
"knowledge_base_id": "kb-example-001",
|
||||
"name": "Example Testset",
|
||||
"created_at": "2026-01-15 15:30:48",
|
||||
"metadata": {
|
||||
"test_size": 15,
|
||||
"question_distribution": {
|
||||
"simple": 0.4,
|
||||
"reasoning": 0.4,
|
||||
"multi_context": 0.2
|
||||
},
|
||||
"sampling_strategy": {
|
||||
"small_file_threshold_mb": 1.0,
|
||||
"medium_file_threshold_mb": 10.0,
|
||||
"small_file_sampling_rate": 1.0,
|
||||
"medium_file_sampling_rate": 0.4,
|
||||
"large_file_sampling_rate": 0.15
|
||||
},
|
||||
"document_count": 1
|
||||
},
|
||||
"questions": [
|
||||
{
|
||||
"index": 0,
|
||||
"question": "Placeholder question 1",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 1",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 1,
|
||||
"question": "Placeholder question 2",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 2",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 2,
|
||||
"question": "Placeholder question 3",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 3",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 3,
|
||||
"question": "Placeholder question 4",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 4",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 4,
|
||||
"question": "Placeholder question 5",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 5",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 5,
|
||||
"question": "Placeholder question 6",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 6",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 6,
|
||||
"question": "Placeholder question 7",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 7",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 7,
|
||||
"question": "Placeholder question 8",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 8",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 8,
|
||||
"question": "Placeholder question 9",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 9",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 9,
|
||||
"question": "Placeholder question 10",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 10",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 10,
|
||||
"question": "Placeholder question 11",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 11",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 11,
|
||||
"question": "Placeholder question 12",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 12",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 12,
|
||||
"question": "Placeholder question 13",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 13",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 13,
|
||||
"question": "Placeholder question 14",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 14",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 14,
|
||||
"question": "Placeholder question 15",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 15",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
{
|
||||
"id": "57e6ea45fb99ed829617e8184d8b7941",
|
||||
"biz_seq": "TS20260115152244701424C2",
|
||||
"sys_seq": "TS20260115152244878A831B",
|
||||
"knowledge_base_id": "kb-example-001",
|
||||
"name": "Example Testset",
|
||||
"created_at": "2026-01-15 15:22:44",
|
||||
"metadata": {
|
||||
"test_size": 15,
|
||||
"question_distribution": {
|
||||
"simple": 0.4,
|
||||
"reasoning": 0.4,
|
||||
"multi_context": 0.2
|
||||
},
|
||||
"sampling_strategy": {
|
||||
"small_file_threshold_mb": 1.0,
|
||||
"medium_file_threshold_mb": 10.0,
|
||||
"small_file_sampling_rate": 1.0,
|
||||
"medium_file_sampling_rate": 0.4,
|
||||
"large_file_sampling_rate": 0.15
|
||||
},
|
||||
"document_count": 1
|
||||
},
|
||||
"questions": [
|
||||
{
|
||||
"index": 0,
|
||||
"question": "Placeholder question 1",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 1",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 1,
|
||||
"question": "Placeholder question 2",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 2",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 2,
|
||||
"question": "Placeholder question 3",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 3",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 3,
|
||||
"question": "Placeholder question 4",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 4",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 4,
|
||||
"question": "Placeholder question 5",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 5",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 5,
|
||||
"question": "Placeholder question 6",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 6",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 6,
|
||||
"question": "Placeholder question 7",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 7",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 7,
|
||||
"question": "Placeholder question 8",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 8",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 8,
|
||||
"question": "Placeholder question 9",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 9",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 9,
|
||||
"question": "Placeholder question 10",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 10",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 10,
|
||||
"question": "Placeholder question 11",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 11",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 11,
|
||||
"question": "Placeholder question 12",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 12",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 12,
|
||||
"question": "Placeholder question 13",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 13",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 13,
|
||||
"question": "Placeholder question 14",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 14",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 14,
|
||||
"question": "Placeholder question 15",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 15",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
{
|
||||
"id": "5a5d6b5aaa1491c8395ad23cc0c317e6",
|
||||
"biz_seq": "TS2026011515311457D636D9",
|
||||
"sys_seq": "TS20260115153114D9777811",
|
||||
"knowledge_base_id": "kb-phase2-demo",
|
||||
"name": "Phase 2 Demo Testset",
|
||||
"created_at": "2026-01-15 15:31:14",
|
||||
"metadata": {
|
||||
"test_size": 5,
|
||||
"question_distribution": {
|
||||
"simple": 0.4,
|
||||
"reasoning": 0.4,
|
||||
"multi_context": 0.2
|
||||
},
|
||||
"sampling_strategy": {
|
||||
"small_file_threshold_mb": 1.0,
|
||||
"medium_file_threshold_mb": 10.0,
|
||||
"small_file_sampling_rate": 1.0,
|
||||
"medium_file_sampling_rate": 0.4,
|
||||
"large_file_sampling_rate": 0.15
|
||||
},
|
||||
"document_count": 2
|
||||
},
|
||||
"questions": [
|
||||
{
|
||||
"index": 0,
|
||||
"question": "Placeholder question 1",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 1",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 1,
|
||||
"question": "Placeholder question 2",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 2",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 2,
|
||||
"question": "Placeholder question 3",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 3",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 3,
|
||||
"question": "Placeholder question 4",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 4",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 4,
|
||||
"question": "Placeholder question 5",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 5",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
{
|
||||
"id": "5bbee315d60baddf2eedcd93cc77e41e",
|
||||
"biz_seq": "TS20260115152918C6B060D1",
|
||||
"sys_seq": "TS202601151529184FE6C773",
|
||||
"knowledge_base_id": "kb-example-001",
|
||||
"name": "Example Testset",
|
||||
"created_at": "2026-01-15 15:29:18",
|
||||
"metadata": {
|
||||
"test_size": 15,
|
||||
"question_distribution": {
|
||||
"simple": 0.4,
|
||||
"reasoning": 0.4,
|
||||
"multi_context": 0.2
|
||||
},
|
||||
"sampling_strategy": {
|
||||
"small_file_threshold_mb": 1.0,
|
||||
"medium_file_threshold_mb": 10.0,
|
||||
"small_file_sampling_rate": 1.0,
|
||||
"medium_file_sampling_rate": 0.4,
|
||||
"large_file_sampling_rate": 0.15
|
||||
},
|
||||
"document_count": 1
|
||||
},
|
||||
"questions": [
|
||||
{
|
||||
"index": 0,
|
||||
"question": "Placeholder question 1",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 1",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 1,
|
||||
"question": "Placeholder question 2",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 2",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 2,
|
||||
"question": "Placeholder question 3",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 3",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 3,
|
||||
"question": "Placeholder question 4",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 4",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 4,
|
||||
"question": "Placeholder question 5",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 5",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 5,
|
||||
"question": "Placeholder question 6",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 6",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 6,
|
||||
"question": "Placeholder question 7",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 7",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 7,
|
||||
"question": "Placeholder question 8",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 8",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 8,
|
||||
"question": "Placeholder question 9",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 9",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 9,
|
||||
"question": "Placeholder question 10",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 10",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 10,
|
||||
"question": "Placeholder question 11",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 11",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 11,
|
||||
"question": "Placeholder question 12",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 12",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 12,
|
||||
"question": "Placeholder question 13",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 13",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 13,
|
||||
"question": "Placeholder question 14",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 14",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 14,
|
||||
"question": "Placeholder question 15",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 15",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
{
|
||||
"id": "614c00fe6d179fb5111424b93499298e",
|
||||
"biz_seq": "TS2026011514520327BA13CD",
|
||||
"sys_seq": "TS20260115145203FD3C9F14",
|
||||
"knowledge_base_id": "test-kb-001",
|
||||
"name": "Test Testset",
|
||||
"created_at": "2026-01-15 14:52:03",
|
||||
"metadata": {
|
||||
"test_size": 5,
|
||||
"question_distribution": {
|
||||
"simple": 0.4,
|
||||
"reasoning": 0.4,
|
||||
"multi_context": 0.2
|
||||
},
|
||||
"sampling_strategy": {
|
||||
"small_file_threshold_mb": 1.0,
|
||||
"medium_file_threshold_mb": 10.0,
|
||||
"small_file_sampling_rate": 1.0,
|
||||
"medium_file_sampling_rate": 0.4,
|
||||
"large_file_sampling_rate": 0.15
|
||||
},
|
||||
"document_count": 2
|
||||
},
|
||||
"questions": [
|
||||
{
|
||||
"index": 0,
|
||||
"question": "Placeholder question 1",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 1",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 1,
|
||||
"question": "Placeholder question 2",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 2",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 2,
|
||||
"question": "Placeholder question 3",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 3",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 3,
|
||||
"question": "Placeholder question 4",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 4",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 4,
|
||||
"question": "Placeholder question 5",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 5",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
{
|
||||
"id": "6262dad9c45f16969ebcda4128661610",
|
||||
"biz_seq": "TS20260115152124E8537E6E",
|
||||
"sys_seq": "TS202601151521245A738E69",
|
||||
"knowledge_base_id": "kb-example-001",
|
||||
"name": "Example Testset",
|
||||
"created_at": "2026-01-15 15:21:24",
|
||||
"metadata": {
|
||||
"test_size": 15,
|
||||
"question_distribution": {
|
||||
"simple": 0.4,
|
||||
"reasoning": 0.4,
|
||||
"multi_context": 0.2
|
||||
},
|
||||
"sampling_strategy": {
|
||||
"small_file_threshold_mb": 1.0,
|
||||
"medium_file_threshold_mb": 10.0,
|
||||
"small_file_sampling_rate": 1.0,
|
||||
"medium_file_sampling_rate": 0.4,
|
||||
"large_file_sampling_rate": 0.15
|
||||
},
|
||||
"document_count": 1
|
||||
},
|
||||
"questions": [
|
||||
{
|
||||
"index": 0,
|
||||
"question": "Placeholder question 1",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 1",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 1,
|
||||
"question": "Placeholder question 2",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 2",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 2,
|
||||
"question": "Placeholder question 3",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 3",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 3,
|
||||
"question": "Placeholder question 4",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 4",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 4,
|
||||
"question": "Placeholder question 5",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 5",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 5,
|
||||
"question": "Placeholder question 6",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 6",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 6,
|
||||
"question": "Placeholder question 7",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 7",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 7,
|
||||
"question": "Placeholder question 8",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 8",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 8,
|
||||
"question": "Placeholder question 9",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 9",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 9,
|
||||
"question": "Placeholder question 10",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 10",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 10,
|
||||
"question": "Placeholder question 11",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 11",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 11,
|
||||
"question": "Placeholder question 12",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 12",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 12,
|
||||
"question": "Placeholder question 13",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 13",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 13,
|
||||
"question": "Placeholder question 14",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 14",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 14,
|
||||
"question": "Placeholder question 15",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 15",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
{
|
||||
"id": "8102ec99405cdb0c284a0392f4c45104",
|
||||
"biz_seq": "TS202601151525194C732351",
|
||||
"sys_seq": "TS20260115152519B8F2C984",
|
||||
"knowledge_base_id": "kb-example-001",
|
||||
"name": "Example Testset",
|
||||
"created_at": "2026-01-15 15:25:19",
|
||||
"metadata": {
|
||||
"test_size": 15,
|
||||
"question_distribution": {
|
||||
"simple": 0.4,
|
||||
"reasoning": 0.4,
|
||||
"multi_context": 0.2
|
||||
},
|
||||
"sampling_strategy": {
|
||||
"small_file_threshold_mb": 1.0,
|
||||
"medium_file_threshold_mb": 10.0,
|
||||
"small_file_sampling_rate": 1.0,
|
||||
"medium_file_sampling_rate": 0.4,
|
||||
"large_file_sampling_rate": 0.15
|
||||
},
|
||||
"document_count": 1
|
||||
},
|
||||
"questions": [
|
||||
{
|
||||
"index": 0,
|
||||
"question": "Placeholder question 1",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 1",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 1,
|
||||
"question": "Placeholder question 2",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 2",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 2,
|
||||
"question": "Placeholder question 3",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 3",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 3,
|
||||
"question": "Placeholder question 4",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 4",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 4,
|
||||
"question": "Placeholder question 5",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 5",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 5,
|
||||
"question": "Placeholder question 6",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 6",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 6,
|
||||
"question": "Placeholder question 7",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 7",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 7,
|
||||
"question": "Placeholder question 8",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 8",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 8,
|
||||
"question": "Placeholder question 9",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 9",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 9,
|
||||
"question": "Placeholder question 10",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 10",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 10,
|
||||
"question": "Placeholder question 11",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 11",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 11,
|
||||
"question": "Placeholder question 12",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 12",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 12,
|
||||
"question": "Placeholder question 13",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 13",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 13,
|
||||
"question": "Placeholder question 14",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 14",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 14,
|
||||
"question": "Placeholder question 15",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 15",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
{
|
||||
"id": "a3acd67be0d2b286ef03ad8b84e47aac",
|
||||
"biz_seq": "TS20260115145433651BE248",
|
||||
"sys_seq": "TS202601151454339BD999F9",
|
||||
"knowledge_base_id": "test-kb-001",
|
||||
"name": "Test Testset",
|
||||
"created_at": "2026-01-15 14:54:33",
|
||||
"metadata": {
|
||||
"test_size": 5,
|
||||
"question_distribution": {
|
||||
"simple": 0.4,
|
||||
"reasoning": 0.4,
|
||||
"multi_context": 0.2
|
||||
},
|
||||
"sampling_strategy": {
|
||||
"small_file_threshold_mb": 1.0,
|
||||
"medium_file_threshold_mb": 10.0,
|
||||
"small_file_sampling_rate": 1.0,
|
||||
"medium_file_sampling_rate": 0.4,
|
||||
"large_file_sampling_rate": 0.15
|
||||
},
|
||||
"document_count": 2
|
||||
},
|
||||
"questions": [
|
||||
{
|
||||
"index": 0,
|
||||
"question": "Placeholder question 1",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 1",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 1,
|
||||
"question": "Placeholder question 2",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 2",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 2,
|
||||
"question": "Placeholder question 3",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 3",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 3,
|
||||
"question": "Placeholder question 4",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 4",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 4,
|
||||
"question": "Placeholder question 5",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 5",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
{
|
||||
"id": "a5640bfb1afaffa1844d2959b8ca52c9",
|
||||
"biz_seq": "TS20260115152936DDA47FD5",
|
||||
"sys_seq": "TS202601151529363D8B409E",
|
||||
"knowledge_base_id": "kb-example-001",
|
||||
"name": "Example Testset",
|
||||
"created_at": "2026-01-15 15:29:36",
|
||||
"metadata": {
|
||||
"test_size": 15,
|
||||
"question_distribution": {
|
||||
"simple": 0.4,
|
||||
"reasoning": 0.4,
|
||||
"multi_context": 0.2
|
||||
},
|
||||
"sampling_strategy": {
|
||||
"small_file_threshold_mb": 1.0,
|
||||
"medium_file_threshold_mb": 10.0,
|
||||
"small_file_sampling_rate": 1.0,
|
||||
"medium_file_sampling_rate": 0.4,
|
||||
"large_file_sampling_rate": 0.15
|
||||
},
|
||||
"document_count": 1
|
||||
},
|
||||
"questions": [
|
||||
{
|
||||
"index": 0,
|
||||
"question": "Placeholder question 1",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 1",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 1,
|
||||
"question": "Placeholder question 2",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 2",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 2,
|
||||
"question": "Placeholder question 3",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 3",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 3,
|
||||
"question": "Placeholder question 4",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 4",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 4,
|
||||
"question": "Placeholder question 5",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 5",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 5,
|
||||
"question": "Placeholder question 6",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 6",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 6,
|
||||
"question": "Placeholder question 7",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 7",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 7,
|
||||
"question": "Placeholder question 8",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 8",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 8,
|
||||
"question": "Placeholder question 9",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 9",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 9,
|
||||
"question": "Placeholder question 10",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 10",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 10,
|
||||
"question": "Placeholder question 11",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 11",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 11,
|
||||
"question": "Placeholder question 12",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 12",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 12,
|
||||
"question": "Placeholder question 13",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 13",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 13,
|
||||
"question": "Placeholder question 14",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 14",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 14,
|
||||
"question": "Placeholder question 15",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 15",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
{
|
||||
"id": "c1c26f66ce33dd94fc89fbf55be12eca",
|
||||
"biz_seq": "TS2026011515303064BFF647",
|
||||
"sys_seq": "TS20260115153030F36FF47C",
|
||||
"knowledge_base_id": "kb-example-001",
|
||||
"name": "Example Testset",
|
||||
"created_at": "2026-01-15 15:30:30",
|
||||
"metadata": {
|
||||
"test_size": 15,
|
||||
"question_distribution": {
|
||||
"simple": 0.4,
|
||||
"reasoning": 0.4,
|
||||
"multi_context": 0.2
|
||||
},
|
||||
"sampling_strategy": {
|
||||
"small_file_threshold_mb": 1.0,
|
||||
"medium_file_threshold_mb": 10.0,
|
||||
"small_file_sampling_rate": 1.0,
|
||||
"medium_file_sampling_rate": 0.4,
|
||||
"large_file_sampling_rate": 0.15
|
||||
},
|
||||
"document_count": 1
|
||||
},
|
||||
"questions": [
|
||||
{
|
||||
"index": 0,
|
||||
"question": "Placeholder question 1",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 1",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 1,
|
||||
"question": "Placeholder question 2",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 2",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 2,
|
||||
"question": "Placeholder question 3",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 3",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 3,
|
||||
"question": "Placeholder question 4",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 4",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 4,
|
||||
"question": "Placeholder question 5",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 5",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 5,
|
||||
"question": "Placeholder question 6",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 6",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 6,
|
||||
"question": "Placeholder question 7",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 7",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 7,
|
||||
"question": "Placeholder question 8",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 8",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 8,
|
||||
"question": "Placeholder question 9",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 9",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 9,
|
||||
"question": "Placeholder question 10",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 10",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 10,
|
||||
"question": "Placeholder question 11",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 11",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 11,
|
||||
"question": "Placeholder question 12",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 12",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 12,
|
||||
"question": "Placeholder question 13",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 13",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 13,
|
||||
"question": "Placeholder question 14",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 14",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 14,
|
||||
"question": "Placeholder question 15",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 15",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
{
|
||||
"id": "c3ff544506406e1677f3b3e6f7c2609a",
|
||||
"biz_seq": "TS202601151523291B980AE0",
|
||||
"sys_seq": "TS202601151523292B96D9AD",
|
||||
"knowledge_base_id": "kb-example-001",
|
||||
"name": "Example Testset",
|
||||
"created_at": "2026-01-15 15:23:29",
|
||||
"metadata": {
|
||||
"test_size": 15,
|
||||
"question_distribution": {
|
||||
"simple": 0.4,
|
||||
"reasoning": 0.4,
|
||||
"multi_context": 0.2
|
||||
},
|
||||
"sampling_strategy": {
|
||||
"small_file_threshold_mb": 1.0,
|
||||
"medium_file_threshold_mb": 10.0,
|
||||
"small_file_sampling_rate": 1.0,
|
||||
"medium_file_sampling_rate": 0.4,
|
||||
"large_file_sampling_rate": 0.15
|
||||
},
|
||||
"document_count": 1
|
||||
},
|
||||
"questions": [
|
||||
{
|
||||
"index": 0,
|
||||
"question": "Placeholder question 1",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 1",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 1,
|
||||
"question": "Placeholder question 2",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 2",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 2,
|
||||
"question": "Placeholder question 3",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 3",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 3,
|
||||
"question": "Placeholder question 4",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 4",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 4,
|
||||
"question": "Placeholder question 5",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 5",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 5,
|
||||
"question": "Placeholder question 6",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 6",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 6,
|
||||
"question": "Placeholder question 7",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 7",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 7,
|
||||
"question": "Placeholder question 8",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 8",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 8,
|
||||
"question": "Placeholder question 9",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 9",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 9,
|
||||
"question": "Placeholder question 10",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 10",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 10,
|
||||
"question": "Placeholder question 11",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 11",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 11,
|
||||
"question": "Placeholder question 12",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 12",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 12,
|
||||
"question": "Placeholder question 13",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 13",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 13,
|
||||
"question": "Placeholder question 14",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 14",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 14,
|
||||
"question": "Placeholder question 15",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 15",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
{
|
||||
"id": "de79408aa3035fad8e223827cec74803",
|
||||
"biz_seq": "TS2026011515294630B5840E",
|
||||
"sys_seq": "TS20260115152946E055D4ED",
|
||||
"knowledge_base_id": "kb-example-001",
|
||||
"name": "Example Testset",
|
||||
"created_at": "2026-01-15 15:29:46",
|
||||
"metadata": {
|
||||
"test_size": 15,
|
||||
"question_distribution": {
|
||||
"simple": 0.4,
|
||||
"reasoning": 0.4,
|
||||
"multi_context": 0.2
|
||||
},
|
||||
"sampling_strategy": {
|
||||
"small_file_threshold_mb": 1.0,
|
||||
"medium_file_threshold_mb": 10.0,
|
||||
"small_file_sampling_rate": 1.0,
|
||||
"medium_file_sampling_rate": 0.4,
|
||||
"large_file_sampling_rate": 0.15
|
||||
},
|
||||
"document_count": 1
|
||||
},
|
||||
"questions": [
|
||||
{
|
||||
"index": 0,
|
||||
"question": "Placeholder question 1",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 1",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 1,
|
||||
"question": "Placeholder question 2",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 2",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 2,
|
||||
"question": "Placeholder question 3",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 3",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 3,
|
||||
"question": "Placeholder question 4",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 4",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 4,
|
||||
"question": "Placeholder question 5",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 5",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 5,
|
||||
"question": "Placeholder question 6",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 6",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 6,
|
||||
"question": "Placeholder question 7",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 7",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 7,
|
||||
"question": "Placeholder question 8",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 8",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 8,
|
||||
"question": "Placeholder question 9",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 9",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 9,
|
||||
"question": "Placeholder question 10",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 10",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 10,
|
||||
"question": "Placeholder question 11",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 11",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 11,
|
||||
"question": "Placeholder question 12",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 12",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 12,
|
||||
"question": "Placeholder question 13",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 13",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 13,
|
||||
"question": "Placeholder question 14",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 14",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 14,
|
||||
"question": "Placeholder question 15",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 15",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
{
|
||||
"id": "f094c8c1bce5e647c3eafeeb5a10e23c",
|
||||
"biz_seq": "TS20260115153012FA9549B4",
|
||||
"sys_seq": "TS202601151530128EE1DE4D",
|
||||
"knowledge_base_id": "kb-example-001",
|
||||
"name": "Example Testset",
|
||||
"created_at": "2026-01-15 15:30:12",
|
||||
"metadata": {
|
||||
"test_size": 15,
|
||||
"question_distribution": {
|
||||
"simple": 0.4,
|
||||
"reasoning": 0.4,
|
||||
"multi_context": 0.2
|
||||
},
|
||||
"sampling_strategy": {
|
||||
"small_file_threshold_mb": 1.0,
|
||||
"medium_file_threshold_mb": 10.0,
|
||||
"small_file_sampling_rate": 1.0,
|
||||
"medium_file_sampling_rate": 0.4,
|
||||
"large_file_sampling_rate": 0.15
|
||||
},
|
||||
"document_count": 1
|
||||
},
|
||||
"questions": [
|
||||
{
|
||||
"index": 0,
|
||||
"question": "Placeholder question 1",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 1",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 1,
|
||||
"question": "Placeholder question 2",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 2",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 2,
|
||||
"question": "Placeholder question 3",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 3",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 3,
|
||||
"question": "Placeholder question 4",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 4",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 4,
|
||||
"question": "Placeholder question 5",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 5",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 5,
|
||||
"question": "Placeholder question 6",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 6",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 6,
|
||||
"question": "Placeholder question 7",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 7",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 7,
|
||||
"question": "Placeholder question 8",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 8",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 8,
|
||||
"question": "Placeholder question 9",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 9",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 9,
|
||||
"question": "Placeholder question 10",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 10",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 10,
|
||||
"question": "Placeholder question 11",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 11",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 11,
|
||||
"question": "Placeholder question 12",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 12",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 12,
|
||||
"question": "Placeholder question 13",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 13",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 13,
|
||||
"question": "Placeholder question 14",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 14",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 14,
|
||||
"question": "Placeholder question 15",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 15",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
{
|
||||
"id": "f1ce263c8b1d2a24a3a0aa728e312537",
|
||||
"biz_seq": "TS202601151521357F27B6CA",
|
||||
"sys_seq": "TS20260115152135F8306B14",
|
||||
"knowledge_base_id": "kb-phase2-demo",
|
||||
"name": "Phase 2 Demo Testset",
|
||||
"created_at": "2026-01-15 15:21:35",
|
||||
"metadata": {
|
||||
"test_size": 5,
|
||||
"question_distribution": {
|
||||
"simple": 0.4,
|
||||
"reasoning": 0.4,
|
||||
"multi_context": 0.2
|
||||
},
|
||||
"sampling_strategy": {
|
||||
"small_file_threshold_mb": 1.0,
|
||||
"medium_file_threshold_mb": 10.0,
|
||||
"small_file_sampling_rate": 1.0,
|
||||
"medium_file_sampling_rate": 0.4,
|
||||
"large_file_sampling_rate": 0.15
|
||||
},
|
||||
"document_count": 2
|
||||
},
|
||||
"questions": [
|
||||
{
|
||||
"index": 0,
|
||||
"question": "Placeholder question 1",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 1",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 1,
|
||||
"question": "Placeholder question 2",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 2",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 2,
|
||||
"question": "Placeholder question 3",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 3",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 3,
|
||||
"question": "Placeholder question 4",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 4",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 4,
|
||||
"question": "Placeholder question 5",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 5",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
{
|
||||
"id": "f567ad832c81c77278693c8e885acb51",
|
||||
"biz_seq": "TS20260115152316F1007387",
|
||||
"sys_seq": "TS202601151523164CB5A69D",
|
||||
"knowledge_base_id": "kb-example-001",
|
||||
"name": "Example Testset",
|
||||
"created_at": "2026-01-15 15:23:16",
|
||||
"metadata": {
|
||||
"test_size": 15,
|
||||
"question_distribution": {
|
||||
"simple": 0.4,
|
||||
"reasoning": 0.4,
|
||||
"multi_context": 0.2
|
||||
},
|
||||
"sampling_strategy": {
|
||||
"small_file_threshold_mb": 1.0,
|
||||
"medium_file_threshold_mb": 10.0,
|
||||
"small_file_sampling_rate": 1.0,
|
||||
"medium_file_sampling_rate": 0.4,
|
||||
"large_file_sampling_rate": 0.15
|
||||
},
|
||||
"document_count": 1
|
||||
},
|
||||
"questions": [
|
||||
{
|
||||
"index": 0,
|
||||
"question": "Placeholder question 1",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 1",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 1,
|
||||
"question": "Placeholder question 2",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 2",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 2,
|
||||
"question": "Placeholder question 3",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 3",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 3,
|
||||
"question": "Placeholder question 4",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 4",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 4,
|
||||
"question": "Placeholder question 5",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 5",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 5,
|
||||
"question": "Placeholder question 6",
|
||||
"type": "simple",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 6",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 6,
|
||||
"question": "Placeholder question 7",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 7",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 7,
|
||||
"question": "Placeholder question 8",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 8",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 8,
|
||||
"question": "Placeholder question 9",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 9",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 9,
|
||||
"question": "Placeholder question 10",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 10",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 10,
|
||||
"question": "Placeholder question 11",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 11",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 11,
|
||||
"question": "Placeholder question 12",
|
||||
"type": "reasoning",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 12",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 12,
|
||||
"question": "Placeholder question 13",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 13",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 13,
|
||||
"question": "Placeholder question 14",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 14",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 14,
|
||||
"question": "Placeholder question 15",
|
||||
"type": "multi_context",
|
||||
"ground_truth": {
|
||||
"answer": "Placeholder answer 15",
|
||||
"context": []
|
||||
},
|
||||
"metadata": {
|
||||
"source_file": "placeholder.txt"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
"""
|
||||
文件加载模块调试脚本
|
||||
|
||||
使用方法:
|
||||
cd rag_evaluation
|
||||
python debug_loader.py
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
|
||||
# 添加父目录到路径
|
||||
parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, parent_dir)
|
||||
|
||||
from rag_evaluation.testset.document_loader import load_documents, Document
|
||||
from rag_evaluation.testset.sampling import SamplingStrategy, DocumentChunker
|
||||
from rag_evaluation.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"[OK] 成功加载 {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"[ERROR] 加载失败: {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[OK] 采样完成: {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"[ERROR] 采样失败: {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[OK] 分块完成: {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"[ERROR] 分块失败: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return None
|
||||
|
||||
return chunks
|
||||
|
||||
|
||||
def create_test_data():
|
||||
"""创建测试数据"""
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
test_dir = Path("test_data")
|
||||
test_dir.mkdir(exist_ok=True)
|
||||
|
||||
# 创建测试文本文件
|
||||
txt_file = test_dir / "test.txt"
|
||||
with open(txt_file, 'w', encoding='utf-8') as f:
|
||||
f.write("这是一个测试文本文件。\n")
|
||||
f.write("包含多行内容。\n")
|
||||
f.write("用于测试文档加载功能。\n")
|
||||
f.write("\n")
|
||||
f.write("This is a test text file.\n")
|
||||
f.write("With multiple lines.\n")
|
||||
f.write("For testing document loading.\n")
|
||||
|
||||
# 创建测试 Markdown 文件
|
||||
md_file = test_dir / "test.md"
|
||||
with open(md_file, 'w', encoding='utf-8') as f:
|
||||
f.write("# 测试 Markdown 文件\n\n")
|
||||
f.write("## 简介\n\n")
|
||||
f.write("这是一个用于测试的 Markdown 文件。\n\n")
|
||||
f.write("## 功能\n\n")
|
||||
f.write("- 支持标题\n")
|
||||
f.write("- 支持列表\n")
|
||||
f.write("- 支持代码块\n\n")
|
||||
f.write("```python\n")
|
||||
f.write("def hello():\n")
|
||||
f.write(" print('Hello, World!')\n")
|
||||
f.write("```\n\n")
|
||||
f.write("## 结论\n\n")
|
||||
f.write("测试完成。\n")
|
||||
|
||||
print(f"[OK] 测试数据已创建:")
|
||||
print(f" - {txt_file}")
|
||||
print(f" - {md_file}")
|
||||
print()
|
||||
|
||||
|
||||
def main():
|
||||
"""主函数"""
|
||||
print("\n" + "=" * 60)
|
||||
print("文件加载模块调试")
|
||||
print("=" * 60)
|
||||
print()
|
||||
|
||||
# 0. 创建测试数据
|
||||
create_test_data()
|
||||
|
||||
# 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()
|
||||
@@ -0,0 +1,359 @@
|
||||
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>RAG评估报告 - eval-demo-001</title>
|
||||
<script src="https://cdn.plot.ly/plotly-2.27.0.min.js"></script>
|
||||
<style>
|
||||
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
||||
line-height: 1.6;
|
||||
color: #333;
|
||||
background-color: #f5f5f5;
|
||||
}
|
||||
|
||||
.container {
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
header {
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
padding: 30px;
|
||||
border-radius: 10px;
|
||||
margin-bottom: 30px;
|
||||
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
header h1 {
|
||||
font-size: 2.5em;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
font-size: 1.1em;
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.timestamp {
|
||||
font-size: 0.9em;
|
||||
opacity: 0.8;
|
||||
margin-top: 5px;
|
||||
}
|
||||
|
||||
.section {
|
||||
background: white;
|
||||
padding: 25px;
|
||||
margin-bottom: 25px;
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.section h2 {
|
||||
color: #667eea;
|
||||
margin-bottom: 20px;
|
||||
font-size: 1.8em;
|
||||
border-bottom: 2px solid #667eea;
|
||||
padding-bottom: 10px;
|
||||
}
|
||||
|
||||
.summary-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
|
||||
gap: 20px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.summary-card {
|
||||
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
|
||||
padding: 20px;
|
||||
border-radius: 8px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.summary-card.score {
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.summary-card h3 {
|
||||
font-size: 0.9em;
|
||||
margin-bottom: 10px;
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
.summary-card .value {
|
||||
font-size: 2.5em;
|
||||
font-weight: bold;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
|
||||
.summary-card .label {
|
||||
font-size: 0.9em;
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.grade {
|
||||
display: inline-block;
|
||||
padding: 5px 15px;
|
||||
border-radius: 20px;
|
||||
font-weight: bold;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.grade-A { background-color: #10b981; color: white; }
|
||||
.grade-B { background-color: #3b82f6; color: white; }
|
||||
.grade-C { background-color: #f59e0b; color: white; }
|
||||
.grade-D { background-color: #ef4444; color: white; }
|
||||
.grade-F { background-color: #991b1b; color: white; }
|
||||
|
||||
.recommendations {
|
||||
background-color: #fef3c7;
|
||||
border-left: 4px solid #f59e0b;
|
||||
padding: 15px;
|
||||
margin-top: 20px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
.recommendations h3 {
|
||||
color: #92400e;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.recommendations ul {
|
||||
list-style-position: inside;
|
||||
color: #78350f;
|
||||
}
|
||||
|
||||
.recommendations li {
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
margin-top: 15px;
|
||||
}
|
||||
|
||||
th, td {
|
||||
padding: 12px;
|
||||
text-align: left;
|
||||
border-bottom: 1px solid #e5e7eb;
|
||||
}
|
||||
|
||||
th {
|
||||
background-color: #f9fafb;
|
||||
font-weight: 600;
|
||||
color: #374151;
|
||||
}
|
||||
|
||||
tr:hover {
|
||||
background-color: #f9fafb;
|
||||
}
|
||||
|
||||
.status-badge {
|
||||
display: inline-block;
|
||||
padding: 4px 12px;
|
||||
border-radius: 12px;
|
||||
font-size: 0.85em;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.status-good { background-color: #d1fae5; color: #065f46; }
|
||||
.status-warning { background-color: #fed7aa; color: #92400e; }
|
||||
.status-poor { background-color: #fee2e2; color: #991b1b; }
|
||||
|
||||
.chart-container {
|
||||
margin: 20px 0;
|
||||
padding: 15px;
|
||||
background: white;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.failed-case {
|
||||
background-color: #fef2f2;
|
||||
border-left: 4px solid #ef4444;
|
||||
padding: 15px;
|
||||
margin-bottom: 15px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
.failed-case h4 {
|
||||
color: #991b1b;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.failed-case .question {
|
||||
font-weight: 600;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.failed-case .metrics {
|
||||
font-size: 0.9em;
|
||||
color: #7f1d1d;
|
||||
}
|
||||
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<header>
|
||||
<h1>RAG评估报告</h1>
|
||||
<p class="subtitle">评估ID: eval-demo-001</p>
|
||||
<p class="timestamp">生成时间: 2026-01-15 21:49:35</p>
|
||||
</header>
|
||||
|
||||
|
||||
<div class="section">
|
||||
<h2>执行摘要</h2>
|
||||
<div class="summary-grid">
|
||||
<div class="summary-card score">
|
||||
<h3>整体评分</h3>
|
||||
<div class="value">82.5</div>
|
||||
<div class="grade grade-B">B (良好)</div>
|
||||
</div>
|
||||
<div class="summary-card">
|
||||
<h3>总问题数</h3>
|
||||
<div class="value">20</div>
|
||||
<div class="label">评估问题</div>
|
||||
</div>
|
||||
<div class="summary-card">
|
||||
<h3>成功率</h3>
|
||||
<div class="value">90.0%</div>
|
||||
<div class="label">18/20 成功</div>
|
||||
</div>
|
||||
<div class="summary-card">
|
||||
<h3>平均响应时间</h3>
|
||||
<div class="value">1031ms</div>
|
||||
<div class="label">检索+生成</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="section">
|
||||
<h2>指标雷达图</h2>
|
||||
<div id="radar-chart" class="chart-container"></div>
|
||||
<script>
|
||||
|
||||
var data = [{"type": "scatterpolar", "r": [0.85, 0.82, 0.88, 0.8, 0.85], "theta": ["\u4e0a\u4e0b\u6587\u53ec\u56de\u7387", "\u4e0a\u4e0b\u6587\u7cbe\u786e\u7387", "\u5fe0\u5b9e\u5ea6", "\u7b54\u6848\u76f8\u5173\u6027", "\u4e0a\u4e0b\u6587\u53ec\u56de\u7387"], "fill": "toself", "name": "\u6307\u6807\u5f97\u5206"}];
|
||||
var layout = {"polar": {"radialaxis": {"visible": true, "range": [0, 1]}}, "showlegend": false};
|
||||
Plotly.newPlot('radar-chart', data, layout);
|
||||
|
||||
</script>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="section">
|
||||
<h2>指标对比</h2>
|
||||
<div id="bar-chart" class="chart-container"></div>
|
||||
<script>
|
||||
|
||||
var data = [{"x": ["\u4e0a\u4e0b\u6587\u53ec\u56de\u7387", "\u4e0a\u4e0b\u6587\u7cbe\u786e\u7387", "\u5fe0\u5b9e\u5ea6", "\u7b54\u6848\u76f8\u5173\u6027"], "y": [0.85, 0.82, 0.88, 0.8], "name": "\u5e73\u5747\u5f97\u5206", "type": "bar", "marker": {"color": "#667eea"}}, {"x": ["\u4e0a\u4e0b\u6587\u53ec\u56de\u7387", "\u4e0a\u4e0b\u6587\u7cbe\u786e\u7387", "\u5fe0\u5b9e\u5ea6", "\u7b54\u6848\u76f8\u5173\u6027"], "y": [0.83, 0.78, 0.89, 0.72], "name": "\u901a\u8fc7\u7387", "type": "bar", "marker": {"color": "#764ba2"}}];
|
||||
var layout = {"barmode": "group", "yaxis": {"range": [0, 1], "title": "\u5f97\u5206"}, "xaxis": {"title": "\u6307\u6807"}};
|
||||
Plotly.newPlot('bar-chart', data, layout);
|
||||
|
||||
</script>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="section">
|
||||
<h2>整体通过率</h2>
|
||||
<div id="pie-chart" class="chart-container"></div>
|
||||
<script>
|
||||
|
||||
var data = [{"values": [18, 2], "labels": ["\u6210\u529f", "\u5931\u8d25"], "type": "pie", "marker": {"colors": ["#10b981", "#ef4444"]}}];
|
||||
var layout = {"showlegend": true};
|
||||
Plotly.newPlot('pie-chart', data, layout);
|
||||
|
||||
</script>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="section">
|
||||
<h2>指标详情</h2>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>指标</th>
|
||||
<th>平均值</th>
|
||||
<th>中位数</th>
|
||||
<th>标准差</th>
|
||||
<th>通过率</th>
|
||||
<th>状态</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
|
||||
<tr>
|
||||
<td>上下文召回率</td>
|
||||
<td>0.850</td>
|
||||
<td>0.870</td>
|
||||
<td>0.120</td>
|
||||
<td>83.0%</td>
|
||||
<td><span class="status-badge status-good">优秀</span></td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>上下文精确率</td>
|
||||
<td>0.820</td>
|
||||
<td>0.840</td>
|
||||
<td>0.100</td>
|
||||
<td>78.0%</td>
|
||||
<td><span class="status-badge status-warning">警告</span></td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>忠实度</td>
|
||||
<td>0.880</td>
|
||||
<td>0.900</td>
|
||||
<td>0.080</td>
|
||||
<td>89.0%</td>
|
||||
<td><span class="status-badge status-good">优秀</span></td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>答案相关性</td>
|
||||
<td>0.800</td>
|
||||
<td>0.820</td>
|
||||
<td>0.110</td>
|
||||
<td>72.0%</td>
|
||||
<td><span class="status-badge status-warning">警告</span></td>
|
||||
</tr>
|
||||
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="section">
|
||||
<h2>失败案例 (前10个)</h2>
|
||||
|
||||
<div class="failed-case">
|
||||
<h4>问题 #18</h4>
|
||||
<div class="question">失败问题 1</div>
|
||||
<div class="metrics">错误: Evaluation timeout</div>
|
||||
</div>
|
||||
|
||||
<div class="failed-case">
|
||||
<h4>问题 #19</h4>
|
||||
<div class="question">失败问题 2</div>
|
||||
<div class="metrics">低分指标: context_recall: 0.300, context_precision: 0.350, faithfulness: 0.400, answer_relevancy: 0.380</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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文档待补充
|
||||
- ⏳ 视频教程待制作
|
||||
@@ -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`
|
||||
@@ -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`
|
||||
@@ -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` - 测试说明
|
||||
@@ -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进行端到端测试
|
||||
@@ -0,0 +1,78 @@
|
||||
"""
|
||||
Evaluation module for RAG systems
|
||||
"""
|
||||
|
||||
from .rag_adapter import (
|
||||
RAGRetriever,
|
||||
RAGGenerator,
|
||||
HTTPRAGRetriever,
|
||||
HTTPRAGGenerator,
|
||||
MockRAGRetriever,
|
||||
MockRAGGenerator,
|
||||
RAGEvaluationAdapter,
|
||||
RetryConfig,
|
||||
retry_with_exponential_backoff
|
||||
)
|
||||
|
||||
from .metrics import (
|
||||
Metric,
|
||||
ContextRecall,
|
||||
ContextPrecision,
|
||||
MRR,
|
||||
NDCG,
|
||||
Faithfulness,
|
||||
AnswerRelevancy,
|
||||
Correctness,
|
||||
MetricsCalculator
|
||||
)
|
||||
|
||||
from .executor import EvaluationExecutor
|
||||
|
||||
from .parallel_executor import (
|
||||
ParallelExecutor,
|
||||
ParallelConfig,
|
||||
BatchEvaluator
|
||||
)
|
||||
|
||||
from .cache import (
|
||||
CacheKey,
|
||||
EvaluationCache,
|
||||
CachedEvaluationExecutor
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
# RAG Adapters
|
||||
"RAGRetriever",
|
||||
"RAGGenerator",
|
||||
"HTTPRAGRetriever",
|
||||
"HTTPRAGGenerator",
|
||||
"MockRAGRetriever",
|
||||
"MockRAGGenerator",
|
||||
"RAGEvaluationAdapter",
|
||||
"RetryConfig",
|
||||
"retry_with_exponential_backoff",
|
||||
|
||||
# Metrics
|
||||
"Metric",
|
||||
"ContextRecall",
|
||||
"ContextPrecision",
|
||||
"MRR",
|
||||
"NDCG",
|
||||
"Faithfulness",
|
||||
"AnswerRelevancy",
|
||||
"Correctness",
|
||||
"MetricsCalculator",
|
||||
|
||||
# Executor
|
||||
"EvaluationExecutor",
|
||||
|
||||
# Parallel Execution
|
||||
"ParallelExecutor",
|
||||
"ParallelConfig",
|
||||
"BatchEvaluator",
|
||||
|
||||
# Cache
|
||||
"CacheKey",
|
||||
"EvaluationCache",
|
||||
"CachedEvaluationExecutor",
|
||||
]
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,399 @@
|
||||
"""
|
||||
Evaluation result cache management
|
||||
"""
|
||||
|
||||
from typing import Dict, Any, Optional, List
|
||||
from pathlib import Path
|
||||
import json
|
||||
import hashlib
|
||||
import pickle
|
||||
from datetime import datetime, timedelta
|
||||
import threading
|
||||
|
||||
|
||||
class CacheKey:
|
||||
"""缓存键生成器"""
|
||||
|
||||
@staticmethod
|
||||
def generate_question_key(
|
||||
question: str,
|
||||
rag_config: Optional[Dict[str, Any]] = None,
|
||||
retrieval_params: Optional[Dict[str, Any]] = None
|
||||
) -> str:
|
||||
"""
|
||||
为单个问题生成缓存键
|
||||
|
||||
Args:
|
||||
question: 问题文本
|
||||
rag_config: RAG配置(可选)
|
||||
retrieval_params: 检索参数(可选)
|
||||
|
||||
Returns:
|
||||
缓存键(MD5哈希)
|
||||
"""
|
||||
# 创建规范化数据
|
||||
data = {
|
||||
'question': question.strip().lower(),
|
||||
'rag_config': rag_config or {},
|
||||
'retrieval_params': retrieval_params or {}
|
||||
}
|
||||
|
||||
# 序列化为JSON
|
||||
data_str = json.dumps(data, sort_keys=True)
|
||||
|
||||
# 生成MD5哈希
|
||||
return hashlib.md5(data_str.encode('utf-8')).hexdigest()
|
||||
|
||||
@staticmethod
|
||||
def generate_testset_key(
|
||||
testset_id: str,
|
||||
knowledge_base_id: str,
|
||||
evaluation_config: Optional[Dict[str, Any]] = None
|
||||
) -> str:
|
||||
"""
|
||||
为测评集评估生成缓存键
|
||||
|
||||
Args:
|
||||
testset_id: 测评集ID
|
||||
knowledge_base_id: 知识库ID
|
||||
evaluation_config: 评估配置(可选)
|
||||
|
||||
Returns:
|
||||
缓存键
|
||||
"""
|
||||
data = {
|
||||
'testset_id': testset_id,
|
||||
'knowledge_base_id': knowledge_base_id,
|
||||
'evaluation_config': evaluation_config or {}
|
||||
}
|
||||
|
||||
data_str = json.dumps(data, sort_keys=True)
|
||||
return hashlib.md5(data_str.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
class EvaluationCache:
|
||||
"""评估结果缓存管理器"""
|
||||
|
||||
def __init__(self, cache_dir: str, ttl_seconds: int = 86400):
|
||||
"""
|
||||
初始化缓存管理器
|
||||
|
||||
Args:
|
||||
cache_dir: 缓存目录
|
||||
ttl_seconds: 缓存过期时间(秒),默认24小时
|
||||
"""
|
||||
self.cache_dir = Path(cache_dir)
|
||||
self.cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
self.ttl_seconds = ttl_seconds
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def _get_cache_path(self, cache_key: str) -> Path:
|
||||
"""获取缓存文件路径"""
|
||||
return self.cache_dir / f"{cache_key}.cache"
|
||||
|
||||
def get(self, cache_key: str) -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
从缓存获取结果
|
||||
|
||||
Args:
|
||||
cache_key: 缓存键
|
||||
|
||||
Returns:
|
||||
缓存的结果,如果不存在或已过期则返回None
|
||||
"""
|
||||
cache_path = self._get_cache_path(cache_key)
|
||||
|
||||
if not cache_path.exists():
|
||||
return None
|
||||
|
||||
try:
|
||||
with open(cache_path, 'rb') as f:
|
||||
cache_data = pickle.load(f)
|
||||
|
||||
# 检查是否过期
|
||||
cached_at = cache_data.get('cached_at')
|
||||
if cached_at:
|
||||
cache_age = (datetime.now() - cached_at).total_seconds()
|
||||
if cache_age > self.ttl_seconds:
|
||||
# 缓存已过期,删除文件
|
||||
cache_path.unlink()
|
||||
return None
|
||||
|
||||
return cache_data.get('data')
|
||||
|
||||
except (pickle.PickleError, EOFError, KeyError):
|
||||
# 缓存文件损坏,删除并返回None
|
||||
if cache_path.exists():
|
||||
cache_path.unlink()
|
||||
return None
|
||||
|
||||
def set(self, cache_key: str, data: Dict[str, Any]) -> None:
|
||||
"""
|
||||
将结果存入缓存
|
||||
|
||||
Args:
|
||||
cache_key: 缓存键
|
||||
data: 要缓存的数据
|
||||
"""
|
||||
cache_path = self._get_cache_path(cache_key)
|
||||
|
||||
cache_data = {
|
||||
'cached_at': datetime.now(),
|
||||
'data': data
|
||||
}
|
||||
|
||||
with self._lock:
|
||||
try:
|
||||
with open(cache_path, 'wb') as f:
|
||||
pickle.dump(cache_data, f)
|
||||
except (IOError, pickle.PickleError) as e:
|
||||
print(f"Warning: Failed to write cache: {e}")
|
||||
|
||||
def delete(self, cache_key: str) -> bool:
|
||||
"""
|
||||
删除缓存
|
||||
|
||||
Args:
|
||||
cache_key: 缓存键
|
||||
|
||||
Returns:
|
||||
是否成功删除
|
||||
"""
|
||||
cache_path = self._get_cache_path(cache_key)
|
||||
|
||||
if cache_path.exists():
|
||||
try:
|
||||
cache_path.unlink()
|
||||
return True
|
||||
except IOError:
|
||||
return False
|
||||
|
||||
return False
|
||||
|
||||
def clear(self) -> int:
|
||||
"""
|
||||
清空所有缓存
|
||||
|
||||
Returns:
|
||||
删除的缓存文件数量
|
||||
"""
|
||||
count = 0
|
||||
for cache_file in self.cache_dir.glob("*.cache"):
|
||||
try:
|
||||
cache_file.unlink()
|
||||
count += 1
|
||||
except IOError:
|
||||
pass
|
||||
|
||||
return count
|
||||
|
||||
def clear_expired(self) -> int:
|
||||
"""
|
||||
清理过期的缓存
|
||||
|
||||
Returns:
|
||||
删除的缓存文件数量
|
||||
"""
|
||||
count = 0
|
||||
now = datetime.now()
|
||||
|
||||
for cache_file in self.cache_dir.glob("*.cache"):
|
||||
try:
|
||||
with open(cache_file, 'rb') as f:
|
||||
cache_data = pickle.load(f)
|
||||
|
||||
cached_at = cache_data.get('cached_at')
|
||||
if cached_at:
|
||||
cache_age = (now - cached_at).total_seconds()
|
||||
if cache_age > self.ttl_seconds:
|
||||
cache_file.unlink()
|
||||
count += 1
|
||||
|
||||
except (pickle.PickleError, EOFError, IOError):
|
||||
# 损坏的文件也删除
|
||||
try:
|
||||
cache_file.unlink()
|
||||
count += 1
|
||||
except IOError:
|
||||
pass
|
||||
|
||||
return count
|
||||
|
||||
def get_stats(self) -> Dict[str, Any]:
|
||||
"""
|
||||
获取缓存统计信息
|
||||
|
||||
Returns:
|
||||
统计信息字典
|
||||
"""
|
||||
total_files = 0
|
||||
total_size = 0
|
||||
expired_files = 0
|
||||
now = datetime.now()
|
||||
|
||||
for cache_file in self.cache_dir.glob("*.cache"):
|
||||
total_files += 1
|
||||
total_size += cache_file.stat().st_size
|
||||
|
||||
try:
|
||||
with open(cache_file, 'rb') as f:
|
||||
cache_data = pickle.load(f)
|
||||
|
||||
cached_at = cache_data.get('cached_at')
|
||||
if cached_at:
|
||||
cache_age = (now - cached_at).total_seconds()
|
||||
if cache_age > self.ttl_seconds:
|
||||
expired_files += 1
|
||||
|
||||
except (pickle.PickleError, EOFError):
|
||||
pass
|
||||
|
||||
return {
|
||||
'total_files': total_files,
|
||||
'total_size_bytes': total_size,
|
||||
'total_size_mb': total_size / (1024 * 1024),
|
||||
'expired_files': expired_files,
|
||||
'active_files': total_files - expired_files,
|
||||
'ttl_seconds': self.ttl_seconds
|
||||
}
|
||||
|
||||
|
||||
class CachedEvaluationExecutor:
|
||||
"""带缓存的评估执行器装饰器"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
cache: EvaluationCache,
|
||||
rag_config: Optional[Dict[str, Any]] = None,
|
||||
retrieval_params: Optional[Dict[str, Any]] = None
|
||||
):
|
||||
"""
|
||||
初始化缓存执行器
|
||||
|
||||
Args:
|
||||
cache: 缓存管理器
|
||||
rag_config: RAG配置
|
||||
retrieval_params: 检索参数
|
||||
"""
|
||||
self.cache = cache
|
||||
self.rag_config = rag_config or {}
|
||||
self.retrieval_params = retrieval_params or {}
|
||||
self._cache_hits = 0
|
||||
self._cache_misses = 0
|
||||
|
||||
def evaluate_question(
|
||||
self,
|
||||
question: str,
|
||||
evaluation_func: callable
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
评估问题(带缓存)
|
||||
|
||||
Args:
|
||||
question: 问题文本
|
||||
evaluation_func: 评估函数(缓存未命中时调用)
|
||||
|
||||
Returns:
|
||||
评估结果
|
||||
"""
|
||||
# 生成缓存键
|
||||
cache_key = CacheKey.generate_question_key(
|
||||
question=question,
|
||||
rag_config=self.rag_config,
|
||||
retrieval_params=self.retrieval_params
|
||||
)
|
||||
|
||||
# 尝试从缓存获取
|
||||
cached_result = self.cache.get(cache_key)
|
||||
if cached_result is not None:
|
||||
self._cache_hits += 1
|
||||
return cached_result
|
||||
|
||||
# 缓存未命中,执行评估
|
||||
self._cache_misses += 1
|
||||
result = evaluation_func(question)
|
||||
|
||||
# 存入缓存
|
||||
self.cache.set(cache_key, result)
|
||||
|
||||
return result
|
||||
|
||||
def evaluate_batch(
|
||||
self,
|
||||
questions: List[str],
|
||||
evaluation_func: callable
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
批量评估问题(带缓存)
|
||||
|
||||
Args:
|
||||
questions: 问题列表
|
||||
evaluation_func: 评估函数
|
||||
|
||||
Returns:
|
||||
评估结果列表
|
||||
"""
|
||||
results = []
|
||||
questions_to_eval = []
|
||||
indices_to_eval = []
|
||||
|
||||
# 第一遍:检查缓存
|
||||
for i, question in enumerate(questions):
|
||||
cache_key = CacheKey.generate_question_key(
|
||||
question=question,
|
||||
rag_config=self.rag_config,
|
||||
retrieval_params=self.retrieval_params
|
||||
)
|
||||
|
||||
cached_result = self.cache.get(cache_key)
|
||||
if cached_result is not None:
|
||||
self._cache_hits += 1
|
||||
results.append((i, cached_result))
|
||||
else:
|
||||
self._cache_misses += 1
|
||||
questions_to_eval.append(question)
|
||||
indices_to_eval.append(i)
|
||||
|
||||
# 第二遍:评估未缓存的问题
|
||||
if questions_to_eval:
|
||||
eval_results = evaluation_func(questions_to_eval)
|
||||
|
||||
for question, result in zip(questions_to_eval, eval_results):
|
||||
# 存入缓存
|
||||
cache_key = CacheKey.generate_question_key(
|
||||
question=question,
|
||||
rag_config=self.rag_config,
|
||||
retrieval_params=self.retrieval_params
|
||||
)
|
||||
self.cache.set(cache_key, result)
|
||||
|
||||
# 添加到结果列表
|
||||
for idx, result in zip(indices_to_eval, eval_results):
|
||||
results.append((idx, result))
|
||||
|
||||
# 按原始顺序排序
|
||||
results.sort(key=lambda x: x[0])
|
||||
return [result for _, result in results]
|
||||
|
||||
def get_cache_stats(self) -> Dict[str, Any]:
|
||||
"""
|
||||
获取缓存统计信息
|
||||
|
||||
Returns:
|
||||
统计信息字典
|
||||
"""
|
||||
stats = self.cache.get_stats()
|
||||
stats['cache_hits'] = self._cache_hits
|
||||
stats['cache_misses'] = self._cache_misses
|
||||
total_requests = self._cache_hits + self._cache_misses
|
||||
if total_requests > 0:
|
||||
stats['hit_rate'] = self._cache_hits / total_requests
|
||||
else:
|
||||
stats['hit_rate'] = 0.0
|
||||
|
||||
return stats
|
||||
|
||||
def reset_stats(self) -> None:
|
||||
"""重置统计信息"""
|
||||
self._cache_hits = 0
|
||||
self._cache_misses = 0
|
||||
@@ -0,0 +1,438 @@
|
||||
"""
|
||||
Evaluation executor for RAG systems
|
||||
"""
|
||||
|
||||
from typing import List, Dict, Any, Optional
|
||||
from datetime import datetime
|
||||
import json
|
||||
|
||||
from ..core.config import Config
|
||||
from ..storage.database import DatabaseManager
|
||||
from ..utils.helpers import generate_id, generate_biz_seq, generate_sys_seq, format_datetime
|
||||
from .rag_adapter import RAGEvaluationAdapter
|
||||
from .metrics import MetricsCalculator
|
||||
from .parallel_executor import ParallelExecutor, ParallelConfig, BatchEvaluator, parallel_evaluator_wrapper
|
||||
|
||||
|
||||
class EvaluationExecutor:
|
||||
"""Executor for RAG evaluation tasks"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: Config,
|
||||
rag_adapter: RAGEvaluationAdapter,
|
||||
db_manager: Optional[DatabaseManager] = None
|
||||
):
|
||||
"""
|
||||
Initialize evaluation executor
|
||||
|
||||
Args:
|
||||
config: Configuration object
|
||||
rag_adapter: RAG evaluation adapter
|
||||
db_manager: Database manager (optional)
|
||||
"""
|
||||
self.config = config
|
||||
self.rag_adapter = rag_adapter
|
||||
self.db_manager = db_manager or DatabaseManager(config.database)
|
||||
self.metrics_calculator = MetricsCalculator()
|
||||
|
||||
def execute_evaluation(
|
||||
self,
|
||||
testset_id: str,
|
||||
knowledge_base_id: str,
|
||||
testset: Dict[str, Any]
|
||||
) -> str:
|
||||
"""
|
||||
Execute evaluation for a testset
|
||||
|
||||
Args:
|
||||
testset_id: Testset ID
|
||||
knowledge_base_id: Knowledge base ID
|
||||
testset: Testset dictionary
|
||||
|
||||
Returns:
|
||||
Evaluation ID
|
||||
"""
|
||||
# Create evaluation record
|
||||
evaluation_id = generate_id("eval")
|
||||
biz_seq = generate_biz_seq("EVAL")
|
||||
sys_seq = generate_sys_seq("EVAL")
|
||||
|
||||
# Insert evaluation record
|
||||
sql = """
|
||||
INSERT INTO evaluations (
|
||||
id, biz_seq, sys_seq, knowledge_base_id, testset_id,
|
||||
status, started_at, create_time
|
||||
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
||||
"""
|
||||
|
||||
now = datetime.now()
|
||||
self.db_manager.execute_update(
|
||||
sql,
|
||||
(
|
||||
evaluation_id, biz_seq, sys_seq, knowledge_base_id, testset_id,
|
||||
'running', now, now
|
||||
)
|
||||
)
|
||||
|
||||
try:
|
||||
# Execute evaluation for each question
|
||||
questions = testset.get('questions', [])
|
||||
results = []
|
||||
|
||||
for question_data in questions:
|
||||
result = self._evaluate_question(
|
||||
evaluation_id=evaluation_id,
|
||||
question_data=question_data
|
||||
)
|
||||
results.append(result)
|
||||
|
||||
# Calculate summary
|
||||
self._save_summary(evaluation_id, results)
|
||||
|
||||
# Update evaluation status
|
||||
self._update_evaluation_status(evaluation_id, 'completed')
|
||||
|
||||
except Exception as e:
|
||||
# Update evaluation status to failed
|
||||
self._update_evaluation_status(evaluation_id, 'failed', str(e))
|
||||
raise
|
||||
|
||||
return evaluation_id
|
||||
|
||||
def execute_evaluation_parallel(
|
||||
self,
|
||||
testset_id: str,
|
||||
knowledge_base_id: str,
|
||||
testset: Dict[str, Any],
|
||||
parallel_config: Optional[ParallelConfig] = None
|
||||
) -> str:
|
||||
"""
|
||||
Execute evaluation in parallel for better performance
|
||||
|
||||
Args:
|
||||
testset_id: Testset ID
|
||||
knowledge_base_id: Knowledge base ID
|
||||
testset: Testset dictionary
|
||||
parallel_config: Parallel execution config (optional)
|
||||
|
||||
Returns:
|
||||
Evaluation ID
|
||||
"""
|
||||
# Create evaluation record
|
||||
evaluation_id = generate_id("eval")
|
||||
biz_seq = generate_biz_seq("EVAL")
|
||||
sys_seq = generate_sys_seq("EVAL")
|
||||
|
||||
# Insert evaluation record
|
||||
sql = """
|
||||
INSERT INTO evaluations (
|
||||
id, biz_seq, sys_seq, knowledge_base_id, testset_id,
|
||||
status, started_at, create_time
|
||||
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
||||
"""
|
||||
|
||||
now = datetime.now()
|
||||
self.db_manager.execute_update(
|
||||
sql,
|
||||
(
|
||||
evaluation_id, biz_seq, sys_seq, knowledge_base_id, testset_id,
|
||||
'running', now, now
|
||||
)
|
||||
)
|
||||
|
||||
try:
|
||||
# Create parallel config
|
||||
if parallel_config is None:
|
||||
parallel_config = ParallelConfig(
|
||||
max_workers=self.config.evaluation.parallel_workers
|
||||
)
|
||||
|
||||
batch_evaluator = BatchEvaluator(parallel_config)
|
||||
|
||||
# Define evaluation function
|
||||
def evaluate_single_question(question_data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Evaluate a single question"""
|
||||
return self._evaluate_question(
|
||||
evaluation_id=evaluation_id,
|
||||
question_data=question_data
|
||||
)
|
||||
|
||||
# Execute evaluation in parallel
|
||||
questions = testset.get('questions', [])
|
||||
results = batch_evaluator.evaluate_questions_batch(
|
||||
questions=questions,
|
||||
evaluation_func=evaluate_single_question
|
||||
)
|
||||
|
||||
# Check for errors
|
||||
successful_results = [r for r in results if r.get('metrics') is not None]
|
||||
failed_count = len(results) - len(successful_results)
|
||||
|
||||
if failed_count > 0:
|
||||
print(f"Warning: {failed_count} questions failed to evaluate")
|
||||
|
||||
# Calculate summary
|
||||
self._save_summary(evaluation_id, successful_results)
|
||||
|
||||
# Update evaluation status
|
||||
self._update_evaluation_status(evaluation_id, 'completed')
|
||||
|
||||
except Exception as e:
|
||||
# Update evaluation status to failed
|
||||
self._update_evaluation_status(evaluation_id, 'failed', str(e))
|
||||
raise
|
||||
|
||||
return evaluation_id
|
||||
|
||||
def _evaluate_question(
|
||||
self,
|
||||
evaluation_id: str,
|
||||
question_data: Dict[str, Any]
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Evaluate a single question
|
||||
|
||||
Args:
|
||||
evaluation_id: Evaluation ID
|
||||
question_data: Question data from testset
|
||||
|
||||
Returns:
|
||||
Evaluation result
|
||||
"""
|
||||
question_text = question_data['question']
|
||||
question_index = question_data['index']
|
||||
ground_truth = question_data.get('ground_truth', )
|
||||
|
||||
# Execute RAG pipeline
|
||||
rag_result = self.rag_adapter.evaluate_question(question_text)
|
||||
|
||||
# Extract ground truth
|
||||
ground_truth_answer = ground_truth.get('answer', '')
|
||||
ground_truth_contexts = ground_truth.get('context', [])
|
||||
|
||||
# Calculate metrics
|
||||
retrieved_context_texts = rag_result['context_texts']
|
||||
generated_answer = rag_result['generated_answer']
|
||||
|
||||
metrics = self.metrics_calculator.calculate_all(
|
||||
question=question_text,
|
||||
retrieved_contexts=retrieved_context_texts,
|
||||
generated_answer=generated_answer,
|
||||
ground_truth_contexts=ground_truth_contexts,
|
||||
ground_truth_answer=ground_truth_answer
|
||||
)
|
||||
|
||||
# Save result to database
|
||||
result_id = generate_id("result")
|
||||
biz_seq = generate_biz_seq("RESULT")
|
||||
sys_seq = generate_sys_seq("RESULT")
|
||||
|
||||
sql = """
|
||||
INSERT INTO evaluation_results (
|
||||
id, biz_seq, sys_seq, evaluation_id, question_index, question_text,
|
||||
context_recall, context_precision, mrr, ndcg,
|
||||
faithfulness, answer_relevancy, correctness,
|
||||
retrieved_contexts, generated_answer, ground_truth_answer, ground_truth_context,
|
||||
retrieval_time_ms, generation_time_ms, create_time
|
||||
) VALUES (
|
||||
%s, %s, %s, %s, %s, %s,
|
||||
%s, %s, %s, %s,
|
||||
%s, %s, %s,
|
||||
%s, %s, %s, %s,
|
||||
%s, %s, %s
|
||||
)
|
||||
"""
|
||||
|
||||
now = datetime.now()
|
||||
self.db_manager.execute_update(
|
||||
sql,
|
||||
(
|
||||
result_id, biz_seq, sys_seq, evaluation_id, question_index, question_text,
|
||||
metrics['context_recall'], metrics['context_precision'],
|
||||
metrics['mrr'], metrics['ndcg'],
|
||||
metrics['faithfulness'], metrics['answer_relevancy'], metrics['correctness'],
|
||||
json.dumps(rag_result['retrieved_contexts']),
|
||||
generated_answer, ground_truth_answer,
|
||||
json.dumps(ground_truth_contexts),
|
||||
rag_result['retrieval_time_ms'], rag_result['generation_time_ms'],
|
||||
now
|
||||
)
|
||||
)
|
||||
|
||||
return {
|
||||
'result_id': result_id,
|
||||
'question_index': question_index,
|
||||
'metrics': metrics
|
||||
}
|
||||
|
||||
def _save_summary(self, evaluation_id: str, results: List[Dict[str, Any]]):
|
||||
"""
|
||||
Save evaluation summary
|
||||
|
||||
Args:
|
||||
evaluation_id: Evaluation ID
|
||||
results: List of evaluation results
|
||||
"""
|
||||
if not results:
|
||||
return
|
||||
|
||||
# Calculate averages
|
||||
total = len(results)
|
||||
failed = sum(1 for r in results if not r.get('metrics'))
|
||||
|
||||
avg_metrics = {
|
||||
'context_recall': 0.0,
|
||||
'context_precision': 0.0,
|
||||
'mrr': 0.0,
|
||||
'ndcg': 0.0,
|
||||
'faithfulness': 0.0,
|
||||
'answer_relevancy': 0.0,
|
||||
'correctness': 0.0
|
||||
}
|
||||
|
||||
for result in results:
|
||||
metrics = result.get('metrics', {})
|
||||
for key in avg_metrics:
|
||||
avg_metrics[key] += metrics.get(key, 0.0)
|
||||
|
||||
for key in avg_metrics:
|
||||
avg_metrics[key] /= total
|
||||
|
||||
# Calculate overall score (weighted average)
|
||||
overall_score = (
|
||||
avg_metrics['context_recall'] * 0.15 +
|
||||
avg_metrics['context_precision'] * 0.15 +
|
||||
avg_metrics['faithfulness'] * 0.25 +
|
||||
avg_metrics['answer_relevancy'] * 0.25 +
|
||||
avg_metrics['correctness'] * 0.20
|
||||
) * 100
|
||||
|
||||
# Save summary
|
||||
summary_id = generate_id("summary")
|
||||
biz_seq = generate_biz_seq("SUMMARY")
|
||||
sys_seq = generate_sys_seq("SUMMARY")
|
||||
|
||||
sql = """
|
||||
INSERT INTO evaluation_summaries (
|
||||
id, biz_seq, sys_seq, evaluation_id,
|
||||
avg_context_recall, avg_context_precision, avg_mrr, avg_ndcg,
|
||||
avg_faithfulness, avg_answer_relevancy, avg_correctness,
|
||||
overall_score, total_questions, failed_questions, create_time
|
||||
) VALUES (
|
||||
%s, %s, %s, %s,
|
||||
%s, %s, %s, %s,
|
||||
%s, %s, %s,
|
||||
%s, %s, %s, %s
|
||||
)
|
||||
"""
|
||||
|
||||
now = datetime.now()
|
||||
self.db_manager.execute_update(
|
||||
sql,
|
||||
(
|
||||
summary_id, biz_seq, sys_seq, evaluation_id,
|
||||
avg_metrics['context_recall'], avg_metrics['context_precision'],
|
||||
avg_metrics['mrr'], avg_metrics['ndcg'],
|
||||
avg_metrics['faithfulness'], avg_metrics['answer_relevancy'],
|
||||
avg_metrics['correctness'],
|
||||
overall_score, total, failed, now
|
||||
)
|
||||
)
|
||||
|
||||
def _update_evaluation_status(
|
||||
self,
|
||||
evaluation_id: str,
|
||||
status: str,
|
||||
error_message: Optional[str] = None
|
||||
):
|
||||
"""
|
||||
Update evaluation status
|
||||
|
||||
Args:
|
||||
evaluation_id: Evaluation ID
|
||||
status: New status
|
||||
error_message: Optional error message
|
||||
"""
|
||||
if status == 'completed':
|
||||
sql = """
|
||||
UPDATE evaluations
|
||||
SET status = %s, completed_at = %s
|
||||
WHERE id = %s
|
||||
"""
|
||||
self.db_manager.execute_update(sql, (status, datetime.now(), evaluation_id))
|
||||
elif status == 'failed':
|
||||
sql = """
|
||||
UPDATE evaluations
|
||||
SET status = %s, error_message = %s, completed_at = %s
|
||||
WHERE id = %s
|
||||
"""
|
||||
self.db_manager.execute_update(
|
||||
sql,
|
||||
(status, error_message, datetime.now(), evaluation_id)
|
||||
)
|
||||
|
||||
def get_evaluation_status(self, evaluation_id: str) -> Dict[str, Any]:
|
||||
"""
|
||||
Get evaluation status
|
||||
|
||||
Args:
|
||||
evaluation_id: Evaluation ID
|
||||
|
||||
Returns:
|
||||
Evaluation status dictionary
|
||||
"""
|
||||
sql = """
|
||||
SELECT id, status, started_at, completed_at, error_message
|
||||
FROM evaluations
|
||||
WHERE id = %s
|
||||
"""
|
||||
|
||||
results = self.db_manager.execute_query(sql, (evaluation_id,))
|
||||
|
||||
if not results:
|
||||
raise ValueError(f"Evaluation not found: {evaluation_id}")
|
||||
|
||||
return results[0]
|
||||
|
||||
def get_evaluation_results(self, evaluation_id: str) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Get evaluation results
|
||||
|
||||
Args:
|
||||
evaluation_id: Evaluation ID
|
||||
|
||||
Returns:
|
||||
List of evaluation results
|
||||
"""
|
||||
sql = """
|
||||
SELECT *
|
||||
FROM evaluation_results
|
||||
WHERE evaluation_id = %s
|
||||
ORDER BY question_index
|
||||
"""
|
||||
|
||||
return self.db_manager.execute_query(sql, (evaluation_id,))
|
||||
|
||||
def get_evaluation_summary(self, evaluation_id: str) -> Dict[str, Any]:
|
||||
"""
|
||||
Get evaluation summary
|
||||
|
||||
Args:
|
||||
evaluation_id: Evaluation ID
|
||||
|
||||
Returns:
|
||||
Evaluation summary dictionary
|
||||
"""
|
||||
sql = """
|
||||
SELECT *
|
||||
FROM evaluation_summaries
|
||||
WHERE evaluation_id = %s
|
||||
"""
|
||||
|
||||
results = self.db_manager.execute_query(sql, (evaluation_id,))
|
||||
|
||||
if not results:
|
||||
raise ValueError(f"Evaluation summary not found: {evaluation_id}")
|
||||
|
||||
return results[0]
|
||||
@@ -0,0 +1,414 @@
|
||||
"""
|
||||
Metrics calculation for RAG evaluation
|
||||
"""
|
||||
|
||||
from typing import List, Dict, Any, Optional, Set
|
||||
from abc import ABC, abstractmethod
|
||||
import re
|
||||
|
||||
|
||||
def _tokenize(text: str) -> Set[str]:
|
||||
"""
|
||||
Tokenize text supporting both Chinese and English
|
||||
|
||||
For Chinese: Extract individual characters
|
||||
For English: Split by whitespace and punctuation
|
||||
For mixed: Combine both approaches
|
||||
|
||||
Args:
|
||||
text: Input text
|
||||
|
||||
Returns:
|
||||
Set of tokens
|
||||
"""
|
||||
if not text:
|
||||
return set()
|
||||
|
||||
text = text.lower()
|
||||
|
||||
# For Chinese or mixed content, extract characters
|
||||
# Match Chinese characters
|
||||
chinese_chars = set(re.findall(r'[\u4e00-\u9fff]', text))
|
||||
|
||||
# For English and other languages, split by non-word characters
|
||||
# This handles English words and numbers
|
||||
english_words = set(re.findall(r'\b\w+\b', text))
|
||||
|
||||
# Combine both
|
||||
return chinese_chars | english_words
|
||||
|
||||
|
||||
class Metric(ABC):
|
||||
"""Abstract base class for metrics"""
|
||||
|
||||
@abstractmethod
|
||||
def calculate(self, **kwargs) -> float:
|
||||
"""
|
||||
Calculate metric score
|
||||
|
||||
Returns:
|
||||
Metric score (0.0 to 1.0)
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
class ContextRecall(Metric):
|
||||
"""
|
||||
Context Recall: Measures how many relevant contexts were retrieved
|
||||
|
||||
Formula: |retrieved ∩ ground_truth| / |ground_truth|
|
||||
"""
|
||||
|
||||
def calculate(
|
||||
self,
|
||||
retrieved_contexts: List[str],
|
||||
ground_truth_contexts: List[str]
|
||||
) -> float:
|
||||
"""
|
||||
Calculate context recall
|
||||
|
||||
Args:
|
||||
retrieved_contexts: List of retrieved context IDs/texts
|
||||
ground_truth_contexts: List of ground truth context IDs/texts
|
||||
|
||||
Returns:
|
||||
Recall score (0.0 to 1.0)
|
||||
"""
|
||||
if not ground_truth_contexts:
|
||||
return 0.0
|
||||
|
||||
# Convert to sets for intersection
|
||||
retrieved_set = set(retrieved_contexts)
|
||||
ground_truth_set = set(ground_truth_contexts)
|
||||
|
||||
# Calculate intersection
|
||||
intersection = retrieved_set & ground_truth_set
|
||||
|
||||
recall = len(intersection) / len(ground_truth_set)
|
||||
return recall
|
||||
|
||||
|
||||
class ContextPrecision(Metric):
|
||||
"""
|
||||
Context Precision: Measures how many retrieved contexts are relevant
|
||||
|
||||
Formula: |retrieved ∩ ground_truth| / |retrieved|
|
||||
"""
|
||||
|
||||
def calculate(
|
||||
self,
|
||||
retrieved_contexts: List[str],
|
||||
ground_truth_contexts: List[str]
|
||||
) -> float:
|
||||
"""
|
||||
Calculate context precision
|
||||
|
||||
Args:
|
||||
retrieved_contexts: List of retrieved context IDs/texts
|
||||
ground_truth_contexts: List of ground truth context IDs/texts
|
||||
|
||||
Returns:
|
||||
Precision score (0.0 to 1.0)
|
||||
"""
|
||||
if not retrieved_contexts:
|
||||
return 0.0
|
||||
|
||||
# Convert to sets for intersection
|
||||
retrieved_set = set(retrieved_contexts)
|
||||
ground_truth_set = set(ground_truth_contexts)
|
||||
|
||||
# Calculate intersection
|
||||
intersection = retrieved_set & ground_truth_set
|
||||
|
||||
precision = len(intersection) / len(retrieved_set)
|
||||
return precision
|
||||
|
||||
|
||||
class MRR(Metric):
|
||||
"""
|
||||
Mean Reciprocal Rank: Measures the rank of the first relevant context
|
||||
|
||||
Formula: 1 / rank_of_first_relevant_context
|
||||
"""
|
||||
|
||||
def calculate(
|
||||
self,
|
||||
retrieved_contexts: List[str],
|
||||
ground_truth_contexts: List[str]
|
||||
) -> float:
|
||||
"""
|
||||
Calculate MRR
|
||||
|
||||
Args:
|
||||
retrieved_contexts: Ordered list of retrieved context IDs/texts
|
||||
ground_truth_contexts: List of ground truth context IDs/texts
|
||||
|
||||
Returns:
|
||||
MRR score (0.0 to 1.0)
|
||||
"""
|
||||
if not retrieved_contexts or not ground_truth_contexts:
|
||||
return 0.0
|
||||
|
||||
ground_truth_set = set(ground_truth_contexts)
|
||||
|
||||
# Find rank of first relevant context
|
||||
for rank, context in enumerate(retrieved_contexts, start=1):
|
||||
if context in ground_truth_set:
|
||||
return 1.0 / rank
|
||||
|
||||
return 0.0
|
||||
|
||||
|
||||
class NDCG(Metric):
|
||||
"""
|
||||
Normalized Discounted Cumulative Gain
|
||||
|
||||
Measures ranking quality with position discount
|
||||
"""
|
||||
|
||||
def calculate(
|
||||
self,
|
||||
retrieved_contexts: List[str],
|
||||
ground_truth_contexts: List[str],
|
||||
k: Optional[int] = None
|
||||
) -> float:
|
||||
"""
|
||||
Calculate NDCG@k
|
||||
|
||||
Args:
|
||||
retrieved_contexts: Ordered list of retrieved context IDs/texts
|
||||
ground_truth_contexts: List of ground truth context IDs/texts
|
||||
k: Cut-off rank (if None, use all retrieved contexts)
|
||||
|
||||
Returns:
|
||||
NDCG score (0.0 to 1.0)
|
||||
"""
|
||||
if not retrieved_contexts or not ground_truth_contexts:
|
||||
return 0.0
|
||||
|
||||
if k is None:
|
||||
k = len(retrieved_contexts)
|
||||
|
||||
ground_truth_set = set(ground_truth_contexts)
|
||||
|
||||
# Calculate DCG
|
||||
dcg = 0.0
|
||||
for i, context in enumerate(retrieved_contexts[:k], start=1):
|
||||
relevance = 1.0 if context in ground_truth_set else 0.0
|
||||
dcg += relevance / (i + 1) # log2(i+1) simplified
|
||||
|
||||
# Calculate IDCG (ideal DCG)
|
||||
# IDCG should consider at most k relevant documents at top positions
|
||||
idcg = 0.0
|
||||
max_relevant = min(len(ground_truth_contexts), k)
|
||||
for i in range(1, max_relevant + 1):
|
||||
idcg += 1.0 / (i + 1)
|
||||
|
||||
if idcg == 0.0:
|
||||
return 0.0
|
||||
|
||||
ndcg = dcg / idcg
|
||||
return ndcg
|
||||
|
||||
|
||||
class Faithfulness(Metric):
|
||||
"""
|
||||
Faithfulness: Measures if the answer is faithful to the contexts
|
||||
|
||||
Uses RAGAS faithfulness metric
|
||||
"""
|
||||
|
||||
def calculate(
|
||||
self,
|
||||
question: str,
|
||||
answer: str,
|
||||
contexts: List[str]
|
||||
) -> float:
|
||||
"""
|
||||
Calculate faithfulness score
|
||||
|
||||
Args:
|
||||
question: Question text
|
||||
answer: Generated answer
|
||||
contexts: Retrieved contexts
|
||||
|
||||
Returns:
|
||||
Faithfulness score (0.0 to 1.0)
|
||||
"""
|
||||
# TODO: Integrate with RAGAS faithfulness metric
|
||||
# For now, simple heuristic: check if answer contains context keywords
|
||||
|
||||
if not answer or not contexts:
|
||||
return 0.0
|
||||
|
||||
# Tokenize answer and contexts
|
||||
answer_tokens = _tokenize(answer)
|
||||
context_text = ' '.join(contexts)
|
||||
context_tokens = _tokenize(context_text)
|
||||
|
||||
if not answer_tokens:
|
||||
return 0.0
|
||||
|
||||
overlap = answer_tokens & context_tokens
|
||||
faithfulness = len(overlap) / len(answer_tokens)
|
||||
|
||||
return min(faithfulness, 1.0)
|
||||
|
||||
|
||||
class AnswerRelevancy(Metric):
|
||||
"""
|
||||
Answer Relevancy: Measures if the answer is relevant to the question
|
||||
|
||||
Uses RAGAS answer relevancy metric
|
||||
"""
|
||||
|
||||
def calculate(
|
||||
self,
|
||||
question: str,
|
||||
answer: str
|
||||
) -> float:
|
||||
"""
|
||||
Calculate answer relevancy score
|
||||
|
||||
Args:
|
||||
question: Question text
|
||||
answer: Generated answer
|
||||
|
||||
Returns:
|
||||
Relevancy score (0.0 to 1.0)
|
||||
"""
|
||||
# TODO: Integrate with RAGAS answer relevancy metric
|
||||
# For now, simple heuristic: check keyword overlap
|
||||
|
||||
if not question or not answer:
|
||||
return 0.0
|
||||
|
||||
# Tokenize question and answer
|
||||
question_tokens = _tokenize(question)
|
||||
answer_tokens = _tokenize(answer)
|
||||
|
||||
if not question_tokens:
|
||||
return 0.0
|
||||
|
||||
# Calculate overlap
|
||||
overlap = question_tokens & answer_tokens
|
||||
relevancy = len(overlap) / len(question_tokens)
|
||||
|
||||
return min(relevancy, 1.0)
|
||||
|
||||
|
||||
class Correctness(Metric):
|
||||
"""
|
||||
Correctness: Measures if the answer is correct compared to ground truth
|
||||
|
||||
Uses RAGAS correctness metric
|
||||
"""
|
||||
|
||||
def calculate(
|
||||
self,
|
||||
answer: str,
|
||||
ground_truth_answer: str
|
||||
) -> float:
|
||||
"""
|
||||
Calculate correctness score
|
||||
|
||||
Args:
|
||||
answer: Generated answer
|
||||
ground_truth_answer: Ground truth answer
|
||||
|
||||
Returns:
|
||||
Correctness score (0.0 to 1.0)
|
||||
"""
|
||||
# TODO: Integrate with RAGAS correctness metric
|
||||
# For now, simple heuristic: word overlap
|
||||
|
||||
if not answer or not ground_truth_answer:
|
||||
return 0.0
|
||||
|
||||
# Tokenize answers
|
||||
answer_tokens = _tokenize(answer)
|
||||
ground_truth_tokens = _tokenize(ground_truth_answer)
|
||||
|
||||
if not ground_truth_tokens:
|
||||
return 0.0
|
||||
|
||||
overlap = answer_tokens & ground_truth_tokens
|
||||
correctness = len(overlap) / len(ground_truth_tokens)
|
||||
|
||||
return min(correctness, 1.0)
|
||||
|
||||
|
||||
class MetricsCalculator:
|
||||
"""Calculator for all evaluation metrics"""
|
||||
|
||||
def __init__(self):
|
||||
self.context_recall = ContextRecall()
|
||||
self.context_precision = ContextPrecision()
|
||||
self.mrr = MRR()
|
||||
self.ndcg = NDCG()
|
||||
self.faithfulness = Faithfulness()
|
||||
self.answer_relevancy = AnswerRelevancy()
|
||||
self.correctness = Correctness()
|
||||
|
||||
def calculate_all(
|
||||
self,
|
||||
question: str,
|
||||
retrieved_contexts: List[str],
|
||||
generated_answer: str,
|
||||
ground_truth_contexts: List[str],
|
||||
ground_truth_answer: str
|
||||
) -> Dict[str, float]:
|
||||
"""
|
||||
Calculate all metrics
|
||||
|
||||
Args:
|
||||
question: Question text
|
||||
retrieved_contexts: Retrieved context IDs/texts
|
||||
generated_answer: Generated answer
|
||||
ground_truth_contexts: Ground truth context IDs/texts
|
||||
ground_truth_answer: Ground truth answer
|
||||
|
||||
Returns:
|
||||
Dictionary of metric scores
|
||||
"""
|
||||
metrics = {}
|
||||
|
||||
# Retrieval metrics
|
||||
metrics['context_recall'] = self.context_recall.calculate(
|
||||
retrieved_contexts=retrieved_contexts,
|
||||
ground_truth_contexts=ground_truth_contexts
|
||||
)
|
||||
|
||||
metrics['context_precision'] = self.context_precision.calculate(
|
||||
retrieved_contexts=retrieved_contexts,
|
||||
ground_truth_contexts=ground_truth_contexts
|
||||
)
|
||||
|
||||
metrics['mrr'] = self.mrr.calculate(
|
||||
retrieved_contexts=retrieved_contexts,
|
||||
ground_truth_contexts=ground_truth_contexts
|
||||
)
|
||||
|
||||
metrics['ndcg'] = self.ndcg.calculate(
|
||||
retrieved_contexts=retrieved_contexts,
|
||||
ground_truth_contexts=ground_truth_contexts
|
||||
)
|
||||
|
||||
# Generation metrics
|
||||
metrics['faithfulness'] = self.faithfulness.calculate(
|
||||
question=question,
|
||||
answer=generated_answer,
|
||||
contexts=retrieved_contexts
|
||||
)
|
||||
|
||||
metrics['answer_relevancy'] = self.answer_relevancy.calculate(
|
||||
question=question,
|
||||
answer=generated_answer
|
||||
)
|
||||
|
||||
metrics['correctness'] = self.correctness.calculate(
|
||||
answer=generated_answer,
|
||||
ground_truth_answer=ground_truth_answer
|
||||
)
|
||||
|
||||
return metrics
|
||||
@@ -0,0 +1,372 @@
|
||||
"""
|
||||
Parallel execution module for RAG evaluation
|
||||
"""
|
||||
|
||||
from typing import List, Dict, Any, Optional, Callable
|
||||
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor, as_completed
|
||||
import threading
|
||||
from dataclasses import dataclass
|
||||
import time
|
||||
|
||||
|
||||
@dataclass
|
||||
class ParallelConfig:
|
||||
"""并行执行配置"""
|
||||
max_workers: int = 5 # 最大工作线程数
|
||||
use_processes: bool = False # 是否使用进程池(默认使用线程池)
|
||||
chunk_size: int = 1 # 每个任务处理的问题数量
|
||||
|
||||
|
||||
class ParallelExecutor:
|
||||
"""并行执行器,用于加速RAG评估"""
|
||||
|
||||
def __init__(self, config: ParallelConfig):
|
||||
"""
|
||||
初始化并行执行器
|
||||
|
||||
Args:
|
||||
config: 并行配置
|
||||
"""
|
||||
self.config = config
|
||||
self._lock = threading.Lock()
|
||||
self._results = []
|
||||
self._errors = []
|
||||
|
||||
def execute_tasks(
|
||||
self,
|
||||
tasks: List[Any],
|
||||
task_func: Callable,
|
||||
task_desc: str = "task"
|
||||
) -> List[Any]:
|
||||
"""
|
||||
并行执行任务列表
|
||||
|
||||
Args:
|
||||
tasks: 任务列表
|
||||
task_func: 任务执行函数,接收单个任务作为参数
|
||||
task_desc: 任务描述(用于日志)
|
||||
|
||||
Returns:
|
||||
结果列表
|
||||
"""
|
||||
if not tasks:
|
||||
return []
|
||||
|
||||
results = []
|
||||
errors = []
|
||||
|
||||
# 选择执行器类型
|
||||
executor_class = ProcessPoolExecutor if self.config.use_processes else ThreadPoolExecutor
|
||||
|
||||
with executor_class(max_workers=self.config.max_workers) as executor:
|
||||
# 提交所有任务
|
||||
future_to_task = {
|
||||
executor.submit(task_func, task): task
|
||||
for task in tasks
|
||||
}
|
||||
|
||||
# 收集结果
|
||||
for future in as_completed(future_to_task):
|
||||
task = future_to_task[future]
|
||||
try:
|
||||
result = future.result()
|
||||
results.append(result)
|
||||
except Exception as e:
|
||||
error_msg = f"Error processing {task_desc}: {str(e)}"
|
||||
errors.append({
|
||||
'task': task,
|
||||
'error': error_msg
|
||||
})
|
||||
|
||||
if errors:
|
||||
# 记录错误但不中断执行
|
||||
print(f"Warnings: {len(errors)} tasks failed:")
|
||||
for error in errors[:3]: # 只显示前3个错误
|
||||
print(f" - {error['error']}")
|
||||
|
||||
return results
|
||||
|
||||
def execute_evaluation_batch(
|
||||
self,
|
||||
evaluation_items: List[Dict[str, Any]],
|
||||
evaluate_func: Callable
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
批量并行执行评估任务
|
||||
|
||||
Args:
|
||||
evaluation_items: 评估项目列表,每个项目包含问题索引和问题数据
|
||||
evaluate_func: 评估函数
|
||||
|
||||
Returns:
|
||||
评估结果列表
|
||||
"""
|
||||
if not evaluation_items:
|
||||
return []
|
||||
|
||||
# 如果任务数量较少,使用串行执行
|
||||
if len(evaluation_items) <= 3:
|
||||
return [evaluate_func(item) for item in evaluation_items]
|
||||
|
||||
# 并行执行
|
||||
return self.execute_tasks(
|
||||
tasks=evaluation_items,
|
||||
task_func=evaluate_func,
|
||||
task_desc="evaluation"
|
||||
)
|
||||
|
||||
def execute_with_progress(
|
||||
self,
|
||||
tasks: List[Any],
|
||||
task_func: Callable,
|
||||
task_desc: str = "task",
|
||||
progress_callback: Optional[Callable] = None
|
||||
) -> List[Any]:
|
||||
"""
|
||||
带进度回调的并行执行
|
||||
|
||||
Args:
|
||||
tasks: 任务列表
|
||||
task_func: 任务执行函数
|
||||
task_desc: 任务描述
|
||||
progress_callback: 进度回调函数(current, total)
|
||||
|
||||
Returns:
|
||||
结果列表
|
||||
"""
|
||||
if not tasks:
|
||||
return []
|
||||
|
||||
total = len(tasks)
|
||||
completed = 0
|
||||
results = []
|
||||
errors = []
|
||||
|
||||
executor_class = ProcessPoolExecutor if self.config.use_processes else ThreadPoolExecutor
|
||||
|
||||
with executor_class(max_workers=self.config.max_workers) as executor:
|
||||
future_to_index = {
|
||||
executor.submit(task_func, task): idx
|
||||
for idx, task in enumerate(tasks)
|
||||
}
|
||||
|
||||
for future in as_completed(future_to_index):
|
||||
try:
|
||||
result = future.result()
|
||||
results.append(result)
|
||||
completed += 1
|
||||
|
||||
# 调用进度回调
|
||||
if progress_callback:
|
||||
progress_callback(completed, total)
|
||||
|
||||
except Exception as e:
|
||||
errors.append(str(e))
|
||||
completed += 1
|
||||
|
||||
if progress_callback:
|
||||
progress_callback(completed, total)
|
||||
|
||||
return results
|
||||
|
||||
|
||||
class BatchEvaluator:
|
||||
"""批量评估器,优化大量评估任务的执行"""
|
||||
|
||||
def __init__(self, parallel_config: Optional[ParallelConfig] = None):
|
||||
"""
|
||||
初始化批量评估器
|
||||
|
||||
Args:
|
||||
parallel_config: 并行配置(可选)
|
||||
"""
|
||||
self.config = parallel_config or ParallelConfig()
|
||||
self.executor = ParallelExecutor(self.config)
|
||||
|
||||
def evaluate_questions_batch(
|
||||
self,
|
||||
questions: List[Dict[str, Any]],
|
||||
evaluation_func: Callable,
|
||||
batch_size: Optional[int] = None
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
批量评估问题
|
||||
|
||||
Args:
|
||||
questions: 问题列表
|
||||
evaluation_func: 单个问题的评估函数
|
||||
batch_size: 批次大小(如果为None,使用配置中的chunk_size)
|
||||
|
||||
Returns:
|
||||
评估结果列表
|
||||
"""
|
||||
if not questions:
|
||||
return []
|
||||
|
||||
batch_size = batch_size or self.config.chunk_size
|
||||
|
||||
# 如果问题数量小于等于批次大小,直接并行执行
|
||||
if len(questions) <= batch_size:
|
||||
results = self.executor.execute_tasks(
|
||||
tasks=questions,
|
||||
task_func=evaluation_func,
|
||||
task_desc="question evaluation"
|
||||
)
|
||||
return results
|
||||
|
||||
# 分批执行
|
||||
all_results = []
|
||||
for i in range(0, len(questions), batch_size):
|
||||
batch = questions[i:i + batch_size]
|
||||
batch_results = self.executor.execute_tasks(
|
||||
tasks=batch,
|
||||
task_func=evaluation_func,
|
||||
task_desc=f"batch {i // batch_size + 1}"
|
||||
)
|
||||
all_results.extend(batch_results)
|
||||
|
||||
return all_results
|
||||
|
||||
def evaluate_with_retry(
|
||||
self,
|
||||
questions: List[Dict[str, Any]],
|
||||
evaluation_func: Callable,
|
||||
max_retries: int = 3
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
带重试机制的批量评估
|
||||
|
||||
Args:
|
||||
questions: 问题列表
|
||||
evaluation_func: 评估函数
|
||||
max_retries: 最大重试次数
|
||||
|
||||
Returns:
|
||||
评估结果列表
|
||||
"""
|
||||
results = []
|
||||
failed_items = []
|
||||
|
||||
# 首次尝试
|
||||
for question in questions:
|
||||
try:
|
||||
result = evaluation_func(question)
|
||||
results.append(result)
|
||||
except Exception as e:
|
||||
failed_items.append((question, e))
|
||||
|
||||
# 重试失败的项目
|
||||
for attempt in range(max_retries):
|
||||
if not failed_items:
|
||||
break
|
||||
|
||||
next_failed = []
|
||||
for question, original_error in failed_items:
|
||||
try:
|
||||
result = evaluation_func(question)
|
||||
results.append(result)
|
||||
except Exception as e:
|
||||
next_failed.append((question, e))
|
||||
|
||||
failed_items = next_failed
|
||||
|
||||
# 记录仍然失败的项目
|
||||
if failed_items:
|
||||
print(f"Warning: {len(failed_items)} items failed after {max_retries} retries")
|
||||
|
||||
return results
|
||||
|
||||
|
||||
def parallel_evaluator_wrapper(evaluation_id: str, question_data: Dict[str, Any],
|
||||
rag_adapter, metrics_calculator, db_manager):
|
||||
"""
|
||||
包装函数,用于进程池执行单个问题的评估
|
||||
|
||||
Args:
|
||||
evaluation_id: 评估ID
|
||||
question_data: 问题数据
|
||||
rag_adapter: RAG适配器
|
||||
metrics_calculator: 指标计算器
|
||||
db_manager: 数据库管理器
|
||||
|
||||
Returns:
|
||||
评估结果
|
||||
"""
|
||||
try:
|
||||
question_text = question_data['question']
|
||||
question_index = question_data['index']
|
||||
ground_truth = question_data.get('ground_truth', {})
|
||||
|
||||
# 执行RAG查询
|
||||
rag_result = rag_adapter.evaluate_question(question_text)
|
||||
|
||||
# 提取ground truth
|
||||
ground_truth_answer = ground_truth.get('answer', '')
|
||||
ground_truth_contexts = ground_truth.get('context', [])
|
||||
|
||||
# 计算指标
|
||||
retrieved_context_texts = rag_result['context_texts']
|
||||
generated_answer = rag_result['generated_answer']
|
||||
|
||||
metrics = metrics_calculator.calculate_all(
|
||||
question=question_text,
|
||||
retrieved_contexts=retrieved_context_texts,
|
||||
generated_answer=generated_answer,
|
||||
ground_truth_contexts=ground_truth_contexts,
|
||||
ground_truth_answer=ground_truth_answer
|
||||
)
|
||||
|
||||
# 保存到数据库
|
||||
from ..utils.helpers import generate_id, generate_biz_seq, generate_sys_seq
|
||||
result_id = generate_id("result")
|
||||
biz_seq = generate_biz_seq("RESULT")
|
||||
sys_seq = generate_sys_seq("RESULT")
|
||||
|
||||
sql = """
|
||||
INSERT INTO evaluation_results (
|
||||
id, biz_seq, sys_seq, evaluation_id, question_index, question_text,
|
||||
context_recall, context_precision, mrr, ndcg,
|
||||
faithfulness, answer_relevancy, correctness,
|
||||
retrieved_contexts, generated_answer, ground_truth_answer, ground_truth_context,
|
||||
retrieval_time_ms, generation_time_ms, create_time
|
||||
) VALUES (
|
||||
%s, %s, %s, %s, %s, %s,
|
||||
%s, %s, %s, %s,
|
||||
%s, %s, %s,
|
||||
%s, %s, %s, %s,
|
||||
%s, %s, %s
|
||||
)
|
||||
"""
|
||||
|
||||
import json
|
||||
from datetime import datetime
|
||||
|
||||
now = datetime.now()
|
||||
db_manager.execute_update(
|
||||
sql,
|
||||
(
|
||||
result_id, biz_seq, sys_seq, evaluation_id, question_index, question_text,
|
||||
metrics['context_recall'], metrics['context_precision'],
|
||||
metrics['mrr'], metrics['ndcg'],
|
||||
metrics['faithfulness'], metrics['answer_relevancy'], metrics['correctness'],
|
||||
json.dumps(rag_result['retrieved_contexts']),
|
||||
generated_answer, ground_truth_answer,
|
||||
json.dumps(ground_truth_contexts),
|
||||
rag_result['retrieval_time_ms'], rag_result['generation_time_ms'],
|
||||
now
|
||||
)
|
||||
)
|
||||
|
||||
return {
|
||||
'result_id': result_id,
|
||||
'question_index': question_index,
|
||||
'metrics': metrics
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
# 返回错误信息
|
||||
return {
|
||||
'question_index': question_data.get('index', -1),
|
||||
'error': str(e),
|
||||
'metrics': None
|
||||
}
|
||||
@@ -0,0 +1,479 @@
|
||||
"""
|
||||
RAG system interface adapters
|
||||
"""
|
||||
|
||||
from typing import List, Dict, Any, Optional, Callable
|
||||
from abc import ABC, abstractmethod
|
||||
import time
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
|
||||
# 配置日志
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class RetryConfig:
|
||||
"""重试配置"""
|
||||
max_retries: int = 3
|
||||
initial_delay: float = 1.0 # 初始延迟(秒)
|
||||
max_delay: float = 60.0 # 最大延迟(秒)
|
||||
exponential_base: float = 2.0 # 指数退避基数
|
||||
timeout: int = 30 # 请求超时(秒)
|
||||
|
||||
|
||||
def retry_with_exponential_backoff(
|
||||
func: Callable,
|
||||
retry_config: RetryConfig,
|
||||
*args,
|
||||
**kwargs
|
||||
) -> Any:
|
||||
"""
|
||||
使用指数退避策略重试函数
|
||||
|
||||
Args:
|
||||
func: 要重试的函数
|
||||
retry_config: 重试配置
|
||||
*args: 函数参数
|
||||
**kwargs: 函数关键字参数
|
||||
|
||||
Returns:
|
||||
函数返回值
|
||||
|
||||
Raises:
|
||||
最后一次尝试的异常
|
||||
"""
|
||||
last_exception = None
|
||||
delay = retry_config.initial_delay
|
||||
|
||||
for attempt in range(retry_config.max_retries + 1):
|
||||
try:
|
||||
return func(*args, **kwargs)
|
||||
except Exception as e:
|
||||
last_exception = e
|
||||
if attempt < retry_config.max_retries:
|
||||
logger.warning(
|
||||
f"Attempt {attempt + 1}/{retry_config.max_retries + 1} failed: {e}. "
|
||||
f"Retrying in {delay:.1f}s..."
|
||||
)
|
||||
time.sleep(delay)
|
||||
delay = min(delay * retry_config.exponential_base, retry_config.max_delay)
|
||||
else:
|
||||
logger.error(f"All {retry_config.max_retries + 1} attempts failed: {e}")
|
||||
|
||||
raise last_exception
|
||||
|
||||
|
||||
class RAGRetriever(ABC):
|
||||
"""Abstract base class for RAG retrieval interface"""
|
||||
|
||||
@abstractmethod
|
||||
def retrieve(self, query: str, top_k: int = 5) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Retrieve relevant contexts for a query
|
||||
|
||||
Args:
|
||||
query: Query text
|
||||
top_k: Number of contexts to retrieve
|
||||
|
||||
Returns:
|
||||
List of retrieved contexts with metadata
|
||||
Each context should have:
|
||||
- content: str (the text content)
|
||||
- score: float (relevance score)
|
||||
- metadata: dict (source, chunk_id, etc.)
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
class RAGGenerator(ABC):
|
||||
"""Abstract base class for RAG generation interface"""
|
||||
|
||||
@abstractmethod
|
||||
def generate(self, query: str, contexts: List[str]) -> str:
|
||||
"""
|
||||
Generate answer based on query and contexts
|
||||
|
||||
Args:
|
||||
query: Query text
|
||||
contexts: List of context strings
|
||||
|
||||
Returns:
|
||||
Generated answer text
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
class HTTPRAGRetriever(RAGRetriever):
|
||||
"""HTTP-based RAG retriever with retry and timeout support"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
endpoint: str,
|
||||
api_key: Optional[str] = None,
|
||||
retry_config: Optional[RetryConfig] = None
|
||||
):
|
||||
"""
|
||||
Initialize HTTP RAG retriever
|
||||
|
||||
Args:
|
||||
endpoint: RAG retrieval API endpoint
|
||||
api_key: Optional API key for authentication
|
||||
retry_config: Optional retry configuration
|
||||
"""
|
||||
self.endpoint = endpoint
|
||||
self.api_key = api_key
|
||||
self.retry_config = retry_config or RetryConfig()
|
||||
self._stats = {
|
||||
'total_requests': 0,
|
||||
'successful_requests': 0,
|
||||
'failed_requests': 0,
|
||||
'total_latency_ms': 0
|
||||
}
|
||||
|
||||
def retrieve(self, query: str, top_k: int = 5) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Retrieve contexts via HTTP API with retry
|
||||
|
||||
Args:
|
||||
query: Query text
|
||||
top_k: Number of contexts to retrieve
|
||||
|
||||
Returns:
|
||||
List of retrieved contexts
|
||||
"""
|
||||
self._stats['total_requests'] += 1
|
||||
|
||||
def _do_retrieve():
|
||||
import requests
|
||||
|
||||
headers = {}
|
||||
if self.api_key:
|
||||
headers['Authorization'] = f'Bearer {self.api_key}'
|
||||
|
||||
logger.info(f"Retrieving contexts for query: {query[:50]}...")
|
||||
start_time = time.time()
|
||||
|
||||
response = requests.post(
|
||||
self.endpoint,
|
||||
json={'query': query, 'top_k': top_k},
|
||||
headers=headers,
|
||||
timeout=self.retry_config.timeout
|
||||
)
|
||||
response.raise_for_status()
|
||||
|
||||
latency_ms = int((time.time() - start_time) * 1000)
|
||||
self._stats['total_latency_ms'] += latency_ms
|
||||
logger.info(f"Retrieval completed in {latency_ms}ms")
|
||||
|
||||
data = response.json()
|
||||
contexts = data.get('contexts', [])
|
||||
|
||||
self._stats['successful_requests'] += 1
|
||||
return contexts
|
||||
|
||||
try:
|
||||
return retry_with_exponential_backoff(
|
||||
_do_retrieve,
|
||||
self.retry_config
|
||||
)
|
||||
except Exception as e:
|
||||
self._stats['failed_requests'] += 1
|
||||
logger.error(f"Retrieval failed after all retries: {e}")
|
||||
return []
|
||||
|
||||
def get_stats(self) -> Dict[str, Any]:
|
||||
"""
|
||||
获取统计信息
|
||||
|
||||
Returns:
|
||||
统计信息字典
|
||||
"""
|
||||
stats = self._stats.copy()
|
||||
if stats['successful_requests'] > 0:
|
||||
stats['avg_latency_ms'] = stats['total_latency_ms'] / stats['successful_requests']
|
||||
else:
|
||||
stats['avg_latency_ms'] = 0
|
||||
return stats
|
||||
|
||||
|
||||
class HTTPRAGGenerator(RAGGenerator):
|
||||
"""HTTP-based RAG generator with retry and timeout support"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
endpoint: str,
|
||||
api_key: Optional[str] = None,
|
||||
retry_config: Optional[RetryConfig] = None
|
||||
):
|
||||
"""
|
||||
Initialize HTTP RAG generator
|
||||
|
||||
Args:
|
||||
endpoint: RAG generation API endpoint
|
||||
api_key: Optional API key for authentication
|
||||
retry_config: Optional retry configuration
|
||||
"""
|
||||
self.endpoint = endpoint
|
||||
self.api_key = api_key
|
||||
self.retry_config = retry_config or RetryConfig(timeout=60) # 生成需要更长超时
|
||||
self._stats = {
|
||||
'total_requests': 0,
|
||||
'successful_requests': 0,
|
||||
'failed_requests': 0,
|
||||
'total_latency_ms': 0
|
||||
}
|
||||
|
||||
def generate(self, query: str, contexts: List[str]) -> str:
|
||||
"""
|
||||
Generate answer via HTTP API with retry
|
||||
|
||||
Args:
|
||||
query: Query text
|
||||
contexts: List of context strings
|
||||
|
||||
Returns:
|
||||
Generated answer
|
||||
"""
|
||||
self._stats['total_requests'] += 1
|
||||
|
||||
def _do_generate():
|
||||
import requests
|
||||
|
||||
headers = {}
|
||||
if self.api_key:
|
||||
headers['Authorization'] = f'Bearer {self.api_key}'
|
||||
|
||||
logger.info(f"Generating answer for query: {query[:50]}...")
|
||||
start_time = time.time()
|
||||
|
||||
response = requests.post(
|
||||
self.endpoint,
|
||||
json={'query': query, 'contexts': contexts},
|
||||
headers=headers,
|
||||
timeout=self.retry_config.timeout
|
||||
)
|
||||
response.raise_for_status()
|
||||
|
||||
latency_ms = int((time.time() - start_time) * 1000)
|
||||
self._stats['total_latency_ms'] += latency_ms
|
||||
logger.info(f"Generation completed in {latency_ms}ms")
|
||||
|
||||
data = response.json()
|
||||
answer = data.get('answer', '')
|
||||
|
||||
self._stats['successful_requests'] += 1
|
||||
return answer
|
||||
|
||||
try:
|
||||
return retry_with_exponential_backoff(
|
||||
_do_generate,
|
||||
self.retry_config
|
||||
)
|
||||
except Exception as e:
|
||||
self._stats['failed_requests'] += 1
|
||||
logger.error(f"Generation failed after all retries: {e}")
|
||||
return ""
|
||||
|
||||
def get_stats(self) -> Dict[str, Any]:
|
||||
"""
|
||||
获取统计信息
|
||||
|
||||
Returns:
|
||||
统计信息字典
|
||||
"""
|
||||
stats = self._stats.copy()
|
||||
if stats['successful_requests'] > 0:
|
||||
stats['avg_latency_ms'] = stats['total_latency_ms'] / stats['successful_requests']
|
||||
else:
|
||||
stats['avg_latency_ms'] = 0
|
||||
return stats
|
||||
|
||||
|
||||
class MockRAGRetriever(RAGRetriever):
|
||||
"""Mock RAG retriever for testing"""
|
||||
|
||||
def __init__(self, documents: Optional[List[str]] = None):
|
||||
"""
|
||||
Initialize mock retriever
|
||||
|
||||
Args:
|
||||
documents: Optional list of documents to retrieve from
|
||||
"""
|
||||
self.documents = documents or [
|
||||
"This is a sample document about RAG systems.",
|
||||
"RAG combines retrieval and generation for better answers.",
|
||||
"Evaluation is important for RAG system quality."
|
||||
]
|
||||
|
||||
def retrieve(self, query: str, top_k: int = 5) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Mock retrieval - returns first top_k documents
|
||||
|
||||
Args:
|
||||
query: Query text (not used in mock)
|
||||
top_k: Number of contexts to retrieve
|
||||
|
||||
Returns:
|
||||
List of mock contexts
|
||||
"""
|
||||
contexts = []
|
||||
for i, doc in enumerate(self.documents[:top_k]):
|
||||
contexts.append({
|
||||
'content': doc,
|
||||
'score': 1.0 - (i * 0.1), # Decreasing scores
|
||||
'metadata': {
|
||||
'source': f'mock_doc_{i}',
|
||||
'chunk_id': i
|
||||
}
|
||||
})
|
||||
return contexts
|
||||
|
||||
|
||||
class MockRAGGenerator(RAGGenerator):
|
||||
"""Mock RAG generator for testing"""
|
||||
|
||||
def generate(self, query: str, contexts: List[str]) -> str:
|
||||
"""
|
||||
Mock generation - returns simple concatenation
|
||||
|
||||
Args:
|
||||
query: Query text
|
||||
contexts: List of context strings
|
||||
|
||||
Returns:
|
||||
Mock generated answer
|
||||
"""
|
||||
if not contexts:
|
||||
return f"Mock answer for: {query}"
|
||||
|
||||
# Simple mock: combine query and first context
|
||||
return f"Based on the context, the answer to '{query}' is: {contexts[0][:100]}..."
|
||||
|
||||
|
||||
class RAGEvaluationAdapter:
|
||||
"""Adapter for RAG system evaluation with performance monitoring"""
|
||||
|
||||
def __init__(self, retriever: RAGRetriever, generator: RAGGenerator):
|
||||
"""
|
||||
Initialize RAG evaluation adapter
|
||||
|
||||
Args:
|
||||
retriever: RAG retriever instance
|
||||
generator: RAG generator instance
|
||||
"""
|
||||
self.retriever = retriever
|
||||
self.generator = generator
|
||||
self._stats = {
|
||||
'total_evaluations': 0,
|
||||
'successful_evaluations': 0,
|
||||
'failed_evaluations': 0,
|
||||
'total_retrieval_time_ms': 0,
|
||||
'total_generation_time_ms': 0
|
||||
}
|
||||
|
||||
def evaluate_question(self, question: str, top_k: int = 5) -> Dict[str, Any]:
|
||||
"""
|
||||
Evaluate a single question through RAG pipeline
|
||||
|
||||
Args:
|
||||
question: Question text
|
||||
top_k: Number of contexts to retrieve
|
||||
|
||||
Returns:
|
||||
Dictionary with retrieval and generation results
|
||||
"""
|
||||
self._stats['total_evaluations'] += 1
|
||||
|
||||
try:
|
||||
# Measure retrieval time
|
||||
retrieval_start = time.time()
|
||||
retrieved_contexts = self.retriever.retrieve(question, top_k)
|
||||
retrieval_time_ms = int((time.time() - retrieval_start) * 1000)
|
||||
self._stats['total_retrieval_time_ms'] += retrieval_time_ms
|
||||
|
||||
# Extract context texts
|
||||
context_texts = [ctx['content'] for ctx in retrieved_contexts]
|
||||
|
||||
# Measure generation time
|
||||
generation_start = time.time()
|
||||
generated_answer = self.generator.generate(question, context_texts)
|
||||
generation_time_ms = int((time.time() - generation_start) * 1000)
|
||||
self._stats['total_generation_time_ms'] += generation_time_ms
|
||||
|
||||
self._stats['successful_evaluations'] += 1
|
||||
|
||||
logger.info(
|
||||
f"Evaluation completed - Retrieval: {retrieval_time_ms}ms, "
|
||||
f"Generation: {generation_time_ms}ms"
|
||||
)
|
||||
|
||||
return {
|
||||
'question': question,
|
||||
'retrieved_contexts': retrieved_contexts,
|
||||
'context_texts': context_texts,
|
||||
'generated_answer': generated_answer,
|
||||
'retrieval_time_ms': retrieval_time_ms,
|
||||
'generation_time_ms': generation_time_ms
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
self._stats['failed_evaluations'] += 1
|
||||
logger.error(f"Evaluation failed for question '{question[:50]}...': {e}")
|
||||
raise
|
||||
|
||||
def get_stats(self) -> Dict[str, Any]:
|
||||
"""
|
||||
获取评估统计信息
|
||||
|
||||
Returns:
|
||||
统计信息字典
|
||||
"""
|
||||
stats = self._stats.copy()
|
||||
|
||||
if stats['successful_evaluations'] > 0:
|
||||
stats['avg_retrieval_time_ms'] = (
|
||||
stats['total_retrieval_time_ms'] / stats['successful_evaluations']
|
||||
)
|
||||
stats['avg_generation_time_ms'] = (
|
||||
stats['total_generation_time_ms'] / stats['successful_evaluations']
|
||||
)
|
||||
stats['avg_total_time_ms'] = (
|
||||
stats['avg_retrieval_time_ms'] + stats['avg_generation_time_ms']
|
||||
)
|
||||
else:
|
||||
stats['avg_retrieval_time_ms'] = 0
|
||||
stats['avg_generation_time_ms'] = 0
|
||||
stats['avg_total_time_ms'] = 0
|
||||
|
||||
# 添加子组件统计
|
||||
if hasattr(self.retriever, 'get_stats'):
|
||||
stats['retriever_stats'] = self.retriever.get_stats()
|
||||
if hasattr(self.generator, 'get_stats'):
|
||||
stats['generator_stats'] = self.generator.get_stats()
|
||||
|
||||
return stats
|
||||
|
||||
def reset_stats(self) -> None:
|
||||
"""重置统计信息"""
|
||||
self._stats = {
|
||||
'total_evaluations': 0,
|
||||
'successful_evaluations': 0,
|
||||
'failed_evaluations': 0,
|
||||
'total_retrieval_time_ms': 0,
|
||||
'total_generation_time_ms': 0
|
||||
}
|
||||
if hasattr(self.retriever, '_stats'):
|
||||
self.retriever._stats = {
|
||||
'total_requests': 0,
|
||||
'successful_requests': 0,
|
||||
'failed_requests': 0,
|
||||
'total_latency_ms': 0
|
||||
}
|
||||
if hasattr(self.generator, '_stats'):
|
||||
self.generator._stats = {
|
||||
'total_requests': 0,
|
||||
'successful_requests': 0,
|
||||
'failed_requests': 0,
|
||||
'total_latency_ms': 0
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
"""
|
||||
Example usage of RAG Evaluation Framework
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
# Add parent directory to path for imports
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent))
|
||||
|
||||
from rag_evaluation.core.config import Config
|
||||
from rag_evaluation.testset.generator import TestsetGenerator
|
||||
from rag_evaluation.storage.database import DatabaseManager
|
||||
|
||||
|
||||
def main():
|
||||
"""Main example function"""
|
||||
|
||||
# 1. Load configuration
|
||||
print("Loading configuration...")
|
||||
|
||||
# Try to load config.yaml first, fallback to config.example.yaml
|
||||
config_file = "config.yaml"
|
||||
if not Path(config_file).exists():
|
||||
if Path("config.example.yaml").exists():
|
||||
print("Note: config.yaml not found, using config.example.yaml")
|
||||
config_file = "config.example.yaml"
|
||||
else:
|
||||
raise FileNotFoundError(
|
||||
"Configuration file not found. "
|
||||
"Please create config.yaml from config.example.yaml"
|
||||
)
|
||||
|
||||
config = Config.from_file(config_file)
|
||||
|
||||
# 2. Initialize database
|
||||
print("Initializing database...")
|
||||
db_manager = DatabaseManager(config.database)
|
||||
|
||||
# Initialize schema (only needed once)
|
||||
schema_file = Path(__file__).parent / "storage" / "schema.sql"
|
||||
try:
|
||||
db_manager.init_schema(str(schema_file))
|
||||
print("Database schema initialized successfully")
|
||||
except Exception as e:
|
||||
print(f"Database initialization error (may already exist): {e}")
|
||||
|
||||
# 3. Generate testset
|
||||
print("\nGenerating testset...")
|
||||
generator = TestsetGenerator(config)
|
||||
|
||||
# Example: Generate testset from sample files
|
||||
knowledge_base_id = "kb-example-001"
|
||||
file_paths = [
|
||||
# Add your knowledge base file paths here
|
||||
# Example: "./data/docs/manual.txt"
|
||||
]
|
||||
|
||||
if not file_paths:
|
||||
print("No files specified. Creating sample file...")
|
||||
# Create a sample file for demonstration
|
||||
sample_dir = Path("./data/sample_docs")
|
||||
sample_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
sample_file = sample_dir / "sample.txt"
|
||||
with open(sample_file, 'w', encoding='utf-8') as f:
|
||||
f.write("""
|
||||
# Sample Knowledge Base Document
|
||||
|
||||
This is a sample document for RAG evaluation.
|
||||
|
||||
## Section 1: Introduction
|
||||
RAG (Retrieval-Augmented Generation) systems combine retrieval and generation
|
||||
to provide accurate and contextual answers.
|
||||
|
||||
## Section 2: Evaluation
|
||||
Evaluating RAG systems requires measuring both retrieval quality and generation quality.
|
||||
|
||||
Key metrics include:
|
||||
- Context Recall: How well the system retrieves relevant context
|
||||
- Context Precision: How precise the retrieved context is
|
||||
- Faithfulness: Whether the generated answer is faithful to the context
|
||||
- Answer Relevancy: How relevant the answer is to the question
|
||||
""")
|
||||
|
||||
file_paths = [str(sample_file)]
|
||||
print(f"Created sample file: {sample_file}")
|
||||
|
||||
# Generate testset
|
||||
testset = generator.generate(
|
||||
knowledge_base_id=knowledge_base_id,
|
||||
file_paths=file_paths,
|
||||
test_size=15,
|
||||
name="Example Testset"
|
||||
)
|
||||
|
||||
print(f"\nTestset generated:")
|
||||
print(f" ID: {testset['id']}")
|
||||
print(f" Name: {testset['name']}")
|
||||
print(f" Questions: {len(testset['questions'])}")
|
||||
|
||||
# 4. Save testset
|
||||
print("\nSaving testset...")
|
||||
file_path = generator.save_testset(testset)
|
||||
print(f"Testset saved to: {file_path}")
|
||||
|
||||
# 5. Load testset (demonstration)
|
||||
print("\nLoading testset...")
|
||||
loaded_testset = generator.load_testset(testset['id'])
|
||||
print(f"Testset loaded: {loaded_testset['name']}")
|
||||
|
||||
print("\n✅ Example completed successfully!")
|
||||
print("\nNext steps:")
|
||||
print("1. Configure your LLM API keys in config.yaml")
|
||||
print("2. Add your knowledge base files")
|
||||
print("3. Run evaluation (Phase 2 - coming soon)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,189 @@
|
||||
"""
|
||||
Example usage of RAG Evaluation Framework - Phase 2
|
||||
Demonstrates evaluation execution with mock RAG system
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# Add parent directory to path for imports
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent))
|
||||
|
||||
from rag_evaluation.core.config import Config
|
||||
from rag_evaluation.testset.generator import TestsetGenerator
|
||||
from rag_evaluation.storage.database import DatabaseManager
|
||||
from rag_evaluation.evaluation import (
|
||||
MockRAGRetriever,
|
||||
MockRAGGenerator,
|
||||
RAGEvaluationAdapter,
|
||||
EvaluationExecutor
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
"""Main example function for Phase 2"""
|
||||
|
||||
print("=" * 60)
|
||||
print("RAG Evaluation Framework - Phase 2 Example")
|
||||
print("=" * 60)
|
||||
|
||||
# 1. Load configuration
|
||||
print("\n[1/6] Loading configuration...")
|
||||
|
||||
# Try to load config.yaml first, fallback to config.example.yaml
|
||||
config_file = "config.yaml"
|
||||
if not Path(config_file).exists():
|
||||
if Path("config.example.yaml").exists():
|
||||
print(" Note: config.yaml not found, using config.example.yaml")
|
||||
config_file = "config.example.yaml"
|
||||
else:
|
||||
raise FileNotFoundError(
|
||||
"Configuration file not found. "
|
||||
"Please create config.yaml from config.example.yaml"
|
||||
)
|
||||
|
||||
config = Config.from_file(config_file)
|
||||
print("✓ Configuration loaded")
|
||||
|
||||
# 2. Initialize database
|
||||
print("\n[2/6] Initializing database...")
|
||||
db_manager = DatabaseManager(config.database)
|
||||
|
||||
try:
|
||||
schema_file = Path(__file__).parent / "storage" / "schema.sql"
|
||||
db_manager.init_schema(str(schema_file))
|
||||
print("✓ Database schema initialized")
|
||||
except Exception as e:
|
||||
print(f"⚠ Database may already be initialized: {e}")
|
||||
|
||||
# 3. Generate or load testset
|
||||
print("\n[3/6] Generating testset...")
|
||||
generator = TestsetGenerator(config)
|
||||
|
||||
# Create sample documents
|
||||
sample_dir = Path("./data/sample_docs")
|
||||
sample_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
sample_file = sample_dir / "rag_guide.txt"
|
||||
with open(sample_file, 'w', encoding='utf-8') as f:
|
||||
f.write("""
|
||||
# RAG System Guide
|
||||
|
||||
## What is RAG?
|
||||
RAG (Retrieval-Augmented Generation) combines information retrieval with text generation.
|
||||
It retrieves relevant documents and uses them to generate accurate answers.
|
||||
|
||||
## Key Components
|
||||
1. Retriever: Finds relevant documents from a knowledge base
|
||||
2. Generator: Creates answers based on retrieved documents
|
||||
3. Knowledge Base: Collection of documents to search
|
||||
|
||||
## Evaluation Metrics
|
||||
- Context Recall: How well relevant documents are retrieved
|
||||
- Context Precision: How precise the retrieved documents are
|
||||
- Faithfulness: Whether answers are faithful to the context
|
||||
- Answer Relevancy: How relevant answers are to questions
|
||||
- Correctness: How correct answers are compared to ground truth
|
||||
""")
|
||||
|
||||
knowledge_base_id = "kb-phase2-demo"
|
||||
testset = generator.generate(
|
||||
knowledge_base_id=knowledge_base_id,
|
||||
file_paths=[str(sample_file)],
|
||||
test_size=5, # Small testset for demo
|
||||
name="Phase 2 Demo Testset"
|
||||
)
|
||||
|
||||
testset_file = generator.save_testset(testset)
|
||||
print(f"✓ Testset generated: {testset['id']}")
|
||||
print(f" - Questions: {len(testset['questions'])}")
|
||||
print(f" - Saved to: {testset_file}")
|
||||
|
||||
# 4. Set up RAG system (using mock for demo)
|
||||
print("\n[4/6] Setting up RAG system...")
|
||||
|
||||
# Create mock RAG components
|
||||
mock_documents = [
|
||||
"RAG combines retrieval and generation for better answers.",
|
||||
"The retriever finds relevant documents from the knowledge base.",
|
||||
"The generator creates answers based on retrieved context.",
|
||||
"Evaluation metrics measure both retrieval and generation quality.",
|
||||
"Context recall measures how well relevant documents are retrieved."
|
||||
]
|
||||
|
||||
retriever = MockRAGRetriever(documents=mock_documents)
|
||||
generator = MockRAGGenerator()
|
||||
rag_adapter = RAGEvaluationAdapter(retriever, generator)
|
||||
|
||||
print("✓ Mock RAG system initialized")
|
||||
print(" - Retriever: MockRAGRetriever")
|
||||
print(" - Generator: MockRAGGenerator")
|
||||
|
||||
# 5. Execute evaluation
|
||||
print("\n[5/6] Executing evaluation...")
|
||||
|
||||
executor = EvaluationExecutor(
|
||||
config=config,
|
||||
rag_adapter=rag_adapter,
|
||||
db_manager=db_manager
|
||||
)
|
||||
|
||||
evaluation_id = executor.execute_evaluation(
|
||||
testset_id=testset['id'],
|
||||
knowledge_base_id=knowledge_base_id,
|
||||
testset=testset
|
||||
)
|
||||
|
||||
print(f"✓ Evaluation completed: {evaluation_id}")
|
||||
|
||||
# 6. Display results
|
||||
print("\n[6/6] Evaluation Results")
|
||||
print("-" * 60)
|
||||
|
||||
# Get summary
|
||||
summary = executor.get_evaluation_summary(evaluation_id)
|
||||
|
||||
print(f"\n📊 Overall Score: {summary['overall_score']:.2f}/100")
|
||||
print(f"\n📈 Retrieval Metrics:")
|
||||
print(f" - Context Recall: {summary['avg_context_recall']:.3f}")
|
||||
print(f" - Context Precision: {summary['avg_context_precision']:.3f}")
|
||||
print(f" - MRR: {summary['avg_mrr']:.3f}")
|
||||
print(f" - NDCG: {summary['avg_ndcg']:.3f}")
|
||||
|
||||
print(f"\n📝 Generation Metrics:")
|
||||
print(f" - Faithfulness: {summary['avg_faithfulness']:.3f}")
|
||||
print(f" - Answer Relevancy: {summary['avg_answer_relevancy']:.3f}")
|
||||
print(f" - Correctness: {summary['avg_correctness']:.3f}")
|
||||
|
||||
print(f"\n📋 Statistics:")
|
||||
print(f" - Total Questions: {summary['total_questions']}")
|
||||
print(f" - Failed Questions: {summary['failed_questions']}")
|
||||
|
||||
# Get detailed results
|
||||
results = executor.get_evaluation_results(evaluation_id)
|
||||
|
||||
print(f"\n🔍 Sample Question Results:")
|
||||
for i, result in enumerate(results[:2], 1): # Show first 2
|
||||
print(f"\n Question {i}: {result['question_text'][:60]}...")
|
||||
print(f" Recall: {result['context_recall']:.3f} | "
|
||||
f"Precision: {result['context_precision']:.3f} | "
|
||||
f"Faithfulness: {result['faithfulness']:.3f}")
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("✅ Phase 2 Example Completed Successfully!")
|
||||
print("=" * 60)
|
||||
|
||||
print("\n📚 Next Steps:")
|
||||
print("1. Replace MockRAG with your actual RAG system")
|
||||
print("2. Use HTTPRAGRetriever/Generator for HTTP APIs")
|
||||
print("3. Integrate real RAGAS metrics for better accuracy")
|
||||
print("4. Move to Phase 3 for report generation")
|
||||
|
||||
print(f"\n💾 Data saved to database:")
|
||||
print(f" - Evaluation ID: {evaluation_id}")
|
||||
print(f" - Testset ID: {testset['id']}")
|
||||
print(f" - Results: {len(results)} questions evaluated")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,274 @@
|
||||
"""
|
||||
Phase 3 功能演示: 报告可视化和历史趋势分析
|
||||
|
||||
本示例展示如何使用:
|
||||
1. 报告可视化 (HTML报告和图表)
|
||||
2. 历史数据存储
|
||||
3. 趋势分析
|
||||
4. 性能回归检测
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
sys.path.insert(0, os.path.dirname(__file__))
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from report.aggregator import ResultAggregator, EvaluationSummary, MetricStats
|
||||
from report.generator import ReportGenerator
|
||||
from report.visualizer import ReportVisualizer
|
||||
|
||||
|
||||
def demo_visualization():
|
||||
"""演示报告可视化功能"""
|
||||
print("=" * 60)
|
||||
print("演示 1: 报告可视化")
|
||||
print("=" * 60)
|
||||
|
||||
# 创建测试数据
|
||||
summary = EvaluationSummary(
|
||||
evaluation_id="eval-demo-001",
|
||||
knowledge_base_id="kb-demo",
|
||||
testset_id="ts-demo",
|
||||
total_questions=20,
|
||||
successful_questions=18,
|
||||
failed_questions=2,
|
||||
overall_score=82.5,
|
||||
metric_stats={
|
||||
'context_recall': MetricStats(
|
||||
name='context_recall',
|
||||
mean=0.85,
|
||||
median=0.87,
|
||||
std_dev=0.12,
|
||||
min=0.60,
|
||||
max=0.98,
|
||||
count=18,
|
||||
pass_rate=0.83
|
||||
),
|
||||
'context_precision': MetricStats(
|
||||
name='context_precision',
|
||||
mean=0.82,
|
||||
median=0.84,
|
||||
std_dev=0.10,
|
||||
min=0.65,
|
||||
max=0.95,
|
||||
count=18,
|
||||
pass_rate=0.78
|
||||
),
|
||||
'faithfulness': MetricStats(
|
||||
name='faithfulness',
|
||||
mean=0.88,
|
||||
median=0.90,
|
||||
std_dev=0.08,
|
||||
min=0.70,
|
||||
max=0.98,
|
||||
count=18,
|
||||
pass_rate=0.89
|
||||
),
|
||||
'answer_relevancy': MetricStats(
|
||||
name='answer_relevancy',
|
||||
mean=0.80,
|
||||
median=0.82,
|
||||
std_dev=0.11,
|
||||
min=0.60,
|
||||
max=0.95,
|
||||
count=18,
|
||||
pass_rate=0.72
|
||||
)
|
||||
},
|
||||
avg_retrieval_time_ms=180.5,
|
||||
avg_generation_time_ms=850.3,
|
||||
created_at=datetime.now()
|
||||
)
|
||||
|
||||
# 创建测试结果
|
||||
results = [
|
||||
{
|
||||
'question_index': i,
|
||||
'question_text': f'测试问题 {i+1}',
|
||||
'metrics': {
|
||||
'context_recall': 0.85 + (i % 3) * 0.05,
|
||||
'context_precision': 0.82 + (i % 3) * 0.04,
|
||||
'faithfulness': 0.88 + (i % 3) * 0.03,
|
||||
'answer_relevancy': 0.80 + (i % 3) * 0.05
|
||||
},
|
||||
'retrieval_time_ms': 180 + i * 5,
|
||||
'generation_time_ms': 850 + i * 10,
|
||||
'metadata': {'source': f'doc{i % 3 + 1}.pdf'}
|
||||
}
|
||||
for i in range(18)
|
||||
] + [
|
||||
{
|
||||
'question_index': 18,
|
||||
'question_text': '失败问题 1',
|
||||
'metrics': None,
|
||||
'error': 'Evaluation timeout'
|
||||
},
|
||||
{
|
||||
'question_index': 19,
|
||||
'question_text': '失败问题 2',
|
||||
'metrics': {
|
||||
'context_recall': 0.3,
|
||||
'context_precision': 0.35,
|
||||
'faithfulness': 0.4,
|
||||
'answer_relevancy': 0.38
|
||||
},
|
||||
'retrieval_time_ms': 250,
|
||||
'generation_time_ms': 1200
|
||||
}
|
||||
]
|
||||
|
||||
# 生成HTML报告
|
||||
try:
|
||||
visualizer = ReportVisualizer()
|
||||
output_path = 'demo_report.html'
|
||||
|
||||
visualizer.generate_html_report(
|
||||
summary,
|
||||
results,
|
||||
output_path,
|
||||
include_charts=True
|
||||
)
|
||||
|
||||
print(f"[OK] HTML报告已生成: {output_path}")
|
||||
print(f" - 包含雷达图、柱状图、饼图")
|
||||
print(f" - 整体评分: {summary.overall_score}")
|
||||
print(f" - 成功率: {summary.successful_questions}/{summary.total_questions}")
|
||||
|
||||
except ImportError as e:
|
||||
print(f"[ERROR] 无法生成可视化报告: {e}")
|
||||
print(" 请安装 plotly: pip install plotly>=5.18.0")
|
||||
|
||||
print()
|
||||
|
||||
|
||||
def demo_history_and_trend():
|
||||
"""演示历史数据和趋势分析功能"""
|
||||
print("=" * 60)
|
||||
print("演示 2: 历史数据存储和趋势分析")
|
||||
print("=" * 60)
|
||||
|
||||
# 注意: 这个演示需要数据库连接
|
||||
# 实际使用时需要配置数据库
|
||||
print("历史数据存储功能:")
|
||||
print(" - HistoryManager.save_evaluation_history() - 保存评估历史")
|
||||
print(" - HistoryManager.get_history_by_knowledge_base() - 获取知识库历史")
|
||||
print(" - HistoryManager.get_metric_trend() - 获取指标趋势")
|
||||
print()
|
||||
|
||||
print("趋势分析功能:")
|
||||
print(" - TrendAnalyzer.compare_with_baseline() - 与基线对比")
|
||||
print(" - TrendAnalyzer.analyze_trend() - 分析指标趋势")
|
||||
print(" - TrendAnalyzer.detect_regression() - 检测性能回归")
|
||||
print(" - TrendAnalyzer.generate_trend_summary() - 生成趋势摘要")
|
||||
print()
|
||||
|
||||
# 模拟趋势数据
|
||||
print("模拟趋势分析结果:")
|
||||
print()
|
||||
|
||||
# 模拟对比结果
|
||||
print("与基线对比:")
|
||||
comparison = {
|
||||
'context_recall': {
|
||||
'current': 0.85,
|
||||
'baseline': 0.80,
|
||||
'change': 0.05,
|
||||
'change_pct': 6.25,
|
||||
'status': 'improved'
|
||||
},
|
||||
'faithfulness': {
|
||||
'current': 0.88,
|
||||
'baseline': 0.90,
|
||||
'change': -0.02,
|
||||
'change_pct': -2.22,
|
||||
'status': 'stable'
|
||||
}
|
||||
}
|
||||
|
||||
for metric, comp in comparison.items():
|
||||
status_icon = "UP" if comp['status'] == 'improved' else "STABLE" if comp['status'] == 'stable' else "DOWN"
|
||||
print(f" {status_icon} {metric}: {comp['current']:.3f} (基线: {comp['baseline']:.3f}, "
|
||||
f"变化: {comp['change_pct']:+.1f}%)")
|
||||
|
||||
print()
|
||||
|
||||
# 模拟回归检测
|
||||
print("性能回归检测:")
|
||||
print(" [OK] 未检测到显著回归 (阈值: 5%)")
|
||||
print()
|
||||
|
||||
|
||||
def demo_trend_visualization():
|
||||
"""演示趋势可视化功能"""
|
||||
print("=" * 60)
|
||||
print("演示 3: 趋势可视化")
|
||||
print("=" * 60)
|
||||
|
||||
# 创建模拟历史数据
|
||||
history_data = []
|
||||
base_date = datetime.now() - timedelta(days=30)
|
||||
|
||||
for i in range(10):
|
||||
date = base_date + timedelta(days=i * 3)
|
||||
history_data.append({
|
||||
'timestamp': date.strftime('%Y-%m-%d'),
|
||||
'metrics': {
|
||||
'context_recall': 0.70 + i * 0.015, # 逐渐改进
|
||||
'faithfulness': 0.85 - i * 0.005, # 轻微下降
|
||||
'answer_relevancy': 0.75 + (i % 3) * 0.02 # 波动
|
||||
}
|
||||
})
|
||||
|
||||
# 生成趋势图
|
||||
try:
|
||||
visualizer = ReportVisualizer()
|
||||
output_path = 'demo_trend.html'
|
||||
|
||||
visualizer.create_trend_chart(history_data, output_path)
|
||||
|
||||
print(f"[OK] 趋势图已生成: {output_path}")
|
||||
print(f" - 包含 {len(history_data)} 个数据点")
|
||||
print(f" - 时间跨度: 30天")
|
||||
print(f" - 指标数量: 3个")
|
||||
|
||||
except ImportError as e:
|
||||
print(f"[ERROR] 无法生成趋势图: {e}")
|
||||
print(" 请安装 plotly: pip install plotly>=5.18.0")
|
||||
|
||||
print()
|
||||
|
||||
|
||||
def main():
|
||||
"""主函数"""
|
||||
print()
|
||||
print("=" + "=" * 58 + "=")
|
||||
print("|" + " " * 10 + "RAG评估框架 - Phase 3 功能演示" + " " * 16 + "|")
|
||||
print("=" + "=" * 58 + "=")
|
||||
print()
|
||||
|
||||
# 演示1: 报告可视化
|
||||
demo_visualization()
|
||||
|
||||
# 演示2: 历史数据和趋势分析
|
||||
demo_history_and_trend()
|
||||
|
||||
# 演示3: 趋势可视化
|
||||
demo_trend_visualization()
|
||||
|
||||
print("=" * 60)
|
||||
print("演示完成!")
|
||||
print("=" * 60)
|
||||
print()
|
||||
print("Phase 3 已完成的功能:")
|
||||
print(" [OK] 报告可视化 (HTML报告、图表)")
|
||||
print(" [OK] 评估历史数据存储")
|
||||
print(" [OK] 趋势对比分析")
|
||||
print(" [OK] 性能回归检测")
|
||||
print(" [OK] 单元测试覆盖")
|
||||
print()
|
||||
print("下一步: Phase 4 - API和用户界面")
|
||||
print()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,20 @@
|
||||
"""
|
||||
Report generation module
|
||||
"""
|
||||
|
||||
from .aggregator import (
|
||||
MetricStats,
|
||||
EvaluationSummary,
|
||||
ResultAggregator
|
||||
)
|
||||
|
||||
from .generator import ReportGenerator
|
||||
from .visualizer import ReportVisualizer
|
||||
|
||||
__all__ = [
|
||||
"MetricStats",
|
||||
"EvaluationSummary",
|
||||
"ResultAggregator",
|
||||
"ReportGenerator",
|
||||
"ReportVisualizer",
|
||||
]
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,334 @@
|
||||
"""
|
||||
Report generation module for RAG evaluation
|
||||
"""
|
||||
|
||||
from typing import List, Dict, Any, Optional
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
import statistics
|
||||
|
||||
|
||||
@dataclass
|
||||
class MetricStats:
|
||||
"""指标统计信息"""
|
||||
name: str
|
||||
mean: float
|
||||
median: float
|
||||
std_dev: float
|
||||
min: float
|
||||
max: float
|
||||
count: int
|
||||
pass_rate: float # 通过率(基于阈值)
|
||||
|
||||
|
||||
@dataclass
|
||||
class EvaluationSummary:
|
||||
"""评估摘要"""
|
||||
evaluation_id: str
|
||||
knowledge_base_id: str
|
||||
testset_id: str
|
||||
total_questions: int
|
||||
successful_questions: int
|
||||
failed_questions: int
|
||||
overall_score: float # 0-100分
|
||||
metric_stats: Dict[str, MetricStats]
|
||||
avg_retrieval_time_ms: float
|
||||
avg_generation_time_ms: float
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class ResultAggregator:
|
||||
"""评估结果聚合器"""
|
||||
|
||||
def __init__(self, metric_thresholds: Optional[Dict[str, float]] = None):
|
||||
"""
|
||||
初始化聚合器
|
||||
|
||||
Args:
|
||||
metric_thresholds: 指标阈值字典,用于计算通过率
|
||||
"""
|
||||
self.metric_thresholds = metric_thresholds or {
|
||||
'context_recall': 0.7,
|
||||
'context_precision': 0.7,
|
||||
'mrr': 0.6,
|
||||
'ndcg': 0.7,
|
||||
'faithfulness': 0.8,
|
||||
'answer_relevancy': 0.7,
|
||||
'correctness': 0.7
|
||||
}
|
||||
|
||||
def aggregate_results(
|
||||
self,
|
||||
evaluation_id: str,
|
||||
knowledge_base_id: str,
|
||||
testset_id: str,
|
||||
results: List[Dict[str, Any]]
|
||||
) -> EvaluationSummary:
|
||||
"""
|
||||
聚合评估结果
|
||||
|
||||
Args:
|
||||
evaluation_id: 评估ID
|
||||
knowledge_base_id: 知识库ID
|
||||
testset_id: 测评集ID
|
||||
results: 评估结果列表
|
||||
|
||||
Returns:
|
||||
评估摘要
|
||||
"""
|
||||
if not results:
|
||||
raise ValueError("Results list cannot be empty")
|
||||
|
||||
# 统计成功和失败的问题
|
||||
successful = [r for r in results if r.get('metrics') is not None]
|
||||
failed = [r for r in results if r.get('metrics') is None]
|
||||
|
||||
# 计算每个指标的统计信息
|
||||
metric_stats = self._calculate_metric_stats(successful)
|
||||
|
||||
# 计算整体评分(0-100)
|
||||
overall_score = self._calculate_overall_score(metric_stats)
|
||||
|
||||
# 计算平均时间
|
||||
avg_retrieval_time = statistics.mean(
|
||||
[r.get('retrieval_time_ms', 0) for r in successful]
|
||||
) if successful else 0
|
||||
|
||||
avg_generation_time = statistics.mean(
|
||||
[r.get('generation_time_ms', 0) for r in successful]
|
||||
) if successful else 0
|
||||
|
||||
return EvaluationSummary(
|
||||
evaluation_id=evaluation_id,
|
||||
knowledge_base_id=knowledge_base_id,
|
||||
testset_id=testset_id,
|
||||
total_questions=len(results),
|
||||
successful_questions=len(successful),
|
||||
failed_questions=len(failed),
|
||||
overall_score=overall_score,
|
||||
metric_stats=metric_stats,
|
||||
avg_retrieval_time_ms=avg_retrieval_time,
|
||||
avg_generation_time_ms=avg_generation_time,
|
||||
created_at=datetime.now()
|
||||
)
|
||||
|
||||
def _calculate_metric_stats(
|
||||
self,
|
||||
results: List[Dict[str, Any]]
|
||||
) -> Dict[str, MetricStats]:
|
||||
"""
|
||||
计算每个指标的统计信息
|
||||
|
||||
Args:
|
||||
results: 成功的评估结果列表
|
||||
|
||||
Returns:
|
||||
指标统计字典
|
||||
"""
|
||||
if not results:
|
||||
return {}
|
||||
|
||||
# 提取所有指标名称
|
||||
metric_names = set()
|
||||
for result in results:
|
||||
if 'metrics' in result and result['metrics']:
|
||||
metric_names.update(result['metrics'].keys())
|
||||
|
||||
# 计算每个指标的统计
|
||||
metric_stats = {}
|
||||
for metric_name in metric_names:
|
||||
values = [
|
||||
r['metrics'][metric_name]
|
||||
for r in results
|
||||
if 'metrics' in r and metric_name in r['metrics']
|
||||
]
|
||||
|
||||
if values:
|
||||
threshold = self.metric_thresholds.get(metric_name, 0.7)
|
||||
pass_count = sum(1 for v in values if v >= threshold)
|
||||
|
||||
metric_stats[metric_name] = MetricStats(
|
||||
name=metric_name,
|
||||
mean=statistics.mean(values),
|
||||
median=statistics.median(values),
|
||||
std_dev=statistics.stdev(values) if len(values) > 1 else 0.0,
|
||||
min=min(values),
|
||||
max=max(values),
|
||||
count=len(values),
|
||||
pass_rate=pass_count / len(values)
|
||||
)
|
||||
|
||||
return metric_stats
|
||||
|
||||
def _calculate_overall_score(
|
||||
self,
|
||||
metric_stats: Dict[str, MetricStats]
|
||||
) -> float:
|
||||
"""
|
||||
计算整体评分(0-100)
|
||||
|
||||
使用加权平均,检索指标和生成指标各占50%
|
||||
|
||||
Args:
|
||||
metric_stats: 指标统计字典
|
||||
|
||||
Returns:
|
||||
整体评分(0-100)
|
||||
"""
|
||||
if not metric_stats:
|
||||
return 0.0
|
||||
|
||||
# 定义指标权重
|
||||
retrieval_metrics = ['context_recall', 'context_precision', 'mrr', 'ndcg']
|
||||
generation_metrics = ['faithfulness', 'answer_relevancy', 'correctness']
|
||||
|
||||
# 计算检索指标平均分
|
||||
retrieval_scores = [
|
||||
metric_stats[m].mean
|
||||
for m in retrieval_metrics
|
||||
if m in metric_stats
|
||||
]
|
||||
retrieval_avg = statistics.mean(retrieval_scores) if retrieval_scores else 0.0
|
||||
|
||||
# 计算生成指标平均分
|
||||
generation_scores = [
|
||||
metric_stats[m].mean
|
||||
for m in generation_metrics
|
||||
if m in metric_stats
|
||||
]
|
||||
generation_avg = statistics.mean(generation_scores) if generation_scores else 0.0
|
||||
|
||||
# 加权平均(检索50%,生成50%)
|
||||
overall = (retrieval_avg * 0.5 + generation_avg * 0.5) * 100
|
||||
|
||||
return round(overall, 2)
|
||||
|
||||
def group_by_source(
|
||||
self,
|
||||
results: List[Dict[str, Any]]
|
||||
) -> Dict[str, List[Dict[str, Any]]]:
|
||||
"""
|
||||
按来源文件分组结果
|
||||
|
||||
Args:
|
||||
results: 评估结果列表
|
||||
|
||||
Returns:
|
||||
按来源分组的结果字典
|
||||
"""
|
||||
grouped = {}
|
||||
|
||||
for result in results:
|
||||
# 从元数据中提取来源信息
|
||||
source = result.get('metadata', {}).get('source', 'unknown')
|
||||
|
||||
if source not in grouped:
|
||||
grouped[source] = []
|
||||
|
||||
grouped[source].append(result)
|
||||
|
||||
return grouped
|
||||
|
||||
def identify_failed_cases(
|
||||
self,
|
||||
results: List[Dict[str, Any]],
|
||||
threshold: float = 0.5
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
识别失败案例(低于阈值的问题)
|
||||
|
||||
Args:
|
||||
results: 评估结果列表
|
||||
threshold: 失败阈值(默认0.5)
|
||||
|
||||
Returns:
|
||||
失败案例列表
|
||||
"""
|
||||
failed_cases = []
|
||||
|
||||
for result in results:
|
||||
if 'metrics' not in result or not result['metrics']:
|
||||
# 完全失败的案例
|
||||
failed_cases.append({
|
||||
'question_index': result.get('question_index', -1),
|
||||
'question': result.get('question_text', ''),
|
||||
'reason': 'evaluation_failed',
|
||||
'error': result.get('error', 'Unknown error'),
|
||||
'metrics': None
|
||||
})
|
||||
continue
|
||||
|
||||
# 检查是否有指标低于阈值
|
||||
metrics = result['metrics']
|
||||
low_metrics = {
|
||||
name: value
|
||||
for name, value in metrics.items()
|
||||
if value < threshold
|
||||
}
|
||||
|
||||
if low_metrics:
|
||||
failed_cases.append({
|
||||
'question_index': result.get('question_index', -1),
|
||||
'question': result.get('question_text', ''),
|
||||
'reason': 'low_metrics',
|
||||
'low_metrics': low_metrics,
|
||||
'all_metrics': metrics,
|
||||
'retrieved_contexts': result.get('retrieved_contexts', []),
|
||||
'generated_answer': result.get('generated_answer', ''),
|
||||
'ground_truth_answer': result.get('ground_truth_answer', '')
|
||||
})
|
||||
|
||||
return failed_cases
|
||||
|
||||
def calculate_metric_distribution(
|
||||
self,
|
||||
results: List[Dict[str, Any]],
|
||||
metric_name: str,
|
||||
bins: int = 10
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
计算指标分布
|
||||
|
||||
Args:
|
||||
results: 评估结果列表
|
||||
metric_name: 指标名称
|
||||
bins: 分箱数量
|
||||
|
||||
Returns:
|
||||
分布信息字典
|
||||
"""
|
||||
values = [
|
||||
r['metrics'][metric_name]
|
||||
for r in results
|
||||
if 'metrics' in r and metric_name in r['metrics']
|
||||
]
|
||||
|
||||
if not values:
|
||||
return {
|
||||
'metric': metric_name,
|
||||
'count': 0,
|
||||
'distribution': []
|
||||
}
|
||||
|
||||
# 创建分箱
|
||||
min_val = 0.0
|
||||
max_val = 1.0
|
||||
bin_width = (max_val - min_val) / bins
|
||||
|
||||
distribution = []
|
||||
for i in range(bins):
|
||||
bin_start = min_val + i * bin_width
|
||||
bin_end = bin_start + bin_width
|
||||
count = sum(1 for v in values if bin_start <= v < bin_end)
|
||||
|
||||
distribution.append({
|
||||
'range': f'{bin_start:.2f}-{bin_end:.2f}',
|
||||
'count': count,
|
||||
'percentage': count / len(values) * 100
|
||||
})
|
||||
|
||||
return {
|
||||
'metric': metric_name,
|
||||
'count': len(values),
|
||||
'distribution': distribution
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
"""
|
||||
Report generator for RAG evaluation
|
||||
"""
|
||||
|
||||
from typing import Dict, Any, List
|
||||
from datetime import datetime
|
||||
import json
|
||||
|
||||
from .aggregator import EvaluationSummary, ResultAggregator
|
||||
|
||||
|
||||
class ReportGenerator:
|
||||
"""报告生成器"""
|
||||
|
||||
def __init__(self, aggregator: ResultAggregator):
|
||||
"""
|
||||
初始化报告生成器
|
||||
|
||||
Args:
|
||||
aggregator: 结果聚合器
|
||||
"""
|
||||
self.aggregator = aggregator
|
||||
|
||||
def generate_json_report(
|
||||
self,
|
||||
summary: EvaluationSummary,
|
||||
results: List[Dict[str, Any]],
|
||||
include_details: bool = True
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
生成JSON格式报告
|
||||
|
||||
Args:
|
||||
summary: 评估摘要
|
||||
results: 评估结果列表
|
||||
include_details: 是否包含详细结果
|
||||
|
||||
Returns:
|
||||
JSON报告字典
|
||||
"""
|
||||
report = {
|
||||
'report_version': '1.0',
|
||||
'generated_at': datetime.now().isoformat(),
|
||||
'evaluation_id': summary.evaluation_id,
|
||||
'knowledge_base_id': summary.knowledge_base_id,
|
||||
'testset_id': summary.testset_id,
|
||||
|
||||
# Executive Summary
|
||||
'executive_summary': self._generate_executive_summary(summary),
|
||||
|
||||
# 详细指标分析
|
||||
'metrics_analysis': self._generate_metrics_analysis(summary),
|
||||
|
||||
# 失败案例
|
||||
'failed_cases': self.aggregator.identify_failed_cases(results),
|
||||
|
||||
# 按来源分组
|
||||
'by_source': self._generate_source_breakdown(results)
|
||||
}
|
||||
|
||||
if include_details:
|
||||
report['detailed_results'] = results
|
||||
|
||||
return report
|
||||
|
||||
def _generate_executive_summary(
|
||||
self,
|
||||
summary: EvaluationSummary
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
生成执行摘要
|
||||
|
||||
Args:
|
||||
summary: 评估摘要
|
||||
|
||||
Returns:
|
||||
执行摘要字典
|
||||
"""
|
||||
# 识别Top 3问题
|
||||
top_issues = self._identify_top_issues(summary)
|
||||
|
||||
return {
|
||||
'overall_score': summary.overall_score,
|
||||
'grade': self._score_to_grade(summary.overall_score),
|
||||
'total_questions': summary.total_questions,
|
||||
'successful_questions': summary.successful_questions,
|
||||
'failed_questions': summary.failed_questions,
|
||||
'success_rate': summary.successful_questions / summary.total_questions * 100,
|
||||
'avg_retrieval_time_ms': summary.avg_retrieval_time_ms,
|
||||
'avg_generation_time_ms': summary.avg_generation_time_ms,
|
||||
'top_issues': top_issues,
|
||||
'recommendations': self._generate_recommendations(summary)
|
||||
}
|
||||
|
||||
def _generate_metrics_analysis(
|
||||
self,
|
||||
summary: EvaluationSummary
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
生成指标分析
|
||||
|
||||
Args:
|
||||
summary: 评估摘要
|
||||
|
||||
Returns:
|
||||
指标分析字典
|
||||
"""
|
||||
metrics_data = {}
|
||||
|
||||
for metric_name, stats in summary.metric_stats.items():
|
||||
metrics_data[metric_name] = {
|
||||
'mean': round(stats.mean, 3),
|
||||
'median': round(stats.median, 3),
|
||||
'std_dev': round(stats.std_dev, 3),
|
||||
'min': round(stats.min, 3),
|
||||
'max': round(stats.max, 3),
|
||||
'pass_rate': round(stats.pass_rate * 100, 1),
|
||||
'status': 'good' if stats.pass_rate >= 0.8 else 'warning' if stats.pass_rate >= 0.6 else 'poor'
|
||||
}
|
||||
|
||||
return metrics_data
|
||||
|
||||
def _generate_source_breakdown(
|
||||
self,
|
||||
results: List[Dict[str, Any]]
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
生成按来源的细分分析
|
||||
|
||||
Args:
|
||||
results: 评估结果列表
|
||||
|
||||
Returns:
|
||||
来源细分字典
|
||||
"""
|
||||
grouped = self.aggregator.group_by_source(results)
|
||||
breakdown = {}
|
||||
|
||||
for source, source_results in grouped.items():
|
||||
# 计算该来源的统计
|
||||
successful = [r for r in source_results if r.get('metrics')]
|
||||
|
||||
if successful:
|
||||
# 计算平均指标
|
||||
avg_metrics = {}
|
||||
for metric_name in successful[0].get('metrics', {}).keys():
|
||||
values = [r['metrics'][metric_name] for r in successful if metric_name in r['metrics']]
|
||||
if values:
|
||||
avg_metrics[metric_name] = round(sum(values) / len(values), 3)
|
||||
|
||||
breakdown[source] = {
|
||||
'total_questions': len(source_results),
|
||||
'successful_questions': len(successful),
|
||||
'avg_metrics': avg_metrics
|
||||
}
|
||||
|
||||
return breakdown
|
||||
|
||||
def _identify_top_issues(
|
||||
self,
|
||||
summary: EvaluationSummary
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
识别Top 3问题
|
||||
|
||||
Args:
|
||||
summary: 评估摘要
|
||||
|
||||
Returns:
|
||||
问题列表
|
||||
"""
|
||||
issues = []
|
||||
|
||||
# 检查每个指标
|
||||
for metric_name, stats in summary.metric_stats.items():
|
||||
if stats.pass_rate < 0.7: # 通过率低于70%
|
||||
issues.append({
|
||||
'metric': metric_name,
|
||||
'severity': 'high' if stats.pass_rate < 0.5 else 'medium',
|
||||
'pass_rate': round(stats.pass_rate * 100, 1),
|
||||
'mean_score': round(stats.mean, 3),
|
||||
'description': f'{metric_name}通过率仅为{stats.pass_rate*100:.1f}%'
|
||||
})
|
||||
|
||||
# 按严重程度和通过率排序
|
||||
issues.sort(key=lambda x: (x['severity'] == 'high', -x['pass_rate']), reverse=True)
|
||||
|
||||
return issues[:3] # 返回Top 3
|
||||
|
||||
def _generate_recommendations(
|
||||
self,
|
||||
summary: EvaluationSummary
|
||||
) -> List[str]:
|
||||
"""
|
||||
生成改进建议(基于规则)
|
||||
|
||||
Args:
|
||||
summary: 评估摘要
|
||||
|
||||
Returns:
|
||||
建议列表
|
||||
"""
|
||||
recommendations = []
|
||||
|
||||
# 检索指标建议
|
||||
if 'context_recall' in summary.metric_stats:
|
||||
recall_stats = summary.metric_stats['context_recall']
|
||||
if recall_stats.mean < 0.7:
|
||||
recommendations.append(
|
||||
"召回率较低,建议:1) 增加检索的top_k数量;2) 优化文档分块策略;3) 改进embedding模型"
|
||||
)
|
||||
|
||||
if 'context_precision' in summary.metric_stats:
|
||||
precision_stats = summary.metric_stats['context_precision']
|
||||
if precision_stats.mean < 0.7:
|
||||
recommendations.append(
|
||||
"精确率较低,建议:1) 优化检索算法;2) 调整相似度阈值;3) 改进查询重写策略"
|
||||
)
|
||||
|
||||
# 生成指标建议
|
||||
if 'faithfulness' in summary.metric_stats:
|
||||
faith_stats = summary.metric_stats['faithfulness']
|
||||
if faith_stats.mean < 0.8:
|
||||
recommendations.append(
|
||||
"忠实度较低,建议:1) 在prompt中强调基于上下文回答;2) 使用更强的LLM;3) 添加事实核查机制"
|
||||
)
|
||||
|
||||
if 'answer_relevancy' in summary.metric_stats:
|
||||
rel_stats = summary.metric_stats['answer_relevancy']
|
||||
if rel_stats.mean < 0.7:
|
||||
recommendations.append(
|
||||
"答案相关性较低,建议:1) 优化prompt模板;2) 改进问题理解;3) 调整生成参数"
|
||||
)
|
||||
|
||||
# 性能建议
|
||||
if summary.avg_retrieval_time_ms > 500:
|
||||
recommendations.append(
|
||||
f"检索时间较长({summary.avg_retrieval_time_ms:.0f}ms),建议:1) 优化向量索引;2) 使用缓存;3) 考虑并行检索"
|
||||
)
|
||||
|
||||
if summary.avg_generation_time_ms > 2000:
|
||||
recommendations.append(
|
||||
f"生成时间较长({summary.avg_generation_time_ms:.0f}ms),建议:1) 使用更快的模型;2) 减少生成长度;3) 启用流式输出"
|
||||
)
|
||||
|
||||
return recommendations[:5] # 最多返回5条建议
|
||||
|
||||
def _score_to_grade(self, score: float) -> str:
|
||||
"""
|
||||
将分数转换为等级
|
||||
|
||||
Args:
|
||||
score: 分数(0-100)
|
||||
|
||||
Returns:
|
||||
等级字符串
|
||||
"""
|
||||
if score >= 90:
|
||||
return 'A (优秀)'
|
||||
elif score >= 80:
|
||||
return 'B (良好)'
|
||||
elif score >= 70:
|
||||
return 'C (中等)'
|
||||
elif score >= 60:
|
||||
return 'D (及格)'
|
||||
else:
|
||||
return 'F (不及格)'
|
||||
|
||||
def save_report(
|
||||
self,
|
||||
report: Dict[str, Any],
|
||||
output_path: str
|
||||
) -> None:
|
||||
"""
|
||||
保存报告到文件
|
||||
|
||||
Args:
|
||||
report: 报告字典
|
||||
output_path: 输出路径
|
||||
"""
|
||||
with open(output_path, 'w', encoding='utf-8') as f:
|
||||
json.dump(report, f, ensure_ascii=False, indent=2)
|
||||
@@ -0,0 +1,675 @@
|
||||
"""
|
||||
Report visualization module for RAG evaluation
|
||||
"""
|
||||
|
||||
from typing import Dict, Any, List, Optional
|
||||
import json
|
||||
from pathlib import Path
|
||||
from datetime import datetime
|
||||
|
||||
try:
|
||||
import plotly.graph_objects as go
|
||||
from plotly.subplots import make_subplots
|
||||
PLOTLY_AVAILABLE = True
|
||||
except ImportError:
|
||||
PLOTLY_AVAILABLE = False
|
||||
|
||||
from .aggregator import EvaluationSummary
|
||||
|
||||
|
||||
class ReportVisualizer:
|
||||
"""报告可视化器"""
|
||||
|
||||
def __init__(self):
|
||||
"""初始化可视化器"""
|
||||
if not PLOTLY_AVAILABLE:
|
||||
raise ImportError(
|
||||
"Plotly is required for visualization. "
|
||||
"Install it with: pip install plotly"
|
||||
)
|
||||
|
||||
def generate_html_report(
|
||||
self,
|
||||
summary: EvaluationSummary,
|
||||
results: List[Dict[str, Any]],
|
||||
output_path: str,
|
||||
include_charts: bool = True
|
||||
) -> None:
|
||||
"""
|
||||
生成HTML格式报告
|
||||
|
||||
Args:
|
||||
summary: 评估摘要
|
||||
results: 评估结果列表
|
||||
output_path: 输出路径
|
||||
include_charts: 是否包含图表
|
||||
"""
|
||||
html_content = self._generate_html_content(
|
||||
summary, results, include_charts
|
||||
)
|
||||
|
||||
with open(output_path, 'w', encoding='utf-8') as f:
|
||||
f.write(html_content)
|
||||
|
||||
def _generate_html_content(
|
||||
self,
|
||||
summary: EvaluationSummary,
|
||||
results: List[Dict[str, Any]],
|
||||
include_charts: bool
|
||||
) -> str:
|
||||
"""
|
||||
生成HTML内容
|
||||
|
||||
Args:
|
||||
summary: 评估摘要
|
||||
results: 评估结果列表
|
||||
include_charts: 是否包含图表
|
||||
|
||||
Returns:
|
||||
HTML字符串
|
||||
"""
|
||||
# 生成图表
|
||||
charts_html = ""
|
||||
if include_charts:
|
||||
charts_html = self._generate_charts_html(summary, results)
|
||||
|
||||
# 生成完整HTML
|
||||
html = f"""
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>RAG评估报告 - {summary.evaluation_id}</title>
|
||||
<script src="https://cdn.plot.ly/plotly-2.27.0.min.js"></script>
|
||||
<style>
|
||||
{self._get_css_styles()}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<header>
|
||||
<h1>RAG评估报告</h1>
|
||||
<p class="subtitle">评估ID: {summary.evaluation_id}</p>
|
||||
<p class="timestamp">生成时间: {summary.created_at.strftime('%Y-%m-%d %H:%M:%S')}</p>
|
||||
</header>
|
||||
|
||||
{self._generate_executive_summary_html(summary)}
|
||||
{charts_html}
|
||||
{self._generate_metrics_table_html(summary)}
|
||||
{self._generate_failed_cases_html(results)}
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
return html
|
||||
|
||||
def _get_css_styles(self) -> str:
|
||||
"""获取CSS样式"""
|
||||
return """
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
||||
line-height: 1.6;
|
||||
color: #333;
|
||||
background-color: #f5f5f5;
|
||||
}
|
||||
|
||||
.container {
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
header {
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
padding: 30px;
|
||||
border-radius: 10px;
|
||||
margin-bottom: 30px;
|
||||
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
header h1 {
|
||||
font-size: 2.5em;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
font-size: 1.1em;
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.timestamp {
|
||||
font-size: 0.9em;
|
||||
opacity: 0.8;
|
||||
margin-top: 5px;
|
||||
}
|
||||
|
||||
.section {
|
||||
background: white;
|
||||
padding: 25px;
|
||||
margin-bottom: 25px;
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.section h2 {
|
||||
color: #667eea;
|
||||
margin-bottom: 20px;
|
||||
font-size: 1.8em;
|
||||
border-bottom: 2px solid #667eea;
|
||||
padding-bottom: 10px;
|
||||
}
|
||||
|
||||
.summary-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
|
||||
gap: 20px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.summary-card {
|
||||
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
|
||||
padding: 20px;
|
||||
border-radius: 8px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.summary-card.score {
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.summary-card h3 {
|
||||
font-size: 0.9em;
|
||||
margin-bottom: 10px;
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
.summary-card .value {
|
||||
font-size: 2.5em;
|
||||
font-weight: bold;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
|
||||
.summary-card .label {
|
||||
font-size: 0.9em;
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.grade {
|
||||
display: inline-block;
|
||||
padding: 5px 15px;
|
||||
border-radius: 20px;
|
||||
font-weight: bold;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.grade-A { background-color: #10b981; color: white; }
|
||||
.grade-B { background-color: #3b82f6; color: white; }
|
||||
.grade-C { background-color: #f59e0b; color: white; }
|
||||
.grade-D { background-color: #ef4444; color: white; }
|
||||
.grade-F { background-color: #991b1b; color: white; }
|
||||
|
||||
.recommendations {
|
||||
background-color: #fef3c7;
|
||||
border-left: 4px solid #f59e0b;
|
||||
padding: 15px;
|
||||
margin-top: 20px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
.recommendations h3 {
|
||||
color: #92400e;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.recommendations ul {
|
||||
list-style-position: inside;
|
||||
color: #78350f;
|
||||
}
|
||||
|
||||
.recommendations li {
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
margin-top: 15px;
|
||||
}
|
||||
|
||||
th, td {
|
||||
padding: 12px;
|
||||
text-align: left;
|
||||
border-bottom: 1px solid #e5e7eb;
|
||||
}
|
||||
|
||||
th {
|
||||
background-color: #f9fafb;
|
||||
font-weight: 600;
|
||||
color: #374151;
|
||||
}
|
||||
|
||||
tr:hover {
|
||||
background-color: #f9fafb;
|
||||
}
|
||||
|
||||
.status-badge {
|
||||
display: inline-block;
|
||||
padding: 4px 12px;
|
||||
border-radius: 12px;
|
||||
font-size: 0.85em;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.status-good { background-color: #d1fae5; color: #065f46; }
|
||||
.status-warning { background-color: #fed7aa; color: #92400e; }
|
||||
.status-poor { background-color: #fee2e2; color: #991b1b; }
|
||||
|
||||
.chart-container {
|
||||
margin: 20px 0;
|
||||
padding: 15px;
|
||||
background: white;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.failed-case {
|
||||
background-color: #fef2f2;
|
||||
border-left: 4px solid #ef4444;
|
||||
padding: 15px;
|
||||
margin-bottom: 15px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
.failed-case h4 {
|
||||
color: #991b1b;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.failed-case .question {
|
||||
font-weight: 600;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.failed-case .metrics {
|
||||
font-size: 0.9em;
|
||||
color: #7f1d1d;
|
||||
}
|
||||
"""
|
||||
|
||||
def _generate_executive_summary_html(
|
||||
self,
|
||||
summary: EvaluationSummary
|
||||
) -> str:
|
||||
"""生成执行摘要HTML"""
|
||||
grade = self._score_to_grade(summary.overall_score)
|
||||
grade_class = f"grade-{grade[0]}"
|
||||
|
||||
success_rate = (summary.successful_questions / summary.total_questions * 100
|
||||
if summary.total_questions > 0 else 0)
|
||||
|
||||
html = f"""
|
||||
<div class="section">
|
||||
<h2>执行摘要</h2>
|
||||
<div class="summary-grid">
|
||||
<div class="summary-card score">
|
||||
<h3>整体评分</h3>
|
||||
<div class="value">{summary.overall_score:.1f}</div>
|
||||
<div class="grade {grade_class}">{grade}</div>
|
||||
</div>
|
||||
<div class="summary-card">
|
||||
<h3>总问题数</h3>
|
||||
<div class="value">{summary.total_questions}</div>
|
||||
<div class="label">评估问题</div>
|
||||
</div>
|
||||
<div class="summary-card">
|
||||
<h3>成功率</h3>
|
||||
<div class="value">{success_rate:.1f}%</div>
|
||||
<div class="label">{summary.successful_questions}/{summary.total_questions} 成功</div>
|
||||
</div>
|
||||
<div class="summary-card">
|
||||
<h3>平均响应时间</h3>
|
||||
<div class="value">{summary.avg_retrieval_time_ms + summary.avg_generation_time_ms:.0f}ms</div>
|
||||
<div class="label">检索+生成</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
"""
|
||||
return html
|
||||
|
||||
def _generate_metrics_table_html(
|
||||
self,
|
||||
summary: EvaluationSummary
|
||||
) -> str:
|
||||
"""生成指标表格HTML"""
|
||||
rows = []
|
||||
for metric_name, stats in summary.metric_stats.items():
|
||||
status = 'good' if stats.pass_rate >= 0.8 else 'warning' if stats.pass_rate >= 0.6 else 'poor'
|
||||
status_text = '优秀' if status == 'good' else '警告' if status == 'warning' else '较差'
|
||||
|
||||
rows.append(f"""
|
||||
<tr>
|
||||
<td>{self._translate_metric_name(metric_name)}</td>
|
||||
<td>{stats.mean:.3f}</td>
|
||||
<td>{stats.median:.3f}</td>
|
||||
<td>{stats.std_dev:.3f}</td>
|
||||
<td>{stats.pass_rate * 100:.1f}%</td>
|
||||
<td><span class="status-badge status-{status}">{status_text}</span></td>
|
||||
</tr>
|
||||
""")
|
||||
|
||||
html = f"""
|
||||
<div class="section">
|
||||
<h2>指标详情</h2>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>指标</th>
|
||||
<th>平均值</th>
|
||||
<th>中位数</th>
|
||||
<th>标准差</th>
|
||||
<th>通过率</th>
|
||||
<th>状态</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{''.join(rows)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
"""
|
||||
return html
|
||||
|
||||
def _generate_failed_cases_html(
|
||||
self,
|
||||
results: List[Dict[str, Any]]
|
||||
) -> str:
|
||||
"""生成失败案例HTML"""
|
||||
from .aggregator import ResultAggregator
|
||||
|
||||
aggregator = ResultAggregator()
|
||||
failed_cases = aggregator.identify_failed_cases(results, threshold=0.5)
|
||||
|
||||
if not failed_cases:
|
||||
return """
|
||||
<div class="section">
|
||||
<h2>失败案例</h2>
|
||||
<p>没有失败案例,所有问题都表现良好!</p>
|
||||
</div>
|
||||
"""
|
||||
|
||||
cases_html = []
|
||||
for case in failed_cases[:10]: # 只显示前10个
|
||||
if case['reason'] == 'evaluation_failed':
|
||||
cases_html.append(f"""
|
||||
<div class="failed-case">
|
||||
<h4>问题 #{case['question_index']}</h4>
|
||||
<div class="question">{case['question']}</div>
|
||||
<div class="metrics">错误: {case['error']}</div>
|
||||
</div>
|
||||
""")
|
||||
else:
|
||||
low_metrics_str = ', '.join(
|
||||
f"{k}: {v:.3f}" for k, v in case['low_metrics'].items()
|
||||
)
|
||||
cases_html.append(f"""
|
||||
<div class="failed-case">
|
||||
<h4>问题 #{case['question_index']}</h4>
|
||||
<div class="question">{case['question']}</div>
|
||||
<div class="metrics">低分指标: {low_metrics_str}</div>
|
||||
</div>
|
||||
""")
|
||||
|
||||
html = f"""
|
||||
<div class="section">
|
||||
<h2>失败案例 (前10个)</h2>
|
||||
{''.join(cases_html)}
|
||||
</div>
|
||||
"""
|
||||
return html
|
||||
|
||||
def _generate_charts_html(
|
||||
self,
|
||||
summary: EvaluationSummary,
|
||||
results: List[Dict[str, Any]]
|
||||
) -> str:
|
||||
"""生成图表HTML"""
|
||||
charts = []
|
||||
|
||||
# 1. 指标雷达图
|
||||
radar_chart = self._create_metrics_radar_chart(summary)
|
||||
charts.append(f"""
|
||||
<div class="section">
|
||||
<h2>指标雷达图</h2>
|
||||
<div id="radar-chart" class="chart-container"></div>
|
||||
<script>
|
||||
{radar_chart}
|
||||
</script>
|
||||
</div>
|
||||
""")
|
||||
|
||||
# 2. 指标分布柱状图
|
||||
bar_chart = self._create_metrics_bar_chart(summary)
|
||||
charts.append(f"""
|
||||
<div class="section">
|
||||
<h2>指标对比</h2>
|
||||
<div id="bar-chart" class="chart-container"></div>
|
||||
<script>
|
||||
{bar_chart}
|
||||
</script>
|
||||
</div>
|
||||
""")
|
||||
|
||||
# 3. 通过率饼图
|
||||
pie_chart = self._create_pass_rate_pie_chart(summary)
|
||||
charts.append(f"""
|
||||
<div class="section">
|
||||
<h2>整体通过率</h2>
|
||||
<div id="pie-chart" class="chart-container"></div>
|
||||
<script>
|
||||
{pie_chart}
|
||||
</script>
|
||||
</div>
|
||||
""")
|
||||
|
||||
return '\n'.join(charts)
|
||||
|
||||
def _create_metrics_radar_chart(
|
||||
self,
|
||||
summary: EvaluationSummary
|
||||
) -> str:
|
||||
"""创建指标雷达图"""
|
||||
categories = []
|
||||
values = []
|
||||
|
||||
for metric_name, stats in summary.metric_stats.items():
|
||||
categories.append(self._translate_metric_name(metric_name))
|
||||
values.append(stats.mean)
|
||||
|
||||
# 闭合雷达图
|
||||
categories.append(categories[0])
|
||||
values.append(values[0])
|
||||
|
||||
data = {
|
||||
'type': 'scatterpolar',
|
||||
'r': values,
|
||||
'theta': categories,
|
||||
'fill': 'toself',
|
||||
'name': '指标得分'
|
||||
}
|
||||
|
||||
layout = {
|
||||
'polar': {
|
||||
'radialaxis': {
|
||||
'visible': True,
|
||||
'range': [0, 1]
|
||||
}
|
||||
},
|
||||
'showlegend': False
|
||||
}
|
||||
|
||||
return f"""
|
||||
var data = [{json.dumps(data)}];
|
||||
var layout = {json.dumps(layout)};
|
||||
Plotly.newPlot('radar-chart', data, layout);
|
||||
"""
|
||||
|
||||
def _create_metrics_bar_chart(
|
||||
self,
|
||||
summary: EvaluationSummary
|
||||
) -> str:
|
||||
"""创建指标柱状图"""
|
||||
categories = []
|
||||
means = []
|
||||
pass_rates = []
|
||||
|
||||
for metric_name, stats in summary.metric_stats.items():
|
||||
categories.append(self._translate_metric_name(metric_name))
|
||||
means.append(stats.mean)
|
||||
pass_rates.append(stats.pass_rate)
|
||||
|
||||
trace1 = {
|
||||
'x': categories,
|
||||
'y': means,
|
||||
'name': '平均得分',
|
||||
'type': 'bar',
|
||||
'marker': {'color': '#667eea'}
|
||||
}
|
||||
|
||||
trace2 = {
|
||||
'x': categories,
|
||||
'y': pass_rates,
|
||||
'name': '通过率',
|
||||
'type': 'bar',
|
||||
'marker': {'color': '#764ba2'}
|
||||
}
|
||||
|
||||
layout = {
|
||||
'barmode': 'group',
|
||||
'yaxis': {'range': [0, 1], 'title': '得分'},
|
||||
'xaxis': {'title': '指标'}
|
||||
}
|
||||
|
||||
return f"""
|
||||
var data = [{json.dumps(trace1)}, {json.dumps(trace2)}];
|
||||
var layout = {json.dumps(layout)};
|
||||
Plotly.newPlot('bar-chart', data, layout);
|
||||
"""
|
||||
|
||||
def _create_pass_rate_pie_chart(
|
||||
self,
|
||||
summary: EvaluationSummary
|
||||
) -> str:
|
||||
"""创建通过率饼图"""
|
||||
data = {
|
||||
'values': [summary.successful_questions, summary.failed_questions],
|
||||
'labels': ['成功', '失败'],
|
||||
'type': 'pie',
|
||||
'marker': {
|
||||
'colors': ['#10b981', '#ef4444']
|
||||
}
|
||||
}
|
||||
|
||||
layout = {
|
||||
'showlegend': True
|
||||
}
|
||||
|
||||
return f"""
|
||||
var data = [{json.dumps(data)}];
|
||||
var layout = {json.dumps(layout)};
|
||||
Plotly.newPlot('pie-chart', data, layout);
|
||||
"""
|
||||
|
||||
def create_trend_chart(
|
||||
self,
|
||||
history_data: List[Dict[str, Any]],
|
||||
output_path: str
|
||||
) -> None:
|
||||
"""
|
||||
创建趋势图
|
||||
|
||||
Args:
|
||||
history_data: 历史数据列表,每项包含 {timestamp, metrics}
|
||||
output_path: 输出路径
|
||||
"""
|
||||
if not history_data:
|
||||
raise ValueError("History data cannot be empty")
|
||||
|
||||
# 提取时间戳和指标
|
||||
timestamps = [item['timestamp'] for item in history_data]
|
||||
|
||||
# 获取所有指标名称
|
||||
metric_names = set()
|
||||
for item in history_data:
|
||||
metric_names.update(item['metrics'].keys())
|
||||
|
||||
# 创建子图
|
||||
fig = make_subplots(
|
||||
rows=len(metric_names),
|
||||
cols=1,
|
||||
subplot_titles=[self._translate_metric_name(m) for m in metric_names],
|
||||
vertical_spacing=0.05
|
||||
)
|
||||
|
||||
# 为每个指标添加趋势线
|
||||
for idx, metric_name in enumerate(sorted(metric_names), start=1):
|
||||
values = [
|
||||
item['metrics'].get(metric_name, None)
|
||||
for item in history_data
|
||||
]
|
||||
|
||||
fig.add_trace(
|
||||
go.Scatter(
|
||||
x=timestamps,
|
||||
y=values,
|
||||
mode='lines+markers',
|
||||
name=self._translate_metric_name(metric_name),
|
||||
line=dict(width=2),
|
||||
marker=dict(size=8)
|
||||
),
|
||||
row=idx,
|
||||
col=1
|
||||
)
|
||||
|
||||
# 更新布局
|
||||
fig.update_layout(
|
||||
height=300 * len(metric_names),
|
||||
title_text="评估指标历史趋势",
|
||||
showlegend=False
|
||||
)
|
||||
|
||||
# 保存为HTML
|
||||
fig.write_html(output_path)
|
||||
|
||||
def _translate_metric_name(self, metric_name: str) -> str:
|
||||
"""翻译指标名称为中文"""
|
||||
translations = {
|
||||
'context_recall': '上下文召回率',
|
||||
'context_precision': '上下文精确率',
|
||||
'mrr': '平均倒数排名',
|
||||
'ndcg': '归一化折损累计增益',
|
||||
'faithfulness': '忠实度',
|
||||
'answer_relevancy': '答案相关性',
|
||||
'correctness': '正确性'
|
||||
}
|
||||
return translations.get(metric_name, metric_name)
|
||||
|
||||
def _score_to_grade(self, score: float) -> str:
|
||||
"""将分数转换为等级"""
|
||||
if score >= 90:
|
||||
return 'A (优秀)'
|
||||
elif score >= 80:
|
||||
return 'B (良好)'
|
||||
elif score >= 70:
|
||||
return 'C (中等)'
|
||||
elif score >= 60:
|
||||
return 'D (及格)'
|
||||
else:
|
||||
return 'F (不及格)'
|
||||
@@ -0,0 +1,14 @@
|
||||
# RAG Evaluation Framework - Minimal Dependencies
|
||||
|
||||
# Phase 1: Core dependencies
|
||||
ragas>=0.1.0
|
||||
langchain>=0.1.0
|
||||
pymysql>=1.1.0
|
||||
pyyaml>=6.0
|
||||
python-dotenv>=1.0.0
|
||||
|
||||
# Phase 2: Evaluation dependencies
|
||||
requests>=2.31.0
|
||||
|
||||
# Phase 3: Report visualization
|
||||
plotly>=5.18.0
|
||||
@@ -0,0 +1,63 @@
|
||||
"""
|
||||
Convenience script to run examples with correct Python path
|
||||
"""
|
||||
|
||||
import sys
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def run_example(script_name):
|
||||
"""Run an example script with correct Python path"""
|
||||
|
||||
# Get the rag_evaluation directory
|
||||
rag_eval_dir = Path(__file__).parent
|
||||
|
||||
# Run the script with correct PYTHONPATH
|
||||
env = dict(subprocess.os.environ)
|
||||
env['PYTHONPATH'] = str(rag_eval_dir.parent)
|
||||
|
||||
script_path = rag_eval_dir / script_name
|
||||
|
||||
if not script_path.exists():
|
||||
print(f"Error: {script_name} not found at {script_path}")
|
||||
return 1
|
||||
|
||||
print(f"Running {script_name}...")
|
||||
print("=" * 60)
|
||||
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[sys.executable, str(script_path)],
|
||||
env=env,
|
||||
cwd=str(rag_eval_dir)
|
||||
)
|
||||
return result.returncode
|
||||
except Exception as e:
|
||||
print(f"Error running {script_name}: {e}")
|
||||
return 1
|
||||
|
||||
|
||||
def main():
|
||||
"""Main function"""
|
||||
|
||||
if len(sys.argv) < 2:
|
||||
print("Usage: python run.py <script_name>")
|
||||
print()
|
||||
print("Available scripts:")
|
||||
print(" python run.py example.py # Run Phase 1 example")
|
||||
print(" python run.py example_phase2.py # Run Phase 2 example")
|
||||
print(" python run.py test_framework.py # Run tests")
|
||||
print()
|
||||
print("Or directly:")
|
||||
print(" python example.py")
|
||||
print(" python example_phase2.py")
|
||||
print(" python test_framework.py")
|
||||
return 1
|
||||
|
||||
script_name = sys.argv[1]
|
||||
return run_example(script_name)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,92 @@
|
||||
"""
|
||||
Setup script for RAG Evaluation Framework
|
||||
"""
|
||||
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def install_dependencies():
|
||||
"""Install required dependencies"""
|
||||
|
||||
print("Installing dependencies...")
|
||||
print("=" * 60)
|
||||
|
||||
requirements_file = Path(__file__).parent / "requirements.txt"
|
||||
|
||||
if not requirements_file.exists():
|
||||
print(f"Error: requirements.txt not found at {requirements_file}")
|
||||
return False
|
||||
|
||||
try:
|
||||
subprocess.check_call([
|
||||
sys.executable, "-m", "pip", "install", "-r", str(requirements_file)
|
||||
])
|
||||
print("\n✓ Dependencies installed successfully!")
|
||||
return True
|
||||
|
||||
except subprocess.CalledProcessError as e:
|
||||
print(f"\n✗ Failed to install dependencies: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def verify_installation():
|
||||
"""Verify that all modules can be imported"""
|
||||
|
||||
print("\nVerifying installation...")
|
||||
print("=" * 60)
|
||||
|
||||
modules_to_test = [
|
||||
("ragas", "RAGAS"),
|
||||
("langchain", "LangChain"),
|
||||
("pymysql", "PyMySQL"),
|
||||
("yaml", "PyYAML"),
|
||||
("dotenv", "python-dotenv"),
|
||||
("requests", "requests"),
|
||||
]
|
||||
|
||||
all_ok = True
|
||||
for module_name, display_name in modules_to_test:
|
||||
try:
|
||||
__import__(module_name)
|
||||
print(f"✓ {display_name}")
|
||||
except ImportError:
|
||||
print(f"✗ {display_name} - NOT INSTALLED")
|
||||
all_ok = False
|
||||
|
||||
return all_ok
|
||||
|
||||
|
||||
def main():
|
||||
"""Main setup function"""
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("RAG Evaluation Framework - Setup")
|
||||
print("=" * 60)
|
||||
|
||||
# Install dependencies
|
||||
if not install_dependencies():
|
||||
print("\n⚠ Setup failed!")
|
||||
return 1
|
||||
|
||||
# Verify installation
|
||||
if not verify_installation():
|
||||
print("\n⚠ Some modules failed to install!")
|
||||
return 1
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("✅ Setup completed successfully!")
|
||||
print("=" * 60)
|
||||
|
||||
print("\nNext steps:")
|
||||
print("1. Copy config.example.yaml to config.yaml")
|
||||
print("2. Update config.yaml with your settings")
|
||||
print("3. Run: python test_framework.py")
|
||||
print("4. Run: python example.py")
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,14 @@
|
||||
"""
|
||||
Storage module for RAG evaluation
|
||||
"""
|
||||
|
||||
from .database import DatabaseManager
|
||||
from .history import HistoryManager, HistoryRecord
|
||||
from .trend_analyzer import TrendAnalyzer
|
||||
|
||||
__all__ = [
|
||||
"DatabaseManager",
|
||||
"HistoryManager",
|
||||
"HistoryRecord",
|
||||
"TrendAnalyzer",
|
||||
]
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,97 @@
|
||||
"""
|
||||
Database connection and operations module
|
||||
"""
|
||||
|
||||
import pymysql
|
||||
from typing import Optional, Dict, List, Any
|
||||
from contextlib import contextmanager
|
||||
from ..core.config import DatabaseConfig
|
||||
|
||||
|
||||
class DatabaseManager:
|
||||
"""Database connection manager"""
|
||||
|
||||
def __init__(self, config: DatabaseConfig):
|
||||
self.config = config
|
||||
self._connection = None
|
||||
|
||||
def connect(self):
|
||||
"""Establish database connection"""
|
||||
self._connection = pymysql.connect(
|
||||
host=self.config.host,
|
||||
port=self.config.port,
|
||||
user=self.config.user,
|
||||
password=self.config.password,
|
||||
database=self.config.database,
|
||||
charset=self.config.charset,
|
||||
cursorclass=pymysql.cursors.DictCursor
|
||||
)
|
||||
return self._connection
|
||||
|
||||
def close(self):
|
||||
"""Close database connection"""
|
||||
if self._connection:
|
||||
self._connection.close()
|
||||
self._connection = None
|
||||
|
||||
@contextmanager
|
||||
def get_connection(self):
|
||||
"""Get database connection context manager"""
|
||||
conn = self.connect()
|
||||
try:
|
||||
yield conn
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
@contextmanager
|
||||
def get_cursor(self):
|
||||
"""Get database cursor context manager"""
|
||||
with self.get_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
try:
|
||||
yield cursor
|
||||
conn.commit()
|
||||
except Exception:
|
||||
conn.rollback()
|
||||
raise
|
||||
finally:
|
||||
cursor.close()
|
||||
|
||||
def execute_query(self, sql: str, params: Optional[tuple] = None) -> List[Dict]:
|
||||
"""Execute SELECT query"""
|
||||
with self.get_cursor() as cursor:
|
||||
cursor.execute(sql, params)
|
||||
return cursor.fetchall()
|
||||
|
||||
def execute_update(self, sql: str, params: Optional[tuple] = None) -> int:
|
||||
"""Execute INSERT/UPDATE/DELETE query"""
|
||||
with self.get_cursor() as cursor:
|
||||
affected_rows = cursor.execute(sql, params)
|
||||
return affected_rows
|
||||
|
||||
def execute_many(self, sql: str, params_list: List[tuple]) -> int:
|
||||
"""Execute batch INSERT/UPDATE"""
|
||||
with self.get_cursor() as cursor:
|
||||
affected_rows = cursor.executemany(sql, params_list)
|
||||
return affected_rows
|
||||
|
||||
def init_schema(self, schema_file: str):
|
||||
"""Initialize database schema from SQL file"""
|
||||
with open(schema_file, 'r', encoding='utf-8') as f:
|
||||
schema_sql = f.read()
|
||||
|
||||
# Split by semicolon and execute each statement
|
||||
statements = [s.strip() for s in schema_sql.split(';') if s.strip()]
|
||||
|
||||
with self.get_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
try:
|
||||
for statement in statements:
|
||||
if statement:
|
||||
cursor.execute(statement)
|
||||
conn.commit()
|
||||
except Exception as e:
|
||||
conn.rollback()
|
||||
raise Exception(f"Failed to initialize schema: {e}")
|
||||
finally:
|
||||
cursor.close()
|
||||
@@ -0,0 +1,308 @@
|
||||
"""
|
||||
Evaluation history management module
|
||||
"""
|
||||
|
||||
from typing import List, Dict, Any, Optional
|
||||
from datetime import datetime
|
||||
from dataclasses import dataclass
|
||||
import uuid
|
||||
|
||||
from .database import DatabaseManager
|
||||
from ..report.aggregator import EvaluationSummary
|
||||
|
||||
|
||||
@dataclass
|
||||
class HistoryRecord:
|
||||
"""历史记录"""
|
||||
id: str
|
||||
evaluation_id: str
|
||||
knowledge_base_id: str
|
||||
metric_name: str
|
||||
metric_value: float
|
||||
recorded_at: datetime
|
||||
metadata: Optional[Dict[str, Any]] = None
|
||||
|
||||
|
||||
class HistoryManager:
|
||||
"""评估历史管理器"""
|
||||
|
||||
def __init__(self, db_manager: DatabaseManager):
|
||||
"""
|
||||
初始化历史管理器
|
||||
|
||||
Args:
|
||||
db_manager: 数据库管理器
|
||||
"""
|
||||
self.db = db_manager
|
||||
|
||||
def save_evaluation_history(
|
||||
self,
|
||||
summary: EvaluationSummary,
|
||||
metadata: Optional[Dict[str, Any]] = None
|
||||
) -> None:
|
||||
"""
|
||||
保存评估历史记录
|
||||
|
||||
Args:
|
||||
summary: 评估摘要
|
||||
metadata: 额外的元数据
|
||||
"""
|
||||
records = []
|
||||
recorded_at = datetime.now()
|
||||
|
||||
# 保存每个指标的历史记录
|
||||
for metric_name, stats in summary.metric_stats.items():
|
||||
record_id = self._generate_id()
|
||||
biz_seq = self._generate_biz_seq()
|
||||
sys_seq = self._generate_sys_seq()
|
||||
|
||||
records.append((
|
||||
record_id,
|
||||
biz_seq,
|
||||
sys_seq,
|
||||
summary.evaluation_id,
|
||||
summary.knowledge_base_id,
|
||||
metric_name,
|
||||
stats.mean,
|
||||
recorded_at,
|
||||
recorded_at
|
||||
))
|
||||
|
||||
# 批量插入
|
||||
if records:
|
||||
sql = """
|
||||
INSERT INTO evaluation_history
|
||||
(id, biz_seq, sys_seq, evaluation_id, knowledge_base_id,
|
||||
metric_name, metric_value, recorded_at, create_time)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||
"""
|
||||
self.db.execute_many(sql, records)
|
||||
|
||||
def get_history_by_knowledge_base(
|
||||
self,
|
||||
knowledge_base_id: str,
|
||||
metric_name: Optional[str] = None,
|
||||
limit: int = 100
|
||||
) -> List[HistoryRecord]:
|
||||
"""
|
||||
获取知识库的历史记录
|
||||
|
||||
Args:
|
||||
knowledge_base_id: 知识库ID
|
||||
metric_name: 指标名称(可选,不指定则返回所有指标)
|
||||
limit: 返回记录数限制
|
||||
|
||||
Returns:
|
||||
历史记录列表
|
||||
"""
|
||||
if metric_name:
|
||||
sql = """
|
||||
SELECT id, evaluation_id, knowledge_base_id, metric_name,
|
||||
metric_value, recorded_at
|
||||
FROM evaluation_history
|
||||
WHERE knowledge_base_id = %s AND metric_name = %s
|
||||
ORDER BY recorded_at DESC
|
||||
LIMIT %s
|
||||
"""
|
||||
params = (knowledge_base_id, metric_name, limit)
|
||||
else:
|
||||
sql = """
|
||||
SELECT id, evaluation_id, knowledge_base_id, metric_name,
|
||||
metric_value, recorded_at
|
||||
FROM evaluation_history
|
||||
WHERE knowledge_base_id = %s
|
||||
ORDER BY recorded_at DESC
|
||||
LIMIT %s
|
||||
"""
|
||||
params = (knowledge_base_id, limit)
|
||||
|
||||
rows = self.db.execute_query(sql, params)
|
||||
|
||||
return [
|
||||
HistoryRecord(
|
||||
id=row['id'],
|
||||
evaluation_id=row['evaluation_id'],
|
||||
knowledge_base_id=row['knowledge_base_id'],
|
||||
metric_name=row['metric_name'],
|
||||
metric_value=row['metric_value'],
|
||||
recorded_at=row['recorded_at']
|
||||
)
|
||||
for row in rows
|
||||
]
|
||||
|
||||
def get_history_by_evaluation(
|
||||
self,
|
||||
evaluation_id: str
|
||||
) -> List[HistoryRecord]:
|
||||
"""
|
||||
获取特定评估的历史记录
|
||||
|
||||
Args:
|
||||
evaluation_id: 评估ID
|
||||
|
||||
Returns:
|
||||
历史记录列表
|
||||
"""
|
||||
sql = """
|
||||
SELECT id, evaluation_id, knowledge_base_id, metric_name,
|
||||
metric_value, recorded_at
|
||||
FROM evaluation_history
|
||||
WHERE evaluation_id = %s
|
||||
ORDER BY metric_name
|
||||
"""
|
||||
|
||||
rows = self.db.execute_query(sql, (evaluation_id,))
|
||||
|
||||
return [
|
||||
HistoryRecord(
|
||||
id=row['id'],
|
||||
evaluation_id=row['evaluation_id'],
|
||||
knowledge_base_id=row['knowledge_base_id'],
|
||||
metric_name=row['metric_name'],
|
||||
metric_value=row['metric_value'],
|
||||
recorded_at=row['recorded_at']
|
||||
)
|
||||
for row in rows
|
||||
]
|
||||
|
||||
def get_metric_trend(
|
||||
self,
|
||||
knowledge_base_id: str,
|
||||
metric_name: str,
|
||||
days: int = 30
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
获取指标趋势数据
|
||||
|
||||
Args:
|
||||
knowledge_base_id: 知识库ID
|
||||
metric_name: 指标名称
|
||||
days: 天数
|
||||
|
||||
Returns:
|
||||
趋势数据列表,每项包含 {timestamp, value, evaluation_id}
|
||||
"""
|
||||
sql = """
|
||||
SELECT evaluation_id, metric_value, recorded_at
|
||||
FROM evaluation_history
|
||||
WHERE knowledge_base_id = %s
|
||||
AND metric_name = %s
|
||||
AND recorded_at >= DATE_SUB(NOW(), INTERVAL %s DAY)
|
||||
ORDER BY recorded_at ASC
|
||||
"""
|
||||
|
||||
rows = self.db.execute_query(sql, (knowledge_base_id, metric_name, days))
|
||||
|
||||
return [
|
||||
{
|
||||
'timestamp': row['recorded_at'].isoformat(),
|
||||
'value': row['metric_value'],
|
||||
'evaluation_id': row['evaluation_id']
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
|
||||
def get_all_metrics_trend(
|
||||
self,
|
||||
knowledge_base_id: str,
|
||||
days: int = 30
|
||||
) -> Dict[str, List[Dict[str, Any]]]:
|
||||
"""
|
||||
获取所有指标的趋势数据
|
||||
|
||||
Args:
|
||||
knowledge_base_id: 知识库ID
|
||||
days: 天数
|
||||
|
||||
Returns:
|
||||
按指标名称分组的趋势数据字典
|
||||
"""
|
||||
sql = """
|
||||
SELECT metric_name, evaluation_id, metric_value, recorded_at
|
||||
FROM evaluation_history
|
||||
WHERE knowledge_base_id = %s
|
||||
AND recorded_at >= DATE_SUB(NOW(), INTERVAL %s DAY)
|
||||
ORDER BY metric_name, recorded_at ASC
|
||||
"""
|
||||
|
||||
rows = self.db.execute_query(sql, (knowledge_base_id, days))
|
||||
|
||||
# 按指标分组
|
||||
trends = {}
|
||||
for row in rows:
|
||||
metric_name = row['metric_name']
|
||||
if metric_name not in trends:
|
||||
trends[metric_name] = []
|
||||
|
||||
trends[metric_name].append({
|
||||
'timestamp': row['recorded_at'].isoformat(),
|
||||
'value': row['metric_value'],
|
||||
'evaluation_id': row['evaluation_id']
|
||||
})
|
||||
|
||||
return trends
|
||||
|
||||
def get_latest_metrics(
|
||||
self,
|
||||
knowledge_base_id: str
|
||||
) -> Dict[str, float]:
|
||||
"""
|
||||
获取最新的指标值
|
||||
|
||||
Args:
|
||||
knowledge_base_id: 知识库ID
|
||||
|
||||
Returns:
|
||||
指标名称到值的字典
|
||||
"""
|
||||
sql = """
|
||||
SELECT h1.metric_name, h1.metric_value
|
||||
FROM evaluation_history h1
|
||||
INNER JOIN (
|
||||
SELECT metric_name, MAX(recorded_at) as max_time
|
||||
FROM evaluation_history
|
||||
WHERE knowledge_base_id = %s
|
||||
GROUP BY metric_name
|
||||
) h2 ON h1.metric_name = h2.metric_name
|
||||
AND h1.recorded_at = h2.max_time
|
||||
WHERE h1.knowledge_base_id = %s
|
||||
"""
|
||||
|
||||
rows = self.db.execute_query(sql, (knowledge_base_id, knowledge_base_id))
|
||||
|
||||
return {
|
||||
row['metric_name']: row['metric_value']
|
||||
for row in rows
|
||||
}
|
||||
|
||||
def delete_old_history(
|
||||
self,
|
||||
days: int = 90
|
||||
) -> int:
|
||||
"""
|
||||
删除旧的历史记录
|
||||
|
||||
Args:
|
||||
days: 保留天数
|
||||
|
||||
Returns:
|
||||
删除的记录数
|
||||
"""
|
||||
sql = """
|
||||
DELETE FROM evaluation_history
|
||||
WHERE recorded_at < DATE_SUB(NOW(), INTERVAL %s DAY)
|
||||
"""
|
||||
|
||||
return self.db.execute_update(sql, (days,))
|
||||
|
||||
def _generate_id(self) -> str:
|
||||
"""生成唯一ID"""
|
||||
return uuid.uuid4().hex
|
||||
|
||||
def _generate_biz_seq(self) -> str:
|
||||
"""生成业务流水号"""
|
||||
return f"BIZ{datetime.now().strftime('%Y%m%d%H%M%S')}{uuid.uuid4().hex[:8]}"
|
||||
|
||||
def _generate_sys_seq(self) -> str:
|
||||
"""生成系统流水号"""
|
||||
return f"SYS{datetime.now().strftime('%Y%m%d%H%M%S')}{uuid.uuid4().hex[:8]}"
|
||||
@@ -0,0 +1,130 @@
|
||||
-- RAG Evaluation Framework Database Schema
|
||||
-- MySQL 8.0+
|
||||
|
||||
-- 知识库表
|
||||
CREATE TABLE IF NOT EXISTS `knowledge_bases` (
|
||||
`id` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT 'id',
|
||||
`biz_seq` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '业务流水号',
|
||||
`sys_seq` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '系统流水号',
|
||||
`name` varchar(255) COLLATE utf8mb4_bin NOT NULL COMMENT '知识库名称',
|
||||
`description` text COLLATE utf8mb4_bin COMMENT '知识库描述',
|
||||
`file_count` int DEFAULT 0 COMMENT '文件数量',
|
||||
`total_size` bigint DEFAULT 0 COMMENT '总大小(字节)',
|
||||
`create_time` datetime NOT NULL COMMENT '创建时间',
|
||||
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_biz_seq` (`biz_seq`),
|
||||
KEY `idx_create_time` (`create_time`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='知识库表';
|
||||
|
||||
-- 测评集表
|
||||
CREATE TABLE IF NOT EXISTS `testsets` (
|
||||
`id` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT 'id',
|
||||
`biz_seq` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '业务流水号',
|
||||
`sys_seq` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '系统流水号',
|
||||
`knowledge_base_id` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '知识库ID',
|
||||
`name` varchar(255) COLLATE utf8mb4_bin NOT NULL COMMENT '测评集名称',
|
||||
`file_path` varchar(512) COLLATE utf8mb4_bin NOT NULL COMMENT 'JSON文件路径',
|
||||
`question_count` int NOT NULL COMMENT '问题数量',
|
||||
`metadata` json COMMENT '元数据(采样策略、问题分布等)',
|
||||
`create_time` datetime NOT NULL COMMENT '创建时间',
|
||||
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_biz_seq` (`biz_seq`),
|
||||
KEY `idx_knowledge_base_id` (`knowledge_base_id`),
|
||||
KEY `idx_create_time` (`create_time`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='测评集表';
|
||||
|
||||
-- 评估任务表
|
||||
CREATE TABLE IF NOT EXISTS `evaluations` (
|
||||
`id` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT 'id',
|
||||
`biz_seq` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '业务流水号',
|
||||
`sys_seq` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '系统流水号',
|
||||
`knowledge_base_id` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '知识库ID',
|
||||
`testset_id` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '测评集ID',
|
||||
`status` varchar(20) COLLATE utf8mb4_bin NOT NULL DEFAULT 'pending' COMMENT '状态: pending/running/completed/failed',
|
||||
`config` json COMMENT '评估配置(采样率、并行度等)',
|
||||
`started_at` datetime DEFAULT NULL COMMENT '开始时间',
|
||||
`completed_at` datetime DEFAULT NULL COMMENT '完成时间',
|
||||
`error_message` text COLLATE utf8mb4_bin COMMENT '错误信息',
|
||||
`create_time` datetime NOT NULL COMMENT '创建时间',
|
||||
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_biz_seq` (`biz_seq`),
|
||||
KEY `idx_knowledge_base_id` (`knowledge_base_id`),
|
||||
KEY `idx_status` (`status`),
|
||||
KEY `idx_create_time` (`create_time`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='评估任务表';
|
||||
|
||||
-- 评估结果表
|
||||
CREATE TABLE IF NOT EXISTS `evaluation_results` (
|
||||
`id` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT 'id',
|
||||
`biz_seq` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '业务流水号',
|
||||
`sys_seq` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '系统流水号',
|
||||
`evaluation_id` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '评估任务ID',
|
||||
`question_index` int NOT NULL COMMENT '问题在测评集中的索引',
|
||||
`question_text` text COLLATE utf8mb4_bin NOT NULL COMMENT '问题文本',
|
||||
`context_recall` float DEFAULT NULL COMMENT '上下文召回率',
|
||||
`context_precision` float DEFAULT NULL COMMENT '上下文精确率',
|
||||
`mrr` float DEFAULT NULL COMMENT '平均倒数排名',
|
||||
`ndcg` float DEFAULT NULL COMMENT '归一化折损累计增益',
|
||||
`faithfulness` float DEFAULT NULL COMMENT '忠实度',
|
||||
`answer_relevancy` float DEFAULT NULL COMMENT '答案相关性',
|
||||
`correctness` float DEFAULT NULL COMMENT '正确性',
|
||||
`retrieved_contexts` json COMMENT '检索到的上下文',
|
||||
`generated_answer` text COLLATE utf8mb4_bin COMMENT 'RAG生成的答案',
|
||||
`ground_truth_answer` text COLLATE utf8mb4_bin COMMENT '参考答案',
|
||||
`ground_truth_context` json COMMENT '参考上下文',
|
||||
`retrieval_time_ms` int DEFAULT NULL COMMENT '检索耗时(毫秒)',
|
||||
`generation_time_ms` int DEFAULT NULL COMMENT '生成耗时(毫秒)',
|
||||
`error_message` text COLLATE utf8mb4_bin COMMENT '错误信息',
|
||||
`create_time` datetime NOT NULL COMMENT '创建时间',
|
||||
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_biz_seq` (`biz_seq`),
|
||||
KEY `idx_evaluation_id` (`evaluation_id`),
|
||||
KEY `idx_question_index` (`question_index`),
|
||||
KEY `idx_create_time` (`create_time`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='评估结果表';
|
||||
|
||||
-- 评估汇总表
|
||||
CREATE TABLE IF NOT EXISTS `evaluation_summaries` (
|
||||
`id` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT 'id',
|
||||
`biz_seq` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '业务流水号',
|
||||
`sys_seq` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '系统流水号',
|
||||
`evaluation_id` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '评估任务ID',
|
||||
`avg_context_recall` float DEFAULT NULL COMMENT '平均上下文召回率',
|
||||
`avg_context_precision` float DEFAULT NULL COMMENT '平均上下文精确率',
|
||||
`avg_mrr` float DEFAULT NULL COMMENT '平均倒数排名',
|
||||
`avg_ndcg` float DEFAULT NULL COMMENT '平均归一化折损累计增益',
|
||||
`avg_faithfulness` float DEFAULT NULL COMMENT '平均忠实度',
|
||||
`avg_answer_relevancy` float DEFAULT NULL COMMENT '平均答案相关性',
|
||||
`avg_correctness` float DEFAULT NULL COMMENT '平均正确性',
|
||||
`overall_score` float DEFAULT NULL COMMENT '整体评分(0-100)',
|
||||
`total_questions` int NOT NULL COMMENT '总问题数',
|
||||
`failed_questions` int DEFAULT 0 COMMENT '失败问题数',
|
||||
`create_time` datetime NOT NULL COMMENT '创建时间',
|
||||
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uniq_evaluation_id` (`evaluation_id`),
|
||||
KEY `idx_biz_seq` (`biz_seq`),
|
||||
KEY `idx_create_time` (`create_time`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='评估汇总表';
|
||||
|
||||
-- 历史趋势表
|
||||
CREATE TABLE IF NOT EXISTS `evaluation_history` (
|
||||
`id` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT 'id',
|
||||
`biz_seq` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '业务流水号',
|
||||
`sys_seq` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '系统流水号',
|
||||
`evaluation_id` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '评估任务ID',
|
||||
`metric_name` varchar(64) COLLATE utf8mb4_bin NOT NULL COMMENT '指标名称',
|
||||
`metric_value` float NOT NULL COMMENT '指标值',
|
||||
`recorded_at` datetime NOT NULL COMMENT '记录时间',
|
||||
`create_time` datetime NOT NULL COMMENT '创建时间',
|
||||
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_biz_seq` (`biz_seq`),
|
||||
KEY `idx_evaluation_id` (`evaluation_id`),
|
||||
KEY `idx_metric_name` (`metric_name`),
|
||||
KEY `idx_recorded_at` (`recorded_at`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='历史趋势表';
|
||||
@@ -0,0 +1,395 @@
|
||||
"""
|
||||
Trend analysis module for evaluation history
|
||||
"""
|
||||
|
||||
from typing import List, Dict, Any, Optional, Tuple
|
||||
from datetime import datetime, timedelta
|
||||
import statistics
|
||||
|
||||
from .history import HistoryManager
|
||||
|
||||
|
||||
class TrendAnalyzer:
|
||||
"""趋势分析器"""
|
||||
|
||||
def __init__(self, history_manager: HistoryManager):
|
||||
"""
|
||||
初始化趋势分析器
|
||||
|
||||
Args:
|
||||
history_manager: 历史管理器
|
||||
"""
|
||||
self.history = history_manager
|
||||
|
||||
def compare_with_baseline(
|
||||
self,
|
||||
knowledge_base_id: str,
|
||||
current_metrics: Dict[str, float],
|
||||
baseline_evaluation_id: Optional[str] = None
|
||||
) -> Dict[str, Dict[str, Any]]:
|
||||
"""
|
||||
与基线对比
|
||||
|
||||
Args:
|
||||
knowledge_base_id: 知识库ID
|
||||
current_metrics: 当前指标值
|
||||
baseline_evaluation_id: 基线评估ID(可选,不指定则使用最新的历史记录)
|
||||
|
||||
Returns:
|
||||
对比结果字典,每个指标包含 {current, baseline, change, change_pct, status}
|
||||
"""
|
||||
# 获取基线指标
|
||||
if baseline_evaluation_id:
|
||||
baseline_records = self.history.get_history_by_evaluation(baseline_evaluation_id)
|
||||
baseline_metrics = {
|
||||
record.metric_name: record.metric_value
|
||||
for record in baseline_records
|
||||
}
|
||||
else:
|
||||
baseline_metrics = self.history.get_latest_metrics(knowledge_base_id)
|
||||
|
||||
# 对比每个指标
|
||||
comparison = {}
|
||||
for metric_name, current_value in current_metrics.items():
|
||||
baseline_value = baseline_metrics.get(metric_name)
|
||||
|
||||
if baseline_value is not None:
|
||||
change = current_value - baseline_value
|
||||
change_pct = (change / baseline_value * 100) if baseline_value != 0 else 0
|
||||
|
||||
# 判断状态
|
||||
if abs(change_pct) < 1:
|
||||
status = 'stable'
|
||||
elif change_pct > 0:
|
||||
status = 'improved'
|
||||
else:
|
||||
status = 'degraded'
|
||||
|
||||
comparison[metric_name] = {
|
||||
'current': current_value,
|
||||
'baseline': baseline_value,
|
||||
'change': change,
|
||||
'change_pct': change_pct,
|
||||
'status': status
|
||||
}
|
||||
else:
|
||||
comparison[metric_name] = {
|
||||
'current': current_value,
|
||||
'baseline': None,
|
||||
'change': None,
|
||||
'change_pct': None,
|
||||
'status': 'new'
|
||||
}
|
||||
|
||||
return comparison
|
||||
|
||||
def analyze_trend(
|
||||
self,
|
||||
knowledge_base_id: str,
|
||||
metric_name: str,
|
||||
days: int = 30
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
分析指标趋势
|
||||
|
||||
Args:
|
||||
knowledge_base_id: 知识库ID
|
||||
metric_name: 指标名称
|
||||
days: 分析天数
|
||||
|
||||
Returns:
|
||||
趋势分析结果
|
||||
"""
|
||||
trend_data = self.history.get_metric_trend(
|
||||
knowledge_base_id, metric_name, days
|
||||
)
|
||||
|
||||
if not trend_data:
|
||||
return {
|
||||
'metric': metric_name,
|
||||
'status': 'no_data',
|
||||
'message': '没有历史数据'
|
||||
}
|
||||
|
||||
values = [item['value'] for item in trend_data]
|
||||
|
||||
# 计算统计信息
|
||||
mean_value = statistics.mean(values)
|
||||
std_dev = statistics.stdev(values) if len(values) > 1 else 0
|
||||
min_value = min(values)
|
||||
max_value = max(values)
|
||||
|
||||
# 计算趋势方向
|
||||
trend_direction = self._calculate_trend_direction(values)
|
||||
|
||||
# 检测异常值
|
||||
anomalies = self._detect_anomalies(trend_data, mean_value, std_dev)
|
||||
|
||||
return {
|
||||
'metric': metric_name,
|
||||
'period_days': days,
|
||||
'data_points': len(trend_data),
|
||||
'statistics': {
|
||||
'mean': mean_value,
|
||||
'std_dev': std_dev,
|
||||
'min': min_value,
|
||||
'max': max_value,
|
||||
'latest': values[-1],
|
||||
'earliest': values[0]
|
||||
},
|
||||
'trend': {
|
||||
'direction': trend_direction,
|
||||
'change': values[-1] - values[0],
|
||||
'change_pct': ((values[-1] - values[0]) / values[0] * 100) if values[0] != 0 else 0
|
||||
},
|
||||
'anomalies': anomalies,
|
||||
'data': trend_data
|
||||
}
|
||||
|
||||
def analyze_all_trends(
|
||||
self,
|
||||
knowledge_base_id: str,
|
||||
days: int = 30
|
||||
) -> Dict[str, Dict[str, Any]]:
|
||||
"""
|
||||
分析所有指标的趋势
|
||||
|
||||
Args:
|
||||
knowledge_base_id: 知识库ID
|
||||
days: 分析天数
|
||||
|
||||
Returns:
|
||||
所有指标的趋势分析结果
|
||||
"""
|
||||
trends = self.history.get_all_metrics_trend(knowledge_base_id, days)
|
||||
|
||||
results = {}
|
||||
for metric_name, trend_data in trends.items():
|
||||
if not trend_data:
|
||||
continue
|
||||
|
||||
values = [item['value'] for item in trend_data]
|
||||
|
||||
mean_value = statistics.mean(values)
|
||||
std_dev = statistics.stdev(values) if len(values) > 1 else 0
|
||||
|
||||
trend_direction = self._calculate_trend_direction(values)
|
||||
anomalies = self._detect_anomalies(trend_data, mean_value, std_dev)
|
||||
|
||||
results[metric_name] = {
|
||||
'period_days': days,
|
||||
'data_points': len(trend_data),
|
||||
'statistics': {
|
||||
'mean': mean_value,
|
||||
'std_dev': std_dev,
|
||||
'min': min(values),
|
||||
'max': max(values),
|
||||
'latest': values[-1],
|
||||
'earliest': values[0]
|
||||
},
|
||||
'trend': {
|
||||
'direction': trend_direction,
|
||||
'change': values[-1] - values[0],
|
||||
'change_pct': ((values[-1] - values[0]) / values[0] * 100) if values[0] != 0 else 0
|
||||
},
|
||||
'anomalies': anomalies
|
||||
}
|
||||
|
||||
return results
|
||||
|
||||
def detect_regression(
|
||||
self,
|
||||
knowledge_base_id: str,
|
||||
current_metrics: Dict[str, float],
|
||||
threshold_pct: float = 5.0
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
检测性能回归
|
||||
|
||||
Args:
|
||||
knowledge_base_id: 知识库ID
|
||||
current_metrics: 当前指标值
|
||||
threshold_pct: 回归阈值百分比(默认5%)
|
||||
|
||||
Returns:
|
||||
回归问题列表
|
||||
"""
|
||||
comparison = self.compare_with_baseline(
|
||||
knowledge_base_id, current_metrics
|
||||
)
|
||||
|
||||
regressions = []
|
||||
for metric_name, comp in comparison.items():
|
||||
if comp['status'] == 'degraded' and comp['change_pct'] is not None:
|
||||
if abs(comp['change_pct']) >= threshold_pct:
|
||||
regressions.append({
|
||||
'metric': metric_name,
|
||||
'current': comp['current'],
|
||||
'baseline': comp['baseline'],
|
||||
'change_pct': comp['change_pct'],
|
||||
'severity': self._calculate_severity(comp['change_pct'])
|
||||
})
|
||||
|
||||
# 按严重程度排序
|
||||
regressions.sort(key=lambda x: abs(x['change_pct']), reverse=True)
|
||||
|
||||
return regressions
|
||||
|
||||
def generate_trend_summary(
|
||||
self,
|
||||
knowledge_base_id: str,
|
||||
days: int = 30
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
生成趋势摘要
|
||||
|
||||
Args:
|
||||
knowledge_base_id: 知识库ID
|
||||
days: 分析天数
|
||||
|
||||
Returns:
|
||||
趋势摘要
|
||||
"""
|
||||
trends = self.analyze_all_trends(knowledge_base_id, days)
|
||||
|
||||
if not trends:
|
||||
return {
|
||||
'status': 'no_data',
|
||||
'message': '没有历史数据'
|
||||
}
|
||||
|
||||
# 统计各种趋势
|
||||
improving_count = 0
|
||||
stable_count = 0
|
||||
degrading_count = 0
|
||||
total_anomalies = 0
|
||||
|
||||
for metric_name, trend in trends.items():
|
||||
direction = trend['trend']['direction']
|
||||
if direction == 'improving':
|
||||
improving_count += 1
|
||||
elif direction == 'stable':
|
||||
stable_count += 1
|
||||
elif direction == 'degrading':
|
||||
degrading_count += 1
|
||||
|
||||
total_anomalies += len(trend['anomalies'])
|
||||
|
||||
# 整体状态
|
||||
if degrading_count > improving_count:
|
||||
overall_status = 'degrading'
|
||||
elif improving_count > degrading_count:
|
||||
overall_status = 'improving'
|
||||
else:
|
||||
overall_status = 'stable'
|
||||
|
||||
return {
|
||||
'period_days': days,
|
||||
'total_metrics': len(trends),
|
||||
'overall_status': overall_status,
|
||||
'metrics_improving': improving_count,
|
||||
'metrics_stable': stable_count,
|
||||
'metrics_degrading': degrading_count,
|
||||
'total_anomalies': total_anomalies,
|
||||
'details': trends
|
||||
}
|
||||
|
||||
def _calculate_trend_direction(
|
||||
self,
|
||||
values: List[float]
|
||||
) -> str:
|
||||
"""
|
||||
计算趋势方向
|
||||
|
||||
使用简单线性回归的斜率判断趋势
|
||||
|
||||
Args:
|
||||
values: 值列表
|
||||
|
||||
Returns:
|
||||
趋势方向: 'improving', 'stable', 'degrading'
|
||||
"""
|
||||
if len(values) < 2:
|
||||
return 'stable'
|
||||
|
||||
# 计算线性回归斜率
|
||||
n = len(values)
|
||||
x = list(range(n))
|
||||
x_mean = statistics.mean(x)
|
||||
y_mean = statistics.mean(values)
|
||||
|
||||
numerator = sum((x[i] - x_mean) * (values[i] - y_mean) for i in range(n))
|
||||
denominator = sum((x[i] - x_mean) ** 2 for i in range(n))
|
||||
|
||||
if denominator == 0:
|
||||
return 'stable'
|
||||
|
||||
slope = numerator / denominator
|
||||
|
||||
# 判断趋势
|
||||
if abs(slope) < 0.001: # 斜率接近0
|
||||
return 'stable'
|
||||
elif slope > 0:
|
||||
return 'improving'
|
||||
else:
|
||||
return 'degrading'
|
||||
|
||||
def _detect_anomalies(
|
||||
self,
|
||||
trend_data: List[Dict[str, Any]],
|
||||
mean: float,
|
||||
std_dev: float,
|
||||
threshold: float = 2.0
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
检测异常值
|
||||
|
||||
使用标准差方法检测异常值
|
||||
|
||||
Args:
|
||||
trend_data: 趋势数据
|
||||
mean: 平均值
|
||||
std_dev: 标准差
|
||||
threshold: 异常阈值(标准差倍数)
|
||||
|
||||
Returns:
|
||||
异常值列表
|
||||
"""
|
||||
if std_dev == 0:
|
||||
return []
|
||||
|
||||
anomalies = []
|
||||
for item in trend_data:
|
||||
value = item['value']
|
||||
z_score = abs((value - mean) / std_dev)
|
||||
|
||||
if z_score > threshold:
|
||||
anomalies.append({
|
||||
'timestamp': item['timestamp'],
|
||||
'value': value,
|
||||
'z_score': z_score,
|
||||
'evaluation_id': item['evaluation_id']
|
||||
})
|
||||
|
||||
return anomalies
|
||||
|
||||
def _calculate_severity(self, change_pct: float) -> str:
|
||||
"""
|
||||
计算回归严重程度
|
||||
|
||||
Args:
|
||||
change_pct: 变化百分比
|
||||
|
||||
Returns:
|
||||
严重程度: 'critical', 'high', 'medium', 'low'
|
||||
"""
|
||||
abs_change = abs(change_pct)
|
||||
|
||||
if abs_change >= 20:
|
||||
return 'critical'
|
||||
elif abs_change >= 10:
|
||||
return 'high'
|
||||
elif abs_change >= 5:
|
||||
return 'medium'
|
||||
else:
|
||||
return 'low'
|
||||
@@ -0,0 +1,20 @@
|
||||
# 测试 Markdown 文件
|
||||
|
||||
## 简介
|
||||
|
||||
这是一个用于测试的 Markdown 文件。
|
||||
|
||||
## 功能
|
||||
|
||||
- 支持标题
|
||||
- 支持列表
|
||||
- 支持代码块
|
||||
|
||||
```python
|
||||
def hello():
|
||||
print('Hello, World!')
|
||||
```
|
||||
|
||||
## 结论
|
||||
|
||||
测试完成。
|
||||
@@ -0,0 +1,7 @@
|
||||
这是一个测试文本文件。
|
||||
包含多行内容。
|
||||
用于测试文档加载功能。
|
||||
|
||||
This is a test text file.
|
||||
With multiple lines.
|
||||
For testing document loading.
|
||||
@@ -0,0 +1,359 @@
|
||||
"""
|
||||
Test script for Phase 1 functionality
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
# Add parent directory to path for imports
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent))
|
||||
|
||||
# Set UTF-8 encoding for Windows
|
||||
if sys.platform == 'win32':
|
||||
import io
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
|
||||
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
|
||||
|
||||
def test_phase1():
|
||||
"""Test Phase 1 - Testset Generation"""
|
||||
|
||||
print("=" * 70)
|
||||
print("Testing Phase 1: Testset Generation")
|
||||
print("=" * 70)
|
||||
|
||||
# Test 1: Configuration loading
|
||||
print("\n[Test 1] Configuration Loading")
|
||||
print("-" * 70)
|
||||
try:
|
||||
from rag_evaluation.core.config import Config
|
||||
|
||||
# Test default config
|
||||
config = Config()
|
||||
print("✓ Default config created")
|
||||
print(f" - Default testset size: {config.testset.default_size}")
|
||||
print(f" - Database host: {config.database.host}")
|
||||
|
||||
# Test config from file
|
||||
config_file = Path("config.example.yaml")
|
||||
if config_file.exists():
|
||||
config = Config.from_file(str(config_file))
|
||||
print("✓ Config loaded from file")
|
||||
else:
|
||||
print("⚠ config.example.yaml not found, using defaults")
|
||||
|
||||
except Exception as e:
|
||||
print(f"✗ Configuration test failed: {e}")
|
||||
return False
|
||||
|
||||
# Test 2: Document loading
|
||||
print("\n[Test 2] Document Loading")
|
||||
print("-" * 70)
|
||||
try:
|
||||
from rag_evaluation.testset.document_loader import (
|
||||
TextLoader, MarkdownLoader, load_documents
|
||||
)
|
||||
|
||||
# Create test files
|
||||
test_dir = Path("./data/test_docs")
|
||||
test_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
test_txt = test_dir / "test.txt"
|
||||
with open(test_txt, 'w', encoding='utf-8') as f:
|
||||
f.write("This is a test document for RAG evaluation.")
|
||||
|
||||
test_md = test_dir / "test.md"
|
||||
with open(test_md, 'w', encoding='utf-8') as f:
|
||||
f.write("# Test Markdown\n\nThis is a markdown test document.")
|
||||
|
||||
# Test text loader
|
||||
loader = TextLoader(str(test_txt))
|
||||
docs = loader.load()
|
||||
print(f"✓ TextLoader: loaded {len(docs)} document(s)")
|
||||
print(f" - File size: {loader.get_file_size()} bytes")
|
||||
|
||||
# Test markdown loader
|
||||
loader = MarkdownLoader(str(test_md))
|
||||
docs = loader.load()
|
||||
print(f"✓ MarkdownLoader: loaded {len(docs)} document(s)")
|
||||
|
||||
# Test batch loading
|
||||
docs = load_documents([str(test_txt), str(test_md)])
|
||||
print(f"✓ Batch loading: loaded {len(docs)} document(s)")
|
||||
|
||||
except Exception as e:
|
||||
print(f"✗ Document loading test failed: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
# Test 3: Sampling and chunking
|
||||
print("\n[Test 3] Sampling and Chunking")
|
||||
print("-" * 70)
|
||||
try:
|
||||
from rag_evaluation.testset.sampling import (
|
||||
SamplingStrategy, DocumentChunker
|
||||
)
|
||||
from rag_evaluation.testset.document_loader import Document
|
||||
|
||||
# Test sampling strategy
|
||||
sampling = SamplingStrategy(config.testset)
|
||||
|
||||
# Test different file sizes
|
||||
small_size = 500 * 1024 # 500KB
|
||||
medium_size = 5 * 1024 * 1024 # 5MB
|
||||
large_size = 50 * 1024 * 1024 # 50MB
|
||||
|
||||
print(f"✓ Sampling rates:")
|
||||
print(f" - Small file (500KB): {sampling.get_sampling_rate(small_size):.2f}")
|
||||
print(f" - Medium file (5MB): {sampling.get_sampling_rate(medium_size):.2f}")
|
||||
print(f" - Large file (50MB): {sampling.get_sampling_rate(large_size):.2f}")
|
||||
|
||||
# Test chunking
|
||||
chunker = DocumentChunker(chunk_size=100, chunk_overlap=20)
|
||||
test_doc = Document(
|
||||
content="This is a test document. " * 20,
|
||||
metadata={'source': 'test.txt'}
|
||||
)
|
||||
chunks = chunker.chunk_document(test_doc)
|
||||
print(f"✓ Chunking: created {len(chunks)} chunks")
|
||||
|
||||
except Exception as e:
|
||||
print(f"✗ Sampling/chunking test failed: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
# Test 4: Testset generation
|
||||
print("\n[Test 4] Testset Generation")
|
||||
print("-" * 70)
|
||||
try:
|
||||
from rag_evaluation.testset.generator import TestsetGenerator
|
||||
|
||||
generator = TestsetGenerator(config)
|
||||
|
||||
# Generate testset
|
||||
testset = generator.generate(
|
||||
knowledge_base_id="test-kb-001",
|
||||
file_paths=[str(test_txt), str(test_md)],
|
||||
test_size=5,
|
||||
name="Test Testset"
|
||||
)
|
||||
|
||||
print(f"✓ Testset generated:")
|
||||
print(f" - ID: {testset['id']}")
|
||||
print(f" - Name: {testset['name']}")
|
||||
print(f" - Questions: {len(testset['questions'])}")
|
||||
print(f" - Question types: {set(q['type'] for q in testset['questions'])}")
|
||||
|
||||
# Test save/load
|
||||
file_path = generator.save_testset(testset)
|
||||
print(f"✓ Testset saved to: {file_path}")
|
||||
|
||||
loaded_testset = generator.load_testset(testset['id'])
|
||||
print(f"✓ Testset loaded: {loaded_testset['name']}")
|
||||
|
||||
assert loaded_testset['id'] == testset['id'], "Testset ID mismatch"
|
||||
print("✓ Save/load verification passed")
|
||||
|
||||
except Exception as e:
|
||||
print(f"✗ Testset generation test failed: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
# Test 5: Database operations
|
||||
print("\n[Test 5] Database Operations")
|
||||
print("-" * 70)
|
||||
try:
|
||||
from rag_evaluation.storage.database import DatabaseManager
|
||||
|
||||
db_manager = DatabaseManager(config.database)
|
||||
|
||||
# Test connection
|
||||
print("⚠ Skipping database test (requires MySQL connection)")
|
||||
print(" To test database:")
|
||||
print(" 1. Ensure MySQL is running")
|
||||
print(" 2. Update config.yaml with correct credentials")
|
||||
print(" 3. Run: python example.py")
|
||||
|
||||
except Exception as e:
|
||||
print(f"⚠ Database test skipped: {e}")
|
||||
|
||||
# Test 6: Utility functions
|
||||
print("\n[Test 6] Utility Functions")
|
||||
print("-" * 70)
|
||||
try:
|
||||
from rag_evaluation.utils.helpers import (
|
||||
generate_id, generate_biz_seq, generate_sys_seq,
|
||||
format_datetime, calculate_file_size_mb
|
||||
)
|
||||
|
||||
# Test ID generation
|
||||
id1 = generate_id("test")
|
||||
id2 = generate_id("test")
|
||||
assert len(id1) == 32, "ID should be 32 characters"
|
||||
assert id1 != id2, "IDs should be unique"
|
||||
print(f"✓ ID generation: {id1[:16]}...")
|
||||
|
||||
# Test sequence generation
|
||||
biz_seq = generate_biz_seq("TEST")
|
||||
sys_seq = generate_sys_seq("TEST")
|
||||
print(f"✓ Business seq: {biz_seq}")
|
||||
print(f"✓ System seq: {sys_seq}")
|
||||
|
||||
# Test datetime formatting
|
||||
dt_str = format_datetime()
|
||||
print(f"✓ Datetime format: {dt_str}")
|
||||
|
||||
# Test file size calculation
|
||||
size_mb = calculate_file_size_mb(5 * 1024 * 1024)
|
||||
assert size_mb == 5.0, "File size calculation error"
|
||||
print(f"✓ File size calculation: 5MB")
|
||||
|
||||
except Exception as e:
|
||||
print(f"✗ Utility functions test failed: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
print("\n" + "=" * 70)
|
||||
print("✅ Phase 1 Tests Completed Successfully!")
|
||||
print("=" * 70)
|
||||
return True
|
||||
|
||||
|
||||
def test_phase2():
|
||||
"""Test Phase 2 - Evaluation Execution"""
|
||||
|
||||
print("\n" + "=" * 70)
|
||||
print("Testing Phase 2: Evaluation Execution")
|
||||
print("=" * 70)
|
||||
|
||||
# Test 1: RAG Adapters
|
||||
print("\n[Test 1] RAG Adapters")
|
||||
print("-" * 70)
|
||||
try:
|
||||
from rag_evaluation.evaluation import (
|
||||
MockRAGRetriever, MockRAGGenerator, RAGEvaluationAdapter
|
||||
)
|
||||
|
||||
# Test mock retriever
|
||||
retriever = MockRAGRetriever()
|
||||
contexts = retriever.retrieve("test query", top_k=3)
|
||||
print(f"✓ MockRAGRetriever: retrieved {len(contexts)} contexts")
|
||||
assert len(contexts) == 3, "Should retrieve 3 contexts"
|
||||
|
||||
# Test mock generator
|
||||
generator = MockRAGGenerator()
|
||||
answer = generator.generate("test query", ["context1", "context2"])
|
||||
print(f"✓ MockRAGGenerator: generated answer")
|
||||
assert len(answer) > 0, "Should generate non-empty answer"
|
||||
|
||||
# Test adapter
|
||||
adapter = RAGEvaluationAdapter(retriever, generator)
|
||||
result = adapter.evaluate_question("What is RAG?")
|
||||
print(f"✓ RAGEvaluationAdapter:")
|
||||
print(f" - Retrieved contexts: {len(result['retrieved_contexts'])}")
|
||||
print(f" - Generated answer: {result['generated_answer'][:50]}...")
|
||||
print(f" - Retrieval time: {result['retrieval_time_ms']}ms")
|
||||
print(f" - Generation time: {result['generation_time_ms']}ms")
|
||||
|
||||
except Exception as e:
|
||||
print(f"✗ RAG adapters test failed: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
# Test 2: Metrics calculation
|
||||
print("\n[Test 2] Metrics Calculation")
|
||||
print("-" * 70)
|
||||
try:
|
||||
from rag_evaluation.evaluation import MetricsCalculator
|
||||
|
||||
calculator = MetricsCalculator()
|
||||
|
||||
# Test data
|
||||
question = "What is RAG?"
|
||||
retrieved = ["doc1", "doc2", "doc3"]
|
||||
ground_truth_contexts = ["doc1", "doc4"]
|
||||
generated_answer = "RAG is a retrieval augmented generation system"
|
||||
ground_truth_answer = "RAG combines retrieval and generation"
|
||||
|
||||
metrics = calculator.calculate_all(
|
||||
question=question,
|
||||
retrieved_contexts=retrieved,
|
||||
generated_answer=generated_answer,
|
||||
ground_truth_contexts=ground_truth_contexts,
|
||||
ground_truth_answer=ground_truth_answer
|
||||
)
|
||||
|
||||
print("✓ Metrics calculated:")
|
||||
for metric_name, value in metrics.items():
|
||||
print(f" - {metric_name}: {value:.3f}")
|
||||
|
||||
# Verify all metrics are present
|
||||
expected_metrics = [
|
||||
'context_recall', 'context_precision', 'mrr', 'ndcg',
|
||||
'faithfulness', 'answer_relevancy', 'correctness'
|
||||
]
|
||||
for metric in expected_metrics:
|
||||
assert metric in metrics, f"Missing metric: {metric}"
|
||||
|
||||
print("✓ All 7 metrics present")
|
||||
|
||||
except Exception as e:
|
||||
print(f"✗ Metrics calculation test failed: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
# Test 3: Evaluation executor (without database)
|
||||
print("\n[Test 3] Evaluation Executor")
|
||||
print("-" * 70)
|
||||
try:
|
||||
print("⚠ Skipping executor test (requires database)")
|
||||
print(" To test evaluation executor:")
|
||||
print(" 1. Ensure MySQL is running")
|
||||
print(" 2. Update config.yaml with correct credentials")
|
||||
print(" 3. Run: python example_phase2.py")
|
||||
|
||||
except Exception as e:
|
||||
print(f"⚠ Executor test skipped: {e}")
|
||||
|
||||
print("\n" + "=" * 70)
|
||||
print("✅ Phase 2 Tests Completed Successfully!")
|
||||
print("=" * 70)
|
||||
return True
|
||||
|
||||
|
||||
def main():
|
||||
"""Run all tests"""
|
||||
|
||||
print("\n" + "=" * 70)
|
||||
print("RAG Evaluation Framework - Test Suite")
|
||||
print("=" * 70)
|
||||
|
||||
# Run Phase 1 tests
|
||||
phase1_passed = test_phase1()
|
||||
|
||||
# Run Phase 2 tests
|
||||
phase2_passed = test_phase2()
|
||||
|
||||
# Summary
|
||||
print("\n" + "=" * 70)
|
||||
print("Test Summary")
|
||||
print("=" * 70)
|
||||
print(f"Phase 1: {'✅ PASSED' if phase1_passed else '✗ FAILED'}")
|
||||
print(f"Phase 2: {'✅ PASSED' if phase2_passed else '✗ FAILED'}")
|
||||
|
||||
if phase1_passed and phase2_passed:
|
||||
print("\n🎉 All tests passed!")
|
||||
return 0
|
||||
else:
|
||||
print("\n⚠ Some tests failed. Please check the output above.")
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Loaded 100 of 143 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user