Spaces:
Sleeping
Sleeping
| """FoodHub Customer Service Chatbot β Streamlit frontend.""" | |
| import streamlit as st | |
| # @st.cache_resource is Streamlit's standard pattern for initialising shared | |
| # resources (models, DB connections, agents) that are expensive to create. | |
| # It runs the function body exactly once per container lifetime and caches | |
| # the result β all sessions and reruns reuse the same initialised agent. | |
| def get_chat_agent(): | |
| try: | |
| from agent import run_chat_agent_query | |
| return run_chat_agent_query, None | |
| except Exception as e: | |
| return None, str(e) | |
| # Assign at module level so the function is available as a normal callable. | |
| # Streamlit's cache ensures the initialisation only runs once, not on every rerun. | |
| run_chat_agent_query, _init_error = get_chat_agent() | |
| # --------------------------------------------------------------------------- | |
| # Page configuration | |
| # --------------------------------------------------------------------------- | |
| st.set_page_config( | |
| page_title="FoodHub Customer Service", | |
| page_icon="π", | |
| layout="centered", | |
| ) | |
| st.title("π FoodHub Customer Service") | |
| st.caption( | |
| "Ask about your order status, delivery ETA, items, or payment. " | |
| "Please have your Order ID ready (e.g. O12486)." | |
| ) | |
| st.divider() | |
| if _init_error: | |
| st.error(f"Agent initialisation failed:\n\n```\n{_init_error}\n```") | |
| st.stop() | |
| # --------------------------------------------------------------------------- | |
| # Session state β persist conversation history across reruns | |
| # --------------------------------------------------------------------------- | |
| if "messages" not in st.session_state: | |
| st.session_state.messages = [] | |
| # --------------------------------------------------------------------------- | |
| # Render existing conversation history | |
| # --------------------------------------------------------------------------- | |
| for message in st.session_state.messages: | |
| with st.chat_message(message["role"]): | |
| st.markdown(message["content"]) | |
| # --------------------------------------------------------------------------- | |
| # Chat input | |
| # --------------------------------------------------------------------------- | |
| if prompt := st.chat_input("Type your question here..."): | |
| # Display the customer's message immediately | |
| st.session_state.messages.append({"role": "user", "content": prompt}) | |
| with st.chat_message("user"): | |
| st.markdown(prompt) | |
| # Get the Chat Agent's response and display it | |
| with st.chat_message("assistant"): | |
| with st.spinner("Looking into your query..."): | |
| response = run_chat_agent_query(prompt) | |
| st.markdown(response) | |
| # Save assistant response to history | |
| st.session_state.messages.append({"role": "assistant", "content": response}) | |