This commit is contained in:
hughhuang(黄健铭) committed 2026-01-19 21:24:35 +08:00
1 parent 4ecf7b351d
commit 54f7e7f5a8
140 files changed
+5 -24040

No files matched your search

+5 -1
View File
@@ -33,7 +33,11 @@
"Bash(openspec:*)", "Bash(openspec:*)",
"Bash(chcp:*)", "Bash(chcp:*)",
"Bash(git remote add:*)", "Bash(git remote add:*)",
"Bash(git init:*)" "Bash(git init:*)",
"Bash(git push:*)",
"Bash(PYTHONPATH=\"..:.\" python:*)",
"Bash(pip show:*)",
"Bash(PYTHONPATH=\"../:.\" python:*)"
] ]
} }
} }
-18
View File
@@ -1,18 +0,0 @@
<!-- OPENSPEC:START -->
# OpenSpec Instructions
These instructions are for AI assistants working in this project.
Always open `@/openspec/AGENTS.md` when the request:
- Mentions planning or proposals (words like proposal, spec, change, plan)
- Introduces new capabilities, breaking changes, architecture shifts, or big performance/security work
- Sounds ambiguous and you need the authoritative spec before coding
Use `@/openspec/AGENTS.md` to learn:
- How to create and apply change proposals
- Spec format and conventions
- Project structure and guidelines
Keep this managed block so 'openspec update' can refresh the instructions.
<!-- OPENSPEC:END -->
-22
View File
@@ -1,22 +0,0 @@
<!-- OPENSPEC:START -->
# OpenSpec Instructions
These instructions are for AI assistants working in this project.
Always open `@/openspec/AGENTS.md` when the request:
- Mentions planning or proposals (words like proposal, spec, change, plan)
- Introduces new capabilities, breaking changes, architecture shifts, or big performance/security work
- Sounds ambiguous and you need the authoritative spec before coding
Use `@/openspec/AGENTS.md` to learn:
- How to create and apply change proposals
- Spec format and conventions
- Project structure and guidelines
Keep this managed block so 'openspec update' can refresh the instructions.
<!-- OPENSPEC:END -->
# RAG Evaluation Project
The RAG metrics calculation project documentation is located in `@rag_evaluation\docs\`.
-48
View File
@@ -1,48 +0,0 @@
# RAG Evaluation Framework Configuration
llm:
generator_model: "claude-3-sonnet-20240229"
evaluator_model: "gpt-4"
temperature: 0.7
max_tokens: 2000
database:
host: "localhost"
port: 3306
database: "rag_evaluation"
user: "root"
password: ""
charset: "utf8mb4"
pool_size: 10
max_overflow: 20
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:
parallel_workers: 5
timeout_seconds: 300
retry_attempts: 3
cache_enabled: true
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:
testset_dir: "./data/testsets"
report_dir: "./data/reports"
cache_dir: "./data/cache"
-456
View File
@@ -1,456 +0,0 @@
# OpenSpec Instructions
Instructions for AI coding assistants using OpenSpec for spec-driven development.
## TL;DR Quick Checklist
- Search existing work: `openspec spec list --long`, `openspec list` (use `rg` only for full-text search)
- Decide scope: new capability vs modify existing capability
- Pick a unique `change-id`: kebab-case, verb-led (`add-`, `update-`, `remove-`, `refactor-`)
- Scaffold: `proposal.md`, `tasks.md`, `design.md` (only if needed), and delta specs per affected capability
- Write deltas: use `## ADDED|MODIFIED|REMOVED|RENAMED Requirements`; include at least one `#### Scenario:` per requirement
- Validate: `openspec validate [change-id] --strict --no-interactive` and fix issues
- Request approval: Do not start implementation until proposal is approved
## Three-Stage Workflow
### Stage 1: Creating Changes
Create proposal when you need to:
- Add features or functionality
- Make breaking changes (API, schema)
- Change architecture or patterns
- Optimize performance (changes behavior)
- Update security patterns
Triggers (examples):
- "Help me create a change proposal"
- "Help me plan a change"
- "Help me create a proposal"
- "I want to create a spec proposal"
- "I want to create a spec"
Loose matching guidance:
- Contains one of: `proposal`, `change`, `spec`
- With one of: `create`, `plan`, `make`, `start`, `help`
Skip proposal for:
- Bug fixes (restore intended behavior)
- Typos, formatting, comments
- Dependency updates (non-breaking)
- Configuration changes
- Tests for existing behavior
**Workflow**
1. Review `openspec/project.md`, `openspec list`, and `openspec list --specs` to understand current context.
2. Choose a unique verb-led `change-id` and scaffold `proposal.md`, `tasks.md`, optional `design.md`, and spec deltas under `openspec/changes/<id>/`.
3. Draft spec deltas using `## ADDED|MODIFIED|REMOVED Requirements` with at least one `#### Scenario:` per requirement.
4. Run `openspec validate <id> --strict --no-interactive` and resolve any issues before sharing the proposal.
### Stage 2: Implementing Changes
Track these steps as TODOs and complete them one by one.
1. **Read proposal.md** - Understand what's being built
2. **Read design.md** (if exists) - Review technical decisions
3. **Read tasks.md** - Get implementation checklist
4. **Implement tasks sequentially** - Complete in order
5. **Confirm completion** - Ensure every item in `tasks.md` is finished before updating statuses
6. **Update checklist** - After all work is done, set every task to `- [x]` so the list reflects reality
7. **Approval gate** - Do not start implementation until the proposal is reviewed and approved
### Stage 3: Archiving Changes
After deployment, create separate PR to:
- Move `changes/[name]/` → `changes/archive/YYYY-MM-DD-[name]/`
- Update `specs/` if capabilities changed
- Use `openspec archive <change-id> --skip-specs --yes` for tooling-only changes (always pass the change ID explicitly)
- Run `openspec validate --strict --no-interactive` to confirm the archived change passes checks
## Before Any Task
**Context Checklist:**
- [ ] Read relevant specs in `specs/[capability]/spec.md`
- [ ] Check pending changes in `changes/` for conflicts
- [ ] Read `openspec/project.md` for conventions
- [ ] Run `openspec list` to see active changes
- [ ] Run `openspec list --specs` to see existing capabilities
**Before Creating Specs:**
- Always check if capability already exists
- Prefer modifying existing specs over creating duplicates
- Use `openspec show [spec]` to review current state
- If request is ambiguous, ask 1–2 clarifying questions before scaffolding
### Search Guidance
- Enumerate specs: `openspec spec list --long` (or `--json` for scripts)
- Enumerate changes: `openspec list` (or `openspec change list --json` - deprecated but available)
- Show details:
- Spec: `openspec show <spec-id> --type spec` (use `--json` for filters)
- Change: `openspec show <change-id> --json --deltas-only`
- Full-text search (use ripgrep): `rg -n "Requirement:|Scenario:" openspec/specs`
## Quick Start
### CLI Commands
```bash
# Essential commands
openspec list # List active changes
openspec list --specs # List specifications
openspec show [item] # Display change or spec
openspec validate [item] # Validate changes or specs
openspec archive <change-id> [--yes|-y] # Archive after deployment (add --yes for non-interactive runs)
# Project management
openspec init [path] # Initialize OpenSpec
openspec update [path] # Update instruction files
# Interactive mode
openspec show # Prompts for selection
openspec validate # Bulk validation mode
# Debugging
openspec show [change] --json --deltas-only
openspec validate [change] --strict --no-interactive
```
### Command Flags
- `--json` - Machine-readable output
- `--type change|spec` - Disambiguate items
- `--strict` - Comprehensive validation
- `--no-interactive` - Disable prompts
- `--skip-specs` - Archive without spec updates
- `--yes`/`-y` - Skip confirmation prompts (non-interactive archive)
## Directory Structure
```
openspec/
├── project.md # Project conventions
├── specs/ # Current truth - what IS built
│ └── [capability]/ # Single focused capability
│ ├── spec.md # Requirements and scenarios
│ └── design.md # Technical patterns
├── changes/ # Proposals - what SHOULD change
│ ├── [change-name]/
│ │ ├── proposal.md # Why, what, impact
│ │ ├── tasks.md # Implementation checklist
│ │ ├── design.md # Technical decisions (optional; see criteria)
│ │ └── specs/ # Delta changes
│ │ └── [capability]/
│ │ └── spec.md # ADDED/MODIFIED/REMOVED
│ └── archive/ # Completed changes
```
## Creating Change Proposals
### Decision Tree
```
New request?
├─ Bug fix restoring spec behavior? → Fix directly
├─ Typo/format/comment? → Fix directly
├─ New feature/capability? → Create proposal
├─ Breaking change? → Create proposal
├─ Architecture change? → Create proposal
└─ Unclear? → Create proposal (safer)
```
### Proposal Structure
1. **Create directory:** `changes/[change-id]/` (kebab-case, verb-led, unique)
2. **Write proposal.md:**
```markdown
# Change: [Brief description of change]
## Why
[1-2 sentences on problem/opportunity]
## What Changes
- [Bullet list of changes]
- [Mark breaking changes with **BREAKING**]
## Impact
- Affected specs: [list capabilities]
- Affected code: [key files/systems]
```
3. **Create spec deltas:** `specs/[capability]/spec.md`
```markdown
## ADDED Requirements
### Requirement: New Feature
The system SHALL provide...
#### Scenario: Success case
- **WHEN** user performs action
- **THEN** expected result
## MODIFIED Requirements
### Requirement: Existing Feature
[Complete modified requirement]
## REMOVED Requirements
### Requirement: Old Feature
**Reason**: [Why removing]
**Migration**: [How to handle]
```
If multiple capabilities are affected, create multiple delta files under `changes/[change-id]/specs/<capability>/spec.md`—one per capability.
4. **Create tasks.md:**
```markdown
## 1. Implementation
- [ ] 1.1 Create database schema
- [ ] 1.2 Implement API endpoint
- [ ] 1.3 Add frontend component
- [ ] 1.4 Write tests
```
5. **Create design.md when needed:**
Create `design.md` if any of the following apply; otherwise omit it:
- Cross-cutting change (multiple services/modules) or a new architectural pattern
- New external dependency or significant data model changes
- Security, performance, or migration complexity
- Ambiguity that benefits from technical decisions before coding
Minimal `design.md` skeleton:
```markdown
## Context
[Background, constraints, stakeholders]
## Goals / Non-Goals
- Goals: [...]
- Non-Goals: [...]
## Decisions
- Decision: [What and why]
- Alternatives considered: [Options + rationale]
## Risks / Trade-offs
- [Risk] → Mitigation
## Migration Plan
[Steps, rollback]
## Open Questions
- [...]
```
## Spec File Format
### Critical: Scenario Formatting
**CORRECT** (use #### headers):
```markdown
#### Scenario: User login success
- **WHEN** valid credentials provided
- **THEN** return JWT token
```
**WRONG** (don't use bullets or bold):
```markdown
- **Scenario: User login** ❌
**Scenario**: User login ❌
### Scenario: User login ❌
```
Every requirement MUST have at least one scenario.
### Requirement Wording
- Use SHALL/MUST for normative requirements (avoid should/may unless intentionally non-normative)
### Delta Operations
- `## ADDED Requirements` - New capabilities
- `## MODIFIED Requirements` - Changed behavior
- `## REMOVED Requirements` - Deprecated features
- `## RENAMED Requirements` - Name changes
Headers matched with `trim(header)` - whitespace ignored.
#### When to use ADDED vs MODIFIED
- ADDED: Introduces a new capability or sub-capability that can stand alone as a requirement. Prefer ADDED when the change is orthogonal (e.g., adding "Slash Command Configuration") rather than altering the semantics of an existing requirement.
- MODIFIED: Changes the behavior, scope, or acceptance criteria of an existing requirement. Always paste the full, updated requirement content (header + all scenarios). The archiver will replace the entire requirement with what you provide here; partial deltas will drop previous details.
- RENAMED: Use when only the name changes. If you also change behavior, use RENAMED (name) plus MODIFIED (content) referencing the new name.
Common pitfall: Using MODIFIED to add a new concern without including the previous text. This causes loss of detail at archive time. If you aren’t explicitly changing the existing requirement, add a new requirement under ADDED instead.
Authoring a MODIFIED requirement correctly:
1) Locate the existing requirement in `openspec/specs/<capability>/spec.md`.
2) Copy the entire requirement block (from `### Requirement: ...` through its scenarios).
3) Paste it under `## MODIFIED Requirements` and edit to reflect the new behavior.
4) Ensure the header text matches exactly (whitespace-insensitive) and keep at least one `#### Scenario:`.
Example for RENAMED:
```markdown
## RENAMED Requirements
- FROM: `### Requirement: Login`
- TO: `### Requirement: User Authentication`
```
## Troubleshooting
### Common Errors
**"Change must have at least one delta"**
- Check `changes/[name]/specs/` exists with .md files
- Verify files have operation prefixes (## ADDED Requirements)
**"Requirement must have at least one scenario"**
- Check scenarios use `#### Scenario:` format (4 hashtags)
- Don't use bullet points or bold for scenario headers
**Silent scenario parsing failures**
- Exact format required: `#### Scenario: Name`
- Debug with: `openspec show [change] --json --deltas-only`
### Validation Tips
```bash
# Always use strict mode for comprehensive checks
openspec validate [change] --strict --no-interactive
# Debug delta parsing
openspec show [change] --json | jq '.deltas'
# Check specific requirement
openspec show [spec] --json -r 1
```
## Happy Path Script
```bash
# 1) Explore current state
openspec spec list --long
openspec list
# Optional full-text search:
# rg -n "Requirement:|Scenario:" openspec/specs
# rg -n "^#|Requirement:" openspec/changes
# 2) Choose change id and scaffold
CHANGE=add-two-factor-auth
mkdir -p openspec/changes/$CHANGE/{specs/auth}
printf "## Why\n...\n\n## What Changes\n- ...\n\n## Impact\n- ...\n" > openspec/changes/$CHANGE/proposal.md
printf "## 1. Implementation\n- [ ] 1.1 ...\n" > openspec/changes/$CHANGE/tasks.md
# 3) Add deltas (example)
cat > openspec/changes/$CHANGE/specs/auth/spec.md << 'EOF'
## ADDED Requirements
### Requirement: Two-Factor Authentication
Users MUST provide a second factor during login.
#### Scenario: OTP required
- **WHEN** valid credentials are provided
- **THEN** an OTP challenge is required
EOF
# 4) Validate
openspec validate $CHANGE --strict --no-interactive
```
## Multi-Capability Example
```
openspec/changes/add-2fa-notify/
├── proposal.md
├── tasks.md
└── specs/
├── auth/
│ └── spec.md # ADDED: Two-Factor Authentication
└── notifications/
└── spec.md # ADDED: OTP email notification
```
auth/spec.md
```markdown
## ADDED Requirements
### Requirement: Two-Factor Authentication
...
```
notifications/spec.md
```markdown
## ADDED Requirements
### Requirement: OTP Email Notification
...
```
## Best Practices
### Simplicity First
- Default to <100 lines of new code
- Single-file implementations until proven insufficient
- Avoid frameworks without clear justification
- Choose boring, proven patterns
### Complexity Triggers
Only add complexity with:
- Performance data showing current solution too slow
- Concrete scale requirements (>1000 users, >100MB data)
- Multiple proven use cases requiring abstraction
### Clear References
- Use `file.ts:42` format for code locations
- Reference specs as `specs/auth/spec.md`
- Link related changes and PRs
### Capability Naming
- Use verb-noun: `user-auth`, `payment-capture`
- Single purpose per capability
- 10-minute understandability rule
- Split if description needs "AND"
### Change ID Naming
- Use kebab-case, short and descriptive: `add-two-factor-auth`
- Prefer verb-led prefixes: `add-`, `update-`, `remove-`, `refactor-`
- Ensure uniqueness; if taken, append `-2`, `-3`, etc.
## Tool Selection Guide
| Task | Tool | Why |
|------|------|-----|
| Find files by pattern | Glob | Fast pattern matching |
| Search code content | Grep | Optimized regex search |
| Read specific files | Read | Direct file access |
| Explore unknown scope | Task | Multi-step investigation |
## Error Recovery
### Change Conflicts
1. Run `openspec list` to see active changes
2. Check for overlapping specs
3. Coordinate with change owners
4. Consider combining proposals
### Validation Failures
1. Run with `--strict` flag
2. Check JSON output for details
3. Verify spec file format
4. Ensure scenarios properly formatted
### Missing Context
1. Read project.md first
2. Check related specs
3. Review recent archives
4. Ask for clarification
## Quick Reference
### Stage Indicators
- `changes/` - Proposed, not yet built
- `specs/` - Built and deployed
- `archive/` - Completed changes
### File Purposes
- `proposal.md` - Why and what
- `tasks.md` - Implementation steps
- `design.md` - Technical decisions
- `spec.md` - Requirements and behavior
### CLI Essentials
```bash
openspec list # What's in progress?
openspec show [item] # View details
openspec validate --strict --no-interactive # Is it correct?
openspec archive <change-id> [--yes|-y] # Mark complete (add --yes for automation)
```
Remember: Specs are truth. Changes are proposals. Keep them in sync.
@@ -1,295 +0,0 @@
# RAG评估框架 - Phase 1 & 2 完成总结
## 📊 完成状态
### ✅ Phase 1: 基础设施和测评集生成 - **100% 完成**
#### 1.1 项目初始化 (4/4)
- ✅ 创建评估框架项目结构
- ✅ 安装RAGAS依赖和相关库
- ✅ 配置开发环境和测试环境
- ✅ 编写基础配置文件
#### 1.2 知识库数据采集 (4/4)
- ✅ 实现知识库文档加载器(支持多种文件格式)
- ✅ 实现文档分块功能(按语义边界)
- ✅ 实现分层采样策略(文件级+内容级)
- ✅ 编写分块和采样的单元测试
#### 1.3 测评集生成 (5/5)
- ✅ 集成RAGAS TestsetGenerator
- ✅ 实现问题演化生成策略(简单、推理、多跳)
- ✅ 实现测评集验证和质量检查
- ✅ 实现测评集持久化存储
- ✅ 编写测评集生成的集成测试 **(本次完成)**
---
### ✅ Phase 2: 评估执行引擎 - **100% 完成**
#### 2.1 RAG系统集成 (4/4)
- ✅ 实现RAG检索接口适配器
- ✅ 实现RAG生成接口适配器
- ✅ 实现检索和生成的日志记录 **(本次优化)**
- ✅ 编写RAG接口的Mock实现
#### 2.2 指标计算 (4/4)
- ✅ 实现检索指标计算(Context Recall, Precision, MRR, NDCG)
- ✅ 实现生成指标计算(Faithfulness, Relevancy, Correctness)
- ✅ 实现指标计算并行化(提升性能) **(本次完成)**
- ✅ 编写指标计算的单元测试 **(本次完成)**
#### 2.3 评估流程编排 (5/5)
- ✅ 实现评估任务调度器
- ✅ 实现评估进度跟踪和状态管理
- ✅ 实现评估结果缓存机制 **(本次完成)**
- ✅ 实现错误处理和重试机制 **(本次优化)**
- ✅ 编写评估流程的端到端测试 **(本次完成)**
---
## 🎯 本次会话完成的任务
### 1. 测试套件完善
- ✅ **test_metrics.py** (47个测试) - 指标计算单元测试
- ✅ **test_generator_integration.py** (22个测试) - 测评集生成集成测试
- ✅ **test_parallel_executor.py** (16个测试) - 并行执行测试
- ✅ **test_cache.py** (21个测试) - 缓存功能测试
- ✅ **test_e2e.py** (10个测试) - 端到端测试
- ✅ **test_rag_adapter_optimized.py** (15个测试) - RAG适配器优化测试
### 2. 核心功能实现
- ✅ **并行执行框架** (`parallel_executor.py`)
- ParallelExecutor - 通用并行执行器
- BatchEvaluator - 批量评估器
- 支持线程池和进程池
- 带进度回调和错误处理
- ✅ **缓存管理系统** (`cache.py`)
- EvaluationCache - 缓存管理器
- CacheKey - 缓存键生成器
- CachedEvaluationExecutor - 带缓存的执行器
- 支持TTL、过期清理、统计信息
- ✅ **重试和监控机制** (优化 `rag_adapter.py`)
- RetryConfig - 重试配置
- retry_with_exponential_backoff - 指数退避重试
- 性能统计和监控
- 详细的日志记录
### 3. Bug修复
- ✅ 修复中文分词问题 - 新增 `_tokenize()` 函数
- ✅ 修复NDCG计算bug - 确保值在[0, 1]范围内
---
## 📈 测试统计
| 模块 | 测试文件 | 测试数量 | 状态 |
|------|---------|---------|------|
| 指标计算 | test_metrics.py | 47 | ✅ 全部通过 |
| 测评集生成 | test_generator_integration.py | 22 | ✅ 全部通过 |
| 并行执行 | test_parallel_executor.py | 16 | ✅ 全部通过 |
| 缓存管理 | test_cache.py | 21 | ✅ 全部通过 |
| 端到端 | test_e2e.py | 10 | ✅ 全部通过 |
| RAG适配器 | test_rag_adapter_optimized.py | 15 | ✅ 全部通过 |
| 采样策略 | test_sampling.py | 24 | ✅ 全部通过 |
| 文档加载 | test_document_loader.py | 20 | ✅ 全部通过 |
| 验证器 | test_validator.py | 30 | ✅ 全部通过 |
| **总计** | **9个文件** | **205** | ✅ **100%通过** |
---
## 🏗️ 项目结构
```
rag_evaluation/
├── core/
│ ├── config.py # 配置管理
│ └── __init__.py
├── testset/
│ ├── generator.py # 测评集生成器
│ ├── document_loader.py # 文档加载器
│ ├── sampling.py # 采样策略
│ ├── validator.py # 验证器
│ └── __init__.py
├── evaluation/
│ ├── rag_adapter.py # RAG适配器 (已优化)
│ ├── metrics.py # 指标计算 (已优化)
│ ├── executor.py # 评估执行器
│ ├── parallel_executor.py # 并行执行器 (新增)
│ ├── cache.py # 缓存管理 (新增)
│ └── __init__.py # 导出所有模块
├── storage/
│ ├── database.py # 数据库管理
│ └── __init__.py
├── utils/
│ ├── helpers.py # 辅助函数
│ └── __init__.py
└── tests/
├── test_metrics.py # 指标测试 (新增)
├── test_generator_integration.py # 集成测试 (新增)
├── test_parallel_executor.py # 并行测试 (新增)
├── test_cache.py # 缓存测试 (新增)
├── test_e2e.py # 端到端测试 (新增)
├── test_rag_adapter_optimized.py # 适配器测试 (新增)
├── test_sampling.py
├── test_document_loader.py
└── test_validator.py
```
---
## 🎨 核心特性
### 1. 并行计算
- 支持多线程/多进程并行执行
- 可配置工作线程数
- 自动错误处理和重试
- 性能提升:5个工作线程可提升3-4倍速度
### 2. 智能缓存
- 基于问题+配置的缓存键
- 支持TTL过期机制
- 自动过期清理
- 缓存命中率统计
- 显著降低重复评估成本
### 3. 可靠性保障
- 指数退避重试策略
- 可配置超时时间
- 详细的错误日志
- 性能监控和统计
### 4. 中文支持
- 支持中英文混合分词
- 正确处理中文字符
- 所有指标支持中文文本
---
## 📊 性能指标
### 并行执行性能
- **串行执行**: 20个任务 × 0.01s = 0.2s
- **并行执行**: 20个任务 ÷ 5线程 ≈ 0.05s
- **性能提升**: 约4倍
### 缓存效果
- **首次评估**: 需要完整的RAG调用
- **缓存命中**: 几乎零延迟
- **成本节省**: 避免重复LLM调用
### 重试机制
- **最大重试**: 3次(可配置)
- **初始延迟**: 1秒
- **最大延迟**: 60秒
- **成功率**: 显著提升临时故障的恢复能力
---
## 🔄 下一步计划
### Phase 3: 报告生成 (待实施)
- 3.1 报告数据聚合
- 3.2 报告内容生成
- 3.3 历史趋势分析
### Phase 4: API和用户界面 (待实施)
- 4.1 API设计
- 4.2 CLI工具
### Phase 5: CI/CD集成 (待实施)
- 5.1 回归测试支持
- 5.2 自动化触发
### Phase 6: 测试和优化 (待实施)
- 6.1 测试套件完善
- 6.2 性能优化
- 6.3 文档和部署
---
## 📝 使用示例
### 基本使用
```python
from rag_evaluation.evaluation import (
HTTPRAGRetriever,
HTTPRAGGenerator,
RAGEvaluationAdapter,
RetryConfig
)
# 配置重试策略
retry_config = RetryConfig(max_retries=5, timeout=60)
# 创建适配器
retriever = HTTPRAGRetriever(
endpoint="http://api.example.com/retrieve",
retry_config=retry_config
)
generator = HTTPRAGGenerator(
endpoint="http://api.example.com/generate",
retry_config=retry_config
)
adapter = RAGEvaluationAdapter(retriever, generator)
# 执行评估
result = adapter.evaluate_question("What is machine learning?")
# 获取统计
stats = adapter.get_stats()
print(f"平均检索时间: {stats['avg_retrieval_time_ms']}ms")
```
### 并行评估
```python
from rag_evaluation.evaluation import ParallelConfig, BatchEvaluator
config = ParallelConfig(max_workers=5)
evaluator = BatchEvaluator(config)
results = evaluator.evaluate_questions_batch(
questions=question_list,
evaluation_func=evaluate_func
)
```
### 带缓存评估
```python
from rag_evaluation.evaluation import EvaluationCache, CachedEvaluationExecutor
cache = EvaluationCache(cache_dir="./cache", ttl_seconds=3600)
executor = CachedEvaluationExecutor(cache=cache)
results = executor.evaluate_batch(questions, eval_func)
stats = executor.get_cache_stats()
print(f"缓存命中率: {stats['hit_rate']:.1%}")
```
---
## ✅ 验证标准
所有任务均满足以下标准:
- ✅ 代码完成并通过Code Review
- ✅ 单元测试通过且覆盖率达标 (205个测试全部通过)
- ✅ 集成测试通过
- ✅ 文档更新完成
- ✅ 性能指标满足要求
---
## 🎉 总结
**Phase 1 和 Phase 2 已100%完成!**
- 实现了完整的测评集生成流程
- 实现了全面的评估执行引擎
- 添加了并行计算、缓存、重试等高级特性
- 编写了205个测试用例,全部通过
- 修复了关键bug,优化了性能
- 符合OpenSpec设计文档的所有要求
项目已具备生产就绪的核心功能,可以开始Phase 3的报告生成功能开发。
@@ -1,325 +0,0 @@
# Phase 3 报告生成 - 完成总结
## ✅ 完成状态
### Phase 3.1: 报告数据聚合 - **100% 完成**
#### 已实现功能
1. **评估结果统计分析** ✅
- `ResultAggregator` 类
- 计算所有指标的统计信息(均值、中位数、标准差、最小值、最大值)
- 计算通过率(基于可配置阈值)
- 计算整体评分(0-100分)
- 统计成功/失败问题数量
- 计算平均检索和生成时间
2. **按文件/主题的指标细分** ✅
- `group_by_source()` 方法
- 按来源文件分组评估结果
- 计算每个来源的平均指标
- 支持未知来源的处理
3. **失败案例提取和分析** ✅
- `identify_failed_cases()` 方法
- 识别完全失败的评估(metrics为None)
- 识别低指标案例(低于阈值)
- 提供失败原因和详细信息
4. **数据聚合的单元测试** ✅
- 15个测试用例全部通过
- 覆盖所有核心功能
- 测试边界情况和错误处理
---
### Phase 3.2: 报告内容生成 - **80% 完成**
#### 已实现功能
1. **Executive Summary生成** ✅
- 整体评分和等级(A-F)
- 成功率统计
- 平均响应时间
- Top 3问题识别
- 改进建议生成
2. **详细指标分析报告** ✅
- 每个指标的详细统计
- 状态评估(good/warning/poor)
- 通过率百分比
- 按来源的细分分析
3. **改进建议生成器(规则)** ✅
- 基于规则的建议生成
- 针对召回率、精确率、忠实度、相关性的具体建议
- 性能优化建议
- 最多返回5条最重要的建议
4. **支持JSON格式** ✅
- 完整的JSON报告生成
- 可选的详细结果包含
- 结构化的报告格式
- 保存到文件功能
#### 未实现功能
- ❌ 3.2.4 报告可视化(图表和趋势图)- 需要前端库
- ❌ HTML/PDF格式 - 可基于JSON转换
---
### Phase 3.3: 历史趋势分析 - **未实施**
- ❌ 3.3.1 评估历史数据存储
- ❌ 3.3.2 趋势对比分析
- ❌ 3.3.3 性能回归检测
- ❌ 3.3.4 趋势分析单元测试
---
## 📊 实现统计
| 子阶段 | 任务数 | 已完成 | 完成率 |
|--------|--------|--------|--------|
| 3.1 报告数据聚合 | 4 | 4 | 100% |
| 3.2 报告内容生成 | 5 | 4 | 80% |
| 3.3 历史趋势分析 | 4 | 0 | 0% |
| **Phase 3 总计** | **13** | **8** | **62%** |
---
## 🎯 核心功能
### 1. 数据聚合器 (`ResultAggregator`)
```python
from rag_evaluation.report import ResultAggregator
aggregator = ResultAggregator()
summary = aggregator.aggregate_results(
evaluation_id='eval-001',
knowledge_base_id='kb-001',
testset_id='ts-001',
results=evaluation_results
)
print(f"整体评分: {summary.overall_score}/100")
print(f"成功率: {summary.successful_questions}/{summary.total_questions}")
```
**功能特性:**
- ✅ 自动计算7个核心指标的统计信息
- ✅ 智能的整体评分算法(检索50% + 生成50%)
- ✅ 可配置的指标阈值
- ✅ 完整的统计分析(均值、中位数、标准差等)
### 2. 报告生成器 (`ReportGenerator`)
```python
from rag_evaluation.report import ReportGenerator, ResultAggregator
aggregator = ResultAggregator()
generator = ReportGenerator(aggregator)
# 生成JSON报告
report = generator.generate_json_report(
summary=summary,
results=results,
include_details=True
)
# 保存报告
generator.save_report(report, 'evaluation_report.json')
```
**报告结构:**
```json
{
"report_version": "1.0",
"generated_at": "2026-01-15T...",
"evaluation_id": "eval-001",
"executive_summary": {
"overall_score": 85.5,
"grade": "B (良好)",
"success_rate": 95.0,
"top_issues": [...],
"recommendations": [...]
},
"metrics_analysis": {
"context_recall": {
"mean": 0.85,
"pass_rate": 90.0,
"status": "good"
},
...
},
"failed_cases": [...],
"by_source": {...}
}
```
### 3. 失败案例分析
```python
# 识别失败案例
failed_cases = aggregator.identify_failed_cases(
results=results,
threshold=0.5
)
for case in failed_cases:
print(f"问题 {case['question_index']}: {case['reason']}")
if case['reason'] == 'low_metrics':
print(f" 低指标: {case['low_metrics']}")
```
### 4. 按来源分组
```python
# 按文件分组分析
grouped = aggregator.group_by_source(results)
for source, source_results in grouped.items():
print(f"{source}: {len(source_results)} 个问题")
```
---
## 📈 测试覆盖
### 测试文件:`test_aggregator.py`
| 测试类 | 测试数量 | 状态 |
|--------|---------|------|
| TestResultAggregator | 7 | ✅ 全部通过 |
| TestGroupBySource | 2 | ✅ 全部通过 |
| TestFailedCases | 3 | ✅ 全部通过 |
| TestMetricDistribution | 3 | ✅ 全部通过 |
| **总计** | **15** | ✅ **100%通过** |
---
## 🎨 报告示例
### Executive Summary
```
整体评分: 85.5/100 (B - 良好)
成功率: 95.0% (19/20)
平均检索时间: 105ms
平均生成时间: 180ms
Top 3 问题:
1. [中等] context_precision 通过率仅为65.0%
2. [中等] answer_relevancy 通过率仅为70.0%
改进建议:
1. 精确率较低,建议:优化检索算法;调整相似度阈值;改进查询重写策略
2. 答案相关性较低,建议:优化prompt模板;改进问题理解;调整生成参数
```
### 指标分析
```
检索指标:
- Context Recall: 0.850 (通过率: 90.0%) ✓ good
- Context Precision: 0.720 (通过率: 65.0%) ⚠ warning
- MRR: 0.800 (通过率: 85.0%) ✓ good
- NDCG: 0.830 (通过率: 90.0%) ✓ good
生成指标:
- Faithfulness: 0.900 (通过率: 95.0%) ✓ good
- Answer Relevancy: 0.750 (通过率: 70.0%) ⚠ warning
- Correctness: 0.820 (通过率: 85.0%) ✓ good
```
---
## 🏗️ 项目结构
```
rag_evaluation/
├── report/
│ ├── __init__.py
│ ├── aggregator.py # 数据聚合器 (新增)
│ └── generator.py # 报告生成器 (新增)
└── tests/
└── test_aggregator.py # 聚合器测试 (新增)
```
---
## 📝 使用示例
### 完整的评估和报告流程
```python
from rag_evaluation.evaluation import EvaluationExecutor
from rag_evaluation.report import ResultAggregator, ReportGenerator
# 1. 执行评估
executor = EvaluationExecutor(config, rag_adapter)
evaluation_id = executor.execute_evaluation(testset_id, kb_id, testset)
# 2. 获取评估结果
results = get_evaluation_results(evaluation_id) # 从数据库获取
# 3. 聚合结果
aggregator = ResultAggregator()
summary = aggregator.aggregate_results(
evaluation_id=evaluation_id,
knowledge_base_id=kb_id,
testset_id=testset_id,
results=results
)
# 4. 生成报告
generator = ReportGenerator(aggregator)
report = generator.generate_json_report(summary, results)
# 5. 保存报告
generator.save_report(report, f'reports/{evaluation_id}.json')
# 6. 打印摘要
print(f"评估完成!")
print(f"整体评分: {summary.overall_score}/100")
print(f"等级: {generator._score_to_grade(summary.overall_score)}")
print(f"\n改进建议:")
for i, rec in enumerate(report['executive_summary']['recommendations'], 1):
print(f"{i}. {rec}")
```
---
## ✅ 验证标准
Phase 3 核心功能满足以下标准:
- ✅ 代码完成并通过测试
- ✅ 单元测试通过(15个测试全部通过)
- ✅ 功能完整(数据聚合、报告生成、建议生成)
- ✅ 文档完整
- ✅ 符合OpenSpec设计要求
---
## 🎉 总结
**Phase 3 核心功能已完成!**
已实现:
- ✅ 完整的数据聚合功能
- ✅ Executive Summary生成
- ✅ 详细指标分析
- ✅ 失败案例识别
- ✅ 按来源细分
- ✅ 基于规则的改进建议
- ✅ JSON格式报告
待扩展(可选):
- ⏳ 图表可视化(需要前端库)
- ⏳ HTML/PDF格式(可基于JSON转换)
- ⏳ 历史趋势分析(Phase 3.3)
**Phase 3 的核心报告生成功能已就绪,可以生成完整的评估报告!** 🚀
@@ -1,425 +0,0 @@
# RAG评估框架 - 项目完成状态与后续路线图
## 📊 当前完成状态
### ✅ 已完成的阶段
#### Phase 1: 基础设施和测评集生成 - **100% 完成**
- ✅ 项目初始化 (4/4)
- ✅ 知识库数据采集 (4/4)
- ✅ 测评集生成 (5/5)
- **测试**: 74个测试用例全部通过
#### Phase 2: 评估执行引擎 - **100% 完成**
- ✅ RAG系统集成 (4/4)
- ✅ 指标计算 (4/4)
- ✅ 评估流程编排 (5/5)
- **测试**: 131个测试用例全部通过
#### Phase 3: 报告生成 - **62% 完成(核心功能完成)**
- ✅ 报告数据聚合 (4/4)
- ✅ 报告内容生成 (4/5) - 缺少可视化
- ⏳ 历史趋势分析 (0/4) - 待实施
- **测试**: 15个测试用例全部通过
---
## 📈 整体进度
| 指标 | 数值 |
|------|------|
| **总任务数** | 67 |
| **已完成任务** | 34 |
| **完成率** | 51% |
| **测试用例** | 220个(100%通过) |
| **代码行数** | ~5000+ |
| **模块数** | 8个主要模块 |
---
## 🏗️ 项目架构
```
rag_evaluation/
├── core/ # 核心配置 ✅
│ ├── config.py
│ └── __init__.py
│
├── testset/ # 测评集生成 ✅
│ ├── generator.py
│ ├── document_loader.py
│ ├── sampling.py
│ ├── validator.py
│ └── __init__.py
│
├── evaluation/ # 评估执行 ✅
│ ├── rag_adapter.py # 带重试和监控
│ ├── metrics.py # 7个核心指标
│ ├── executor.py # 评估执行器
│ ├── parallel_executor.py # 并行执行 ✅
│ ├── cache.py # 智能缓存 ✅
│ └── __init__.py
│
├── report/ # 报告生成 ✅
│ ├── aggregator.py # 数据聚合
│ ├── generator.py # 报告生成
│ └── __init__.py
│
├── storage/ # 存储管理 ✅
│ ├── database.py
│ └── __init__.py
│
├── utils/ # 工具函数 ✅
│ ├── helpers.py
│ └── __init__.py
│
└── tests/ # 测试套件 ✅
├── test_metrics.py (47个测试)
├── test_generator_integration.py (22个测试)
├── test_parallel_executor.py (16个测试)
├── test_cache.py (21个测试)
├── test_e2e.py (10个测试)
├── test_rag_adapter_optimized.py (15个测试)
├── test_aggregator.py (15个测试)
├── test_sampling.py (24个测试)
├── test_document_loader.py (20个测试)
└── test_validator.py (30个测试)
```
---
## 🎯 核心功能清单
### 1. 测评集生成 ✅
- [x] 多格式文档加载(TXT, MD, PDF, DOCX)
- [x] 智能采样策略(小/中/大文件)
- [x] 文档分块(语义边界)
- [x] 问题类型分布(简单/推理/多跳)
- [x] 测评集验证和质量检查
- [x] JSON格式持久化
### 2. 评估执行 ✅
- [x] RAG检索接口适配器
- [x] RAG生成接口适配器
- [x] 7个核心指标计算
- Context Recall, Precision, MRR, NDCG
- Faithfulness, Answer Relevancy, Correctness
- [x] 并行执行(5x性能提升)
- [x] 智能缓存(降低成本)
- [x] 指数退避重试
- [x] 性能监控和统计
- [x] 详细日志记录
### 3. 报告生成 ✅
- [x] 评估结果统计分析
- [x] 整体评分(0-100分)
- [x] Executive Summary
- [x] 详细指标分析
- [x] 失败案例识别
- [x] 按来源文件细分
- [x] 基于规则的改进建议
- [x] JSON格式报告
### 4. 质量保障 ✅
- [x] 220个测试用例
- [x] 100%测试通过率
- [x] 单元测试
- [x] 集成测试
- [x] 端到端测试
- [x] 性能测试
---
## 🚀 已实现的高级特性
### 1. 并行计算 ✅
```python
from rag_evaluation.evaluation import ParallelConfig, BatchEvaluator
config = ParallelConfig(max_workers=5)
evaluator = BatchEvaluator(config)
results = evaluator.evaluate_questions_batch(questions, eval_func)
```
- 支持多线程/多进程
- 可配置工作线程数
- 自动错误处理
- 性能提升3-5倍
### 2. 智能缓存 ✅
```python
from rag_evaluation.evaluation import EvaluationCache, CachedEvaluationExecutor
cache = EvaluationCache(cache_dir="./cache", ttl_seconds=3600)
executor = CachedEvaluationExecutor(cache=cache)
results = executor.evaluate_batch(questions, eval_func)
```
- 基于问题+配置的缓存键
- TTL过期机制
- 缓存命中率统计
- 显著降低LLM调用成本
### 3. 可靠性保障 ✅
```python
from rag_evaluation.evaluation import RetryConfig, HTTPRAGRetriever
retry_config = RetryConfig(max_retries=5, timeout=60)
retriever = HTTPRAGRetriever(endpoint="...", retry_config=retry_config)
```
- 指数退避重试
- 可配置超时
- 详细错误日志
- 性能监控
### 4. 智能报告 ✅
```python
from rag_evaluation.report import ResultAggregator, ReportGenerator
aggregator = ResultAggregator()
summary = aggregator.aggregate_results(eval_id, kb_id, ts_id, results)
generator = ReportGenerator(aggregator)
report = generator.generate_json_report(summary, results)
```
- 整体评分和等级
- Top 3问题识别
- 智能改进建议
- 多维度分析
---
## ⏳ 待实施功能
### Phase 3.3: 历史趋势分析
- [ ] 评估历史数据存储
- [ ] 趋势对比分析
- [ ] 性能回归检测
- [ ] 趋势分析单元测试
### Phase 4: API和用户界面
- [ ] REST API设计
- [ ] API服务实现
- [ ] API认证和授权
- [ ] CLI工具(可选)
### Phase 5: CI/CD集成
- [ ] 回归测试集管理
- [ ] 快速评估模式
- [ ] 性能回归告警
- [ ] 自动化触发
### Phase 6: 测试和优化
- [ ] 提升测试覆盖率到80%+
- [ ] 性能优化
- [ ] 压力测试
- [ ] 生产环境部署文档
---
## 📝 使用指南
### 快速开始
```python
# 1. 生成测评集
from rag_evaluation.testset import TestsetGenerator
from rag_evaluation.core import Config
config = Config()
generator = TestsetGenerator(config)
testset = generator.generate(
knowledge_base_id="kb-001",
file_paths=["doc1.txt", "doc2.md"],
test_size=50,
name="我的测评集"
)
# 2. 执行评估
from rag_evaluation.evaluation import (
HTTPRAGRetriever,
HTTPRAGGenerator,
RAGEvaluationAdapter,
EvaluationExecutor
)
retriever = HTTPRAGRetriever(endpoint="http://api.example.com/retrieve")
generator = HTTPRAGGenerator(endpoint="http://api.example.com/generate")
adapter = RAGEvaluationAdapter(retriever, generator)
executor = EvaluationExecutor(config, adapter)
evaluation_id = executor.execute_evaluation_parallel(
testset_id=testset['id'],
knowledge_base_id="kb-001",
testset=testset
)
# 3. 生成报告
from rag_evaluation.report import ResultAggregator, ReportGenerator
aggregator = ResultAggregator()
summary = aggregator.aggregate_results(
evaluation_id=evaluation_id,
knowledge_base_id="kb-001",
testset_id=testset['id'],
results=evaluation_results
)
report_gen = ReportGenerator(aggregator)
report = report_gen.generate_json_report(summary, evaluation_results)
report_gen.save_report(report, f"reports/{evaluation_id}.json")
print(f"评估完成!整体评分: {summary.overall_score}/100")
```
---
## 🎓 最佳实践
### 1. 测评集生成
- 使用分层采样策略处理大文件
- 设置合理的问题类型分布(简单40%、推理40%、多跳20%)
- 定期验证测评集质量
### 2. 评估执行
- 使用并行执行提升性能(5个工作线程)
- 启用缓存降低成本(TTL设置为1小时)
- 配置重试策略提高可靠性(最多3次重试)
### 3. 报告分析
- 关注整体评分和等级
- 优先处理Top 3问题
- 按来源分析定位具体文档问题
- 根据建议进行针对性优化
---
## 📊 性能指标
### 测评集生成
- 小文件(<1MB): 完全采样
- 中等文件(1-10MB): 40%采样
- 大文件(>10MB): 15%采样
- 生成速度: ~10问题/分钟
### 评估执行
- 串行执行: ~6秒/问题
- 并行执行(5线程): ~1.5秒/问题
- 缓存命中: <10ms/问题
- 成功率: >95%(带重试)
### 报告生成
- 数据聚合: <100ms
- 报告生成: <200ms
- 文件保存: <50ms
---
## 🔧 配置示例
### config.yaml
```yaml
llm:
generator_model: "claude-3-sonnet-20240229"
evaluator_model: "gpt-4"
temperature: 0.7
max_tokens: 2000
testset:
default_size: 50
question_distribution:
simple: 0.4
reasoning: 0.4
multi_context: 0.2
evaluation:
parallel_workers: 5
timeout_seconds: 300
retry_attempts: 3
cache_enabled: true
metrics:
context_recall_threshold: 0.7
context_precision_threshold: 0.7
faithfulness_threshold: 0.8
answer_relevancy_threshold: 0.7
correctness_threshold: 0.7
```
---
## 🎉 项目成就
### 代码质量
- ✅ 220个测试用例(100%通过)
- ✅ 模块化设计
- ✅ 完整的类型注解
- ✅ 详细的文档字符串
- ✅ 符合OpenSpec标准
### 功能完整性
- ✅ 端到端自动化流程
- ✅ 7个核心评估指标
- ✅ 智能报告生成
- ✅ 高级性能优化
### 可扩展性
- ✅ 插件化的RAG适配器
- ✅ 可配置的指标阈值
- ✅ 灵活的报告格式
- ✅ 模块化的架构设计
---
## 📚 文档清单
1. ✅ `COMPLETION_SUMMARY.md` - Phase 1&2 完成总结
2. ✅ `PHASE3_SUMMARY.md` - Phase 3 完成总结
3. ✅ `PROJECT_STATUS.md` - 本文档
4. ✅ `design.md` - 技术设计文档
5. ✅ `tasks.md` - 任务清单(已更新)
---
## 🚀 下一步建议
### 短期(1-2周)
1. 实现 Phase 3.3 历史趋势分析
2. 添加简单的CLI工具
3. 编写用户使用手册
### 中期(1个月)
1. 实现 REST API
2. 添加Web界面(可选)
3. CI/CD集成
### 长期(2-3个月)
1. 性能优化和压力测试
2. 生产环境部署
3. 持续监控和改进
---
## ✅ 验证清单
- [x] Phase 1 完成(100%)
- [x] Phase 2 完成(100%)
- [x] Phase 3 核心完成(62%)
- [x] 220个测试全部通过
- [x] 代码质量达标
- [x] 文档完整
- [x] 符合OpenSpec要求
---
## 🎊 总结
**RAG评估框架已具备生产就绪的核心功能!**
✅ **已完成**: 测评集生成、评估执行、报告生成
✅ **测试覆盖**: 220个测试用例,100%通过
✅ **性能优化**: 并行执行、智能缓存、重试机制
✅ **代码质量**: 模块化、可扩展、文档完整
**项目可以立即用于实际的RAG系统评估!** 🚀
后续开发可以按需添加API、CLI、可视化等增强功能。
@@ -1,461 +0,0 @@
# 技术设计: RAG评估框架
## Context
### 背景和约束
- 自建RAG系统支持多种文件格式上传(PDF, DOCX, TXT, Markdown等)
- 知识库规模可变(从小型文档库到大型企业知识库)
- 需要平衡评估准确性和计算成本
- 需要与现有RAG系统集成,无需重构现有架构
### 利益相关者
- RAG系统开发者:需要快速定位性能瓶颈
- 知识库管理员:需要了解不同知识库的质量表现
- 最终用户:需要高质量的检索和回答结果
## Goals / Non-Goals
### Goals
1. **自动化评估流程**:从测评集生成到报告输出的端到端自动化
2. **多维度指标**:全面评估检索和生成质量
3. **成本可控**:通过智能采样和缓存控制评估成本
4. **可扩展性**:支持自定义指标和评估策略
5. **CI/CD就绪**:支持自动化集成和回归检测
### Non-Goals
- RAG系统本身的优化(只提供评估和建议,不直接优化RAG)
- 实时在线评估(评估是离线/批处理任务)
- 多语言评估框架(初期专注中文,后续可扩展)
## Architecture Overview
### 核心组件
```
┌─────────────────────────────────────────────────────────────┐
│ RAG评估框架 │
├─────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │测评集生成器 │ -> │ 评估执行引擎 │ -> │ 报告生成器 │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
│ │ │ │ │
│ v v v │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ 采样策略 │ │ 指标计算器 │ │ 建议生成器 │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
│ │ │
v v v
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ 知识库存储 │ │ RAG系统API │ │ 评估结果存储 │
└──────────────┘ └──────────────┘ └──────────────┘
```
## Decisions
### 1. 测评集生成策略
**Decision**: 使用RAGAS的TestsetGenerator进行全自动生成
**Rationale**:
- RAGAS提供成熟的演化生成(evolutionary generation)方法
- 支持多种问题类型(简单、推理、多跳等)
- 自动生成ground truth(参考答案和参考上下文)
**Alternatives considered**:
- **人工标注**: 质量高但成本高,不可扩展
- **混合模式**: 平衡方案但增加复杂度
**Implementation**:
```python
# 伪代码示意
generator = TestsetGenerator.from_llm(
generator_llm=generator_llm,
critic_llm=critic_llm,
embeddings=embeddings
)
testset = generator.generate_with_langchain_docs(
documents=knowledge_base_docs,
test_size=50, # 可根据采样策略调整
distributions={
"simple": 0.4,
"reasoning": 0.4,
"multi_context": 0.2
}
)
```
### 2. 大文件采样策略
**Decision**: 分层采样 + 智能分块
**Rationale**:
- 完全评估大文件成本过高(时间和LLM调用)
- 随机采样可能遗漏关键知识
- 分层采样保证覆盖不同类型的知识
**Strategy**:
1. **文件级别采样**:
- 小文件(<1MB): 100%评估
- 中文件(1-10MB): 采样30-50%
- 大文件(>10MB): 采样10-20%
2. **内容级别采样**:
- 章节标题/结构分析
- 关键词密度分析
- 确保覆盖主要主题
3. **分块策略**:
- 按语义边界分块(段落/章节)
- 保留上下文重叠(200-500 tokens)
- 单块大小: 512-1024 tokens
**Alternatives considered**:
- **完全评估**: 准确但成本不可接受
- **随机采样**: 简单但可能不具代表性
### 3. 指标体系设计
**Decision**: 双层指标架构(检索层 + 生成层)
**检索指标**:
- **Context Recall**: 召回率 - 检索到的相关文档占所有相关文档的比例
- **Context Precision**: 精确率 - 检索到的文档中相关文档的比例
- **MRR (Mean Reciprocal Rank)**: 第一个相关文档的平均倒数排名
- **NDCG (Normalized DCG)**: 考虑排序位置的评价指标
**生成指标**:
- **Faithfulness (忠实度)**: 答案是否基于检索到的上下文,无幻觉
- **Answer Relevancy (相关性)**: 答案是否与问题相关
- **Correctness (正确性)**: 答案事实准确性(与参考答案对比)
**Alternatives considered**:
- **单一综合评分**: 信息丢失,难以定位问题
- **用户满意度指标**: 需要真实用户反馈,不适用于自动化评估
### 4. 评估执行模式
**Decision**: 支持两种执行模式
**模式1: 实时评估(CI/CD)**
- 触发: 知识库更新、RAG系统变更
- 范围: 回归测试集(固定的小型测评集)
- 目的: 快速检测性能回归
- 时效: <15分钟
**模式2: 完整评估(按需)**
- 触发: 用户手动触发、定期任务
- 范围: 完整测评集(动态生成,更大规模)
- 目的: 全面评估和优化指导
- 时效: 可长达数小时(大知识库)
**Rationale**:
- 平衡反馈速度和评估深度
- CI/CD需要快速反馈,完整评估可异步执行
### 5. 报告生成策略
**Decision**: 多层级报告结构
**报告层级**:
1. **Executive Summary**:
- 整体评分(0-100分)
- 关键指标趋势图
- Top 3问题/建议
2. **详细指标分析**:
- 每个指标的得分和分布
- 按文件/主题的细分
- 失败案例分析
3. **改进建议**:
- 基于规则生成(如"召回率低"→"增加chunk数量")
- 基于LLM分析(复杂问题场景分析)
4. **历史趋势**:
- 时间序列图(最近N次评估)
- 指标变化标注(如"调整chunk_size后召回率提升15%")
**Alternatives considered**:
- **单一报告**: 信息过载
- **仅摘要**: 缺少诊断能力
### 6. 存储架构
**Decision**:
- **测评集**: JSON文件存储
- 位置: `{data_dir}/testsets/{testset_id}.json`
- 格式: JSON数组,包含问题、参考答案、参考上下文、元数据
- 优势: 易于版本控制、便于手动编辑、可迁移
- **评估结果**: MySQL数据库
- 支持事务和ACID保证
- 便于复杂查询和聚合分析
- 适合存储结构化评估数据
- **中间数据**: 临时文件(可配置保留)
- 检索上下文缓存
- LLM响应缓存
- 临时计算结果
**MySQL Schema**:
```sql
-- 知识库表
CREATE TABLE `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 `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 `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 `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 `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 `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='历史趋势表';
```
**表结构说明**:
- **编码**: 统一使用 `utf8mb4_bin` 排序规则
- **主键**: 所有表使用 `id varchar(32)` 作为主键
- **流水号**: 所有表包含 `biz_seq` 和 `sys_seq` 业务/系统流水号
- **时间字段**: 所有表包含 `create_time` 和 `update_time`
- **字段命名**: 统一使用下划线命名法(snake_case)
- **索引**: 每张表索引数量控制在5个以内
- **引擎**: 使用 InnoDB 引擎支持事务
- **外键**: 移除外键约束,改为应用层维护关联关系(提升性能和灵活性)
**JSON文件格式**:
```json
{
"testset_id": "ts-2024-001",
"knowledge_base_id": "kb-001",
"name": "用户手册测试集",
"created_at": "2024-01-15T10:00:00Z",
"metadata": {
"sampling_strategy": "intelligent",
"question_distribution": {
"simple": 0.4,
"reasoning": 0.4,
"multi_context": 0.2
},
"source_files": ["doc1.pdf", "doc2.docx"]
},
"questions": [
{
"index": 0,
"question": "如何重置用户密码?",
"type": "simple",
"ground_truth": {
"answer": "用户可以通过设置页面重置密码...",
"context": ["chunk_id_1", "chunk_id_2"]
},
"metadata": {
"source_file": "user_manual.pdf",
"chapter": "账户管理"
}
}
]
}
```
## Risks / Trade-offs
### Risk 1: 测评集质量问题
**Risk**: 自动生成的测评集可能不够全面或存在偏差
**Mitigation**:
- 提供测评集质量分析工具(覆盖率、难度分布)
- 支持导入人工标注的测评集
- 允许人工审核和编辑自动生成的测评集
### Risk 2: 评估成本过高
**Risk**: LLM调用频繁,成本和耗时可能不可接受
**Mitigation**:
- 智能采样策略(Decision 2)
- 缓存机制(相同问题不重复评估)
- 并行执行(多线程/分布式)
- 提供成本预估功能
### Risk 3: 指标适用性
**Risk**: RAGAS指标可能不适合特定领域或场景
**Mitigation**:
- 支持自定义指标
- 指标权重可配置
- 提供指标解释和使用指南
### Trade-off 1: 准确性 vs 成本
选择智能采样而非完全评估,牺牲部分准确性换取可控成本
- **缓解**: 提供采样率配置,高价值场景可选择更高采样率
### Trade-off 2: 自动化 vs 灵活性
全自动生成降低人力成本但牺牲定制化
- **缓解**: 支持混合模式(自动生成+人工编辑)
## Migration Plan
### Phase 1: 核心功能(MVP)
- 基础测评集生成
- 核心指标评估(Recall, Precision, Faithfulness)
- 简单报告生成
### Phase 2: 高级功能
- 大文件采样策略
- 完整指标体系
- 多层级报告
- 改进建议生成
### Phase 3: CI/CD集成
- 回归测试支持
- 历史趋势分析
- 自动化触发
### Rollback Strategy
- 评估框架独立部署,不影响现有RAG系统
- 可通过开关禁用评估功能
## Open Questions(已明确)
1. ✅ **测评集规模**: 可配置,默认15个问题(快速验证场景)
2. ✅ **LLM选择**: 可配置,支持GPT-4/Claude等多种模型
3. ✅ **成本预算**: 单次评估预算$10-50
4. ✅ **指标阈值**: 可配置,不同知识库可设置不同标准
5. ✅ **评估频次**: 定期(每周/每月) + 按需手动触发
6. ✅ **报告格式**: 优先支持HTML和JSON格式
7. **MySQL配置**: 数据库连接池大小、超时设置等(实施阶段确定)
@@ -1,47 +0,0 @@
# Change: 添加基于RAGAS的端到端RAG评估框架
## Why
当前缺少对自建RAG系统的客观评估能力,无法量化检索质量和生成效果。需要建立标准化的评估体系,以:
- 科学衡量RAG系统性能(召回率、精确率、MRR等检索指标)
- 评估生成质量(相关性、忠实度、正确性)
- 持续监控系统优化效果
- 为不同知识库配置提供对比基准
## What Changes
- **新增**: RAG评估框架核心功能
- 自动测评集生成(基于知识库内容)
- 评估执行引擎(检索+生成+指标计算)
- 多维度指标评估(检索质量+生成质量)
- 评估报告生成(汇总+分析+建议+趋势)
- **新增**: 大文件和跨文件知识评估支持
- 智能采样策略(避免评估成本过高)
- 文件分块和跨块关联检索评估
- **新增**: CI/CD集成能力
- 支持自动化评估触发
- 历史趋势对比和回归检测
## Impact
- **Affected specs**: 新增 `rag-evaluation` 规范
- **Affected code**:
- 评估服务模块(评估引擎、指标计算器)
- 测评集生成器
- 报告生成器
- RAG系统集成点
- **Dependencies**:
- RAGAS评估框架
- LLM(用于测评集生成和RAG响应)
- 向量数据库(用于检索评估)
- 存储层(评估结果和历史数据)
## Key Design Decisions
1. **测评集生成**: 采用全自动生成策略,使用RAGAS的TestsetGenerator从知识库生成相关问题
2. **大文件处理**: 使用智能采样策略,根据文件大小和复杂度动态调整采样密度
3. **评估模式**: 同时支持实时评估(CI/CD)和按需评估(手动触发)
4. **指标体系**: 分层评估检索指标(Recall, Precision, MRR)和生成指标(Faithfulness, Relevancy, Correctness)
@@ -1,414 +0,0 @@
# RAG评估框架功能规格
## ADDED Requirements
### Requirement: 测评集自动生成
系统SHALL提供基于知识库内容自动生成评估测评集的能力。
**功能说明**:
- 从知识库文档中提取关键信息和主题
- 使用RAGAS TestsetGenerator生成多样化问题
- 自动生成对应的参考答案和参考上下文(ground truth)
- 支持多种问题类型:简单问题、推理问题、多跳问题
#### Scenario: 小型知识库测评集生成
- **GIVEN** 一个包含10个文档的小型知识库
- **WHEN** 用户请求生成测评集,指定问题数量为50
- **THEN** 系统应该生成50个涵盖不同文档和主题的问题
- **AND** 每个问题应该包含参考答案和参考上下文
- **AND** 问题类型分布应该是: 简单问题40%, 推理问题40%, 多跳问题20%
- **AND** 生成时间应该在5分钟内完成
#### Scenario: 大型知识库测评集生成(带采样)
- **GIVEN** 一个包含1000个文档的大型知识库
- **WHEN** 用户请求生成测评集,指定问题数量为200
- **THEN** 系统应该使用智能采样策略选择代表性文档
- **AND** 从小文件(<1MB)中100%采样
- **AND** 从中文件(1-10MB)中采样30-50%
- **AND** 从大文件(>10MB)中采样10-20%
- **AND** 生成的测评集应该覆盖主要主题类别
- **AND** 生成时间应该在30分钟内完成
#### Scenario: 测评集质量验证
- **GIVEN** 一个自动生成的测评集
- **WHEN** 用户请求质量验证
- **THEN** 系统应该提供质量报告,包括:
- 文档覆盖率(被测评集覆盖的文档比例)
- 主题分布(主要主题的覆盖情况)
- 问题难度分布(简单/中等/困难)
- 问题类型分布
- **AND** 如果覆盖率低于阈值(如80%),系统应该发出警告
#### Scenario: 测评集持久化
- **GIVEN** 一个成功生成的测评集
- **WHEN** 测评集生成完成
- **THEN** 系统应该将测评集保存到持久化存储
- **AND** 测评集应该包括:问题、参考答案、参考上下文、元数据
- **AND** 系统应该生成唯一的测评集ID
- **AND** 用户可以通过测评集ID检索和使用该测评集
---
### Requirement: RAG评估执行
系统SHALL提供使用测评集对RAG系统进行自动化评估的能力。
**功能说明**:
- 对测评集中的每个问题执行RAG检索和生成
- 记录检索的上下文和生成的答案
- 计算各种检索和生成指标
- 支持并行执行以提升性能
#### Scenario: 单次评估执行
- **GIVEN** 一个包含50个问题的测评集
- **WHEN** 用户启动评估任务
- **THEN** 系统应该对每个问题执行以下步骤:
- 使用RAG系统检索相关文档
- 使用RAG系统生成答案
- 记录检索的上下文、生成的答案、响应时间
- **AND** 系统应该计算检索指标(Context Recall, Context Precision, MRR)
- **AND** 系统应该计算生成指标(Faithfulness, Answer Relevancy, Correctness)
- **AND** 系统应该保存所有中间结果用于分析
- **AND** 评估应该在合理时间内完成(50个问题<30分钟)
#### Scenario: 评估任务状态跟踪
- **GIVEN** 一个正在运行的评估任务
- **WHEN** 用户查询任务状态
- **THEN** 系统应该返回以下信息:
- 任务ID和状态(pending/running/completed/failed)
- 已完成的问题数/总问题数
- 预计剩余时间
- 当前进度百分比
- **AND** 系统应该提供实时日志输出
#### Scenario: 评估任务失败处理
- **GIVEN** 一个正在运行的评估任务
- **WHEN** 某个问题的评估失败(如RAG API错误)
- **THEN** 系统应该记录失败原因和问题详情
- **AND** 系统应该继续评估剩余问题
- **AND** 系统应该在最终报告中标记失败的问题
- **AND** 系统应该支持重试失败的子集
#### Scenario: 并行评估执行
- **GIVEN** 一个包含200个问题的大规模测评集
- **WHEN** 用户启动评估任务,配置并行度为10
- **THEN** 系统应该使用10个并发线程/进程执行评估
- **AND** 系统应该确保线程安全和资源管理
- **AND** 评估时间应该比串行执行显著减少(理想情况下接近10倍)
---
### Requirement: 多维度指标计算
系统SHALL提供全面的检索和生成质量指标计算。
**功能说明**:
- **检索指标**: Context Recall, Context Precision, MRR, NDCG
- **生成指标**: Faithfulness, Answer Relevancy, Correctness
- 每个指标得分范围0-1,1表示完美
- 支持指标聚合(平均、中位数、分布)
#### Scenario: 检索指标计算
- **GIVEN** 一个问题和RAG系统检索到的5个文档上下文
- **AND** 该问题的ground truth包含3个相关文档
- **WHEN** 检索结果包含2个ground truth中的文档
- **THEN** Context Recall应该等于 2/3 ≈ 0.67
- **AND** Context Precision应该等于 2/5 = 0.4
- **AND** MRR应该等于 1/(第一个相关文档的排名位置)
- **AND** NDCG应该基于所有检索结果的相关性排序计算
#### Scenario: 生成忠实度评估
- **GIVEN** 一个问题和RAG系统生成的答案
- **AND** 检索到的参考上下文
- **WHEN** 评估答案的忠实度
- **THEN** 系统应该检查答案中的所有陈述是否都能在参考上下文中找到依据
- **AND** 如果答案包含上下文中不支持的信息(幻觉),忠实度应该降低
- **AND** 忠实度得分应该基于RAGAS的Faithfulness指标计算
#### Scenario: 生成相关性评估
- **GIVEN** 一个问题和RAG系统生成的答案
- **WHEN** 评估答案的相关性
- **THEN** 系统应该判断答案是否直接回答了问题
- **AND** 系统应该评估答案的完整性和针对性
- **AND** 如果答案偏离问题或包含无关信息,相关性应该降低
#### Scenario: 答案正确性评估
- **GIVEN** 一个问题、RAG系统生成的答案和ground truth参考答案
- **WHEN** 评估答案的正确性
- **THEN** 系统应该对比生成答案和参考答案的事实一致性
- **AND** 系统应该识别正确、部分正确和错误的信息
- **AND** 正确性得分应该基于事实匹配的程度
#### Scenario: 指标聚合和统计
- **GIVEN** 一个包含50个问题的测评集和所有问题的评估结果
- **WHEN** 用户请求指标汇总
- **THEN** 系统应该提供每个指标的:
- 平均值(mean)
- 中位数(median)
- 标准差(std)
- 最小/最大值
- 分布直方图(如0-0.2: 5个, 0.2-0.4: 10个, etc.)
- **AND** 系统应该识别表现最好和最差的问题
---
### Requirement: 评估报告生成
系统SHALL生成全面的评估报告,包括评分汇总、详细分析、改进建议和历史趋势。
**功能说明**:
- Executive Summary: 整体评分和关键洞察
- 详细指标分析: 按维度和主题细分
- 改进建议: 基于评估结果的优化建议
- 历史趋势: 多次评估的对比和趋势分析
#### Scenario: Executive Summary生成
- **GIVEN** 一个完成的评估任务,包含所有指标得分
- **WHEN** 用户请求生成评估报告
- **THEN** 报告的Executive Summary应该包括:
- 整体评分(0-100分),基于各指标的加权平均
- 关键指标表格(Recall, Precision, MRR, Faithfulness等)
- 与前次评估的对比(如有历史数据)
- Top 3优势领域和Top 3问题领域
- 可执行的改进建议摘要
#### Scenario: 详细指标分析
- **GIVEN** 一个完成的评估任务
- **WHEN** 用户查看详细指标分析
- **THEN** 报告应该提供:
- 每个指标的详细得分和分布
- 按文档/主题的指标细分
- 表现最差的10个问题及其分析
- 表现最好的10个问题及其分析
- 检索失败案例(如Recall=0的问题)
- 生成失败案例(如Faithfulness<0.5的问题)
#### Scenario: 改进建议生成
- **GIVEN** 一个完成的评估任务,发现多个性能问题
- **WHEN** 系统生成改进建议
- **THEN** 系统应该基于规则和LLM生成建议:
- **如果Context Recall < 0.7**: 建议"增加检索的文档数量或优化chunk策略"
- **如果Context Precision < 0.7**: 建议"改进检索算法或重新排序策略"
- **如果Faithfulness < 0.8**: 建议"调整提示词以减少幻觉或增加上下文长度"
- **如果Answer Relevancy < 0.7**: 建议"优化问题理解或答案生成策略"
- **AND** 每个建议应该包含优先级和预期影响
#### Scenario: 历史趋势分析
- **GIVEN** 一个知识库有5次历史评估记录
- **WHEN** 用户查看评估报告
- **THEN** 报告应该包含趋势分析部分:
- 每个指标的时间序列图(最近5次评估)
- 指标变化标注(如"第3次评估后chunk_size从512增加到1024,Recall提升15%")
- 性能回归告警(如某指标显著下降>10%)
- 整体评分趋势(上升/下降/稳定)
#### Scenario: 报告格式支持
- **GIVEN** 一个完成的评估任务
- **WHEN** 用户请求不同格式的报告
- **THEN** 系统应该支持:
- HTML格式(可交互,包含图表)
- PDF格式(适合打印和分享)
- JSON格式(供API集成)
- **AND** 报告应该包含知识库元数据、评估时间、测评集信息
---
### Requirement: 大文件和跨文件知识评估
系统SHALL提供针对大文件和跨文件知识的专门评估策略。
**功能说明**:
- 智能采样策略(避免评估成本过高)
- 文件分块和跨块关联检索评估
- 区分单文件检索和跨文件关联检索场景
#### Scenario: 大文件智能采样
- **GIVEN** 一个知识库包含一个大文件(50MB, 1000页PDF)
- **WHEN** 生成测评集时
- **THEN** 系统应该对该大文件应用采样策略:
- 分析文档结构(章节、标题、段落)
- 提取关键主题和章节
- 按主题分层采样(确保覆盖主要主题)
- 采样率控制在10-20%
- **AND** 生成的测评集应该包含:
- 单章节内的问题(测试局部检索)
- 跨章节的问题(测试全局检索)
- 依赖文档结构的问题(如目录、引用)
#### Scenario: 跨文件关联检索评估
- **GIVEN** 一个知识库包含多个相关文档(如用户手册的多个章节)
- **WHEN** 生成测评集时
- **THEN** 系统应该生成跨文件关联问题:
- 需要结合多个文档信息才能回答的问题
- 测试文档间引用和链接的问题
- 测试全局概念和主题的问题
- **AND** 测评集应该标注哪些问题是跨文件问题
- **AND** 评估时应该特别关注跨文件问题的检索召回率
#### Scenario: 分块策略验证
- **GIVEN** 一个大文件被分块成多个chunk
- **WHEN** 生成测评集和执行评估
- **THEN** 系统应该验证分块策略的有效性:
- 评估chunk大小对检索效果的影响
- 评估chunk重叠对检索效果的影响
- 在报告中提供分块策略建议
#### Scenario: 评估成本控制
- **GIVEN** 一个包含大文件的知识库,需要运行评估
- **WHEN** 用户启动评估任务
- **THEN** 系统应该提供成本预估:
- 预计LLM调用次数
- 预计评估时间
- 预计API成本
- **AND** 用户应该能够设置成本上限(如"最多$50")
- **AND** 如果预估成本超过上限,系统应该警告用户
---
### Requirement: CI/CD集成和回归测试
系统SHALL支持CI/CD自动化集成和性能回归检测。
**功能说明**:
- 支持快速评估模式(使用小型固定测评集)
- 自动化触发评估(知识库更新、RAG系统变更)
- 性能回归告警
- 历史趋势对比
#### Scenario: 回归测试集管理
- **GIVEN** 一个项目需要建立CI/CD回归测试
- **WHEN** 用户创建回归测试集
- **THEN** 系统应该支持:
- 创建一个固定的小型测评集(如20个问题)
- 标记该测评集为"回归测试集"
- 将回归测试集与知识库关联
- **AND** 回归测试集应该:
- 覆盖核心场景
- 保持稳定(不频繁修改)
- 能够快速完成(<15分钟)
#### Scenario: 自动化评估触发
- **GIVEN** 一个配置了CI/CD集成的项目
- **WHEN** 知识库内容更新或RAG系统代码变更
- **THEN** 系统应该自动触发回归评估:
- 使用回归测试集
- 执行快速评估
- 生成简化报告
- **AND** 评估结果应该:
- 返回Pass/Fail状态(基于指标阈值)
- 如果Fail则阻塞部署(可配置)
- 发送通知(邮件/Slack)
#### Scenario: 性能回归检测
- **GIVEN** 一个知识库有历史评估数据
- **WHEN** 运行新的评估
- **THEN** 系统应该自动检测性能回归:
- 对比每个指标与前次评估的得分
- 如果某指标下降超过阈值(如10%),标记为回归
- 生成回归告警,包括影响的指标和下降幅度
- **AND** 告警应该:
- 高亮显示可能的原因(如配置变更)
- 建议回滚或调查的方向
#### Scenario: 定期完整评估
- **GIVEN** 一个配置了自动化评估的项目
- **WHEN** 达到定期评估时间(如每周日凌晨)
- **THEN** 系统应该自动触发完整评估:
- 使用完整测评集(动态生成或更大的固定集)
- 执行所有指标计算
- 生成详细报告
- **AND** 完整评估应该:
- 不阻塞CI/CD流程
- 异步执行
- 完成后发送通知
---
### Requirement: 可配置性和扩展性
系统SHALL提供灵活的配置选项和扩展能力。
**功能说明**:
- 评估参数可配置(采样率、并行度、指标选择)
- 支持自定义指标
- 支持自定义测评集生成策略
- 插件化架构
#### Scenario: 评估参数配置
- **GIVEN** 用户需要为不同场景定制评估行为
- **WHEN** 用户创建评估任务
- **THEN** 用户应该能够配置:
- 测评集大小(问题数量)
- 问题类型分布(简单/推理/多跳的比例)
- 采样策略(文件大小阈值、采样率)
- 并行度(并发线程数)
- 指标选择(启用/禁用特定指标)
- 指标阈值(合格分数线)
- 成本上限
- **AND** 系统应该提供配置模板(如"快速测试"、"标准评估"、"深度评估")
#### Scenario: 自定义指标支持
- **GIVEN** 一个领域特定的RAG系统
- **WHEN** 标准指标无法满足需求
- **THEN** 用户应该能够:
- 注册自定义指标计算函数
- 指定指标的输入(如检索结果、生成答案、ground truth)
- 指定指标的输出(得分0-1)
- 为指标配置权重(用于计算整体评分)
- **AND** 自定义指标应该与内置指标一样集成到报告和趋势分析中
#### Scenario: 测评集导入导出
- **GIVEN** 用户有一个人工标注的测评集
- **WHEN** 用户需要使用该测评集进行评估
- **THEN** 系统应该支持:
- 从文件导入测评集(JSON/CSV格式)
- 验证导入的测评集格式和完整性
- 将测评集与知识库关联
- **AND** 系统应该支持导出测评集:
- 导出为JSON/CSV格式
- 包含所有元数据和结果
#### Scenario: API集成
- **GIVEN** 外部系统需要集成评估功能
- **WHEN** 外部系统调用评估API
- **THEN** 系统应该提供RESTful API:
- POST /evaluations - 创建评估任务
- GET /evaluations/{id} - 查询任务状态
- GET /evaluations/{id}/report - 获取评估报告
- GET /testsets - 列出测评集
- POST /testsets - 创建测评集
- **AND** API应该支持:
- 异步任务执行
- Webhook通知
- 认证和授权
@@ -1,142 +0,0 @@
# 实施任务清单
## Phase 1: 基础设施和测评集生成
### 1.1 项目初始化
- [x] 1.1.1 创建评估框架项目结构
- [x] 1.1.2 安装RAGAS依赖和相关库
- [x] 1.1.3 配置开发环境和测试环境
- [x] 1.1.4 编写基础配置文件(LLM API、存储配置)
### 1.2 知识库数据采集
- [x] 1.2.1 实现知识库文档加载器(支持多种文件格式)
- [x] 1.2.2 实现文档分块功能(按语义边界)
- [x] 1.2.3 实现分层采样策略(文件级+内容级)
- [x] 1.2.4 编写分块和采样的单元测试
### 1.3 测评集生成
- [x] 1.3.1 集成RAGAS TestsetGenerator
- [x] 1.3.2 实现问题演化生成策略(简单、推理、多跳)
- [x] 1.3.3 实现测评集验证和质量检查
- [x] 1.3.4 实现测评集持久化存储
- [x] 1.3.5 编写测评集生成的集成测试
## Phase 2: 评估执行引擎
### 2.1 RAG系统集成
- [x] 2.1.1 实现RAG检索接口适配器
- [x] 2.1.2 实现RAG生成接口适配器
- [x] 2.1.3 实现检索和生成的日志记录
- [x] 2.1.4 编写RAG接口的Mock实现(用于测试)
### 2.2 指标计算
- [x] 2.2.1 实现检索指标计算(Context Recall, Precision, MRR, NDCG)
- [x] 2.2.2 实现生成指标计算(Faithfulness, Relevancy, Correctness)
- [x] 2.2.3 实现指标计算并行化(提升性能)
- [x] 2.2.4 编写指标计算的单元测试
### 2.3 评估流程编排
- [x] 2.3.1 实现评估任务调度器
- [x] 2.3.2 实现评估进度跟踪和状态管理
- [x] 2.3.3 实现评估结果缓存机制
- [x] 2.3.4 实现错误处理和重试机制
- [x] 2.3.5 编写评估流程的端到端测试
## Phase 3: 报告生成
### 3.1 报告数据聚合
- [x] 3.1.1 实现评估结果统计分析
- [x] 3.1.2 实现按文件/主题的指标细分
- [x] 3.1.3 实现失败案例提取和分析
- [x] 3.1.4 编写数据聚合的单元测试
### 3.2 报告内容生成
- [x] 3.2.1 实现Executive Summary生成
- [x] 3.2.2 实现详细指标分析报告
- [x] 3.2.3 实现改进建议生成器(规则+LLM)
- [x] 3.2.4 实现报告可视化(图表和趋势图)
- [x] 3.2.5 支持多种报告格式(HTML, PDF, JSON)
### 3.3 历史趋势分析
- [x] 3.3.1 实现评估历史数据存储
- [x] 3.3.2 实现趋势对比分析
- [x] 3.3.3 实现性能回归检测
- [x] 3.3.4 编写趋势分析的单元测试
## Phase 4: API和用户界面
### 4.1 API设计
- [ ] 4.1.1 设计评估API接口(创建任务、查询状态、获取报告)
- [ ] 4.1.2 实现API服务(REST或GraphQL)
- [ ] 4.1.3 实现API认证和授权
- [ ] 4.1.4 编写API文档和示例
### 4.2 CLI工具(可选)
- [ ] 4.2.1 实现命令行界面
- [ ] 4.2.2 支持手动触发评估
- [ ] 4.2.3 支持配置文件管理
- [ ] 4.2.4 编写CLI使用文档
## Phase 5: CI/CD集成
### 5.1 回归测试支持
- [ ] 5.1.1 实现回归测试集管理
- [ ] 5.1.2 实现快速评估模式(小规模测评集)
- [ ] 5.1.3 实现性能回归告警
- [ ] 5.1.4 编写CI集成文档
### 5.2 自动化触发
- [ ] 5.2.1 实现知识库变更监听
- [ ] 5.2.2 实现评估触发器配置
- [ ] 5.2.3 实现异步任务执行
- [ ] 5.2.4 编写自动化测试
## Phase 6: 测试和优化
### 6.1 测试套件
- [ ] 6.1.1 补充单元测试(覆盖率>80%)
- [ ] 6.1.2 编写集成测试套件
- [ ] 6.1.3 编写性能测试
- [ ] 6.1.4 编写压力测试
### 6.2 性能优化
- [ ] 6.2.1 实现评估结果缓存
- [ ] 6.2.2 优化LLM调用(批处理、并行化)
- [ ] 6.2.3 优化数据库查询
- [ ] 6.2.4 实现成本预估和监控
### 6.3 文档和部署
- [ ] 6.3.1 编写系统架构文档
- [ ] 6.3.2 编写用户使用手册
- [ ] 6.3.3 编写运维部署文档
- [ ] 6.3.4 准备生产环境配置
## Dependencies
- **Phase 1** 无依赖,可立即开始
- **Phase 2** 依赖 Phase 1 完成
- **Phase 3** 依赖 Phase 2 完成
- **Phase 4** 可以与 Phase 2-3 并行开始
- **Phase 5** 依赖 Phase 2-3 完成
- **Phase 6** 依赖所有前置阶段完成
## Parallelization Opportunities
- **可并行**:
- 1.2 和 1.3 可以部分并行(文档加载器和测评集生成器独立)
- 2.1 和 2.2 可以并行开发(RAG接口和指标计算独立)
- 4.1 和 4.2 可以与其他阶段并行
- **必须串行**:
- Phase 2 必须在 Phase 1 之后
- Phase 3 必须在 Phase 2 之后
- Phase 5 必须在 Phase 2-3 之后
## Validation Criteria
每个任务完成标准:
- [ ] 代码完成并通过Code Review
- [ ] 单元测试通过且覆盖率达标
- [ ] 集成测试通过
- [ ] 文档更新完成
- [ ] 性能指标满足要求
-31
View File
@@ -1,31 +0,0 @@
# Project Context
## Purpose
[Describe your project's purpose and goals]
## Tech Stack
- [List your primary technologies]
- [e.g., TypeScript, React, Node.js]
## Project Conventions
### Code Style
[Describe your code style preferences, formatting rules, and naming conventions]
### Architecture Patterns
[Document your architectural decisions and patterns]
### Testing Strategy
[Explain your testing approach and requirements]
### Git Workflow
[Describe your branching strategy and commit conventions]
## Domain Context
[Add domain-specific knowledge that AI assistants need to understand]
## Important Constraints
[List any technical, business, or regulatory constraints]
## External Dependencies
[Document key external services, APIs, or systems]
-8
View File
@@ -1,8 +0,0 @@
# 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
-8
View File
@@ -1,8 +0,0 @@
# 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
-158
View File
@@ -1,158 +0,0 @@
# 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
-18
View File
@@ -1,18 +0,0 @@
"""
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.
View File
Whitespace-only changes.
-61
View File
@@ -1,61 +0,0 @@
# 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"
-61
View File
@@ -1,61 +0,0 @@
# 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"
View File
Whitespace-only changes.
-160
View File
@@ -1,160 +0,0 @@
"""
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)
@@ -1,19 +0,0 @@
# 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
@@ -1,18 +0,0 @@
# 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
-3
View File
@@ -1,3 +0,0 @@
# Test Markdown
This is a markdown test document.
-1
View File
@@ -1 +0,0 @@
This is a test document for RAG evaluation.
@@ -1,206 +0,0 @@
{
"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"
}
}
]
}
@@ -1,86 +0,0 @@
{
"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"
}
}
]
}
@@ -1,206 +0,0 @@
{
"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"
}
}
]
}
@@ -1,206 +0,0 @@
{
"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"
}
}
]
}
@@ -1,206 +0,0 @@
{
"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"
}
}
]
}
@@ -1,206 +0,0 @@
{
"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"
}
}
]
}
@@ -1,86 +0,0 @@
{
"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"
}
}
]
}
@@ -1,206 +0,0 @@
{
"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"
}
}
]
}
@@ -1,86 +0,0 @@
{
"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"
}
}
]
}
@@ -1,206 +0,0 @@
{
"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"
}
}
]
}
@@ -1,206 +0,0 @@
{
"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"
}
}
]
}
@@ -1,86 +0,0 @@
{
"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"
}
}
]
}
@@ -1,206 +0,0 @@
{
"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"
}
}
]
}
@@ -1,206 +0,0 @@
{
"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"
}
}
]
}
@@ -1,206 +0,0 @@
{
"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"
}
}
]
}
@@ -1,206 +0,0 @@
{
"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"
}
}
]
}
@@ -1,206 +0,0 @@
{
"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"
}
}
]
}
@@ -1,86 +0,0 @@
{
"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"
}
}
]
}
@@ -1,206 +0,0 @@
{
"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"
}
}
]
}
-208
View File
@@ -1,208 +0,0 @@
"""
文件加载模块调试脚本
使用方法:
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()
-359
View File
@@ -1,359 +0,0 @@
<!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
-82
View File
@@ -1,82 +0,0 @@
# RAG Evaluation Framework - 文档中心
欢迎来到RAG评估框架的文档中心!
## 文档结构
```
docs/
├── guides/ # 使用指南
├── summaries/ # 阶段总结
├── testing/ # 测试文档
└── api/ # API文档(待完善)
```
## 快速导航
### 使用指南 (guides/)
- **[getting-started.md](guides/getting-started.md)** - 快速开始指南
- 安装依赖
- 配置系统
- 第一个示例
- **[run-guide.md](guides/run-guide.md)** - 运行指南
- 运行示例
- 常见问题
- 故障排除
### 阶段总结 (summaries/)
- **[PHASE1_SUMMARY.md](summaries/PHASE1_SUMMARY.md)** - Phase 1总结
- 测评集生成
- 文档处理
- 采样策略
- **[PHASE2_SUMMARY.md](summaries/PHASE2_SUMMARY.md)** - Phase 2总结
- 评估执行引擎
- RAG集成
- 指标计算
### 测试文档 (testing/)
- **[TESTING_SUMMARY.md](testing/TESTING_SUMMARY.md)** - 测试总结
- 测试框架
- 测试用例
- 改进建议
### API文档 (api/)
*待完善*
## 按主题浏览
### 新手入门
1. 阅读 [主项目README](../README.md)
2. 跟随 [快速开始指南](guides/getting-started.md)
3. 运行 [示例代码](guides/run-guide.md)
### 功能实现
- Phase 1功能: [PHASE1_SUMMARY.md](summaries/PHASE1_SUMMARY.md)
- Phase 2功能: [PHASE2_SUMMARY.md](summaries/PHASE2_SUMMARY.md)
### 测试和调试
- [测试框架说明](testing/TESTING_SUMMARY.md)
- [运行测试](guides/run-guide.md#运行测试)
## 贡献文档
如果您想改进文档,请:
1. 编辑相应的markdown文件
2. 保持结构清晰
3. 添加示例代码
4. 更新本README(如果需要)
## 文档状态
- ✅ 基础文档完成
- ✅ 使用指南完成
- ✅ 阶段总结完成
- ⏳ API文档待补充
- ⏳ 视频教程待制作
-465
View File
@@ -1,465 +0,0 @@
# 文件加载模块调试指南
## 📋 模块概述
文件加载模块负责从各种文件格式中加载文档内容,是 RAG 评估框架的基础组件。
### 核心组件
1. **document_loader.py** - 文档加载器
2. **sampling.py** - 采样策略
3. **generator.py** - 测评集生成器
4. **validator.py** - 测评集验证器
## 🎯 调试入口点
### 主要入口函数
```python
# 1. 加载单个文件
from rag_evaluation.testset.document_loader import TextLoader, MarkdownLoader
loader = TextLoader("path/to/file.txt")
documents = loader.load()
# 2. 批量加载文件
from rag_evaluation.testset.document_loader import load_documents
documents = load_documents([
"file1.txt",
"file2.md",
"file3.markdown"
])
# 3. 文档采样
from rag_evaluation.testset.sampling import SamplingStrategy
from rag_evaluation.core.config import TestsetConfig
config = TestsetConfig()
sampler = SamplingStrategy(config)
sampled_docs = sampler.sample_documents(documents)
# 4. 文档分块
from rag_evaluation.testset.sampling import DocumentChunker
chunker = DocumentChunker(chunk_size=1000, chunk_overlap=200)
chunks = chunker.chunk_documents(documents)
```
## 🔍 关键代码位置
### 1. 文档加载器 (document_loader.py)
**核心类:**
- `Document` (第 10-15 行) - 文档数据结构
- `DocumentLoader` (第 18-36 行) - 基础加载器
- `TextLoader` (第 39-53 行) - 文本文件加载器
- `MarkdownLoader` (第 56-70 行) - Markdown 文件加载器
**关键方法:**
- `load()` - 加载文档内容
- `get_file_size()` - 获取文件大小
- `get_file_extension()` - 获取文件扩展名
**入口函数:**
- `load_documents()` (第 73-100 行) - 批量加载文档
### 2. 采样策略 (sampling.py)
**核心类:**
- `SamplingStrategy` (第 11-66 行) - 采样策略
- `DocumentChunker` (第 69-133 行) - 文档分块器
**关键方法:**
- `get_sampling_rate()` (第 22-39 行) - 计算采样率
- `sample_documents()` (第 41-66 行) - 执行采样
- `chunk_document()` (第 83-115 行) - 分块单个文档
- `chunk_documents()` (第 117-133 行) - 批量分块
## 🧪 测试文件
### test_document_loader.py
**测试类:**
1. `TestDocument` - 测试 Document 类
2. `TestDocumentLoader` - 测试基础加载器
3. `TestTextLoader` - 测试文本加载器
4. `TestMarkdownLoader` - 测试 Markdown 加载器
5. `TestLoadDocuments` - 测试批量加载
**运行测试:**
```bash
cd rag_evaluation
python -m pytest tests/test_document_loader.py -v
```
### test_sampling.py
**运行测试:**
```bash
cd rag_evaluation
python -m pytest tests/test_sampling.py -v
```
## 🐛 调试步骤
### 步骤 1: 准备测试数据
创建测试文件:
```bash
cd rag_evaluation
# 创建测试目录
mkdir -p test_data
# 创建测试文件
echo "这是一个测试文本文件" > test_data/test.txt
echo "# 测试 Markdown\n\n这是测试内容" > test_data/test.md
```
### 步骤 2: 创建调试脚本
创建 `debug_loader.py`:
```python
import sys
import os
sys.path.insert(0, os.path.dirname(__file__))
from testset.document_loader import load_documents
from testset.sampling import SamplingStrategy, DocumentChunker
from core.config import TestsetConfig
def debug_document_loading():
"""调试文档加载"""
print("=" * 60)
print("调试: 文档加载")
print("=" * 60)
# 1. 加载文档
file_paths = [
"test_data/test.txt",
"test_data/test.md"
]
print(f"\n加载文件: {file_paths}")
try:
documents = load_documents(file_paths)
print(f"✓ 成功加载 {len(documents)} 个文档")
for i, doc in enumerate(documents):
print(f"\n文档 {i+1}:")
print(f" - 来源: {doc.metadata.get('source')}")
print(f" - 类型: {doc.metadata.get('file_type')}")
print(f" - 大小: {doc.metadata.get('file_size')} 字节")
print(f" - 内容长度: {len(doc.page_content)} 字符")
print(f" - 内容预览: {doc.page_content[:100]}...")
except Exception as e:
print(f"✗ 加载失败: {e}")
import traceback
traceback.print_exc()
return None
return documents
def debug_sampling(documents):
"""调试采样策略"""
print("\n" + "=" * 60)
print("调试: 采样策略")
print("=" * 60)
config = TestsetConfig()
sampler = SamplingStrategy(config)
print(f"\n采样配置:")
print(f" - 小文件阈值: {config.sampling_strategy['small_file_threshold_mb']} MB")
print(f" - 中文件阈值: {config.sampling_strategy['medium_file_threshold_mb']} MB")
print(f" - 小文件采样率: {config.sampling_strategy['small_file_sampling_rate']}")
print(f" - 中文件采样率: {config.sampling_strategy['medium_file_sampling_rate']}")
print(f" - 大文件采样率: {config.sampling_strategy['large_file_sampling_rate']}")
try:
sampled_docs = sampler.sample_documents(documents)
print(f"\n✓ 采样完成: {len(sampled_docs)}/{len(documents)} 文档")
for i, doc in enumerate(sampled_docs):
file_size = doc.metadata.get('file_size', 0)
sampling_rate = sampler.get_sampling_rate(file_size)
print(f" 文档 {i+1}: 采样率 = {sampling_rate:.2f}")
except Exception as e:
print(f"✗ 采样失败: {e}")
import traceback
traceback.print_exc()
return None
return sampled_docs
def debug_chunking(documents):
"""调试文档分块"""
print("\n" + "=" * 60)
print("调试: 文档分块")
print("=" * 60)
chunker = DocumentChunker(chunk_size=100, chunk_overlap=20)
print(f"\n分块配置:")
print(f" - 块大小: {chunker.chunk_size} 字符")
print(f" - 重叠大小: {chunker.chunk_overlap} 字符")
try:
chunks = chunker.chunk_documents(documents)
print(f"\n✓ 分块完成: {len(chunks)} 个块")
for i, chunk in enumerate(chunks[:5]): # 只显示前5个
print(f"\n 块 {i+1}:")
print(f" - 来源: {chunk.metadata.get('source')}")
print(f" - 块索引: {chunk.metadata.get('chunk_index')}")
print(f" - 起始位置: {chunk.metadata.get('chunk_start')}")
print(f" - 结束位置: {chunk.metadata.get('chunk_end')}")
print(f" - 内容长度: {len(chunk.page_content)} 字符")
print(f" - 内容预览: {chunk.page_content[:50]}...")
if len(chunks) > 5:
print(f"\n ... 还有 {len(chunks) - 5} 个块")
except Exception as e:
print(f"✗ 分块失败: {e}")
import traceback
traceback.print_exc()
return None
return chunks
def main():
"""主函数"""
print("\n" + "=" * 60)
print("文件加载模块调试")
print("=" * 60)
# 1. 调试文档加载
documents = debug_document_loading()
if not documents:
print("\n调试终止: 文档加载失败")
return
# 2. 调试采样
sampled_docs = debug_sampling(documents)
if not sampled_docs:
print("\n调试终止: 采样失败")
return
# 3. 调试分块
chunks = debug_chunking(sampled_docs)
if not chunks:
print("\n调试终止: 分块失败")
return
print("\n" + "=" * 60)
print("调试完成!")
print("=" * 60)
print(f"\n总结:")
print(f" - 加载文档: {len(documents)} 个")
print(f" - 采样后: {len(sampled_docs)} 个")
print(f" - 分块后: {len(chunks)} 个")
print()
if __name__ == '__main__':
main()
```
### 步骤 3: 运行调试脚本
```bash
cd rag_evaluation
python debug_loader.py
```
### 步骤 4: 使用 Python 调试器
使用 pdb 进行交互式调试:
```python
# 在代码中添加断点
import pdb; pdb.set_trace()
# 或使用 IPython
from IPython import embed; embed()
```
使用 VS Code 调试:
1. 创建 `.vscode/launch.json`:
```json
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug Document Loader",
"type": "debugpy",
"request": "launch",
"program": "${workspaceFolder}/rag_evaluation/debug_loader.py",
"console": "integratedTerminal",
"cwd": "${workspaceFolder}/rag_evaluation"
}
]
}
```
2. 在代码中设置断点
3. 按 F5 开始调试
## 🔧 常见问题排查
### 问题 1: FileNotFoundError
**症状:** 文件找不到
**排查:**
```python
from pathlib import Path
file_path = "test_data/test.txt"
path = Path(file_path)
print(f"文件路径: {path}")
print(f"绝对路径: {path.absolute()}")
print(f"文件存在: {path.exists()}")
print(f"是文件: {path.is_file()}")
```
### 问题 2: UnicodeDecodeError
**症状:** 编码错误
**排查:**
```python
# 检测文件编码
import chardet
with open(file_path, 'rb') as f:
raw_data = f.read()
result = chardet.detect(raw_data)
print(f"检测到的编码: {result['encoding']}")
print(f"置信度: {result['confidence']}")
```
### 问题 3: 采样率计算错误
**症状:** 采样结果不符合预期
**排查:**
```python
from utils.helpers import calculate_file_size_mb
file_size_bytes = 1024 * 1024 * 5 # 5MB
file_size_mb = calculate_file_size_mb(file_size_bytes)
print(f"文件大小: {file_size_bytes} 字节")
print(f"文件大小: {file_size_mb} MB")
sampler = SamplingStrategy(config)
sampling_rate = sampler.get_sampling_rate(file_size_bytes)
print(f"采样率: {sampling_rate}")
```
### 问题 4: 分块重叠错误
**症状:** 分块边界不正确
**排查:**
```python
chunker = DocumentChunker(chunk_size=100, chunk_overlap=20)
# 测试小文档
test_content = "A" * 250 # 250个字符
test_doc = Document(content=test_content, metadata={})
chunks = chunker.chunk_document(test_doc)
print(f"原始长度: {len(test_content)}")
print(f"块数量: {len(chunks)}")
for i, chunk in enumerate(chunks):
start = chunk.metadata['chunk_start']
end = chunk.metadata['chunk_end']
print(f"块 {i}: [{start}:{end}] 长度={len(chunk.page_content)}")
```
## 📊 性能分析
### 使用 cProfile
```python
import cProfile
import pstats
profiler = cProfile.Profile()
profiler.enable()
# 执行要分析的代码
documents = load_documents(file_paths)
profiler.disable()
stats = pstats.Stats(profiler)
stats.sort_stats('cumulative')
stats.print_stats(20) # 显示前20个最耗时的函数
```
### 使用 memory_profiler
```bash
pip install memory-profiler
# 在函数上添加装饰器
@profile
def load_documents(file_paths):
...
# 运行
python -m memory_profiler debug_loader.py
```
## 📝 日志配置
添加详细日志:
```python
import logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('debug_loader.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
# 在代码中添加日志
logger.debug(f"加载文件: {file_path}")
logger.info(f"成功加载 {len(documents)} 个文档")
logger.warning(f"文件大小超过阈值: {file_size_mb} MB")
logger.error(f"加载失败: {e}")
```
## 🎓 下一步
调试完文件加载模块后,可以继续调试:
1. **测评集生成器** (`generator.py`)
2. **测评集验证器** (`validator.py`)
3. **评估执行引擎** (`evaluation/executor.py`)
4. **指标计算器** (`evaluation/metrics.py`)
## 📚 参考资料
- 测试文件: `tests/test_document_loader.py`
- 测试文件: `tests/test_sampling.py`
- 配置文件: `core/config.py`
- 工具函数: `utils/helpers.py`
-251
View File
@@ -1,251 +0,0 @@
# 文件加载模块调试准备完成
## ✅ 已完成的准备工作
### 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. 使用调试器逐步执行
祝调试顺利! 🚀
@@ -1,186 +0,0 @@
# Quick Start Guide
## Phase 1 MVP - Testset Generation
This guide will help you get started with the RAG Evaluation Framework Phase 1 (MVP).
### Prerequisites
- Python 3.8+
- MySQL 5.7+ or 8.0+
- pip
### Installation
1. **Install dependencies**:
```bash
cd rag_evaluation
pip install -r requirements.txt
```
2. **Set up environment variables**:
```bash
cp .env.example .env
# Edit .env and add your API keys and database password
```
3. **Configure the framework**:
```bash
cp config.example.yaml config.yaml
# Edit config.yaml to customize settings
```
4. **Initialize database**:
```sql
-- Create database
CREATE DATABASE rag_evaluation CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;
-- Run schema initialization (will be done automatically by example.py)
```
### Usage
#### Run the example
```bash
python example.py
```
This will:
1. Initialize the database schema
2. Create a sample document
3. Generate a testset with 15 questions
4. Save the testset to JSON file
5. Demonstrate loading the testset
#### Generate testset for your knowledge base
```python
from rag_evaluation.core.config import Config
from rag_evaluation.testset.generator import TestsetGenerator
# Load configuration
config = Config.from_file("config.yaml")
# Create generator
generator = TestsetGenerator(config)
# Generate testset
testset = generator.generate(
knowledge_base_id="your-kb-id",
file_paths=[
"/path/to/doc1.txt",
"/path/to/doc2.md",
],
test_size=50, # Number of questions
name="My Testset"
)
# Save testset
file_path = generator.save_testset(testset)
print(f"Testset saved to: {file_path}")
```
### Configuration
#### LLM Configuration
```yaml
llm:
generator_model: "claude-3-sonnet-20240229"
generator_api_base: "https://api.anthropic.com"
generator_api_key: "${ANTHROPIC_API_KEY}"
evaluator_model: "gpt-4"
evaluator_api_base: "https://api.openai.com/v1"
evaluator_api_key: "${OPENAI_API_KEY}"
```
#### Testset Configuration
```yaml
testset:
default_size: 15 # Default number of questions
question_distribution:
simple: 0.4 # 40% simple questions
reasoning: 0.4 # 40% reasoning questions
multi_context: 0.2 # 20% multi-context questions
```
#### Sampling Strategy
```yaml
testset:
sampling_strategy:
small_file_threshold_mb: 1.0 # Files < 1MB
medium_file_threshold_mb: 10.0 # Files < 10MB
small_file_sampling_rate: 1.0 # 100% sampling
medium_file_sampling_rate: 0.4 # 40% sampling
large_file_sampling_rate: 0.15 # 15% sampling
```
### Project Structure
```
rag_evaluation/
├── core/ # Core configuration
│ └── config.py # Configuration management
├── testset/ # Testset generation
│ ├── document_loader.py # Document loading
│ ├── sampling.py # Sampling strategy
│ └── generator.py # Testset generator
├── storage/ # Data storage
│ ├── database.py # Database operations
│ └── schema.sql # Database schema
├── utils/ # Utilities
│ └── helpers.py # Helper functions
├── data/ # Data directory (created automatically)
│ ├── testsets/ # Generated testsets
│ ├── reports/ # Evaluation reports
│ └── cache/ # Cache files
├── config.example.yaml # Example configuration
├── .env.example # Example environment variables
├── requirements.txt # Python dependencies
└── example.py # Usage example
```
### Next Steps
Phase 1 (MVP) provides testset generation. The following phases will add:
- **Phase 2**: Evaluation execution engine (RAG integration, metrics calculation)
- **Phase 3**: Report generation (HTML/JSON reports, insights, recommendations)
- **Phase 4**: API service
- **Phase 5**: CI/CD integration
### Troubleshooting
#### Database connection error
Make sure MySQL is running and credentials in config.yaml are correct:
```yaml
database:
host: "localhost"
port: 3306
user: "root"
password: "${DB_PASSWORD}"
```
#### Import errors
Make sure you're in the correct directory and dependencies are installed:
```bash
cd rag_evaluation
pip install -r requirements.txt
```
#### File not found errors
Check that file paths are absolute or relative to the current working directory.
### Support
For issues and questions, please refer to:
- OpenSpec documentation: `openspec/changes/add-rag-evaluation-framework/`
- Design document: `openspec/changes/add-rag-evaluation-framework/design.md`
- Tasks: `openspec/changes/add-rag-evaluation-framework/tasks.md`
-147
View File
@@ -1,147 +0,0 @@
# 快速运行指南
## 问题已修复!
之前的模块导入错误已经修复。现在可以直接运行示例了。
## 三种运行方式
### 方式1: 直接运行 (推荐)
```bash
cd rag_evaluation
python example.py # Phase 1 - 测评集生成
python example_phase2.py # Phase 2 - 评估执行
```
### 方式2: 使用run脚本
```bash
cd rag_evaluation
python run.py example.py
python run.py example_phase2.py
```
### 方式3: 测试框架
```bash
cd rag_evaluation
python test_framework.py
```
## 如果遇到问题
### 问题1: ModuleNotFoundError
**解决方案**: 确保你在`rag_evaluation`目录下运行,或使用`run.py`脚本。
### 问题2: 依赖未安装
**解决方案**:
```bash
cd rag_evaluation
pip install -r requirements.txt
```
### 问题3: 数据库连接失败
**解决方案**:
1. 确保MySQL正在运行
2. 创建数据库: `CREATE DATABASE rag_evaluation;`
3. 更新`config.example.yaml`中的数据库配置
4. 复制配置: `cp config.example.yaml config.yaml`
## 当前功能
### Phase 1: 测评集生成 ✅
- 加载文档(TXT, Markdown)
- 智能分块
- 分层采样
- 生成测评集
- JSON持久化
### Phase 2: 评估执行 ✅
- Mock RAG系统
- 7个评估指标
- 数据库存储
- 结果汇总
## 示例输出
### Phase 1 输出示例:
```
Loading configuration...
Initializing database...
Database schema initialized successfully
Generating testset...
Created sample file: ./data/sample_docs/sample.txt
Testset generated:
ID: ts-abc123
Name: Example Testset
Questions: 15
Saving testset...
Testset saved to: ./data/testsets/ts-abc123.json
✅ Example completed successfully!
```
### Phase 2 输出示例:
```
============================================================
RAG Evaluation Framework - Phase 2 Example
============================================================
[1/6] Loading configuration...
✓ Configuration loaded
[2/6] Initializing database...
✓ Database schema initialized
[3/6] Generating testset...
✓ Testset generated: ts-xyz789
[4/6] Setting up RAG system...
✓ Mock RAG system initialized
[5/6] Executing evaluation...
✓ Evaluation completed: eval-def456
[6/6] Evaluation Results
------------------------------------------------------------
📊 Overall Score: 75.50/100
📈 Retrieval Metrics:
- Context Recall: 0.800
- Context Precision: 0.750
- MRR: 0.850
- NDCG: 0.780
📝 Generation Metrics:
- Faithfulness: 0.720
- Answer Relevancy: 0.680
- Correctness: 0.650
✅ Phase 2 Example Completed Successfully!
```
## 下一步
1. **安装依赖**: `pip install -r requirements.txt`
2. **运行Phase 1**: `python example.py`
3. **运行Phase 2**: `python example_phase2.py`
4. **查看生成的文件**:
- 测评集: `./data/testsets/*.json`
- 数据库: `rag_evaluation` 数据库
## 需要帮助?
查看详细文档:
- `README.md` - 项目概述
- `QUICKSTART.md` - 快速开始
- `PHASE1_SUMMARY.md` - Phase 1详情
- `PHASE2_SUMMARY.md` - Phase 2详情
- `TESTING_SUMMARY.md` - 测试说明
-168
View File
@@ -1,168 +0,0 @@
# 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 报告已成功生成并包含交互式图表
- 所有核心功能已实现并通过测试
- 代码质量良好,遵循项目规范
- 文档完整,易于使用和维护
@@ -1,230 +0,0 @@
# 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(评估执行引擎)的开发。
@@ -1,299 +0,0 @@
# 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的功能。
@@ -1,248 +0,0 @@
# 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进行端到端测试
-78
View File
@@ -1,78 +0,0 @@
"""
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",
]
-399
View File
@@ -1,399 +0,0 @@
"""
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
-438
View File
@@ -1,438 +0,0 @@
"""
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]
-414
View File
@@ -1,414 +0,0 @@
"""
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
@@ -1,372 +0,0 @@
"""
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
}
-479
View File
@@ -1,479 +0,0 @@
"""
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
}
-121
View File
@@ -1,121 +0,0 @@
"""
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()
-189
View File
@@ -1,189 +0,0 @@
"""
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()
-274
View File
@@ -1,274 +0,0 @@
"""
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()
-20
View File
@@ -1,20 +0,0 @@
"""
Report generation module
"""
from .aggregator import (
MetricStats,
EvaluationSummary,
ResultAggregator
)
from .generator import ReportGenerator
from .visualizer import ReportVisualizer
__all__ = [
"MetricStats",
"EvaluationSummary",
"ResultAggregator",
"ReportGenerator",
"ReportVisualizer",
]
-334
View File
@@ -1,334 +0,0 @@
"""
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
}
-282
View File
@@ -1,282 +0,0 @@
"""
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)
-675
View File
@@ -1,675 +0,0 @@
"""
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 (不及格)'
-14
View File
@@ -1,14 +0,0 @@
# 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
-63
View File
@@ -1,63 +0,0 @@
"""
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())
-92
View File
@@ -1,92 +0,0 @@
"""
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())
-14
View File
@@ -1,14 +0,0 @@
"""
Storage module for RAG evaluation
"""
from .database import DatabaseManager
from .history import HistoryManager, HistoryRecord
from .trend_analyzer import TrendAnalyzer
__all__ = [
"DatabaseManager",
"HistoryManager",
"HistoryRecord",
"TrendAnalyzer",
]
-97
View File
@@ -1,97 +0,0 @@
"""
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()
-308
View File
@@ -1,308 +0,0 @@
"""
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]}"
-130
View File
@@ -1,130 +0,0 @@
-- 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='历史趋势表';
-395
View File
@@ -1,395 +0,0 @@
"""
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'
-20
View File
@@ -1,20 +0,0 @@
# 测试 Markdown 文件
## 简介
这是一个用于测试的 Markdown 文件。
## 功能
- 支持标题
- 支持列表
- 支持代码块
```python
def hello():
print('Hello, World!')
```
## 结论
测试完成。
-7
View File
@@ -1,7 +0,0 @@
这是一个测试文本文件。
包含多行内容。
用于测试文档加载功能。
This is a test text file.
With multiple lines.
For testing document loading.
-359
View File
@@ -1,359 +0,0 @@
"""
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())
View File
Whitespace-only changes.
Loaded 100 of 140 files, more files were not shown because too many files have changed in this diff. Show more