To persist thought data across sessions, implement a database-backed storage solution. This involves creating a SQLAlchemy ThoughtModel that maps to the ThoughtData structure and a DatabaseStorage class to handle session management and data insertion.
from sqlalchemy import create_engine, Column, Integer, String, Float, Boolean, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
Base = declarative_base()
class ThoughtModel(Base):
"""SQLAlchemy model for thought data."""
__tablename__ = "thoughts"
id = Column(Integer, primary_key=True)
thought = Column(String, nullable=False)
thought_number = Column(Integer, nullable=False)
total_thoughts = Column(Integer, nullable=False)
next_thought_needed = Column(Boolean, nullable=False)
stage = Column(String, nullable=False)
timestamp = Column(String, nullable=False)
tags = relationship("TagModel", back_populates="thought")
axioms = relationship("AxiomModel", back_populates="thought")
assumptions = relationship("AssumptionModel", back_populates="thought")
class DatabaseStorage:
"""Database-backed storage for thought data."""
def __init__(self, db_url: str = "sqlite:///thoughts.db"):
"""Initialize database connection."""
self.engine = create_engine(db_url)
Base.metadata.create_all(self.engine)
self.Session = sessionmaker(bind=self.engine)
def add_thought(self, thought: ThoughtData) -> None:
"""Add a thought to the database."""
with self.Session() as session:
# Convert ThoughtData to ThoughtModel
thought_model = ThoughtModel(
thought=thought.thought,
thought_number=thought.thought_number,
total_thoughts=thought.total_thoughts,
next_thought_needed=thought.next_thought_needed,
stage=thought.stage.value,
timestamp=thought.timestamp
)
session.add(thought_model)
session.commit()