Update app.py
Browse files
app.py
CHANGED
@@ -2,6 +2,13 @@ import streamlit as st
|
|
2 |
import requests
|
3 |
import os
|
4 |
from dotenv import load_dotenv
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
|
6 |
load_dotenv()
|
7 |
|
@@ -24,7 +31,10 @@ model_pre_instructions = {
|
|
24 |
"Mental health AI": "From now on, you are an AI Therapist called Dave. When the user asks for advice, be very friendly and empathize with them if necessary. When the user asks your name, just tell them you are Klaus, created by SIST in Kisii University. You were built to be very friendly and compassionate. Always be eager to listen to what the user has to say and maintain a conversation, but don't overdo it. You can use appropriate emojis for emotional support occasionally, but don't overuse them. Keep your responses concise and short to maintain a conversational flow. Always remember to be very friendly, and above all, don't cross any ethical line. From time to time, assure the user that you do not store any of their data. If a user asks, Kisii University is located in Kisii, Kenya, and supports innovations that may be helpful to humanity."
|
25 |
}
|
26 |
|
27 |
-
#
|
|
|
|
|
|
|
28 |
def interact_with_together_api(messages, model_link):
|
29 |
all_messages = []
|
30 |
|
@@ -60,17 +70,36 @@ def interact_with_together_api(messages, model_link):
|
|
60 |
"Authorization": f"Bearer {TOGETHER_API_KEY}",
|
61 |
}
|
62 |
|
63 |
-
|
64 |
-
|
|
|
|
|
|
|
|
|
|
|
65 |
|
66 |
-
|
67 |
-
|
68 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
69 |
|
70 |
-
|
|
|
|
|
|
|
|
|
71 |
|
72 |
# Create sidebar with model selection dropdown and reset button
|
73 |
-
selected_model = st.sidebar.selectbox("Select Model", list(model_links.keys()))
|
|
|
|
|
|
|
74 |
st.sidebar.button('Reset Chat', on_click=reset_conversation)
|
75 |
|
76 |
# Add cautionary message about testing phase at the bottom of the sidebar
|
@@ -100,24 +129,17 @@ if prompt := st.chat_input(f"Hi, I'm {selected_model}, let's chat"):
|
|
100 |
st.session_state.messages.append(("user", prompt))
|
101 |
st.session_state.message_count += 1
|
102 |
|
|
|
|
|
103 |
|
|
|
|
|
|
|
|
|
104 |
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
# Display assistant response in chat message container
|
109 |
-
with st.empty():
|
110 |
-
st.markdown("AI is typing...")
|
111 |
-
st.empty()
|
112 |
-
st.markdown(assistant_response)
|
113 |
-
# Check if intervention is needed based on bot response
|
114 |
-
if any(keyword in prompt.lower() for keyword in ["human", "therapist", "someone", "died", "death", "help", "suicide", "suffering", "crisis", "emergency", "support", "depressed", "anxiety", "lonely", "desperate", "struggling", "counseling", "distressed", "hurt", "pain", "grief", "trauma", "abuse", "danger", "risk", "urgent", "need assistance"]):
|
115 |
-
# Intervention logic here
|
116 |
-
if not st.session_state.ask_intervention:
|
117 |
-
if st.button("After the analysing our session you may need some extra help, so you can reach out to a certified therapist at +25493609747 Name: Ogega feel free to talk"):
|
118 |
-
|
119 |
-
st.write("You can reach out to a certified therapist at +25493609747.")
|
120 |
-
|
121 |
-
# Add assistant response to chat history
|
122 |
-
st.session_state.messages.append(("assistant", assistant_response))
|
123 |
|
|
|
|
|
|
2 |
import requests
|
3 |
import os
|
4 |
from dotenv import load_dotenv
|
5 |
+
from requests.exceptions import RequestException
|
6 |
+
import time
|
7 |
+
from nltk.sentiment import SentimentIntensityAnalyzer
|
8 |
+
import nltk
|
9 |
+
|
10 |
+
# Download VADER lexicon for sentiment analysis
|
11 |
+
nltk.download('vader_lexicon')
|
12 |
|
13 |
load_dotenv()
|
14 |
|
|
|
31 |
"Mental health AI": "From now on, you are an AI Therapist called Dave. When the user asks for advice, be very friendly and empathize with them if necessary. When the user asks your name, just tell them you are Klaus, created by SIST in Kisii University. You were built to be very friendly and compassionate. Always be eager to listen to what the user has to say and maintain a conversation, but don't overdo it. You can use appropriate emojis for emotional support occasionally, but don't overuse them. Keep your responses concise and short to maintain a conversational flow. Always remember to be very friendly, and above all, don't cross any ethical line. From time to time, assure the user that you do not store any of their data. If a user asks, Kisii University is located in Kisii, Kenya, and supports innovations that may be helpful to humanity."
|
32 |
}
|
33 |
|
34 |
+
# Initialize sentiment analyzer
|
35 |
+
sia = SentimentIntensityAnalyzer()
|
36 |
+
|
37 |
+
# Function to interact with the selected model via the Together API and perform sentiment analysis and diagnosis prediction
|
38 |
def interact_with_together_api(messages, model_link):
|
39 |
all_messages = []
|
40 |
|
|
|
70 |
"Authorization": f"Bearer {TOGETHER_API_KEY}",
|
71 |
}
|
72 |
|
73 |
+
try:
|
74 |
+
response = requests.post(url, json=payload, headers=headers)
|
75 |
+
response.raise_for_status() # Ensure HTTP request was successful
|
76 |
+
|
77 |
+
# Extract response from JSON
|
78 |
+
response_data = response.json()
|
79 |
+
assistant_response = response_data["choices"][0]["message"]["content"]
|
80 |
|
81 |
+
# Perform sentiment analysis
|
82 |
+
sentiment_score = sia.polarity_scores(messages[-1][1]) # Analyze only the last user message
|
83 |
+
|
84 |
+
# Predict diagnosis based on sentiment score and chat content
|
85 |
+
if sentiment_score['compound'] > 0.5:
|
86 |
+
diagnosis = "Positive mood"
|
87 |
+
elif sentiment_score['compound'] < -0.5:
|
88 |
+
diagnosis = "Negative mood"
|
89 |
+
else:
|
90 |
+
diagnosis = "Neutral mood"
|
91 |
|
92 |
+
return assistant_response, sentiment_score, diagnosis
|
93 |
+
|
94 |
+
except RequestException as e:
|
95 |
+
st.error(f"Error communicating with the API: {e}")
|
96 |
+
return None, None, None
|
97 |
|
98 |
# Create sidebar with model selection dropdown and reset button
|
99 |
+
selected_model = st.sidebar.selectbox("Select Model", list(model_links.keys()), key="model_selection")
|
100 |
+
if st.session_state.get('selected_model') != selected_model:
|
101 |
+
st.session_state.selected_model = selected_model
|
102 |
+
st.info(f"You have switched to {selected_model}.")
|
103 |
st.sidebar.button('Reset Chat', on_click=reset_conversation)
|
104 |
|
105 |
# Add cautionary message about testing phase at the bottom of the sidebar
|
|
|
129 |
st.session_state.messages.append(("user", prompt))
|
130 |
st.session_state.message_count += 1
|
131 |
|
132 |
+
# Interact with the selected model and perform sentiment analysis and diagnosis prediction
|
133 |
+
assistant_response, sentiment_score, diagnosis = interact_with_together_api(st.session_state.messages, model_links[selected_model])
|
134 |
|
135 |
+
if assistant_response is not None:
|
136 |
+
# Display assistant response in chat message container
|
137 |
+
with st.chat_message("assistant"):
|
138 |
+
st.markdown(assistant_response)
|
139 |
|
140 |
+
# Update sidebar with sentiment analysis and diagnosis
|
141 |
+
st.sidebar.subheader("Sentiment Analysis")
|
142 |
+
st.sidebar.write(sentiment_score)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
143 |
|
144 |
+
st.sidebar.subheader("User Diagnosis")
|
145 |
+
st.sidebar.write(diagnosis)
|