chats.py 27 KB

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