fix: 修复AI重复调用问题,统一消息处理流程

- _process_message 只保存用户消息并通知
- 新增 generate_ai_response action 统一处理AI回复
- 避免重复调用AI和重复发送消息
This commit is contained in:
2026-04-12 00:34:30 +08:00
parent f3636dddd6
commit a07de626ad
7 changed files with 69 additions and 32 deletions

58
main.py
View File

@@ -457,6 +457,64 @@ async def handle_matrix_message(action: str, conversation_id: str = None, user_m
db.close()
return
if action == "generate_ai_response":
# 生成AI回复并同步
db = SessionLocal()
try:
conv_service = ConversationService(db)
conversation = conv_service.get_conversation(conversation_id)
if conversation:
# 发送"正在输入"状态
try:
await matrix_bot.client.room_typing(room_id, typing_state=True)
except:
pass
# 获取会话历史
history = conv_service.get_conversation_history(conversation_id, limit=20)
# 调用AI
ai_response = await ai_service.chat(history)
# 保存AI回复
assistant_msg = conv_service.add_message(
conversation_id=conversation.id,
role='assistant',
content=ai_response,
source='matrix'
)
# 发送到Matrix
await matrix_bot.send_message(room_id, ai_response)
# 关闭"正在输入"状态
try:
await matrix_bot.client.room_typing(room_id, typing_state=False)
except:
pass
# 同步到网页端WebSocket
await manager.send_to_user(MAIN_USER_ID, {
"type": "assistant_message",
"conversation_id": conversation_id,
"message": {
"id": assistant_msg.id,
"role": "assistant",
"content": ai_response,
"source": "matrix",
"created_at": assistant_msg.created_at.isoformat()
}
})
logger.info(f"Matrix AI回复已发送: {ai_response[:50]}")
except Exception as e:
logger.error(f"生成AI回复失败: {e}")
await matrix_bot.send_message(room_id, f"处理消息时出错: {str(e)}")
finally:
db.close()
return
if action == "chat":
db = SessionLocal()
try: