chats.py 30 KB

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