50 lines
2.4 KiB
Python
50 lines
2.4 KiB
Python
"""对话会话与消息模型。"""
|
|
from datetime import datetime
|
|
|
|
from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, String, Text
|
|
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
|
|
|
from ..database import Base
|
|
|
|
|
|
class ChatSession(Base):
|
|
__tablename__ = "chat_sessions"
|
|
|
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
|
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True, nullable=False)
|
|
agent_id: Mapped[int | None] = mapped_column(ForeignKey("agents.id"), nullable=True)
|
|
title: Mapped[str] = mapped_column(String(128), default="新对话")
|
|
model: Mapped[str] = mapped_column(String(64), default="")
|
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)
|
|
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
|
|
|
messages: Mapped[list["ChatMessage"]] = relationship(
|
|
back_populates="session", cascade="all, delete-orphan", order_by="ChatMessage.id"
|
|
)
|
|
|
|
|
|
class ChatMessage(Base):
|
|
__tablename__ = "chat_messages"
|
|
|
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
|
session_id: Mapped[int] = mapped_column(ForeignKey("chat_sessions.id"), index=True, nullable=False)
|
|
role: Mapped[str] = mapped_column(String(16), nullable=False) # user / assistant / system
|
|
content: Mapped[str] = mapped_column(Text, default="")
|
|
model: Mapped[str] = mapped_column(String(64), default="")
|
|
tokens_in: Mapped[int] = mapped_column(Integer, default=0)
|
|
tokens_out: Mapped[int] = mapped_column(Integer, default=0)
|
|
# 附件文件 ID 列表(JSON 数组)
|
|
file_ids: Mapped[str] = mapped_column(String(256), default="[]")
|
|
# 用户反馈:like / dislike / 空
|
|
feedback: Mapped[str] = mapped_column(String(8), default="")
|
|
# 推荐短语(JSON 数组,AI 回答后生成 1-3 条)
|
|
suggestions: Mapped[str] = mapped_column(Text, default="[]")
|
|
# 用户消息是否被编辑过
|
|
edited: Mapped[bool] = mapped_column(Boolean, default=False)
|
|
# 重新生成次数
|
|
regenerated: Mapped[int] = mapped_column(Integer, default=0)
|
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)
|
|
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
|
|
|
session: Mapped["ChatSession"] = relationship(back_populates="messages")
|