chats.py 29 KB

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