chats.py 10.6 KB
Newer Older
1
from pydantic import BaseModel, ConfigDict
Timothy J. Baek's avatar
Timothy J. Baek committed
2
3
4
5
6
7
from typing import List, Union, Optional

import json
import uuid
import time

8
9
10
from sqlalchemy import Column, String, BigInteger, Boolean
from sqlalchemy.orm import Session

11
from apps.webui.internal.db import Base, get_session
12

Timothy J. Baek's avatar
Timothy J. Baek committed
13
14
15
16
17
18

####################
# Chat DB Schema
####################


19
20
class Chat(Base):
    __tablename__ = "chat"
21

22
23
24
25
    id = Column(String, primary_key=True)
    user_id = Column(String)
    title = Column(String)
    chat = Column(String)  # Save Chat JSON as Text
26

27
28
    created_at = Column(BigInteger)
    updated_at = Column(BigInteger)
Timothy J. Baek's avatar
Timothy J. Baek committed
29

30
31
    share_id = Column(String, unique=True, nullable=True)
    archived = Column(Boolean, default=False)
Timothy J. Baek's avatar
Timothy J. Baek committed
32
33
34


class ChatModel(BaseModel):
35
36
    model_config = ConfigDict(from_attributes=True)

Timothy J. Baek's avatar
Timothy J. Baek committed
37
38
39
    id: str
    user_id: str
    title: str
Timothy J. Baek's avatar
Timothy J. Baek committed
40
    chat: str
41
42
43
44

    created_at: int  # timestamp in epoch
    updated_at: int  # timestamp in epoch

45
    share_id: Optional[str] = None
Timothy J. Baek's avatar
Timothy J. Baek committed
46
    archived: bool = False
Timothy J. Baek's avatar
Timothy J. Baek committed
47
48
49
50
51
52
53
54
55
56
57


####################
# Forms
####################


class ChatForm(BaseModel):
    chat: dict


Timothy J. Baek's avatar
Timothy J. Baek committed
58
59
60
61
class ChatTitleForm(BaseModel):
    title: str


62
class ChatResponse(BaseModel):
Timothy J. Baek's avatar
Timothy J. Baek committed
63
    id: str
64
65
66
    user_id: str
    title: str
    chat: dict
67
68
    updated_at: int  # timestamp in epoch
    created_at: int  # timestamp in epoch
69
    share_id: Optional[str] = None  # id of the chat to be shared
70
    archived: bool
Timothy J. Baek's avatar
Timothy J. Baek committed
71
72
73
74
75


class ChatTitleIdResponse(BaseModel):
    id: str
    title: str
76
77
    updated_at: int
    created_at: int
Timothy J. Baek's avatar
Timothy J. Baek committed
78
79
80
81


class ChatTable:

82
    def insert_new_chat(self, user_id: str, form_data: ChatForm) -> Optional[ChatModel]:
83
84
85
86
87
88
89
        with get_session() as db:
            id = str(uuid.uuid4())
            chat = ChatModel(
                **{
                    "id": id,
                    "user_id": user_id,
                    "title": (
90
91
92
                        form_data.chat["title"]
                        if "title" in form_data.chat
                        else "New Chat"
93
94
95
                    ),
                    "chat": json.dumps(form_data.chat),
                    "created_at": int(time.time()),
96
97
98
99
                    "updated_at": int(time.time()),
                }
            )

100
101
102
103
104
            result = Chat(**chat.model_dump())
            db.add(result)
            db.commit()
            db.refresh(result)
            return ChatModel.model_validate(result) if result else None
Timothy J. Baek's avatar
Timothy J. Baek committed
105

106
    def update_chat_by_id(self, id: str, chat: dict) -> Optional[ChatModel]:
107
108
109
110
111
112
113
114
115
116
117
118
        with get_session() as db:
            try:
                chat_obj = db.get(Chat, id)
                chat_obj.chat = json.dumps(chat)
                chat_obj.title = chat["title"] if "title" in chat else "New Chat"
                chat_obj.updated_at = int(time.time())
                db.commit()
                db.refresh(chat_obj)

                return ChatModel.model_validate(chat_obj)
            except Exception as e:
                return None
119

120
    def insert_shared_chat_by_chat_id(self, chat_id: str) -> Optional[ChatModel]:
121
122
        with get_session() as db:
            # Get the existing chat to share
123
            chat = db.get(Chat, chat_id)
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
            # Check if the chat is already shared
            if chat.share_id:
                return self.get_chat_by_id_and_user_id(chat.share_id, "shared")
            # Create a new chat with the same data, but with a new ID
            shared_chat = ChatModel(
                **{
                    "id": str(uuid.uuid4()),
                    "user_id": f"shared-{chat_id}",
                    "title": chat.title,
                    "chat": chat.chat,
                    "created_at": chat.created_at,
                    "updated_at": int(time.time()),
                }
            )
            shared_result = Chat(**shared_chat.model_dump())
            db.add(shared_result)
            db.commit()
            db.refresh(shared_result)
            # Update the original chat with the share_id
            result = (
144
145
146
                db.query(Chat)
                .filter_by(id=chat_id)
                .update({"share_id": shared_chat.id})
147
            )
Timothy J. Baek's avatar
Timothy J. Baek committed
148

149
150
            return shared_chat if (shared_result and result) else None

151
    def update_shared_chat_by_chat_id(self, chat_id: str) -> Optional[ChatModel]:
152
153
154
155
156
157
158
159
160
161
162
163
164
        with get_session() as db:
            try:
                print("update_shared_chat_by_id")
                chat = db.get(Chat, chat_id)
                print(chat)
                chat.title = chat.title
                chat.chat = chat.chat
                db.commit()
                db.refresh(chat)

                return self.get_chat_by_id(chat.share_id)
            except:
                return None
Timothy J. Baek's avatar
Timothy J. Baek committed
165

166
    def delete_shared_chat_by_chat_id(self, chat_id: str) -> bool:
Timothy J. Baek's avatar
Timothy J. Baek committed
167
        try:
168
169
            with get_session() as db:
                db.query(Chat).filter_by(user_id=f"shared-{chat_id}").delete()
Timothy J. Baek's avatar
Timothy J. Baek committed
170
171
172
173
            return True
        except:
            return False

174
    def update_chat_share_id_by_id(
175
        self, id: str, share_id: Optional[str]
176
177
    ) -> Optional[ChatModel]:
        try:
178
179
180
181
182
183
            with get_session() as db:
                chat = db.get(Chat, id)
                chat.share_id = share_id
                db.commit()
                db.refresh(chat)
                return chat
184
185
186
        except:
            return None

187
    def toggle_chat_archive_by_id(self, id: str) -> Optional[ChatModel]:
Timothy J. Baek's avatar
Timothy J. Baek committed
188
        try:
189
190
191
            with get_session() as db:
                chat = self.get_chat_by_id(id)
                db.query(Chat).filter_by(id=id).update({"archived": not chat.archived})
Timothy J. Baek's avatar
Timothy J. Baek committed
192

193
                return self.get_chat_by_id(id)
Timothy J. Baek's avatar
Timothy J. Baek committed
194
195
196
        except:
            return None

197
    def archive_all_chats_by_user_id(self, user_id: str) -> bool:
198
        try:
199
200
            with get_session() as db:
                db.query(Chat).filter_by(user_id=user_id).update({"archived": True})
201
202
203
204
205

            return True
        except:
            return False

Timothy J. Baek's avatar
Timothy J. Baek committed
206
    def get_archived_chat_list_by_user_id(
207
        self, user_id: str, skip: int = 0, limit: int = 50
208
    ) -> List[ChatModel]:
209
210
211
212
213
214
215
216
217
        with get_session() as db:
            all_chats = (
                db.query(Chat)
                .filter_by(user_id=user_id, archived=True)
                .order_by(Chat.updated_at.desc())
                # .limit(limit).offset(skip)
                .all()
            )
            return [ChatModel.model_validate(chat) for chat in all_chats]
218

Timothy J. Baek's avatar
Timothy J. Baek committed
219
    def get_chat_list_by_user_id(
220
221
222
223
224
        self,
        user_id: str,
        include_archived: bool = False,
        skip: int = 0,
        limit: int = 50,
Timothy J. Baek's avatar
Timothy J. Baek committed
225
    ) -> List[ChatModel]:
226
227
228
229
230
231
232
233
234
235
        with get_session() as db:
            query = db.query(Chat).filter_by(user_id=user_id)
            if not include_archived:
                query = query.filter_by(archived=False)
            all_chats = (
                query.order_by(Chat.updated_at.desc())
                # .limit(limit).offset(skip)
                .all()
            )
            return [ChatModel.model_validate(chat) for chat in all_chats]
Timothy J. Baek's avatar
Timothy J. Baek committed
236

Timothy J. Baek's avatar
Timothy J. Baek committed
237
    def get_chat_list_by_chat_ids(
238
        self, chat_ids: List[str], skip: int = 0, limit: int = 50
Timothy J. Baek's avatar
Timothy J. Baek committed
239
    ) -> List[ChatModel]:
240
241
242
243
244
245
246
247
248
249
250
        with get_session() as db:
            all_chats = (
                db.query(Chat)
                .filter(Chat.id.in_(chat_ids))
                .filter_by(archived=False)
                .order_by(Chat.updated_at.desc())
                .all()
            )
            return [ChatModel.model_validate(chat) for chat in all_chats]

    def get_chat_by_id(self, id: str) -> Optional[ChatModel]:
Timothy J. Baek's avatar
Timothy J. Baek committed
251
        try:
252
253
254
            with get_session() as db:
                chat = db.get(Chat, id)
                return ChatModel.model_validate(chat)
Timothy J. Baek's avatar
Timothy J. Baek committed
255
256
257
        except:
            return None

258
    def get_chat_by_share_id(self, id: str) -> Optional[ChatModel]:
259
        try:
260
261
            with get_session() as db:
                chat = db.query(Chat).filter_by(share_id=id).first()
262

263
264
265
266
                if chat:
                    return self.get_chat_by_id(id)
                else:
                    return None
267
        except Exception as e:
268
269
            return None

270
    def get_chat_by_id_and_user_id(self, id: str, user_id: str) -> Optional[ChatModel]:
Timothy J. Baek's avatar
Timothy J. Baek committed
271
        try:
272
273
274
            with get_session() as db:
                chat = db.query(Chat).filter_by(id=id, user_id=user_id).first()
                return ChatModel.model_validate(chat)
Timothy J. Baek's avatar
Timothy J. Baek committed
275
276
277
        except:
            return None

278
279
280
281
282
283
284
285
    def get_chats(self, skip: int = 0, limit: int = 50) -> List[ChatModel]:
        with get_session() as db:
            all_chats = (
                db.query(Chat)
                # .limit(limit).offset(skip)
                .order_by(Chat.updated_at.desc())
            )
            return [ChatModel.model_validate(chat) for chat in all_chats]
286

287
288
289
    def get_chats_by_user_id(self, user_id: str) -> List[ChatModel]:
        with get_session() as db:
            all_chats = (
290
291
292
                db.query(Chat)
                .filter_by(user_id=user_id)
                .order_by(Chat.updated_at.desc())
293
294
            )
            return [ChatModel.model_validate(chat) for chat in all_chats]
295

296
    def get_archived_chats_by_user_id(self, user_id: str) -> List[ChatModel]:
297
298
299
300
301
302
303
304
305
        with get_session() as db:
            all_chats = (
                db.query(Chat)
                .filter_by(user_id=user_id, archived=True)
                .order_by(Chat.updated_at.desc())
            )
            return [ChatModel.model_validate(chat) for chat in all_chats]

    def delete_chat_by_id(self, id: str) -> bool:
306
        try:
307
308
            with get_session() as db:
                db.query(Chat).filter_by(id=id).delete()
309

310
                return True and self.delete_shared_chat_by_chat_id(id)
311
312
313
        except:
            return False

314
    def delete_chat_by_id_and_user_id(self, id: str, user_id: str) -> bool:
315
        try:
316
317
            with get_session() as db:
                db.query(Chat).filter_by(id=id, user_id=user_id).delete()
318

319
                return True and self.delete_shared_chat_by_chat_id(id)
320
321
322
        except:
            return False

323
    def delete_chats_by_user_id(self, user_id: str) -> bool:
324
        try:
325
326
            with get_session() as db:
                self.delete_shared_chats_by_user_id(user_id)
327

328
                db.query(Chat).filter_by(user_id=user_id).delete()
329
            return True
Timothy J. Baek's avatar
Timothy J. Baek committed
330
331
332
        except:
            return False

333
    def delete_shared_chats_by_user_id(self, user_id: str) -> bool:
Timothy J. Baek's avatar
Timothy J. Baek committed
334
        try:
335
336
337
            with get_session() as db:
                chats_by_user = db.query(Chat).filter_by(user_id=user_id).all()
                shared_chat_ids = [f"shared-{chat.id}" for chat in chats_by_user]
Timothy J. Baek's avatar
Timothy J. Baek committed
338

339
                db.query(Chat).filter(Chat.user_id.in_(shared_chat_ids)).delete()
Timothy J. Baek's avatar
Timothy J. Baek committed
340

341
342
343
344
            return True
        except:
            return False

Timothy J. Baek's avatar
Timothy J. Baek committed
345

346
Chats = ChatTable()