Initial commit

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

No files matched your search

View File
Whitespace-only changes.
+100
View File
@@ -0,0 +1,100 @@
"""
Document loader for various file formats
"""
from typing import List, Dict, Any
from pathlib import Path
import os
class Document:
"""Document class to represent loaded documents"""
def __init__(self, content: str, metadata: Dict[str, Any]):
self.page_content = content
self.metadata = metadata
class DocumentLoader:
"""Base document loader"""
def __init__(self, file_path: str):
self.file_path = Path(file_path)
if not self.file_path.exists():
raise FileNotFoundError(f"File not found: {file_path}")
def load(self) -> List[Document]:
"""Load document and return list of Document objects"""
raise NotImplementedError("Subclasses must implement load()")
def get_file_size(self) -> int:
"""Get file size in bytes"""
return os.path.getsize(self.file_path)
def get_file_extension(self) -> str:
"""Get file extension"""
return self.file_path.suffix.lower()
class TextLoader(DocumentLoader):
"""Text file loader"""
def load(self) -> List[Document]:
"""Load text file"""
with open(self.file_path, 'r', encoding='utf-8') as f:
content = f.read()
metadata = {
'source': str(self.file_path),
'file_type': 'text',
'file_size': self.get_file_size()
}
return [Document(content=content, metadata=metadata)]
class MarkdownLoader(DocumentLoader):
"""Markdown file loader"""
def load(self) -> List[Document]:
"""Load markdown file"""
with open(self.file_path, 'r', encoding='utf-8') as f:
content = f.read()
metadata = {
'source': str(self.file_path),
'file_type': 'markdown',
'file_size': self.get_file_size()
}
return [Document(content=content, metadata=metadata)]
def load_documents(file_paths: List[str]) -> List[Document]:
"""
Load multiple documents from file paths
Args:
file_paths: List of file paths to load
Returns:
List of Document objects
"""
documents = []
for file_path in file_paths:
path = Path(file_path)
extension = path.suffix.lower()
if extension in ['.txt']:
loader = TextLoader(file_path)
elif extension in ['.md', '.markdown']:
loader = MarkdownLoader(file_path)
else:
# For now, treat unknown types as text
loader = TextLoader(file_path)
docs = loader.load()
documents.extend(docs)
return documents
+199
View File
@@ -0,0 +1,199 @@
"""
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
+133
View File
@@ -0,0 +1,133 @@
"""
Document sampling strategy for large files
"""
from typing import List, Dict, Any
from ..core.config import TestsetConfig
from ..utils.helpers import calculate_file_size_mb
from .document_loader import Document
class SamplingStrategy:
"""Document sampling strategy"""
def __init__(self, config: TestsetConfig):
self.config = config
self.small_threshold = config.sampling_strategy['small_file_threshold_mb']
self.medium_threshold = config.sampling_strategy['medium_file_threshold_mb']
self.small_rate = config.sampling_strategy['small_file_sampling_rate']
self.medium_rate = config.sampling_strategy['medium_file_sampling_rate']
self.large_rate = config.sampling_strategy['large_file_sampling_rate']
def get_sampling_rate(self, file_size_bytes: int) -> float:
"""
Determine sampling rate based on file size
Args:
file_size_bytes: File size in bytes
Returns:
Sampling rate (0.0 to 1.0)
"""
file_size_mb = calculate_file_size_mb(file_size_bytes)
if file_size_mb < self.small_threshold:
return self.small_rate
elif file_size_mb < self.medium_threshold:
return self.medium_rate
else:
return self.large_rate
def sample_documents(self, documents: List[Document]) -> List[Document]:
"""
Sample documents based on file size
Args:
documents: List of documents to sample
Returns:
Sampled list of documents
"""
sampled_docs = []
for doc in documents:
file_size = doc.metadata.get('file_size', 0)
sampling_rate = self.get_sampling_rate(file_size)
# For now, simple implementation: include document if sampling rate >= 1.0
# In production, implement more sophisticated sampling (e.g., stratified sampling)
if sampling_rate >= 1.0:
sampled_docs.append(doc)
elif sampling_rate > 0:
# TODO: Implement probabilistic or stratified sampling
# For now, include all documents with sampling_rate > 0
sampled_docs.append(doc)
return sampled_docs
class DocumentChunker:
"""Document chunking for large documents"""
def __init__(self, chunk_size: int = 1000, chunk_overlap: int = 200):
"""
Initialize document chunker
Args:
chunk_size: Size of each chunk in characters
chunk_overlap: Overlap between chunks in characters
"""
self.chunk_size = chunk_size
self.chunk_overlap = chunk_overlap
def chunk_document(self, document: Document) -> List[Document]:
"""
Split document into chunks
Args:
document: Document to chunk
Returns:
List of chunked documents
"""
content = document.page_content
chunks = []
start = 0
chunk_index = 0
while start < len(content):
end = start + self.chunk_size
chunk_content = content[start:end]
# Create new document for chunk
chunk_metadata = document.metadata.copy()
chunk_metadata['chunk_index'] = chunk_index
chunk_metadata['chunk_start'] = start
chunk_metadata['chunk_end'] = end
chunks.append(Document(content=chunk_content, metadata=chunk_metadata))
# Move to next chunk with overlap
start = end - self.chunk_overlap
chunk_index += 1
return chunks
def chunk_documents(self, documents: List[Document]) -> List[Document]:
"""
Chunk multiple documents
Args:
documents: List of documents to chunk
Returns:
List of all chunks from all documents
"""
all_chunks = []
for doc in documents:
chunks = self.chunk_document(doc)
all_chunks.extend(chunks)
return all_chunks
+486
View File
@@ -0,0 +1,486 @@
"""
Testset validation and quality checks
"""
from typing import Dict, Any, List, Tuple
from collections import Counter
import re
class TestsetValidationError(Exception):
"""Exception raised for testset validation errors"""
pass
class TestsetValidator:
"""Validates testset structure and quality"""
# Required fields in testset
REQUIRED_TOP_LEVEL_FIELDS = [
'id', 'biz_seq', 'sys_seq', 'knowledge_base_id',
'name', 'created_at', 'metadata', 'questions'
]
# Required fields in metadata
REQUIRED_METADATA_FIELDS = [
'test_size', 'question_distribution', 'sampling_strategy', 'document_count'
]
# Required fields in question
REQUIRED_QUESTION_FIELDS = [
'index', 'question', 'type', 'ground_truth', 'metadata'
]
# Valid question types
VALID_QUESTION_TYPES = ['simple', 'reasoning', 'multi_context']
# Valid ground truth fields
REQUIRED_GROUND_TRUTH_FIELDS = ['answer', 'context']
def __init__(self, strict_mode: bool = True):
"""
Initialize testset validator
Args:
strict_mode: If True, raises exceptions on errors. If False, collects all errors.
"""
self.strict_mode = strict_mode
def validate(self, testset: Dict[str, Any]) -> Tuple[bool, List[str]]:
"""
Validate testset structure and content
Args:
testset: Testset dictionary to validate
Returns:
Tuple of (is_valid, error_messages)
"""
errors = []
try:
# Validate top-level structure
self._validate_top_level_structure(testset, errors)
# Validate metadata
self._validate_metadata(testset, errors)
# Validate questions
self._validate_questions(testset, errors)
# Validate consistency
self._validate_consistency(testset, errors)
except TestsetValidationError as e:
if self.strict_mode:
raise
errors.append(str(e))
is_valid = len(errors) == 0
return is_valid, errors
def _validate_top_level_structure(self, testset: Dict[str, Any], errors: List[str]):
"""Validate top-level testset structure"""
if not isinstance(testset, dict):
error = "Testset must be a dictionary"
if self.strict_mode:
raise TestsetValidationError(error)
errors.append(error)
return
# Check required fields
for field in self.REQUIRED_TOP_LEVEL_FIELDS:
if field not in testset:
errors.append(f"Missing required top-level field: {field}")
# Validate ID format (32 characters)
if 'id' in testset:
if not isinstance(testset['id'], str) or len(testset['id']) != 32:
error_msg = f"Invalid ID format: must be 32-character string, got {testset.get('id')}"
if self.strict_mode:
raise TestsetValidationError(error_msg)
errors.append(error_msg)
# Validate biz_seq format
if 'biz_seq' in testset:
if not isinstance(testset['biz_seq'], str) or len(testset['biz_seq']) < 10:
errors.append(f"Invalid biz_seq format: must be string with at least 10 characters")
# Validate sys_seq format
if 'sys_seq' in testset:
if not isinstance(testset['sys_seq'], str) or len(testset['sys_seq']) < 10:
errors.append(f"Invalid sys_seq format: must be string with at least 10 characters")
# Validate knowledge_base_id
if 'knowledge_base_id' in testset:
if not isinstance(testset['knowledge_base_id'], str) or not testset['knowledge_base_id']:
errors.append("Invalid knowledge_base_id: must be non-empty string")
# Validate name
if 'name' in testset:
if not isinstance(testset['name'], str) or not testset['name'].strip():
errors.append("Invalid name: must be non-empty string")
def _validate_metadata(self, testset: Dict[str, Any], errors: List[str]):
"""Validate testset metadata"""
if 'metadata' not in testset:
errors.append("Missing metadata field")
return
metadata = testset['metadata']
if not isinstance(metadata, dict):
errors.append("Metadata must be a dictionary")
return
# Check required metadata fields
for field in self.REQUIRED_METADATA_FIELDS:
if field not in metadata:
errors.append(f"Missing required metadata field: {field}")
# Validate test_size
if 'test_size' in metadata:
if not isinstance(metadata['test_size'], int) or metadata['test_size'] <= 0:
errors.append(f"Invalid test_size: must be positive integer, got {metadata.get('test_size')}")
# Validate question_distribution
if 'question_distribution' in metadata:
dist = metadata['question_distribution']
if not isinstance(dist, dict):
errors.append("question_distribution must be a dictionary")
else:
# Check distribution sums to 1.0
dist_sum = sum(dist.values())
if not (0.99 <= dist_sum <= 1.01):
errors.append(f"question_distribution must sum to 1.0, got {dist_sum}")
# Check valid question types
for qtype in dist.keys():
if qtype not in self.VALID_QUESTION_TYPES:
errors.append(f"Invalid question type in distribution: {qtype}")
# Validate document_count
if 'document_count' in metadata:
if not isinstance(metadata['document_count'], int) or metadata['document_count'] < 0:
errors.append(f"Invalid document_count: must be non-negative integer, got {metadata.get('document_count')}")
def _validate_questions(self, testset: Dict[str, Any], errors: List[str]):
"""Validate questions array"""
if 'questions' not in testset:
errors.append("Missing questions field")
return
questions = testset['questions']
if not isinstance(questions, list):
errors.append("Questions must be a list")
return
# Check if questions list is empty
if len(questions) == 0:
errors.append("Questions list cannot be empty")
return
# Validate each question
for idx, question in enumerate(questions):
self._validate_single_question(question, idx, errors)
def _validate_single_question(self, question: Any, idx: int, errors: List[str]):
"""Validate a single question"""
if not isinstance(question, dict):
errors.append(f"Question {idx}: must be a dictionary, got {type(question).__name__}")
return
# Check required fields
for field in self.REQUIRED_QUESTION_FIELDS:
if field not in question:
errors.append(f"Question {idx}: missing required field '{field}'")
# Validate index
if 'index' in question:
if not isinstance(question['index'], int) or question['index'] < 0:
errors.append(f"Question {idx}: invalid index, must be non-negative integer")
# Validate question text
if 'question' in question:
if not isinstance(question['question'], str) or not question['question'].strip():
errors.append(f"Question {idx}: question text must be non-empty string")
elif len(question['question']) < 5:
errors.append(f"Question {idx}: question text too short (< 5 characters)")
# Validate question type
if 'type' in question:
if question['type'] not in self.VALID_QUESTION_TYPES:
errors.append(f"Question {idx}: invalid type '{question['type']}', must be one of {self.VALID_QUESTION_TYPES}")
# Validate ground_truth
if 'ground_truth' in question:
ground_truth = question['ground_truth']
if not isinstance(ground_truth, dict):
errors.append(f"Question {idx}: ground_truth must be a dictionary")
else:
# Check answer
if 'answer' in ground_truth:
if not isinstance(ground_truth['answer'], str) or not ground_truth['answer'].strip():
errors.append(f"Question {idx}: ground_truth.answer must be non-empty string")
# Check context
if 'context' in ground_truth:
if not isinstance(ground_truth['context'], list):
errors.append(f"Question {idx}: ground_truth.context must be a list")
# Validate metadata
if 'metadata' in question:
if not isinstance(question['metadata'], dict):
errors.append(f"Question {idx}: metadata must be a dictionary")
def _validate_consistency(self, testset: Dict[str, Any], errors: List[str]):
"""Validate consistency across testset"""
if 'questions' not in testset or 'metadata' not in testset:
return
questions = testset['questions']
metadata = testset['metadata']
# Check if question count matches metadata
if 'test_size' in metadata:
expected_count = metadata['test_size']
actual_count = len(questions)
if expected_count != actual_count:
errors.append(f"Inconsistent question count: metadata says {expected_count}, but found {actual_count} questions")
# Check if indices are sequential
indices = [q.get('index') for q in questions if 'index' in q]
if indices:
expected_indices = list(range(len(indices)))
if indices != expected_indices:
errors.append(f"Question indices are not sequential: expected {expected_indices}, got {indices}")
# Check for duplicate questions
question_texts = [q.get('question', '') for q in questions if 'question' in q]
duplicates = [text for text, count in Counter(question_texts).items() if count > 1 and text]
if duplicates:
errors.append(f"Found duplicate questions: {duplicates}")
class TestsetQualityChecker:
"""Checks testset quality metrics"""
def __init__(self):
"""Initialize quality checker"""
pass
def check_quality(self, testset: Dict[str, Any]) -> Dict[str, Any]:
"""
Perform quality checks on testset
Args:
testset: Testset dictionary
Returns:
Quality report dictionary with metrics and recommendations
"""
if 'questions' not in testset or not testset['questions']:
return {
'status': 'error',
'message': 'No questions found in testset',
'metrics': {},
'issues': [],
'recommendations': [],
'overall_score': 0.0
}
questions = testset['questions']
quality_report = {
'status': 'success',
'metrics': {},
'issues': [],
'recommendations': []
}
# Check 1: Question type distribution
type_dist = self._check_type_distribution(questions)
quality_report['metrics']['type_distribution'] = type_dist
# Check 2: Question length diversity
length_stats = self._check_question_length(questions)
quality_report['metrics']['question_length'] = length_stats
# Check 3: Answer completeness
answer_completeness = self._check_answer_completeness(questions)
quality_report['metrics']['answer_completeness'] = answer_completeness
# Check 4: Context coverage
context_coverage = self._check_context_coverage(questions)
quality_report['metrics']['context_coverage'] = context_coverage
# Check 5: Question diversity
diversity_score = self._check_question_diversity(questions)
quality_report['metrics']['diversity_score'] = diversity_score
# Generate recommendations
self._generate_recommendations(quality_report)
# Overall quality score
quality_report['overall_score'] = float(self._calculate_overall_score(quality_report))
return quality_report
def _check_type_distribution(self, questions: List[Dict]) -> Dict[str, Any]:
"""Check question type distribution"""
type_counts = Counter(q.get('type', 'unknown') for q in questions)
total = len(questions)
distribution = {
'counts': dict(type_counts),
'percentages': {k: v/total for k, v in type_counts.items()},
'total': total
}
return distribution
def _check_question_length(self, questions: List[Dict]) -> Dict[str, Any]:
"""Check question length statistics"""
lengths = [len(q.get('question', '')) for q in questions]
if not lengths:
return {'error': 'No questions found'}
return {
'min': min(lengths),
'max': max(lengths),
'avg': sum(lengths) / len(lengths),
'median': sorted(lengths)[len(lengths) // 2]
}
def _check_answer_completeness(self, questions: List[Dict]) -> Dict[str, Any]:
"""Check answer completeness"""
total = len(questions)
complete = 0
incomplete = 0
for q in questions:
ground_truth = q.get('ground_truth', {})
answer = ground_truth.get('answer', '')
if answer and len(answer.strip()) > 10:
complete += 1
else:
incomplete += 1
return {
'total': total,
'complete': complete,
'incomplete': incomplete,
'completeness_rate': complete / total if total > 0 else 0
}
def _check_context_coverage(self, questions: List[Dict]) -> Dict[str, Any]:
"""Check context coverage"""
total = len(questions)
with_context = 0
without_context = 0
for q in questions:
ground_truth = q.get('ground_truth', {})
context = ground_truth.get('context', [])
if context and len(context) > 0:
with_context += 1
else:
without_context += 1
return {
'total': total,
'with_context': with_context,
'without_context': without_context,
'coverage_rate': with_context / total if total > 0 else 0
}
def _check_question_diversity(self, questions: List[Dict]) -> Dict[str, Any]:
"""Check question diversity using simple text analysis"""
question_texts = [q.get('question', '') for q in questions]
# Calculate unique word ratio
all_words = []
for text in question_texts:
words = set(re.findall(r'\w+', text.lower()))
all_words.extend(words)
unique_words = set(all_words)
diversity_ratio = len(unique_words) / len(all_words) if all_words else 0
return {
'total_words': len(all_words),
'unique_words': len(unique_words),
'diversity_ratio': diversity_ratio
}
def _generate_recommendations(self, quality_report: Dict[str, Any]):
"""Generate recommendations based on quality metrics"""
metrics = quality_report['metrics']
issues = quality_report['issues']
recommendations = quality_report['recommendations']
# Check type distribution
if 'type_distribution' in metrics:
type_dist = metrics['type_distribution']['percentages']
if type_dist.get('simple', 0) > 0.8:
issues.append("Too many simple questions")
recommendations.append("Increase reasoning and multi_context questions for better evaluation")
# Check question length
if 'question_length' in metrics:
length_stats = metrics['question_length']
if length_stats.get('avg', 0) < 20:
issues.append("Questions are too short on average")
recommendations.append("Generate more detailed questions for comprehensive evaluation")
# Check answer completeness
if 'answer_completeness' in metrics:
completeness = metrics['answer_completeness']
if completeness['completeness_rate'] < 0.8:
issues.append(f"Low answer completeness: {completeness['completeness_rate']:.1%}")
recommendations.append("Improve ground truth answers to be more detailed")
# Check context coverage
if 'context_coverage' in metrics:
coverage = metrics['context_coverage']
if coverage['coverage_rate'] < 0.9:
issues.append(f"Low context coverage: {coverage['coverage_rate']:.1%}")
recommendations.append("Ensure ground truth contexts are provided for all questions")
# Check diversity
if 'diversity_score' in metrics:
diversity = metrics['diversity_score']
if diversity['diversity_ratio'] < 0.5:
issues.append(f"Low question diversity: {diversity['diversity_ratio']:.1%}")
recommendations.append("Generate more diverse questions covering different topics")
def _calculate_overall_score(self, quality_report: Dict[str, Any]) -> float:
"""Calculate overall quality score (0-100)"""
metrics = quality_report['metrics']
score = 100.0
# Deduct points for issues
score -= len(quality_report['issues']) * 10
# Deduct points for low completeness
if 'answer_completeness' in metrics:
completeness_rate = metrics['answer_completeness']['completeness_rate']
score -= (1 - completeness_rate) * 20
# Deduct points for low context coverage
if 'context_coverage' in metrics:
coverage_rate = metrics['context_coverage']['coverage_rate']
score -= (1 - coverage_rate) * 15
# Deduct points for low diversity
if 'diversity_score' in metrics:
diversity_ratio = metrics['diversity_score']['diversity_ratio']
if diversity_ratio < 0.5:
score -= 10
return max(0, min(100, score))