import streamlit as st import google.generativeai as genai import os # --- Page Configuration and Styling --- st.set_page_config( page_title="Monster Group AI Assistant", page_icon="👾", layout="wide", ) st.markdown(""" """, unsafe_allow_html=True) # --- Title and Header --- st.title("Monster Group AI Assistant 👾") st.write("A specialized AI assistant for the **Monster Group**, the largest sporadic simple group.") st.info("I use the **Gemini Flash 2.0** model to provide concise and accurate information.") st.write("---") # --- API Key Configuration --- if "GOOGLE_API_KEY" not in os.environ: st.error("API key not found. Please add your `GOOGLE_API_KEY` to the Hugging Face Space secrets.") st.stop() else: genai.configure(api_key=os.environ["GOOGLE_API_KEY"]) # --- System Prompt and Model Initialization --- SYSTEM_PROMPT = """ You are a helpful and knowledgeable assistant for the Monster Group in mathematics. Your goal is to provide accurate, detailed, and clear information about this topic. You should be able to answer questions about its properties, its order, its connection to other mathematical fields like Monstrous Moonshine, and its role in physics. Be polite and professional. """ # Initialize the model with the system prompt and cache it in session_state if "model" not in st.session_state: try: st.session_state.model = genai.GenerativeModel( "gemini-2.0-flash", system_instruction=SYSTEM_PROMPT ) except Exception as e: st.error(f"Failed to initialize the Gemini model. Please check your API key. Error: {e}") st.stop() # Initialize chat history in session state if "messages" not in st.session_state: st.session_state.messages = [] # --- Display Chat History --- for message in st.session_state.messages: with st.chat_message(message["role"]): st.markdown(message["content"]) # --- Handle User Input and Generate Response --- if prompt := st.chat_input("Ask a question about the Monster Group..."): # Display user message in chat message container with st.chat_message("user"): st.markdown(prompt) st.session_state.messages.append({"role": "user", "content": prompt}) # Generate and stream the assistant's response with st.chat_message("assistant"): with st.spinner("Thinking..."): try: # The correct method for streaming is to use the model object directly stream = st.session_state.model.generate_content(prompt, stream=True) response_text = "" # Iterate through the chunks and append the text for chunk in stream: if chunk.text: response_text += chunk.text st.markdown(response_text) except Exception as e: st.error(f"An error occurred while generating a response. Error: {e}") st.stop() # Add the complete assistant response to chat history st.session_state.messages.append({"role": "assistant", "content": response_text})