""" JioPay RAG Chatbot - Streamlit User Interface This script provides a clean, production-ready user interface for the JioPayRAGChatbot, separating the UI logic from the core RAG implementation. """ import os import streamlit as st from pathlib import Path from dotenv import load_dotenv # Ensure all required modules are available try: from jiopay_llm_rag import JioPayRAGChatbot except ImportError: st.error("Failed to import JioPayRAGChatbot. Make sure 'jiopay_llm_rag.py' is in the same directory.") st.stop() # --- Configuration and Initialization --- # --- Hardcoded API Key --- # This is not a secure practice. Use environment variables in production. API_KEY = "AIzaSyC-J9I4rNSIwWhxceSVWJHYwmlniJg9hbw" # Set page configuration st.set_page_config( page_title="JioPay Support Chatbot", page_icon="🤖", layout="wide", initial_sidebar_state="expanded" ) @st.cache_resource def get_chatbot_instance(): """ Initializes and caches the RAG chatbot instance. Using st.cache_resource ensures the model and index are loaded only once. """ if not API_KEY: st.error( "Gemini API Key is missing. Please hardcode it in streamlit_app.py." ) st.stop() # This assumes the index has been created by the pipeline in this location. index_path = "chunked_data/faiss_index" if not (os.path.exists(f"{index_path}_faiss.index") and os.path.exists(f"{index_path}_docs.pkl")): st.error(f"FAISS index not found at '{index_path}'. Please run the indexing pipeline first (`python main_orchestration.py index`).") st.stop() return JioPayRAGChatbot(api_key=API_KEY, index_path=index_path) def initialize_session_state(): """Initializes Streamlit session state variables.""" if "messages" not in st.session_state: st.session_state.messages = [{"role": "assistant", "content": "Welcome to JioPay Support! How can I assist you today?"}] def render_sidebar(chatbot_instance): """Renders the sidebar with settings and statistics.""" with st.sidebar: st.header("⚙️ Chat Settings") k_value = st.slider("Number of Context Chunks (k)", 1, 10, 5, help="How many relevant text chunks to retrieve for context.") prompt_type = st.selectbox("Response Style", ["default", "detailed", "technical"], help="Choose the persona for the chatbot's response.") st.divider() st.header("📊 Chatbot Statistics") if st.button("Refresh Stats"): st.rerun() stats = chatbot_instance.stats st.metric("Total Queries", stats.get('total_queries', 0)) success_rate = (stats.get('successful_answers', 0) / max(1, stats.get('total_queries', 0))) * 100 st.metric("Success Rate", f"{success_rate:.1f}%") st.metric("Avg. Response Time", f"{stats.get('avg_response_time', 0):.2f}s") def render_chat_interface(chatbot_instance, k_value, prompt_type): """Renders the main chat interface.""" st.title("🤖 JioPay RAG Support Chatbot") st.caption("Powered by Gemini & Advanced RAG") # Display chat messages for msg in st.session_state.messages: with st.chat_message(msg["role"]): st.markdown(msg["content"]) # Handle user input if prompt := st.chat_input("Ask anything about JioPay..."): st.session_state.messages.append({"role": "user", "content": prompt}) st.chat_message("user").markdown(prompt) with st.chat_message("assistant"): with st.spinner("Thinking..."): response = chatbot_instance.generate_answer( query=prompt, k=k_value, prompt_type=prompt_type ) st.markdown(response['answer']) # Display citations/sources if available if response.get('citations'): with st.expander("📚 View Sources"): for i, citation in enumerate(response['citations'], 1): st.write(f"**Source {i}:** {citation.source_url} (Relevance: {citation.relevance_score:.2f})") st.caption(citation.text) st.session_state.messages.append({"role": "assistant", "content": response['answer']}) def main(): """Main function to run the Streamlit app.""" chatbot = get_chatbot_instance() initialize_session_state() render_sidebar(chatbot) render_chat_interface(chatbot, st.session_state.get('k_value', 5), st.session_state.get('prompt_type', 'default')) if __name__ == "__main__": main()