""" 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))