Update app.py
Browse files
app.py
CHANGED
|
@@ -1,19 +1,38 @@
|
|
| 1 |
"""
|
| 2 |
-
RICA Agent -
|
| 3 |
"""
|
| 4 |
|
| 5 |
import streamlit as st
|
| 6 |
import os
|
| 7 |
-
from pathlib import Path
|
| 8 |
import sys
|
|
|
|
|
|
|
| 9 |
|
| 10 |
# Add project root to path for imports
|
| 11 |
if str(Path(__file__).parent) not in sys.path:
|
| 12 |
sys.path.append(str(Path(__file__).parent))
|
| 13 |
|
| 14 |
# Import modules
|
| 15 |
-
|
| 16 |
-
from
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
# Page configuration
|
| 19 |
st.set_page_config(
|
|
@@ -51,27 +70,31 @@ st.markdown("""
|
|
| 51 |
st.markdown('<h1 class="main-header">π€ RICA - AI Revenue Intelligence Agent</h1>', unsafe_allow_html=True)
|
| 52 |
st.markdown("### Enterprise Business Intelligence Powered by Machine Learning")
|
| 53 |
|
| 54 |
-
# Initialize session state
|
| 55 |
-
if 'model_trained' not in st.session_state:
|
| 56 |
-
st.session_state.model_trained = False
|
| 57 |
-
if 'trainer' not in st.session_state:
|
| 58 |
-
st.session_state.trainer = EmbeddedChurnTrainer()
|
| 59 |
-
|
| 60 |
# Sidebar configuration
|
| 61 |
with st.sidebar:
|
| 62 |
st.header("π§ Configuration")
|
| 63 |
|
| 64 |
-
# API Key input
|
| 65 |
openai_key = st.text_input(
|
| 66 |
"OpenAI API Key",
|
| 67 |
-
type="password",
|
| 68 |
-
help="Required for AI agent operations"
|
|
|
|
|
|
|
| 69 |
)
|
| 70 |
|
| 71 |
-
|
|
|
|
| 72 |
os.environ["OPENAI_API_KEY"] = openai_key
|
| 73 |
-
st.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
else:
|
|
|
|
| 75 |
st.warning("β οΈ Enter API Key to enable AI features")
|
| 76 |
|
| 77 |
st.divider()
|
|
@@ -79,53 +102,78 @@ with st.sidebar:
|
|
| 79 |
# Model status
|
| 80 |
st.header("π§ ML Model Status")
|
| 81 |
|
| 82 |
-
|
|
|
|
| 83 |
|
| 84 |
if model_exists:
|
| 85 |
st.success("β
Model Ready")
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
else:
|
| 91 |
st.warning("β οΈ Model Not Trained")
|
|
|
|
| 92 |
|
| 93 |
-
if st.button("ποΈ Train Model Now", type="primary"):
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
|
|
|
|
|
|
|
|
|
| 105 |
|
| 106 |
st.divider()
|
| 107 |
|
| 108 |
-
# Analysis configuration
|
| 109 |
-
st.
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
|
| 126 |
-
# Main content
|
| 127 |
-
if not
|
| 128 |
-
#
|
| 129 |
st.info("π Please enter your OpenAI API Key in the sidebar to begin")
|
| 130 |
|
| 131 |
col1, col2 = st.columns(2)
|
|
@@ -167,7 +215,7 @@ if not openai_key:
|
|
| 167 |
with col4:
|
| 168 |
st.metric("Model Accuracy", "87.3%", delta="2.1%")
|
| 169 |
|
| 170 |
-
elif not
|
| 171 |
# Model training required
|
| 172 |
st.warning("π§ Machine learning model needs to be trained before analysis")
|
| 173 |
st.info("π Use the 'Train Model Now' button in the sidebar (takes 1-2 minutes)")
|
|
@@ -182,68 +230,68 @@ elif not model_exists and not st.session_state.model_trained:
|
|
| 182 |
""")
|
| 183 |
|
| 184 |
else:
|
| 185 |
-
# Main analysis interface
|
| 186 |
-
st.markdown("## π― AI Business Intelligence")
|
| 187 |
|
| 188 |
# Analysis execution
|
| 189 |
if st.button("π Run RICA Analysis", type="primary", use_container_width=True):
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
|
|
|
| 205 |
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
tab1, tab2, tab3 = st.tabs(["π Executive Summary", "π¨ Risk Analysis", "π‘ Recommendations"])
|
| 209 |
-
|
| 210 |
-
with tab1:
|
| 211 |
-
st.markdown("### Executive Dashboard")
|
| 212 |
-
st.info(str(result))
|
| 213 |
-
|
| 214 |
-
with tab2:
|
| 215 |
-
st.markdown("### Customer Risk Analysis")
|
| 216 |
-
st.write("Detailed churn risk breakdown and customer segmentation")
|
| 217 |
-
|
| 218 |
-
with tab3:
|
| 219 |
-
st.markdown("### AI Recommendations")
|
| 220 |
-
st.write("Specific actions prioritized by business impact")
|
| 221 |
-
|
| 222 |
-
else:
|
| 223 |
-
st.markdown(f"### {analysis_type.replace('_', ' ').title()} Results")
|
| 224 |
st.info(str(result))
|
| 225 |
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
st.
|
| 229 |
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 233 |
|
| 234 |
-
#
|
| 235 |
if st.session_state.trainer.model_exists():
|
| 236 |
st.markdown("## π Model Performance")
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
|
|
|
|
|
|
|
|
|
| 247 |
|
| 248 |
# Footer
|
| 249 |
st.markdown("---")
|
|
|
|
| 1 |
"""
|
| 2 |
+
RICA Agent - Complete Fixed Version
|
| 3 |
"""
|
| 4 |
|
| 5 |
import streamlit as st
|
| 6 |
import os
|
|
|
|
| 7 |
import sys
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
import json
|
| 10 |
|
| 11 |
# Add project root to path for imports
|
| 12 |
if str(Path(__file__).parent) not in sys.path:
|
| 13 |
sys.path.append(str(Path(__file__).parent))
|
| 14 |
|
| 15 |
# Import modules
|
| 16 |
+
try:
|
| 17 |
+
from utils.model_trainer import EmbeddedChurnTrainer
|
| 18 |
+
from agent.rica_agent import execute_rica_analysis_hf
|
| 19 |
+
except ImportError as e:
|
| 20 |
+
st.error(f"Import error: {e}")
|
| 21 |
+
st.stop()
|
| 22 |
+
|
| 23 |
+
# Initialize session state
|
| 24 |
+
if 'api_key_valid' not in st.session_state:
|
| 25 |
+
st.session_state.api_key_valid = False
|
| 26 |
+
if 'model_trained' not in st.session_state:
|
| 27 |
+
st.session_state.model_trained = False
|
| 28 |
+
if 'trainer' not in st.session_state:
|
| 29 |
+
st.session_state.trainer = EmbeddedChurnTrainer()
|
| 30 |
+
if 'analysis_type' not in st.session_state:
|
| 31 |
+
st.session_state.analysis_type = 'comprehensive'
|
| 32 |
+
if 'risk_threshold' not in st.session_state:
|
| 33 |
+
st.session_state.risk_threshold = 0.6
|
| 34 |
+
if 'max_customers' not in st.session_state:
|
| 35 |
+
st.session_state.max_customers = 200
|
| 36 |
|
| 37 |
# Page configuration
|
| 38 |
st.set_page_config(
|
|
|
|
| 70 |
st.markdown('<h1 class="main-header">π€ RICA - AI Revenue Intelligence Agent</h1>', unsafe_allow_html=True)
|
| 71 |
st.markdown("### Enterprise Business Intelligence Powered by Machine Learning")
|
| 72 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
# Sidebar configuration
|
| 74 |
with st.sidebar:
|
| 75 |
st.header("π§ Configuration")
|
| 76 |
|
| 77 |
+
# API Key input with proper validation
|
| 78 |
openai_key = st.text_input(
|
| 79 |
"OpenAI API Key",
|
| 80 |
+
type="password",
|
| 81 |
+
help="Required for AI agent operations",
|
| 82 |
+
key="openai_api_key",
|
| 83 |
+
placeholder="sk-..."
|
| 84 |
)
|
| 85 |
|
| 86 |
+
# Validate and store API key
|
| 87 |
+
if openai_key and openai_key.startswith('sk-') and len(openai_key) > 20:
|
| 88 |
os.environ["OPENAI_API_KEY"] = openai_key
|
| 89 |
+
st.session_state.api_key_valid = True
|
| 90 |
+
st.success("β
OpenAI API Key Configured")
|
| 91 |
+
st.caption("Key validated and ready for use")
|
| 92 |
+
elif openai_key:
|
| 93 |
+
st.session_state.api_key_valid = False
|
| 94 |
+
st.error("β Invalid API Key Format")
|
| 95 |
+
st.caption("Key should start with 'sk-' and be longer than 20 characters")
|
| 96 |
else:
|
| 97 |
+
st.session_state.api_key_valid = False
|
| 98 |
st.warning("β οΈ Enter API Key to enable AI features")
|
| 99 |
|
| 100 |
st.divider()
|
|
|
|
| 102 |
# Model status
|
| 103 |
st.header("π§ ML Model Status")
|
| 104 |
|
| 105 |
+
trainer = st.session_state.trainer
|
| 106 |
+
model_exists = trainer.model_exists()
|
| 107 |
|
| 108 |
if model_exists:
|
| 109 |
st.success("β
Model Ready")
|
| 110 |
+
try:
|
| 111 |
+
metadata = trainer.load_existing_metadata()
|
| 112 |
+
if metadata and 'metrics' in metadata:
|
| 113 |
+
st.metric("Model Accuracy", f"{metadata['metrics'].get('test_accuracy', 0):.1%}")
|
| 114 |
+
st.metric("Training Date", metadata.get('training_date', 'Unknown')[:10])
|
| 115 |
+
st.session_state.model_trained = True
|
| 116 |
+
except:
|
| 117 |
+
st.info("Model exists but metadata unavailable")
|
| 118 |
+
st.session_state.model_trained = True
|
| 119 |
else:
|
| 120 |
st.warning("β οΈ Model Not Trained")
|
| 121 |
+
st.session_state.model_trained = False
|
| 122 |
|
| 123 |
+
if st.button("ποΈ Train Model Now", type="primary", key="train_model_btn"):
|
| 124 |
+
if not st.session_state.api_key_valid:
|
| 125 |
+
st.error("Please configure API key first")
|
| 126 |
+
else:
|
| 127 |
+
with st.spinner("Training ML model... This may take 1-2 minutes"):
|
| 128 |
+
try:
|
| 129 |
+
metrics = trainer.train_model_if_needed()
|
| 130 |
+
if metrics:
|
| 131 |
+
st.success("π Model trained successfully!")
|
| 132 |
+
st.session_state.model_trained = True
|
| 133 |
+
st.rerun()
|
| 134 |
+
else:
|
| 135 |
+
st.error("Training failed. Please check the logs.")
|
| 136 |
+
except Exception as e:
|
| 137 |
+
st.error(f"Training error: {str(e)}")
|
| 138 |
|
| 139 |
st.divider()
|
| 140 |
|
| 141 |
+
# Analysis configuration (only if API key is valid)
|
| 142 |
+
if st.session_state.api_key_valid:
|
| 143 |
+
st.header("π Analysis Options")
|
| 144 |
+
|
| 145 |
+
analysis_type = st.selectbox(
|
| 146 |
+
"Select Analysis Type",
|
| 147 |
+
["comprehensive", "churn_focus", "quick_insights"],
|
| 148 |
+
format_func=lambda x: {
|
| 149 |
+
"comprehensive": "π― Comprehensive Review",
|
| 150 |
+
"churn_focus": "π¨ Churn Risk Analysis",
|
| 151 |
+
"quick_insights": "β‘ Quick Insights"
|
| 152 |
+
}[x],
|
| 153 |
+
key="analysis_type_select"
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
st.session_state.analysis_type = analysis_type
|
| 157 |
+
|
| 158 |
+
# Advanced options
|
| 159 |
+
with st.expander("βοΈ Advanced Options"):
|
| 160 |
+
risk_threshold = st.slider(
|
| 161 |
+
"Churn Risk Threshold",
|
| 162 |
+
0.3, 0.9, 0.6,
|
| 163 |
+
key="risk_threshold_slider"
|
| 164 |
+
)
|
| 165 |
+
max_customers = st.number_input(
|
| 166 |
+
"Max Customers to Analyze",
|
| 167 |
+
50, 500, 200,
|
| 168 |
+
key="max_customers_input"
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
st.session_state.risk_threshold = risk_threshold
|
| 172 |
+
st.session_state.max_customers = max_customers
|
| 173 |
|
| 174 |
+
# Main content logic
|
| 175 |
+
if not st.session_state.api_key_valid:
|
| 176 |
+
# Show welcome screen when API key not configured
|
| 177 |
st.info("π Please enter your OpenAI API Key in the sidebar to begin")
|
| 178 |
|
| 179 |
col1, col2 = st.columns(2)
|
|
|
|
| 215 |
with col4:
|
| 216 |
st.metric("Model Accuracy", "87.3%", delta="2.1%")
|
| 217 |
|
| 218 |
+
elif not st.session_state.model_trained:
|
| 219 |
# Model training required
|
| 220 |
st.warning("π§ Machine learning model needs to be trained before analysis")
|
| 221 |
st.info("π Use the 'Train Model Now' button in the sidebar (takes 1-2 minutes)")
|
|
|
|
| 230 |
""")
|
| 231 |
|
| 232 |
else:
|
| 233 |
+
# Main analysis interface - API key valid and model trained
|
| 234 |
+
st.markdown("## π― AI Business Intelligence Dashboard")
|
| 235 |
|
| 236 |
# Analysis execution
|
| 237 |
if st.button("π Run RICA Analysis", type="primary", use_container_width=True):
|
| 238 |
+
with st.spinner("π€ RICA is analyzing your business data..."):
|
| 239 |
+
try:
|
| 240 |
+
# Execute analysis
|
| 241 |
+
parameters = {
|
| 242 |
+
"risk_threshold": st.session_state.risk_threshold,
|
| 243 |
+
"max_customers": st.session_state.max_customers
|
| 244 |
+
}
|
| 245 |
+
|
| 246 |
+
result = execute_rica_analysis_hf(st.session_state.analysis_type, parameters)
|
| 247 |
+
|
| 248 |
+
# Display results
|
| 249 |
+
st.success("β
Analysis Complete!")
|
| 250 |
+
|
| 251 |
+
# Create tabs for different result views
|
| 252 |
+
if st.session_state.analysis_type == "comprehensive":
|
| 253 |
+
tab1, tab2, tab3 = st.tabs(["π Executive Summary", "π¨ Risk Analysis", "π‘ Recommendations"])
|
| 254 |
|
| 255 |
+
with tab1:
|
| 256 |
+
st.markdown("### Executive Dashboard")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 257 |
st.info(str(result))
|
| 258 |
|
| 259 |
+
with tab2:
|
| 260 |
+
st.markdown("### Customer Risk Analysis")
|
| 261 |
+
st.write("Detailed churn risk breakdown and customer segmentation")
|
| 262 |
|
| 263 |
+
with tab3:
|
| 264 |
+
st.markdown("### AI Recommendations")
|
| 265 |
+
st.write("Specific actions prioritized by business impact")
|
| 266 |
+
|
| 267 |
+
else:
|
| 268 |
+
st.markdown(f"### {st.session_state.analysis_type.replace('_', ' ').title()} Results")
|
| 269 |
+
st.info(str(result))
|
| 270 |
+
|
| 271 |
+
# Raw response in expander
|
| 272 |
+
with st.expander("π Detailed Analysis Response"):
|
| 273 |
+
st.code(str(result), language="text")
|
| 274 |
+
|
| 275 |
+
except Exception as e:
|
| 276 |
+
st.error(f"β Analysis failed: {str(e)}")
|
| 277 |
+
st.info("Please check your API key and model status")
|
| 278 |
|
| 279 |
+
# Show model performance metrics
|
| 280 |
if st.session_state.trainer.model_exists():
|
| 281 |
st.markdown("## π Model Performance")
|
| 282 |
+
try:
|
| 283 |
+
metadata = st.session_state.trainer.load_existing_metadata()
|
| 284 |
+
if metadata and 'metrics' in metadata:
|
| 285 |
+
col1, col2, col3 = st.columns(3)
|
| 286 |
+
|
| 287 |
+
with col1:
|
| 288 |
+
st.metric("Model Accuracy", f"{metadata['metrics'].get('test_accuracy', 0):.1%}")
|
| 289 |
+
with col2:
|
| 290 |
+
st.metric("Training Samples", f"{metadata['metrics'].get('training_samples', 0):,}")
|
| 291 |
+
with col3:
|
| 292 |
+
st.metric("Churn Rate", f"{metadata['metrics'].get('churn_rate', 0):.1%}")
|
| 293 |
+
except:
|
| 294 |
+
st.info("Model performance metrics unavailable")
|
| 295 |
|
| 296 |
# Footer
|
| 297 |
st.markdown("---")
|