Spaces:
Sleeping

Digitalytics / tests /chat_automation.py
faseehsandhu's picture
added insights with extracted values,uses tool calling and test framework
db9343f
Raw History Blame Contribute Delete
26.4 kB
"""
chat_automation.py
Automated chat testing harness for the Streamlit Data Dictionary Chatbot.
Simulates user interactions, captures responses, and stores results for accuracy analysis.
"""
import json
import logging
import os
from pathlib import Path
from datetime import datetime
from typing import Dict, List, Any, Optional, Tuple
import sys
from dotenv import load_dotenv
# Add parent directories to path for imports
project_dir = Path(__file__).parent.parent
src_dir = project_dir / "src"
sys.path.insert(0, str(src_dir))
sys.path.insert(0, str(project_dir))
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
# Load environment variables
load_dotenv()
class ChatAutomation:
"""Automates chat interactions and captures responses for testing."""
def __init__(self, use_mock: bool = False):
"""
Initialize the chat automation harness.
Args:
use_mock: If True, use mock Azure OpenAI service; otherwise use real API
"""
self.use_mock = use_mock
self.test_results = []
self.session_id = datetime.now().isoformat()
try:
if use_mock:
logger.info("Using MOCK Azure OpenAI service for testing")
self.openai_service = MockAzureOpenAIService()
else:
logger.info("Using REAL Azure OpenAI service")
from services.azure_openai_service import AzureOpenAIService
self.openai_service = AzureOpenAIService()
from services.data_dictionary_service import DataDictionaryService
from services.retrieval_service import RetrievalService, format_retrieved_chunks
self.data_dict_service = DataDictionaryService()
self.retrieval_service = RetrievalService(self.data_dict_service)
logger.info("Chat automation initialized successfully")
except Exception as e:
logger.error(f"Failed to initialize chat automation: {e}")
raise
def run_chat_test(self, test_case: Dict[str, Any]) -> Dict[str, Any]:
"""
Run a single chat test case.
Args:
test_case: Test case dictionary with 'test_id', 'query', etc.
Returns:
Dictionary containing test results with response, citations, metrics
"""
test_id = test_case.get("test_id", "UNKNOWN")
query = test_case.get("query", "")
logger.info(f"Running test {test_id}: {query[:50]}...")
result = {
"test_id": test_id,
"name": test_case.get("name", ""),
"type": test_case.get("type", "chat"),
"query": query,
"timestamp": datetime.now().isoformat(),
"success": False,
"response": None,
"retrieved_chunks": [],
"retrieved_datasets": [],
"citations": [],
"response_length": 0,
"execution_time_ms": 0,
"error": None
}
try:
import time
start_time = time.time()
# Run retrieval if not a simple greeting
should_retrieve = self._should_run_retrieval(query)
retrieved_chunks = []
if should_retrieve:
try:
active_dicts = [d['name'] for d in self.data_dict_service.get_all_dictionaries()
if d.get('active', True)]
# Use the retrieval service's available method
if hasattr(self.retrieval_service, 'retrieve'):
retrieved_chunks, _ = self.retrieval_service.retrieve(query, active_dicts, top_k=10)
elif hasattr(self.retrieval_service, 'hybrid_search'):
retrieved_chunks = self.retrieval_service.hybrid_search(query, top_k=10)
else:
retrieved_chunks = []
result["retrieved_chunks"] = [
{
"text": chunk.get("text", ""),
"dataset": chunk.get("dataset", ""),
"line": chunk.get("line_number", 0)
} for chunk in retrieved_chunks[:5] # Store top 5
]
result["retrieved_datasets"] = list(set([c.get("dataset", "") for c in retrieved_chunks]))
except Exception as e:
logger.warning(f"Retrieval failed for {test_id}: {e}")
result["retrieved_chunks"] = []
# Format context for LLM
context = self._format_context(retrieved_chunks) if retrieved_chunks else ""
# Get response from Azure OpenAI
if hasattr(self.openai_service, 'get_chat_response'):
# Mock service
response = self.openai_service.get_chat_response(
query=query,
context=context,
chat_history=[],
system_prompt=self._get_system_prompt()
)
else:
# Real Azure OpenAI service
# Build full prompt with context
full_prompt = f"{context}\n\nUser Question: {query}" if context else query
response_obj = self.openai_service.generate_response(
prompt=full_prompt,
chat_history=[],
system_prompt=self._get_system_prompt()
)
# Extract response text from Azure OpenAI response
if isinstance(response_obj, dict):
if "choices" in response_obj and len(response_obj["choices"]) > 0:
response = response_obj["choices"][0]["message"]["content"]
else:
response = response_obj.get('response', 'No response from the model.')
else:
response = str(response_obj)
end_time = time.time()
result["response"] = response
result["response_length"] = len(response)
result["execution_time_ms"] = int((end_time - start_time) * 1000)
result["success"] = True
# Extract citations from response
result["citations"] = self._extract_citations(response)
logger.info(f"Test {test_id} completed in {result['execution_time_ms']}ms")
except Exception as e:
logger.error(f"Test {test_id} failed: {e}", exc_info=True)
result["error"] = str(e)
return result
def run_area_insights_test(self, test_case: Dict[str, Any]) -> Dict[str, Any]:
"""
Run an Area Insights test case.
Args:
test_case: Test case with location/ZIP information
Returns:
Test result dictionary
"""
test_id = test_case.get("test_id", "UNKNOWN")
query = test_case.get("query", "")
location = test_case.get("location_name", "")
logger.info(f"Running Area Insights test {test_id}: {location}")
result = {
"test_id": test_id,
"name": test_case.get("name", ""),
"type": "area_insights",
"query": query,
"location": location,
"zip_code": test_case.get("zip_code", ""),
"timestamp": datetime.now().isoformat(),
"success": False,
"response": None,
"retrieved_chunks": [],
"retrieved_datasets": [],
"citations": [],
"error": None
}
try:
import time
start_time = time.time()
# In real implementation, would use zip_resolution_service here
# For now, simulate the area insights query
query_with_location = f"{query} (Location: {location})"
# Retrieve area-specific data
active_dicts = [d['name'] for d in self.data_dict_service.get_all_dictionaries()
if d.get('active', True)]
# Use search() method instead of retrieve()
if hasattr(self.retrieval_service, 'search'):
retrieved_chunks = self.retrieval_service.search(
query_with_location,
active_dicts,
top_k=15
)
else:
retrieved_chunks = []
result["retrieved_chunks"] = [
{
"text": chunk.get("text", "")[:100],
"dataset": chunk.get("dataset", ""),
"line": chunk.get("line_number", 0)
} for chunk in retrieved_chunks[:5]
]
result["retrieved_datasets"] = list(set([c.get("dataset", "") for c in retrieved_chunks]))
context = self._format_context(retrieved_chunks)
if hasattr(self.openai_service, 'get_chat_response'):
# Mock service
response = self.openai_service.get_chat_response(
query=query_with_location,
context=context,
chat_history=[],
system_prompt=self._get_area_insights_prompt()
)
else:
# Real Azure OpenAI service
full_prompt = f"{context}\n\nUser Question: {query_with_location}" if context else query_with_location
response_obj = self.openai_service.generate_response(
prompt=full_prompt,
chat_history=[],
system_prompt=self._get_area_insights_prompt()
)
# Extract response text from Azure OpenAI response
if isinstance(response_obj, dict):
if "choices" in response_obj and len(response_obj["choices"]) > 0:
response = response_obj["choices"][0]["message"]["content"]
else:
response = response_obj.get('response', 'No response from the model.')
else:
response = str(response_obj)
result["response"] = response
result["success"] = True
result["citations"] = self._extract_citations(response)
logger.info(f"Area Insights test {test_id} completed successfully")
except Exception as e:
logger.error(f"Area Insights test {test_id} failed: {e}")
result["error"] = str(e)
return result
def run_all_tests(self, test_cases_file: str = None) -> List[Dict[str, Any]]:
"""
Run all test cases from test_cases.json.
Args:
test_cases_file: Path to test_cases.json (auto-detected if None)
Returns:
List of test results
"""
# Auto-detect test cases file
if test_cases_file is None:
test_cases_file = Path(__file__).parent / "test_cases.json"
test_cases_file = Path(test_cases_file)
if not test_cases_file.exists():
logger.error(f"Test cases file not found: {test_cases_file}")
return []
with open(test_cases_file, 'r') as f:
test_data = json.load(f)
self.test_results = []
# Run chat interface tests
logger.info("Starting Chat Interface tests...")
for test_case in test_data.get("chat_interface_tests", []):
result = self.run_chat_test(test_case)
self.test_results.append(result)
# Run area insights tests
logger.info("Starting Area Insights tests...")
for test_case in test_data.get("area_insights_tests", []):
result = self.run_area_insights_test(test_case)
self.test_results.append(result)
logger.info(f"Completed {len(self.test_results)} tests")
return self.test_results
def save_results(self, output_file: str = None) -> str:
"""
Save test results to JSON file.
Args:
output_file: Output file path (auto-generated if None)
Returns:
Path to saved file
"""
if output_file is None:
output_dir = Path(__file__).parent / "test_results"
output_dir.mkdir(exist_ok=True)
output_file = output_dir / f"chat_results_{self.session_id.replace(':', '-')}.json"
output_file = Path(output_file)
with open(output_file, 'w') as f:
json.dump(self.test_results, f, indent=2)
logger.info(f"Results saved to {output_file}")
return str(output_file)
@staticmethod
def _should_run_retrieval(query: str) -> bool:
"""Determine if retrieval should run for this query."""
simple_queries = ["hi", "hello", "hey", "thanks", "thank you", "ok", "okay", "bye", "goodbye"]
return query.lower().strip() not in simple_queries and len(query.split()) > 3
@staticmethod
def _format_context(chunks: List[Dict]) -> str:
"""Format retrieved chunks for LLM context."""
if not chunks:
return ""
context = "Retrieved Data Dictionary Entries:\n\n"
for i, chunk in enumerate(chunks[:10], 1):
dataset = chunk.get("dataset", "Unknown")
text = chunk.get("text", "")[:200]
context += f"{i}. [{dataset}] {text}\n"
return context
@staticmethod
def _get_system_prompt() -> str:
"""System prompt for chat interface."""
return """You are an expert data scientist assistant helping users find relevant columns and datasets for machine learning projects.
When recommending columns:
1. Always cite the source dataset in format: **ColumnName** (Dataset: DatasetName)
2. Explain why each column is relevant to the user's use case
3. Group recommendations by dataset when multiple datasets are involved
4. Be specific and cite only columns that actually exist in the provided data dictionaries
5. If you're not certain a column exists, do not recommend it
6. Provide 3-5 most relevant recommendations unless the user asks for more"""
@staticmethod
def _get_area_insights_prompt() -> str:
"""System prompt for area insights."""
return """You are an expert in geographic health data analysis. When answering about a specific area:
1. Always cite which dataset contains information for this area
2. Focus on data specific to the requested geography
3. If certain data isn't available for the area, suggest general state or national alternatives
4. Format recommendations as: **ColumnName** (Dataset: DatasetName, Available for: CityName, State)"""
@staticmethod
def _extract_citations(text: str) -> List[str]:
"""Extract dataset citations from response text."""
import re
# Pattern: (Dataset: DatasetName) or (Source: DatasetName)
pattern = r'\((?:Dataset|Source): ([^\)]+)\)'
matches = re.findall(pattern, text)
return list(set(matches))
class MockAzureOpenAIService:
"""Mock Azure OpenAI service for testing without API costs."""
def __init__(self):
self.call_count = 0
def get_chat_response(
self,
query: str,
context: str = "",
chat_history: List = None,
system_prompt: str = ""
) -> str:
"""Return mock response based on query patterns."""
self.call_count += 1
query_lower = query.lower()
# Mock responses for different query types
if "diabetes" in query_lower:
return """Based on the available data dictionaries, here are the most relevant columns for diabetes risk prediction:
1. **HbA1c Level** (Dataset: EJI_2024) - Glycated hemoglobin percentage, primary indicator of diabetes
2. **Fasting Glucose** (Dataset: AHRF-2025) - Fasting blood glucose concentration in mg/dL
3. **BMI** (Dataset: EJI_2024) - Body Mass Index, strong predictor of diabetes risk
4. **Family History of Diabetes** (Dataset: AHRF-2025) - Genetic predisposition indicator
5. **Age** (Dataset: SVI_2022) - Age group demographic available across all datasets
These columns appear in multiple datasets, with the most complete coverage in EJI_2024 and AHRF-2025. I recommend using these as your primary features for the model."""
elif "hospital" in query_lower and "readmission" in query_lower:
return """For predicting 30-day hospital readmission, these columns are most relevant:
1. **Length of Stay** (Dataset: AHRF-2025) - Previous hospitalization duration
2. **Number of Chronic Conditions** (Dataset: EJI_2024) - Comorbidity burden
3. **Age** (Dataset: SVI_2022) - Older patients have higher readmission rates
4. **Insurance Status** (Dataset: AHRF-2025) - Access to follow-up care
5. **Medication Adherence** (Dataset: EJI_2024) - Post-discharge compliance
Primary data sources: AHRF-2025 and EJI_2024."""
elif "food" in query_lower or "insecurity" in query_lower:
return """Food insecurity and health impact columns:
1. **Food Insecurity Index** (Dataset: EJI_2024) - Direct measure from environmental justice data
2. **Poverty Rate** (Dataset: SVI_2022) - Strong correlation with food insecurity
3. **SNAP Participation** (Dataset: EJI_2024) - Food assistance program enrollment
4. **Household Food Spending** (Dataset: SVI_2022) - Economic burden indicator
Data sources: EJI_2024 (primary), SVI_2022 (demographic context)"""
elif "svi" in query_lower or "social vulnerability" in query_lower:
return """The Social Vulnerability Index (SVI) dataset includes:
1. **SVI Theme 1: Socioeconomic Status** (Dataset: SVI_2022) - Poverty, unemployment, income ratios
2. **SVI Theme 2: Household Composition** (Dataset: SVI_2022) - Age, disability, single parents
3. **SVI Theme 3: Racial/Ethnic Minorities** (Dataset: SVI_2022) - Minority status and language
4. **SVI Theme 4: Housing Type & Transportation** (Dataset: SVI_2022) - Mobile homes, crowding
5. **Overall SVI Score** (Dataset: SVI_2022) - Percentile ranking of vulnerability
Cross-referenced with (Dataset: EJI_2024) and (Dataset: AHRF-2025) for comprehensive analysis."""
elif "environmental" in query_lower and "health" in query_lower:
return """Environmental health and pollution columns:
1. **PM2.5 Concentration** (Dataset: EJI_2024) - Fine particulate matter exposure
2. **Ozone Level** (Dataset: EJI_2024) - Ground-level ozone concentration
3. **Proximity to Hazardous Waste** (Dataset: EJI_2024) - Facility distance measure
4. **Industrial Facility Count** (Dataset: EJI_2024) - Local pollution sources
5. **Drinking Water Violations** (Dataset: EJI_2024) - Water quality issues
Also referenced in (Dataset: AHRF-2025) and (Dataset: SVI_2022) for health outcomes."""
elif "healthcare" in query_lower or "provider" in query_lower or "workforce" in query_lower:
return """Healthcare workforce and provider columns:
1. **Physician Density** (Dataset: AHRF-2025) - Physicians per 100,000 population
2. **Nurse Availability** (Dataset: AHRF-2025) - Registered nurses per capita
3. **Hospital Beds** (Dataset: AHRF-2025) - Acute care hospital bed availability
4. **Mental Health Provider Count** (Dataset: AHRF-2025) - Psychiatrists and counselors
5. **Primary Care Physician Shortage** (Dataset: AHRF-2025) - Designation status
Supplemented with (Dataset: EJI_2024) health outcome data and (Dataset: SVI_2022) demographics."""
elif "demographic" in query_lower:
return """Demographic columns across all datasets:
1. **Age Group** (Dataset: EJI_2024) - Population age distribution
2. **Gender/Sex** (Dataset: SVI_2022) - Gender breakdown
3. **Race/Ethnicity** (Dataset: AHRF-2025) - Racial and ethnic categories
4. **Education Level** (Dataset: SVI_2022) - Educational attainment
5. **Population Density** (Dataset: EJI_2024) - Urban vs rural
Available in all three datasets: SVI_2022, EJI_2024, and AHRF-2025."""
elif "mental" in query_lower:
return """Mental health related columns:
1. **Mental Health Provider Count** (Dataset: AHRF-2025) - Psychiatrists, therapists per capita
2. **Behavioral Health Disorder Rate** (Dataset: EJI_2024) - Prevalence of behavioral health issues
3. **Substance Use Disorder** (Dataset: EJI_2024) - Addiction and drug abuse indicators
4. **Depression Screening Rate** (Dataset: AHRF-2025) - Mental health assessment coverage
Primary sources: AHRF-2025 and EJI_2024."""
elif "hi" in query_lower or "hello" in query_lower or "hey" in query_lower:
return "Hello! I'm here to help you find relevant data columns for your machine learning projects. What would you like to know about the available datasets?"
elif "most recent" in query_lower or "recent data" in query_lower or "dataset" in query_lower and ("recent" in query_lower or "newest" in query_lower or "latest" in query_lower):
return """Our system includes the following datasets:
1. **AHRF-2025** (Dataset: AHRF-2025) - Area Health Resources File 2025, most recent healthcare data
2. **EJI_2024** (Dataset: EJI_2024) - Environmental Justice Indicators 2024 edition
3. **SVI_2022** (Dataset: SVI_2022) - Social Vulnerability Index 2022 edition
The most recently updated dataset is (Dataset: AHRF-2025), containing the latest healthcare workforce and availability data. Use (Dataset: EJI_2024) for environmental and health equity indicators, and (Dataset: SVI_2022) for demographic vulnerability context."""
elif "chronic" in query_lower and ("disease" in query_lower or "burden" in query_lower):
return """Chronic disease burden indicators:
1. **Chronic Disease Prevalence** (Dataset: EJI_2024) - Overall chronic disease rates
2. **Diabetes Prevalence** (Dataset: EJI_2024) - Type 1 and Type 2 diabetes cases
3. **Heart Disease Rate** (Dataset: AHRF-2025) - Cardiovascular disease indicators
4. **Respiratory Disease** (Dataset: EJI_2024) - Asthma and lung disease rates
5. **Cancer Incidence** (Dataset: AHRF-2025) - Cancer case data
Data sources: (Dataset: EJI_2024) for prevalence, (Dataset: AHRF-2025) for healthcare response."""
elif "access" in query_lower and ("care" in query_lower or "healthcare" in query_lower or "services" in query_lower):
return """Access to care indicators:
1. **Healthcare Provider Density** (Dataset: AHRF-2025) - Doctors and clinics per population
2. **Hospital Proximity** (Dataset: AHRF-2025) - Distance to nearest hospital
3. **Insurance Coverage** (Dataset: AHRF-2025) - Percentage with health insurance
4. **Transportation Access** (Dataset: SVI_2022) - Vehicle availability and transit options
5. **Uninsured Rate** (Dataset: AHRF-2025) - Population without insurance
Primary source: (Dataset: AHRF-2025); supplemented with (Dataset: SVI_2022) demographic context."""
elif "economic" in query_lower or ("poverty" in query_lower and "columns" in query_lower) or ("poverty" in query_lower and "relate" in query_lower):
return """Economic and poverty indicators:
1. **Poverty Rate** (Dataset: SVI_2022) - Percentage below poverty line
2. **Median Household Income** (Dataset: EJI_2024) - Income distribution
3. **Unemployment Rate** (Dataset: AHRF-2025) - Job market indicators
4. **Income Inequality** (Dataset: SVI_2022) - Gini coefficient and ratios
5. **Economic Hardship Index** (Dataset: EJI_2024) - Combined economic distress
Available in: (Dataset: SVI_2022) primary source, (Dataset: EJI_2024) and (Dataset: AHRF-2025) supplementary."""
elif "housing" in query_lower or "living" in query_lower or "crowding" in query_lower:
return """Housing and living condition columns:
1. **Housing Unit Density** (Dataset: SVI_2022) - People per housing unit
2. **Mobile Home Percentage** (Dataset: SVI_2022, Dataset: EJI_2024) - Mobile vs permanent housing
3. **Crowding Index** (Dataset: SVI_2022) - Occupancy per room ratio
4. **Occupied Housing Units** (Dataset: SVI_2022) - Household count
5. **Housing Cost Burden** (Dataset: SVI_2022, Dataset: AHRF-2025) - Percentage spending on housing
Data from: (Dataset: SVI_2022) primary, (Dataset: EJI_2024) and (Dataset: AHRF-2025) supplementary."""
else:
return f"""I found relevant columns for your query about '{query[:50]}...'.
Based on the available data dictionaries (EJI_2024, AHRF-2025, SVI_2022), here are some potentially useful columns:
1. **Sample Column A** (Dataset: EJI_2024) - Description of column A
2. **Sample Column B** (Dataset: AHRF-2025) - Description of column B
3. **Sample Column C** (Dataset: SVI_2022) - Description of column C
Would you like more details about any of these columns or datasets?"""
def main():
"""Run chat automation tests."""
import argparse
parser = argparse.ArgumentParser(description="Automated chat testing for Data Dictionary Chatbot")
parser.add_argument("--mock", action="store_true", help="Use mock Azure OpenAI service")
parser.add_argument("--output", default=None, help="Output file path")
parser.add_argument("--test-cases", default=None, help="Path to test_cases.json")
args = parser.parse_args()
automation = ChatAutomation(use_mock=args.mock)
results = automation.run_all_tests(args.test_cases)
output_file = automation.save_results(args.output)
print(f"\n✅ Completed {len(results)} tests")
print(f"📊 Results saved to: {output_file}")
if __name__ == "__main__":
main()