Files

66 lines
2.4 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""会话模型"""
from __future__ import annotations
from datetime import datetime, timezone
from typing import List, Optional, TYPE_CHECKING
from sqlalchemy import Boolean, DateTime, Index, String, Text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from backend.database import Base
if TYPE_CHECKING:
from backend.models.message import Message
def utc_now():
"""返回带时区的UTC时间"""
return datetime.now(timezone.utc)
class Session(Base):
"""会话表"""
__tablename__ = "sessions"
id: Mapped[str] = mapped_column(String, primary_key=True)
name: Mapped[str] = mapped_column(String, nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, default=utc_now)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=utc_now, onupdate=utc_now
)
# 会话总结字段20-200字符
summary: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
summary_updated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
# 上下文滚动压缩已总结到的消息ID该ID及之前的消息已写入记忆
last_summarized_msg_id: Mapped[Optional[int]] = mapped_column(nullable=True)
# 整会话自动总结到记忆的游标,避免重启后重复总结整段会话
auto_memory_summary_msg_id: Mapped[Optional[int]] = mapped_column(nullable=True)
# 会话级短期上下文总结缓存
short_context_summary: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
short_context_summary_msg_id: Mapped[Optional[int]] = mapped_column(nullable=True)
short_context_summary_updated_at: Mapped[Optional[datetime]] = mapped_column(
DateTime,
nullable=True,
)
short_context_summary_window_size: Mapped[Optional[int]] = mapped_column(
nullable=True,
)
# 会话级配置(可选)
session_model_config: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
session_persona_config: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
use_custom_config: Mapped[bool] = mapped_column(Boolean, default=False)
channel_context: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
messages: Mapped[List["Message"]] = relationship(
"Message", back_populates="session", cascade="all, delete-orphan"
)
__table_args__ = (Index("idx_sessions_updated", "updated_at"),)