chats.py 27 KB

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