diff --git a/AI/WxMini/Sql/t_chat_log.sql b/AI/WxMini/Sql/t_chat_log.sql index 200da8fe..cbb24698 100644 --- a/AI/WxMini/Sql/t_chat_log.sql +++ b/AI/WxMini/Sql/t_chat_log.sql @@ -1,11 +1,37 @@ +/* + Navicat Premium Dump SQL + + Source Server : 10.10.14.210 + Source Server Type : MySQL + Source Server Version : 50742 (5.7.42-log) + Source Host : 10.10.14.210:22066 + Source Schema : ai_db + + Target Server Type : MySQL + Target Server Version : 50742 (5.7.42-log) + File Encoding : 65001 + + Date: 25/03/2025 10:03:37 +*/ + +SET NAMES utf8mb4; +SET FOREIGN_KEY_CHECKS = 0; + +-- ---------------------------- +-- Table structure for t_chat_log +-- ---------------------------- DROP TABLE IF EXISTS `t_chat_log`; CREATE TABLE `t_chat_log` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键', `session_id` char(36) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '用户人员编号', `user_input` varchar(2000) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '用户提出的问题', `model_response` varchar(2000) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '大模型的反馈', + `audio_url` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '生成的语音文件路径', + `duration` double NULL DEFAULT 0 COMMENT '音频时长,单位:秒', `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', PRIMARY KEY (`id`) USING BTREE, - INDEX `idx_session_id` (`session_id`) USING BTREE, - INDEX `idx_create_time` (`create_time`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; \ No newline at end of file + INDEX `idx_session_id`(`session_id`) USING BTREE, + INDEX `idx_create_time`(`create_time`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = DYNAMIC; + +SET FOREIGN_KEY_CHECKS = 1; diff --git a/AI/WxMini/Start.py b/AI/WxMini/Start.py index cb78bc81..e88b1292 100644 --- a/AI/WxMini/Start.py +++ b/AI/WxMini/Start.py @@ -4,7 +4,7 @@ import time import uuid from contextlib import asynccontextmanager -from fastapi import FastAPI, Form, HTTPException +from fastapi import FastAPI, Form, HTTPException, Query from openai import AsyncOpenAI from WxMini.Milvus.Config.MulvusConfig import * @@ -12,7 +12,7 @@ from WxMini.Milvus.Utils.MilvusCollectionManager import MilvusCollectionManager from WxMini.Milvus.Utils.MilvusConnectionPool import * from WxMini.Utils.OssUtil import upload_mp3_to_oss_from_memory from WxMini.Utils.TtsUtil import TTS -from WxMini.Utils.MySQLUtil import init_mysql_pool, save_chat_to_mysql +from WxMini.Utils.MySQLUtil import init_mysql_pool, save_chat_to_mysql, get_chat_log_by_session from WxMini.Utils.EmbeddingUtil import text_to_embedding # 配置日志 @@ -178,6 +178,28 @@ async def reply(session_id: str = Form(...), prompt: str = Form(...)): # 释放连接 milvus_pool.release_connection(connection) + +# 获取聊天记录 +@app.get("/get_chat_log") +async def get_chat_log( + session_id: str, + page: int = Query(default=1, ge=1, description="当前页码"), + page_size: int = Query(default=10, ge=1, le=100, description="每页记录数") +): + """ + 根据 session_id 查询聊天记录,并按 id 降序分页 + :param session_id: 用户会话 ID + :param page: 当前页码 + :param page_size: 每页记录数 + :return: 分页数据 + """ + try: + result = await get_chat_log_by_session(app.state.mysql_pool,session_id, page, page_size) + return result + except Exception as e: + logger.error(f"查询聊天记录失败: {str(e)}") + raise HTTPException(status_code=500, detail=f"查询聊天记录失败: {str(e)}") + # 运行 FastAPI 应用 if __name__ == "__main__": import uvicorn diff --git a/AI/WxMini/Utils/MySQLUtil.py b/AI/WxMini/Utils/MySQLUtil.py index a8b0028b..8cb2c96d 100644 --- a/AI/WxMini/Utils/MySQLUtil.py +++ b/AI/WxMini/Utils/MySQLUtil.py @@ -41,4 +41,55 @@ async def truncate_chat_log(mysql_pool): async with conn.cursor() as cur: await cur.execute("TRUNCATE TABLE t_chat_log") await conn.commit() - logger.info("表 t_chat_log 已清空。") \ No newline at end of file + logger.info("表 t_chat_log 已清空。") + +# 分页查询聊天记录 +async def get_chat_log_by_session(mysql_pool,session_id, page=1, page_size=10): + """ + 根据 session_id 查询聊天记录,并按 id 降序分页 + :param session_id: 用户会话 ID + :param page: 当前页码 + :param page_size: 每页记录数 + :return: 分页数据 + """ + if not mysql_pool: + raise ValueError("MySQL 连接池未初始化") + + offset = (page - 1) * page_size + async with mysql_pool.acquire() as conn: + async with conn.cursor() as cur: + # 查询总记录数 + await cur.execute( + "SELECT COUNT(*) FROM t_chat_log WHERE session_id = %s", + (session_id,) + ) + total = (await cur.fetchone())[0] + + # 查询分页数据 + await cur.execute( + "SELECT id, session_id, user_input, model_response, audio_url, duration, create_time " + "FROM t_chat_log WHERE session_id = %s ORDER BY id DESC LIMIT %s OFFSET %s", + (session_id, page_size, offset) + ) + records = await cur.fetchall() + + # 将查询结果转换为字典列表 + result = [ + { + "id": record[0], + "session_id": record[1], + "user_input": record[2], + "model_response": record[3], + "audio_url": record[4], + "duration": record[5], + "create_time": record[6].strftime("%Y-%m-%d %H:%M:%S") + } + for record in records + ] + + return { + "data": result, + "total": total, + "page": page, + "page_size": page_size + } \ No newline at end of file diff --git a/AI/WxMini/Utils/__pycache__/MySQLUtil.cpython-310.pyc b/AI/WxMini/Utils/__pycache__/MySQLUtil.cpython-310.pyc index 98649a68..8731b166 100644 Binary files a/AI/WxMini/Utils/__pycache__/MySQLUtil.cpython-310.pyc and b/AI/WxMini/Utils/__pycache__/MySQLUtil.cpython-310.pyc differ diff --git a/AI/WxMini/__pycache__/Start.cpython-310.pyc b/AI/WxMini/__pycache__/Start.cpython-310.pyc index fbbaaf2e..197a0985 100644 Binary files a/AI/WxMini/__pycache__/Start.cpython-310.pyc and b/AI/WxMini/__pycache__/Start.cpython-310.pyc differ