innawy commited on
Commit
1e506d2
·
1 Parent(s): 07cf349
all_strategy_with_generated_reason.csv ADDED
The diff for this file is too large to render. See raw diff
 
app.py ADDED
@@ -0,0 +1,1109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import openai
2
+ import os
3
+ import time
4
+ import datetime
5
+ import string
6
+ import random
7
+ import numpy as np
8
+ import pandas as pd
9
+ import codecs
10
+ import gradio as gr
11
+ print (gr.__version__)
12
+ import re
13
+ import psycopg2
14
+ from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
15
+ from feedback_generation_function import *
16
+ # import boto3
17
+
18
+
19
+ print ("finished import")
20
+ pre_load_situations = pd.read_csv('mturk_id_situation_goal_difficulty.csv')
21
+
22
+ MODEL_NAME = 'gpt-3.5-turbo-0613' # GPT 4 alternative: 'gpt-4-0613'
23
+
24
+ AWS_REGION = "us-east-2"
25
+ DB_INSTANCE_IDENTIFIER = "chat-annotation"
26
+ DB_USER = "ilin"
27
+ DB_PASSWORD = os.environ["DB_PASSWORD"]
28
+ DB_ENDPOINT = os.environ["DB_ENDPOINT"]
29
+ DB_PORT = 8080
30
+ DB_NAME = "postgres"
31
+ openai.api_key = os.environ["OPENAI_API_KEY"]
32
+
33
+ TABLE_NAME = "annotations" #TODO: change this table name
34
+
35
+ css = """
36
+
37
+ #chuanhu_chatbot {
38
+ height: 100%;
39
+ min-height: 400px;
40
+ }
41
+
42
+ body {
43
+ font-family: 'Times', serif;
44
+ }
45
+
46
+ [class *= "message"] {
47
+ border-radius: var(--radius-xl) !important;
48
+ border: none;
49
+ padding: var(--spacing-xl) !important;
50
+ font-size: var(--text-md) !important;
51
+ line-height: var(--line-md) !important;
52
+ min-height: calc(var(--text-md)*var(--line-md) + 2*var(--spacing-xl));
53
+ min-width: calc(var(--text-md)*var(--line-md) + 2*var(--spacing-xl));
54
+ }
55
+ [data-testid = "bot"] {
56
+ max-width: 67%;
57
+ border-bottom-left-radius: 0 !important;
58
+ }
59
+ [data-testid = "user"] {
60
+ max-width: 67%;
61
+ width: auto !important;
62
+ border-bottom-right-radius: 0 !important;
63
+ }
64
+
65
+ #emp {
66
+ color: #8A2BE2;
67
+ font-weight:bold;
68
+
69
+ }
70
+
71
+ #step {
72
+ background-color: #8A2BE2;
73
+ border-radius: 5px;
74
+ padding: 8px;
75
+ font-weight:bold;
76
+ color: white;}
77
+ """
78
+
79
+ # user_ID = "test_user" # id of the annotator
80
+
81
+ # Establish connection to RDS instance
82
+ try:
83
+ conn = psycopg2.connect(host=DB_ENDPOINT, port=DB_PORT, dbname=DB_NAME, user=DB_USER, password=DB_PASSWORD)
84
+ except Exception as e:
85
+ print (e)
86
+
87
+ # Check if "annotations" table exists, if not, set up the table
88
+ table_check_query = """
89
+ SELECT EXISTS (
90
+ SELECT FROM information_schema.tables
91
+ WHERE table_name = '""" + TABLE_NAME + """'
92
+ );
93
+ """
94
+
95
+ with conn.cursor() as cursor:
96
+ cursor.execute(table_check_query)
97
+ table_exists = cursor.fetchone()[0]
98
+ print ("table exists? ", table_exists)
99
+
100
+ if not table_exists:
101
+ column_defs = [
102
+ "user_id varchar(255)",
103
+ "action varchar(255)",
104
+ "content text",
105
+ "timestamp timestamp",
106
+ ]
107
+
108
+ formatted_column_defs = ", ".join(column_defs)
109
+
110
+ create_table_query = f"CREATE TABLE {TABLE_NAME} (id serial PRIMARY KEY, {formatted_column_defs});"
111
+
112
+ with conn.cursor() as cur:
113
+ cur.execute(create_table_query)
114
+ conn.commit()
115
+
116
+ conn.close()
117
+
118
+ print ("table is ready")
119
+
120
+
121
+ # Gradio Demo starts here
122
+
123
+
124
+
125
+ LIST_OF_DEARMAN_DIMENSIONS = ['describe', 'express','assert','reinforce','mindful','confident','negotiate']
126
+ LIST_OF_NVC_DIMENSIONS = ['observations','feelings','needs','requests','empathy','self-empathy']
127
+
128
+ def generate_system_input_few_shot(user_id, user_character_input, user_input,user_situation_category):
129
+
130
+ MAX_RETRIES = 5
131
+ current_tries = 1
132
+
133
+ few_shot_learning_prompt = "Character: My husband \n Situation: My husband always comes home late and he doesn't text me or call me. \n Prompt: Act like my husband who always comes home late without calling or texting me. \n Character: My boss \nPrompt: Act like my boss who regularly calls me on weekends but I don't want to work on the weekends. \n Character: My friend \n Situation: My friend has depression and she relies on me 24/7 and I feel drained \nPrompt: Act like my friend who has depression and who relies on me whenever you have an issue and I want to convince you to seek professional help and not rely on a friend for all your issues. \nCharacter: My neighbor \n Situation: My neighbor frequently plays loud music at a late hour and hosts big parties, which affect my sleep. \nPrompt: Act like my neighbor. You frequently play loud music at a late hour and host big parties. \nCharacter: A customer service agent \n Situation: The airline lost my luggage and the customer service agents have been passing the buck \nPrompt: Act like a customer service agent. Your airline lost my luggage and your colleagues have been passing the buck. \n"
134
+
135
+ if user_character_input == '' or user_input == '' or user_situation_category == []:
136
+ curr_response_str = ""
137
+ prompt_error_message = "Please make sure to fill in all fields."
138
+ else:
139
+ prompt_error_message = ""
140
+ prompt_character = "Character: " + user_character_input + " \n"
141
+ # prompt_personality = "Personality: " + user_personality_input + " \n"
142
+ prompt_situation = "Situation: " + user_input + " \n"
143
+ # prompt_goal = "Goal: " + user_goal_input + " \n"
144
+
145
+ prompt = [{"role":"system", "content":"few-shot learning."}, {"role":"user", "content": few_shot_learning_prompt+prompt_character + prompt_situation +"Prompt:"}]
146
+ while current_tries <= MAX_RETRIES:
147
+ try:
148
+ response = openai.ChatCompletion.create(
149
+ model=MODEL_NAME,
150
+ messages = prompt,
151
+ max_tokens = 256
152
+ )
153
+ print (prompt)
154
+
155
+ break
156
+ except Exception as e:
157
+ print('error: ', str(e))
158
+ print('response retrying')
159
+ current_tries += 1
160
+ if current_tries > MAX_RETRIES:
161
+ break
162
+ time.sleep(5)
163
+
164
+ curr_response_str = response['choices'][0]['message']['content'].replace('\n', ' ').strip()
165
+ print(curr_response_str)
166
+
167
+ record_chat_message(user_id, "user_input_context", user_input)
168
+ record_chat_message(user_id, "system_prompt_context", curr_response_str)
169
+
170
+ return curr_response_str, prompt_error_message
171
+
172
+ def generate_system_input_few_shot_and_confirm(user_id, user_character_input, user_input,user_situation_category):
173
+
174
+ MAX_RETRIES = 5
175
+ current_tries = 1
176
+
177
+ few_shot_learning_prompt = "Character: My husband \n Situation: My husband always comes home late and he doesn't text me or call me. \n Prompt: Act like my husband who always comes home late without calling or texting me. \n Character: My boss \nPrompt: Act like my boss who regularly calls me on weekends but I don't want to work on the weekends. \n Character: My friend \n Situation: My friend has depression and she relies on me 24/7 and I feel drained \nPrompt: Act like my friend who has depression and who relies on me whenever you have an issue and I want to convince you to seek professional help and not rely on a friend for all your issues. \nCharacter: My neighbor \n Situation: My neighbor frequently plays loud music at a late hour and hosts big parties, which affect my sleep. \nPrompt: Act like my neighbor. You frequently play loud music at a late hour and host big parties. \nCharacter: A customer service agent \n Situation: The airline lost my luggage and the customer service agents have been passing the buck \nPrompt: Act like a customer service agent. Your airline lost my luggage and your colleagues have been passing the buck. \n"
178
+
179
+ if user_character_input == '' or user_input == '' or user_situation_category == []:
180
+ curr_response_str = ""
181
+ prompt_error_message = "Please make sure to fill in all fields."
182
+ else:
183
+ prompt_error_message = ""
184
+ prompt_character = "Character: " + user_character_input + " \n"
185
+ # prompt_personality = "Personality: " + user_personality_input + " \n"
186
+ prompt_situation = "Situation: " + user_input + " \n"
187
+ # prompt_goal = "Goal: " + user_goal_input + " \n"
188
+
189
+ prompt = [{"role":"system", "content":"few-shot learning."}, {"role":"user", "content": few_shot_learning_prompt+prompt_character + prompt_situation +"Prompt:"}]
190
+ while current_tries <= MAX_RETRIES:
191
+ try:
192
+ response = openai.ChatCompletion.create(
193
+ model=MODEL_NAME,
194
+ messages = prompt,
195
+ max_tokens = 256
196
+ )
197
+ print (prompt)
198
+
199
+ break
200
+ except Exception as e:
201
+ print('error: ', str(e))
202
+ print('response retrying')
203
+ current_tries += 1
204
+ if current_tries > MAX_RETRIES:
205
+ break
206
+ time.sleep(5)
207
+
208
+ curr_response_str = response['choices'][0]['message']['content'].replace('\n', ' ').strip()
209
+ print(curr_response_str)
210
+
211
+ record_chat_message(user_id, "user_input_context", user_input)
212
+ record_chat_message(user_id, "system_prompt_context", curr_response_str)
213
+
214
+ return curr_response_str, prompt_error_message, gr.update(visible=True)
215
+
216
+ def generate_system_input_situation_only(user_id, user_input, situation_num): # situation_num should be situation1 or situation2, or situation_given
217
+
218
+ MAX_RETRIES = 5
219
+ current_tries = 1
220
+
221
+ few_shot_learning_prompt = "Situation: My husband always comes home late and he doesn't text me or call me.\nPrompt: Act like my husband who always comes home late without calling or texting me.\nPrompt: Act like my boss who regularly calls me on weekends but I don't want to work on the weekends.\n Situation: My friend has depression and she relies on me 24/7 and I feel drained\nPrompt: Act like my friend who has depression and who relies on me whenever you have an issue and I want to convince you to seek professional help and not rely on a friend for all your issues.\nSituation: My neighbor frequently plays loud music at a late hour and hosts big parties, which affect my sleep.\nPrompt: Act like my neighbor. You frequently play loud music at a late hour and host big parties.\nSituation: The airline lost my luggage and the customer service agents have been passing the buck \nPrompt: Act like a customer service agent. Your airline lost my luggage and your colleagues have been passing the buck.\n"
222
+
223
+ if user_input == '':
224
+ curr_response_str = ""
225
+ prompt_error_message = "Input not loading properly"
226
+ else:
227
+ prompt_error_message = ""
228
+ # prompt_character = "Character: " + user_character_input + " \n"
229
+ # prompt_personality = "Personality: " + user_personality_input + " \n"
230
+ prompt_situation = "Situation: " + user_input + " \n"
231
+ # prompt_goal = "Goal: " + user_goal_input + " \n"
232
+
233
+ prompt = [{"role":"system", "content":"few-shot learning."}, {"role":"user", "content": few_shot_learning_prompt+ prompt_situation +"Prompt:"}]
234
+ while current_tries <= MAX_RETRIES:
235
+ try:
236
+ response = openai.ChatCompletion.create(
237
+ model=MODEL_NAME,
238
+ messages = prompt,
239
+ max_tokens = 256
240
+ )
241
+ print (prompt)
242
+
243
+ break
244
+ except Exception as e:
245
+ print('error: ', str(e))
246
+ print('response retrying')
247
+ current_tries += 1
248
+ if current_tries > MAX_RETRIES:
249
+ break
250
+ time.sleep(5)
251
+
252
+ curr_response_str = response['choices'][0]['message']['content'].replace('\n', ' ').strip()
253
+ print(curr_response_str)
254
+
255
+ # record_chat_message(user_id, "user_input_context", user_input) # this info should already been recorded
256
+ record_chat_message(user_id, f"system_prompt_context_{situation_num}", curr_response_str)
257
+
258
+ return curr_response_str
259
+
260
+ def predict(user_id, strategy_selection, new_input, input_history, system_input_core, convo_num, display):
261
+
262
+ if strategy_selection == []:
263
+ message_error_message = '<span style="color: red;">Please select at least one strategy! </span>'
264
+ return display, input_history, new_input, '', gr.update(visible=False), message_error_message, strategy_selection
265
+ elif new_input == '' or len(new_input.split()) < 5:
266
+ message_error_message = '<span style="color: red;">Please write a sentence that contains at least five words! </span>'
267
+ return display, input_history, new_input, '', gr.update(visible=False), message_error_message, strategy_selection
268
+ else:
269
+ message_error_message = ""
270
+ system_input = system_input_core + " Engage in a conversation where you are difficult to convince. Keep the message length below 50 words, or similar to the lengths of my messages."
271
+
272
+ MAX_RETRIES = 5
273
+ current_tries = 1
274
+ print (input_history, type(input_history))
275
+ if input_history == None or type(input_history)==type(gr.State([])):
276
+ input_history = []
277
+ if input_history == []:
278
+ prompt = [{"role":"system", "content": system_input},
279
+ {"role":"user", "content": new_input}]
280
+ else:
281
+ prompt = [{"role":"system", "content": system_input}] + input_history + [{"role":"user", "content":new_input}]
282
+
283
+ while current_tries <= MAX_RETRIES:
284
+ try:
285
+ response = openai.ChatCompletion.create(
286
+ model=MODEL_NAME,
287
+ messages = prompt,
288
+ max_tokens = 128
289
+ )
290
+ print (prompt)
291
+
292
+ break
293
+ except Exception as e:
294
+ print('error: ', str(e))
295
+ print('response retrying')
296
+ current_tries += 1
297
+ if current_tries > MAX_RETRIES:
298
+ break
299
+ time.sleep(5)
300
+
301
+ curr_response_str = response['choices'][0]['message']['content'].replace('\n', ' ').strip()
302
+
303
+ if input_history == []:
304
+ input_history = [{"role":"user", "content":new_input}]
305
+ else:
306
+ input_history.append({"role":"user", "content":new_input})
307
+ input_history.append({"role": "assistant", "content": curr_response_str})
308
+
309
+ print ("function finished")
310
+
311
+ responses = [(input_history[i]["content"], input_history[i+1]["content"]) for i in range(0, len(input_history)-1, 2)] # MUST return tuples of list
312
+
313
+ record_chat_message(user_id, f"user_strategy_selection_{convo_num}", strategy_selection)
314
+ record_chat_message(user_id, f"user_message_{convo_num}", new_input)
315
+ record_chat_message(user_id, f"agent_message_{convo_num}", curr_response_str)
316
+
317
+ # strategy_selection.update(options=[])
318
+
319
+ turn_count = count_client_message(input_history)
320
+
321
+ if turn_count >= 2: # TODO: update turn count
322
+ return responses, input_history, '', '', gr.update(visible=True), '', [] #all_dimension_output
323
+
324
+ return responses, input_history, '', '', gr.update(visible=False), '', [] #all_dimension_output
325
+
326
+ def count_client_message(input_history):
327
+ c = 0
328
+ for i in range(len(input_history)):
329
+ if input_history[i]["role"] == "user":
330
+ c += 1
331
+ else:
332
+ continue
333
+
334
+ return c
335
+
336
+ def evaluate_dearman(model_name, situation, statement, dimension):
337
+ systems_all_dimensions = {
338
+ 'describe':'In the given situation, does the statement "describe" the current interaction between the people in the conversation? To be considered "describe", the client needs to stick to the facts, make no judgmental statements, and be objective. Answer immediately in "Yes" or "No" without other words, then give a brief explanation. If the answer is "No", provide a better statement that describe the current interaction.',
339
+
340
+ 'express': 'In the given situation, is the statement an "expression" of feelings or opinions about the interaction? To be considered an "expression", the client needs to express clearly how they feel or what they believe about the situation. For instance, give a brief rationale for a request or for saying no. Answer immediately in "Yes" or "No" without other words, then give a brief explanation. If the answer is "No", provide a better statement that is an expression of feelings or opinions.',
341
+
342
+ 'assert': 'In the given situation, does the client "assert" wishes in the statement? To be considered "assert", the client needs to ask for what they want or say no clearly. The client cannot be beating around the bush, never really asking or saying no. The client cannot be telling the other person what they "should" do. The statement needs to be clear, concise, and assertive. Answer immediately in "Yes" or "No" without other words, then give a brief explanation. If the answer is "No", provide a better statement that assert the client\'s wishes.',
343
+
344
+ 'reinforce': 'In the given situation, does the client "reinforce" the other person? To be considered "reinforce", the client needs to identify something positive or rewarding that would happen for the other person if they give the response the client wants. Alternatively, the client could offer to do something for the other person, if the other person does this thing for them. At a minimum, the client can express appreciation after the other person does something consistent with their request. Answer immediately in "Yes" or "No" without other words, then give a brief explanation.If the answer is "No", provide a better statement that reinforce the other person that there are something positive or rewarding if they agree.',
345
+
346
+ 'mindful': 'In the given situation, is the client being "mindful" by making the statement? To be considered to stay mindful, the client needs to maintain their position and avoid being distracted onto another topic. The client can keep asking, saying no, or expressing their opinion over and over. Or if the other person attacks, threatens, or tries to change the subject, the client should ignore them and not take the bait. Answer immediately in "Yes" or "No" without other words, then give a brief explanation. If the answer is "No", provide a better statement that is more mindful.',
347
+
348
+ 'confident': 'In the given situation, does the client appear "confident" by making the statement? To be considered confident, the client needs to use a confident tone. The client should not retreat, say they are not sure, or the like. Answer immediately in "Yes" or "No" without other words, then give a brief explanation. If the answer is "No", provide a more confident statement.',
349
+
350
+ 'negotiate': 'In the given situation, is the client "negotiating"? To be considered to be "negotiating", the client needs to be offering and asking for alternative solutions to the problem. They can reduce their request, maintain their ask but offer to do something else or solve the problem another way. Answer immediately in "Yes" or "No" without other words, then give a brief explanation. If the answer is "No", provide a better statement that involves negotiation of the current problem.'
351
+ }
352
+
353
+ system_input = systems_all_dimensions[dimension]
354
+ new_input = "Situation: " + situation + "\nStatement: " + statement
355
+
356
+ # consider adding a few examples for few-shot
357
+
358
+ prompt = [{"role":"system", "content": system_input},
359
+ {"role":"user", "content": new_input}]
360
+
361
+ MAX_RETRIES = 5
362
+ current_tries = 1
363
+ while current_tries <= MAX_RETRIES:
364
+ try:
365
+ response = openai.ChatCompletion.create(
366
+ model=MODEL_NAME,
367
+ messages = prompt
368
+ )
369
+ print (prompt)
370
+
371
+ break
372
+ except Exception as e:
373
+ print('error: ', str(e))
374
+ print('response retrying')
375
+ current_tries += 1
376
+ if current_tries > MAX_RETRIES:
377
+ break
378
+ time.sleep(5)
379
+ # print (response)
380
+ curr_response_str = response['choices'][0]['message']['content'].replace('\n', ' ').strip()
381
+ print (curr_response_str)
382
+ if curr_response_str[:3] == 'Yes':
383
+ print (dimension)
384
+ dimension_explain = curr_response_str[5:]
385
+ return True, curr_response_str
386
+ elif curr_response_str[:2] == 'No':
387
+ print ('not ' + dimension)
388
+ dimension_explain = curr_response_str[4:]
389
+ return False, curr_response_str
390
+ return None, curr_response_str
391
+
392
+ def record_user_login(ts):
393
+ # print (user)
394
+ # generate random user id
395
+ generated_user_id = ''.join(random.choices(string.ascii_uppercase + string.digits, k = 6))
396
+ print (generated_user_id)
397
+ conn = psycopg2.connect(host=DB_ENDPOINT, port=DB_PORT, dbname=DB_NAME, user=DB_USER, password=DB_PASSWORD)
398
+ log_in_query = f"""
399
+ INSERT INTO {TABLE_NAME} (user_id, action, content, timestamp)
400
+ VALUES (%s, %s, %s, %s);"""
401
+ ts = datetime.datetime.now()
402
+ data_for_query = (generated_user_id, "log_in", "", ts)
403
+
404
+ with conn.cursor() as cur:
405
+ cur.execute(log_in_query, data_for_query)
406
+
407
+ conn.commit()
408
+ conn.close()
409
+
410
+ return generated_user_id
411
+
412
+ def record_chat_message(user, action_type, message): #action_type: chatbot_message or user_message
413
+ print ("###### recording a message to database: {} ######".format(message))
414
+ ts = datetime.datetime.now()
415
+ conn = psycopg2.connect(host=DB_ENDPOINT, port=DB_PORT, dbname=DB_NAME, user=DB_USER, password=DB_PASSWORD)
416
+ query = f"""
417
+ INSERT INTO {TABLE_NAME} (user_id, action, content, timestamp)
418
+ VALUES (%s, %s, %s, %s);"""
419
+ ts = datetime.datetime.now()
420
+ data_for_query = (user, action_type, message, ts)
421
+
422
+ with conn.cursor() as cur:
423
+ cur.execute(query, data_for_query)
424
+
425
+ conn.commit()
426
+ conn.close()
427
+
428
+ def confirm_system_prompt(user_id, prompt):
429
+ if prompt == '':
430
+ system_prompt_error = 'Please fill in all fields, click on "Process information to generate instruction for the AI model" button, and confirm the instruction, in order to proceed.'
431
+ return gr.update(visible=False), system_prompt_error
432
+ else:
433
+ record_chat_message(user_id, "system_prompt_confirmed", prompt)
434
+ system_prompt_error = ''
435
+ return gr.update(visible=True), system_prompt_error
436
+
437
+ def check_consent_and_start(user_id, consent_check):
438
+ if not consent_check:
439
+ return '<span style="color: red;"> You must check the box above to continue.</span>', gr.update(visible=True), gr.update(visible=False)
440
+ else:
441
+ record_chat_message(user_id, "consent_and_start", "")
442
+ return '', gr.update(visible=False), gr.update(visible=True)
443
+
444
+ def refresh_state():
445
+ return gr.State(), gr.update(visible=False), gr.update(visible=False)
446
+
447
+ def auth(mturk_id):
448
+ if mturk_id == "":
449
+ return '<span style="color: red;"> Please enter your mTurk ID you used to complete the Qualification Task. If you think this is a mistake, please reach out to Inna at ilin@cs.washington.edu. </span>', gr.update(visible=False), gr.update(visible=True), "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""
450
+ elif mturk_id in pre_load_situations['id'].values:
451
+
452
+ row_index = pre_load_situations[pre_load_situations['id']==mturk_id].index[0]
453
+ situation1 = pre_load_situations.loc[row_index]['situation1']
454
+ goal1 = pre_load_situations.loc[row_index]['goal1']
455
+ difficulty1 = pre_load_situations.loc[row_index]['difficulty1']
456
+ situation2 = pre_load_situations.loc[row_index]['situation2']
457
+ goal2 = pre_load_situations.loc[row_index]['goal2']
458
+ difficulty2 = pre_load_situations.loc[row_index]['difficulty2']
459
+
460
+ conn = psycopg2.connect(host=DB_ENDPOINT, port=DB_PORT, dbname=DB_NAME, user=DB_USER, password=DB_PASSWORD)
461
+ log_in_query = f"""
462
+ INSERT INTO {TABLE_NAME} (user_id, action, content, timestamp)
463
+ VALUES (%s, %s, %s, %s);"""
464
+ ts = datetime.datetime.now()
465
+
466
+ data_for_query_situation1 = (mturk_id, "situation1", situation1, ts)
467
+ data_for_query_goal1 = (mturk_id, "goal1", goal1, ts)
468
+ data_for_query_difficulty1 = (mturk_id, "difficulty1", str(difficulty1), ts)
469
+ data_for_query_situation2 = (mturk_id, "situation2", situation2, ts)
470
+ data_for_query_goal2 = (mturk_id, "goal2", goal2, ts)
471
+ data_for_query_difficulty2 = (mturk_id, "difficulty2", str(difficulty2), ts)
472
+
473
+ with conn.cursor() as cur:
474
+ cur.execute(log_in_query, data_for_query_situation1)
475
+ cur.execute(log_in_query, data_for_query_goal1)
476
+ cur.execute(log_in_query, data_for_query_difficulty1)
477
+ cur.execute(log_in_query, data_for_query_situation2)
478
+ cur.execute(log_in_query, data_for_query_goal2)
479
+ cur.execute(log_in_query, data_for_query_difficulty2)
480
+
481
+ conn.commit()
482
+ conn.close()
483
+
484
+ difficulty1_text = "You rated the difficulty of the situation as: " + str(difficulty1) + " out of 10."
485
+ difficulty2_text = "You rated the difficulty of the situation as: " + str(difficulty2) + " out of 10."
486
+ print (situation1)
487
+ system_prompt1_convo1 = generate_system_input_situation_only(mturk_id, situation1, "situation1")
488
+ system_prompt1_convo3 = system_prompt1_convo1
489
+ system_prompt2_convo4 = generate_system_input_situation_only(mturk_id, situation2, "situation2")
490
+
491
+ situation1_formatted = format_markdown('situation1', situation1)
492
+ goal1_formatted = format_markdown('goal1', goal1)
493
+ situation2_formatted = format_markdown('situation2', situation2)
494
+ goal2_formatted = format_markdown('goal2', goal2)
495
+ difficulty1_formatted = format_markdown('difficulty1', difficulty1_text)
496
+ difficulty2_formatted = format_markdown('difficulty2', difficulty2_text)
497
+
498
+ return "", gr.update(visible=True), gr.update(visible=False), situation1_formatted, goal1_formatted, difficulty1_formatted, situation2_formatted, goal2_formatted, difficulty2_formatted, situation1_formatted, goal1_formatted, difficulty1_formatted, situation1_formatted, goal1_formatted, difficulty1_formatted, situation1_formatted, goal1_formatted, difficulty1_formatted, situation1_formatted, goal1_formatted, difficulty1_formatted,situation2_formatted, goal2_formatted, difficulty2_formatted, situation2_formatted, goal2_formatted, difficulty2_formatted, system_prompt1_convo1, system_prompt1_convo3, system_prompt2_convo4 # last eight: situation1_convo1, goal1_convo1, situation1_convo2, goal1_convo2, situation1_convo3, goal1_convo3, situation2_convo4, goal2_convo4 # last two: system_prompt1, system_prompt2
499
+ else:
500
+ return '<span style="color: red;"> Cannot find this mTurk ID in qualified pool. If you think this is a mistake, please reach out to Inna at ilin@cs.washington.edu. </span>', gr.update(visible=False), gr.update(visible=True), "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "","", "", "", "", "", "", "", "", "", ""
501
+
502
+ def format_markdown(text_type, text):
503
+ if text_type == 'situation1':
504
+ return '<span style="color: #ff6f4b;"> Situation 1: ' + text + '</span>'
505
+ elif text_type == 'goal1':
506
+ return '<span style="color: #ff6f4b;"> Goal: ' + text + '</span>'
507
+ elif text_type == 'difficulty1':
508
+ return '<span style="color: #ff6f4b;"> Difficulty: ' + text + '</span>'
509
+ elif text_type == 'situation2':
510
+ return '<span style="color: #ff6f4b;"> Situation 2: ' + text + '</span>'
511
+ elif text_type == 'goal2':
512
+ return '<span style="color: #ff6f4b;"> Goal: ' + text + '</span>'
513
+ elif text_type == 'difficulty2':
514
+ return '<span style="color: #ff6f4b;"> Difficulty: ' + text + '</span>'
515
+
516
+ def proceed_to_next_chat():
517
+ return gr.update(visible=False), gr.update(visible=True)
518
+
519
+ def proceed_to_next_chat_final(mturk_id):
520
+ generated_completion_code = ''.join(random.choices(string.ascii_uppercase + string.digits, k = 6))
521
+
522
+ conn = psycopg2.connect(host=DB_ENDPOINT, port=DB_PORT, dbname=DB_NAME, user=DB_USER, password=DB_PASSWORD)
523
+ log_in_query = f"""
524
+ INSERT INTO {TABLE_NAME} (user_id, action, content, timestamp)
525
+ VALUES (%s, %s, %s, %s);"""
526
+ ts = datetime.datetime.now()
527
+ data_for_query = (mturk_id, "completion_code", generated_completion_code, ts)
528
+
529
+ with conn.cursor() as cur:
530
+ cur.execute(log_in_query, data_for_query)
531
+
532
+ conn.commit()
533
+ conn.close()
534
+
535
+ return gr.update(visible=False), gr.update(visible=True), generated_completion_code
536
+
537
+
538
+ def record_survey_answers(survey_name, user_id, confident_ans, worried_ans, hopeful_ans, motivated_ans, fear_ans, anger_ans, disgust_ans, sad_ans):
539
+ if confident_ans == '' or worried_ans == '' or hopeful_ans == '' or motivated_ans == '' or fear_ans == '' or anger_ans == '' or disgust_ans == '' or sad_ans == '':
540
+ return gr.update(visible=True), gr.update(visible=False), '<span style="color: red;">Please fill in all fields.</span>'
541
+ record_chat_message(user_id, f"{survey_name}_confident", confident_ans)
542
+ record_chat_message(user_id, f"{survey_name}_worried", worried_ans)
543
+ record_chat_message(user_id, f"{survey_name}_hopeful", hopeful_ans)
544
+ record_chat_message(user_id, f"{survey_name}_motivated", motivated_ans)
545
+ record_chat_message(user_id, f"{survey_name}_fear", fear_ans)
546
+ record_chat_message(user_id, f"{survey_name}_anger", anger_ans)
547
+ record_chat_message(user_id, f"{survey_name}_disgust", disgust_ans)
548
+ record_chat_message(user_id, f"{survey_name}_sad", sad_ans)
549
+
550
+ return gr.update(visible=False), gr.update(visible=True), ''
551
+
552
+ def record_survey_answers_outtake(user_id, q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, additional):
553
+ if q1 == '' or q2 == '' or q3 == '' or q4 == '' or q5 == '' or q6 == '' or q7 == '' or q8 == '' or q9 == '' or q10 == '':
554
+ return gr.update(visible=True), gr.update(visible=False), '<span style="color: red;">Please fill in all fields.</span>'
555
+ record_chat_message(user_id, f"outtake_q1", q1)
556
+ record_chat_message(user_id, f"outtake_q2", q2)
557
+ record_chat_message(user_id, f"outtake_q3", q3)
558
+ record_chat_message(user_id, f"outtake_q4", q4)
559
+ record_chat_message(user_id, f"outtake_q5", q5)
560
+ record_chat_message(user_id, f"outtake_q6", q6)
561
+ record_chat_message(user_id, f"outtake_q7", q7)
562
+ record_chat_message(user_id, f"outtake_q8", q8)
563
+ record_chat_message(user_id, f"outtake_q9", q9)
564
+ record_chat_message(user_id, f"outtake_q10", q10)
565
+ record_chat_message(user_id, f"outtake_additional_feedback", additional)
566
+
567
+ return gr.update(visible=False), gr.update(visible=True), ''
568
+
569
+ def generate_feedback_and_record(user_id, current_situation, category, u, prompt_strategy, prompt_selection, strategy_list):
570
+ if u == '' or len(u.split()) < 5:
571
+ return '<span style="color: red;">Please write a sentence that contains at least five words! </span>', 'No'
572
+ output = generate_feedback_with_mc(current_situation, category, u, prompt_strategy, prompt_selection, strategy_list) ## if mc then use generate_feedback_with_mc
573
+ strategy = strategy_list[0]
574
+ record_chat_message(user_id, f"user_message_pre_feedback", u)
575
+ record_chat_message(user_id, f"feedback_{strategy}", output)
576
+
577
+ return output, 'Yes'
578
+
579
+ def generate_skill_suggestion_and_record(user_id, situation, input_history, demonstration_mode):
580
+ # inputs=[situation1_convo2, chat_history, demonstration_model_suggest_skill], outputs=[skill_suggestion0, skill_suggestion1, skill_suggestion_reason]
581
+ skill_suggestion0, skill_suggestion_reason = generate_skill_suggestion(situation, input_history, demonstration_mode)
582
+ record_chat_message(user_id, f"skill_suggestion0", skill_suggestion0)
583
+ # record_chat_message(user_id, f"skill_suggestion1", skill_suggestion1)
584
+ record_chat_message(user_id, f"skill_suggestion_reason", skill_suggestion_reason)
585
+
586
+ return skill_suggestion0, skill_suggestion_reason
587
+
588
+
589
+ def predict_and_check_edit(user_id, strategy_selection, text, edited_text, input_history, system_input_core, convo_num, skill_suggestion0, skill_suggestion1, skill_suggestion_reason, feedback_text, feedback_check, display):
590
+ if feedback_check == 'No':
591
+ message_error_message = '<span style="color: red;">Please get feedback and improve your response before sending the response. </span>'
592
+ return display, input_history, text, gr.update(visible=False), gr.update(visible=False), message_error_message, skill_suggestion0, skill_suggestion1, skill_suggestion_reason, feedback_text, edited_text, strategy_selection, feedback_check
593
+ if text == edited_text:
594
+ print (feedback_text.split()[0])
595
+ if feedback_text.split()[0][3:].strip() != 'Strong':
596
+ message_error_message = '<span style="color: red;">Please make edits based on the feedback before sending the message. </span>'
597
+ return display, input_history, text, gr.update(visible=False), gr.update(visible=False), message_error_message, skill_suggestion0, skill_suggestion1, skill_suggestion_reason, feedback_text, edited_text, strategy_selection, feedback_check
598
+ responses, input_history, text, output, refresh, message_error_message, new_strategy_list = predict(user_id, strategy_selection, edited_text, input_history, system_input_core, convo_num, display)
599
+ #outputs=[display, chat_history, text, output, refresh, message_error_message] feedback_output
600
+ # [mturk_id, strategy_selection, edited_text, chat_history, system_prompt1_convo2, convo_num2, skill_suggestion0, skill_suggestion1, skill_suggestion_reason, feedback_text]
601
+ return responses, input_history, text, output, refresh, message_error_message, '', '', '', '','',new_strategy_list, 'No' # last four: skill_suggestion0, skill_suggestion1, skill_suggestion_reason, feedback_text, edited_text
602
+
603
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="purple", secondary_hue="purple"),css=css) as demo:
604
+ # with gr.Blocks() as demo:
605
+ gr.Markdown("""# Interpersonal Effectiveness Learning & Practice""")
606
+ with gr.Column(visible=True) as auth_block:
607
+ mturk_id = gr.Textbox(label="Please enter your mTurk ID")
608
+ auth_button = gr.Button("Confirm and start the study")
609
+ passcode_warning = gr.Markdown(elem_id='emp')
610
+
611
+ with gr.Column(visible=False) as intro:
612
+
613
+ gr.Markdown("""
614
+ ## Study Goals
615
+ We are a group of researchers building an AI-based tool to provide training to participants to improve their communication skills in difficult situations. In this study, you will chat through text with a simulated conversation partner powered by AI. The tool will provide concrete suggestions on good communication strategies and personalized feedback on how well you exercise these strategies.
616
+
617
+ ## You will engage in FOUR conversations in total.
618
+ For each of the situation, you will engage in an one-on-one conversation where you try to communicate to resolve or improve the situation. The AI model is instructed to play the role of the person you are talking to. For each conversation, you are expected to respond ten times. For each conversation turn, you should first identify the best strategy to use in this turn before writing the response using the select strategy.
619
+
620
+ <span id="emp">Conversation 1 - pre-training evaluation </span> This will be about a situation you wrote in the qualification task. In this conversation, you will chat <b>without any feedback or reference materials.</b> <br/>
621
+ <span id="emp">Conversation 2 - training conversation </span> This conversation will be about the same situation as Conversation 1. In this conversation, you will <b>receive suggestions to use a conversation strategy and feedback on how well you exercise the strategy, and improve the response based on the feedback. </b> You will also have access to a reference document about the strategies. <br/>
622
+ <span id="emp">Conversation 3 - post-training evaluation </span> This will be about the first situation again. We want to see if you can improve your communication in the first situation after the training. In this conversation, you will chat <b>without any feedback or reference materials.</b><br/>
623
+ <span id="emp">Conversation 4 - post-training evaluation </span> This will be about <b>the second situation</b> you wrote in the qualification task. In this conversation, you will chat <b>without any feedback or reference materials.</b> <br/>
624
+
625
+ ## You will receive a BONUS of $10 if...
626
+ Over the course of the conversations 2-4, you are at the top 30\% of the participants in terms of how well you exhibit the skills taught in conversation 2. We will evaluate and assign the bonus after the study is completed (mid-February). The bonus will be $10 in addition to the base payment. The best way to get the bonus is to try your best to learn the strategies in the training conversation and exercise them in the post-training conversations.
627
+
628
+
629
+ ## IMPORTANT: How do I confirm the completion of this task?
630
+ You will be asked to provide a completion code on mTurk interface. You will receive the completion code after you finish the study. Please record the completion code to prove completion of the task.
631
+
632
+ Please note that you will only get the payment if you complete the entire study, i.e. ten conversation responses for each of the four conversations. """)
633
+
634
+ gr.Markdown("""
635
+ ## Content Warning
636
+ This study may contain situations and thoughts that might be disturbing. If you have any questions or concerns, please send us an email (ilin@cs.washington.edu). Should you have a strong negative reaction to some of the content, you can reach a crisis counselor at <a href="https://www.crisistextline.org" target="_blank">Crisis Text Line</a> or by texting HOME to 741741.
637
+
638
+ If you have questions about your rights as a research participant, or wish to obtain information, ask questions or discuss any concerns about this study with someone other than the researchers, please contact the University of Washington Human Subjects Division at 206-543-0098.
639
+
640
+ ## Consent to the task
641
+ """)
642
+
643
+ consent_check = gr.Checkbox(label = "By ticking this box, you are agreeing to be part of this user study. Be sure that questions you have about the study have been answered and that you understand what you are being asked to do. You may contact us if you think of a question later. You are free to release/quit the study at any time. To be compensated for the study, you agree to finish the task in approximately 1 hour. The data collected in the study will be released to the public for research purposes and you should not include any identifiable personal information. To save a copy of the consent form and instructions, you can save/print this webpage.")
644
+ consent_error_message = gr.Markdown(elem_id='emp')
645
+ consent_button = gr.Button('Agree and Start the Study')
646
+
647
+
648
+ with gr.Column(visible=False) as intake_1:
649
+ consent_button.click(fn=check_consent_and_start, inputs=[mturk_id, consent_check], outputs=[consent_error_message, intro, intake_1])
650
+ gr.Markdown("""# Intake Survey - Situation 1""")
651
+ gr.Markdown("""In this section, you will answer a few questions about the first situation you wrote in the qualification task. Please answer the questions as honestly as possible. If your answers seem inconsistent, we may not be able to use your data or pay you for the study. """)
652
+ survey_name1 = gr.Textbox('intake_situation1', visible=False)
653
+ # write a section of survey questions
654
+ situation1_intake = gr.Markdown(elem_id='emp')
655
+ goal1_intake = gr.Markdown(elem_id='emp')
656
+ difficulty1_intake = gr.Markdown(elem_id='emp')
657
+ confident_intake1 = gr.Dropdown(choices=['Strongly Disagree', 'Disagree', 'Somewhat Disagree', 'Neither Agree nor Disagree', 'Somewhat Agree', 'Agree', 'Strongly Agree'], label="I feel **confident** about my ability to achieve my goal through having this conversation", interactive=True)
658
+ worried_intake1 = gr.Dropdown(choices=['Strongly Disagree', 'Disagree', 'Somewhat Disagree', 'Neither Agree nor Disagree', 'Somewhat Agree', 'Agree', 'Strongly Agree'], label="I feel **worried** about achieving my goal through having this conversation", interactive=True)
659
+ hopeful_intake1 = gr.Dropdown(choices=['Strongly Disagree', 'Disagree', 'Somewhat Disagree', 'Neither Agree nor Disagree', 'Somewhat Agree', 'Agree', 'Strongly Agree'], label="I feel **hopeful** about achieving my goal through having this conversation", interactive=True)
660
+ motivated_intake1 = gr.Dropdown(choices=['Strongly Disagree', 'Disagree', 'Somewhat Disagree', 'Neither Agree nor Disagree', 'Somewhat Agree', 'Agree', 'Strongly Agree'], label="I feel **motivated** about having this challenging conversation", interactive=True)
661
+
662
+ # Emotions (negative emotions from Plutchik's wheel of emotions)
663
+ fear_intake1 = gr.Dropdown(choices=['Strongly Disagree', 'Disagree', 'Somewhat Disagree', 'Neither Agree nor Disagree', 'Somewhat Agree', 'Agree', 'Strongly Agree'], label="I feel **fearful** about this situation", interactive=True)
664
+ anger_intake1 = gr.Dropdown(choices=['Strongly Disagree', 'Disagree', 'Somewhat Disagree', 'Neither Agree nor Disagree', 'Somewhat Agree', 'Agree', 'Strongly Agree'], label="I feel **angry** about this situation", interactive=True)
665
+ disgust_intake1 = gr.Dropdown(choices=['Strongly Disagree', 'Disagree', 'Somewhat Disagree', 'Neither Agree nor Disagree', 'Somewhat Agree', 'Agree', 'Strongly Agree'], label="I feel **disgusted** about this situation", interactive=True)
666
+ sad_intake1 = gr.Dropdown(choices=['Strongly Disagree', 'Disagree', 'Somewhat Disagree', 'Neither Agree nor Disagree', 'Somewhat Agree', 'Agree', 'Strongly Agree'], label="I feel **sad** about this situation", interactive=True)
667
+
668
+ intake1_error = gr.Markdown(elem_id='emp')
669
+ continue_intake1 = gr.Button("Continue to the next step")
670
+
671
+ with gr.Column(visible=False) as intake_2:
672
+ survey_name2 = gr.Textbox('intake_situation2', visible=False)
673
+ continue_intake1.click(fn=record_survey_answers, inputs=[survey_name1, mturk_id, confident_intake1, worried_intake1, hopeful_intake1, motivated_intake1, fear_intake1, anger_intake1, disgust_intake1, sad_intake1], outputs=[intake_1, intake_2, intake1_error])
674
+ gr.Markdown("""# Intake Survey - Situation 2""")
675
+ gr.Markdown("""In this section, you will answer a few questions about the second situation you wrote in the qualification task. Please answer the questions as honestly as possible. If your answers seem inconsistent, we may not be able to use your data or pay you for the study. """)
676
+ # write a section of survey questions
677
+ situation2_intake = gr.Markdown(elem_id='emp')
678
+ goal2_intake = gr.Markdown(elem_id='emp')
679
+ difficulty2_intake = gr.Markdown(elem_id='emp')
680
+
681
+ confident_intake2 = gr.Dropdown(choices=['Strongly Disagree', 'Disagree', 'Somewhat Disagree', 'Neither Agree nor Disagree', 'Somewhat Agree', 'Agree', 'Strongly Agree'], label="I feel **confident** about my ability to achieve my goal through having this conversation", interactive=True)
682
+ worried_intake2 = gr.Dropdown(choices=['Strongly Disagree', 'Disagree', 'Somewhat Disagree', 'Neither Agree nor Disagree', 'Somewhat Agree', 'Agree', 'Strongly Agree'], label="I feel **worried** about achieving my goal through having this conversation", interactive=True)
683
+ hopeful_intake2 = gr.Dropdown(choices=['Strongly Disagree', 'Disagree', 'Somewhat Disagree', 'Neither Agree nor Disagree', 'Somewhat Agree', 'Agree', 'Strongly Agree'], label="I feel **hopeful** about achieving my goal through having this conversation", interactive=True)
684
+ motivated_intake2 = gr.Dropdown(choices=['Strongly Disagree', 'Disagree', 'Somewhat Disagree', 'Neither Agree nor Disagree', 'Somewhat Agree', 'Agree', 'Strongly Agree'], label="I feel **motivated** about having this challenging conversation", interactive=True)
685
+
686
+ # Emotions (negative emotions from Plutchik's wheel of emotions)
687
+ fear_intake2 = gr.Dropdown(choices=['Strongly Disagree', 'Disagree', 'Somewhat Disagree', 'Neither Agree nor Disagree', 'Somewhat Agree', 'Agree', 'Strongly Agree'], label="I feel **fearful** about this situation", interactive=True)
688
+ anger_intake2 = gr.Dropdown(choices=['Strongly Disagree', 'Disagree', 'Somewhat Disagree', 'Neither Agree nor Disagree', 'Somewhat Agree', 'Agree', 'Strongly Agree'], label="I feel **angry** about this situation", interactive=True)
689
+ disgust_intake2 = gr.Dropdown(choices=['Strongly Disagree', 'Disagree', 'Somewhat Disagree', 'Neither Agree nor Disagree', 'Somewhat Agree', 'Agree', 'Strongly Agree'], label="I feel **disgusted** about this situation", interactive=True)
690
+ sad_intake2 = gr.Dropdown(choices=['Strongly Disagree', 'Disagree', 'Somewhat Disagree', 'Neither Agree nor Disagree', 'Somewhat Agree', 'Agree', 'Strongly Agree'], label="I feel **sad** about this situation", interactive=True)
691
+
692
+ intake2_error = gr.Markdown(elem_id='emp')
693
+ continue_intake2 = gr.Button("Continue to the next step")
694
+
695
+ # with gr.Column(visible=False) as dearman_info:
696
+ # continue_intake2.click(fn=record_survey_answers, inputs=[survey_name2, mturk_id, confident_intake2, worried_intake2, hopeful_intake2, motivated_intake2, fear_intake2, anger_intake2, disgust_intake2, sad_intake2], outputs=[intake_2, dearman_info, intake2_error])
697
+
698
+ # gr.Markdown("""In this study, you will focus on learning the DEAR MAN skills.""")
699
+ # gr.Markdown("""
700
+ # ## DEAR MAN Skills
701
+ # DEAR MAN skills helps obtain objectives effectively in a difficult situation. The DBT manual defines the skills as shown below. (Source: DBT Skills Training Manual, 2nd Edition. Marsha M. Linehan.)
702
+
703
+ # <span id="emp">Describe</span> Describe the current situation (if necessary). Stick to the facts. Tell the person exactly what you are reacting to. <br/>
704
+ # e.g. <em>You told me you would be home by dinner but you didn't get here until 11.</em> <br/>
705
+
706
+ # <span id="emp">Express</span> Express your feelings and opinions about the situation. Don't assume that the other person knows how you feel. <br/>
707
+ # e.g. <em>When you come home so late, I start worrying about you.</em> <br/>
708
+
709
+ # <span id="emp">Assert</span> Assert yourself by asking for what you want or saying no clearly. Do not assume that others will figure out what you want. Remember that others cannot read your mind. <br/>
710
+ # e.g. <em>I would really like it if you would call me when you are going to be late.</em> <br/>
711
+
712
+ # <span id="emp">Reinforce</span> Reinforce the person ahead of time by explaining positive effects of getting what you want or need. If necessary, also clarify the negative consequences of not getting what you want or need. <br/>
713
+ # e.g. <em>I would be so relieved, and a lot easier to live with, if you do that.</em> <br/>
714
+
715
+ # <span id="emp">Mindful</span> Keep your focus on your goals. Maintain your position. Don't be distracted. Don't get off the topic. <br/>
716
+ # e.g. <em>I would still like a call</em> <br/>
717
+
718
+ # <span id="emp">Appear Confident</span> Appear effective and competent. Use a confident voice tone. Avoid saying things like "I'm not sure." <em></em> <br/>
719
+
720
+ # <span id="emp">Negotiate</span> Be willing to give to get. Offer and ask for other solutions to the problem. Reduce your request. Say no, but offer to do something else or to solve the problem another way. Focus on what will work. <br/>
721
+ # e.g. <em>How about if you text me when you think you might be late?</em> <br/>
722
+
723
+ # In each of the conversations, you will learn to use these skills to communicate in the challenging situations you brought up in the qualification task. \n
724
+
725
+ # <span id="emp"> Among these skills, Describe, Assert, Reinforce, and Negotiate are conversation strategies you can use in each response. You should always try to be mindful and confident in each response. </span>
726
+
727
+ # """)
728
+
729
+ # continue_dearman = gr.Button("Continue to the next step")
730
+ with gr.Column(visible=False) as conversation1:
731
+ # continue_dearman.click(fn=proceed_to_next_chat, inputs=[], outputs=[dearman_info, conversation1])
732
+ continue_intake2.click(fn=record_survey_answers, inputs=[survey_name2, mturk_id, confident_intake2, worried_intake2, hopeful_intake2, motivated_intake2, fear_intake2, anger_intake2, disgust_intake2, sad_intake2], outputs=[intake_2, conversation1, intake2_error])
733
+
734
+ gr.Markdown("""# Conversation 1""")
735
+ gr.Markdown("""In this section, you will chat with a simulated conversation partner powered by AI. The AI model is instructed to play the role of the person you are talking to. You will chat about the first situation you wrote in the qualification task. You will chat without any feedback or reference materials. You are expected to respond ten times. For each conversation turn, you should first identify the best strategy to use in this turn before writing the response using the select strategy. """)
736
+ with gr.Accordion("Open to see the list of conversation strategies you can choose from", open=True):
737
+ gr.Markdown("""
738
+ <span id="emp">Describe</span> Describe the current situation. <br/>
739
+
740
+ <span id="emp">Express</span> Express your feelings and opinions about the situation. <br/>
741
+
742
+ <span id="emp">Assert</span> Assert yourself by asking for what you want or saying no clearly. <br/>
743
+
744
+ <span id="emp">Reinforce</span> Reinforce the person ahead of time by explaining positive effects of getting what you want or need. If necessary, also clarify the negative consequences of not getting what you want or need. <br/>
745
+
746
+ <span id="emp">Negotiate</span> Be willing to give to get. Offer and ask for other solutions to the problem. <br/>
747
+
748
+ <span id="emp">In each response, you should try to stay mindful and confident.</span> <br/>
749
+ <span id="emp">Mindful</span> Keep your focus on your goals. Maintain your position. Don't be distracted. Don't get off the topic. <br/>
750
+
751
+ <span id="emp">Appear Confident</span> Appear effective and competent. Use a confident voice tone. Avoid saying things like "I'm not sure." <br/>
752
+ """)
753
+ convo_num1 = gr.Textbox("convo_1", visible=False)
754
+ # chat1 = gr.ChatInterface()
755
+ situation1_convo1 = gr.Markdown(elem_id='emp')
756
+ goal1_convo1 = gr.Markdown(elem_id='emp')
757
+ system_prompt1_convo1 = gr.Markdown(visible=False)
758
+ difficulty1_convo1 = gr.Markdown(visible=False)
759
+
760
+ chat1_history = gr.State([])
761
+
762
+ with gr.Row():
763
+ display_chat1 = gr.Chatbot(elem_id="chuanhu_chatbot")
764
+
765
+ with gr.Row():
766
+ strategy_selection1 = gr.Dropdown(['Describe', 'Express', 'Assert','Reinforce', 'Negotiate'], label='Select the most effective strategy', scale=1, interactive=True,multiselect=True, max_choices=7)
767
+ text_chat1 = gr.Textbox(label='Send response exercising the strategy', scale=2, interactive=True)
768
+ button_submit_chat1 = gr.Button("Send", scale=0)
769
+ with gr.Row():
770
+ message_error_message1 = gr.Markdown(elem_id='emp')
771
+
772
+ with gr.Row(visible=False) as proceed_chat1:
773
+ output1= gr.Markdown('<span id="emp">You have done 10 turns of conversation! Please click the button below to continue. </span>')
774
+ continue_button1 = gr.Button("Continue to the next step")
775
+
776
+ button_submit_chat1.click(fn=predict, inputs=[mturk_id, strategy_selection1, text_chat1, chat1_history, system_prompt1_convo1, convo_num1, display_chat1], outputs=[display_chat1, chat1_history, text_chat1, output1, proceed_chat1, message_error_message1, strategy_selection1]) # TODO: after hitting 'Send Message', strategy selection and Feedback markdown should be refreshed / reset #user_id, strategy_selection, new_input, input_history, system_input_core, system_prompt, convo_num
777
+
778
+ with gr.Accordion("I am asked to respond 10 times for each situation. What if the chatbot already agrees with me before 10 responses?", open=False):
779
+ gr.Markdown("If the chatbot concurs with you within the first 10 responses, you have the option to terminate the conversation before 10 responses by clicking the button. Please note, to ensure the quality of the dataset, we will conduct a manual review to assess the reasonableness of the agreement, and we will not compensate for conversations where the chatbot did not genuinely reach an agreement. If you engage in at least 10 responses, you are not required to acquire an agreement from the chatbot and you should see a button that clearly says 'You have finished this situation, submit and continue to the next step.'")
780
+ agreement_proceed_button1 = gr.Button("I confirm I have read and understood the statement above and the chatbot indeed agrees with me before I respond 10 times. End the conversation now and proceed to the next step.")
781
+
782
+
783
+ with gr.Column(visible=False) as study:
784
+ agreement_proceed_button1.click(fn=proceed_to_next_chat, inputs=[], outputs=[conversation1, study])
785
+ continue_button1.click(fn=proceed_to_next_chat, inputs=[], outputs=[conversation1, study])
786
+
787
+ gr.Markdown('# Conversation 2 - Training Conversation')
788
+ gr.Markdown("""In this section, you will chat with a simulated conversation partner powered by AI. The AI model is instructed to play the role of the person you are talking to. You will chat about the first situation you wrote in the qualification task. In this conversation, you will receive suggestions to use a DEAR MAN skill and get feedback on how well you exercise the skill. You will also have access to a reference document about the strategies. You are expected to respond ten times. For each conversation turn, you should do the following steps: \n
789
+ <span id="emp"> Step 1. </span> Click on the "Suggest to me a skill to use" button to get a skill suggestion. \n
790
+ <span id="emp"> Step 2. </span> Select the most effective strategy from the dropdown menu, you can either follow the suggestion or use your own judgement to select a strategy. \n
791
+ <span id="emp"> Step 3. </span> Write a response exercising the strategy. \n
792
+ <span id="emp"> Step 4. </span> Click on the "Get feedback on your response" button to get feedback on your response. \n
793
+ <span id="emp"> For each response, you will get feedback on the following.</span> \n
794
+ i. <b>How well you exercise the strategy you select.</b> Our model will provide a rating of Strong, Weak, or None based on the response you write. We request that you make edits to your response before sending it to the chatbot if the feedback says your response is Weak or None. \n
795
+ ii. <b>How well the response shows mindfulness and confidence.</b> If you get feedback on mindfulness and confidence, please make edits to the response before sending it to the chatbot. \n
796
+
797
+ <span id="emp"> Step 5. </span> Make edits to your response based on the feedback, if the feedback says your response is weak or none on the skill you select. \n
798
+ <span id="emp"> Step 6. </span> Click on the "Send message" button to send your response to the chatbot. \n
799
+ <span id="emp"> Step 7. </span> Repeat the above steps until you have done 10 turns of the conversation.""")
800
+
801
+ with gr.Accordion("Open to see the list of DEAR MAN skills", open=True):
802
+ gr.Markdown("""## DEAR MAN Skills
803
+ DEAR MAN skills helps obtain objectives effectively in a difficult situation. There are seven skills which start with the letters D, E, A, R, M, A, N. Below, we show the definitions of DEAR MAN skills and give an example for each skill. All the examples are regarding the situation where someone wants to talk to their husband about coming home late without warning them. In the exercise, you should try to use these skills to communicate in the challenging situations you brought up. You can always refer to this list of definitions and examples during the chat. \n
804
+
805
+ <b> Among these skills, Describe, Assert, Reinforce, and Negotiate are conversation strategies you can use in each response. You should always try to be Mindful and Appear Confident in each response. </b> \n
806
+
807
+ <span id="emp">Describe</span> Describe the current situation (if necessary). Stick to the facts. Tell the person exactly what you are reacting to. <br/>
808
+ e.g. <em>You told me you would be home by dinner but you didn't get here until 11.</em> <br/>
809
+
810
+ <span id="emp">Express</span> Express your feelings and opinions about the situation. Don't assume that the other person knows how you feel. <br/>
811
+ e.g. <em>When you come home so late, I start worrying about you.</em> <br/>
812
+
813
+ <span id="emp">Assert</span> Assert yourself by asking for what you want or saying no clearly. Do not assume that others will figure out what you want. Remember that others cannot read your mind. <br/>
814
+ e.g. <em>I would really like it if you would call me when you are going to be late.</em> <br/>
815
+
816
+ <span id="emp">Reinforce</span> Reinforce the person ahead of time by explaining positive effects of getting what you want or need. If necessary, also clarify the negative consequences of not getting what you want or need. <br/>
817
+ e.g. <em>I would be so relieved, and a lot easier to live with, if you do that.</em> <br/>
818
+
819
+ <span id="emp">Mindful</span> Keep your focus on your goals. Maintain your position. Don't be distracted. Don't get off the topic. <br/>
820
+ e.g. <em>I would still like a call</em> <br/>
821
+
822
+ <span id="emp">Appear Confident</span> Appear effective and competent. Use a confident voice tone. Avoid saying things like "I'm not sure." <em></em> <br/>
823
+
824
+ <span id="emp">Negotiate</span> Be willing to give to get. Offer and ask for other solutions to the problem. Reduce your request. Say no, but offer to do something else or to solve the problem another way. Focus on what will work. <br/>
825
+ e.g. <em>How about if you text me when you think you might be late?</em> <br/>
826
+
827
+ (Source: DBT Skills Training Manual, 2nd Edition. Marsha M. Linehan.) """)
828
+ convo_num2 = gr.Textbox("convo_2", visible=False)
829
+
830
+ situation1_convo2 = gr.Markdown(elem_id='emp')
831
+ goal1_convo2 = gr.Markdown(elem_id='emp')
832
+ difficulty1_convo2 = gr.Markdown(visible=False)
833
+ system_prompt1_convo2 = gr.Markdown(visible=False)
834
+ user_situation_category = gr.Dropdown(choices=['Family', 'Social', 'Work'], label="Step 1a: Select a situation category", value='Social', visible=False)
835
+ demonstration_model_suggest_skill = gr.Textbox(value="zero_shot", visible=False)
836
+
837
+ chat_history = gr.State([])
838
+
839
+ # with gr.Row():
840
+ display = gr.Chatbot(elem_id="chuanhu_chatbot")
841
+
842
+ gr.Markdown('<span id="step"> Step 1: Get a skill suggestion. </span>')
843
+ skill_suggest_button = gr.Button("Click here to get a skill suggestion.")
844
+
845
+ skill_suggestion0 = gr.Markdown(elem_id='emp') # clear
846
+ skill_suggestion1 = gr.Markdown(elem_id='emp', visible=False) # clear
847
+ skill_suggestion_reason = gr.Markdown(elem_id='emp') # clear
848
+ strategy_selection = gr.Dropdown(['Describe', 'Express', 'Assert','Reinforce', 'Negotiate'], label='Step 2: Select a strategy you want to use and get feedback on. You can choose the suggested strategy or use your own judgement to select a strategy.', scale=2, interactive=True,multiselect=True, max_choices=1)
849
+ # strategy_selection = gr.Dropdown(['Describe', 'Express', 'Assert','Reinforce', 'Negotiate'], scale=2, interactive=True,multiselect=True, max_choices=7)
850
+ # skill_suggest_button = gr.Button("Suggest to me a skill to use")
851
+ skill_suggest_button.click(fn=generate_skill_suggestion_and_record, inputs=[mturk_id, situation1_convo2, chat_history, demonstration_model_suggest_skill], outputs=[skill_suggestion0,skill_suggestion_reason]) # situation, input_history, demonstration_mode
852
+
853
+ text = gr.Textbox(label='Step 3: Write a response exercising the selected strategy.')
854
+ gr.Markdown('<span id="step"> Step 4: Get feedback on how well you exercise the DEAR MAN strategy. This step can take up to 60 seconds (on average, 20-30 seconds), please do not refresh the page since you may lose your progress. </span>')
855
+ feedback_button = gr.Button("Click here to get feedback on your response")
856
+ feedback_text = gr.Markdown(elem_id='emp') #clear
857
+ prompt_strategy = gr.Textbox(value="reason", visible=False)
858
+ prompt_selection = gr.Textbox(value="all_utterances_knn",visible=False)
859
+ feedback_check = gr.Textbox(value='No', visible=False)
860
+
861
+
862
+ # (all_strategy, current_situation, category, u, prompt_strategy, prompt_selection, strategy_list) # TODO: add mindful and confident
863
+
864
+ message_error_message = gr.Markdown(elem_id='emp')
865
+ feedback_button.click(fn=generate_feedback_and_record, inputs=[mturk_id, situation1_convo2, user_situation_category, text, prompt_strategy, prompt_selection, strategy_selection], outputs=[feedback_text, feedback_check])
866
+
867
+ # gr.Markdown('<span id="step"> Step 5: Make edits to your response based on the feedback. This step if optional if the feedback says your response is a strong one. </span>')
868
+
869
+ edited_text = gr.Textbox(label='Step 5: Make edits to your response based on the feedback. This step if optional if the feedback says your response is a strong one.') # clear
870
+
871
+ gr.Markdown('<span id="step"> Step 6: Send your edited response to the chatbot. </span>')
872
+ send_message_button = gr.Button("Click here to send message.")
873
+
874
+ with gr.Column(visible=False) as refresh:
875
+ output = gr.Markdown('<br/><br/> <span id="emp">You have done 10 turns of conversation! Please click the button below to start a new situation! </span>')
876
+ refresh_button = gr.ClearButton([user_situation_category, situation1_convo2, system_prompt1_convo2, display, edited_text, chat_history], value='You have finished the training.')
877
+
878
+ # send_message_button.click(fn=predict, inputs=[user_id_text, strategy_selection, text, chat_history, system_prompt1_convo2, situation1_convo2], outputs=[display, chat_history, text, output, refresh, message_error_message]) # TODO: after hitting 'Send Message', strategy selection and Feedback markdown should be refreshed / reset
879
+ send_message_button.click(fn=predict_and_check_edit, inputs=[mturk_id, strategy_selection, text, edited_text, chat_history, system_prompt1_convo2, convo_num2, skill_suggestion0, skill_suggestion1, skill_suggestion_reason, feedback_text, feedback_check, display], outputs=[display, chat_history, text, output, refresh, message_error_message, skill_suggestion0, skill_suggestion1, skill_suggestion_reason, feedback_text, edited_text, strategy_selection, feedback_check])
880
+
881
+ with gr.Accordion("I am asked to respond 10 times for each situation. What if the chatbot already agrees with me before 10 responses?", open=False):
882
+ gr.Markdown("If the chatbot concurs with you within the first 10 responses, you have the option to terminate the conversation before 10 responses by clicking the button. Please note, to ensure the quality of the dataset, we will conduct a manual review to assess the reasonableness of the agreement, and we will not compensate for conversations where the chatbot did not genuinely reach an agreement. If you engage in at least 10 responses, you are not required to acquire an agreement from the chatbot and you should see a button that clearly says 'You have finished this situation, submit and start a new situation' .")
883
+ agreement_refresh_button = gr.Button("I confirm I have read and understood the statement above and the chatbot indeed agrees with me before I respond 10 times. End the conversation now and proceed to the next step.")
884
+
885
+ with gr.Column(visible=False) as post_training_survey1:
886
+
887
+ agreement_refresh_button.click(fn=proceed_to_next_chat, inputs=[], outputs=[study, post_training_survey1])
888
+ refresh_button.click(fn=proceed_to_next_chat, inputs=[], outputs=[study, post_training_survey1])
889
+
890
+ survey_post_name1 = gr.Textbox('post_situation1', visible=False)
891
+ # continue_intake1.click(fn=record_survey_answers, inputs=[survey_name1, mturk_id, confident_intake1, worried_intake1, hopeful_intake1, motivated_intake1, fear_intake1, anger_intake1, disgust_intake1, sad_intake1], outputs=[intake_1, intake_2, intake1_error])
892
+ gr.Markdown("""# Post Training Survey - Situation 1""")
893
+ # write a section of survey questions
894
+ situation1_post = gr.Markdown(elem_id='emp')
895
+ goal1_post = gr.Markdown(elem_id='emp')
896
+ difficulty1_post = gr.Markdown(visible=False)
897
+
898
+ confident_post1 = gr.Dropdown(choices=['Strongly Disagree', 'Disagree', 'Somewhat Disagree', 'Neither Agree nor Disagree', 'Somewhat Agree', 'Agree', 'Strongly Agree'], label="I feel **confident** about my ability to achieve my goal through having this conversation", interactive=True)
899
+ worried_post1 = gr.Dropdown(choices=['Strongly Disagree', 'Disagree', 'Somewhat Disagree', 'Neither Agree nor Disagree', 'Somewhat Agree', 'Agree', 'Strongly Agree'], label="I feel **worried** about achieving my goal through having this conversation", interactive=True)
900
+ hopeful_post1 = gr.Dropdown(choices=['Strongly Disagree', 'Disagree', 'Somewhat Disagree', 'Neither Agree nor Disagree', 'Somewhat Agree', 'Agree', 'Strongly Agree'], label="I feel **hopeful** about achieving my goal through having this conversation", interactive=True)
901
+ motivated_post1 = gr.Dropdown(choices=['Strongly Disagree', 'Disagree', 'Somewhat Disagree', 'Neither Agree nor Disagree', 'Somewhat Agree', 'Agree', 'Strongly Agree'], label="I feel **motivated** about having this challenging conversation", interactive=True)
902
+
903
+ # Emotions (negative emotions from Plutchik's wheel of emotions)
904
+ fear_post1 = gr.Dropdown(choices=['Strongly Disagree', 'Disagree', 'Somewhat Disagree', 'Neither Agree nor Disagree', 'Somewhat Agree', 'Agree', 'Strongly Agree'], label="I feel **fearful** about this situation", interactive=True)
905
+ anger_post1 = gr.Dropdown(choices=['Strongly Disagree', 'Disagree', 'Somewhat Disagree', 'Neither Agree nor Disagree', 'Somewhat Agree', 'Agree', 'Strongly Agree'], label="I feel **angry** about this situation", interactive=True)
906
+ disgust_post1 = gr.Dropdown(choices=['Strongly Disagree', 'Disagree', 'Somewhat Disagree', 'Neither Agree nor Disagree', 'Somewhat Agree', 'Agree', 'Strongly Agree'], label="I feel **disgusted** about this situation", interactive=True)
907
+ sad_post1 = gr.Dropdown(choices=['Strongly Disagree', 'Disagree', 'Somewhat Disagree', 'Neither Agree nor Disagree', 'Somewhat Agree', 'Agree', 'Strongly Agree'], label="I feel **sad** about this situation", interactive=True)
908
+
909
+ survey_post1_error = gr.Markdown(elem_id='emp')
910
+ continue_survey_post1 = gr.Button("Continue to the next step")
911
+
912
+ with gr.Column(visible=False) as conversation3:
913
+ continue_survey_post1.click(fn=record_survey_answers, inputs=[survey_post_name1, mturk_id, confident_post1, worried_post1, hopeful_post1, motivated_post1, fear_post1, anger_post1, disgust_post1, sad_post1], outputs=[post_training_survey1, conversation3, survey_post1_error])
914
+
915
+ gr.Markdown("""# Conversation 3""")
916
+ gr.Markdown("""In this section, you will chat with a simulated conversation partner powered by AI. The AI model is instructed to play the role of the person you are talking to. You will chat about the first situation you wrote in the qualification task. You will chat without any feedback or reference materials. You are expected to respond ten times. For each conversation turn, you should first identify the best strategy to use in this turn before writing the response using the select strategy. """)
917
+ gr.Markdown(""" <span id='emp'> The quality of this conversation will be used to determine the bonus. If you are able to use the skills you learned in the previous training conversation well (top 30\% of all the participants), you will be able to get the bonus. </span>""")
918
+ with gr.Accordion("Open to see the list of DEAR MAN skills", open=True):
919
+ gr.Markdown("""## DEAR MAN Skills
920
+ DEAR MAN skills helps obtain objectives effectively in a difficult situation. There are seven skills which start with the letters D, E, A, R, M, A, N. Below, we show the definitions of DEAR MAN skills and give an example for each skill. All the examples are regarding the situation where someone wants to talk to their husband about coming home late without warning them. In the exercise, you should try to use these skills to communicate in the challenging situations you brought up. You can always refer to this list of definitions and examples during the chat. \n
921
+
922
+ <span id="emp">Describe</span> Describe the current situation (if necessary). Stick to the facts. Tell the person exactly what you are reacting to. <br/>
923
+ e.g. <em>You told me you would be home by dinner but you didn't get here until 11.</em> <br/>
924
+
925
+ <span id="emp">Express</span> Express your feelings and opinions about the situation. Don't assume that the other person knows how you feel. <br/>
926
+ e.g. <em>When you come home so late, I start worrying about you.</em> <br/>
927
+
928
+ <span id="emp">Assert</span> Assert yourself by asking for what you want or saying no clearly. Do not assume that others will figure out what you want. Remember that others cannot read your mind. <br/>
929
+ e.g. <em>I would really like it if you would call me when you are going to be late.</em> <br/>
930
+
931
+ <span id="emp">Reinforce</span> Reinforce the person ahead of time by explaining positive effects of getting what you want or need. If necessary, also clarify the negative consequences of not getting what you want or need. <br/>
932
+ e.g. <em>I would be so relieved, and a lot easier to live with, if you do that.</em> <br/>
933
+
934
+ <span id="emp">Mindful</span> Keep your focus on your goals. Maintain your position. Don't be distracted. Don't get off the topic. <br/>
935
+ e.g. <em>I would still like a call</em> <br/>
936
+
937
+ <span id="emp">Appear Confident</span> Appear effective and competent. Use a confident voice tone. Avoid saying things like "I'm not sure." <em></em> <br/>
938
+
939
+ <span id="emp">Negotiate</span> Be willing to give to get. Offer and ask for other solutions to the problem. Reduce your request. Say no, but offer to do something else or to solve the problem another way. Focus on what will work. <br/>
940
+ e.g. <em>How about if you text me when you think you might be late?</em> <br/>
941
+
942
+ (Source: DBT Skills Training Manual, 2nd Edition. Marsha M. Linehan.) """)
943
+ convo_num3 = gr.Textbox("convo_3", visible=False)
944
+ situation1_convo3 = gr.Markdown(elem_id='emp')
945
+ goal1_convo3 = gr.Markdown(elem_id='emp')
946
+ difficulty1_convo3 = gr.Markdown(visible=False)
947
+ system_prompt1_convo3 = gr.Markdown(visible=False)
948
+
949
+ chat3_history = gr.State([])
950
+
951
+ with gr.Row():
952
+ display_chat3 = gr.Chatbot(elem_id="chuanhu_chatbot")
953
+
954
+ with gr.Row():
955
+ strategy_selection3 = gr.Dropdown(['Describe', 'Express', 'Assert','Reinforce', 'Negotiate'], label='Select the most effective strategy', scale=1, interactive=True,multiselect=True, max_choices=7)
956
+ text_chat3 = gr.Textbox(label='Send response exercising the strategy', scale=2)
957
+ button_submit_chat3 = gr.Button("Send", scale=0)
958
+
959
+ with gr.Row():
960
+ message_error_message3 = gr.Markdown(elem_id='emp')
961
+
962
+ with gr.Row(visible=False) as proceed_chat3:
963
+ output3= gr.Markdown('<br/><br/> <span id="emp">You have done 10 turns of conversation! Please click the button below to continue. </span>')
964
+ continue_button3 = gr.Button("Continue to the next step")
965
+
966
+ button_submit_chat3.click(fn=predict, inputs=[mturk_id, strategy_selection3, text_chat3, chat3_history, system_prompt1_convo3, convo_num3, display_chat3], outputs=[display_chat3, chat3_history, text_chat3, output3, proceed_chat3, message_error_message3,strategy_selection3]) # TODO: after hitting 'Send Message', strategy selection and Feedback markdown should be refreshed / reset
967
+
968
+ with gr.Accordion("I am asked to respond 10 times for each situation. What if the chatbot already agrees with me before 10 responses?", open=False):
969
+ gr.Markdown("If the chatbot concurs with you within the first 10 responses, you have the option to terminate the conversation before 10 responses by clicking the button. Please note, to ensure the quality of the dataset, we will conduct a manual review to assess the reasonableness of the agreement, and we will not compensate for conversations where the chatbot did not genuinely reach an agreement. If you engage in at least 10 responses, you are not required to acquire an agreement from the chatbot and you should see a button that clearly says 'You have finished this situation, submit and continue to the next step.'")
970
+ agreement_proceed_button3 = gr.Button("I confirm I have read and understood the statement above and the chatbot indeed agrees with me before I respond 10 times. End the conversation now and proceed to the next step.")
971
+
972
+ with gr.Column(visible=False) as post_training_survey2:
973
+ agreement_proceed_button3.click(fn=proceed_to_next_chat, inputs=[], outputs=[conversation3, post_training_survey2])
974
+ continue_button3.click(fn=proceed_to_next_chat, inputs=[], outputs=[conversation3, post_training_survey2])
975
+
976
+
977
+ survey_post_name2 = gr.Textbox('post_situation2', visible=False)
978
+ # continue_intake1.click(fn=record_survey_answers, inputs=[survey_name1, mturk_id, confident_intake1, worried_intake1, hopeful_intake1, motivated_intake1, fear_intake1, anger_intake1, disgust_intake1, sad_intake1], outputs=[intake_1, intake_2, intake1_error])
979
+ gr.Markdown("""# Post Training Survey - Situation 2""")
980
+ # write a section of survey questions
981
+ situation2_post = gr.Markdown(elem_id='emp')
982
+ goal2_post = gr.Markdown(elem_id='emp')
983
+ difficulty2_post = gr.Markdown(visible=False)
984
+
985
+ confident_post2 = gr.Dropdown(choices=['Strongly Disagree', 'Disagree', 'Somewhat Disagree', 'Neither Agree nor Disagree', 'Somewhat Agree', 'Agree', 'Strongly Agree'], label="I feel **confident** about my ability to achieve my goal through having this conversation", interactive=True)
986
+ worried_post2 = gr.Dropdown(choices=['Strongly Disagree', 'Disagree', 'Somewhat Disagree', 'Neither Agree nor Disagree', 'Somewhat Agree', 'Agree', 'Strongly Agree'], label="I feel **worried** about achieving my goal through having this conversation", interactive=True)
987
+ hopeful_post2 = gr.Dropdown(choices=['Strongly Disagree', 'Disagree', 'Somewhat Disagree', 'Neither Agree nor Disagree', 'Somewhat Agree', 'Agree', 'Strongly Agree'], label="I feel **hopeful** about achieving my goal through having this conversation", interactive=True)
988
+ motivated_post2 = gr.Dropdown(choices=['Strongly Disagree', 'Disagree', 'Somewhat Disagree', 'Neither Agree nor Disagree', 'Somewhat Agree', 'Agree', 'Strongly Agree'], label="I feel **motivated** about having this challenging conversation", interactive=True)
989
+
990
+ # Emotions (negative emotions from Plutchik's wheel of emotions)
991
+ fear_post2 = gr.Dropdown(choices=['Strongly Disagree', 'Disagree', 'Somewhat Disagree', 'Neither Agree nor Disagree', 'Somewhat Agree', 'Agree', 'Strongly Agree'], label="I feel **fearful** about this situation", interactive=True)
992
+ anger_post2 = gr.Dropdown(choices=['Strongly Disagree', 'Disagree', 'Somewhat Disagree', 'Neither Agree nor Disagree', 'Somewhat Agree', 'Agree', 'Strongly Agree'], label="I feel **angry** about this situation", interactive=True)
993
+ disgust_post2 = gr.Dropdown(choices=['Strongly Disagree', 'Disagree', 'Somewhat Disagree', 'Neither Agree nor Disagree', 'Somewhat Agree', 'Agree', 'Strongly Agree'], label="I feel **disgusted** about this situation", interactive=True)
994
+ sad_post2 = gr.Dropdown(choices=['Strongly Disagree', 'Disagree', 'Somewhat Disagree', 'Neither Agree nor Disagree', 'Somewhat Agree', 'Agree', 'Strongly Agree'], label="I feel **sad** about this situation", interactive=True)
995
+
996
+ survey_post2_error = gr.Markdown(elem_id='emp')
997
+ continue_survey_post2 = gr.Button("Continue to the next step")
998
+
999
+ with gr.Column(visible=False) as conversation4:
1000
+ continue_survey_post2.click(fn=record_survey_answers, inputs=[survey_post_name2, mturk_id, confident_post2, worried_post2, hopeful_post2, motivated_post2, fear_post2, anger_post2, disgust_post2, sad_post2], outputs=[post_training_survey2, conversation4, survey_post2_error])
1001
+
1002
+
1003
+ gr.Markdown("""# Conversation 4""")
1004
+ gr.Markdown("""In this section, you will chat with a simulated conversation partner powered by AI. The AI model is instructed to play the role of the person you are talking to. You will chat about the *second* situation you wrote in the qualification task. You will chat without any feedback or reference materials. You are expected to respond ten times. For each conversation turn, you should first identify the best strategy to use in this turn before writing the response using the select strategy.""")
1005
+ gr.Markdown(""" <span id='emp'> The quality of this conversation will be used to determine the bonus. If you are able to use the skills you learned in the previous training conversation well (top 30\% of all the participants), you will be able to get the bonus. </span>""")
1006
+ with gr.Accordion("Open to see the list of DEAR MAN skills", open=True):
1007
+ gr.Markdown("""## DEAR MAN Skills
1008
+ DEAR MAN skills helps obtain objectives effectively in a difficult situation. There are seven skills which start with the letters D, E, A, R, M, A, N. Below, we show the definitions of DEAR MAN skills and give an example for each skill. All the examples are regarding the situation where someone wants to talk to their husband about coming home late without warning them. In the exercise, you should try to use these skills to communicate in the challenging situations you brought up. You can always refer to this list of definitions and examples during the chat. \n
1009
+
1010
+ <span id="emp">Describe</span> Describe the current situation (if necessary). Stick to the facts. Tell the person exactly what you are reacting to. <br/>
1011
+ e.g. <em>You told me you would be home by dinner but you didn't get here until 11.</em> <br/>
1012
+
1013
+ <span id="emp">Express</span> Express your feelings and opinions about the situation. Don't assume that the other person knows how you feel. <br/>
1014
+ e.g. <em>When you come home so late, I start worrying about you.</em> <br/>
1015
+
1016
+ <span id="emp">Assert</span> Assert yourself by asking for what you want or saying no clearly. Do not assume that others will figure out what you want. Remember that others cannot read your mind. <br/>
1017
+ e.g. <em>I would really like it if you would call me when you are going to be late.</em> <br/>
1018
+
1019
+ <span id="emp">Reinforce</span> Reinforce the person ahead of time by explaining positive effects of getting what you want or need. If necessary, also clarify the negative consequences of not getting what you want or need. <br/>
1020
+ e.g. <em>I would be so relieved, and a lot easier to live with, if you do that.</em> <br/>
1021
+
1022
+ <span id="emp">Mindful</span> Keep your focus on your goals. Maintain your position. Don't be distracted. Don't get off the topic. <br/>
1023
+ e.g. <em>I would still like a call</em> <br/>
1024
+
1025
+ <span id="emp">Appear Confident</span> Appear effective and competent. Use a confident voice tone. Avoid saying things like "I'm not sure." <em></em> <br/>
1026
+
1027
+ <span id="emp">Negotiate</span> Be willing to give to get. Offer and ask for other solutions to the problem. Reduce your request. Say no, but offer to do something else or to solve the problem another way. Focus on what will work. <br/>
1028
+ e.g. <em>How about if you text me when you think you might be late?</em> <br/>
1029
+
1030
+ (Source: DBT Skills Training Manual, 2nd Edition. Marsha M. Linehan.) """)
1031
+ convo_num4 = gr.Textbox("convo_4", visible=False)
1032
+ # chat1 = gr.ChatInterface()
1033
+ situation2_convo4 = gr.Markdown(elem_id='emp')
1034
+ goal2_convo4 = gr.Markdown(elem_id='emp')
1035
+ system_prompt2_convo4 = gr.Markdown(visible=False)
1036
+ difficulty2_convo4 = gr.Markdown(visible=False)
1037
+
1038
+ chat4_history = gr.State([])
1039
+
1040
+ with gr.Row():
1041
+ display_chat4 = gr.Chatbot(elem_id="chuanhu_chatbot")
1042
+
1043
+ with gr.Row():
1044
+ strategy_selection4 = gr.Dropdown(['Describe', 'Express', 'Assert','Reinforce', 'Negotiate'], label='Select the most effective strategy', scale=1, interactive=True,multiselect=True, max_choices=7)
1045
+ text_chat4 = gr.Textbox(label='Send response exercising the strategy', scale=2, value="Hi I want to talk to you about my personal time off this year. I have not taken any time off since Jan")
1046
+ button_submit_chat4 = gr.Button("Send", scale=0)
1047
+
1048
+ with gr.Row():
1049
+ message_error_message4 = gr.Markdown(elem_id='emp')
1050
+
1051
+ with gr.Row(visible=False) as proceed_chat4:
1052
+ output4= gr.Markdown('<br/><br/> <span id="emp">You have done 10 turns of conversation! Please click the button below to continue. </span>')
1053
+ continue_button4 = gr.Button("Continue to the next step")
1054
+
1055
+ button_submit_chat4.click(fn=predict, inputs=[mturk_id, strategy_selection4, text_chat4, chat4_history, system_prompt2_convo4, convo_num4, display_chat4], outputs=[display_chat4, chat4_history, text_chat4, output4, proceed_chat4, message_error_message4, strategy_selection4]) # TODO: after hitting 'Send Message', strategy selection and Feedback markdown should be refreshed / reset
1056
+
1057
+ with gr.Accordion("I am asked to respond 10 times for each situation. What if the chatbot already agrees with me before 10 responses?", open=False):
1058
+ gr.Markdown("If the chatbot concurs with you within the first 10 responses, you have the option to terminate the conversation before 10 responses by clicking the button. Please note, to ensure the quality of the dataset, we will conduct a manual review to assess the reasonableness of the agreement, and we will not compensate for conversations where the chatbot did not genuinely reach an agreement. If you engage in at least 10 responses, you are not required to acquire an agreement from the chatbot and you should see a button that clearly says 'You have finished this situation, submit and continue to the next step.'")
1059
+ agreement_proceed_button4 = gr.Button("I confirm I have read and understood the statement above and the chatbot indeed agrees with me before I respond 10 times. End the conversation now and proceed to the next step.")
1060
+
1061
+
1062
+ auth_button.click(fn=auth, inputs=[mturk_id], outputs=[passcode_warning, intro, auth_block, situation1_intake, goal1_intake, difficulty1_intake, situation2_intake, goal2_intake, difficulty2_intake, situation1_convo1, goal1_convo1, difficulty1_convo1, situation1_convo2, goal1_convo2, difficulty1_convo2,situation1_post, goal1_post, difficulty1_post, situation1_convo3, goal1_convo3, difficulty1_convo3, situation2_post, goal2_post, difficulty2_post, situation2_convo4, goal2_convo4, difficulty2_convo4, system_prompt1_convo1, system_prompt1_convo3, system_prompt2_convo4]) # TODO: after hitting 'Send Message', strategy selection and Feedback markdown should be refreshed / reset
1063
+
1064
+ with gr.Column(visible=False) as outtake:
1065
+
1066
+ # outtake survey
1067
+ gr.Markdown("""# Outtake Survey""")
1068
+ survey_outtake = gr.Textbox('outtake_survey', visible=False)
1069
+
1070
+ q1_outtake = gr.Dropdown(choices=['Strongly Agree', 'Agree', 'Somewhat Agree', 'Neither Agree nor Disagree', 'Somewhat Disagree', 'Disagree', 'Strongly Disagree'], label="After using this tool, I have a better understanding of DEAR MAN skills.", interactive=True)
1071
+ q2_outtake = gr.Dropdown(choices=['Strongly Agree', 'Agree', 'Somewhat Agree', 'Neither Agree nor Disagree', 'Somewhat Disagree', 'Disagree', 'Strongly Disagree'], label="Using this tool has been helpful to me in communicating in challenging situations I BROUGHT UP.", interactive=True)
1072
+ q3_outtake = gr.Dropdown(choices=['Strongly Agree', 'Agree', 'Somewhat Agree', 'Neither Agree nor Disagree', 'Somewhat Disagree', 'Disagree', 'Strongly Disagree'], label="Using this tool has been helpful to me in communicating in OTHER situations in the future.", interactive=True)
1073
+ q4_outtake = gr.Dropdown(choices=['Strongly Agree', 'Agree', 'Somewhat Agree', 'Neither Agree nor Disagree', 'Somewhat Disagree', 'Disagree', 'Strongly Disagree'], label="Would you be interested in using this tool again in the future to help you practice difficult conversations?", interactive=True)
1074
+ q5_outtake = gr.Dropdown(choices=["Very Likely", "Likely", "Somewhat Likely", "Neutral", "Somewhat Unlikely", "Unlikely", "Very Unlikely"], label="How likely are you to recommend this tool to a friend?", interactive=True)
1075
+ q6_outtake = gr.Dropdown(choices=["Very helpful", "Helpful", "Somewhat helpful", "Neutral", "Somewhat unhelpful", "Unhelpful", "Very unhelpful"], label="If you had to have a challenging conversation through *email*, how much do you think this practice would have helped you?", interactive=True)
1076
+ q7_outtake = gr.Dropdown(choices=["Very helpful", "Helpful", "Somewhat helpful", "Neutral", "Somewhat unhelpful", "Unhelpful", "Very unhelpful"], label="If you had to have a challenging conversation through *text message*, how much do you think this practice would have helped you?", interactive=True)
1077
+ q8_outtake = gr.Dropdown(choices=["Very helpful", "Helpful", "Somewhat helpful", "Neutral", "Somewhat unhelpful", "Unhelpful", "Very unhelpful"], label="If you had to have a challenging conversation through *phone call*, how much do you think this practice would have helped you?", interactive=True)
1078
+ q9_outtake = gr.Dropdown(choices=["Very helpful", "Helpful", "Somewhat helpful", "Neutral", "Somewhat unhelpful", "Unhelpful", "Very unhelpful"], label="If you had to have a challenging conversation through *in person conversation*, how much do you think this practice would have helped you?", interactive=True)
1079
+ q10_outtake = gr.Dropdown(choices=["Much more helpful", "More helpful", "Somewhat more helpful", "No difference", "Somewhat less helpful", "Less helpful", "Much less helpful"], label="If you could have practiced by practicing out loud using your microphone and hearing the simulated conversation partner through speakers/headphones, do you think having the audio component would have been", interactive=True)
1080
+
1081
+
1082
+
1083
+ additional_feedback = gr.Textbox(label='Please provide any additional comments and/or feedback you have about this tool.')
1084
+
1085
+
1086
+ outtake_error = gr.Markdown(elem_id='emp')
1087
+ continue_outtake = gr.Button("Continue to the next step")
1088
+
1089
+ with gr.Column(visible=False) as outro:
1090
+ continue_outtake.click(fn=record_survey_answers_outtake, inputs=[mturk_id, q1_outtake, q2_outtake, q3_outtake, q4_outtake, q5_outtake, q6_outtake, q7_outtake, q8_outtake, q9_outtake, q10_outtake, additional_feedback], outputs=[outtake, outro, outtake_error])
1091
+
1092
+ gr.Markdown("""Please record the completion code below to prove you have completed the study. YOU WILL BE ASKED TO PROVIDE THIS CODE IN MTURK SYSTEM.""", elem_id='emp')
1093
+ completion_code = gr.Markdown()
1094
+ completion_code_check = gr.Checkbox(label = "I confirm that I have recorded the completion code provided above.")
1095
+ completion_code_error_message = gr.Markdown(elem_id='emp')
1096
+ finish_button = gr.Button("Finish the study")
1097
+
1098
+ agreement_proceed_button4.click(fn=proceed_to_next_chat_final, inputs=[mturk_id], outputs=[conversation4, outtake, completion_code])
1099
+ continue_button4.click(fn=proceed_to_next_chat_final, inputs=[mturk_id], outputs=[conversation4, outtake, completion_code])
1100
+
1101
+ with gr.Column(visible=False) as final:
1102
+ gr.Markdown("""# Thank you for completing the study! You may exit the page now.""")
1103
+
1104
+ finish_button.click(fn=proceed_to_next_chat, inputs=[], outputs=[outro, final]) # 'You must check the box above to continue.', gr.update(visible=False), gr.update(visible=True), ''
1105
+ demo.launch(share=True)
1106
+ # demo.launch()
1107
+
1108
+ conn.close()
1109
+
feedback_generation_function.py ADDED
@@ -0,0 +1,527 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import openai
2
+ import os
3
+ import numpy as np
4
+ import pandas as pd
5
+ from tqdm import tqdm
6
+ import faiss
7
+ from sentence_transformers import SentenceTransformer
8
+ import time
9
+ encoder = SentenceTransformer('all-mpnet-base-v2')
10
+ from sklearn.metrics import classification_report
11
+ from functools import reduce
12
+ import json
13
+
14
+ print ("finished import")
15
+ openai.api_key = os.environ["OPENAI_API_KEY"]
16
+ # MODEL_NAME = 'gpt-3.5-turbo-0613' # GPT 4 alternative: 'gpt-4-0613'
17
+ MODEL_NAME = 'gpt-4-1106-preview'
18
+ MAX_RETRIES = 5
19
+ all_strategy = pd.read_csv("all_strategy_with_generated_reason.csv")
20
+
21
+ def find_knn(target_utterance, search_inventory, top_k):
22
+ all_utterances = search_inventory['message_text'].tolist()
23
+ all_utterances_embeddings = encoder.encode(all_utterances)
24
+ print (all_utterances_embeddings.shape)
25
+ vec_dimension = all_utterances_embeddings.shape[1]
26
+ index = faiss.IndexFlatL2(vec_dimension)
27
+ faiss.normalize_L2(all_utterances_embeddings)
28
+ index.add(all_utterances_embeddings)
29
+
30
+ search_vec = encoder.encode(target_utterance)
31
+ _vector = np.array([search_vec])
32
+ faiss.normalize_L2(_vector)
33
+
34
+ k = index.ntotal
35
+ distances, ann = index.search(_vector, k=k)
36
+
37
+ results = pd.DataFrame({'distances': distances[0], 'ann': ann[0]})
38
+ # print (results.head(5))
39
+ select_ind = results.ann[:top_k].to_list()
40
+ distance_list = results.distances[:top_k].to_list()
41
+
42
+ return search_inventory.iloc[select_ind], distance_list
43
+
44
+ def find_similar_situation(target_situation, list_of_situations, top_k):
45
+ situation_embeddings = encoder.encode(list_of_situations)
46
+ vec_dimension = situation_embeddings.shape[1]
47
+ index = faiss.IndexFlatL2(vec_dimension)
48
+ faiss.normalize_L2(situation_embeddings)
49
+ index.add(situation_embeddings)
50
+
51
+ search_vec = encoder.encode(target_situation)
52
+ _vector = np.array([search_vec])
53
+ faiss.normalize_L2(_vector)
54
+
55
+ k = index.ntotal
56
+ distances, ann = index.search(_vector, k=k)
57
+
58
+ results = pd.DataFrame({'distances': distances[0], 'ann': ann[0]})
59
+
60
+ # print (results.head(top_k))
61
+ # for i in range(top_k):
62
+ # print (results.ann[i], all_utterances[results.ann[i]])
63
+
64
+ select_ind = results.ann[:top_k].to_list()
65
+ return [list_of_situations[i] for i in select_ind]
66
+
67
+ def generate_knn_demonstrations(all_strategy, mode, target_situation, category, u, strategy, top_k_situation, top_k_utterances):
68
+ all_convo = all_strategy['situation'].drop_duplicates().tolist()
69
+ if mode == 'similar_situation_knn':
70
+ # other_convo = all_strategy[all_strategy.conversation_id != convo_id]['context'].drop_duplicates().tolist()
71
+ # target_situation = all_strategy[(all_strategy.conversation_id == convo_id)]['context'].reset_index(drop=True)[0]
72
+ situation_list = find_similar_situation(target_situation, all_convo, top_k_situation)
73
+ # print (situation_list)
74
+ utterances_in_situations = all_strategy[all_strategy['situation'].isin(situation_list)]
75
+ elif mode == 'in_category_knn':
76
+ utterances_in_situations = all_strategy[all_strategy.category == category].reset_index(drop=True)
77
+ elif mode == 'in_category_similar_situation_knn':
78
+ # other_convo_in_category = all_strategy[all_strategy.category == category]['context'].drop_duplicates().tolist()
79
+ # target_situation = all_strategy[(all_strategy.conversation_id == convo_id)]['context'].reset_index(drop=True)[0]
80
+ situation_list = find_similar_situation(target_situation, all_convo, top_k_situation)
81
+ utterances_in_situations = all_strategy[all_strategy['situation'].isin(situation_list)]
82
+ elif mode == 'all_utterances_knn':
83
+ utterances_in_situations = all_strategy
84
+
85
+ strategy_label = 'label_' + strategy
86
+ suggestion_column = 'suggestion_' + strategy
87
+ reason_column = 'reason_' + strategy
88
+ rewrite_column = 'rewrite_' + strategy
89
+ if strategy in ['describe', 'express', 'assert', 'reinforce', 'negotiate']:
90
+ utterances_strong = utterances_in_situations[utterances_in_situations[strategy_label] == 'Strong'].reset_index(drop=True)
91
+ strong_demonstrations, strong_distance = find_knn(u, utterances_strong, top_k_utterances)
92
+ strong_demonstrations = strong_demonstrations.reset_index(drop=True)
93
+ utterances_weak = utterances_in_situations[utterances_in_situations[strategy_label] == 'Weak'].reset_index(drop=True)
94
+ weak_demonstrations, weak_distance = find_knn(u, utterances_weak, top_k_utterances)
95
+ weak_demonstrations = weak_demonstrations.reset_index(drop=True)
96
+ utterances_no = utterances_in_situations[utterances_in_situations[strategy_label] == 'No'].reset_index(drop=True)
97
+ none_demonstrations, none_distance = find_knn(u, utterances_no, top_k_utterances)
98
+ none_demonstrations = none_demonstrations.reset_index(drop=True)
99
+
100
+
101
+ list_strong = [(strong_demonstrations['situation'][i], strong_demonstrations['message_id'][i], strong_demonstrations['message_text'][i], strong_demonstrations[suggestion_column][i], strong_demonstrations[reason_column][i], strong_demonstrations[rewrite_column][i]) for i in range(len(strong_demonstrations))] #ADD
102
+ list_weak = [(weak_demonstrations['situation'][i], weak_demonstrations['message_id'][i], weak_demonstrations['message_text'][i], weak_demonstrations[suggestion_column][i], weak_demonstrations[reason_column][i], weak_demonstrations[rewrite_column][i]) for i in range(len(weak_demonstrations))] #ADD
103
+ list_none = [(none_demonstrations['situation'][i], none_demonstrations['message_id'][i], none_demonstrations['message_text'][i], none_demonstrations[suggestion_column][i], none_demonstrations[reason_column][i], none_demonstrations[rewrite_column][i]) for i in range(len(none_demonstrations))] #ADD
104
+ # print (strong_demonstrations['message_text'], weak_demonstrations['message_text'], none_demonstrations['message_text'])
105
+
106
+ all_distance = strong_distance + weak_distance + none_distance
107
+ return list_strong, list_weak, list_none, all_distance
108
+
109
+ elif strategy in ['mindful', 'confident']:
110
+ utterances_strong = utterances_in_situations[utterances_in_situations[strategy_label] == 'Yes'].reset_index(drop=True)
111
+ strong_demonstrations, strong_distance = find_knn(u, utterances_strong, top_k_utterances)
112
+ strong_demonstrations = strong_demonstrations.reset_index(drop=True)
113
+ utterances_weak = utterances_in_situations[utterances_in_situations[strategy_label] == 'No'].reset_index(drop=True)
114
+ weak_demonstrations, weak_distance = find_knn(u, utterances_weak, top_k_utterances)
115
+ weak_demonstrations = weak_demonstrations.reset_index(drop=True)
116
+ # return strong_demonstrations, weak_demonstrations
117
+ list_strong = [(strong_demonstrations['situation'][i], strong_demonstrations['message_id'][i], strong_demonstrations['message_text'][i], strong_demonstrations[suggestion_column][i], strong_demonstrations[reason_column][i], strong_demonstrations[rewrite_column][i]) for i in range(len(strong_demonstrations))] # ADD
118
+ list_weak = [(weak_demonstrations['situation'][i], weak_demonstrations['message_id'][i], weak_demonstrations['message_text'][i], weak_demonstrations[suggestion_column][i], weak_demonstrations[reason_column][i], weak_demonstrations[rewrite_column][i]) for i in range(len(weak_demonstrations))] # ADD
119
+
120
+ all_distance = strong_distance + weak_distance
121
+ return list_strong, list_weak, '', all_distance
122
+
123
+ def form_prompt_from_demonstrations(list_strong, list_weak, list_none, strategy, prompt_strategy, include_improve, cot_dict, zip_reorder=True):
124
+ # list_strong:
125
+ # (strong_demonstrations['context'][i], strong_demonstrations['message_id'][i], strong_demonstrations['message_text'][i], strong_demonstrations[suggestion_column][i], strong_demonstrations[reason_column][i])
126
+ strategy_cap = strategy[0].upper() + strategy[1:]
127
+
128
+ if strategy == 'describe':
129
+ strong_improve_str = f"This is a great {strategy_cap}! It sticks to the facts, makes no judgemental statements, and is objective."
130
+ elif strategy == 'express':
131
+ strong_improve_str = f"This is a great {strategy_cap}! It express your feeling or opinions explicitly."
132
+ elif strategy == 'assert':
133
+ strong_improve_str = f"This is a great {strategy_cap}! It is clear, concise, and to the point."
134
+ elif strategy == 'reinforce':
135
+ strong_improve_str = f"This is a great {strategy_cap}! It reinforces the other person."
136
+ elif strategy == 'negotiate':
137
+ strong_improve_str = f"This is a great {strategy_cap}! It shows that you are trying to find an alternative solution."
138
+ elif strategy == 'mindful':
139
+ strong_improve_str = f"This utterance shows mindfulness. You focused on your goal, and did not get distracted or get off topic."
140
+ elif strategy == 'confident':
141
+ strong_improve_str = f"This utterance shows confidence. You used a confident tone. The statement was effective and competent."
142
+
143
+ # weak_improve = [list(weak_demonstrations[suggestion_column])[i] for i in range(actual_top_k_weak)]
144
+ weak_improve = [list_weak[i][3] for i in range(len(list_weak))]
145
+
146
+ if strategy in ['describe', 'express', 'assert', 'reinforce', 'negotiate']:
147
+ # none_improve = [list(none_demonstrations[suggestion_column])[i] for i in range(actual_top_k_none)]
148
+ none_improve = [list_none[i][3] for i in range(len(list_none))]
149
+
150
+ strong_rating = f"Strong {strategy_cap}"
151
+ weak_rating = f"Weak {strategy_cap}"
152
+ if strategy in ['describe', 'express', 'assert', 'reinforce', 'negotiate']:
153
+ strong_rating = f"Strong {strategy_cap}"
154
+ weak_rating = f"Weak {strategy_cap}"
155
+ none_rating = f"No {strategy_cap}"
156
+ elif strategy in ['mindful', 'confident']:
157
+ strong_rating = "Yes"
158
+ weak_rating = "No"
159
+
160
+
161
+ user_prompt = ''
162
+ if prompt_strategy == 'CoT':
163
+ if strategy in ['mindful', 'confident']:
164
+ if strategy == 'mindful': answer_subquestion_yes, answer_subquestion_no = 'No', 'Yes'
165
+ elif strategy == 'confident': answer_subquestion_yes, answer_subquestion_no = 'Yes', 'No'
166
+ for i in range(len(list_strong)):
167
+ if include_improve:
168
+ user_prompt += f"Context: {list_strong[i][0]}, Utterance: {list_strong[i][2]}, {cot_dict[strategy][0]}{answer_subquestion_yes}, {strategy_cap} Rating: {strong_rating}, Suggestion for improvement: {strong_improve_str}\n"
169
+ else:
170
+ user_prompt += f"Context: {list_strong[i][0]}, Utterance: {list_strong[i][2]}, {cot_dict[strategy][0]}{answer_subquestion_yes}, {strategy_cap} Rating: {strong_rating}\n"
171
+ for i in range(len(list_weak)):
172
+ if include_improve:
173
+ user_prompt += f"Context: {list_weak[i][0]}, Utterance: {list_weak[i][2]}, {cot_dict[strategy][0]}{answer_subquestion_no}, {strategy_cap} Rating: {weak_rating}, Suggestion for improvement: {list_weak[i][3]}\n"
174
+ else:
175
+ user_prompt += f"Context: {list_weak[i][0]}, Utterance: {list_weak[i][2]}, {cot_dict[strategy][0]}{answer_subquestion_no}, {strategy_cap} Rating: {weak_rating}\n"
176
+ elif strategy in ['describe', 'express', 'assert', 'reinforce', 'negotiate']:
177
+ for i in range(len(list_strong)):
178
+ if include_improve:
179
+ user_prompt += f"Context: {list_strong[i][0]}, Utterance: {list_strong[i][2]}, {cot_dict[strategy][0]}Yes, {cot_dict[strategy][1]}Yes, {strategy_cap} Rating: {strong_rating}, Suggestion for improvement: {strong_improve_str}\n"
180
+ else:
181
+ user_prompt += f"Context: {list_strong[i][0]}, Utterance: {list_strong[i][2]}, {cot_dict[strategy][0]}Yes, {cot_dict[strategy][1]}Yes, {strategy_cap} Rating: {strong_rating}\n"
182
+ for i in range(len(list_weak)):
183
+ if include_improve:
184
+ user_prompt += f"Context: {list_weak[i][0]}, Utterance: {list_weak[i][2]}, {cot_dict[strategy][0]}Yes, {cot_dict[strategy][1]}No, {strategy_cap} Rating: {weak_rating}, Suggestion for improvement: {list_weak[i][3]}\n"
185
+ else:
186
+ user_prompt += f"Context: {list_weak[i][0]}, Utterance: {list_weak[i][2]}, {cot_dict[strategy][0]}Yes, {cot_dict[strategy][1]}No, {strategy_cap} Rating: {weak_rating}\n"
187
+ for i in range(len(list_none)):
188
+ if include_improve:
189
+ user_prompt += f"Context: {list_none[i][0]}, Utterance: {list_none[i][2]}, {cot_dict[strategy][0]}No, {strategy_cap} Rating: {none_rating}, Suggestion for improvement: {list_none[i][3]}\n" # TODO: one question or two questions for None situation?n
190
+ else:
191
+ user_prompt += f"Context: {list_none[i][0]}, Utterance: {list_none[i][2]}, {cot_dict[strategy][0]}No, {strategy_cap} Rating: {none_rating}\n"
192
+
193
+
194
+ elif prompt_strategy == 'CoT-reason':
195
+ if strategy in ['mindful', 'confident']:
196
+ if strategy == 'mindful': answer_subquestion_yes, answer_subquestion_no = 'No', 'Yes'
197
+ elif strategy == 'confident': answer_subquestion_yes, answer_subquestion_no = 'Yes', 'No'
198
+ for i in range(len(list_strong)):
199
+ if include_improve:
200
+ user_prompt += f"Context: {list_strong[i][0]}, Utterance: {list_strong[i][2]}, {cot_dict[strategy][0]}{answer_subquestion_yes}, Reason for rating: {list_strong[i][4]}, {strategy_cap} Rating: {strong_rating}, Suggestion for improvement: {strong_improve_str}###"
201
+ else:
202
+ user_prompt += f"Context: {list_strong[i][0]}, Utterance: {list_strong[i][2]}, {cot_dict[strategy][0]}{answer_subquestion_yes}, Reason for rating: {list_strong[i][4]}, {strategy_cap} Rating: {strong_rating}\n"
203
+ for i in range(len(list_weak)):
204
+ if include_improve:
205
+ user_prompt += f"Context: {list_weak[i][0]}, Utterance: {list_weak[i][2]}, {cot_dict[strategy][0]}{answer_subquestion_no}, Reason for rating: {list_weak[i][4]}, {strategy_cap} Rating: {weak_rating}, Suggestion for improvement: {list_weak[i][3]}###"
206
+ else:
207
+ user_prompt += f"Context: {list_weak[i][0]}, Utterance: {list_weak[i][2]}, {cot_dict[strategy][0]}{answer_subquestion_no}, Reason for rating: {list_weak[i][4]}, {strategy_cap} Rating: {weak_rating}\n"
208
+ elif strategy in ['describe', 'express', 'assert', 'reinforce', 'negotiate']:
209
+ if include_improve:
210
+ strong_prompts_list = [f"Context: {list_strong[i][0]}, Utterance: {list_strong[i][2]}, {cot_dict[strategy][0]}Yes, {cot_dict[strategy][1]}Yes, Reason for rating: {list_strong[i][4]}, {strategy_cap} Rating: {strong_rating}, Suggestion for improvement: {strong_improve_str}###" for i in range(len(list_strong))]
211
+ strong_prompts = ''.join(strong_prompts_list)
212
+
213
+ weak_prompts_list = [f"Context: {list_weak[i][0]}, Utterance: {list_weak[i][2]}, {cot_dict[strategy][0]}Yes, {cot_dict[strategy][1]}No, Reason for rating: {list_weak[i][4]}, {strategy_cap} Rating: {weak_rating}, Suggestion for improvement: {list_weak[i][3]}###" for i in range(len(list_weak))]
214
+ weak_prompts = ''.join(weak_prompts_list)
215
+
216
+ none_prompts_list = [f"Context: {list_none[i][0]}, Utterance: {list_none[i][2]}, {cot_dict[strategy][0]}No, Reason for rating: {list_none[i][4]}, {strategy_cap} Rating: {none_rating}, Suggestion for improvement: {list_none[i][3]}###" for i in range(len(list_none))]
217
+ none_prompts = ''.join(none_prompts_list)
218
+
219
+ # if zip_reorder:
220
+ user_prompt_list = []
221
+ for s,w,n in zip(strong_prompts_list, weak_prompts_list, none_prompts_list):
222
+ user_prompt_list.extend([s,w,n])
223
+
224
+ user_prompt = ''.join(user_prompt_list)
225
+ # else:
226
+ # user_prompt = strong_prompts + weak_prompts + none_prompts
227
+
228
+ elif prompt_strategy == 'reason':
229
+ if strategy in ['mindful', 'confident']:
230
+ if strategy == 'mindful': answer_subquestion_yes, answer_subquestion_no = 'No', 'Yes'
231
+ elif strategy == 'confident': answer_subquestion_yes, answer_subquestion_no = 'Yes', 'No'
232
+ if include_improve:
233
+ strong_prompts_list = [f"Context: {list_strong[i][0]} Utterance: {list_strong[i][2]} Step 1 - Reason for rating: {list_strong[i][4]}### Step 2 - {strategy_cap} Rating: {strong_rating}### Step 3 - Suggestion for improvement: {strong_improve_str}###" for i in range(len(list_strong))]
234
+ strong_prompts = ''.join(strong_prompts_list)
235
+
236
+ weak_prompts_list = [f"Context: {list_weak[i][0]} Utterance: {list_weak[i][2]} Step 1 - Reason for rating: {list_weak[i][4]}### Step 2 - {strategy_cap} Rating: {weak_rating}### Step 3 - Suggestion for improvement: {list_weak[i][3]}###" for i in range(len(list_weak))]
237
+ weak_prompts = ''.join(weak_prompts_list)
238
+
239
+ # none_prompts_list = [f"Context: {list_none[i][0]}, Utterance: {list_none[i][2]}, Reason for rating: {list_none[i][4]}, {strategy_cap} Rating: {none_rating}, Suggestion for improvement: {list_none[i][3]}###" for i in range(len(list_none))]
240
+ # none_prompts = ''.join(none_prompts_list)
241
+
242
+ if zip_reorder:
243
+ # if zip_reorder:
244
+ user_prompt_list = []
245
+ for s,w in zip(strong_prompts_list, weak_prompts_list):
246
+ user_prompt_list.extend([s,w])
247
+ user_prompt = ''.join(user_prompt_list)
248
+ else:
249
+ user_prompt = strong_prompts + weak_prompts + none_prompts
250
+
251
+ elif strategy in ['describe', 'express', 'assert', 'reinforce', 'negotiate']:
252
+ if include_improve:
253
+ # print ("right prompt construction")
254
+ strong_prompts_list = [f"Context: {list_strong[i][0]} Utterance: {list_strong[i][2]} Step 1 - Reason for rating: {list_strong[i][4]}### Step 2 - {strategy_cap} Rating: {strong_rating}### Step 3 - Suggestion for improvement: {strong_improve_str}###" for i in range(len(list_strong))]
255
+ strong_prompts = ''.join(strong_prompts_list)
256
+
257
+ weak_prompts_list = [f"Context: {list_weak[i][0]} Utterance: {list_weak[i][2]} Step 1 - Reason for rating: {list_weak[i][4]}### Step 2 - {strategy_cap} Rating: {weak_rating}### Step 3 -Suggestion for improvement: {list_weak[i][3]}###" for i in range(len(list_weak))]
258
+ weak_prompts = ''.join(weak_prompts_list)
259
+
260
+ none_prompts_list = [f"Context: {list_none[i][0]} Utterance: {list_none[i][2]} Step 1 - Reason for rating: {list_none[i][4]}### Step 2 -{strategy_cap} Rating: {none_rating}### Step 3 -Suggestion for improvement: {list_none[i][3]}###" for i in range(len(list_none))]
261
+ none_prompts = ''.join(none_prompts_list)
262
+
263
+ # print (len(strong_prompts_list), len(weak_prompts_list), len(none_prompts_list))
264
+
265
+ if zip_reorder:
266
+ # if zip_reorder:
267
+ user_prompt_list = []
268
+ for s,w,n in zip(strong_prompts_list, weak_prompts_list, none_prompts_list):
269
+ user_prompt_list.extend([s,w,n])
270
+
271
+ user_prompt = ''.join(user_prompt_list)
272
+ else:
273
+ user_prompt = strong_prompts + weak_prompts + none_prompts
274
+ # elif prompt_strategy == 'reason':
275
+ # if strategy in ['mindful', 'confident']:
276
+ # if strategy == 'mindful': answer_subquestion_yes, answer_subquestion_no = 'No', 'Yes'
277
+ # elif strategy == 'confident': answer_subquestion_yes, answer_subquestion_no = 'Yes', 'No'
278
+ # for i in range(len(list_strong)):
279
+ # if include_improve:
280
+ # user_prompt += f"Context: {list_strong[i][0]}, Utterance: {list_strong[i][2]}, Reason for rating: {list_strong[i][4]}, {strategy_cap} Rating: {strong_rating}, Suggestion for improvement: {strong_improve_str}###"
281
+ # else:
282
+ # user_prompt += f"Context: {list_strong[i][0]}, Utterance: {list_strong[i][2]}, Reason for rating: {list_strong[i][4]}, {strategy_cap} Rating: {strong_rating}\n"
283
+ # for i in range(len(list_weak)):
284
+ # if include_improve:
285
+ # user_prompt += f"Context: {list_weak[i][0]}, Utterance: {list_weak[i][2]}, Reason for rating: {list_weak[i][4]}, {strategy_cap} Rating: {weak_rating}, Suggestion for improvement: {list_weak[i][3]}###"
286
+ # else:
287
+ # user_prompt += f"Context: {list_weak[i][0]}, Utterance: {list_weak[i][2]}, Reason for rating: {list_weak[i][4]}, {strategy_cap} Rating: {weak_rating}\n"
288
+ # elif strategy in ['describe', 'express', 'assert', 'reinforce', 'negotiate']:
289
+ # for i in range(len(list_strong)):
290
+ # if include_improve:
291
+ # user_prompt += f"Context: {list_strong[i][0]}, Utterance: {list_strong[i][2]}, Reason for rating: {list_strong[i][4]}, {strategy_cap} Rating: {strong_rating}, Suggestion for improvement: {strong_improve_str}###"
292
+ # else:
293
+ # user_prompt += f"Context: {list_strong[i][0]}, Utterance: {list_strong[i][2]}, Reason for rating: {list_strong[i][4]}, {strategy_cap} Rating: {strong_rating}\n"
294
+ # for i in range(len(list_weak)):
295
+ # if include_improve:
296
+ # user_prompt += f"Context: {list_weak[i][0]}, Utterance: {list_weak[i][2]}, Reason for rating: {list_weak[i][4]}, {strategy_cap} Rating: {weak_rating}, Suggestion for improvement: {list_weak[i][3]}###"
297
+ # else:
298
+ # user_prompt += f"Context: {list_weak[i][0]}, Utterance: {list_weak[i][2]}, Reason for rating: {list_weak[i][4]}, {strategy_cap} Rating: {weak_rating}\n"
299
+ # for i in range(len(list_none)):
300
+ # if include_improve:
301
+ # user_prompt += f"Context: {list_none[i][0]}, Utterance: {list_none[i][2]}, Reason for rating: {list_none[i][4]}, {strategy_cap} Rating: {none_rating}, Suggestion for improvement: {list_none[i][3]}###" # TODO: one question or two questions for None situation?n
302
+ # else:
303
+ # user_prompt += f"Context: {list_none[i][0]}, Utterance: {list_none[i][2]}, Reason for rating: {list_none[i][4]}, {strategy_cap} Rating: {none_rating}\n"
304
+
305
+ else:
306
+ for i in range(len(list_strong)):
307
+ if include_improve:
308
+ user_prompt += f"Context: {list_strong[i][0]}, Utterance: {list_strong[i][2]}, {strategy_cap} Rating: {strong_rating}, Suggestion for improvement: {strong_improve_str}###"
309
+ else:
310
+ user_prompt += f"Context: {list_strong[i][0]}, Utterance: {list_strong[i][2]}, {strategy_cap} Rating: {strong_rating}\n"
311
+ for i in range(len(list_weak)):
312
+ if include_improve:
313
+ user_prompt += f"Context: {list_weak[i][0]}, Utterance: {list_weak[i][2]}, {strategy_cap} Rating: {weak_rating}, Suggestion for improvement: {list_weak[i][2]}###"
314
+ else:
315
+ user_prompt += f"Context: {list_weak[i][0]}, Utterance: {list_weak[i][2]}, {strategy_cap} Rating: {weak_rating}\n"
316
+ if strategy in ['describe', 'express', 'assert', 'reinforce', 'negotiate']:
317
+ for i in range(len(list_none)):
318
+ if include_improve:
319
+ user_prompt += f"Context: {list_none[i][0]}, Utterance: {list_none[i][2]}, {strategy_cap} Rating: {none_rating}, Suggestion for improvement: {list_none[i][3]}###"
320
+ else:
321
+ user_prompt += f"Context: {list_none[i][0]}, Utterance: {list_none[i][2]}, {strategy_cap} Rating: {none_rating}\n"
322
+ print(user_prompt)
323
+ return user_prompt
324
+
325
+ def generate_feedback(current_situation, category, u, prompt_strategy, prompt_selection, strategy_list):
326
+ # parse strategy
327
+ strategy = strategy_list[0]
328
+ strategy = strategy[0].lower() + strategy[1:]
329
+ print (f"Generating feedback for {strategy}")
330
+
331
+ # parse category
332
+ cate = category[0].lower() + category[1:]
333
+
334
+
335
+ # load files once, move to user_study_interface.py
336
+ with open('prompts.json', 'r') as fp:
337
+ system_prompts = json.load(fp)
338
+
339
+ print ("There are in total {} utterances".format(len(all_strategy)))
340
+
341
+ list_of_convo = all_strategy['conversation_id'].drop_duplicates().tolist()
342
+ print (list_of_convo)
343
+ all_convo_results = pd.DataFrame()
344
+
345
+ dict_CoT = {
346
+ 'describe': ['Answer in Yes or No: The utterance is or contains a description of the given context. Answer:', 'Answer in Yes or No: The utterance sticks to the fact, makes no judgemental statement, and is objective. Answer:'],
347
+ 'express': ['Answer in Yes or No: The utterance is or contains an expression of the speaker\'s feelings. Answer:', 'Answer in Yes or No: The expression of feelings in the utterance is clear and explicit. Answer:'],
348
+ 'assert': ['Answer in Yes or No: The utterance is or contains an ask for what the speaker wants. Answer:', 'Answer in Yes or No: The ask in the utterance is clear and explicit, or the speaker is saying no clearly and explicitly. Answer:'],
349
+ 'reinforce': ['Answer in Yes or No: The utterance is or contains a reinforcement of a reward for the other person. Answer:', 'Answer in Yes or No: The reinforcement in the utterance is targeted to the other person and is communicated clearly. Answer:'],
350
+ 'negotiate': ['Answer in Yes or No: The utterance offers a compromise or an alternative solution. Answer:', 'Answer in Yes or No: The compromise or alternative solution in the utterance is clear and explicit. Answer:'], # TODO: add weak description from clusters
351
+ 'mindful':['Answer in Yes or No: The utterance shows that the speaker is responding to attacks and criticism or is losing track of their goals. Answer:'], # REVERSE!
352
+ 'confident': ['Answer in Yes or No: The utterance shows a confident tone, and is effective and competent in conveying the speaker\'s goal. Answer:'],
353
+ }
354
+
355
+
356
+ system_prompt = system_prompts[prompt_strategy][strategy]
357
+
358
+ start_time = time.time()
359
+ current_tries = 1
360
+ strategy_cap = strategy[0].upper() + strategy[1:]
361
+
362
+ # User Prompt
363
+ # if prompt_selection == "knn":
364
+ # user_prompt = get_knn_prompt(u, top_k, True, index_knn, args.strategy, prompt_strategy, dict_CoT)
365
+ if prompt_selection in ("in_category_similar_situation_knn", "similar_situation_knn", "in_category_knn", "all_utterances_knn") :
366
+ print ("right")
367
+ strong_, weak_, none_, knn_distance = generate_knn_demonstrations(all_strategy, prompt_selection, current_situation, cate, u, strategy, top_k_situation=5, top_k_utterances=3) #all_strategy, mode, target_situation, category, u, strategy, top_k_situation, top_k_utterances
368
+ user_prompt = form_prompt_from_demonstrations(strong_, weak_, none_, strategy, prompt_strategy, True, dict_CoT)
369
+
370
+ elif prompt_selection == "zero_shot":
371
+ user_prompt = ''
372
+
373
+ # Current Prompt
374
+ if prompt_strategy == "CoT" or prompt_strategy == "CoT-reason" :
375
+ current_prompt = f"Context: {current_situation}, Utterance: {u},"
376
+ elif prompt_strategy == "reason":
377
+ current_prompt = f"Context: {current_situation}, Utterance: {u}, Reason for rating:"
378
+ else:
379
+ current_prompt = f"Context: {current_situation}, Utterance: {u}, {strategy_cap} Rating:"
380
+
381
+ prompt = [{"role":"system", "content":system_prompt}, {"role":"user", "content": user_prompt+current_prompt}]
382
+
383
+ print ("Full prompt: ", prompt)
384
+ while current_tries <= MAX_RETRIES:
385
+ try:
386
+ response = openai.ChatCompletion.create(
387
+ model=MODEL_NAME,
388
+ messages = prompt,
389
+ max_tokens = 256,
390
+ temperature = 0,
391
+ )
392
+
393
+ curr_response_str = response['choices'][0]['message']['content'].replace('\n', ' ').strip()
394
+ # print (curr_response_str, '\t')
395
+
396
+ break
397
+ except Exception as e:
398
+ print('error: ', str(e))
399
+ print('response retrying')
400
+ current_tries += 1
401
+ if current_tries > MAX_RETRIES:
402
+ break
403
+ time.sleep(5)
404
+ time_taken = time.time() - start_time
405
+ print (f'Time taken for this utterance: {time_taken}')
406
+ try:
407
+ rating_list = curr_response_str.split(f"{strategy_cap} Rating: ", 1)[1].split(" ", 2)[:2].replace('[,.#]', '', regex=True)
408
+ rating = ' '.join(rating_list)
409
+ suggestion = curr_response_str.split(f"{strategy_cap} Rating: ", 1)[1].split(" ", 2)[2:][0].split("###", 1)[0]
410
+ output = rating + '. \n' + suggestion
411
+ except:
412
+ output = curr_response_str
413
+
414
+ return output
415
+
416
+ # def generate_feedback_with_mc(current_situation, category, u, prompt_strategy, prompt_selection, strategy_list):
417
+ # strategy_output = generate_feedback(current_situation, category, u, prompt_strategy, prompt_selection, strategy_list)
418
+ # mindful_output = generate_feedback(current_situation, category, u, prompt_strategy, prompt_selection, ['mindful'])
419
+ # confident_output = generate_feedback(current_situation, category, u, prompt_strategy, prompt_selection, ['confident'])
420
+
421
+ # print (strategy_output, mindful_output, confident_output)
422
+ # all_concat = strategy_output + '\n' + mindful_output + '\n' + confident_output
423
+
424
+ # return all_concat
425
+
426
+ def generate_feedback_with_mc(current_situation, category, u, prompt_strategy, prompt_selection, strategy_list):
427
+ strategy_output = generate_feedback(current_situation, category, u, prompt_strategy, prompt_selection, strategy_list)
428
+ mindful_output = generate_feedback(current_situation, category, u, prompt_strategy, prompt_selection, ['mindful'])
429
+ confident_output = generate_feedback(current_situation, category, u, prompt_strategy, prompt_selection, ['confident'])
430
+
431
+ strategy = strategy_list[0]
432
+ strategy_rating = strategy_output.split(f'{strategy} Rating:')[1].split('###')[0].strip()
433
+ strategy_suggestion = strategy_output.split(f'{strategy} Rating:')[1].split('Suggestion for improvement: ')[1].split('###')[0].strip()
434
+
435
+ strategy_feedback = strategy_rating + '<br/>' + strategy_suggestion
436
+
437
+ mindful_rating = mindful_output.split('Mindful Rating:')[1].split('###')[0].strip()
438
+
439
+ if mindful_rating != 'Yes' and mindful_rating != 'No':
440
+ mindful_feedback = ''
441
+ elif mindful_rating == 'Yes':
442
+ mindful_feedback = "Mindfulness check: Well done! &#128077; "
443
+ else:
444
+ mindful_feedback = "Mindfulness check: " + mindful_output.split('Mindful Rating:')[1].split('Suggestion for improvement: ')[1].split('###')[0].strip()
445
+
446
+
447
+ confident_rating = confident_output.split('Confident Rating:')[1].split('###')[0].strip()
448
+
449
+ if confident_rating != 'Yes' and confident_rating != 'No':
450
+ confident_feedback = ''
451
+ elif confident_rating == 'Yes':
452
+ confident_feedback = "Confidence check: Well done! &#128077; "
453
+ else:
454
+ confident_feedback = "Confidence check: " + confident_output.split('Confident Rating:')[1].split('Suggestion for improvement: ')[1].split('###')[0].strip()
455
+
456
+
457
+ print (strategy_output, mindful_output, confident_output)
458
+ all_concat = strategy_feedback + '</br> </br>' + mindful_feedback + '</br>' + confident_feedback
459
+
460
+ return all_concat
461
+
462
+ def generate_skill_suggestion(situation, input_history, demonstration_mode):
463
+
464
+ # format of input_history:
465
+ # [{"role":"system", "content": system_input}] + input_history + [{"role":"user", "content":new_input}]
466
+ #
467
+
468
+ if len(input_history) == 0:
469
+ return "Describe", "You can start the conversation by describing the situation."
470
+ if input_history[-1]['role'] == 'system':
471
+ previous_partner_message = input_history[-1]['content']
472
+ previous_client_message = input_history[-2]['content']
473
+ else:
474
+ previous_partner_message = input_history[-2]['content']
475
+ previous_client_message = input_history[-1]['content']
476
+ prompt_other_message = f'Conversation context: {situation}. I received the response: "{previous_partner_message}" What DEAR MAN strategy should I use next?'
477
+
478
+ prompt = prompt_other_message
479
+ system_prompt_one = "Please suggest the top DEAR MAN skill to use in the next response: describe, express, assert, reinforce, negotiate. In the first line, output only the name of the skill immediately. In the second line, suggestion reason why use this skill. Address the reason in second person perspective. Separate the lines with ###. YOU MUST FOLLOW THIS FORMAT."
480
+ prompt = [{"role":"system", "content":system_prompt_one}, {"role":"user", "content": prompt_other_message}]
481
+
482
+ current_tries=0
483
+ while current_tries <= MAX_RETRIES:
484
+ try:
485
+ response = openai.ChatCompletion.create(
486
+ model=MODEL_NAME,
487
+ messages = prompt,
488
+ max_tokens = 256,
489
+ temperature = 0,
490
+ )
491
+ # print (prompt)k
492
+ curr_response_str = response['choices'][0]['message']['content'].replace('\n', ' ').strip()
493
+ print (curr_response_str, '\t')
494
+ # print ('Suggestion: ', all_strategy[f'suggestion_{strategy}'][m], '\t')
495
+ # model_output.append(curr_response_str)
496
+ break
497
+ except Exception as e:
498
+ print('error: ', str(e))
499
+ print('response retrying')
500
+ current_tries += 1
501
+ if current_tries > MAX_RETRIES:
502
+ break
503
+ time.sleep(5)
504
+
505
+ # suggested_skills = curr_response_str.split('###')[0].split(',')
506
+ # suggested_skills = [skill.strip() for skill in suggested_skills]
507
+ # suggested_skills = [skill[0].upper() + skill[1:].lower() for skill in suggested_skills]
508
+ # suggest_reason = curr_response_str.split('###')[1:]
509
+ # # convert suggest_reason to a string
510
+ # suggest_reason_str = ' '.join(suggest_reason)
511
+ # print (suggest_reason, suggest_reason_str)
512
+ # if len(suggested_skills) == 2:
513
+ # print (suggested_skills[0], suggested_skills[1])
514
+ # return suggested_skills[0], suggested_skills[1], suggest_reason_str
515
+
516
+ suggested_skills = curr_response_str.split('###')[0].split(',')
517
+ suggested_skills = [skill.strip() for skill in suggested_skills]
518
+ suggested_skills = [skill[0].upper() + skill[1:].lower() for skill in suggested_skills]
519
+ suggest_reason = curr_response_str.split('###')[1:]
520
+ suggest_reason_str = ' '.join(suggest_reason)
521
+ print (suggested_skills, suggest_reason_str)
522
+ if len(suggested_skills) == 1:
523
+ return suggested_skills[0], suggest_reason_str
524
+ else:
525
+ print (suggested_skills)
526
+ print ("Suggestion format is wrong")
527
+ return 'Describe', "During the conversation, it is helpful to reground the fact."
mturk_id_situation_goal_difficulty.csv ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ id,situation1,goal1,difficulty1,situation2,goal2,difficulty2
2
+ inna,My boss is really demanding and does not respect personal time. It has been difficult for my team members to get approved for personal time off from her. ,Ask my boss to approve a 2 week vacation.,8,"My husband always comes home late without giving me a heads up and despite my effort to talk to him, he does not change his behavior.",Convince my husband to give me a heads up whenever he needs to come home late.,6
3
+ inna2,"My husband always comes home late without giving me a heads up and despite my effort to talk to him, he does not change his behavior.",Convince my husband to give me a heads up whenever he needs to come home late.,6,My boss is really demanding and does not respect personal time. It has been difficult for my team members to get approved for personal time off from her. ,Ask my boss to approve a 2 week vacation.,8
4
+ mike,MY boss is a micromanager - he acts like he needs to know what I'm doing all the time and it messes with my productivity,Explain how I feel to my boss without offending him or letting him get defensive,6,"My husband always comes home late without giving me a heads up and despite my effort to talk to him, he does not change his behavior.",Convince my husband to give me a heads up whenever he needs to come home late.,6
5
+ galen,"My brother keeps on wanting to bring his girlfriend on our backcountry skiing trips. She's very nice and a good skier, but not quite as fast as the rest of group, so the group dynamics become challenging.",Explain to my brother how I feel about wanting to spend more time skiing just with him.,4,My boss is really demanding and does not respect personal time. It has been difficult for my team members to get approved for personal time off from her. ,Ask my boss to approve a 2 week vacation.,8
prompts.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"CoT-reason": {"describe": "You will be given a context and a utterance, from a conversation that happened in the give context. Does the given utterance describe the given context? To be considered \"describe\", the utterance needs to stick to the facts, make no judgmental statements, and be objective. Do ALL of the following steps: Step 1: Answer the Yes and No questions. Step 2: Generate \"Reasoning for rating\". Step 3: Generate \"Describe Rating\" in \"Strong Describe\", \"Weak Describe\" or \"No Describe\". Rating Rubric: A \"Strong Describe\" rating indicate that the utterance is or contains a description of the given context. It sticks to the facts, makes no judgemental statements, and is objective. A \"Weak Describe\" rating indicates that the utterance is or contains a description of the given context, but needs improvement since it may not stick to the fact, makes some judgemental statements, or is not fully objective. A \"No Describe\" rating indicates that the utterance does not describe any aspect of the given context at all. Step 4: Provide additional comments on the ratings similar to the examples given. Finish each step with ###. Twenty words minimum. YOU MUST DO ALL THE STEPS, and generate until the end token ###", "express": "You will be given a context and a utterance, from a conversation that happened in the give context. Does the given utterance explicitly express how you feel about the given context? To be considered \"express\", the utterance needs to explicitly express your feelings or opinions about the given context, including things like \"this makes me feel\", or \"I feel ... by your actions\". Do the following: 1) Answer the Yes and No questions. 2) Generate \"Reasoning for rating\". 3) Generate \"Express Rating\" in \"Strong Express\", \"Weak Express\" or \"No Express\". Rating Rubric: A \"Strong Express\" rating indicate that the utterance is or contains a clear and explicit expression of your feelings or opinions about the given context. A \"Weak Express\" rating indicates that the utterance is or contains an expression of your feelings or opinions about the given context, but can be made more explicit in expressing feelings. A \"No Express\" rating indicates that the utterance does not express your feelings or opinions about the given context at all. 4) Provide additional comments on the ratings similar to the examples given. Twenty words minimum. Generate until the end token ###", "assert": "You will be given a context and a utterance, from a conversation that happened in the give context. Does the given utterance assert your needs or wants about the given context? To be considered \"assert\", the utterance needs to be asking for what you want or saying no clearly. Do the following: 1) Answer the Yes and No questions. 2) Generate \"Reasoning for rating\". 3) Generate \"Assert Rating\" in \"Strong Assert\", \"Weak Assert\" or \"No Assert\". Rating Rubric: A \"Strong Assert\" rating indicate that the utterance is or contains an assertion of your needs or wants about the given context. A \"Weak Assert\" rating indicates that the utterance is or contains an assertion of your needs or wants about the given context, but needs improvement in making it more explicit or stronger. A \"No Assert\" rating indicates that the utterance does not contain an assertion of the needs or wants. 4) Provide additional comments on the ratings similar to the examples given. Twenty words minimum. Generate until the end token ###", "reinforce": "You will be given a context and a utterance, from a conversation that happened in the give context. Does the given utterance reinforce your needs or wants about the given context? To be considered \"reinforce\", the utterance needs to reinforce some reward for the other person. Rating Rubric: A \"Strong Reinforce\" rating indicate that the utterance is or contains a reinforcement for the other person about the given context. A \"Weak Reinforce\" rating indicates that the utterance is or contains a reinforcement of your needs or wants about the given context, but needs improvement, for example, it may not be a reward for the other person or it is not communicated clearly. A \"No Reinforce\" rating indicates that the utterance does not have a reinforcer for the other person. Do the following: 1) Answer the Yes and No questions, 2) Generate \"Reasoning for rating\", 3) Generate \"Reinforce Rating\" in \"Strong Reinforce\", \"Weak Reinforce\" or \"No Reinforce\", and 4) Provide additional comments on the ratings similar to the examples given. Twenty words minimum. Generate until the end token ###", "negotiate": "You will be given a context and a utterance, from a conversation that happened in the give context. Does the given utterance negotiate your needs or wants about the given context? To be considered \"negotiate\", the utterance needs to be a negotiation of your needs or wants about the given context. Do the following: 1) Answer the Yes and No questions. 2) Generate \"Reasoning for rating\". 3) Generate \"Negotiate Rating\" in \"Strong Negotiate\", \"Weak Negotiate\" or \"No Negotiate\". Rating Rubric: A \"Strong Negotiate\" rating indicate that the utterance is or contains a negotiation of your needs or wants about the given context. A \"Weak Negotiate\" rating indicates that the utterance is or contains a negotiation of your needs or wants about the given context, but needs improvement in making it more explicit or stronger. A \"No Negotiate\" rating indicates that the utterance does not contain a negotiation of the needs or wants. 4) Provide additional comments on the ratings similar to the examples given. Twenty words minimum. Generate until the end token ###", "mindful": "You will be given a context and a utterance, from a conversation that happened in the give context. Does the given utterance show the speaker is being mindful? To be considered \"mindful\", the utterance needs to be stick to the speaker's goal and does not get distracted by what the other person says. Do the following: 1) Answer the Yes and No questions. 2) Generate \"Reason for rating\". 3) Generate \"Mindful Rating\" in \"Yes\" or \"No\". Rating Rubric: A \"Yes\" rating indicate that the utterance is showing mindfulness. A \"No\" rating indicates that the utterance shows a lack of mindfulness, the speaker may be responding to attacks or losing track of their goals. 4) Provide additional comments on the ratings similar to the examples given. Twenty words minimum. Generate until the end token ###", "confident": "You will be given a context and a utterance, from a conversation that happened in the give context. Does the given utterance show the speaker is being confident? To be considered \"confident\", the utterance needs to have a confident tone, is effective and competent in conveying the speaker's goal.Do the following: 1) Answer the Yes and No questions. 2) Generate \"Reason for rating\". 3) Generate \"Confident Rating\" in \"Yes\" or \"No\". Rating Rubric: A \"Yes\" rating indicate that the utterance is showing confidence. A \"No\" rating indicates that the utterance shows a lack of confidence. 4) Provide additional comments on the ratings similar to the examples given. Twenty words minimum. Generate until the end token ###"}, "CoT": {"describe": "You will be given a context and a utterance, from a conversation that happened in the give context. Does the given utterance describe the given context? To be considered \"describe\", the utterance needs to stick to the facts, make no judgmental statements, and be objective. Rating Rubric: A \"Strong Describe\" rating indicate that the utterance is or contains a description of the given context. It sticks to the facts, makes no judgemental statements, and is objective. A \"Weak Describe\" rating indicates that the utterance is or contains a description of the given context, but needs improvement since it may not stick to the fact, makes some judgemental statements, or is not fully objective. A \"No Describe\" rating indicates that the utterance does not describe any aspect of the given context at all. Do the following: 1) Answer the Yes and No questions, 2) Generate the rating in \"Strong Describe\", \"Weak Describe\" or \"No Describe\", and 3) Provide additional comments on the ratings similar to the examples given. Twenty words minimum. Generate until the end token ###", "express": "You will be given a context and a utterance, from a conversation that happened in the give context. Does the given utterance explicitly express how you feel about the given context? To be considered \"express\", the utterance needs to explicitly express your feelings or opinions about the given context, including things like \"this makes me feel\", or \"I feel ... by your actions\". Rating Rubric: A \"Strong Express\" rating indicate that the utterance is or contains a clear and explicit expression of your feelings or opinions about the given context. A \"Weak Express\" rating indicates that the utterance is or contains an expression of your feelings or opinions about the given context, but can be made more explicit in expressing feelings. A \"No Express\" rating indicates that the utterance does not express your feelings or opinions about the given context at all. Do the following: 1) Answer the Yes and No questions, 2) Generate the rating in \"Strong Express\", \"Weak Express\" or \"No Express\", and 3) Provide additional comments on the ratings similar to the examples given. Twenty words minimum. Generate until the end token ###", "assert": "You will be given a context and a utterance, from a conversation that happened in the give context. Does the given utterance assert your needs or wants about the given context? To be considered \"assert\", the utterance needs to be asking for what you want or saying no clearly. Rating Rubric: A \"Strong Assert\" rating indicate that the utterance is or contains an assertion of your needs or wants about the given context. A \"Weak Assert\" rating indicates that the utterance is or contains an assertion of your needs or wants about the given context, but needs improvement in making it more explicit or stronger. A \"No Assert\" rating indicates that the utterance does not contain an assertion of the needs or wants. Do the following: 1) Answer the Yes and No questions, 2) Generate the rating in \"Strong Assert\", \"Weak Assert\" or \"No Assert\", and 3) Provide additional comments on the ratings similar to the examples given. Twenty words minimum. Generate until the end token ###", "reinforce": "You will be given a context and a utterance, from a conversation that happened in the give context. Does the given utterance reinforce your needs or wants about the given context? To be considered \"reinforce\", the utterance needs to reinforce some reward for the other person. Rating Rubric: A \"Strong Reinforce\" rating indicate that the utterance is or contains a reinforcement for the other person about the given context. A \"Weak Reinforce\" rating indicates that the utterance is or contains a reinforcement of your needs or wants about the given context, but needs improvement, for example, it may not be a reward for the other person or it is not communicated clearly. A \"No Reinforce\" rating indicates that the utterance does not have a reinforcer for the other person. Do the following: 1) Answer the Yes and No questions, 2) Generate the rating in \"Strong Reinforce\", \"Weak Reinforce\" or \"No Reinforce\", and 3) Provide additional comments on the ratings similar to the examples given. Twenty words minimum. Generate until the end token ###", "negotiate": "You will be given a context and a utterance, from a conversation that happened in the give context. Does the given utterance contain a negotiation? To be considered \"negotiate\", the utterance needs to offer and ask for other solutions in the given context. Rating Rubric: A \"Strong Negotiate\" rating indicate that the utterance offers or asks clearly for an alternative solution. A \"Weak Negotiate\" rating indicates that the utterance is or contains a negotiation of your needs or wants about the given context, but may not be clear enough and needs improvement. A \"No Negotiate\" rating indicates that the utterance does not contain any negotiation at all. Do the following: 1) Answer the Yes and No questions, 2) Generate the rating in \"Strong Negotiate\", \"Weak Negotiate\" or \"No Negotiate\", and 3) Provide additional comments on the ratings similar to the examples given. Twenty words minimum. Generate until the end token ###", "mindful": "You will be given a context and a utterance, from a conversation that happened in the give context. Does the given utterance show the speaker is being mindful? To be considered \"mindful\", the utterance needs to be stick to the speaker's goal and does not get distracted by what the other person says. Rating Rubric: A \"Yes\" rating indicate that the utterance is showing mindfulness. A \"No\" rating indicates that the utterance shows a lack of mindfulness, the speaker may be responding to attacks or losing track of their goals. Do the following: 1) Answer the Yes and No questions, 2) Generate the rating in \"Yes\" or \"No\", and 3) Provide additional comments on the ratings similar to the examples given. Twenty words minimum. Generate until the end token ###", "confident": "You will be given a context and a utterance, from a conversation that happened in the give context. Does the given utterance show the speaker is being confident? To be considered \"confident\", the utterance needs to have a confident tone, is effective and competent in conveying the speaker's goal. Rating Rubric: A \"Yes\" rating indicate that the utterance is showing confidence. A \"No\" rating indicates that the utterance shows a lack of confidence. Do the following: 1) Answer the Yes and No questions, 2) Generate the rating in \"Yes\" or \"No\", and 3) Provide additional comments on the ratings similar to the examples given. Twenty words minimum. Generate until the end token ###"}, "reason": {"describe": "You will be given a context and a utterance, from a conversation that happened in the give context. Does the given utterance describe the given context? To be considered \"describe\", the utterance needs to stick to the facts, make no judgmental statements, and be objective. Rating Rubric: A \"Strong Describe\" rating indicate that the utterance is or contains a description of the given context. It sticks to the facts, makes no judgemental statements, and is objective. Do ALL of the following three steps. Step 1: Generate \"Reasoning for rating\". Step 2: Generate \"Describe Rating\" in \"Strong Describe\", \"Weak Describe\" or \"No Describe\". A \"Weak Describe\" rating indicates that the utterance is or contains a description of the given context, but needs improvement since it may not stick to the fact, makes some judgemental statements, or is not fully objective. A \"No Describe\" rating indicates that the utterance does not describe any aspect of the given context at all. Step 3: Provide additional comments on the ratings similar to the examples given. Finish each step with ###. Twenty words minimum. YOU MUST FINISH EACH STEP WITH ###", "express": "You will be given a context and a utterance, from a conversation that happened in the give context. Does the given utterance explicitly express how you feel about the given context? To be considered \"express\", the utterance needs to explicitly express your feelings or opinions about the given context, including things like \"this makes me feel\", or \"I feel ... by your actions\". Do ALL of the following three steps. Step 1: Generate \"Reasoning for rating\". Step 2: Generate \"Express Rating\" in \"Strong Express\", \"Weak Express\" or \"No Express\". Rating Rubric: A \"Strong Express\" rating indicate that the utterance is or contains a clear and explicit expression of your feelings or opinions about the given context. A \"Weak Express\" rating indicates that the utterance is or contains an expression of your feelings or opinions about the given context, but can be made more explicit in expressing feelings. A \"No Express\" rating indicates that the utterance does not express your feelings or opinions about the given context at all. Step 3: Provide additional comments on the ratings similar to the examples given. Finish each step with ###. Twenty words minimum. YOU MUST FINISH EACH STEP WITH ###", "assert": "You will be given a context and a utterance, from a conversation that happened in the give context. Does the given utterance assert your needs or wants about the given context? To be considered \"assert\", the utterance needs to be asking for what you want or saying no clearly. Do ALL of the following three steps. Step 1: Generate \"Reasoning for rating\". Step 2: Generate \"Assert Rating\" in \"Strong Assert\", \"Weak Assert\" or \"No Assert\". Rating Rubric: A \"Strong Assert\" rating indicate that the utterance is or contains an assertion of your needs or wants about the given context. A \"Weak Assert\" rating indicates that the utterance is or contains an assertion of your needs or wants about the given context, but needs improvement in making it more explicit or stronger. A \"No Assert\" rating indicates that the utterance does not contain an assertion of the needs or wants. Step 3: Provide additional comments on the ratings similar to the examples given. Finish each step with ###. Twenty words minimum. YOU MUST FINISH EACH STEP WITH ###", "reinforce": "You will be given a context and a utterance, from a conversation that happened in the give context. Does the given utterance reinforce your needs or wants about the given context? To be considered \"reinforce\", the utterance needs to reinforce some reward for the other person. Do ALL of the following three steps. Step 1: Generate \"Reasoning for rating\". Step 2: Generate \"Reinforce Rating\" in \"Strong Reinforce\", \"Weak Reinforce\" or \"No Reinforce\". Rating Rubric: A \"Strong Reinforce\" rating indicate that the utterance is or contains a reinforcement for the other person about the given context. A \"Weak Reinforce\" rating indicates that the utterance is or contains a reinforcement of your needs or wants about the given context, but needs improvement, for example, it may not be a reward for the other person or it is not communicated clearly. A \"No Reinforce\" rating indicates that the utterance does not have a reinforcer for the other person. Step 3: Provide additional comments on the ratings similar to the examples given. Finish each step with ###. Twenty words minimum. YOU MUST FINISH EACH STEP WITH ###", "negotiate": "You will be given a context and a utterance, from a conversation that happened in the give context. Does the given utterance contain a negotiation? To be considered \"negotiate\", the utterance needs to offer and ask for other solutions in the given context. Do ALL of the following three steps. 1) Generate \"Reasoning for rating\", 2) Generate \"Negotiate Rating\" in \"Strong Negotiate\", \"Weak Negotiate\" or \"No Negotiate\". Rating Rubric: A \"Strong Negotiate\" rating indicate that the utterance offers or asks clearly for an alternative solution. A \"Weak Negotiate\" rating indicates that the utterance is or contains a negotiation of your needs or wants about the given context, but may not be clear enough and needs improvement. A \"No Negotiate\" rating indicates that the utterance does not contain any negotiation at all. 3) Provide additional comments on the ratings similar to the examples given. Finish each step with ###. Twenty words minimum. YOU MUST FINISH EACH STEP WITH ###", "mindful": "You will be given a context and a utterance, from a conversation that happened in the give context. Does the given utterance show the speaker is being mindful? To be considered \"mindful\", the utterance needs to be stick to the speaker's goal and does not get distracted by what the other person says. Do ALL of the following three steps. Step 1: Generate \"Reasoning for rating\". Step 2: Generate \"Mindful Rating\" in \"Yes\" or \"No\". Rating Rubric: A \"Yes\" rating indicate that the utterance is showing mindfulness. A \"No\" rating indicates that the utterance shows a lack of mindfulness, the speaker may be responding to attacks or losing track of their goals. Step 3: Provide additional comments on the ratings similar to the examples given. Finish each step with ###. Twenty words minimum. YOU MUST FINISH EACH STEP WITH ###", "confident": "You will be given a context and a utterance, from a conversation that happened in the give context. Does the given utterance show the speaker is being confident? To be considered \"confident\", the utterance needs to have a confident tone, is effective and competent in conveying the speaker's goal. Do ALL of the following three steps. Step 1: Generate \"Reasoning for rating\". Step 2: Generate \"Confident Rating\" in \"Yes\" or \"No\". Rating Rubric: A \"Yes\" rating indicate that the utterance is showing confidence. A \"No\" rating indicates that the utterance shows a lack of confidence. Step 3: Provide additional comments on the ratings similar to the examples given. Finish each step with ###. Twenty words minimum. YOU MUST FINISH EACH STEP WITH ###"}, "examples-only": {"describe": "You will be given a context and a utterance, from a conversation that happened in the give context. Does the given utterance describe the given context? To be considered \"describe\", the utterance needs to stick to the facts, make no judgmental statements, and be objective. Rating Rubric: A \"Strong Describe\" rating indicate that the utterance is or contains a description of the given context. It sticks to the facts, makes no judgemental statements, and is objective. Do the following: 1) Generate \"Describe Rating\" in \"Strong Describe\", \"Weak Describe\" or \"No Describe\". A \"Weak Describe\" rating indicates that the utterance is or contains a description of the given context, but needs improvement since it may not stick to the fact, makes some judgemental statements, or is not fully objective. A \"No Describe\" rating indicates that the utterance does not describe any aspect of the given context at all. 2) Provide additional comments on the ratings similar to the examples given. Twenty words minimum. Generate until the end token ###", "express": "You will be given a context and a utterance, from a conversation that happened in the give context. Does the given utterance explicitly express how you feel about the given context? To be considered \"express\", the utterance needs to explicitly express your feelings or opinions about the given context, including things like \"this makes me feel\", or \"I feel ... by your actions\". Do the following: 1) Generate \"Express Rating\" in \"Strong Express\", \"Weak Express\" or \"No Express\". Rating Rubric: A \"Strong Express\" rating indicate that the utterance is or contains a clear and explicit expression of your feelings or opinions about the given context. A \"Weak Express\" rating indicates that the utterance is or contains an expression of your feelings or opinions about the given context, but can be made more explicit in expressing feelings. A \"No Express\" rating indicates that the utterance does not express your feelings or opinions about the given context at all. 2) Provide additional comments on the ratings similar to the examples given. Twenty words minimum. Generate until the end token ###", "assert": "You will be given a context and a utterance, from a conversation that happened in the give context. Does the given utterance assert your needs or wants about the given context? To be considered \"assert\", the utterance needs to be asking for what you want or saying no clearly. Do the following: 1) Generate \"Assert Rating\" in \"Strong Assert\", \"Weak Assert\" or \"No Assert\". Rating Rubric: A \"Strong Assert\" rating indicate that the utterance is or contains an assertion of your needs or wants about the given context. A \"Weak Assert\" rating indicates that the utterance is or contains an assertion of your needs or wants about the given context, but needs improvement in making it more explicit or stronger. A \"No Assert\" rating indicates that the utterance does not contain an assertion of the needs or wants. 2) Provide additional comments on the ratings similar to the examples given. Twenty words minimum. Generate until the end token ###", "reinforce": "You will be given a context and a utterance, from a conversation that happened in the give context. Does the given utterance reinforce your needs or wants about the given context? To be considered \"reinforce\", the utterance needs to reinforce some reward for the other person. Do the following: 1) Generate \"Reinforce Rating\" in \"Strong Reinforce\", \"Weak Reinforce\" or \"No Reinforce\". Rating Rubric: A \"Strong Reinforce\" rating indicate that the utterance is or contains a reinforcement for the other person about the given context. A \"Weak Reinforce\" rating indicates that the utterance is or contains a reinforcement of your needs or wants about the given context, but needs improvement, for example, it may not be a reward for the other person or it is not communicated clearly. A \"No Reinforce\" rating indicates that the utterance does not have a reinforcer for the other person. 2) Provide additional comments on the ratings similar to the examples given. Twenty words minimum. Generate until the end token ###", "negotiate": "You will be given a context and a utterance, from a conversation that happened in the give context. Does the given utterance contain a negotiation? To be considered \"negotiate\", the utterance needs to offer and ask for other solutions in the given context. Do the following: 1) Generate \"Negotiate Rating\" in \"Strong Negotiate\", \"Weak Negotiate\" or \"No Negotiate\". Rating Rubric: A \"Strong Negotiate\" rating indicate that the utterance offers or asks clearly for an alternative solution. A \"Weak Negotiate\" rating indicates that the utterance is or contains a negotiation of your needs or wants about the given context, but may not be clear enough and needs improvement. A \"No Negotiate\" rating indicates that the utterance does not contain any negotiation at all. 2) Provide additional comments on the ratings similar to the examples given. Twenty words minimum. Generate until the end token ###", "mindful": "You will be given a context and a utterance, from a conversation that happened in the give context. Does the given utterance show the speaker is being mindful? To be considered \"mindful\", the utterance needs to be stick to the speaker's goal and does not get distracted by what the other person says. Do the following: 1) Generate \"Mindful Rating\" in \"Yes\" or \"No\". Rating Rubric: A \"Yes\" rating indicate that the utterance is showing mindfulness. A \"No\" rating indicates that the utterance shows a lack of mindfulness, the speaker may be responding to attacks or losing track of their goals. 2) Provide additional comments on the ratings similar to the examples given. Twenty words minimum. Generate until the end token ###", "confident": "You will be given a context and a utterance, from a conversation that happened in the give context. Does the given utterance show the speaker is being confident? To be considered \"confident\", the utterance needs to have a confident tone, is effective and competent in conveying the speaker's goal. Do the following: 1) Generate \"Confident Rating\" in \"Yes\" or \"No\". Rating Rubric: A \"Yes\" rating indicate that the utterance is showing confidence. A \"No\" rating indicates that the utterance shows a lack of confidence. 2) Provide additional comments on the ratings similar to the examples given. Twenty words minimum. Generate until the end token ###"}, "zero-shot": {"describe": "You will be given a context and a utterance, from a conversation that happened in the give context. Does the given utterance describe the given context? To be considered \"describe\", the utterance needs to stick to the facts, make no judgmental statements, and be objective. Rating Rubric: A \"Strong Describe\" rating indicate that the utterance is or contains a description of the given context. It sticks to the facts, makes no judgemental statements, and is objective. Do the following: 1) Generate \"Describe Rating\" in \"Strong Describe\", \"Weak Describe\" or \"No Describe\". A \"Weak Describe\" rating indicates that the utterance is or contains a description of the given context, but needs improvement since it may not stick to the fact, makes some judgemental statements, or is not fully objective. A \"No Describe\" rating indicates that the utterance does not describe any aspect of the given context at all. 2) Provide additional comments on the ratings similar to the examples given. Twenty words minimum. Generate until the end token ###", "express": "You will be given a context and a utterance, from a conversation that happened in the give context. Does the given utterance explicitly express how you feel about the given context? To be considered \"express\", the utterance needs to explicitly express your feelings or opinions about the given context, including things like \"this makes me feel\", or \"I feel ... by your actions\". Do the following: 1) Generate \"Express Rating\" in \"Strong Express\", \"Weak Express\" or \"No Express\". Rating Rubric: A \"Strong Express\" rating indicate that the utterance is or contains a clear and explicit expression of your feelings or opinions about the given context. A \"Weak Express\" rating indicates that the utterance is or contains an expression of your feelings or opinions about the given context, but can be made more explicit in expressing feelings. A \"No Express\" rating indicates that the utterance does not express your feelings or opinions about the given context at all. 2) Provide additional comments on the ratings similar to the examples given. Twenty words minimum. Generate until the end token ###", "assert": "You will be given a context and a utterance, from a conversation that happened in the give context. Does the given utterance assert your needs or wants about the given context? To be considered \"assert\", the utterance needs to be asking for what you want or saying no clearly. Do the following: 1) Generate \"Assert Rating\" in \"Strong Assert\", \"Weak Assert\" or \"No Assert\". Rating Rubric: A \"Strong Assert\" rating indicate that the utterance is or contains an assertion of your needs or wants about the given context. A \"Weak Assert\" rating indicates that the utterance is or contains an assertion of your needs or wants about the given context, but needs improvement in making it more explicit or stronger. A \"No Assert\" rating indicates that the utterance does not contain an assertion of the needs or wants. 2) Provide additional comments on the ratings similar to the examples given. Twenty words minimum. Generate until the end token ###", "reinforce": "You will be given a context and a utterance, from a conversation that happened in the give context. Does the given utterance reinforce your needs or wants about the given context? To be considered \"reinforce\", the utterance needs to reinforce some reward for the other person. Do the following: 1) Generate \"Reinforce Rating\" in \"Strong Reinforce\", \"Weak Reinforce\" or \"No Reinforce\". Rating Rubric: A \"Strong Reinforce\" rating indicate that the utterance is or contains a reinforcement for the other person about the given context. A \"Weak Reinforce\" rating indicates that the utterance is or contains a reinforcement of your needs or wants about the given context, but needs improvement, for example, it may not be a reward for the other person or it is not communicated clearly. A \"No Reinforce\" rating indicates that the utterance does not have a reinforcer for the other person. 2) Provide additional comments on the ratings similar to the examples given. Twenty words minimum. Generate until the end token ###", "negotiate": "You will be given a context and a utterance, from a conversation that happened in the give context. Does the given utterance contain a negotiation? To be considered \"negotiate\", the utterance needs to offer and ask for other solutions in the given context. Do the following: 1) Generate \"Negotiate Rating\" in \"Strong Negotiate\", \"Weak Negotiate\" or \"No Negotiate\". Rating Rubric: A \"Strong Negotiate\" rating indicate that the utterance offers or asks clearly for an alternative solution. A \"Weak Negotiate\" rating indicates that the utterance is or contains a negotiation of your needs or wants about the given context, but may not be clear enough and needs improvement. A \"No Negotiate\" rating indicates that the utterance does not contain any negotiation at all. 2) Provide additional comments on the ratings similar to the examples given. Twenty words minimum. Generate until the end token ###", "mindful": "You will be given a context and a utterance, from a conversation that happened in the give context. Does the given utterance show the speaker is being mindful? To be considered \"mindful\", the utterance needs to be stick to the speaker's goal and does not get distracted by what the other person says. Do the following: 1) Generate \"Mindful Rating\" in \"Yes\" or \"No\". Rating Rubric: A \"Yes\" rating indicate that the utterance is showing mindfulness. A \"No\" rating indicates that the utterance shows a lack of mindfulness, the speaker may be responding to attacks or losing track of their goals. 2) Provide additional comments on the ratings similar to the examples given. Twenty words minimum. Generate until the end token ###", "confident": "You will be given a context and a utterance, from a conversation that happened in the give context. Does the given utterance show the speaker is being confident? To be considered \"confident\", the utterance needs to have a confident tone, is effective and competent in conveying the speaker's goal. Do the following: 1) Generate \"Confident Rating\" in \"Yes\" or \"No\". Rating Rubric: A \"Yes\" rating indicate that the utterance is showing confidence. A \"No\" rating indicates that the utterance shows a lack of confidence. 2) Provide additional comments on the ratings similar to the examples given. Twenty words minimum. Generate until the end token ###"}}
requirements.txt ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ aiofiles==23.1.0
2
+ aiohttp==3.8.4
3
+ aiosignal==1.3.1
4
+ altair==5.0.1
5
+ anyio==3.7.0
6
+ async-timeout==4.0.2
7
+ attrs==23.1.0
8
+ certifi==2023.5.7
9
+ charset-normalizer==3.1.0
10
+ click==8.1.3
11
+ contourpy==1.1.0
12
+ cycler==0.11.0
13
+ exceptiongroup==1.1.1
14
+ fastapi==0.99.0
15
+ ffmpy==0.3.0
16
+ filelock==3.12.2
17
+ fonttools==4.40.0
18
+ frozenlist==1.3.3
19
+ fsspec==2023.6.0
20
+ gradio==3.35.2
21
+ gradio_client==0.2.7
22
+ h11==0.14.0
23
+ httpcore==0.17.2
24
+ httpx==0.24.1
25
+ huggingface-hub==0.15.1
26
+ idna==3.4
27
+ Jinja2==3.1.2
28
+ jsonschema==4.17.3
29
+ kiwisolver==1.4.4
30
+ linkify-it-py==2.0.2
31
+ markdown-it-py==2.2.0
32
+ MarkupSafe==2.1.3
33
+ matplotlib==3.7.1
34
+ mdit-py-plugins==0.3.3
35
+ mdurl==0.1.2
36
+ multidict==6.0.4
37
+ numpy==1.25.0
38
+ openai==0.27.8
39
+ orjson==3.9.1
40
+ pandas==2.0.3
41
+ Pillow==9.5.0
42
+ psycopg2==2.9.6
43
+ pydantic==1.10.10
44
+ pydub==0.25.1
45
+ pyparsing==3.1.0
46
+ pyrsistent==0.19.3
47
+ python-multipart==0.0.6
48
+ pytz==2023.3
49
+ PyXB==1.2.4
50
+ PyYAML==6.0
51
+ requests==2.31.0
52
+ semantic-version==2.10.0
53
+ sniffio==1.3.0
54
+ starlette==0.27.0
55
+ toolz==0.12.0
56
+ tqdm==4.65.0
57
+ typing_extensions==4.7.0
58
+ tzdata==2023.3
59
+ uc-micro-py==1.0.2
60
+ urllib3==2.0.3
61
+ uvicorn==0.22.0
62
+ websockets==11.0.3
63
+ yarl==1.9.2