HelenaXH commited on
Commit
a3835fc
·
verified ·
1 Parent(s): ac6c750

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -84
app.py CHANGED
@@ -4,13 +4,12 @@ import os
4
 
5
  # ============================ 用户信息结构 ============================
6
  user_profile = {
7
- "mode": None, # 是 / 否 (Backward / Forward)
8
- "specific_career": None, # Backward 目标职业
9
- "bg_info": None, # 学术背景
10
- "work_value": None, # 工作意义
11
- "personality_summary": None, # 性格总结
12
- "dream_day": None, # 理想工作一天
13
- # 新增:记录用户在Forward时选的方向
14
  "forward_direction_choice": None
15
  }
16
 
@@ -52,8 +51,6 @@ forward_index = 0
52
  backward_index = 0
53
  forward_done = False
54
  backward_done = False
55
-
56
- # 新增:用于判断是否在 Forward 模式下,已经给过“自动推荐方向”
57
  forward_recommendation_given = False
58
 
59
  # ============================ 模型设置 ============================
@@ -95,7 +92,6 @@ def generate_system_prompt():
95
  - 性格总结: {personality_summary}
96
  - 理想一天: {dream_day}
97
  - 学生选择方向: {forward_choice}
98
-
99
  请输出:
100
  1. 学生的优势、性格、价值观分析
101
  2. 推荐3个具体职业,并说明日常工作内容、适配性、要求、准备路径
@@ -111,7 +107,6 @@ def predict(message, history):
111
  global forward_done, backward_done
112
  global forward_recommendation_given
113
 
114
- # ========== 如果是对话第一轮,重置所有状态 ==========
115
  if not history:
116
  current_q_index = 0
117
  questions = base_questions[:]
@@ -126,62 +121,56 @@ def predict(message, history):
126
  backward_done = False
127
  forward_recommendation_given = False
128
 
129
- # ========== 如果还在问 base_questions (目前就1个问题) ==========
130
  if 0 < current_q_index <= len(questions):
131
- # 把刚才的回答存入 user_profile
132
  key = questions[current_q_index - 1][0]
133
  user_profile[key] = message.strip()
134
-
135
- # 根据回答决定 Forward / Backward
136
  if key == "mode" and "是" in user_profile["mode"]:
137
- # 如果用户回答“是”,进入Backward
138
  questions.insert(1, ("specific_career", "请具体描述你想要从事的职业方向。"))
139
  in_backward_flow = True
140
  elif key == "mode" and "否" in user_profile["mode"]:
141
- # 如果用户回答“否”,进入Forward
142
  in_forward_flow = True
143
 
144
- # 如果还没问完 base_questions,就继续问
145
  if current_q_index < len(questions):
146
  nxt = questions[current_q_index][1]
147
  current_q_index += 1
148
  return nxt
149
 
150
- # ========== 判断模式 ==========
151
  mode = user_profile.get("mode") or ""
152
 
153
- # ========== Backward 模式逻辑 ==========
154
  if "是" in mode:
155
  if in_backward_flow and not backward_done:
156
- # 如果 backward_index 还没问完
157
  if backward_index < len(backward_additional_questions):
158
  k, prompt_text = backward_additional_questions[backward_index]
159
  backward_index += 1
160
  return prompt_text
161
  else:
162
- # Backward 问题问完
163
  backward_done = True
164
 
165
- # ========== Forward 模式逻辑 ==========
166
  else:
167
  if in_forward_flow and not forward_done:
168
- # 1) 如果还 Forward 问题没有问完
169
  if forward_index < len(forward_additional_questions):
170
  k, prompt_text = forward_additional_questions[forward_index]
171
  forward_index += 1
172
  return prompt_text
173
 
174
- # 2) 如果已问完 4 Forward问题,但自动推荐过方向
175
  elif not forward_recommendation_given:
176
  forward_recommendation_given = True
 
 
 
 
 
177
  try:
178
  api_key = os.environ.get("API_TOKEN")
179
  if not api_key:
180
  return "错误:API_TOKEN 未设置,请在环境变量中添加。"
181
-
182
  client = OpenAI(api_key=api_key)
183
 
184
- # 根据用户信息,让AI自动生成简短画像+3个大方向
185
  recommendation_prompt = f"""
186
  请根据以下信息,为这位学生撰写一份结构化、条理清晰的“人物画像分析”:
187
  - 学术背景: {user_profile['bg_info']}
@@ -192,25 +181,28 @@ def predict(message, history):
192
  请分为两个主要部分:
193
 
194
  一、人物画像分析:
195
- 1) 学背景与可能的专业优势:如学校资源、专业特点、已有项目/技能等。
196
- 2) 职业价值观与工作偏好:基于“帮助他人/���质回报/自由时间/挑战”等关键词,说明此人的动力及对工作环境的期待。
197
- 3) 性格特点:结合其自我描述,总结其性格特质及可能的优劣势。
198
- 4) 理想工作状态:描述其对日常工作节奏、团队协作、创造性或挑战性的需求。
199
-
200
- 二、基于上述画像,推荐3个大方向
201
- - 每个方向请用简短段落说明:
202
- (A) 典型岗位或行业示例
203
- (B) 主要特点(如社会价值、薪酬潜力、工作自由度、发展难度)
204
- (C) 建议的行动(如需要的课程/证书/实习类型/社交网络)
205
-
206
- 在最后列出 3 个方向并提示学生:“请从中选择一个方向进行下一步深入探讨”,格式如下:
207
  1. XXX方向
208
  2. XXX方向
209
  3. XXX方向
210
 
211
- 如果信息不足,请根据通用的求职与专业发展逻辑合理推测要点,以充实建议字数尽量在500字左右,使用中文分段写作。
212
  """
213
 
 
 
 
 
214
  msgs = [
215
  {"role": "system", "content": "你是一位专业的职业生涯顾问,善于总结用户信息并给出大方向建议。"},
216
  {"role": "user", "content": recommendation_prompt}
@@ -228,14 +220,13 @@ def predict(message, history):
228
  except Exception as e:
229
  return f"生成推荐方向时出错: {str(e)}"
230
 
231
- # 3) 如果已经自动推荐过方向,那么等待用户输入方向选择
232
  else:
 
233
  user_profile["forward_direction_choice"] = message.strip()
234
  forward_done = True
235
 
236
- # ========== 当 forward_done 或 backward_done 后,进入最终生成阶段 ==========
237
  if ("是" in mode and backward_done) or ("否" in mode and forward_done):
238
- # 此时调用OpenAI做最终规划建议
239
  try:
240
  api_key = os.environ.get("API_TOKEN")
241
  if not api_key:
@@ -246,7 +237,7 @@ def predict(message, history):
246
 
247
  msgs = [
248
  {"role": "system", "content": system_prompt},
249
- {"role": "user", "content": f"请根据我提供的信息,给职业规划建议: {user_profile}. {message}"}
250
  ]
251
  resp = client.chat.completions.create(
252
  model=model_default,
@@ -263,6 +254,7 @@ def predict(message, history):
263
 
264
  return "信息收集完毕,若尚未得到最终回复,请输入任意文字以继续。"
265
 
 
266
  # ============================ Gradio UI ============================
267
  with gr.Blocks(css="""
268
  body {
@@ -328,26 +320,16 @@ footer {
328
 
329
  gr.Markdown("""
330
  **📝 Forward / Backward 多轮交互:新增“自动职业方向推荐”功能**
331
-
332
  - 若已确定方向:回答“是”(Backward)
333
  - 若还在探索:回答“否”(Forward)
334
  - Forward模式会在你回答完四大问题后,自动给出一个简短“学生画像”+3个大方向供你选择
335
  """)
336
 
337
- chatbot = gr.Chatbot(
338
- height=500,
339
- show_label=False,
340
- show_copy_button=True,
341
- type="messages"
342
- )
343
 
344
  with gr.Row():
345
  with gr.Column(scale=8):
346
- msg = gr.Textbox(
347
- placeholder="请在这里输入你的回答...",
348
- show_label=False,
349
- container=False
350
- )
351
  with gr.Column(scale=1):
352
  submit_btn = gr.Button("🚀 发送", elem_id="custom-send")
353
 
@@ -366,27 +348,11 @@ footer {
366
  history.append({"role": "assistant", "content": bot_message})
367
  return history
368
 
369
- # 点击发送按钮
370
- submit_btn.click(
371
- fn=add_message,
372
- inputs=[msg, chatbot],
373
- outputs=[msg, chatbot]
374
- ).then(
375
- fn=bot_response,
376
- inputs=[chatbot],
377
- outputs=[chatbot]
378
- )
379
-
380
- # 回车提交
381
- msg.submit(
382
- fn=add_message,
383
- inputs=[msg, chatbot],
384
- outputs=[msg, chatbot]
385
- ).then(
386
- fn=bot_response,
387
- inputs=[chatbot],
388
- outputs=[chatbot]
389
- )
390
 
391
  def reset_conversation():
392
  global current_q_index, questions
@@ -407,15 +373,9 @@ footer {
407
  forward_done = False
408
  backward_done = False
409
  forward_recommendation_given = False
410
-
411
  return []
412
 
413
- reset_btn.click(
414
- fn=reset_conversation,
415
- inputs=None,
416
- outputs=chatbot,
417
- queue=False
418
- )
419
 
420
  def auto_first_question():
421
  return [{"role": "assistant", "content": questions[0][1]}]
 
4
 
5
  # ============================ 用户信息结构 ============================
6
  user_profile = {
7
+ "mode": None,
8
+ "specific_career": None,
9
+ "bg_info": None,
10
+ "work_value": None,
11
+ "personality_summary": None,
12
+ "dream_day": None,
 
13
  "forward_direction_choice": None
14
  }
15
 
 
51
  backward_index = 0
52
  forward_done = False
53
  backward_done = False
 
 
54
  forward_recommendation_given = False
55
 
56
  # ============================ 模型设置 ============================
 
92
  - 性格总结: {personality_summary}
93
  - 理想一天: {dream_day}
94
  - 学生选择方向: {forward_choice}
 
95
  请输出:
96
  1. 学生的优势、性格、价值观分析
97
  2. 推荐3个具体职业,并说明日常工作内容、适配性、要求、准备路径
 
107
  global forward_done, backward_done
108
  global forward_recommendation_given
109
 
 
110
  if not history:
111
  current_q_index = 0
112
  questions = base_questions[:]
 
121
  backward_done = False
122
  forward_recommendation_given = False
123
 
124
+ # 如果还在问 base_questions
125
  if 0 < current_q_index <= len(questions):
 
126
  key = questions[current_q_index - 1][0]
127
  user_profile[key] = message.strip()
 
 
128
  if key == "mode" and "是" in user_profile["mode"]:
 
129
  questions.insert(1, ("specific_career", "请具体描述你想要从事的职业方向。"))
130
  in_backward_flow = True
131
  elif key == "mode" and "否" in user_profile["mode"]:
 
132
  in_forward_flow = True
133
 
 
134
  if current_q_index < len(questions):
135
  nxt = questions[current_q_index][1]
136
  current_q_index += 1
137
  return nxt
138
 
 
139
  mode = user_profile.get("mode") or ""
140
 
141
+ # ========== Backward ==========
142
  if "是" in mode:
143
  if in_backward_flow and not backward_done:
 
144
  if backward_index < len(backward_additional_questions):
145
  k, prompt_text = backward_additional_questions[backward_index]
146
  backward_index += 1
147
  return prompt_text
148
  else:
 
149
  backward_done = True
150
 
151
+ # ========== Forward ==========
152
  else:
153
  if in_forward_flow and not forward_done:
154
+ # 如果还没问完 Forward问题
155
  if forward_index < len(forward_additional_questions):
156
  k, prompt_text = forward_additional_questions[forward_index]
157
  forward_index += 1
158
  return prompt_text
159
 
160
+ # 如果已问完4个问题,但没推荐过方向
161
  elif not forward_recommendation_given:
162
  forward_recommendation_given = True
163
+
164
+ # ================== 调试打印 user_profile ==================
165
+ print("===== Debug user_profile =====")
166
+ print(user_profile)
167
+
168
  try:
169
  api_key = os.environ.get("API_TOKEN")
170
  if not api_key:
171
  return "错误:API_TOKEN 未设置,请在环境变量中添加。"
 
172
  client = OpenAI(api_key=api_key)
173
 
 
174
  recommendation_prompt = f"""
175
  请根据以下信息,为这位学生撰写一份结构化、条理清晰的“人物画像分析”:
176
  - 学术背景: {user_profile['bg_info']}
 
181
  请分为两个主要部分:
182
 
183
  一、人物画像分析:
184
+ 1) 学校/专业背景与可能的优势
185
+ 2) 职业价值观与工作偏好
186
+ 3) 性格特点
187
+ 4) 理想工作状态
188
+
189
+ 二、推荐3个大方向
190
+ (A) 典型岗位或行业示例
191
+ (B) 主要特点
192
+ (C) 建议行动
193
+
194
+ 在最后列出3个方向让学生从中选一个深入:
 
195
  1. XXX方向
196
  2. XXX方向
197
  3. XXX方向
198
 
199
+ 如果信息不足,请基于通用逻辑合理推使用中文分段写作,字数不少于500字
200
  """
201
 
202
+ # ================== 调试打印 recommendation_prompt ==================
203
+ print("===== Debug recommendation_prompt =====")
204
+ print(recommendation_prompt)
205
+
206
  msgs = [
207
  {"role": "system", "content": "你是一位专业的职业生涯顾问,善于总结用户信息并给出大方向建议。"},
208
  {"role": "user", "content": recommendation_prompt}
 
220
  except Exception as e:
221
  return f"生成推荐方向时出错: {str(e)}"
222
 
 
223
  else:
224
+ # 等待用户输入方向choice
225
  user_profile["forward_direction_choice"] = message.strip()
226
  forward_done = True
227
 
228
+ # ========== 最终生成阶段 ==========
229
  if ("是" in mode and backward_done) or ("否" in mode and forward_done):
 
230
  try:
231
  api_key = os.environ.get("API_TOKEN")
232
  if not api_key:
 
237
 
238
  msgs = [
239
  {"role": "system", "content": system_prompt},
240
+ {"role": "user", "content": f"请根据我提供的信息,给职业规划建议: {user_profile}. {message}"}
241
  ]
242
  resp = client.chat.completions.create(
243
  model=model_default,
 
254
 
255
  return "信息收集完毕,若尚未得到最终回复,请输入任意文字以继续。"
256
 
257
+
258
  # ============================ Gradio UI ============================
259
  with gr.Blocks(css="""
260
  body {
 
320
 
321
  gr.Markdown("""
322
  **📝 Forward / Backward 多轮交互:新增“自动职业方向推荐”功能**
 
323
  - 若已确定方向:回答“是”(Backward)
324
  - 若还在探索:回答“否”(Forward)
325
  - Forward模式会在你回答完四大问题后,自动给出一个简短“学生画像”+3个大方向供你选择
326
  """)
327
 
328
+ chatbot = gr.Chatbot(height=500, show_label=False, show_copy_button=True, type="messages")
 
 
 
 
 
329
 
330
  with gr.Row():
331
  with gr.Column(scale=8):
332
+ msg = gr.Textbox(placeholder="请在这里输入你的回答...", show_label=False, container=False)
 
 
 
 
333
  with gr.Column(scale=1):
334
  submit_btn = gr.Button("🚀 发送", elem_id="custom-send")
335
 
 
348
  history.append({"role": "assistant", "content": bot_message})
349
  return history
350
 
351
+ submit_btn.click(fn=add_message, inputs=[msg, chatbot], outputs=[msg, chatbot]) \
352
+ .then(fn=bot_response, inputs=[chatbot], outputs=[chatbot])
353
+
354
+ msg.submit(fn=add_message, inputs=[msg, chatbot], outputs=[msg, chatbot]) \
355
+ .then(fn=bot_response, inputs=[chatbot], outputs=[chatbot])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
356
 
357
  def reset_conversation():
358
  global current_q_index, questions
 
373
  forward_done = False
374
  backward_done = False
375
  forward_recommendation_given = False
 
376
  return []
377
 
378
+ reset_btn.click(fn=reset_conversation, inputs=None, outputs=chatbot, queue=False)
 
 
 
 
 
379
 
380
  def auto_first_question():
381
  return [{"role": "assistant", "content": questions[0][1]}]