diff --git a/backend/api/voice_chat_router.py b/backend/api/voice_chat_router.py index 38415e0..0f973b4 100644 --- a/backend/api/voice_chat_router.py +++ b/backend/api/voice_chat_router.py @@ -797,6 +797,16 @@ async def _persist_voice_session_history( ) main_log = existing.scalar_one_or_none() + # 如果有当前轮次的日志,更新它;否则更新最后一轮 + current_log_id = session_state.get("current_log_id") + if current_log_id: + current_result = await db.execute( + select(ChatLog).where(ChatLog.id == current_log_id) + ) + current_log = current_result.scalar_one_or_none() + if current_log: + main_log = current_log + if main_log: # 更新已有的 ChatLog:填充 token 数据和消息内容 if input_tokens + output_tokens > 0: @@ -859,25 +869,24 @@ async def _append_voice_log_chunk( content = (user_msg or "").strip() if not content: return - if not main_log: - main_log = ChatLog( - user_id=numeric_user_id, - trace_id=session_state.get("trace_id") or f"trace-{user_id}-{uuid.uuid4().hex[:12]}", - conversation_id=conversation_id, - pet_id=int(session_state.get("pet_id") or 0), - bg_id=int(session_state.get("bg_id") or 0), - user_msg=content, - ai_msg="", - tokens_input=0, - tokens_output=0, - duration_ms=0, - mode=mode, - created_at=datetime.now() - ) - db.add(main_log) - else: - main_log.user_msg = content - main_log.trace_id = main_log.trace_id or session_state.get("trace_id") or main_log.trace_id + # 每次新用户消息都创建新的 ChatLog 记录,实现逐轮保存 + new_log = ChatLog( + user_id=numeric_user_id, + trace_id=session_state.get("trace_id") or f"trace-{user_id}-{uuid.uuid4().hex[:12]}", + conversation_id=conversation_id, + pet_id=int(session_state.get("pet_id") or 0), + bg_id=int(session_state.get("bg_id") or 0), + user_msg=content, + ai_msg="", + tokens_input=0, + tokens_output=0, + duration_ms=0, + mode=mode, + created_at=datetime.now() + ) + db.add(new_log) + await db.flush() + session_state["current_log_id"] = new_log.id session_state["last_persisted_user_msg"] = content await db.commit() return @@ -886,6 +895,14 @@ async def _append_voice_log_chunk( if not content: return + # 查找当前轮次的 ChatLog 记录(由 persist_kind="user" 创建) + current_log_id = session_state.get("current_log_id") + if current_log_id: + current_result = await db.execute( + select(ChatLog).where(ChatLog.id == current_log_id) + ) + main_log = current_result.scalar_one_or_none() + if not main_log: main_log = ChatLog( user_id=numeric_user_id,