Spaces:
Build error
Build error
Update moti_chat.py
Browse files- moti_chat.py +155 -15
moti_chat.py
CHANGED
|
@@ -1,21 +1,27 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
-
import
|
| 3 |
from datetime import datetime
|
|
|
|
| 4 |
|
| 5 |
def show_moti_chat():
|
| 6 |
-
st.title("Moti Chat - AI
|
| 7 |
|
| 8 |
# Initialize chat history
|
| 9 |
if "messages" not in st.session_state:
|
| 10 |
-
st.session_state.messages = [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
# Display chat history
|
| 13 |
-
for message in st.session_state.messages:
|
| 14 |
with st.chat_message(message["role"]):
|
| 15 |
st.markdown(message["content"])
|
| 16 |
|
| 17 |
# Chat input
|
| 18 |
-
if prompt := st.chat_input("
|
| 19 |
# Add user message to chat history
|
| 20 |
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 21 |
|
|
@@ -25,13 +31,147 @@ def show_moti_chat():
|
|
| 25 |
|
| 26 |
# Generate AI response
|
| 27 |
with st.chat_message("assistant"):
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
+
import google.generativeai as genai
|
| 3 |
from datetime import datetime
|
| 4 |
+
from prompts import USER_SUPPORT_SYSTEM_PROMPT, MI_SYSTEM_PROMPT
|
| 5 |
|
| 6 |
def show_moti_chat():
|
| 7 |
+
st.title("Moti Chat - AI Mental Health Assistant")
|
| 8 |
|
| 9 |
# Initialize chat history
|
| 10 |
if "messages" not in st.session_state:
|
| 11 |
+
st.session_state.messages = [
|
| 12 |
+
{"role": "system", "content": USER_SUPPORT_SYSTEM_PROMPT}
|
| 13 |
+
]
|
| 14 |
+
|
| 15 |
+
# Chat interface
|
| 16 |
+
st.write("This is a safe space to discuss your thoughts and feelings. I'm here to listen and support you.")
|
| 17 |
|
| 18 |
# Display chat history
|
| 19 |
+
for message in st.session_state.messages[1:]: # Skip system message
|
| 20 |
with st.chat_message(message["role"]):
|
| 21 |
st.markdown(message["content"])
|
| 22 |
|
| 23 |
# Chat input
|
| 24 |
+
if prompt := st.chat_input("Share what's on your mind..."):
|
| 25 |
# Add user message to chat history
|
| 26 |
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 27 |
|
|
|
|
| 31 |
|
| 32 |
# Generate AI response
|
| 33 |
with st.chat_message("assistant"):
|
| 34 |
+
message_placeholder = st.empty()
|
| 35 |
+
try:
|
| 36 |
+
# Prepare chat context
|
| 37 |
+
chat_context = "\n".join([
|
| 38 |
+
msg["content"] for msg in st.session_state.messages[-5:] # Last 5 messages for context
|
| 39 |
+
])
|
| 40 |
+
|
| 41 |
+
# Generate response using Gemini
|
| 42 |
+
response = generate_response(chat_context, prompt)
|
| 43 |
+
|
| 44 |
+
# Display response
|
| 45 |
+
message_placeholder.markdown(response)
|
| 46 |
+
|
| 47 |
+
# Add AI response to chat history
|
| 48 |
+
st.session_state.messages.append({"role": "assistant", "content": response})
|
| 49 |
+
|
| 50 |
+
except Exception as e:
|
| 51 |
+
error_message = f"I apologize, but I'm having trouble responding right now. Error: {str(e)}"
|
| 52 |
+
message_placeholder.error(error_message)
|
| 53 |
+
st.session_state.messages.append({"role": "assistant", "content": error_message})
|
| 54 |
+
|
| 55 |
+
def generate_response(context, prompt):
|
| 56 |
+
try:
|
| 57 |
+
# Configure Gemini model
|
| 58 |
+
model = genai.GenerativeModel('gemini-pro')
|
| 59 |
+
|
| 60 |
+
# Prepare the prompt with context and MI principles
|
| 61 |
+
full_prompt = f"""
|
| 62 |
+
Context: You are a mental health support AI using Motivational Interviewing principles.
|
| 63 |
+
Previous conversation context: {context}
|
| 64 |
+
|
| 65 |
+
User's message: {prompt}
|
| 66 |
+
|
| 67 |
+
Please provide an empathetic, supportive response that:
|
| 68 |
+
1. Shows empathy and understanding
|
| 69 |
+
2. Uses reflective listening
|
| 70 |
+
3. Encourages self-reflection
|
| 71 |
+
4. Supports autonomy
|
| 72 |
+
5. Avoids direct advice unless specifically requested
|
| 73 |
+
6. Maintains professional boundaries
|
| 74 |
+
|
| 75 |
+
Response:
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
# Generate response
|
| 79 |
+
response = model.generate_content(full_prompt)
|
| 80 |
+
|
| 81 |
+
# Process and return response
|
| 82 |
+
return response.text
|
| 83 |
+
|
| 84 |
+
except Exception as e:
|
| 85 |
+
st.error(f"Error generating response: {str(e)}")
|
| 86 |
+
return "I apologize, but I'm having trouble responding right now. Please try again."
|
| 87 |
+
|
| 88 |
+
def save_chat_history():
|
| 89 |
+
"""Save chat history to file"""
|
| 90 |
+
if len(st.session_state.messages) > 1: # If there are messages besides the system prompt
|
| 91 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 92 |
+
filename = f"chat_history_{timestamp}.txt"
|
| 93 |
+
|
| 94 |
+
try:
|
| 95 |
+
with open(filename, "w", encoding="utf-8") as f:
|
| 96 |
+
for message in st.session_state.messages[1:]: # Skip system message
|
| 97 |
+
f.write(f"{message['role']}: {message['content']}\n\n")
|
| 98 |
+
return filename
|
| 99 |
+
except Exception as e:
|
| 100 |
+
st.error(f"Error saving chat history: {str(e)}")
|
| 101 |
+
return None
|
| 102 |
+
|
| 103 |
+
def load_chat_history(file):
|
| 104 |
+
"""Load chat history from file"""
|
| 105 |
+
try:
|
| 106 |
+
messages = [{"role": "system", "content": USER_SUPPORT_SYSTEM_PROMPT}]
|
| 107 |
+
|
| 108 |
+
with open(file, "r", encoding="utf-8") as f:
|
| 109 |
+
content = f.read().split("\n\n")
|
| 110 |
+
for message in content:
|
| 111 |
+
if message.strip():
|
| 112 |
+
role, content = message.split(": ", 1)
|
| 113 |
+
messages.append({"role": role, "content": content})
|
| 114 |
+
|
| 115 |
+
return messages
|
| 116 |
+
except Exception as e:
|
| 117 |
+
st.error(f"Error loading chat history: {str(e)}")
|
| 118 |
+
return None
|
| 119 |
+
|
| 120 |
+
# Add chat controls
|
| 121 |
+
def show_chat_controls():
|
| 122 |
+
st.sidebar.subheader("Chat Controls")
|
| 123 |
+
|
| 124 |
+
# Save chat history
|
| 125 |
+
if st.sidebar.button("Save Chat History"):
|
| 126 |
+
filename = save_chat_history()
|
| 127 |
+
if filename:
|
| 128 |
+
st.sidebar.success(f"Chat history saved to {filename}")
|
| 129 |
+
|
| 130 |
+
# Load chat history
|
| 131 |
+
uploaded_file = st.sidebar.file_uploader("Load Chat History", type="txt")
|
| 132 |
+
if uploaded_file is not None:
|
| 133 |
+
messages = load_chat_history(uploaded_file)
|
| 134 |
+
if messages:
|
| 135 |
+
st.session_state.messages = messages
|
| 136 |
+
st.sidebar.success("Chat history loaded successfully")
|
| 137 |
+
|
| 138 |
+
# Clear chat
|
| 139 |
+
if st.sidebar.button("Clear Chat"):
|
| 140 |
+
st.session_state.messages = [
|
| 141 |
+
{"role": "system", "content": USER_SUPPORT_SYSTEM_PROMPT}
|
| 142 |
+
]
|
| 143 |
+
st.sidebar.success("Chat cleared")
|
| 144 |
+
|
| 145 |
+
# Add emergency resources
|
| 146 |
+
def show_emergency_resources():
|
| 147 |
+
with st.sidebar.expander("Emergency Resources"):
|
| 148 |
+
st.markdown("""
|
| 149 |
+
If you're experiencing a mental health emergency:
|
| 150 |
+
|
| 151 |
+
🚨 **Emergency Services**: 911
|
| 152 |
+
|
| 153 |
+
🆘 **Crisis Hotlines**:
|
| 154 |
+
- National Suicide Prevention Lifeline: 988
|
| 155 |
+
- Crisis Text Line: Text HOME to 741741
|
| 156 |
+
|
| 157 |
+
🏥 **Other Resources**:
|
| 158 |
+
- SAMHSA's National Helpline: 1-800-662-4357
|
| 159 |
+
- National Alliance on Mental Illness: 1-800-950-6264
|
| 160 |
+
|
| 161 |
+
Remember: If you're having thoughts of self-harm or suicide,
|
| 162 |
+
please seek immediate professional help.
|
| 163 |
+
""")
|
| 164 |
+
|
| 165 |
+
# Add feedback mechanism
|
| 166 |
+
def show_feedback():
|
| 167 |
+
with st.sidebar.expander("Provide Feedback"):
|
| 168 |
+
feedback = st.text_area("How can we improve?")
|
| 169 |
+
if st.button("Submit Feedback"):
|
| 170 |
+
# Add feedback handling logic here
|
| 171 |
+
st.success("Thank you for your feedback!")
|
| 172 |
+
|
| 173 |
+
def show_moti_chat_main():
|
| 174 |
+
show_moti_chat()
|
| 175 |
+
show_chat_controls()
|
| 176 |
+
show_emergency_resources()
|
| 177 |
+
show_feedback()
|