| """Response Validator - Validate AI generated responses""" |
|
|
| import re |
| from typing import Dict, List, Optional, Tuple |
| from dataclasses import dataclass |
| from enum import Enum |
|
|
|
|
| class ResponseQuality(Enum): |
| """Response quality levels""" |
|
|
| EXCELLENT = "excellent" |
| GOOD = "good" |
| ADEQUATE = "adequate" |
| POOR = "poor" |
| INVALID = "invalid" |
|
|
|
|
| @dataclass |
| class ValidationResult: |
| """Validation result container""" |
|
|
| quality: ResponseQuality |
| score: float |
| issues: List[str] |
| suggestions: List[str] |
|
|
|
|
| class ResponseValidator: |
| """Validate AI generated code responses""" |
|
|
| def __init__(self): |
| self.min_code_length = 50 |
| self.max_issues = 3 |
| self.quality_threshold = 0.6 |
|
|
| def validate(self, response: str, instruction: str) -> ValidationResult: |
| """Validate response quality""" |
| issues: List[str] = [] |
| suggestions: List[str] = [] |
| score = 1.0 |
|
|
| if len(response) < self.min_code_length: |
| issues.append("Response too short") |
| score -= 0.3 |
|
|
| if not self._contains_code(response): |
| issues.append("No code block found in response") |
| score -= 0.5 |
|
|
| if not self._is_relevant(response, instruction): |
| issues.append("Response may not address the instruction") |
| score -= 0.2 |
|
|
| if self._has_obvious_errors(response): |
| issues.append("Potential errors detected in code") |
| score -= 0.2 |
|
|
| code_blocks = self._extract_code_blocks(response) |
| for i, block in enumerate(code_blocks): |
| if block_language := self._detect_language(block): |
| lang_issues = self._check_language_specific(block, block_language) |
| issues.extend([f"Block {i+1}: {issue}" for issue in lang_issues]) |
|
|
| if not issues: |
| suggestions.append("Response looks good!") |
| else: |
| suggestions.append("Consider adding more explanatory comments") |
|
|
| quality = self._determine_quality(score, issues) |
|
|
| return ValidationResult( |
| quality=quality, score=max(0, score), issues=issues, suggestions=suggestions |
| ) |
|
|
| def _contains_code(self, response: str) -> bool: |
| """Check if response contains code blocks""" |
| return bool(re.search(r"```[\s\S]*?```", response)) |
|
|
| def _is_relevant(self, response: str, instruction: str) -> bool: |
| """Check if response is relevant to instruction""" |
| instruction_words = set( |
| re.findall(r"\b\w+\b", instruction.lower()) |
| ) |
| response_words = set(re.findall(r"\b\w+\b", response.lower())) |
| overlap = instruction_words & response_words |
|
|
| return len(overlap) >= min(3, len(instruction_words) * 0.3) |
|
|
| def _has_obvious_errors(self, response: str) -> bool: |
| """Check for obvious code errors""" |
| error_patterns = [ |
| r"undefined\s+variable", |
| r"cannot\s+find\s+module", |
| r"syntax\s+error", |
| r"indentation\s+error", |
| ] |
|
|
| for pattern in error_patterns: |
| if re.search(pattern, response, re.IGNORECASE): |
| return True |
|
|
| return False |
|
|
| def _extract_code_blocks(self, response: str) -> List[str]: |
| """Extract all code blocks from response""" |
| pattern = r"```[\w]*\n?([\s\S]*?)```" |
| matches = re.findall(pattern, response) |
| return [match.strip() for match in matches] |
|
|
| def _detect_language(self, code: str) -> Optional[str]: |
| """Detect programming language from code""" |
| language_signatures = { |
| "python": [r"def\s+\w+\s*\(", r"import\s+\w+", r"if\s+__name__"], |
| "javascript": [r"const\s+\w+", r"function\s+\w+\s*\(", r"=>\s*{"], |
| "typescript": [r":\s*(string|number|boolean)\b", r"interface\s+\w+"], |
| "java": [r"public\s+class\s+\w+", r"System\.out\.println"], |
| "sql": [r"SELECT\s+.+\s+FROM", r"INSERT\s+INTO", r"CREATE\s+TABLE"], |
| "bash": [r"#!/bin/bash", r"echo\s+", r"\$\w+"], |
| } |
|
|
| for lang, patterns in language_signatures.items(): |
| if any(re.search(p, code) for p in patterns): |
| return lang |
|
|
| return None |
|
|
| def _check_language_specific(self, code: str, language: str) -> List[str]: |
| """Language-specific validation checks""" |
| issues = [] |
|
|
| if language == "python": |
| if re.search(r"def\s+\w+\s*\([^)]*$", code): |
| issues.append("Missing colon at end of function definition") |
|
|
| if language == "javascript": |
| if re.search(r"const\s+\w+\s*=\s*\w+\s*\+\s*['\"]\s*['\"]", code): |
| issues.append("Empty string concatenation detected") |
|
|
| return issues |
|
|
| def _determine_quality( |
| self, score: float, issues: List[str] |
| ) -> ResponseQuality: |
| """Determine response quality based on score and issues""" |
| if score <= 0: |
| return ResponseQuality.INVALID |
| elif score >= 0.8 and len(issues) == 0: |
| return ResponseQuality.EXCELLENT |
| elif score >= 0.6: |
| return ResponseQuality.GOOD |
| elif score >= 0.4: |
| return ResponseQuality.ADEQUATE |
| else: |
| return ResponseQuality.POOR |
|
|
| def validate_multiple( |
| self, responses: List[str], instruction: str |
| ) -> List[ValidationResult]: |
| """Validate multiple responses and rank them""" |
| results = [self.validate(resp, instruction) for resp in responses] |
| return sorted(results, key=lambda r: r.score, reverse=True) |
|
|