Update app_shared.py
Browse files- app_shared.py +30 -17
app_shared.py
CHANGED
|
@@ -398,27 +398,40 @@ class ChatManager:
|
|
| 398 |
current_time = time.time()
|
| 399 |
step = st.session_state.chat_step
|
| 400 |
history = st.session_state.chat_history
|
| 401 |
-
|
| 402 |
-
if step
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 407 |
history.append(next_msg)
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 418 |
history.append({"role": "assistant", "content": ai_reply})
|
| 419 |
-
|
| 420 |
st.session_state.chat_step += 1
|
| 421 |
st.session_state.last_update_time = current_time
|
|
|
|
| 422 |
|
| 423 |
|
| 424 |
def render_message(self, role: str, content: str) -> str:
|
|
|
|
| 398 |
current_time = time.time()
|
| 399 |
step = st.session_state.chat_step
|
| 400 |
history = st.session_state.chat_history
|
| 401 |
+
|
| 402 |
+
if step >= len(self.initial_history):
|
| 403 |
+
return # 结束,无消息处理
|
| 404 |
+
|
| 405 |
+
if current_time - st.session_state.last_update_time < CHAT_CONFIG["update_interval"]:
|
| 406 |
+
return # 等待更新间隔
|
| 407 |
+
|
| 408 |
+
next_msg = self.initial_history[step]
|
| 409 |
+
|
| 410 |
+
if next_msg["role"] == "user":
|
| 411 |
+
# 只有当 history 最后一条不是这个用户消息,才添加,避免重复
|
| 412 |
+
if len(history) == 0 or history[-1]["content"] != next_msg["content"]:
|
| 413 |
history.append(next_msg)
|
| 414 |
+
st.session_state.chat_step += 1
|
| 415 |
+
st.session_state.last_update_time = current_time
|
| 416 |
+
|
| 417 |
+
elif next_msg["role"] == "assistant":
|
| 418 |
+
# 必须保证上一条是用户消息
|
| 419 |
+
if len(history) == 0 or history[-1]["role"] != "user":
|
| 420 |
+
st.warning("⚠️ 无法生成 AI 回答:找不到上一条用户消息")
|
| 421 |
+
return
|
| 422 |
+
|
| 423 |
+
user_prompt = history[-1]["content"]
|
| 424 |
+
app_id = "c968f91131ac432787f5ef81f51922ba"
|
| 425 |
+
api_key = os.getenv("DASHSCOPE_API_KEY")
|
| 426 |
+
ai_reply = self.generate_response(user_prompt, app_id, api_key)
|
| 427 |
+
|
| 428 |
+
# 避免重复插入相同的回复
|
| 429 |
+
if len(history) == 0 or history[-1]["content"] != ai_reply:
|
| 430 |
history.append({"role": "assistant", "content": ai_reply})
|
| 431 |
+
|
| 432 |
st.session_state.chat_step += 1
|
| 433 |
st.session_state.last_update_time = current_time
|
| 434 |
+
|
| 435 |
|
| 436 |
|
| 437 |
def render_message(self, role: str, content: str) -> str:
|