Files
auto-ragas/rag_evaluation/testset/generator.py
T
2026-01-16 16:01:39 +08:00

200 lines
5.9 KiB
Python

"""
Testset generator using RAGAS
"""
from typing import List, Dict, Any, Optional
from datetime import datetime
import json
from pathlib import Path
from ..core.config import Config
from ..utils.helpers import generate_id, generate_biz_seq, generate_sys_seq, format_datetime
from .document_loader import Document, load_documents
from .sampling import SamplingStrategy, DocumentChunker
class TestsetGenerator:
"""Testset generator using RAGAS"""
def __init__(self, config: Config):
self.config = config
self.sampling_strategy = SamplingStrategy(config.testset)
self.chunker = DocumentChunker()
def generate(
self,
knowledge_base_id: str,
file_paths: List[str],
test_size: Optional[int] = None,
name: Optional[str] = None
) -> Dict[str, Any]:
"""
Generate testset from knowledge base files
Args:
knowledge_base_id: Knowledge base ID
file_paths: List of file paths in knowledge base
test_size: Number of questions to generate (default from config)
name: Testset name (optional)
Returns:
Testset dictionary
"""
if test_size is None:
test_size = self.config.testset.default_size
if name is None:
name = f"Testset-{datetime.now().strftime('%Y%m%d-%H%M%S')}"
# Load documents
documents = load_documents(file_paths)
# Apply sampling strategy
sampled_docs = self.sampling_strategy.sample_documents(documents)
# Chunk documents
chunked_docs = self.chunker.chunk_documents(sampled_docs)
# Generate testset using RAGAS
# TODO: Integrate with RAGAS TestsetGenerator
# For now, create a placeholder testset structure
testset = self._create_testset_structure(
knowledge_base_id=knowledge_base_id,
name=name,
test_size=test_size,
documents=chunked_docs
)
return testset
def _create_testset_structure(
self,
knowledge_base_id: str,
name: str,
test_size: int,
documents: List[Document]
) -> Dict[str, Any]:
"""
Create testset structure
Args:
knowledge_base_id: Knowledge base ID
name: Testset name
test_size: Number of questions
documents: List of documents
Returns:
Testset dictionary
"""
testset_id = generate_id("ts")
biz_seq = generate_biz_seq("TS")
sys_seq = generate_sys_seq("TS")
testset = {
"id": testset_id,
"biz_seq": biz_seq,
"sys_seq": sys_seq,
"knowledge_base_id": knowledge_base_id,
"name": name,
"created_at": format_datetime(),
"metadata": {
"test_size": test_size,
"question_distribution": self.config.testset.question_distribution,
"sampling_strategy": self.config.testset.sampling_strategy,
"document_count": len(documents)
},
"questions": []
}
# TODO: Generate actual questions using RAGAS
# For now, create placeholder questions
for i in range(test_size):
question = {
"index": i,
"question": f"Placeholder question {i+1}",
"type": self._get_question_type(i, test_size),
"ground_truth": {
"answer": f"Placeholder answer {i+1}",
"context": []
},
"metadata": {
"source_file": "placeholder.txt"
}
}
testset["questions"].append(question)
return testset
def _get_question_type(self, index: int, total: int) -> str:
"""
Determine question type based on distribution
Args:
index: Question index
total: Total number of questions
Returns:
Question type (simple/reasoning/multi_context)
"""
distribution = self.config.testset.question_distribution
simple_count = int(total * distribution['simple'])
reasoning_count = int(total * distribution['reasoning'])
if index < simple_count:
return "simple"
elif index < simple_count + reasoning_count:
return "reasoning"
else:
return "multi_context"
def save_testset(self, testset: Dict[str, Any], output_dir: Optional[str] = None) -> str:
"""
Save testset to JSON file
Args:
testset: Testset dictionary
output_dir: Output directory (default from config)
Returns:
File path where testset was saved
"""
if output_dir is None:
output_dir = self.config.storage.testset_dir
# Create output directory if it doesn't exist
output_path = Path(output_dir)
output_path.mkdir(parents=True, exist_ok=True)
# Save testset to JSON file
file_name = f"{testset['id']}.json"
file_path = output_path / file_name
with open(file_path, 'w', encoding='utf-8') as f:
json.dump(testset, f, ensure_ascii=False, indent=2)
return str(file_path)
def load_testset(self, testset_id: str, testset_dir: Optional[str] = None) -> Dict[str, Any]:
"""
Load testset from JSON file
Args:
testset_id: Testset ID
testset_dir: Testset directory (default from config)
Returns:
Testset dictionary
"""
if testset_dir is None:
testset_dir = self.config.storage.testset_dir
file_path = Path(testset_dir) / f"{testset_id}.json"
if not file_path.exists():
raise FileNotFoundError(f"Testset file not found: {file_path}")
with open(file_path, 'r', encoding='utf-8') as f:
testset = json.load(f)
return testset