import datetime from sqlalchemy import Date, ForeignKey, Index, Integer, Text from sqlalchemy import inspect from sqlalchemy.dialects.postgresql import JSONB from sqlalchemy.orm import Mapped, mapped_column, relationship from fabledassistant.models import Base from fabledassistant.models.base import CreatedAtMixin, TimestampMixin class Conversation(Base, TimestampMixin): __tablename__ = "conversations" id: Mapped[int] = mapped_column(primary_key=True) user_id: Mapped[int | None] = mapped_column( Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=True ) title: Mapped[str] = mapped_column(Text, default="") model: Mapped[str] = mapped_column(Text, default="") # 'chat' (default) or 'briefing'. Briefing conversations are hidden from # the main chat view and managed by the briefing pipeline. conversation_type: Mapped[str] = mapped_column(Text, default="chat", server_default="chat") # For briefing conversations only: the calendar date this briefing covers. briefing_date: Mapped[datetime.date | None] = mapped_column(Date, nullable=True) messages: Mapped[list["Message"]] = relationship( back_populates="conversation", cascade="all, delete-orphan", order_by="Message.created_at", ) __table_args__ = ( Index("ix_conversations_updated_at", "updated_at"), Index("ix_conversations_user_id", "user_id"), ) def to_dict(self) -> dict: # Use loaded messages if available, otherwise 0 if "messages" in inspect(self).dict: msg_count = len(self.messages) if self.messages else 0 else: msg_count = 0 return { "id": self.id, "title": self.title, "model": self.model, "conversation_type": self.conversation_type, "briefing_date": self.briefing_date.isoformat() if self.briefing_date else None, "message_count": msg_count, "created_at": self.created_at.isoformat(), "updated_at": self.updated_at.isoformat(), } class Message(Base, CreatedAtMixin): __tablename__ = "messages" id: Mapped[int] = mapped_column(primary_key=True) conversation_id: Mapped[int] = mapped_column( Integer, ForeignKey("conversations.id", ondelete="CASCADE") ) role: Mapped[str] = mapped_column(Text) content: Mapped[str] = mapped_column(Text, default="") status: Mapped[str] = mapped_column(Text, default="complete") context_note_id: Mapped[int | None] = mapped_column( Integer, ForeignKey("notes.id", ondelete="SET NULL"), nullable=True ) tool_calls: Mapped[list | None] = mapped_column(JSONB, nullable=True) conversation: Mapped["Conversation"] = relationship(back_populates="messages") __table_args__ = ( Index("ix_messages_conversation_id", "conversation_id"), ) def to_dict(self) -> dict: return { "id": self.id, "conversation_id": self.conversation_id, "role": self.role, "content": self.content, "status": self.status, "context_note_id": self.context_note_id, "tool_calls": self.tool_calls, "created_at": self.created_at.isoformat(), }