v0.1.0: CRM/ERP 系统内测版本 - 安全加固完成
- Docker bridge 网络隔离(8000 端口封死) - Gunicorn 4 Worker 多进程 - Alembic 数据库迁移基线 - 日志轮转 20m×3 - JWT 密钥 + DB 密码 + CORS 收紧 - 3-2-1 备份链路(NAS + R740-B 冷备) - 连接池 pool_pre_ping + pool_recycle=3600
This commit is contained in:
@@ -0,0 +1,58 @@
|
||||
"""
|
||||
AI 对话历史服务 — 持久化 + 查询
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from sqlalchemy import select, desc
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.ai import AiChatSession
|
||||
|
||||
|
||||
async def save_message(
|
||||
db: AsyncSession,
|
||||
user_id: uuid.UUID,
|
||||
role: str,
|
||||
content: str,
|
||||
msg_type: str = "text",
|
||||
) -> AiChatSession:
|
||||
"""保存一条对话消息"""
|
||||
msg = AiChatSession(
|
||||
user_id=user_id,
|
||||
role=role,
|
||||
content=content,
|
||||
msg_type=msg_type,
|
||||
)
|
||||
db.add(msg)
|
||||
await db.commit()
|
||||
await db.refresh(msg)
|
||||
return msg
|
||||
|
||||
|
||||
async def load_history(
|
||||
db: AsyncSession,
|
||||
user_id: uuid.UUID,
|
||||
limit: int = 50,
|
||||
) -> list[dict]:
|
||||
"""加载用户最近 N 条对话(时间正序返回,方便前端渲染)"""
|
||||
stmt = (
|
||||
select(AiChatSession)
|
||||
.where(AiChatSession.user_id == user_id)
|
||||
.order_by(desc(AiChatSession.created_at))
|
||||
.limit(limit)
|
||||
)
|
||||
result = await db.execute(stmt)
|
||||
rows = result.scalars().all()
|
||||
# 反转为时间正序
|
||||
rows = list(reversed(rows))
|
||||
return [
|
||||
{
|
||||
"id": str(r.id),
|
||||
"role": r.role,
|
||||
"content": r.content,
|
||||
"type": r.msg_type,
|
||||
"created_at": r.created_at.isoformat() if r.created_at else None,
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
Reference in New Issue
Block a user