chats.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  1. import json
  2. import time
  3. import uuid
  4. from typing import Optional
  5. from open_webui.apps.webui.internal.db import Base, get_db
  6. from open_webui.apps.webui.models.tags import TagModel, Tag, Tags
  7. from pydantic import BaseModel, ConfigDict
  8. from sqlalchemy import BigInteger, Boolean, Column, String, Text, JSON
  9. from sqlalchemy import or_, func, select, and_, text
  10. from sqlalchemy.sql import exists
  11. ####################
  12. # Chat DB Schema
  13. ####################
  14. class Chat(Base):
  15. __tablename__ = "chat"
  16. id = Column(String, primary_key=True)
  17. user_id = Column(String)
  18. title = Column(Text)
  19. chat = Column(JSON)
  20. created_at = Column(BigInteger)
  21. updated_at = Column(BigInteger)
  22. share_id = Column(Text, unique=True, nullable=True)
  23. archived = Column(Boolean, default=False)
  24. pinned = Column(Boolean, default=False, nullable=True)
  25. meta = Column(JSON, server_default="{}")
  26. folder_id = Column(Text, nullable=True)
  27. class ChatModel(BaseModel):
  28. model_config = ConfigDict(from_attributes=True)
  29. id: str
  30. user_id: str
  31. title: str
  32. chat: dict
  33. created_at: int # timestamp in epoch
  34. updated_at: int # timestamp in epoch
  35. share_id: Optional[str] = None
  36. archived: bool = False
  37. pinned: Optional[bool] = False
  38. meta: dict = {}
  39. folder_id: Optional[str] = None
  40. ####################
  41. # Forms
  42. ####################
  43. class ChatForm(BaseModel):
  44. chat: dict
  45. class ChatTitleMessagesForm(BaseModel):
  46. title: str
  47. messages: list[dict]
  48. class ChatTitleForm(BaseModel):
  49. title: str
  50. class ChatResponse(BaseModel):
  51. id: str
  52. user_id: str
  53. title: str
  54. chat: dict
  55. updated_at: int # timestamp in epoch
  56. created_at: int # timestamp in epoch
  57. share_id: Optional[str] = None # id of the chat to be shared
  58. archived: bool
  59. pinned: Optional[bool] = False
  60. meta: dict = {}
  61. folder_id: Optional[str] = None
  62. class ChatTitleIdResponse(BaseModel):
  63. id: str
  64. title: str
  65. updated_at: int
  66. created_at: int
  67. class ChatTable:
  68. def insert_new_chat(self, user_id: str, form_data: ChatForm) -> Optional[ChatModel]:
  69. with get_db() as db:
  70. id = str(uuid.uuid4())
  71. chat = ChatModel(
  72. **{
  73. "id": id,
  74. "user_id": user_id,
  75. "title": (
  76. form_data.chat["title"]
  77. if "title" in form_data.chat
  78. else "New Chat"
  79. ),
  80. "chat": form_data.chat,
  81. "created_at": int(time.time()),
  82. "updated_at": int(time.time()),
  83. }
  84. )
  85. result = Chat(**chat.model_dump())
  86. db.add(result)
  87. db.commit()
  88. db.refresh(result)
  89. return ChatModel.model_validate(result) if result else None
  90. def update_chat_by_id(self, id: str, chat: dict) -> Optional[ChatModel]:
  91. try:
  92. with get_db() as db:
  93. chat_item = db.get(Chat, id)
  94. chat_item.chat = chat
  95. chat_item.title = chat["title"] if "title" in chat else "New Chat"
  96. chat_item.updated_at = int(time.time())
  97. db.commit()
  98. db.refresh(chat_item)
  99. return ChatModel.model_validate(chat_item)
  100. except Exception:
  101. return None
  102. def insert_shared_chat_by_chat_id(self, chat_id: str) -> Optional[ChatModel]:
  103. with get_db() as db:
  104. # Get the existing chat to share
  105. chat = db.get(Chat, chat_id)
  106. # Check if the chat is already shared
  107. if chat.share_id:
  108. return self.get_chat_by_id_and_user_id(chat.share_id, "shared")
  109. # Create a new chat with the same data, but with a new ID
  110. shared_chat = ChatModel(
  111. **{
  112. "id": str(uuid.uuid4()),
  113. "user_id": f"shared-{chat_id}",
  114. "title": chat.title,
  115. "chat": chat.chat,
  116. "created_at": chat.created_at,
  117. "updated_at": int(time.time()),
  118. }
  119. )
  120. shared_result = Chat(**shared_chat.model_dump())
  121. db.add(shared_result)
  122. db.commit()
  123. db.refresh(shared_result)
  124. # Update the original chat with the share_id
  125. result = (
  126. db.query(Chat)
  127. .filter_by(id=chat_id)
  128. .update({"share_id": shared_chat.id})
  129. )
  130. db.commit()
  131. return shared_chat if (shared_result and result) else None
  132. def update_shared_chat_by_chat_id(self, chat_id: str) -> Optional[ChatModel]:
  133. try:
  134. with get_db() as db:
  135. print("update_shared_chat_by_id")
  136. chat = db.get(Chat, chat_id)
  137. print(chat)
  138. chat.title = chat.title
  139. chat.chat = chat.chat
  140. db.commit()
  141. db.refresh(chat)
  142. return self.get_chat_by_id(chat.share_id)
  143. except Exception:
  144. return None
  145. def delete_shared_chat_by_chat_id(self, chat_id: str) -> bool:
  146. try:
  147. with get_db() as db:
  148. db.query(Chat).filter_by(user_id=f"shared-{chat_id}").delete()
  149. db.commit()
  150. return True
  151. except Exception:
  152. return False
  153. def update_chat_share_id_by_id(
  154. self, id: str, share_id: Optional[str]
  155. ) -> Optional[ChatModel]:
  156. try:
  157. with get_db() as db:
  158. chat = db.get(Chat, id)
  159. chat.share_id = share_id
  160. db.commit()
  161. db.refresh(chat)
  162. return ChatModel.model_validate(chat)
  163. except Exception:
  164. return None
  165. def toggle_chat_pinned_by_id(self, id: str) -> Optional[ChatModel]:
  166. try:
  167. with get_db() as db:
  168. chat = db.get(Chat, id)
  169. chat.pinned = not chat.pinned
  170. chat.updated_at = int(time.time())
  171. db.commit()
  172. db.refresh(chat)
  173. return ChatModel.model_validate(chat)
  174. except Exception:
  175. return None
  176. def toggle_chat_archive_by_id(self, id: str) -> Optional[ChatModel]:
  177. try:
  178. with get_db() as db:
  179. chat = db.get(Chat, id)
  180. chat.archived = not chat.archived
  181. chat.updated_at = int(time.time())
  182. db.commit()
  183. db.refresh(chat)
  184. return ChatModel.model_validate(chat)
  185. except Exception:
  186. return None
  187. def archive_all_chats_by_user_id(self, user_id: str) -> bool:
  188. try:
  189. with get_db() as db:
  190. db.query(Chat).filter_by(user_id=user_id).update({"archived": True})
  191. db.commit()
  192. return True
  193. except Exception:
  194. return False
  195. def get_archived_chat_list_by_user_id(
  196. self, user_id: str, skip: int = 0, limit: int = 50
  197. ) -> list[ChatModel]:
  198. with get_db() as db:
  199. all_chats = (
  200. db.query(Chat)
  201. .filter_by(user_id=user_id, archived=True)
  202. .order_by(Chat.updated_at.desc())
  203. # .limit(limit).offset(skip)
  204. .all()
  205. )
  206. return [ChatModel.model_validate(chat) for chat in all_chats]
  207. def get_chat_list_by_user_id(
  208. self,
  209. user_id: str,
  210. include_archived: bool = False,
  211. skip: int = 0,
  212. limit: int = 50,
  213. ) -> list[ChatModel]:
  214. with get_db() as db:
  215. query = db.query(Chat).filter_by(user_id=user_id).filter_by(folder_id=None)
  216. if not include_archived:
  217. query = query.filter_by(archived=False)
  218. query = query.order_by(Chat.updated_at.desc())
  219. if skip:
  220. query = query.offset(skip)
  221. if limit:
  222. query = query.limit(limit)
  223. all_chats = query.all()
  224. return [ChatModel.model_validate(chat) for chat in all_chats]
  225. def get_chat_title_id_list_by_user_id(
  226. self,
  227. user_id: str,
  228. include_archived: bool = False,
  229. skip: Optional[int] = None,
  230. limit: Optional[int] = None,
  231. ) -> list[ChatTitleIdResponse]:
  232. with get_db() as db:
  233. query = db.query(Chat).filter_by(user_id=user_id).filter_by(folder_id=None)
  234. query = query.filter(or_(Chat.pinned == False, Chat.pinned == None))
  235. if not include_archived:
  236. query = query.filter_by(archived=False)
  237. query = query.order_by(Chat.updated_at.desc()).with_entities(
  238. Chat.id, Chat.title, Chat.updated_at, Chat.created_at
  239. )
  240. if skip:
  241. query = query.offset(skip)
  242. if limit:
  243. query = query.limit(limit)
  244. all_chats = query.all()
  245. # result has to be destrctured from sqlalchemy `row` and mapped to a dict since the `ChatModel`is not the returned dataclass.
  246. return [
  247. ChatTitleIdResponse.model_validate(
  248. {
  249. "id": chat[0],
  250. "title": chat[1],
  251. "updated_at": chat[2],
  252. "created_at": chat[3],
  253. }
  254. )
  255. for chat in all_chats
  256. ]
  257. def get_chat_list_by_chat_ids(
  258. self, chat_ids: list[str], skip: int = 0, limit: int = 50
  259. ) -> list[ChatModel]:
  260. with get_db() as db:
  261. all_chats = (
  262. db.query(Chat)
  263. .filter(Chat.id.in_(chat_ids))
  264. .filter_by(archived=False)
  265. .order_by(Chat.updated_at.desc())
  266. .all()
  267. )
  268. return [ChatModel.model_validate(chat) for chat in all_chats]
  269. def get_chat_by_id(self, id: str) -> Optional[ChatModel]:
  270. try:
  271. with get_db() as db:
  272. chat = db.get(Chat, id)
  273. return ChatModel.model_validate(chat)
  274. except Exception:
  275. return None
  276. def get_chat_by_share_id(self, id: str) -> Optional[ChatModel]:
  277. try:
  278. with get_db() as db:
  279. chat = db.query(Chat).filter_by(share_id=id).first()
  280. if chat:
  281. return self.get_chat_by_id(id)
  282. else:
  283. return None
  284. except Exception:
  285. return None
  286. def get_chat_by_id_and_user_id(self, id: str, user_id: str) -> Optional[ChatModel]:
  287. try:
  288. with get_db() as db:
  289. chat = db.query(Chat).filter_by(id=id, user_id=user_id).first()
  290. return ChatModel.model_validate(chat)
  291. except Exception:
  292. return None
  293. def get_chats(self, skip: int = 0, limit: int = 50) -> list[ChatModel]:
  294. with get_db() as db:
  295. all_chats = (
  296. db.query(Chat)
  297. # .limit(limit).offset(skip)
  298. .order_by(Chat.updated_at.desc())
  299. )
  300. return [ChatModel.model_validate(chat) for chat in all_chats]
  301. def get_chats_by_user_id(self, user_id: str) -> list[ChatModel]:
  302. with get_db() as db:
  303. all_chats = (
  304. db.query(Chat)
  305. .filter_by(user_id=user_id)
  306. .order_by(Chat.updated_at.desc())
  307. )
  308. return [ChatModel.model_validate(chat) for chat in all_chats]
  309. def get_pinned_chats_by_user_id(self, user_id: str) -> list[ChatModel]:
  310. with get_db() as db:
  311. all_chats = (
  312. db.query(Chat)
  313. .filter_by(user_id=user_id, pinned=True, archived=False)
  314. .filter(Chat.folder_id == None)
  315. .order_by(Chat.updated_at.desc())
  316. )
  317. return [ChatModel.model_validate(chat) for chat in all_chats]
  318. def get_archived_chats_by_user_id(self, user_id: str) -> list[ChatModel]:
  319. with get_db() as db:
  320. all_chats = (
  321. db.query(Chat)
  322. .filter_by(user_id=user_id, archived=True)
  323. .order_by(Chat.updated_at.desc())
  324. )
  325. return [ChatModel.model_validate(chat) for chat in all_chats]
  326. def get_chats_by_user_id_and_search_text(
  327. self,
  328. user_id: str,
  329. search_text: str,
  330. include_archived: bool = False,
  331. skip: int = 0,
  332. limit: int = 60,
  333. ) -> list[ChatModel]:
  334. """
  335. Filters chats based on a search query using Python, allowing pagination using skip and limit.
  336. """
  337. search_text = search_text.lower().strip()
  338. if not search_text:
  339. return self.get_chat_list_by_user_id(user_id, include_archived, skip, limit)
  340. search_text_words = search_text.split(" ")
  341. # search_text might contain 'tag:tag_name' format so we need to extract the tag_name, split the search_text and remove the tags
  342. tag_ids = [
  343. word.replace("tag:", "").replace(" ", "_").lower()
  344. for word in search_text_words
  345. if word.startswith("tag:")
  346. ]
  347. search_text_words = [
  348. word for word in search_text_words if not word.startswith("tag:")
  349. ]
  350. search_text = " ".join(search_text_words)
  351. with get_db() as db:
  352. query = db.query(Chat).filter(Chat.user_id == user_id)
  353. if not include_archived:
  354. query = query.filter(Chat.archived == False)
  355. query = query.order_by(Chat.updated_at.desc())
  356. # Check if the database dialect is either 'sqlite' or 'postgresql'
  357. dialect_name = db.bind.dialect.name
  358. if dialect_name == "sqlite":
  359. # SQLite case: using JSON1 extension for JSON searching
  360. query = query.filter(
  361. (
  362. Chat.title.ilike(
  363. f"%{search_text}%"
  364. ) # Case-insensitive search in title
  365. | text(
  366. """
  367. EXISTS (
  368. SELECT 1
  369. FROM json_each(Chat.chat, '$.messages') AS message
  370. WHERE LOWER(message.value->>'content') LIKE '%' || :search_text || '%'
  371. )
  372. """
  373. )
  374. ).params(search_text=search_text)
  375. )
  376. # Check if there are any tags to filter, it should have all the tags
  377. if tag_ids:
  378. query = query.filter(
  379. and_(
  380. *[
  381. text(
  382. f"""
  383. EXISTS (
  384. SELECT 1
  385. FROM json_each(Chat.meta, '$.tags') AS tag
  386. WHERE tag.value = :tag_id_{tag_idx}
  387. )
  388. """
  389. ).params(**{f"tag_id_{tag_idx}": tag_id})
  390. for tag_idx, tag_id in enumerate(tag_ids)
  391. ]
  392. )
  393. )
  394. elif dialect_name == "postgresql":
  395. # PostgreSQL relies on proper JSON query for search
  396. query = query.filter(
  397. (
  398. Chat.title.ilike(
  399. f"%{search_text}%"
  400. ) # Case-insensitive search in title
  401. | text(
  402. """
  403. EXISTS (
  404. SELECT 1
  405. FROM json_array_elements(Chat.chat->'messages') AS message
  406. WHERE LOWER(message->>'content') LIKE '%' || :search_text || '%'
  407. )
  408. """
  409. )
  410. ).params(search_text=search_text)
  411. )
  412. # Check if there are any tags to filter, it should have all the tags
  413. if tag_ids:
  414. query = query.filter(
  415. and_(
  416. *[
  417. text(
  418. f"""
  419. EXISTS (
  420. SELECT 1
  421. FROM json_array_elements_text(Chat.meta->'tags') AS tag
  422. WHERE tag = :tag_id_{tag_idx}
  423. )
  424. """
  425. ).params(**{f"tag_id_{tag_idx}": tag_id})
  426. for tag_idx, tag_id in enumerate(tag_ids)
  427. ]
  428. )
  429. )
  430. else:
  431. raise NotImplementedError(
  432. f"Unsupported dialect: {db.bind.dialect.name}"
  433. )
  434. # Perform pagination at the SQL level
  435. all_chats = query.offset(skip).limit(limit).all()
  436. print(len(all_chats))
  437. # Validate and return chats
  438. return [ChatModel.model_validate(chat) for chat in all_chats]
  439. def get_chats_by_folder_id_and_user_id(
  440. self, folder_id: str, user_id: str
  441. ) -> list[ChatModel]:
  442. with get_db() as db:
  443. query = db.query(Chat).filter_by(folder_id=folder_id, user_id=user_id)
  444. query = query.filter_by(archived=False)
  445. query = query.order_by(Chat.updated_at.desc())
  446. all_chats = query.all()
  447. return [ChatModel.model_validate(chat) for chat in all_chats]
  448. def update_chat_folder_id_by_id_and_user_id(
  449. self, id: str, user_id: str, folder_id: str
  450. ) -> Optional[ChatModel]:
  451. try:
  452. with get_db() as db:
  453. chat = db.get(Chat, id)
  454. chat.folder_id = folder_id
  455. chat.updated_at = int(time.time())
  456. db.commit()
  457. db.refresh(chat)
  458. return ChatModel.model_validate(chat)
  459. except Exception:
  460. return None
  461. def get_chat_tags_by_id_and_user_id(self, id: str, user_id: str) -> list[TagModel]:
  462. with get_db() as db:
  463. chat = db.get(Chat, id)
  464. tags = chat.meta.get("tags", [])
  465. return [Tags.get_tag_by_name_and_user_id(tag, user_id) for tag in tags]
  466. def get_chat_list_by_user_id_and_tag_name(
  467. self, user_id: str, tag_name: str, skip: int = 0, limit: int = 50
  468. ) -> list[ChatModel]:
  469. with get_db() as db:
  470. query = db.query(Chat).filter_by(user_id=user_id)
  471. tag_id = tag_name.replace(" ", "_").lower()
  472. print(db.bind.dialect.name)
  473. if db.bind.dialect.name == "sqlite":
  474. # SQLite JSON1 querying for tags within the meta JSON field
  475. query = query.filter(
  476. text(
  477. f"EXISTS (SELECT 1 FROM json_each(Chat.meta, '$.tags') WHERE json_each.value = :tag_id)"
  478. )
  479. ).params(tag_id=tag_id)
  480. elif db.bind.dialect.name == "postgresql":
  481. # PostgreSQL JSON query for tags within the meta JSON field (for `json` type)
  482. query = query.filter(
  483. text(
  484. "EXISTS (SELECT 1 FROM json_array_elements_text(Chat.meta->'tags') elem WHERE elem = :tag_id)"
  485. )
  486. ).params(tag_id=tag_id)
  487. else:
  488. raise NotImplementedError(
  489. f"Unsupported dialect: {db.bind.dialect.name}"
  490. )
  491. all_chats = query.all()
  492. print("all_chats", all_chats)
  493. return [ChatModel.model_validate(chat) for chat in all_chats]
  494. def add_chat_tag_by_id_and_user_id_and_tag_name(
  495. self, id: str, user_id: str, tag_name: str
  496. ) -> Optional[ChatModel]:
  497. tag = Tags.get_tag_by_name_and_user_id(tag_name, user_id)
  498. if tag is None:
  499. tag = Tags.insert_new_tag(tag_name, user_id)
  500. try:
  501. with get_db() as db:
  502. chat = db.get(Chat, id)
  503. tag_id = tag.id
  504. if tag_id not in chat.meta.get("tags", []):
  505. chat.meta = {
  506. **chat.meta,
  507. "tags": list(set(chat.meta.get("tags", []) + [tag_id])),
  508. }
  509. db.commit()
  510. db.refresh(chat)
  511. return ChatModel.model_validate(chat)
  512. except Exception:
  513. return None
  514. def count_chats_by_tag_name_and_user_id(self, tag_name: str, user_id: str) -> int:
  515. with get_db() as db: # Assuming `get_db()` returns a session object
  516. query = db.query(Chat).filter_by(user_id=user_id, archived=False)
  517. # Normalize the tag_name for consistency
  518. tag_id = tag_name.replace(" ", "_").lower()
  519. if db.bind.dialect.name == "sqlite":
  520. # SQLite JSON1 support for querying the tags inside the `meta` JSON field
  521. query = query.filter(
  522. text(
  523. f"EXISTS (SELECT 1 FROM json_each(Chat.meta, '$.tags') WHERE json_each.value = :tag_id)"
  524. )
  525. ).params(tag_id=tag_id)
  526. elif db.bind.dialect.name == "postgresql":
  527. # PostgreSQL JSONB support for querying the tags inside the `meta` JSON field
  528. query = query.filter(
  529. text(
  530. "EXISTS (SELECT 1 FROM json_array_elements_text(Chat.meta->'tags') elem WHERE elem = :tag_id)"
  531. )
  532. ).params(tag_id=tag_id)
  533. else:
  534. raise NotImplementedError(
  535. f"Unsupported dialect: {db.bind.dialect.name}"
  536. )
  537. # Get the count of matching records
  538. count = query.count()
  539. # Debugging output for inspection
  540. print(f"Count of chats for tag '{tag_name}':", count)
  541. return count
  542. def delete_tag_by_id_and_user_id_and_tag_name(
  543. self, id: str, user_id: str, tag_name: str
  544. ) -> bool:
  545. try:
  546. with get_db() as db:
  547. chat = db.get(Chat, id)
  548. tags = chat.meta.get("tags", [])
  549. tag_id = tag_name.replace(" ", "_").lower()
  550. tags = [tag for tag in tags if tag != tag_id]
  551. chat.meta = {
  552. **chat.meta,
  553. "tags": list(set(tags)),
  554. }
  555. db.commit()
  556. return True
  557. except Exception:
  558. return False
  559. def delete_all_tags_by_id_and_user_id(self, id: str, user_id: str) -> bool:
  560. try:
  561. with get_db() as db:
  562. chat = db.get(Chat, id)
  563. chat.meta = {
  564. **chat.meta,
  565. "tags": [],
  566. }
  567. db.commit()
  568. return True
  569. except Exception:
  570. return False
  571. def delete_chat_by_id(self, id: str) -> bool:
  572. try:
  573. with get_db() as db:
  574. db.query(Chat).filter_by(id=id).delete()
  575. db.commit()
  576. return True and self.delete_shared_chat_by_chat_id(id)
  577. except Exception:
  578. return False
  579. def delete_chat_by_id_and_user_id(self, id: str, user_id: str) -> bool:
  580. try:
  581. with get_db() as db:
  582. db.query(Chat).filter_by(id=id, user_id=user_id).delete()
  583. db.commit()
  584. return True and self.delete_shared_chat_by_chat_id(id)
  585. except Exception:
  586. return False
  587. def delete_chats_by_user_id(self, user_id: str) -> bool:
  588. try:
  589. with get_db() as db:
  590. self.delete_shared_chats_by_user_id(user_id)
  591. db.query(Chat).filter_by(user_id=user_id).delete()
  592. db.commit()
  593. return True
  594. except Exception:
  595. return False
  596. def delete_chats_by_user_id_and_folder_id(
  597. self, user_id: str, folder_id: str
  598. ) -> bool:
  599. try:
  600. with get_db() as db:
  601. db.query(Chat).filter_by(user_id=user_id, folder_id=folder_id).delete()
  602. db.commit()
  603. return True
  604. except Exception:
  605. return False
  606. def delete_shared_chats_by_user_id(self, user_id: str) -> bool:
  607. try:
  608. with get_db() as db:
  609. chats_by_user = db.query(Chat).filter_by(user_id=user_id).all()
  610. shared_chat_ids = [f"shared-{chat.id}" for chat in chats_by_user]
  611. db.query(Chat).filter(Chat.user_id.in_(shared_chat_ids)).delete()
  612. db.commit()
  613. return True
  614. except Exception:
  615. return False
  616. Chats = ChatTable()