File: //opt/af/src/calendar_agent/routes.py
import streamlit as st
import logging
from datetime import datetime
import traceback
from src.calendar_agent.agent import CalendarAgent
log = logging.getLogger(__name__)
def render_calendar_page():
"""
Renders the Streamlit page for the Calendar Agent.
"""
st.title("📅 Calendar")
st.markdown("Ask questions about economic events and financial calendar data.")
# Initialize the Calendar Agent in Session State if not present
if 'calendar_agent' not in st.session_state:
log.info("Initializing CalendarAgent...")
st.session_state.calendar_agent = CalendarAgent()
log.info("CalendarAgent initialized and stored in Session State.")
# Initialize chat history if not present
if 'calendar_chat_history' not in st.session_state:
st.session_state.calendar_chat_history = []
# Display current events
with st.expander("🔍 Today's Events", expanded=True):
try:
today = datetime.now().strftime("%Y%m%d")
if st.button("Refresh Today's Events"):
with st.spinner("Getting current events..."):
try:
today_events = st.session_state.calendar_agent.process_query("Show me today's events.")
st.session_state.today_events = today_events
log.info(f"Today's events updated: {type(today_events)}")
except Exception as e:
error_msg = f"Error retrieving events: {str(e)}"
log.error(error_msg, exc_info=True)
st.session_state.today_events = error_msg
st.error(error_msg)
if 'today_events' not in st.session_state:
with st.spinner("Getting current events..."):
try:
today_events = st.session_state.calendar_agent.process_query("Show me today's events.")
st.session_state.today_events = today_events
log.info(f"Today's events retrieved: {type(today_events)}")
except Exception as e:
error_msg = f"Error retrieving events: {str(e)}"
log.error(error_msg, exc_info=True)
st.session_state.today_events = error_msg
st.error(error_msg)
# Safe display of the response
if 'today_events' in st.session_state:
events = st.session_state.today_events
log.info(f"Displaying today_events of type: {type(events)}")
try:
if isinstance(events, str):
st.markdown(events)
else:
st.write(events) # Fallback for non-string objects
except Exception as e:
log.error(f"Error displaying events: {str(e)}", exc_info=True)
st.error(f"Error displaying events: {str(e)}")
st.json({"error": str(e), "events_type": str(type(events))})
except Exception as e:
error_trace = traceback.format_exc()
log.error(f"Error displaying current events: {e}\n{error_trace}")
st.error(f"Error displaying current events: {str(e)}")
st.code(error_trace)
# Date input for specific events
st.markdown("### 📆 Show Events for Specific Date")
col1, col2 = st.columns(2)
with col1:
date_input = st.date_input("Select date", datetime.now())
with col2:
weekly_format = st.checkbox("Weekly format", value=False)
if st.button("Show Events for Date"):
date_formatted = date_input.strftime("%Y%m%d")
with st.spinner(f"Getting events for {date_formatted}..."):
date_events = st.session_state.calendar_agent.process_query(
f"Show me the events for {date_input.strftime('%m/%d/%Y')}" +
(" in weekly format" if weekly_format else "")
)
st.markdown(date_events)
# Chat interface
st.markdown("### 💬 Calendar Chat")
st.markdown("Ask questions about events and calendar data.")
# Display chat history
for message in st.session_state.calendar_chat_history:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# Chat input
prompt = st.chat_input("Your question about the calendar...")
if prompt:
# Add user message to history and display
st.session_state.calendar_chat_history.append({"role": "user", "content": prompt})
with st.chat_message("user"):
st.markdown(prompt)
# Generate and display agent response
with st.chat_message("assistant"):
with st.spinner("Agent thinking..."):
log.info(f"Processing user request to Calendar Agent: {prompt}")
try:
response = st.session_state.calendar_agent.process_query(prompt)
log.info(f"Response received from Calendar Agent: {type(response)}")
# Safe display of the response
try:
if isinstance(response, str):
st.markdown(response)
else:
st.write(response) # Fallback for non-string objects
except Exception as e:
log.error(f"Error displaying response: {str(e)}", exc_info=True)
st.error(f"Error displaying response: {str(e)}")
st.json({"error": str(e), "response_type": str(type(response))})
# Add response to history
if isinstance(response, str):
st.session_state.calendar_chat_history.append({"role": "assistant", "content": response})
else:
st.session_state.calendar_chat_history.append({"role": "assistant", "content": str(response)})
except Exception as e:
error_trace = traceback.format_exc()
log.error(f"Error processing request by Calendar Agent: {e}\n{error_trace}")
error_message = f"Error processing your request: {str(e)}"
st.error(error_message)
st.code(error_trace)
st.session_state.calendar_chat_history.append({"role": "assistant", "content": error_message})
# Clear history
if st.sidebar.button("Clear Chat History"):
st.session_state.calendar_chat_history = []
st.rerun()