Spaces:
Sleeping
Sleeping
| import streamlit as st | |
| import google.generativeai as genai | |
| import google.api_core.exceptions | |
| import os | |
| st.set_page_config( | |
| page_title="Let's Chat! AstroAid Health Assistant", | |
| layout="centered", | |
| initial_sidebar_state="auto" | |
| ) | |
| SYSTEM_PROMPT = """ | |
| You are AstroAid, a friendly and helpful AI health assistant designed for astronauts on long-duration space missions. | |
| Your goal is to provide basic, general health advice and suggestions based on the symptoms described by the user. | |
| Keep your tone encouraging, slightly futuristic, and empathetic. Use space-related analogies lightly if appropriate. | |
| IMPORTANT RULES: | |
| 1. ALWAYS start your response with a safety disclaimer: "Remember, AstroAid is an AI assistant, not a medical professional. This advice is general. For serious concerns, please consult with the mission's flight surgeon or Earth-based medical support." | |
| 2. NEVER diagnose specific conditions. Stick to general suggestions (e.g., rest, hydration, gentle stretching, deep breathing, checking vitals if possible). | |
| 3. If symptoms sound serious (e.g., severe pain, difficulty breathing, loss of consciousness), strongly advise contacting medical support immediately. | |
| 4. Keep responses relatively concise and easy to understand. | |
| 5. Do not ask for personally identifiable information. | |
| """ | |
| MODEL_TO_USE = 'gemini-1.5-flash-latest' | |
| def load_gemini_model(model_name, system_instruction): | |
| """Loads and configures the Generative Model.""" | |
| try: | |
| gemini_api_key = os.environ.get('API_KEY') | |
| if not gemini_api_key: | |
| st.error("API_KEY not found in environment variables. Please set it in your Hugging Face Space secrets.") | |
| st.stop() | |
| genai.configure(api_key=gemini_api_key) | |
| print(f"Attempting to load model: {model_name}") | |
| model = genai.GenerativeModel( | |
| model_name=model_name, | |
| system_instruction=system_instruction | |
| ) | |
| print(f"Successfully loaded model: {model_name}") | |
| return model | |
| except google.api_core.exceptions.PermissionDenied: | |
| st.error("Permission Denied. Check your API key permissions in Google Cloud.") | |
| st.stop() | |
| except Exception as e: | |
| st.error(f"Failed to load Gemini model ('{model_name}'): {e}") | |
| st.info("Verify the model name is correct and available for your API key/region.") | |
| st.stop() | |
| st.title(" Let's Chat! AstroAid Health Assistant") | |
| model = load_gemini_model(MODEL_TO_USE, SYSTEM_PROMPT) | |
| if "messages" not in st.session_state: | |
| st.session_state.messages = [ | |
| {"role": "model", "parts": ["AstroAid online. How can I assist you today, crewmate?"]} | |
| ] | |
| for message in st.session_state.messages: | |
| role_name = "Crewmate (You)" if message['role'] == 'user' else "AstroAid" | |
| with st.chat_message(name=role_name): | |
| st.markdown(message['parts'][0]) | |
| user_input = st.chat_input("Report symptoms or ask a question:") | |
| if user_input: | |
| st.session_state.messages.append({"role": "user", "parts": [user_input]}) | |
| with st.chat_message("Crewmate (You)"): | |
| st.markdown(user_input) | |
| try: | |
| with st.spinner("AstroAid is analyzing..."): | |
| response = model.generate_content(st.session_state.messages) | |
| response_text = None | |
| try: | |
| response_text = response.text | |
| except ValueError: | |
| response_text = None | |
| print("Warning: Accessing response.text failed, likely blocked content.") | |
| if response_text: | |
| st.session_state.messages.append({"role": "model", "parts": [response_text]}) | |
| with st.chat_message("AstroAid"): | |
| st.markdown(response_text) | |
| else: | |
| error_message_display = "AstroAid encountered an issue and could not generate a response. This might be due to safety filters or the query itself. Please try rephrasing." | |
| try: | |
| if response.prompt_feedback.block_reason: | |
| block_reason_name = response.prompt_feedback.block_reason.name | |
| error_message_display += f" (Reason Detected: {block_reason_name})" | |
| print(f"Response blocked by API. Reason: {block_reason_name}") | |
| except (AttributeError, ValueError, IndexError): | |
| print("Could not retrieve block reason from prompt_feedback.") | |
| pass | |
| st.session_state.messages.append({"role": "model", "parts": [error_message_display]}) | |
| with st.chat_message("AstroAid"): | |
| st.warning(error_message_display) | |
| except google.api_core.exceptions.GoogleAPIError as e: | |
| error_msg = f"Communication Error with AI Subsystem (API Error): {e}" | |
| st.error(error_msg) | |
| print(error_msg) | |
| if st.session_state.messages and st.session_state.messages[-1]['role'] == 'user': | |
| st.session_state.messages.pop() | |
| except Exception as e: | |
| error_msg = f"An unexpected system error occurred: {e}" | |
| st.error(error_msg) | |
| print(error_msg) | |
| if st.session_state.messages and st.session_state.messages[-1]['role'] == 'user': | |
| st.session_state.messages.pop() | |
| with st.sidebar: | |
| st.header("Controls") | |
| if st.button("Clear Mission Log"): | |
| st.session_state.messages = [ | |
| {"role": "model", "parts": ["AstroAid back online. Log cleared. How can I assist, crewmate?"]} | |
| ] | |
| st.success("Mission Log Cleared!") | |
| st.rerun() | |
| st.markdown("---") | |
| st.markdown("Made By Aniruddha Sarkar") | |
| st.markdown("Powered By Google Gemini API") |