43 lines
1.7 KiB
Python
43 lines
1.7 KiB
Python
|
|
"""Chat models."""
|
||
|
|
from sqlalchemy import ForeignKey, JSON, String, Text
|
||
|
|
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||
|
|
|
||
|
|
from app.models.base import Base, TimestampMixin, UUIDMixin
|
||
|
|
|
||
|
|
|
||
|
|
class ChatSession(Base, UUIDMixin, TimestampMixin):
|
||
|
|
"""Chat session."""
|
||
|
|
|
||
|
|
__tablename__ = "chat_sessions"
|
||
|
|
|
||
|
|
user_id: Mapped[str | None] = mapped_column(
|
||
|
|
ForeignKey("users.id", ondelete="CASCADE"), nullable=True, index=True
|
||
|
|
)
|
||
|
|
title: Mapped[str | None] = mapped_column(String(256), default="")
|
||
|
|
skill_id: Mapped[str | None] = mapped_column(
|
||
|
|
ForeignKey("skills.id", ondelete="SET NULL"), nullable=True
|
||
|
|
)
|
||
|
|
context_window: Mapped[int] = mapped_column(default=10, nullable=False)
|
||
|
|
|
||
|
|
messages: Mapped[list["ChatMessage"]] = relationship(
|
||
|
|
"ChatMessage", back_populates="session", cascade="all, delete-orphan"
|
||
|
|
)
|
||
|
|
|
||
|
|
|
||
|
|
class ChatMessage(Base, UUIDMixin, TimestampMixin):
|
||
|
|
"""Chat message."""
|
||
|
|
|
||
|
|
__tablename__ = "chat_messages"
|
||
|
|
|
||
|
|
session_id: Mapped[str] = mapped_column(
|
||
|
|
ForeignKey("chat_sessions.id", ondelete="CASCADE"), nullable=False, index=True
|
||
|
|
)
|
||
|
|
role: Mapped[str] = mapped_column(String(32), nullable=False, index=True) # user / assistant / tool
|
||
|
|
content: Mapped[str | None] = mapped_column(Text, default="")
|
||
|
|
tool_calls: Mapped[list] = mapped_column(JSON, default=list, nullable=False)
|
||
|
|
tool_results: Mapped[list] = mapped_column(JSON, default=list, nullable=False)
|
||
|
|
references: Mapped[list] = mapped_column(JSON, default=list, nullable=False)
|
||
|
|
token_usage: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
||
|
|
|
||
|
|
session: Mapped["ChatSession"] = relationship("ChatSession", back_populates="messages")
|