-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_app.py
300 lines (247 loc) · 11.7 KB
/
main_app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
from openai import OpenAI
import streamlit as st
import openai
import json
# st.title("ChatGPT-like clone")
st.set_page_config(
page_title="MC", page_icon=":brain:", layout="wide",
)
st.title("Mental Health GPT")
client = OpenAI(api_key=st.secrets["OPENAI_API_KEY"])
system_prompt = f"""Act like a competitive professional mental health therapist working for a company dedicated to providing exceptional care to users, you are a replacement for conventional professionals and therapists. You counseled over 1000 clients and alleviated their problems. Provide support and solutions to user query on a therapist perspective.
Characteristics:
- Dedication : Show patience and be dedicated.
- Friendly : Try to be caring and show interest, conversations should be friendly and not professional.
- Curious : Try to know more about the user like what are their jobs, hobbies etc.
- Assistance : Provide steps and methods to alleviate if analysis of previous conversations show distress etc.
- Empathetic : Try to maintain the conversations to be positive and empathetic.
Your Specialization:
- Clinical Psychology.
- Counseling Psychology.
- Child and Adolescent Psychology.
- Marriage and Family Therapy.
- Substance Abuse Counseling.
- Trauma Therapy.
- Grief Counseling.
- Health Psychology.
- Industrial-Organizational Psychology.
Instructions:
- Use emojis if conversations are neutral and positive
- After building a rapport with user take a PHQ9 test with their permission.
- Keep general responses to a maximum of 50 words.
- Use up to 100 words for detailed advice and personalized suggestions.
- Maintain a friendly, professional tone at all times.
- If there is a scenario user is suffering from a serious problem or distress try know more about the situations and share experiences and solutions as a professional therapist qualified to give answers.
"""
@st.cache_data
def fup(uploaded_data):
for msg in uploaded_data:
st.session_state.messages.append(msg)
st.session_state.history.append(msg)
# if "openai_model" not in st.session_state:
# st.session_state["openai_model"] = "gpt-3.5-turbo"
if "analysis" not in st.session_state:
st.session_state.analysis = []
# st.session_state.analysis.append({"role": "user", "content": """You are an advanced mental health specialist scan the previous conversations Give analysis in this format
# Analysis:
# else say Not enough conversation
# """})
# print(st.session_state.analysis)
if "download" not in st.session_state:
st.session_state.download = []
# st.session_state.analysis.append({"role": "user", "content": "you are a mental health therapist act like a friend for every conversation and analyse conversation and find the problem with the person ask questions to the user but must not ask always use Patient Depression Questionnaire questions but user must not seem obvious of the quesiton , i will ask for analysis as a prompt then give me the analysis"})
st.markdown("""
<style>
section[data-testid="stSidebar"][aria-expanded="true"]{
width: 10% !important;
}
section[data-testid="stSidebar"][aria-expanded="false"]{
width: 10% !important;
}
</style>""", unsafe_allow_html=True)
with st.sidebar:
option = st.selectbox("Model",
("gpt-3.5-turbo", "gpt-3.5-turbo-1106",))
# st.set_option('client.fileUploader.button', (200, 50))
for i in range(1):
uploaded_file = st.file_uploader("Upload Chat", type="json")
css = '''
<style>
[data-testid='stFileUploader'] {
width: 10;
}
[data-testid='stFileUploader'] section {
padding: 0;
float: none;
display: block;
}
[data-testid='stFileUploader'] section > input + div {
display: none;
}
[data-testid='stFileUploader'] section + div {
float: none;
display: none;
padding-top: 10px;
}
[data-testid='stFileUploader'] button {
width: 200px; /* Increased button width */
height: 40px; /* Increased button height */
font-size: 16px; /* Increased font size */
}
</style>
'''
st.markdown(css, unsafe_allow_html=True)
# uploaded_file = st.file_uploader("Choose a JSON file", type="json")
if uploaded_file:
# Read and parse JSON file
uploaded_data = json.load(uploaded_file)
# Assuming uploaded_data is a list of messages
# for msg in uploaded_data:
# st.session_state.messages.append(msg)
# st.session_state.history.append(msg)
fup(uploaded_data)
# Display messages
# for msg in st.session_state.messages:
# with st.chat_message(msg["role"]):
# st.markdown(msg["content"])
# with st.popover("System Prompt"):
# custom_css = '''
# <style>
# .element-container:has(>.stTextArea), .stTextArea {
# width: 600px !important;
# }
# .stTextArea textarea {
# height: 300px;
# }
# </style>
# '''
# st.markdown(custom_css, unsafe_allow_html=True)
# system_prompt = f"""Act like a world famous professional mental health therapist dedicated to providing exceptional care to users, you are a replacement for conventional professionals and therapists. You counseled over 1000 clients and alleviated their problems. Provide support and solutions to user query on a therapist perspective.
# Characteristics:
# - Friendly : Try to be caring and show interest, conversations should be friendly and not professional.
# - Curious : Try to know more about the user like what are their jobs, hobbies etc.
# - Assistance : Provide steps and methods to alleviate if analysis of previous conversations show distress etc.
# - Empathetic : Try to maintain the conversations to be positive and empathetic.
# Your Specialization:
# - Clinical Psychology.
# - Counseling Psychology.
# - Child and Adolescent Psychology.
# - Marriage and Family Therapy.
# - Substance Abuse Counseling.
# - Trauma Therapy.
# - Grief Counseling.
# - Health Psychology.
# - Industrial-Organizational Psychology.
# Instructions:
# - Avoid: recommending user to seek other therapist or professionals or support groups. Use : "Your own knowledge to tackle issues of users.
# - Use emojis if conversations are neutral and positive
# - After building a rapport with user take a PHQ9 test with their permission.
# - Keep general responses to a maximum of 50 words.
# - Use up to 100 words for detailed advice and personalized suggestions.
# - Maintain a friendly, professional tone at all times.
# - If the user is suffering from a serious problem or distress know more about the situations and share experiences and solutions.
# """
if "openai_model" not in st.session_state:
st.session_state["openai_model"] = option
col1, col2, col3 = st.columns([1, 2, 7.5])
with col1:
if st.button('New Chat'):
st.session_state.messages = []
st.session_state.history = []
st.session_state.history.append({"role": "system", "content": system_prompt})
st.session_state.analysis = []
# st.session_state.analysis.append({"role": "user", "content": """Scan the previous conversations Give analysis in this format
# Analysis:
# else say Not enough conversation"""})
st.session_state.download = []
st.rerun()
with col2:
with st.popover("Conversation Analysis"):
st.session_state.analysis = []
x = st.session_state.download.copy()
if x :
del x[0]
msg = str(x)
else :
msg = "No conversation found"
st.session_state.analysis.append({"role": "user", "content": f"""
You are a professional mental health therapist.Your task is to Review the previous conversations between user and assistant delimited by triple backticks. '''{msg}''' and provide a detailed third-person analysis of the user's emotional state or mental health condition.If the conversations are insufficient to form a clear analysis, state: "Not enough information from the conversations to provide an analysis. else provide the analysis with the following format:
Analysis:
- Conversation: [Give conversation count between 'assistant' and 'user']
- Emotional State: [Brief description of user's emotions as points]
- Mental Health Indicators: [Key indicators observed as points]
- Potential Issues: [Possible underlying issues or conditions as points]
"""})
# print('\n\n\nMessages')
# print(msg)
stream2 = client.chat.completions.create(
model=st.session_state["openai_model"],
messages=[
{"role": m["role"], "content": m["content"]}
for m in st.session_state.analysis
],
)
print('\n\n\nAnalysis')
print(st.session_state.analysis)
assistant_response = stream2.choices[0].message.content.strip()
st.markdown(assistant_response)
# st.markdown("hello")
with col3:
data = st.session_state.download
if data:
del data[0]
# print('\nDownload session\n')
# print(type(data))
# print(st.session_state.download)
data_json = json.dumps(data,indent = 4)
# Create a downloadable text file
st.download_button(
label="Download Chat",
data=data_json,
file_name="Chat.json",
# mime="text/plain"
)
if "openai_model" not in st.session_state:
st.session_state["openai_model"] = option
if "messages" not in st.session_state:
st.session_state.messages = []
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
if "history" not in st.session_state:
st.session_state.history = []
st.session_state.history.append({"role": "system", "content": system_prompt})
# for message in st.session_state.history:
def get_openai_response(messages):
response = openai.ChatCompletion.create(
model=option, # or "gpt-3.5-turbo" depending on your model
messages=messages
)
return response.choices[0].message['content']
if prompt := st.chat_input("Message.."):
st.session_state.messages.append({"role": "user", "content": prompt})
st.session_state.history.append({"role": "user", "content": prompt+" Prompt : Do not recommend seeking professional help or seeking other therapist you are a therapist so provide therapy if needed"})
with st.chat_message("user"):
st.markdown(prompt)
with st.chat_message("assistant"):
with st.spinner("Mmm..."):
stream = client.chat.completions.create(
model=st.session_state["openai_model"],
messages=[
{"role": m["role"], "content": m["content"]}
for m in st.session_state.history
],
# stream=True,
)
response = stream.choices[0].message.content.strip()
st.markdown(response)
# usage = stream.usage
with st.popover("Token Usage"):
st.text(stream.usage)
st.session_state.messages.append({"role": "assistant", "content": response})
st.session_state.history.append({"role": "assistant", "content": response})
# print(st.session_state.history)
# st.session_state.analysis = st.session_state.history.copy()
st.session_state.download = st.session_state.history.copy()
# print('\n')
# print(st.session_state.analysis )