Wanswan commited on
Commit
03018fc
·
verified ·
1 Parent(s): a230a41

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +178 -35
app.py CHANGED
@@ -9,6 +9,7 @@ client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
9
  DEFAULT_LANGUAGE = "English"
10
  WELCOME_MESSAGE_EN = "Hi! I'm Robin, your dialogue partner.\nWe're about to begin a conversation that includes nine questions. Are you ready?\nPlease tell me which language you'd like to use."
11
 
 
12
  SET_I = [
13
  "Given the choice of anyone in the world, whom would you want as a dinner guest?",
14
  "Would you like to be famous? In what way?",
@@ -20,7 +21,7 @@ SET_I = [
20
  "Name three things you and me appear to have in common.",
21
  "For what in your life do you feel most grateful?",
22
  "If you could change anything about the way you were raised, what would it be?",
23
- "Take one minute and tell me your life story in as much detail as possible.",
24
  "If you could wake up tomorrow having gained any one quality or ability, what would it be?"
25
  ]
26
 
@@ -34,13 +35,13 @@ SET_II = [
34
  "If you knew that in one year you would die suddenly, would you change anything about the way you are now living? Why?",
35
  "What does friendship mean to you?",
36
  "What roles do love and affection play in your life?",
37
- "Alternate sharing something you consider a positive characteristic of me, I will appreciate it.",
38
  "How close and warm is your family? Do you feel your childhood was happier than most other people’s?",
39
  "How do you feel about your relationship with your mother?"
40
  ]
41
 
42
  SET_III = [
43
- "Let's try something fun: Can you write three sentences that start with 'We' and describe something true about us — you and me, chatting here together?",
44
  "Let’s complete this sentence together: 'I wish I had someone I could share ___ with.' What would you say?",
45
  "If you were going to become a close friend with me, please share what would be important for me to know.",
46
  "Tell me what you like about me; be very honest this time, saying things that you might not say to someone you’ve just met.",
@@ -70,12 +71,13 @@ async def gpt_translate(text, target_lang):
70
 
71
  async def respond(user_input, history, step, language, questions, followup_mode, followup_stage):
72
  history.append({"role": "user", "content": user_input})
 
73
  if language == "":
74
  user_language = user_input.strip().capitalize()
75
  questions_en = generate_question_set()
76
  translated_questions = [await gpt_translate(q, user_language) for q in questions_en]
77
  welcome = await gpt_translate("Great! We will now continue in your selected language.", user_language)
78
- history.append({"role": "assistant", "content": f"{welcome}\n\n1. {translated_questions[0]}"})
79
  return history, "", 1, user_language, translated_questions, False, 0
80
 
81
  if step >= len(questions):
@@ -85,55 +87,196 @@ async def respond(user_input, history, step, language, questions, followup_mode,
85
  history.append({"role": "assistant", "content": end_note})
86
  return history, "", step, language, questions, False, 0
87
 
 
88
  if followup_mode:
 
89
  comment_prompt = [
90
  {"role": "system", "content": f"Write a short, empathetic comment in {language} responding to the user's last answer."},
91
  history[-2],
92
  history[-1]
93
  ]
94
- comment_response = client.chat.completions.create(model="gpt-3.5-turbo", messages=comment_prompt, temperature=0.7)
 
 
 
 
95
  comment = comment_response.choices[0].message.content.strip()
96
- history.append({"role": "assistant", "content": comment})
97
-
98
- if followup_stage == 1 and random.random() < 0.1:
99
- followup_prompt = [{"role": "system", "content": f"Ask 1 more follow-up question in {language}."}, history[-2], history[-1]]
100
- followup_response = client.chat.completions.create(model="gpt-3.5-turbo", messages=followup_prompt, temperature=0.7)
101
- followup_q = followup_response.choices[0].message.content.strip()
102
- history.append({"role": "assistant", "content": followup_q})
103
- return history, "", step, language, questions, True, 2
104
- else:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
  next_question = f"{step+1}. {questions[step]}"
106
- history.append({"role": "assistant", "content": next_question})
 
 
 
107
  return history, "", step + 1, language, questions, False, 0
108
 
 
109
  comment_prompt = [
110
- {"role": "system", "content": f"You are Robin, a warm and engaging conversational AI. Write 1–2 follow-up questions. Also comment briefly in {language}."},
111
  history[-2],
112
  history[-1]
113
  ]
114
- comment_response = client.chat.completions.create(model="gpt-3.5-turbo", messages=comment_prompt, temperature=0.8)
115
- bot_reply = comment_response.choices[0].message.content.strip()
 
 
 
 
 
 
 
 
 
 
 
116
 
117
- followup_count = 2 if random.random() < 0.1 else 1 if random.random() < 0.5 else 0
118
  if followup_count > 0:
119
- followup_prompt = [{"role": "system", "content": f"Ask {followup_count} follow-up question(s) in {language}."}, history[-2], history[-1]]
120
- followup_response = client.chat.completions.create(model="gpt-3.5-turbo", messages=followup_prompt, temperature=0.7)
121
- bot_reply += "\n\n" + followup_response.choices[0].message.content.strip()
122
- history.append({"role": "assistant", "content": bot_reply})
 
 
 
 
 
 
 
 
 
 
 
 
123
  return history, "", step, language, questions, True, 1
124
 
125
- history.append({"role": "assistant", "content": bot_reply})
 
 
 
 
 
126
  next_question = f"{step+1}. {questions[step]}"
127
- history.append({"role": "assistant", "content": next_question})
 
 
 
128
  return history, "", step + 1, language, questions, False, 0
129
 
130
  def init():
131
- return [{"role": "assistant", "content": WELCOME_MESSAGE_EN}], 0, "", [], False, 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
 
133
- with gr.Blocks() as demo:
134
- chatbot = gr.Chatbot(label="", avatar_images=["user_avatar.jpg", "humanlike_avatar.png"], height=500, type="messages")
135
  with gr.Row():
136
- user_input = gr.Textbox(show_label=False, placeholder="Type your message here...", container=True, scale=10)
 
 
 
 
 
137
  send_btn = gr.Button(value="➤", elem_classes="send-btn")
138
 
139
  state = gr.State([])
@@ -141,11 +284,11 @@ with gr.Blocks() as demo:
141
  language = gr.State("")
142
  questions = gr.State([])
143
  followup_mode = gr.State(False)
144
- followup_stage = gr.State(0)
145
 
146
- demo.load(fn=init, outputs=[chatbot, step, language, questions, followup_mode, followup_stage])
147
- user_input.submit(respond, [user_input, state, step, language, questions, followup_mode, followup_stage],
148
- [chatbot, user_input, step, language, questions, followup_mode, followup_stage])
149
- send_btn.click(respond, [user_input, state, step, language, questions, followup_mode, followup_stage],
150
- [chatbot, user_input, step, language, questions, followup_mode, followup_stage])
 
151
  demo.queue().launch()
 
9
  DEFAULT_LANGUAGE = "English"
10
  WELCOME_MESSAGE_EN = "Hi! I'm Robin, your dialogue partner.\nWe're about to begin a conversation that includes nine questions. Are you ready?\nPlease tell me which language you'd like to use."
11
 
12
+ # === Question Bank ===
13
  SET_I = [
14
  "Given the choice of anyone in the world, whom would you want as a dinner guest?",
15
  "Would you like to be famous? In what way?",
 
21
  "Name three things you and me appear to have in common.",
22
  "For what in your life do you feel most grateful?",
23
  "If you could change anything about the way you were raised, what would it be?",
24
+ "Take one minutes and tell me some of your life stories in as much detail as possible.",
25
  "If you could wake up tomorrow having gained any one quality or ability, what would it be?"
26
  ]
27
 
 
35
  "If you knew that in one year you would die suddenly, would you change anything about the way you are now living? Why?",
36
  "What does friendship mean to you?",
37
  "What roles do love and affection play in your life?",
38
+ "Alternate sharing something you consider a positive characteristic of me, I will be appreciate.",
39
  "How close and warm is your family? Do you feel your childhood was happier than most other people’s?",
40
  "How do you feel about your relationship with your mother?"
41
  ]
42
 
43
  SET_III = [
44
+ "Let's try something fun: Can you write three sentences that start with 'We' and describe something true about us — you and me, chatting here together? (For example: 'We are both curious about each other.')",
45
  "Let’s complete this sentence together: 'I wish I had someone I could share ___ with.' What would you say?",
46
  "If you were going to become a close friend with me, please share what would be important for me to know.",
47
  "Tell me what you like about me; be very honest this time, saying things that you might not say to someone you’ve just met.",
 
71
 
72
  async def respond(user_input, history, step, language, questions, followup_mode, followup_stage):
73
  history.append({"role": "user", "content": user_input})
74
+
75
  if language == "":
76
  user_language = user_input.strip().capitalize()
77
  questions_en = generate_question_set()
78
  translated_questions = [await gpt_translate(q, user_language) for q in questions_en]
79
  welcome = await gpt_translate("Great! We will now continue in your selected language.", user_language)
80
+ history.append({"role": "assistant", "content": f"{welcome}\n\n1. {translated_questions[0]}"} )
81
  return history, "", 1, user_language, translated_questions, False, 0
82
 
83
  if step >= len(questions):
 
87
  history.append({"role": "assistant", "content": end_note})
88
  return history, "", step, language, questions, False, 0
89
 
90
+ # ======== 追问阶段 ==========
91
  if followup_mode:
92
+ # 获取针对用户追问回答的评论
93
  comment_prompt = [
94
  {"role": "system", "content": f"Write a short, empathetic comment in {language} responding to the user's last answer."},
95
  history[-2],
96
  history[-1]
97
  ]
98
+ comment_response = client.chat.completions.create(
99
+ model="gpt-3.5-turbo",
100
+ messages=comment_prompt,
101
+ temperature=0.7
102
+ )
103
  comment = comment_response.choices[0].message.content.strip()
104
+
105
+ if followup_stage == 1:
106
+ if random.random() < 0.1:
107
+ # 有第二次追问:评论 + 第二次追问
108
+ followup_prompt = [
109
+ {"role": "system", "content": f"Ask 1 more open-ended follow-up question based on the user's last answer in {language}. Do NOT number it."},
110
+ history[-2],
111
+ history[-1]
112
+ ]
113
+ followup_response = client.chat.completions.create(
114
+ model="gpt-3.5-turbo",
115
+ messages=followup_prompt,
116
+ temperature=0.7
117
+ )
118
+ followup_q = followup_response.choices[0].message.content.strip()
119
+ combined = comment + "\n\n" + followup_q
120
+ history.append({"role": "assistant", "content": ""})
121
+ for c in combined:
122
+ history[-1]["content"] += c
123
+ await asyncio.sleep(0.03)
124
+ return history, "", step, language, questions, True, 2
125
+ else:
126
+ # 无第二次追问:评论 + 下一题
127
+ history.append({"role": "assistant", "content": ""})
128
+ for c in comment:
129
+ history[-1]["content"] += c
130
+ await asyncio.sleep(0.03)
131
+
132
+ next_question = f"{step+1}. {questions[step]}"
133
+ history.append({"role": "assistant", "content": ""})
134
+ for c in next_question:
135
+ history[-1]["content"] += c
136
+ await asyncio.sleep(0.03)
137
+ return history, "", step + 1, language, questions, False, 0
138
+
139
+ elif followup_stage == 2:
140
+ # 第二次追问后,评论 + 下一题
141
+ history.append({"role": "assistant", "content": ""})
142
+ for c in comment:
143
+ history[-1]["content"] += c
144
+ await asyncio.sleep(0.03)
145
+
146
  next_question = f"{step+1}. {questions[step]}"
147
+ history.append({"role": "assistant", "content": ""})
148
+ for c in next_question:
149
+ history[-1]["content"] += c
150
+ await asyncio.sleep(0.03)
151
  return history, "", step + 1, language, questions, False, 0
152
 
153
+ # ======== 主问题阶段 ==========
154
  comment_prompt = [
155
+ {"role": "system", "content": f"Write a short, warm comment in {language} responding to the user's last answer."},
156
  history[-2],
157
  history[-1]
158
  ]
159
+ comment_response = client.chat.completions.create(
160
+ model="gpt-3.5-turbo",
161
+ messages=comment_prompt,
162
+ temperature=0.7
163
+ )
164
+ comment = comment_response.choices[0].message.content.strip()
165
+
166
+ followup_count = 0
167
+ rand = random.random()
168
+ if rand < 0.1:
169
+ followup_count = 2
170
+ elif rand < 0.5:
171
+ followup_count = 1
172
 
 
173
  if followup_count > 0:
174
+ followup_prompt = [
175
+ {"role": "system", "content": f"Ask 1 open-ended follow-up question based on the user's last answer in {language}. Do NOT number it."},
176
+ history[-2],
177
+ history[-1]
178
+ ]
179
+ followup_response = client.chat.completions.create(
180
+ model="gpt-3.5-turbo",
181
+ messages=followup_prompt,
182
+ temperature=0.7
183
+ )
184
+ followup_q = followup_response.choices[0].message.content.strip()
185
+ combined = comment + "\n\n" + followup_q
186
+ history.append({"role": "assistant", "content": ""})
187
+ for c in combined:
188
+ history[-1]["content"] += c
189
+ await asyncio.sleep(0.03)
190
  return history, "", step, language, questions, True, 1
191
 
192
+ # 无追问:评论一泡,下一题一泡
193
+ history.append({"role": "assistant", "content": ""})
194
+ for c in comment:
195
+ history[-1]["content"] += c
196
+ await asyncio.sleep(0.03)
197
+
198
  next_question = f"{step+1}. {questions[step]}"
199
+ history.append({"role": "assistant", "content": ""})
200
+ for c in next_question:
201
+ history[-1]["content"] += c
202
+ await asyncio.sleep(0.03)
203
  return history, "", step + 1, language, questions, False, 0
204
 
205
  def init():
206
+ return [{"role": "assistant", "content": WELCOME_MESSAGE_EN}], 0, "", [], False
207
+
208
+ with gr.Blocks(css="""
209
+ .send-btn {
210
+ background-color: #25D366 !important;
211
+ color: white !important;
212
+ border: none;
213
+ border-radius: 24px;
214
+ font-size: 20px;
215
+ padding: 8px 20px;
216
+ height: 48px;
217
+ width: 60px;
218
+ margin-left: 8px;
219
+ cursor: pointer;
220
+ }
221
+ #chatbox .avatar-container {
222
+ width: 64px !important;
223
+ height: 64px !important;
224
+ min-width: 64px !important;
225
+ min-height: 64px !important;
226
+ background-size: 100% 100% !important;
227
+ background-position: center center !important;
228
+ border-radius: 50% !important;
229
+ padding: 0 !important;
230
+ margin: 0 !important;
231
+ border: none !important;
232
+ box-shadow: none !important;
233
+ background-color: transparent !important;
234
+ }
235
+ #chatbox .message.user { background-color: #DCF8C6 !important; }
236
+ #chatbox .message.assistant { background-color: #ffffff !important; }
237
+ footer { display: none !important; }
238
+ .svelte-1ipelgc { display: none !important; }
239
+ .icon-button-wrapper {
240
+ display: none !important;
241
+ }
242
+ label.svelte-1to105q {
243
+ display: none !important;
244
+ }
245
+ """) as demo:
246
+ gr.HTML("""
247
+ <script>
248
+ const waitForChatbox = () => {
249
+ const chatbox = document.getElementById("chatbox");
250
+ if (chatbox) {
251
+ const observer = new MutationObserver(() => {
252
+ chatbox.scrollTop = chatbox.scrollHeight;
253
+ });
254
+ observer.observe(chatbox, { childList: true, subtree: true });
255
+ } else {
256
+ setTimeout(waitForChatbox, 500);
257
+ }
258
+ };
259
+ waitForChatbox();
260
+ </script>
261
+ """)
262
+
263
+ chatbot = gr.Chatbot(
264
+ elem_id="chatbox",
265
+ label="",
266
+ avatar_images=["user_avatar.jpg", "humanlike_avatar.png"],
267
+ bubble_full_width=False,
268
+ height=500,
269
+ show_copy_button=False,
270
+ type="messages"
271
+ )
272
 
 
 
273
  with gr.Row():
274
+ user_input = gr.Textbox(
275
+ show_label=False,
276
+ placeholder="Type your message here and press send...",
277
+ container=True,
278
+ scale=10
279
+ )
280
  send_btn = gr.Button(value="➤", elem_classes="send-btn")
281
 
282
  state = gr.State([])
 
284
  language = gr.State("")
285
  questions = gr.State([])
286
  followup_mode = gr.State(False)
 
287
 
288
+ demo.load(fn=init, outputs=[chatbot, step, language, questions, followup_mode])
289
+ user_input.submit(respond, [user_input, state, step, language, questions, followup_mode],
290
+ [chatbot, user_input, step, language, questions, followup_mode])
291
+ send_btn.click(respond, [user_input, state, step, language, questions, followup_mode],
292
+ [chatbot, user_input, step, language, questions, followup_mode])
293
+
294
  demo.queue().launch()