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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Utility functions for the Pharmaceutical Analytics application.
|
| 3 |
+
This module contains helper functions for environment setup, agent initialization,
|
| 4 |
+
and workflow execution.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
import streamlit as st
|
| 9 |
+
import traceback
|
| 10 |
+
import logging
|
| 11 |
+
import threading
|
| 12 |
+
import time
|
| 13 |
+
from datetime import datetime
|
| 14 |
+
from config import DB_PATH
|
| 15 |
+
|
| 16 |
+
# Get logger
|
| 17 |
+
logger = logging.getLogger("pharma-analytics")
|
| 18 |
+
|
| 19 |
+
def setup_environment():
|
| 20 |
+
"""Setup the demo environment"""
|
| 21 |
+
st.sidebar.markdown("### Setting up environment...")
|
| 22 |
+
|
| 23 |
+
# Create directories
|
| 24 |
+
os.makedirs("data", exist_ok=True)
|
| 25 |
+
os.makedirs("agents", exist_ok=True)
|
| 26 |
+
os.makedirs("workflows", exist_ok=True)
|
| 27 |
+
os.makedirs("utils", exist_ok=True)
|
| 28 |
+
os.makedirs("ui", exist_ok=True)
|
| 29 |
+
|
| 30 |
+
# Check for database file
|
| 31 |
+
if not os.path.exists(DB_PATH):
|
| 32 |
+
if st.session_state.get("initialization_attempted", False):
|
| 33 |
+
st.sidebar.warning("Previous initialization attempt failed. Check logs.")
|
| 34 |
+
return False
|
| 35 |
+
|
| 36 |
+
st.sidebar.info("Database not found. Generating synthetic data...")
|
| 37 |
+
st.session_state.initialization_attempted = True
|
| 38 |
+
|
| 39 |
+
try:
|
| 40 |
+
# Import needed modules
|
| 41 |
+
from data.schema import create_schema
|
| 42 |
+
from data.seed_data import create_seed_data
|
| 43 |
+
|
| 44 |
+
# Create schema first
|
| 45 |
+
create_schema(DB_PATH)
|
| 46 |
+
st.sidebar.info("✓ Database schema created")
|
| 47 |
+
|
| 48 |
+
# Add seed data
|
| 49 |
+
create_seed_data(DB_PATH)
|
| 50 |
+
st.sidebar.info("✓ Seed data created")
|
| 51 |
+
|
| 52 |
+
# Generate full synthetic dataset
|
| 53 |
+
from data.data_generator import generate_all_data
|
| 54 |
+
generate_all_data()
|
| 55 |
+
st.sidebar.success("✓ Synthetic data generated successfully")
|
| 56 |
+
|
| 57 |
+
return True
|
| 58 |
+
except Exception as e:
|
| 59 |
+
error_msg = f"Error setting up environment: {e}"
|
| 60 |
+
stack_trace = traceback.format_exc()
|
| 61 |
+
logger.error(f"{error_msg}\n{stack_trace}")
|
| 62 |
+
st.sidebar.error(error_msg)
|
| 63 |
+
return False
|
| 64 |
+
else:
|
| 65 |
+
st.sidebar.success("✓ Database found")
|
| 66 |
+
return True
|
| 67 |
+
|
| 68 |
+
@st.cache_resource
|
| 69 |
+
def initialize_agents():
|
| 70 |
+
"""Initialize agents and return status"""
|
| 71 |
+
try:
|
| 72 |
+
logger.info("Initializing agents...")
|
| 73 |
+
# We'll only import these modules when needed
|
| 74 |
+
from agents.planning_agent import PlanningAgent, AnalysisPlan
|
| 75 |
+
from agents.data_agent import DataAgent, DataRequest, DataSource
|
| 76 |
+
from agents.analytics_agent import AnalyticsAgent, AnalysisRequest, AnalysisResult
|
| 77 |
+
from agents.qa_agent import QAAgent, ValidationRequest, ValidationResult
|
| 78 |
+
from agents.insights_agent import InsightsAgent, InsightRequest, InsightCard
|
| 79 |
+
from workflows.sales_analysis import SalesAnalysisWorkflow, WorkflowState
|
| 80 |
+
|
| 81 |
+
logger.info("All agents imported successfully")
|
| 82 |
+
|
| 83 |
+
return True, {
|
| 84 |
+
"PlanningAgent": PlanningAgent,
|
| 85 |
+
"DataAgent": DataAgent,
|
| 86 |
+
"AnalyticsAgent": AnalyticsAgent,
|
| 87 |
+
"QAAgent": QAAgent,
|
| 88 |
+
"InsightsAgent": InsightsAgent,
|
| 89 |
+
"SalesAnalysisWorkflow": SalesAnalysisWorkflow
|
| 90 |
+
}
|
| 91 |
+
except Exception as e:
|
| 92 |
+
error_msg = f"Failed to initialize agents: {e}"
|
| 93 |
+
stack_trace = traceback.format_exc()
|
| 94 |
+
logger.error(f"{error_msg}\n{stack_trace}")
|
| 95 |
+
return False, error_msg
|
| 96 |
+
|
| 97 |
+
def run_workflow_thread(workflow, alert):
|
| 98 |
+
"""Run the workflow in a separate thread"""
|
| 99 |
+
try:
|
| 100 |
+
# Log start of workflow
|
| 101 |
+
logger.info(f"Starting workflow for alert: {alert}")
|
| 102 |
+
|
| 103 |
+
# Update status
|
| 104 |
+
st.session_state.status_queue.put(("info", "Planning analysis approach..."))
|
| 105 |
+
st.session_state.current_step = "planning"
|
| 106 |
+
|
| 107 |
+
# Run the workflow with more detailed logging
|
| 108 |
+
logger.info("Invoking workflow run...")
|
| 109 |
+
result = workflow.run_workflow(alert)
|
| 110 |
+
|
| 111 |
+
# Log completion
|
| 112 |
+
logger.info("Workflow completed successfully")
|
| 113 |
+
|
| 114 |
+
# Store the result
|
| 115 |
+
st.session_state.workflow_state = result
|
| 116 |
+
|
| 117 |
+
# Update status
|
| 118 |
+
st.session_state.status_queue.put(("success", "Analysis complete!"))
|
| 119 |
+
st.session_state.current_step = "complete"
|
| 120 |
+
except Exception as e:
|
| 121 |
+
# Capture the full stack trace
|
| 122 |
+
stack_trace = traceback.format_exc()
|
| 123 |
+
error_msg = f"Error: {str(e)}\n\nStack trace:\n{stack_trace}"
|
| 124 |
+
|
| 125 |
+
# Log the error
|
| 126 |
+
logger.error(error_msg)
|
| 127 |
+
|
| 128 |
+
# Update status with more details
|
| 129 |
+
st.session_state.status_queue.put(("error", f"Error: {str(e)}"))
|
| 130 |
+
st.session_state.current_step = "error"
|
| 131 |
+
|
| 132 |
+
# Store error details for debugging
|
| 133 |
+
if "error_details" not in st.session_state:
|
| 134 |
+
st.session_state.error_details = []
|
| 135 |
+
st.session_state.error_details.append(error_msg)
|
| 136 |
+
|
| 137 |
+
def start_workflow(alert_text):
|
| 138 |
+
"""Start the workflow with the given alert text"""
|
| 139 |
+
try:
|
| 140 |
+
# Create and start the workflow
|
| 141 |
+
logger.info(f"Creating workflow with alert: {alert_text}")
|
| 142 |
+
SalesAnalysisWorkflow = st.session_state.agents["SalesAnalysisWorkflow"]
|
| 143 |
+
workflow = SalesAnalysisWorkflow(db_path=DB_PATH)
|
| 144 |
+
|
| 145 |
+
# Start the workflow in a separate thread
|
| 146 |
+
thread = threading.Thread(
|
| 147 |
+
target=run_workflow_thread,
|
| 148 |
+
args=(workflow, alert_text),
|
| 149 |
+
daemon=True
|
| 150 |
+
)
|
| 151 |
+
thread.start()
|
| 152 |
+
logger.info("Workflow thread started")
|
| 153 |
+
|
| 154 |
+
# Store the thread and mark alert as submitted
|
| 155 |
+
st.session_state.workflow_thread = thread
|
| 156 |
+
st.session_state.alert_submitted = True
|
| 157 |
+
|
| 158 |
+
# Display initial status
|
| 159 |
+
st.info("Starting analysis workflow...")
|
| 160 |
+
st.session_state.logs.append({
|
| 161 |
+
"timestamp": datetime.now().isoformat(),
|
| 162 |
+
"type": "info",
|
| 163 |
+
"message": "Starting analysis workflow..."
|
| 164 |
+
})
|
| 165 |
+
|
| 166 |
+
# Force page refresh
|
| 167 |
+
time.sleep(1)
|
| 168 |
+
return True
|
| 169 |
+
except Exception as e:
|
| 170 |
+
stack_trace = traceback.format_exc()
|
| 171 |
+
error_msg = f"Error starting workflow: {str(e)}\n\nStack trace:\n{stack_trace}"
|
| 172 |
+
logger.error(error_msg)
|
| 173 |
+
st.error(f"Error starting workflow: {str(e)}")
|
| 174 |
+
st.session_state.error_details.append(error_msg)
|
| 175 |
+
return False
|