Spaces:
Sleeping

Digitalytics / tests /accuracy_validators.py
faseehsandhu's picture
added insights with extracted values,uses tool calling and test framework
db9343f
Raw History Blame Contribute Delete
21.4 kB
"""
accuracy_validators.py
Accuracy validation modules for analyzing chatbot responses against expected results.
Includes citation validation, relevance scoring, hallucination detection, and more.
"""
import re
import json
import logging
from typing import Dict, List, Any, Tuple, Optional
from pathlib import Path
from difflib import SequenceMatcher
logger = logging.getLogger(__name__)
class CitationValidator:
"""Validates that all recommendations are properly cited with dataset sources."""
CITATION_PATTERNS = [
r'\(Dataset:\s*([^\)]+)\)',
r'\(Source:\s*([^\)]+)\)',
r'Dataset:\s*([A-Za-z0-9_\-]+)',
]
KNOWN_DATASETS = ["EJI_2024", "AHRF-2025", "SVI_2022", "CHR", "chr.xlsx"]
def validate(self, response: str, test_case: Dict[str, Any]) -> Dict[str, Any]:
"""
Validate citations in response.
Args:
response: LLM response text
test_case: Original test case dictionary
Returns:
Validation result dictionary
"""
result = {
"validator": "citation",
"passed": True,
"score": 1.0,
"issues": [],
"citations_found": [],
"citation_count": 0,
"expected_citation_count": test_case.get("min_recommendations", 0)
}
# Handle None or empty response
if response is None or (isinstance(response, str) and not response.strip()):
result["issues"].append("Response is empty or None - cannot extract citations")
result["passed"] = False
result["score"] = 0.0
return result
# Extract all citations
citations = self._extract_citations(response)
result["citations_found"] = citations
result["citation_count"] = len(citations)
# Check minimum citations
if result["expected_citation_count"] > 0:
if result["citation_count"] < result["expected_citation_count"]:
result["issues"].append(
f"Insufficient citations: found {result['citation_count']}, "
f"expected at least {result['expected_citation_count']}"
)
result["passed"] = False
# Check for expected datasets
expected_datasets = set(test_case.get("expected_datasets", []))
found_datasets = set([self._normalize_dataset(c) for c in citations])
missing_datasets = expected_datasets - found_datasets
if missing_datasets and expected_datasets:
result["issues"].append(
f"Expected datasets not cited: {', '.join(missing_datasets)}"
)
result["passed"] = False
# Check for citations to unknown datasets
invalid_citations = []
for citation in citations:
normalized = self._normalize_dataset(citation)
if normalized and not self._is_valid_dataset(normalized):
invalid_citations.append(citation)
if invalid_citations:
result["issues"].append(
f"Citations to unknown datasets: {', '.join(invalid_citations)}"
)
result["passed"] = False
# Calculate score
if result["passed"]:
result["score"] = 1.0
else:
result["score"] = max(0.0, 1.0 - (len(result["issues"]) * 0.25))
return result
@staticmethod
def _extract_citations(text: str) -> List[str]:
"""Extract dataset names from citation patterns."""
citations = []
for pattern in CitationValidator.CITATION_PATTERNS:
matches = re.findall(pattern, text, re.IGNORECASE)
citations.extend([m.strip() for m in matches])
return list(set(citations))
@staticmethod
def _normalize_dataset(dataset_str: str) -> str:
"""Normalize dataset name for comparison."""
return dataset_str.strip().upper().replace(" ", "_")
@classmethod
def _is_valid_dataset(cls, dataset: str) -> bool:
"""Check if dataset is in known list."""
normalized_known = [d.upper().replace(" ", "_") for d in cls.KNOWN_DATASETS]
return dataset.upper() in normalized_known
class RelevanceScorer:
"""Scores how relevant recommendations are to the user's query."""
def validate(self, response: str, test_case: Dict[str, Any]) -> Dict[str, Any]:
"""
Score response relevance to query.
Args:
response: LLM response text
test_case: Original test case with expected patterns
Returns:
Validation result with relevance score
"""
result = {
"validator": "relevance",
"passed": True,
"score": 0.5,
"issues": [],
"matched_patterns": [],
"expected_patterns": test_case.get("expected_column_patterns", []),
"pattern_match_count": 0
}
# Handle None or empty response
if response is None or (isinstance(response, str) and not response.strip()):
result["issues"].append("Response is empty or None - cannot score relevance")
result["passed"] = False
result["score"] = 0.0
return result
expected_patterns = test_case.get("expected_column_patterns", [])
if not expected_patterns:
result["score"] = 1.0
result["passed"] = True
return result
# Count pattern matches
matches = []
for pattern in expected_patterns:
if re.search(pattern, response, re.IGNORECASE):
matches.append(pattern)
result["matched_patterns"] = matches
result["pattern_match_count"] = len(matches)
# Calculate relevance score
if expected_patterns:
match_ratio = len(matches) / len(expected_patterns)
result["score"] = match_ratio
if match_ratio < 0.4:
result["issues"].append(
f"Low pattern match: {len(matches)}/{len(expected_patterns)} expected patterns found"
)
result["passed"] = False
return result
class HallucinationDetector:
"""Detects when the model recommends columns that don't exist in the dictionaries."""
def __init__(self, data_dictionary_service):
"""
Initialize with access to loaded dictionaries.
Args:
data_dictionary_service: Service with loaded dictionary data
"""
self.data_dict_service = data_dictionary_service
self._build_known_columns_index()
def _build_known_columns_index(self):
"""Build searchable index of all columns in loaded dictionaries."""
self.known_columns = set()
self.column_to_datasets = {}
try:
all_dicts = self.data_dict_service.get_all_dictionaries()
for dict_info in all_dicts:
dict_name = dict_info.get('name', '')
dict_data = self.data_dict_service.data_dictionaries.get(dict_name, [])
if isinstance(dict_data, list):
for entry in dict_data:
# Extract column names from various possible formats
if isinstance(entry, dict):
col_names = [
entry.get('column_name', ''),
entry.get('Column Name', ''),
entry.get('Column', '')
]
else:
col_names = [str(entry).split('\t')[0] if '\t' in str(entry) else '']
for col in col_names:
if col:
normalized = col.lower().strip()
self.known_columns.add(normalized)
if normalized not in self.column_to_datasets:
self.column_to_datasets[normalized] = []
self.column_to_datasets[normalized].append(dict_name)
except Exception as e:
logger.warning(f"Could not build column index: {e}")
def validate(self, response: str, test_case: Dict[str, Any], retrieved_chunks: List = None) -> Dict[str, Any]:
"""
Detect hallucinated columns in response.
Args:
response: LLM response text
test_case: Original test case
retrieved_chunks: Optional retrieved chunks for context
Returns:
Validation result
"""
result = {
"validator": "hallucination",
"passed": True,
"score": 1.0,
"issues": [],
"hallucinated_columns": [],
"legitimate_columns": [],
"uncertain_columns": []
}
# Handle None or empty response
if response is None or (isinstance(response, str) and not response.strip()):
result["issues"].append("Response is empty or None - cannot check for hallucinations")
result["passed"] = False
result["score"] = 0.0
return result
# Extract column names from response
# Look for patterns like **ColumnName** or ColumnName (Dataset: ...)
recommended_columns = self._extract_column_names(response)
for col_name in recommended_columns:
normalized_col = col_name.lower().strip()
if normalized_col in self.known_columns:
result["legitimate_columns"].append(col_name)
elif self._is_likely_real(col_name, retrieved_chunks):
result["uncertain_columns"].append(col_name)
else:
result["hallucinated_columns"].append(col_name)
# Validation logic
if result["hallucinated_columns"]:
result["passed"] = False
result["issues"].append(
f"Hallucinated columns detected: {', '.join(result['hallucinated_columns'])}"
)
# Score calculation
total_cols = len(recommended_columns)
if total_cols > 0:
legitimate_ratio = len(result["legitimate_columns"]) / total_cols
result["score"] = legitimate_ratio * 0.7 + (1.0 - len(result["hallucinated_columns"]) / max(total_cols, 1)) * 0.3
return result
@staticmethod
def _extract_column_names(text: str) -> List[str]:
"""Extract column names from response text."""
columns = []
# Pattern: **ColumnName** (Dataset: ...)
pattern1 = r'\*\*([A-Za-z0-9\s\-_/]+)\*\*'
matches1 = re.findall(pattern1, text)
columns.extend(matches1)
# Pattern: ColumnName (Dataset: ...)
pattern2 = r'([A-Z][A-Za-z0-9\s\-_/]*)\s*\(Dataset:'
matches2 = re.findall(pattern2, text)
columns.extend(matches2)
return [c.strip() for c in list(set(columns)) if len(c.strip()) > 2]
@staticmethod
def _is_likely_real(column_name: str, retrieved_chunks: List = None) -> bool:
"""Heuristic to determine if a column name looks realistic."""
if not column_name or len(column_name) < 2:
return False
# Check if column appears in retrieved chunks
if retrieved_chunks:
col_lower = column_name.lower()
for chunk in retrieved_chunks:
if col_lower in chunk.get("text", "").lower():
return True
# Check if it matches typical column name patterns
# Valid: descriptive names, snake_case, CamelCase
valid_patterns = [
r'^[A-Z][a-zA-Z]+$', # CamelCase
r'^[a-z]+(_[a-z]+)*$', # snake_case
r'^[A-Z][A-Z0-9_\-]+$', # UPPER_CASE
r'^[A-Za-z0-9\s/\-]+$' # Descriptive with spaces/slashes
]
return any(re.match(pattern, column_name) for pattern in valid_patterns)
class AreaInsightsValidator:
"""Validates Area Insights geographic accuracy."""
def validate(self, response: str, test_case: Dict[str, Any]) -> Dict[str, Any]:
"""
Validate area/geographic specificity in response.
Args:
response: LLM response text
test_case: Test case with area information
Returns:
Validation result
"""
result = {
"validator": "area_insights",
"passed": True,
"score": 1.0,
"issues": [],
"mentions_location": False,
"mentions_datasets": False,
"fallback_used": False
}
if test_case.get("type") != "area_insights":
return result # Not applicable
# Handle None or empty response
if response is None or (isinstance(response, str) and not response.strip()):
result["issues"].append("Response is empty or None - cannot validate area insights")
result["passed"] = False
result["score"] = 0.0
return result
location = test_case.get("location_name", "")
zip_code = test_case.get("zip_code", "")
# Check if location/ZIP is mentioned
if location:
if location.lower() in response.lower() or zip_code in response:
result["mentions_location"] = True
else:
result["issues"].append(
f"Response does not mention location '{location}' or ZIP {zip_code}"
)
# Check if datasets are mentioned
expected_datasets = test_case.get("expected_datasets", [])
for dataset in expected_datasets:
if dataset in response or dataset.replace("_", " ") in response:
result["mentions_datasets"] = True
break
if not result["mentions_datasets"] and expected_datasets:
result["issues"].append("Response does not mention expected datasets")
# Check for fallback indicators if invalid ZIP
if test_case.get("should_fallback_to_general"):
fallback_phrases = ["general knowledge", "nationwide", "not available for", "no data", "general data"]
if any(phrase in response.lower() for phrase in fallback_phrases):
result["fallback_used"] = True
# Validation logic
if result["issues"]:
result["passed"] = False
# Scoring
score = 1.0
if not result["mentions_location"]:
score -= 0.3
if not result["mentions_datasets"]:
score -= 0.3
result["score"] = max(0.0, score)
return result
class FormatValidator:
"""Validates response format and structure."""
def validate(self, response: str, test_case: Dict[str, Any]) -> Dict[str, Any]:
"""
Validate response formatting and structure.
Args:
response: LLM response text
test_case: Original test case
Returns:
Validation result
"""
result = {
"validator": "format",
"passed": True,
"score": 1.0,
"issues": [],
"has_structured_list": False,
"uses_bold_formatting": False,
"is_coherent": True,
"response_length": 0
}
# Handle None or empty response
if response is None or (isinstance(response, str) and not response.strip()):
result["issues"].append("Response is empty or None - cannot validate format")
result["passed"] = False
result["score"] = 0.0
result["response_length"] = 0
return result
result["response_length"] = len(response)
# Check for structured list format
list_patterns = [r'^\d+\.\s', r'^[-*]\s']
if any(re.search(pattern, response, re.MULTILINE) for pattern in list_patterns):
result["has_structured_list"] = True
# Check for bold formatting
if "**" in response:
result["uses_bold_formatting"] = True
# Check response length (should be reasonable)
min_length = 100 if test_case.get("min_recommendations", 0) > 0 else 20
if result["response_length"] < min_length:
result["issues"].append(f"Response too short ({result['response_length']} < {min_length} chars)")
result["passed"] = False
# Check for typical errors
if "i don't know" in response.lower() and test_case.get("min_recommendations", 0) > 0:
result["issues"].append("Response indicates lack of knowledge despite available data")
result["passed"] = False
# Scoring
score = 1.0
if not result["has_structured_list"]:
score -= 0.15
if not result["uses_bold_formatting"]:
score -= 0.1
if result["issues"]:
score -= len(result["issues"]) * 0.1
result["score"] = max(0.0, score)
return result
class AccuracyAnalyzer:
"""Orchestrates all validators and produces overall accuracy assessment."""
def __init__(self, data_dictionary_service=None):
"""Initialize validators."""
self.citation_validator = CitationValidator()
self.relevance_scorer = RelevanceScorer()
self.hallucination_detector = HallucinationDetector(data_dictionary_service) if data_dictionary_service else None
self.area_insights_validator = AreaInsightsValidator()
self.format_validator = FormatValidator()
def analyze_response(
self,
test_case: Dict[str, Any],
response: str,
retrieved_chunks: List = None
) -> Dict[str, Any]:
"""
Analyze a single response using all validators.
Args:
test_case: Original test case
response: LLM response text
retrieved_chunks: Retrieved chunks for context
Returns:
Comprehensive analysis result
"""
validations = {}
# Run all validators
validations["citation"] = self.citation_validator.validate(response, test_case)
validations["relevance"] = self.relevance_scorer.validate(response, test_case)
validations["format"] = self.format_validator.validate(response, test_case)
validations["area_insights"] = self.area_insights_validator.validate(response, test_case)
if self.hallucination_detector:
validations["hallucination"] = self.hallucination_detector.validate(
response, test_case, retrieved_chunks
)
# Calculate overall score
scores = [v["score"] for v in validations.values() if v]
overall_score = sum(scores) / len(scores) if scores else 0.0
# Determine overall pass/fail
overall_passed = all(v["passed"] for v in validations.values() if v)
return {
"test_id": test_case.get("test_id", ""),
"test_name": test_case.get("name", ""),
"overall_score": overall_score,
"overall_passed": overall_passed,
"validations": validations,
"response_snippet": response[:200] + "..." if len(response) > 200 else response
}
def analyze_batch(
self,
test_results: List[Dict[str, Any]],
test_cases: List[Dict[str, Any]]
) -> Dict[str, Any]:
"""
Analyze multiple test results.
Args:
test_results: List of test execution results
test_cases: List of original test cases
Returns:
Batch analysis with aggregate metrics
"""
analyses = []
# Create lookup for test cases
test_case_map = {tc.get("test_id"): tc for tc in test_cases}
for result in test_results:
test_case = test_case_map.get(result["test_id"], result)
analysis = self.analyze_response(
test_case,
result.get("response", ""),
result.get("retrieved_chunks", [])
)
analyses.append(analysis)
# Aggregate metrics
return {
"total_tests": len(analyses),
"passed_tests": sum(1 for a in analyses if a["overall_passed"]),
"failed_tests": sum(1 for a in analyses if not a["overall_passed"]),
"average_score": sum(a["overall_score"] for a in analyses) / len(analyses) if analyses else 0,
"pass_rate": sum(1 for a in analyses if a["overall_passed"]) / len(analyses) if analyses else 0,
"analyses": analyses
}