|
| 1 | +try: |
| 2 | + from sqlalchemy.orm import declarative_base, relationship, mapped_column |
| 3 | + from sqlalchemy import String, Text, ForeignKey, Boolean, Integer |
| 4 | + from sqlalchemy.ext.asyncio import create_async_engine |
| 5 | + from sqlalchemy.types import TypeDecorator |
| 6 | +except ImportError as e: |
| 7 | + raise ImportError( |
| 8 | + "This module requires 'sqlalchemy' and 'ulid-py'. " |
| 9 | + "Install them with: pip install codetide[agents-ui]" |
| 10 | + ) from e |
| 11 | + |
| 12 | +from datetime import datetime |
| 13 | +from sqlalchemy import Select |
| 14 | +from ulid import ulid |
| 15 | +import asyncio |
| 16 | +import json |
| 17 | + |
| 18 | +# SQLite-compatible JSON and UUID types |
| 19 | +class GUID(TypeDecorator): |
| 20 | + impl = String |
| 21 | + |
| 22 | + def process_bind_param(self, value, dialect): |
| 23 | + if value is None: |
| 24 | + return None |
| 25 | + return str(value) |
| 26 | + |
| 27 | + def process_result_value(self, value, dialect): |
| 28 | + return value |
| 29 | +class JSONEncodedDict(TypeDecorator): |
| 30 | + impl = Text |
| 31 | + |
| 32 | + def process_bind_param(self, value, dialect): |
| 33 | + return json.dumps(value) if value is not None else None |
| 34 | + |
| 35 | + def process_result_value(self, value, dialect): |
| 36 | + return json.loads(value) if value is not None else None |
| 37 | + |
| 38 | +class JSONEncodedList(TypeDecorator): |
| 39 | + impl = Text |
| 40 | + |
| 41 | + def process_bind_param(self, value, dialect): |
| 42 | + return json.dumps(value) if value is not None else None |
| 43 | + |
| 44 | + def process_result_value(self, value, dialect): |
| 45 | + return json.loads(value) if value is not None else None |
| 46 | + |
| 47 | +Base = declarative_base() |
| 48 | + |
| 49 | +class User(Base): |
| 50 | + __tablename__ = "users" |
| 51 | + id = mapped_column(GUID, primary_key=True, default=ulid) |
| 52 | + identifier = mapped_column(Text, unique=True, nullable=False) |
| 53 | + user_metadata = mapped_column("metadata", JSONEncodedDict, nullable=False) |
| 54 | + createdAt = mapped_column(Text, default=lambda: datetime.utcnow().isoformat()) |
| 55 | + |
| 56 | +class Thread(Base): |
| 57 | + __tablename__ = "threads" |
| 58 | + id = mapped_column(GUID, primary_key=True, default=ulid) |
| 59 | + createdAt = mapped_column(Text, default=lambda: datetime.utcnow().isoformat()) |
| 60 | + name = mapped_column(Text) |
| 61 | + userId = mapped_column(GUID, ForeignKey("users.id", ondelete="CASCADE")) |
| 62 | + userIdentifier = mapped_column(Text) |
| 63 | + tags = mapped_column(JSONEncodedList) |
| 64 | + user_metadata = mapped_column("metadata", JSONEncodedDict) |
| 65 | + |
| 66 | + user = relationship("User", backref="threads") |
| 67 | + |
| 68 | +class Step(Base): |
| 69 | + __tablename__ = "steps" |
| 70 | + id = mapped_column(GUID, primary_key=True, default=ulid) |
| 71 | + name = mapped_column(Text, nullable=False) |
| 72 | + type = mapped_column(Text, nullable=False) |
| 73 | + threadId = mapped_column(GUID, ForeignKey("threads.id", ondelete="CASCADE"), nullable=False) |
| 74 | + parentId = mapped_column(GUID) |
| 75 | + streaming = mapped_column(Boolean, nullable=False) |
| 76 | + waitForAnswer = mapped_column(Boolean) |
| 77 | + isError = mapped_column(Boolean) |
| 78 | + user_metadata = mapped_column("metadata", JSONEncodedDict) |
| 79 | + tags = mapped_column(JSONEncodedList) |
| 80 | + input = mapped_column(Text) |
| 81 | + output = mapped_column(Text) |
| 82 | + createdAt = mapped_column(Text, default=lambda: datetime.utcnow().isoformat()) |
| 83 | + command = mapped_column(Text) |
| 84 | + start = mapped_column(Text) |
| 85 | + end = mapped_column(Text) |
| 86 | + generation = mapped_column(JSONEncodedDict) |
| 87 | + showInput = mapped_column(Text) |
| 88 | + language = mapped_column(Text) |
| 89 | + indent = mapped_column(Integer) |
| 90 | + defaultOpen = mapped_column(Boolean, default=False) |
| 91 | + |
| 92 | +class Element(Base): |
| 93 | + __tablename__ = "elements" |
| 94 | + id = mapped_column(GUID, primary_key=True, default=ulid) |
| 95 | + threadId = mapped_column(GUID, ForeignKey("threads.id", ondelete="CASCADE")) |
| 96 | + type = mapped_column(Text) |
| 97 | + url = mapped_column(Text) |
| 98 | + chainlitKey = mapped_column(Text) |
| 99 | + name = mapped_column(Text, nullable=False) |
| 100 | + display = mapped_column(Text) |
| 101 | + objectKey = mapped_column(Text) |
| 102 | + size = mapped_column(Text) |
| 103 | + page = mapped_column(Integer) |
| 104 | + language = mapped_column(Text) |
| 105 | + forId = mapped_column(GUID) |
| 106 | + mime = mapped_column(Text) |
| 107 | + props = mapped_column(JSONEncodedDict) |
| 108 | + |
| 109 | +class Feedback(Base): |
| 110 | + __tablename__ = "feedbacks" |
| 111 | + id = mapped_column(GUID, primary_key=True, default=ulid) |
| 112 | + forId = mapped_column(GUID, nullable=False) |
| 113 | + threadId = mapped_column(GUID, ForeignKey("threads.id", ondelete="CASCADE"), nullable=False) |
| 114 | + value = mapped_column(Integer, nullable=False) |
| 115 | + comment = mapped_column(Text) |
| 116 | + |
| 117 | +# class AsyncMessageDB: |
| 118 | +# def __init__(self, db_path: str): |
| 119 | +# self.db_url = f"sqlite+aiosqlite:///{db_path}" |
| 120 | +# self.engine = create_async_engine(self.db_url, echo=False) |
| 121 | +# self.async_session = async_sessionmaker(bind=self.engine, class_=AsyncSession, expire_on_commit=False) |
| 122 | + |
| 123 | +# async def init_db(self): |
| 124 | +# async with self.engine.begin() as conn: |
| 125 | +# await conn.run_sync(Base.user_metadata.create_all) |
| 126 | + |
| 127 | +# async def create_chat(self, name: str) -> Chat: |
| 128 | +# async with self.async_session() as session: |
| 129 | +# chat = Chat(name=name) |
| 130 | +# session.add(chat) |
| 131 | +# await session.commit() |
| 132 | +# await session.refresh(chat) |
| 133 | +# return chat |
| 134 | + |
| 135 | +# async def add_message(self, chat_id: str, role: str, content: str) -> Message: |
| 136 | +# async with self.async_session() as session: |
| 137 | +# message = Message(chat_id=chat_id, role=role, content=content) |
| 138 | +# session.add(message) |
| 139 | +# await session.commit() |
| 140 | +# await session.refresh(message) |
| 141 | +# return message |
| 142 | + |
| 143 | +# async def get_messages_for_chat(self, chat_id: str) -> List[Message]: |
| 144 | +# async with self.async_session() as session: |
| 145 | +# result = await session.execute( |
| 146 | +# select(Message).where(Message.chat_id == chat_id).order_by(Message.timestamp) |
| 147 | +# ) |
| 148 | +# return result.scalars().all() |
| 149 | + |
| 150 | +# async def list_chats(self) -> List[Chat]: |
| 151 | +# async with self.async_session() as session: |
| 152 | +# result = await session.execute(select(Chat).order_by(Chat.name)) |
| 153 | +# return result.scalars().all() |
| 154 | + |
| 155 | +# async def main(): |
| 156 | +# db = AsyncMessageDB(str(Path(os.path.abspath(__file__)).parent / "my_messages.db")) |
| 157 | +# await db.init_db() |
| 158 | + |
| 159 | +# chat = await db.create_chat("My First Chat") |
| 160 | +# await db.add_message(chat.id, "user", "Hello Assistant!") |
| 161 | +# await db.add_message(chat.id, "assistant", "Hello, how can I help you?") |
| 162 | + |
| 163 | +# print(f"Messages for chat '{chat.name}':") |
| 164 | +# messages = await db.get_messages_for_chat(chat.id) |
| 165 | +# for msg in messages: |
| 166 | +# print(f"[{msg.timestamp}] {msg.role.upper()}: {msg.content}") |
| 167 | + |
| 168 | +# print("\nAll chats:") |
| 169 | +# chats = await db.list_chats() |
| 170 | +# for c in chats: |
| 171 | +# print(f"{c.id} — {c.name}") |
| 172 | +async def init_db(path: str): |
| 173 | + from sqlalchemy.ext.asyncio import async_sessionmaker, AsyncSession |
| 174 | + engine = create_async_engine(f"sqlite+aiosqlite:///{path}") |
| 175 | + async with engine.begin() as conn: |
| 176 | + await conn.run_sync(Base.metadata.create_all) |
| 177 | + |
| 178 | +if __name__ == "__main__": |
| 179 | + asyncio.run(init_db("database.db")) |
0 commit comments