chats.py 28 KB

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