ogegadavis254 commited on
Commit
c0992c4
·
verified ·
1 Parent(s): 3aacb50

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +20 -59
app.py CHANGED
@@ -3,17 +3,9 @@ import requests
3
  import os
4
  from dotenv import load_dotenv
5
  from requests.exceptions import RequestException, HTTPError, ConnectionError, Timeout, TooManyRedirects, JSONDecodeError
6
- from textblob import TextBlob
7
 
8
- # Load environment variables
9
  load_dotenv()
10
 
11
- # Define pre-instructions for each model
12
- model_pre_instructions = {
13
- "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 the addiction they are facing.",
14
- "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."
15
- }
16
-
17
  # Function to reset conversation
18
  def reset_conversation():
19
  st.session_state.messages = []
@@ -74,68 +66,37 @@ def interact_with_together_api(messages, model_link):
74
  st.error(f"RequestException: {e}")
75
  return None
76
 
77
- # Function to perform sentiment analysis on the conversation
78
- def analyze_sentiment(messages):
79
- sentiments = []
80
- for _, message in messages:
81
- blob = TextBlob(message)
82
- sentiment_score = blob.sentiment.polarity
83
- sentiments.append(sentiment_score)
84
-
85
- if sentiments: # Check if sentiments list is not empty
86
- average_sentiment = sum(sentiments) / len(sentiments)
87
- else:
88
- average_sentiment = 0 # Set default sentiment to 0 if no messages are available
89
-
90
- return average_sentiment
91
-
92
  # Initialize chat history and session state attributes
93
  if "messages" not in st.session_state:
94
  st.session_state.messages = []
95
  st.session_state.ask_intervention = False
96
 
97
  # Create sidebar with model selection dropdown and reset button
98
- model_links = {
99
- "Addiction recovery AI": "NousResearch/Nous-Hermes-2-Yi-34B",
100
- "Mental health AI": "NousResearch/Nous-Hermes-2-Yi-34B"
101
- }
102
  selected_model = st.sidebar.selectbox("Select Model", list(model_links.keys()))
103
  reset_button = st.sidebar.button('Reset Chat', on_click=reset_conversation)
104
 
105
  # Accept user input with input validation
106
  max_input_length = 100 # Maximum allowed character limit for user input
107
- if prompt := st.text_input(f"Hi, I'm {selected_model}, let's chat (Max {max_input_length} characters)"):
 
108
  if len(prompt) > max_input_length:
109
  st.error(f"Maximum input length exceeded. Please limit your input to {max_input_length} characters.")
110
  else:
111
- if st.button("Send"):
112
- with st.spinner("Sending..."):
113
- with st.chat_message("user"):
114
- st.markdown(prompt)
115
- st.session_state.messages.append(("user", prompt))
116
-
117
- # Interact with the selected model
118
- assistant_response = interact_with_together_api(st.session_state.messages, model_links[selected_model])
119
-
120
- if assistant_response is not None:
121
- with st.empty():
122
- st.markdown("AI is typing...")
123
- st.empty()
124
- with st.chat_message("assistant"):
125
- st.markdown(assistant_response)
126
-
127
- 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"]):
128
- if not st.session_state.ask_intervention:
129
- if st.button("After the analyzing 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"):
130
- st.write("You can reach out to a certified therapist at +25493609747.")
131
-
132
- st.session_state.messages.append(("assistant", assistant_response))
133
-
134
- # Display conversation insights
135
- st.sidebar.subheader("Conversation Insights")
136
- average_sentiment = analyze_sentiment(st.session_state.messages)
137
- st.sidebar.write(f"Average Sentiment: {average_sentiment}")
138
-
139
- # Add logo and text to the sidebar
140
- st.sidebar.image("https://assets.isu.pub/document-structure/221118065013-a6029cf3d563afaf9b946bb9497d45d4/v1/2841525b232adaef7bd0efe1da81a4c5.jpeg", width=200)
141
- st.sidebar.write("A product proudly developed by Kisii University")
 
3
  import os
4
  from dotenv import load_dotenv
5
  from requests.exceptions import RequestException, HTTPError, ConnectionError, Timeout, TooManyRedirects, JSONDecodeError
 
6
 
 
7
  load_dotenv()
8
 
 
 
 
 
 
 
9
  # Function to reset conversation
10
  def reset_conversation():
11
  st.session_state.messages = []
 
66
  st.error(f"RequestException: {e}")
67
  return None
68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  # Initialize chat history and session state attributes
70
  if "messages" not in st.session_state:
71
  st.session_state.messages = []
72
  st.session_state.ask_intervention = False
73
 
74
  # Create sidebar with model selection dropdown and reset button
 
 
 
 
75
  selected_model = st.sidebar.selectbox("Select Model", list(model_links.keys()))
76
  reset_button = st.sidebar.button('Reset Chat', on_click=reset_conversation)
77
 
78
  # Accept user input with input validation
79
  max_input_length = 100 # Maximum allowed character limit for user input
80
+
81
+ if prompt := st.chat_input(f"Hi, I'm {selected_model}, let's chat (Max {max_input_length} characters)"):
82
  if len(prompt) > max_input_length:
83
  st.error(f"Maximum input length exceeded. Please limit your input to {max_input_length} characters.")
84
  else:
85
+ with st.chat_message("user"):
86
+ st.markdown(prompt)
87
+ st.session_state.messages.append(("user", prompt))
88
+
89
+ assistant_response = interact_with_together_api(st.session_state.messages, model_links[selected_model])
90
+
91
+ if assistant_response is not None:
92
+ with st.empty():
93
+ st.markdown("AI is typing...")
94
+ st.empty()
95
+ st.markdown(assistant_response)
96
+
97
+ 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"]):
98
+ if not st.session_state.ask_intervention:
99
+ if st.button("After the analyzing 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"):
100
+ st.write("You can reach out to a certified therapist at +25493609747.")
101
+
102
+ st.session_state.messages.append(("assistant", assistant_response))