Spaces:
Runtime error
Runtime error
Upload streamlit_ui.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808"""
Streamlit UI for Autonomous Demand Forecasting Agent
Displays agent actions, system status, and provides chat interface
"""
import streamlit as st
import asyncio
import json
import logging
import sqlite3
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Any
import time
import threading
from pathlib import Path
# Import agent and MCP components
try:
from autonomous_demand_forecasting.agent import root_agent
from autonomous_demand_forecasting.optimized_agent import create_optimized_agent
from autonomous_demand_forecasting.ds_prompt import DATA_SCIENTIST_AGENT_PROMPT
except ImportError as e:
st.error(f"Failed to import agent components: {e}")
root_agent = None
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Database path
DATABASE_PATH = Path(__file__).parent / "database" / "autonomous_demand_forecasting.db"
class AgentActionTracker:
"""Tracks and stores agent actions for UI display"""
def __init__(self):
self.actions = []
self.max_actions = 100
def add_action(self, action_type: str, description: str, status: str = "completed",
metadata: Dict = None):
"""Add a new agent action"""
action = {
"timestamp": datetime.now(),
"type": action_type,
"description": description,
"status": status,
"metadata": metadata or {}
}
self.actions.insert(0, action) # Most recent first
if len(self.actions) > self.max_actions:
self.actions.pop()
def get_recent_actions(self, limit: int = 20) -> List[Dict]:
"""Get recent actions for display"""
return self.actions[:limit]
def get_actions_by_type(self, action_type: str) -> List[Dict]:
"""Get actions filtered by type"""
return [a for a in self.actions if a["type"] == action_type]
# Initialize action tracker using agent monitor
if 'agent_monitor' not in st.session_state:
try:
from autonomous_demand_forecasting.agent_monitor import get_global_monitor
st.session_state.agent_monitor = get_global_monitor()
# Populate with sample data if empty
if not st.session_state.agent_monitor.get_recent_actions(1):
st.session_state.agent_monitor.populate_sample_data()
except Exception as e:
logger.error(f"Failed to initialize agent monitor: {e}")
st.session_state.agent_monitor = None
# Keep the old action tracker for backward compatibility
if 'action_tracker' not in st.session_state:
st.session_state.action_tracker = AgentActionTracker()
def get_db_connection():
"""Get database connection"""
try:
conn = sqlite3.connect(str(DATABASE_PATH))
conn.row_factory = sqlite3.Row
return conn
except Exception as e:
logger.error(f"Database connection failed: {e}")
return None
def load_system_metrics():
"""Load system performance metrics"""
try:
# Import and use the agent monitor
from autonomous_demand_forecasting.agent_monitor import get_global_monitor
monitor = get_global_monitor()
return monitor.get_system_metrics_for_ui()
except Exception as e:
logger.error(f"Failed to load system metrics: {e}")
return {
"drift_events": 0,
"high_severity_ratio": 0,
"avg_accuracy": 0.85,
"total_predictions": 0
}
def display_agent_status():
"""Display current agent status and capabilities"""
st.header("π€ Agent Status")
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("Agent Status", "π’ Active", "Running")
with col2:
st.metric("MCP Servers", "4", "Connected")
with col3:
metrics = load_system_metrics()
if metrics:
st.metric("Avg Accuracy", f"{metrics['avg_accuracy']:.3f}",
f"{metrics['total_predictions']} predictions")
else:
st.metric("Avg Accuracy", "0.850", "No data")
with col4:
if metrics:
st.metric("Drift Events", metrics['drift_events'], "Last 24h")
else:
st.metric("Drift Events", "0", "Last 24h")
def display_agent_actions():
"""Display recent agent actions"""
st.header("π Recent Agent Actions")
# Try to get actions from agent monitor first
actions = []
if st.session_state.agent_monitor:
try:
monitor_actions = st.session_state.agent_monitor.get_recent_actions(20)
actions = [
{
"timestamp": action.timestamp,
"type": action.type.value,
"description": action.description,
"status": action.status.value,
"metadata": action.metadata,
"duration": action.duration,
"error_message": action.error_message
}
for action in monitor_actions
]
except Exception as e:
logger.error(f"Failed to get actions from monitor: {e}")
# Fallback to old action tracker
if not actions:
actions = st.session_state.action_tracker.get_recent_actions(20)
if not actions:
st.info("No recent agent actions recorded. The agent will start logging actions once it begins processing.")
return
for action in actions:
action_type = action.get('type', 'unknown')
timestamp = action.get('timestamp', datetime.now())
with st.expander(f"{action_type.replace('_', ' ').title()} - {timestamp.strftime('%H:%M:%S')}"):
col1, col2 = st.columns([3, 1])
with col1:
st.write(f"**Description:** {action.get('description', 'No description')}")
st.write(f"**Time:** {timestamp.strftime('%Y-%m-%d %H:%M:%S')}")
if action.get('duration'):
st.write(f"**Duration:** {action['duration']:.2f}s")
if action.get('error_message'):
st.error(f"**Error:** {action['error_message']}")
if action.get('metadata'):
st.json(action['metadata'])
with col2:
status = action.get('status', 'unknown')
status_color = {
"completed": "π’",
"in_progress": "π‘",
"failed": "π΄",
"pending": "βͺ",
"cancelled": "β«"
}
st.write(f"**Status:** {status_color.get(status, 'βͺ')} {status}")
def display_system_overview():
"""Display system overview with charts"""
st.header("π System Overview")
# Create sample data for visualization
dates = pd.date_range(start=datetime.now() - timedelta(days=7), end=datetime.now(), freq='H')
accuracy_data = pd.DataFrame({
'timestamp': dates,
'accuracy': [0.85 + 0.1 * (i % 10) / 10 for i in range(len(dates))]
})
col1, col2 = st.columns(2)
with col1:
st.subheader("Model Accuracy Trend")
fig = px.line(accuracy_data, x='timestamp', y='accuracy',
title="Model Accuracy Over Time")
fig.update_layout(height=300)
st.plotly_chart(fig, use_container_width=True)
with col2:
st.subheader("Action Distribution")
action_types = ["drift_detection", "data_collection", "model_training", "deployment"]
action_counts = [15, 8, 5, 3]
fig = px.pie(values=action_counts, names=action_types,
title="Agent Actions (Last 24h)")
fig.update_layout(height=300)
st.plotly_chart(fig, use_container_width=True)
async def chat_with_agent(message: str) -> str:
"""Send message to agent and get response"""
try:
if root_agent is None:
return "β Agent not available. Please check the system configuration."
# Log chat interaction using agent monitor
if st.session_state.agent_monitor:
from autonomous_demand_forecasting.agent_monitor import ActionType
action_id = st.session_state.agent_monitor.start_action(
ActionType.CHAT_INTERACTION,
f"User query: {message[:50]}...",
metadata={"query_length": len(message)}
)
# Send message to agent
response = await root_agent.send_message(message)
# Complete chat interaction logging
if st.session_state.agent_monitor and 'action_id' in locals():
st.session_state.agent_monitor.complete_action(
action_id,
metadata={"response_length": len(str(response)), "success": True}
)
return str(response)
except Exception as e:
logger.error(f"Chat error: {e}")
return f"β Error communicating with agent: {str(e)}"
def display_chat_bubble():
"""Display floating chat bubble with embedded Hugging Face space"""
# Initialize chat bubble state
if 'chat_bubble_open' not in st.session_state:
st.session_state.chat_bubble_open = False
if 'chat_bubble_minimized' not in st.session_state:
st.session_state.chat_bubble_minimized = False
# CSS for chat bubble styling
st.markdown("""
<style>
.chat-bubble-container {
position: fixed;
bottom: 20px;
right: 20px;
z-index: 1000;
}
.chat-bubble-button {
width: 60px;
height: 60px;
border-radius: 50%;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border: none;
cursor: pointer;
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
display: flex;
align-items: center;
justify-content: center;
font-size: 24px;
color: white;
transition: all 0.3s ease;
}
.chat-bubble-button:hover {
transform: scale(1.1);
box-shadow: 0 6px 20px rgba(0,0,0,0.25);
}
.chat-bubble-window {
position: fixed;
bottom: 90px;
right: 20px;
width: 870px;
height: 470px;
background: white;
border-radius: 15px;
box-shadow: 0 8px 32px rgba(0,0,0,0.2);
z-index: 1001;
overflow: hidden;
border: 2px solid #e1e5e9;
transition: all 0.3s ease;
}
.chat-bubble-window.minimized {
height: 60px;
overflow: hidden;
}
.chat-bubble-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 15px 20px;
font-weight: bold;
display: flex;
justify-content: space-between;
align-items: center;
cursor: pointer;
}
.chat-bubble-controls {
display: flex;
gap: 5px;
}
.chat-bubble-control-btn {
background: none;
border: none;
color: white;
font-size: 16px;
cursor: pointer;
padding: 0;
width: 25px;
height: 25px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
transition: background 0.2s ease;
}
.chat-bubble-control-btn:hover {
background: rgba(255,255,255,0.2);
}
.chat-iframe-container {
width: 100%;
height: calc(100% - 60px);
border: none;
transition: opacity 0.3s ease;
}
.chat-bubble-window.minimized .chat-iframe-container {
opacity: 0;
pointer-events: none;
}
</style>
""", unsafe_allow_html=True)
# Chat bubble toggle button
col1, col2 = st.columns([10, 1])
with col2:
if st.button("π¬", key="chat_bubble_toggle", help="Open AI Agent Chat"):
st.session_state.chat_bubble_open = not st.session_state.chat_bubble_open
if st.session_state.chat_bubble_open:
st.session_state.chat_bubble_minimized = False
# Handle minimize/maximize actions
if st.session_state.get('minimize_chat', False):
st.session_state.chat_bubble_minimized = not st.session_state.chat_bubble_minimized
st.session_state.minimize_chat = False
st.rerun()
if st.session_state.get('close_chat', False):
st.session_state.chat_bubble_open = False
st.session_state.chat_bubble_minimized = False
st.session_state.close_chat = False
st.rerun()
# Chat bubble window
if st.session_state.chat_bubble_open:
window_class = "chat-bubble-window minimized" if st.session_state.chat_bubble_minimized else "chat-bubble-window"
minimize_icon = "πΌ" if st.session_state.chat_bubble_minimized else "π½"
st.markdown(f"""
<div class="{window_class}">
<div class="chat-bubble-header" onclick="document.getElementById('minimize_chat_btn').click()">
<span>π€ AI Demand Forecasting Agent</span>
<div class="chat-bubble-controls">
<button class="chat-bubble-control-btn" onclick="document.getElementById('minimize_chat_btn').click()" title="Minimize/Maximize">
{minimize_icon}
</button>
<button class="chat-bubble-control-btn" onclick="document.getElementById('close_chat_btn').click()" title="Close">
β
</button>
</div>
</div>
<iframe
src="https://vah6002-demand-forecasting-ai-agent-mcp.hf.space"
frameborder="0"
width="100%"
height="100%"
class="chat-iframe-container">
</iframe>
</div>
""", unsafe_allow_html=True)
# Hidden buttons for control actions
col1, col2, col3 = st.columns([1, 1, 1])
with col1:
if st.button("", key="minimize_chat_btn", help="Minimize/Maximize"):
st.session_state.minimize_chat = True
st.rerun()
with col2:
if st.button("", key="close_chat_btn", help="Close"):
st.session_state.close_chat = True
st.rerun()
# Apply CSS to hide the control buttons
st.markdown("""
<style>
button[data-testid="baseButton-secondary"][title="Minimize/Maximize"],
button[data-testid="baseButton-secondary"][title="Close"] {
display: none !important;
}
</style>
""", unsafe_allow_html=True)
def display_chat_interface():
"""Display chat interface with the agent"""
st.header("π¬ Chat with Agent")
# Initialize iframe display state
if 'show_embedded_iframe' not in st.session_state:
st.session_state.show_embedded_iframe = True
# Add chat bubble option
col1, col2 = st.columns([3, 1])
with col1:
st.markdown("Choose your preferred chat interface:")
with col2:
if st.button("π Open AI Agent Chat", use_container_width=True):
st.session_state.chat_bubble_open = True
st.rerun()
# Embedded Hugging Face Space with controls
col1, col2 = st.columns([4, 1])
with col1:
st.subheader("π€ AI Agent Interface")
with col2:
if st.session_state.show_embedded_iframe:
if st.button("π Minimize", key="minimize_iframe", use_container_width=True):
st.session_state.show_embedded_iframe = False
st.rerun()
else:
if st.button("π Restore", key="restore_iframe", use_container_width=True):
st.session_state.show_embedded_iframe = True
st.rerun()
if st.session_state.show_embedded_iframe:
st.markdown("**Direct access to the AI Demand Forecasting Agent:**")
# Embed the Hugging Face space
st.components.v1.iframe(
src="https://vah6002-demand-forecasting-ai-agent-mcp.hf.space",
width=850,
height=450,
scrolling=True
)
else:
st.info("π¬ AI Agent Interface is minimized. Click 'Restore' to show it again.")
st.divider()
# Local chat interface as backup
st.subheader("π¬ Local Chat Interface")
st.markdown("**Fallback chat interface (for testing and backup):**")
# Initialize chat history
if 'chat_history' not in st.session_state:
st.session_state.chat_history = []
# Display chat history
chat_container = st.container()
with chat_container:
for i, (role, message, timestamp) in enumerate(st.session_state.chat_history):
if role == "user":
st.chat_message("user").write(f"{message}")
else:
st.chat_message("assistant").write(f"{message}")
# Chat input
user_input = st.chat_input("Ask the agent about system status, request actions, or get insights...")
if user_input:
# Add user message to history
st.session_state.chat_history.append(("user", user_input, datetime.now()))
# Show user message immediately
st.chat_message("user").write(user_input)
# Get agent response
with st.chat_message("assistant"):
with st.spinner("Agent is thinking..."):
try:
# For now, provide intelligent responses based on keywords
response = generate_agent_response(user_input)
st.write(response)
# Add to history
st.session_state.chat_history.append(("assistant", response, datetime.now()))
except Exception as e:
error_msg = f"β Error: {str(e)}"
st.write(error_msg)
st.session_state.chat_history.append(("assistant", error_msg, datetime.now()))
def generate_agent_response(user_input: str) -> str:
"""Generate intelligent responses based on user input"""
user_input_lower = user_input.lower()
# System status queries
if any(word in user_input_lower for word in ["status", "health", "running"]):
return """π’ **System Status: Healthy**
**Active Components:**
- Drift Detection MCP: β
Running
- Sales Data MCP: β
Running
- Inventory MCP: β
Running
- Forecasting Model MCP: β οΈ Disabled
**Recent Activity:**
- Last drift check: 2 minutes ago
- Model accuracy: 85.3%
- No critical alerts
**Next Actions:**
- Scheduled drift analysis in 3 minutes
- Data collection pipeline ready"""
# Drift detection queries
elif any(word in user_input_lower for word in ["drift", "accuracy", "performance"]):
return """π **Model Performance Analysis**
**Current Metrics:**
- Model Accuracy: 85.3% (β 2.1% from yesterday)
- Drift Status: LOW severity
- Last retraining: 3 days ago
**Drift Detection Results:**
- Performance threshold: 85%
- Current performance: Above threshold β
- Trend: Stable with minor fluctuations
**Recommendation:**
Continue monitoring. No immediate retraining required."""
# Training and retraining queries
elif any(word in user_input_lower for word in ["train", "retrain", "model"]):
return """π **Model Training Status**
**Current Training Pipeline:**
- Status: Standby (no active training)
- Last training: 3 days ago
- Next scheduled: Based on drift detection
**Available Models:**
- ARIMA: Ready for training
- Prophet: Ready for training
- XGBoost: Ready for training
- Ensemble: Ready for training
**Training Triggers:**
- High drift severity detected
- Manual user request
- Scheduled weekly retraining
Would you like me to initiate a training cycle?"""
# Data queries
elif any(word in user_input_lower for word in ["data", "sales", "inventory"]):
return """π **Data Pipeline Status**
**Sales Data:**
- Last collection: 1 hour ago
- Records processed: 15,847 transactions
- Data quality: 98.2% β
- Coverage: 90 days historical
**Inventory Data:**
- Current snapshot: Available
- Stock levels: Normal
- Out-of-stock items: 3.2%
**Data Quality Checks:**
- Missing values: < 1%
- Anomaly detection: Passed
- Schema validation: Passed"""
# Help and capabilities
elif any(word in user_input_lower for word in ["help", "what can you", "capabilities"]):
return """π€ **Agent Capabilities**
**I can help you with:**
**π Monitoring & Analysis:**
- Check system health and status
- Analyze model performance and drift
- Review recent agent actions
- Monitor data pipeline status
**π Model Management:**
- Trigger model retraining
- Deploy new model versions
- Rollback problematic deployments
- Validate model performance
**π Data Operations:**
- Collect and validate sales data
- Analyze customer behavior patterns
- Check inventory levels
- Assess data quality
**π¨ Alerting & Escalation:**
- Handle drift alerts
- Manage business impact notifications
- Escalate critical issues
**Example queries:**
- "What's the current system status?"
- "Show me model performance"
- "Start a retraining cycle"
- "Check data quality"
"""
# Default response
else:
return f"""π€ **Processing your request...**
I understand you're asking about: "{user_input}"
**Current System Context:**
- Agent Status: Active and monitoring
- Model Performance: 85.3% accuracy
- No critical alerts
**Available Actions:**
- System status check
- Performance analysis
- Data collection
- Model retraining
- Deployment management
Could you be more specific about what you'd like me to help with? Try asking about "status", "performance", "training", or "data"."""
def main():
"""Main Streamlit application"""
st.set_page_config(
page_title="Autonomous Demand Forecasting Agent",
page_icon="π€",
layout="wide",
initial_sidebar_state="expanded"
)
st.title("π€ Autonomous Demand Forecasting Agent")
st.markdown("Real-time monitoring and interaction with the intelligent forecasting system")
# Sidebar navigation
st.sidebar.title("Navigation")
page = st.sidebar.selectbox(
"Choose a view:",
["Dashboard", "Agent Actions", "System Overview", "Chat Interface", "Configuration"]
)
# Auto-refresh toggle
auto_refresh = st.sidebar.checkbox("Auto-refresh (30s)", value=False)
# Quick chat access
st.sidebar.divider()
st.sidebar.subheader("π€ Quick Chat")
if st.sidebar.button("π¬ Open AI Agent", use_container_width=True):
st.session_state.chat_bubble_open = True
st.rerun()
if auto_refresh:
time.sleep(30)
st.rerun()
# Main content based on selected page
if page == "Dashboard":
display_agent_status()
st.divider()
col1, col2 = st.columns([2, 1])
with col1:
display_agent_actions()
with col2:
st.header("π― Quick Actions")
if st.button("π Run Drift Analysis", use_container_width=True):
if st.session_state.agent_monitor:
from autonomous_demand_forecasting.agent_monitor import ActionType
action_id = st.session_state.agent_monitor.start_action(
ActionType.DRIFT_DETECTION,
"Manual drift analysis triggered via UI"
)
# Simulate completion after a short delay
time.sleep(1)
st.session_state.agent_monitor.complete_action(
action_id,
metadata={"trigger": "manual", "drift_detected": False, "accuracy": 0.87}
)
st.session_state.agent_monitor.log_drift_event("LOW", "v1.2", 0.15, 0.2)
else:
st.session_state.action_tracker.add_action(
"drift_detection", "Manual drift analysis triggered", "completed"
)
st.success("Drift analysis completed!")
st.rerun()
if st.button("π Collect Sales Data", use_container_width=True):
if st.session_state.agent_monitor:
from autonomous_demand_forecasting.agent_monitor import ActionType
action_id = st.session_state.agent_monitor.start_action(
ActionType.DATA_COLLECTION,
"Manual sales data collection triggered via UI"
)
time.sleep(1)
st.session_state.agent_monitor.complete_action(
action_id,
metadata={"trigger": "manual", "records_collected": 15847, "data_quality": 0.982}
)
else:
st.session_state.action_tracker.add_action(
"data_collection", "Manual sales data collection triggered", "completed"
)
st.success("Data collection completed!")
st.rerun()
if st.button("π Start Retraining", use_container_width=True):
if st.session_state.agent_monitor:
from autonomous_demand_forecasting.agent_monitor import ActionType
action_id = st.session_state.agent_monitor.start_action(
ActionType.MODEL_TRAINING,
"Manual model retraining triggered via UI"
)
time.sleep(2)
st.session_state.agent_monitor.complete_action(
action_id,
metadata={"trigger": "manual", "model_type": "ensemble", "training_time": 120}
)
# Log accuracy improvement
st.session_state.agent_monitor.log_accuracy_metric(0.89, "v1.3", 50000)
else:
st.session_state.action_tracker.add_action(
"model_training", "Manual model retraining triggered", "completed"
)
st.success("Model retraining completed!")
st.rerun()
elif page == "Agent Actions":
display_agent_actions()
elif page == "System Overview":
display_system_overview()
elif page == "Chat Interface":
display_chat_interface()
elif page == "Configuration":
st.header("βοΈ System Configuration")
st.subheader("MCP Server Status")
mcp_servers = {
"Drift Detection": {"status": "π’ Active", "endpoint": "drift_detection_mcp_server"},
"Sales Data": {"status": "π’ Active", "endpoint": "sales_data_mcp_server"},
"Inventory": {"status": "π’ Active", "endpoint": "inventory_mcp_server"},
"Forecasting Model": {"status": "π΄ Disabled", "endpoint": "forecasting_model_mcp_server"}
}
for server, info in mcp_servers.items():
col1, col2, col3 = st.columns([2, 1, 1])
with col1:
st.write(f"**{server}**")
with col2:
st.write(info["status"])
with col3:
if "Disabled" in info["status"]:
if st.button(f"Enable", key=f"enable_{server}"):
st.success(f"Enabled {server}")
st.subheader("Agent Parameters")
threshold = st.slider("Drift Detection Threshold", 0.0, 1.0, 0.85, 0.01)
days_back = st.number_input("Sales Data Days", min_value=1, max_value=365, value=90)
if st.button("Update Configuration"):
st.success("Configuration updated successfully!")
# Display floating chat bubble on all pages
display_chat_bubble()
if __name__ == "__main__":
main()streamlit_ui.pyAdded+808