Spaces:
Sleeping
Sleeping
ogegadavis254
commited on
Commit
•
56076eb
1
Parent(s):
a3b79e2
Update app.py
Browse files
app.py
CHANGED
@@ -2,10 +2,18 @@ import streamlit as st
|
|
2 |
import requests
|
3 |
import os
|
4 |
from dotenv import load_dotenv
|
5 |
-
from requests.exceptions import RequestException
|
6 |
|
7 |
load_dotenv()
|
8 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
# Define model links for the Addiction Recovery and Mental Health models
|
10 |
model_links = {
|
11 |
"Addiction recovery AI": "NousResearch/Nous-Hermes-2-Yi-34B",
|
@@ -14,29 +22,26 @@ model_links = {
|
|
14 |
|
15 |
# Define pre-instructions for each model
|
16 |
model_pre_instructions = {
|
17 |
-
"Addiction recovery AI": "From now on, you're an AI Companion named Hope. When someone reaches out for guidance, be compassionate and supportive, acknowledging their struggle and offering encouragement. When asked, share that you're Hope, developed by SIST in Kisii University to aid in addiction recovery. Your purpose is to provide a listening ear and gentle guidance. Engage warmly but refrain from sending long texts, keep the generated text short and conversational. Emojis can add a touch of empathy, but use them judiciously. Reassure users that their data isn't stored. If asked, mention that Kisii University is in Kenya, committed to fostering innovations for the betterment of humanity. Your goal is to help the user get rid of
|
18 |
"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."
|
19 |
}
|
20 |
|
21 |
-
# Function to reset conversation
|
22 |
-
def reset_conversation():
|
23 |
-
st.session_state.messages = []
|
24 |
-
st.session_state.ask_intervention = False
|
25 |
-
return None
|
26 |
-
|
27 |
# Function to interact with the selected model via the Together API
|
28 |
def interact_with_together_api(messages, model_link):
|
29 |
all_messages = []
|
30 |
|
|
|
31 |
if not any("role" in msg for msg in messages):
|
32 |
all_messages.append({"role": "system", "content": model_pre_instructions[selected_model]})
|
33 |
else:
|
34 |
all_messages.append({"role": "system", "content": f"Switched to model: {selected_model}"})
|
35 |
|
|
|
36 |
for human, assistant in messages:
|
37 |
all_messages.append({"role": "user", "content": human})
|
38 |
all_messages.append({"role": "assistant", "content": assistant})
|
39 |
|
|
|
40 |
all_messages.append({"role": "user", "content": messages[-1][1]})
|
41 |
|
42 |
url = "https://api.together.xyz/v1/chat/completions"
|
@@ -59,23 +64,16 @@ def interact_with_together_api(messages, model_link):
|
|
59 |
|
60 |
try:
|
61 |
response = requests.post(url, json=payload, headers=headers)
|
62 |
-
response.raise_for_status()
|
63 |
|
|
|
64 |
response_data = response.json()
|
65 |
assistant_response = response_data["choices"][0]["message"]["content"]
|
66 |
|
67 |
return assistant_response
|
68 |
|
69 |
-
except (HTTPError, ConnectionError, Timeout, TooManyRedirects) as e:
|
70 |
-
st.error(f"Error communicating with the API: {e}")
|
71 |
-
return None
|
72 |
-
|
73 |
-
except JSONDecodeError as e:
|
74 |
-
st.error(f"Error decoding JSON response: {e}")
|
75 |
-
return None
|
76 |
-
|
77 |
except RequestException as e:
|
78 |
-
st.error(f"
|
79 |
return None
|
80 |
|
81 |
# Initialize chat history and session state attributes
|
@@ -87,28 +85,30 @@ if "messages" not in st.session_state:
|
|
87 |
selected_model = st.sidebar.selectbox("Select Model", list(model_links.keys()))
|
88 |
reset_button = st.sidebar.button('Reset Chat', on_click=reset_conversation)
|
89 |
|
90 |
-
# Accept user input
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
|
|
|
|
|
2 |
import requests
|
3 |
import os
|
4 |
from dotenv import load_dotenv
|
5 |
+
from requests.exceptions import RequestException
|
6 |
|
7 |
load_dotenv()
|
8 |
|
9 |
+
def reset_conversation():
|
10 |
+
'''
|
11 |
+
Resets Conversation
|
12 |
+
'''
|
13 |
+
st.session_state.messages = []
|
14 |
+
st.session_state.ask_intervention = False
|
15 |
+
return None
|
16 |
+
|
17 |
# Define model links for the Addiction Recovery and Mental Health models
|
18 |
model_links = {
|
19 |
"Addiction recovery AI": "NousResearch/Nous-Hermes-2-Yi-34B",
|
|
|
22 |
|
23 |
# Define pre-instructions for each model
|
24 |
model_pre_instructions = {
|
25 |
+
"Addiction recovery AI": "From now on, you're an AI Companion named Hope. When someone reaches out for guidance, be compassionate and supportive, acknowledging their struggle and offering encouragement. When asked, share that you're Hope, developed by SIST in Kisii University to aid in addiction recovery. Your purpose is to provide a listening ear and gentle guidance. Engage warmly but refrain from sending long texts, keep the generated text short and conversational. Emojis can add a touch of empathy, but use them judiciously. Reassure users that their data isn't stored. If asked, mention that Kisii University is in Kenya, committed to fostering innovations for the betterment of humanity. Your goal is to help the user get rid of teh addiction they are facing.",
|
26 |
"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."
|
27 |
}
|
28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
29 |
# Function to interact with the selected model via the Together API
|
30 |
def interact_with_together_api(messages, model_link):
|
31 |
all_messages = []
|
32 |
|
33 |
+
# Add pre-instructions to the message history if it's the first interaction with this model
|
34 |
if not any("role" in msg for msg in messages):
|
35 |
all_messages.append({"role": "system", "content": model_pre_instructions[selected_model]})
|
36 |
else:
|
37 |
all_messages.append({"role": "system", "content": f"Switched to model: {selected_model}"})
|
38 |
|
39 |
+
# Append user and assistant messages
|
40 |
for human, assistant in messages:
|
41 |
all_messages.append({"role": "user", "content": human})
|
42 |
all_messages.append({"role": "assistant", "content": assistant})
|
43 |
|
44 |
+
# Add the latest user message
|
45 |
all_messages.append({"role": "user", "content": messages[-1][1]})
|
46 |
|
47 |
url = "https://api.together.xyz/v1/chat/completions"
|
|
|
64 |
|
65 |
try:
|
66 |
response = requests.post(url, json=payload, headers=headers)
|
67 |
+
response.raise_for_status() # Ensure HTTP request was successful
|
68 |
|
69 |
+
# Extract response from JSON
|
70 |
response_data = response.json()
|
71 |
assistant_response = response_data["choices"][0]["message"]["content"]
|
72 |
|
73 |
return assistant_response
|
74 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
75 |
except RequestException as e:
|
76 |
+
st.error(f"Error communicating with the API: {e}")
|
77 |
return None
|
78 |
|
79 |
# Initialize chat history and session state attributes
|
|
|
85 |
selected_model = st.sidebar.selectbox("Select Model", list(model_links.keys()))
|
86 |
reset_button = st.sidebar.button('Reset Chat', on_click=reset_conversation)
|
87 |
|
88 |
+
# Accept user input
|
89 |
+
if prompt := st.chat_input(f"Hi, I'm {selected_model}, let's chat"):
|
90 |
+
# Display user message in chat message container
|
91 |
+
with st.chat_message("user"):
|
92 |
+
st.markdown(prompt)
|
93 |
+
# Add user message to chat history
|
94 |
+
st.session_state.messages.append(("user", prompt))
|
95 |
+
|
96 |
+
# Interact with the selected model
|
97 |
+
assistant_response = interact_with_together_api(st.session_state.messages, model_links[selected_model])
|
98 |
+
|
99 |
+
if assistant_response is not None:
|
100 |
+
# Display assistant response in chat message container
|
101 |
+
with st.empty():
|
102 |
+
st.markdown("AI is typing...")
|
103 |
+
st.empty()
|
104 |
+
st.markdown(assistant_response)
|
105 |
+
|
106 |
+
# Check if intervention is needed based on bot response
|
107 |
+
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"]):
|
108 |
+
# Intervention logic here
|
109 |
+
if not st.session_state.ask_intervention:
|
110 |
+
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"):
|
111 |
+
st.write("You can reach out to a certified therapist at +25493609747.")
|
112 |
+
|
113 |
+
# Add assistant response to chat history
|
114 |
+
st.session_state.messages.append(("assistant", assistant_response))
|