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(
83
        self, user_id: str, form_data: ChatForm
84
    ) -> Optional[ChatModel]:
85
86
87
88
89
90
91
92
93
94
95
        with get_session() as db:
            id = str(uuid.uuid4())
            chat = ChatModel(
                **{
                    "id": id,
                    "user_id": user_id,
                    "title": (
                        form_data.chat["title"] if "title" in form_data.chat else "New Chat"
                    ),
                    "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
107
    def update_chat_by_id(
        self, id: str, chat: dict
108
    ) -> Optional[ChatModel]:
109
110
111
112
113
114
115
116
117
118
119
120
        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
121

122
123
    def insert_shared_chat_by_chat_id(
        self, chat_id: str
124
    ) -> Optional[ChatModel]:
125
126
        with get_session() as db:
            # Get the existing chat to share
127
            chat = db.get(Chat, chat_id)
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
            # 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 = (
                db.query(Chat).filter_by(id=chat_id).update({"share_id": shared_chat.id})
149
            )
Timothy J. Baek's avatar
Timothy J. Baek committed
150

151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
            return shared_chat if (shared_result and result) else None

    def update_shared_chat_by_chat_id(
        self, chat_id: str
    ) -> Optional[ChatModel]:
        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
169

170
    def delete_shared_chat_by_chat_id(self, chat_id: str) -> bool:
Timothy J. Baek's avatar
Timothy J. Baek committed
171
        try:
172
173
            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
174
175
176
177
            return True
        except:
            return False

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

191
    def toggle_chat_archive_by_id(self, id: str) -> Optional[ChatModel]:
Timothy J. Baek's avatar
Timothy J. Baek committed
192
        try:
193
194
195
            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
196

197
                return self.get_chat_by_id(id)
Timothy J. Baek's avatar
Timothy J. Baek committed
198
199
200
        except:
            return None

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

            return True
        except:
            return False

Timothy J. Baek's avatar
Timothy J. Baek committed
210
    def get_archived_chat_list_by_user_id(
211
        self, user_id: str, skip: int = 0, limit: int = 50
212
    ) -> List[ChatModel]:
213
214
215
216
217
218
219
220
221
        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]
222

Timothy J. Baek's avatar
Timothy J. Baek committed
223
    def get_chat_list_by_user_id(
224
225
226
227
228
        self,
        user_id: str,
        include_archived: bool = False,
        skip: int = 0,
        limit: int = 50,
Timothy J. Baek's avatar
Timothy J. Baek committed
229
    ) -> List[ChatModel]:
230
231
232
233
234
235
236
237
238
239
        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
240

Timothy J. Baek's avatar
Timothy J. Baek committed
241
    def get_chat_list_by_chat_ids(
242
        self, chat_ids: List[str], skip: int = 0, limit: int = 50
Timothy J. Baek's avatar
Timothy J. Baek committed
243
    ) -> List[ChatModel]:
244
245
246
247
248
249
250
251
252
253
254
        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
255
        try:
256
257
258
            with get_session() as db:
                chat = db.get(Chat, id)
                return ChatModel.model_validate(chat)
Timothy J. Baek's avatar
Timothy J. Baek committed
259
260
261
        except:
            return None

262
    def get_chat_by_share_id(self, id: str) -> Optional[ChatModel]:
263
        try:
264
265
            with get_session() as db:
                chat = db.query(Chat).filter_by(share_id=id).first()
266

267
268
269
270
                if chat:
                    return self.get_chat_by_id(id)
                else:
                    return None
271
        except Exception as e:
272
273
            return None

274
    def get_chat_by_id_and_user_id(
275
        self, id: str, user_id: str
276
    ) -> Optional[ChatModel]:
Timothy J. Baek's avatar
Timothy J. Baek committed
277
        try:
278
279
280
            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
281
282
283
        except:
            return None

284
285
286
287
288
289
290
291
    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]
292

293
294
295
296
297
298
    def get_chats_by_user_id(self, user_id: str) -> List[ChatModel]:
        with get_session() as db:
            all_chats = (
                db.query(Chat).filter_by(user_id=user_id).order_by(Chat.updated_at.desc())
            )
            return [ChatModel.model_validate(chat) for chat in all_chats]
299
300

    def get_archived_chats_by_user_id(
301
        self, user_id: str
302
    ) -> List[ChatModel]:
303
304
305
306
307
308
309
310
311
        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:
312
        try:
313
314
            with get_session() as db:
                db.query(Chat).filter_by(id=id).delete()
315

316
                return True and self.delete_shared_chat_by_chat_id(id)
317
318
319
        except:
            return False

320
    def delete_chat_by_id_and_user_id(self, id: str, user_id: str) -> bool:
321
        try:
322
323
            with get_session() as db:
                db.query(Chat).filter_by(id=id, user_id=user_id).delete()
324

325
                return True and self.delete_shared_chat_by_chat_id(id)
326
327
328
        except:
            return False

329
    def delete_chats_by_user_id(self, user_id: str) -> bool:
330
        try:
331
332
            with get_session() as db:
                self.delete_shared_chats_by_user_id(user_id)
333

334
                db.query(Chat).filter_by(user_id=user_id).delete()
335
            return True
Timothy J. Baek's avatar
Timothy J. Baek committed
336
337
338
        except:
            return False

339
    def delete_shared_chats_by_user_id(self, user_id: str) -> bool:
Timothy J. Baek's avatar
Timothy J. Baek committed
340
        try:
341
342
343
            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
344

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

347
348
349
350
            return True
        except:
            return False

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

352
Chats = ChatTable()