chats.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  1. import logging
  2. import json
  3. import time
  4. import uuid
  5. from typing import Optional
  6. from open_webui.internal.db import Base, get_db
  7. from open_webui.models.tags import TagModel, Tag, Tags
  8. from open_webui.models.folders import Folders
  9. from open_webui.env import SRC_LOG_LEVELS
  10. from pydantic import BaseModel, ConfigDict
  11. from sqlalchemy import BigInteger, Boolean, Column, String, Text, JSON
  12. from sqlalchemy import or_, func, select, and_, text
  13. from sqlalchemy.sql import exists
  14. from sqlalchemy.sql.expression import bindparam
  15. ####################
  16. # Chat DB Schema
  17. ####################
  18. log = logging.getLogger(__name__)
  19. log.setLevel(SRC_LOG_LEVELS["MODELS"])
  20. class Chat(Base):
  21. __tablename__ = "chat"
  22. id = Column(String, primary_key=True)
  23. user_id = Column(String)
  24. title = Column(Text)
  25. chat = Column(JSON)
  26. created_at = Column(BigInteger)
  27. updated_at = Column(BigInteger)
  28. share_id = Column(Text, unique=True, nullable=True)
  29. archived = Column(Boolean, default=False)
  30. pinned = Column(Boolean, default=False, nullable=True)
  31. meta = Column(JSON, server_default="{}")
  32. folder_id = Column(Text, nullable=True)
  33. class ChatModel(BaseModel):
  34. model_config = ConfigDict(from_attributes=True)
  35. id: str
  36. user_id: str
  37. title: str
  38. chat: dict
  39. created_at: int # timestamp in epoch
  40. updated_at: int # timestamp in epoch
  41. share_id: Optional[str] = None
  42. archived: bool = False
  43. pinned: Optional[bool] = False
  44. meta: dict = {}
  45. folder_id: Optional[str] = None
  46. ####################
  47. # Forms
  48. ####################
  49. class ChatForm(BaseModel):
  50. chat: dict
  51. folder_id: Optional[str] = None
  52. class ChatImportForm(ChatForm):
  53. meta: Optional[dict] = {}
  54. pinned: Optional[bool] = False
  55. created_at: Optional[int] = None
  56. updated_at: Optional[int] = None
  57. class ChatTitleMessagesForm(BaseModel):
  58. title: str
  59. messages: list[dict]
  60. class ChatTitleForm(BaseModel):
  61. title: str
  62. class ChatResponse(BaseModel):
  63. id: str
  64. user_id: str
  65. title: str
  66. chat: dict
  67. updated_at: int # timestamp in epoch
  68. created_at: int # timestamp in epoch
  69. share_id: Optional[str] = None # id of the chat to be shared
  70. archived: bool
  71. pinned: Optional[bool] = False
  72. meta: dict = {}
  73. folder_id: Optional[str] = None
  74. class ChatTitleIdResponse(BaseModel):
  75. id: str
  76. title: str
  77. updated_at: int
  78. created_at: int
  79. class ChatTable:
  80. def insert_new_chat(self, user_id: str, form_data: ChatForm) -> Optional[ChatModel]:
  81. with get_db() as db:
  82. id = str(uuid.uuid4())
  83. chat = ChatModel(
  84. **{
  85. "id": id,
  86. "user_id": user_id,
  87. "title": (
  88. form_data.chat["title"]
  89. if "title" in form_data.chat
  90. else "New Chat"
  91. ),
  92. "chat": form_data.chat,
  93. "folder_id": form_data.folder_id,
  94. "created_at": int(time.time()),
  95. "updated_at": int(time.time()),
  96. }
  97. )
  98. result = Chat(**chat.model_dump())
  99. db.add(result)
  100. db.commit()
  101. db.refresh(result)
  102. return ChatModel.model_validate(result) if result else None
  103. def import_chat(
  104. self, user_id: str, form_data: ChatImportForm
  105. ) -> Optional[ChatModel]:
  106. with get_db() as db:
  107. id = str(uuid.uuid4())
  108. chat = ChatModel(
  109. **{
  110. "id": id,
  111. "user_id": user_id,
  112. "title": (
  113. form_data.chat["title"]
  114. if "title" in form_data.chat
  115. else "New Chat"
  116. ),
  117. "chat": form_data.chat,
  118. "meta": form_data.meta,
  119. "pinned": form_data.pinned,
  120. "folder_id": form_data.folder_id,
  121. "created_at": (
  122. form_data.created_at
  123. if form_data.created_at
  124. else int(time.time())
  125. ),
  126. "updated_at": (
  127. form_data.updated_at
  128. if form_data.updated_at
  129. else int(time.time())
  130. ),
  131. }
  132. )
  133. result = Chat(**chat.model_dump())
  134. db.add(result)
  135. db.commit()
  136. db.refresh(result)
  137. return ChatModel.model_validate(result) if result else None
  138. def update_chat_by_id(self, id: str, chat: dict) -> Optional[ChatModel]:
  139. try:
  140. with get_db() as db:
  141. chat_item = db.get(Chat, id)
  142. chat_item.chat = chat
  143. chat_item.title = chat["title"] if "title" in chat else "New Chat"
  144. chat_item.updated_at = int(time.time())
  145. db.commit()
  146. db.refresh(chat_item)
  147. return ChatModel.model_validate(chat_item)
  148. except Exception:
  149. return None
  150. def update_chat_title_by_id(self, id: str, title: str) -> Optional[ChatModel]:
  151. chat = self.get_chat_by_id(id)
  152. if chat is None:
  153. return None
  154. chat = chat.chat
  155. chat["title"] = title
  156. return self.update_chat_by_id(id, chat)
  157. def update_chat_tags_by_id(
  158. self, id: str, tags: list[str], user
  159. ) -> Optional[ChatModel]:
  160. chat = self.get_chat_by_id(id)
  161. if chat is None:
  162. return None
  163. self.delete_all_tags_by_id_and_user_id(id, user.id)
  164. for tag in chat.meta.get("tags", []):
  165. if self.count_chats_by_tag_name_and_user_id(tag, user.id) == 0:
  166. Tags.delete_tag_by_name_and_user_id(tag, user.id)
  167. for tag_name in tags:
  168. if tag_name.lower() == "none":
  169. continue
  170. self.add_chat_tag_by_id_and_user_id_and_tag_name(id, user.id, tag_name)
  171. return self.get_chat_by_id(id)
  172. def get_chat_title_by_id(self, id: str) -> Optional[str]:
  173. chat = self.get_chat_by_id(id)
  174. if chat is None:
  175. return None
  176. return chat.chat.get("title", "New Chat")
  177. def get_messages_by_chat_id(self, id: str) -> Optional[dict]:
  178. chat = self.get_chat_by_id(id)
  179. if chat is None:
  180. return None
  181. return chat.chat.get("history", {}).get("messages", {}) or {}
  182. def get_message_by_id_and_message_id(
  183. self, id: str, message_id: str
  184. ) -> Optional[dict]:
  185. chat = self.get_chat_by_id(id)
  186. if chat is None:
  187. return None
  188. return chat.chat.get("history", {}).get("messages", {}).get(message_id, {})
  189. def upsert_message_to_chat_by_id_and_message_id(
  190. self, id: str, message_id: str, message: dict
  191. ) -> Optional[ChatModel]:
  192. chat = self.get_chat_by_id(id)
  193. if chat is None:
  194. return None
  195. # Sanitize message content for null characters before upserting
  196. if isinstance(message.get("content"), str):
  197. message["content"] = message["content"].replace("\x00", "")
  198. chat = chat.chat
  199. history = chat.get("history", {})
  200. if message_id in history.get("messages", {}):
  201. history["messages"][message_id] = {
  202. **history["messages"][message_id],
  203. **message,
  204. }
  205. else:
  206. history["messages"][message_id] = message
  207. history["currentId"] = message_id
  208. chat["history"] = history
  209. return self.update_chat_by_id(id, chat)
  210. def add_message_status_to_chat_by_id_and_message_id(
  211. self, id: str, message_id: str, status: dict
  212. ) -> Optional[ChatModel]:
  213. chat = self.get_chat_by_id(id)
  214. if chat is None:
  215. return None
  216. chat = chat.chat
  217. history = chat.get("history", {})
  218. if message_id in history.get("messages", {}):
  219. status_history = history["messages"][message_id].get("statusHistory", [])
  220. status_history.append(status)
  221. history["messages"][message_id]["statusHistory"] = status_history
  222. chat["history"] = history
  223. return self.update_chat_by_id(id, chat)
  224. def insert_shared_chat_by_chat_id(self, chat_id: str) -> Optional[ChatModel]:
  225. with get_db() as db:
  226. # Get the existing chat to share
  227. chat = db.get(Chat, chat_id)
  228. # Check if the chat is already shared
  229. if chat.share_id:
  230. return self.get_chat_by_id_and_user_id(chat.share_id, "shared")
  231. # Create a new chat with the same data, but with a new ID
  232. shared_chat = ChatModel(
  233. **{
  234. "id": str(uuid.uuid4()),
  235. "user_id": f"shared-{chat_id}",
  236. "title": chat.title,
  237. "chat": chat.chat,
  238. "meta": chat.meta,
  239. "pinned": chat.pinned,
  240. "folder_id": chat.folder_id,
  241. "created_at": chat.created_at,
  242. "updated_at": int(time.time()),
  243. }
  244. )
  245. shared_result = Chat(**shared_chat.model_dump())
  246. db.add(shared_result)
  247. db.commit()
  248. db.refresh(shared_result)
  249. # Update the original chat with the share_id
  250. result = (
  251. db.query(Chat)
  252. .filter_by(id=chat_id)
  253. .update({"share_id": shared_chat.id})
  254. )
  255. db.commit()
  256. return shared_chat if (shared_result and result) else None
  257. def update_shared_chat_by_chat_id(self, chat_id: str) -> Optional[ChatModel]:
  258. try:
  259. with get_db() as db:
  260. chat = db.get(Chat, chat_id)
  261. shared_chat = (
  262. db.query(Chat).filter_by(user_id=f"shared-{chat_id}").first()
  263. )
  264. if shared_chat is None:
  265. return self.insert_shared_chat_by_chat_id(chat_id)
  266. shared_chat.title = chat.title
  267. shared_chat.chat = chat.chat
  268. shared_chat.meta = chat.meta
  269. shared_chat.pinned = chat.pinned
  270. shared_chat.folder_id = chat.folder_id
  271. shared_chat.updated_at = int(time.time())
  272. db.commit()
  273. db.refresh(shared_chat)
  274. return ChatModel.model_validate(shared_chat)
  275. except Exception:
  276. return None
  277. def delete_shared_chat_by_chat_id(self, chat_id: str) -> bool:
  278. try:
  279. with get_db() as db:
  280. db.query(Chat).filter_by(user_id=f"shared-{chat_id}").delete()
  281. db.commit()
  282. return True
  283. except Exception:
  284. return False
  285. def update_chat_share_id_by_id(
  286. self, id: str, share_id: Optional[str]
  287. ) -> Optional[ChatModel]:
  288. try:
  289. with get_db() as db:
  290. chat = db.get(Chat, id)
  291. chat.share_id = share_id
  292. db.commit()
  293. db.refresh(chat)
  294. return ChatModel.model_validate(chat)
  295. except Exception:
  296. return None
  297. def toggle_chat_pinned_by_id(self, id: str) -> Optional[ChatModel]:
  298. try:
  299. with get_db() as db:
  300. chat = db.get(Chat, id)
  301. chat.pinned = not chat.pinned
  302. chat.updated_at = int(time.time())
  303. db.commit()
  304. db.refresh(chat)
  305. return ChatModel.model_validate(chat)
  306. except Exception:
  307. return None
  308. def toggle_chat_archive_by_id(self, id: str) -> Optional[ChatModel]:
  309. try:
  310. with get_db() as db:
  311. chat = db.get(Chat, id)
  312. chat.archived = not chat.archived
  313. chat.updated_at = int(time.time())
  314. db.commit()
  315. db.refresh(chat)
  316. return ChatModel.model_validate(chat)
  317. except Exception:
  318. return None
  319. def archive_all_chats_by_user_id(self, user_id: str) -> bool:
  320. try:
  321. with get_db() as db:
  322. db.query(Chat).filter_by(user_id=user_id).update({"archived": True})
  323. db.commit()
  324. return True
  325. except Exception:
  326. return False
  327. def get_archived_chat_list_by_user_id(
  328. self,
  329. user_id: str,
  330. filter: Optional[dict] = None,
  331. skip: int = 0,
  332. limit: int = 50,
  333. ) -> list[ChatModel]:
  334. with get_db() as db:
  335. query = db.query(Chat).filter_by(user_id=user_id, archived=True)
  336. if filter:
  337. query_key = filter.get("query")
  338. if query_key:
  339. query = query.filter(Chat.title.ilike(f"%{query_key}%"))
  340. order_by = filter.get("order_by")
  341. direction = filter.get("direction")
  342. if order_by and direction and getattr(Chat, order_by):
  343. if direction.lower() == "asc":
  344. query = query.order_by(getattr(Chat, order_by).asc())
  345. elif direction.lower() == "desc":
  346. query = query.order_by(getattr(Chat, order_by).desc())
  347. else:
  348. raise ValueError("Invalid direction for ordering")
  349. else:
  350. query = query.order_by(Chat.updated_at.desc())
  351. if skip:
  352. query = query.offset(skip)
  353. if limit:
  354. query = query.limit(limit)
  355. all_chats = query.all()
  356. return [ChatModel.model_validate(chat) for chat in all_chats]
  357. def get_chat_list_by_user_id(
  358. self,
  359. user_id: str,
  360. include_archived: bool = False,
  361. filter: Optional[dict] = None,
  362. skip: int = 0,
  363. limit: int = 50,
  364. ) -> list[ChatModel]:
  365. with get_db() as db:
  366. query = db.query(Chat).filter_by(user_id=user_id)
  367. if not include_archived:
  368. query = query.filter_by(archived=False)
  369. if filter:
  370. query_key = filter.get("query")
  371. if query_key:
  372. query = query.filter(Chat.title.ilike(f"%{query_key}%"))
  373. order_by = filter.get("order_by")
  374. direction = filter.get("direction")
  375. if order_by and direction and getattr(Chat, order_by):
  376. if direction.lower() == "asc":
  377. query = query.order_by(getattr(Chat, order_by).asc())
  378. elif direction.lower() == "desc":
  379. query = query.order_by(getattr(Chat, order_by).desc())
  380. else:
  381. raise ValueError("Invalid direction for ordering")
  382. else:
  383. query = query.order_by(Chat.updated_at.desc())
  384. if skip:
  385. query = query.offset(skip)
  386. if limit:
  387. query = query.limit(limit)
  388. all_chats = query.all()
  389. return [ChatModel.model_validate(chat) for chat in all_chats]
  390. def get_chat_title_id_list_by_user_id(
  391. self,
  392. user_id: str,
  393. include_archived: bool = False,
  394. skip: Optional[int] = None,
  395. limit: Optional[int] = None,
  396. ) -> list[ChatTitleIdResponse]:
  397. with get_db() as db:
  398. query = db.query(Chat).filter_by(user_id=user_id).filter_by(folder_id=None)
  399. query = query.filter(or_(Chat.pinned == False, Chat.pinned == None))
  400. if not include_archived:
  401. query = query.filter_by(archived=False)
  402. query = query.order_by(Chat.updated_at.desc()).with_entities(
  403. Chat.id, Chat.title, Chat.updated_at, Chat.created_at
  404. )
  405. if skip:
  406. query = query.offset(skip)
  407. if limit:
  408. query = query.limit(limit)
  409. all_chats = query.all()
  410. # result has to be destructured from sqlalchemy `row` and mapped to a dict since the `ChatModel`is not the returned dataclass.
  411. return [
  412. ChatTitleIdResponse.model_validate(
  413. {
  414. "id": chat[0],
  415. "title": chat[1],
  416. "updated_at": chat[2],
  417. "created_at": chat[3],
  418. }
  419. )
  420. for chat in all_chats
  421. ]
  422. def get_chat_list_by_chat_ids(
  423. self, chat_ids: list[str], skip: int = 0, limit: int = 50
  424. ) -> list[ChatModel]:
  425. with get_db() as db:
  426. all_chats = (
  427. db.query(Chat)
  428. .filter(Chat.id.in_(chat_ids))
  429. .filter_by(archived=False)
  430. .order_by(Chat.updated_at.desc())
  431. .all()
  432. )
  433. return [ChatModel.model_validate(chat) for chat in all_chats]
  434. def get_chat_by_id(self, id: str) -> Optional[ChatModel]:
  435. try:
  436. with get_db() as db:
  437. chat = db.get(Chat, id)
  438. return ChatModel.model_validate(chat)
  439. except Exception:
  440. return None
  441. def get_chat_by_share_id(self, id: str) -> Optional[ChatModel]:
  442. try:
  443. with get_db() as db:
  444. # it is possible that the shared link was deleted. hence,
  445. # we check if the chat is still shared by checking if a chat with the share_id exists
  446. chat = db.query(Chat).filter_by(share_id=id).first()
  447. if chat:
  448. return self.get_chat_by_id(id)
  449. else:
  450. return None
  451. except Exception:
  452. return None
  453. def get_chat_by_id_and_user_id(self, id: str, user_id: str) -> Optional[ChatModel]:
  454. try:
  455. with get_db() as db:
  456. chat = db.query(Chat).filter_by(id=id, user_id=user_id).first()
  457. return ChatModel.model_validate(chat)
  458. except Exception:
  459. return None
  460. def get_chats(self, skip: int = 0, limit: int = 50) -> list[ChatModel]:
  461. with get_db() as db:
  462. all_chats = (
  463. db.query(Chat)
  464. # .limit(limit).offset(skip)
  465. .order_by(Chat.updated_at.desc())
  466. )
  467. return [ChatModel.model_validate(chat) for chat in all_chats]
  468. def get_chats_by_user_id(self, user_id: str) -> list[ChatModel]:
  469. with get_db() as db:
  470. all_chats = (
  471. db.query(Chat)
  472. .filter_by(user_id=user_id)
  473. .order_by(Chat.updated_at.desc())
  474. )
  475. return [ChatModel.model_validate(chat) for chat in all_chats]
  476. def get_pinned_chats_by_user_id(self, user_id: str) -> list[ChatModel]:
  477. with get_db() as db:
  478. all_chats = (
  479. db.query(Chat)
  480. .filter_by(user_id=user_id, pinned=True, archived=False)
  481. .order_by(Chat.updated_at.desc())
  482. )
  483. return [ChatModel.model_validate(chat) for chat in all_chats]
  484. def get_archived_chats_by_user_id(self, user_id: str) -> list[ChatModel]:
  485. with get_db() as db:
  486. all_chats = (
  487. db.query(Chat)
  488. .filter_by(user_id=user_id, archived=True)
  489. .order_by(Chat.updated_at.desc())
  490. )
  491. return [ChatModel.model_validate(chat) for chat in all_chats]
  492. def get_chats_by_user_id_and_search_text(
  493. self,
  494. user_id: str,
  495. search_text: str,
  496. include_archived: bool = False,
  497. skip: int = 0,
  498. limit: int = 60,
  499. ) -> list[ChatModel]:
  500. """
  501. Filters chats based on a search query using Python, allowing pagination using skip and limit.
  502. """
  503. search_text = search_text.replace("\u0000", "").lower().strip()
  504. if not search_text:
  505. return self.get_chat_list_by_user_id(
  506. user_id, include_archived, filter={}, skip=skip, limit=limit
  507. )
  508. search_text_words = search_text.split(" ")
  509. # search_text might contain 'tag:tag_name' format so we need to extract the tag_name, split the search_text and remove the tags
  510. tag_ids = [
  511. word.replace("tag:", "").replace(" ", "_").lower()
  512. for word in search_text_words
  513. if word.startswith("tag:")
  514. ]
  515. # Extract folder names - handle spaces and case insensitivity
  516. folders = Folders.search_folders_by_names(
  517. user_id,
  518. [
  519. word.replace("folder:", "")
  520. for word in search_text_words
  521. if word.startswith("folder:")
  522. ],
  523. )
  524. folder_ids = [folder.id for folder in folders]
  525. is_pinned = None
  526. if "pinned:true" in search_text_words:
  527. is_pinned = True
  528. elif "pinned:false" in search_text_words:
  529. is_pinned = False
  530. is_archived = None
  531. if "archived:true" in search_text_words:
  532. is_archived = True
  533. elif "archived:false" in search_text_words:
  534. is_archived = False
  535. is_shared = None
  536. if "shared:true" in search_text_words:
  537. is_shared = True
  538. elif "shared:false" in search_text_words:
  539. is_shared = False
  540. search_text_words = [
  541. word
  542. for word in search_text_words
  543. if (
  544. not word.startswith("tag:")
  545. and not word.startswith("folder:")
  546. and not word.startswith("pinned:")
  547. and not word.startswith("archived:")
  548. and not word.startswith("shared:")
  549. )
  550. ]
  551. search_text = " ".join(search_text_words)
  552. with get_db() as db:
  553. query = db.query(Chat).filter(Chat.user_id == user_id)
  554. if is_archived is not None:
  555. query = query.filter(Chat.archived == is_archived)
  556. elif not include_archived:
  557. query = query.filter(Chat.archived == False)
  558. if is_pinned is not None:
  559. query = query.filter(Chat.pinned == is_pinned)
  560. if is_shared is not None:
  561. if is_shared:
  562. query = query.filter(Chat.share_id.isnot(None))
  563. else:
  564. query = query.filter(Chat.share_id.is_(None))
  565. if folder_ids:
  566. query = query.filter(Chat.folder_id.in_(folder_ids))
  567. query = query.order_by(Chat.updated_at.desc())
  568. # Check if the database dialect is either 'sqlite' or 'postgresql'
  569. dialect_name = db.bind.dialect.name
  570. if dialect_name == "sqlite":
  571. # SQLite case: using JSON1 extension for JSON searching
  572. sqlite_content_sql = (
  573. "EXISTS ("
  574. " SELECT 1 "
  575. " FROM json_each(Chat.chat, '$.messages') AS message "
  576. " WHERE LOWER(message.value->>'content') LIKE '%' || :content_key || '%'"
  577. ")"
  578. )
  579. sqlite_content_clause = text(sqlite_content_sql)
  580. query = query.filter(
  581. or_(
  582. Chat.title.ilike(bindparam("title_key")), sqlite_content_clause
  583. ).params(title_key=f"%{search_text}%", content_key=search_text)
  584. )
  585. # Check if there are any tags to filter, it should have all the tags
  586. if "none" in tag_ids:
  587. query = query.filter(
  588. text(
  589. """
  590. NOT EXISTS (
  591. SELECT 1
  592. FROM json_each(Chat.meta, '$.tags') AS tag
  593. )
  594. """
  595. )
  596. )
  597. elif tag_ids:
  598. query = query.filter(
  599. and_(
  600. *[
  601. text(
  602. f"""
  603. EXISTS (
  604. SELECT 1
  605. FROM json_each(Chat.meta, '$.tags') AS tag
  606. WHERE tag.value = :tag_id_{tag_idx}
  607. )
  608. """
  609. ).params(**{f"tag_id_{tag_idx}": tag_id})
  610. for tag_idx, tag_id in enumerate(tag_ids)
  611. ]
  612. )
  613. )
  614. elif dialect_name == "postgresql":
  615. # PostgreSQL relies on proper JSON query for search
  616. postgres_content_sql = (
  617. "EXISTS ("
  618. " SELECT 1 "
  619. " FROM json_array_elements(Chat.chat->'messages') AS message "
  620. " WHERE LOWER(message->>'content') LIKE '%' || :content_key || '%'"
  621. ")"
  622. )
  623. postgres_content_clause = text(postgres_content_sql)
  624. query = query.filter(
  625. or_(
  626. Chat.title.ilike(bindparam("title_key")),
  627. postgres_content_clause,
  628. ).params(title_key=f"%{search_text}%", content_key=search_text)
  629. )
  630. # Check if there are any tags to filter, it should have all the tags
  631. if "none" in tag_ids:
  632. query = query.filter(
  633. text(
  634. """
  635. NOT EXISTS (
  636. SELECT 1
  637. FROM json_array_elements_text(Chat.meta->'tags') AS tag
  638. )
  639. """
  640. )
  641. )
  642. elif tag_ids:
  643. query = query.filter(
  644. and_(
  645. *[
  646. text(
  647. f"""
  648. EXISTS (
  649. SELECT 1
  650. FROM json_array_elements_text(Chat.meta->'tags') AS tag
  651. WHERE tag = :tag_id_{tag_idx}
  652. )
  653. """
  654. ).params(**{f"tag_id_{tag_idx}": tag_id})
  655. for tag_idx, tag_id in enumerate(tag_ids)
  656. ]
  657. )
  658. )
  659. else:
  660. raise NotImplementedError(
  661. f"Unsupported dialect: {db.bind.dialect.name}"
  662. )
  663. # Perform pagination at the SQL level
  664. all_chats = query.offset(skip).limit(limit).all()
  665. log.info(f"The number of chats: {len(all_chats)}")
  666. # Validate and return chats
  667. return [ChatModel.model_validate(chat) for chat in all_chats]
  668. def get_chats_by_folder_id_and_user_id(
  669. self, folder_id: str, user_id: str
  670. ) -> list[ChatModel]:
  671. with get_db() as db:
  672. query = db.query(Chat).filter_by(folder_id=folder_id, user_id=user_id)
  673. query = query.filter(or_(Chat.pinned == False, Chat.pinned == None))
  674. query = query.filter_by(archived=False)
  675. query = query.order_by(Chat.updated_at.desc())
  676. all_chats = query.all()
  677. return [ChatModel.model_validate(chat) for chat in all_chats]
  678. def get_chats_by_folder_ids_and_user_id(
  679. self, folder_ids: list[str], user_id: str
  680. ) -> list[ChatModel]:
  681. with get_db() as db:
  682. query = db.query(Chat).filter(
  683. Chat.folder_id.in_(folder_ids), Chat.user_id == user_id
  684. )
  685. query = query.filter(or_(Chat.pinned == False, Chat.pinned == None))
  686. query = query.filter_by(archived=False)
  687. query = query.order_by(Chat.updated_at.desc())
  688. all_chats = query.all()
  689. return [ChatModel.model_validate(chat) for chat in all_chats]
  690. def update_chat_folder_id_by_id_and_user_id(
  691. self, id: str, user_id: str, folder_id: str
  692. ) -> Optional[ChatModel]:
  693. try:
  694. with get_db() as db:
  695. chat = db.get(Chat, id)
  696. chat.folder_id = folder_id
  697. chat.updated_at = int(time.time())
  698. chat.pinned = False
  699. db.commit()
  700. db.refresh(chat)
  701. return ChatModel.model_validate(chat)
  702. except Exception:
  703. return None
  704. def get_chat_tags_by_id_and_user_id(self, id: str, user_id: str) -> list[TagModel]:
  705. with get_db() as db:
  706. chat = db.get(Chat, id)
  707. tags = chat.meta.get("tags", [])
  708. return [Tags.get_tag_by_name_and_user_id(tag, user_id) for tag in tags]
  709. def get_chat_list_by_user_id_and_tag_name(
  710. self, user_id: str, tag_name: str, skip: int = 0, limit: int = 50
  711. ) -> list[ChatModel]:
  712. with get_db() as db:
  713. query = db.query(Chat).filter_by(user_id=user_id)
  714. tag_id = tag_name.replace(" ", "_").lower()
  715. log.info(f"DB dialect name: {db.bind.dialect.name}")
  716. if db.bind.dialect.name == "sqlite":
  717. # SQLite JSON1 querying for tags within the meta JSON field
  718. query = query.filter(
  719. text(
  720. f"EXISTS (SELECT 1 FROM json_each(Chat.meta, '$.tags') WHERE json_each.value = :tag_id)"
  721. )
  722. ).params(tag_id=tag_id)
  723. elif db.bind.dialect.name == "postgresql":
  724. # PostgreSQL JSON query for tags within the meta JSON field (for `json` type)
  725. query = query.filter(
  726. text(
  727. "EXISTS (SELECT 1 FROM json_array_elements_text(Chat.meta->'tags') elem WHERE elem = :tag_id)"
  728. )
  729. ).params(tag_id=tag_id)
  730. else:
  731. raise NotImplementedError(
  732. f"Unsupported dialect: {db.bind.dialect.name}"
  733. )
  734. all_chats = query.all()
  735. log.debug(f"all_chats: {all_chats}")
  736. return [ChatModel.model_validate(chat) for chat in all_chats]
  737. def add_chat_tag_by_id_and_user_id_and_tag_name(
  738. self, id: str, user_id: str, tag_name: str
  739. ) -> Optional[ChatModel]:
  740. tag = Tags.get_tag_by_name_and_user_id(tag_name, user_id)
  741. if tag is None:
  742. tag = Tags.insert_new_tag(tag_name, user_id)
  743. try:
  744. with get_db() as db:
  745. chat = db.get(Chat, id)
  746. tag_id = tag.id
  747. if tag_id not in chat.meta.get("tags", []):
  748. chat.meta = {
  749. **chat.meta,
  750. "tags": list(set(chat.meta.get("tags", []) + [tag_id])),
  751. }
  752. db.commit()
  753. db.refresh(chat)
  754. return ChatModel.model_validate(chat)
  755. except Exception:
  756. return None
  757. def count_chats_by_tag_name_and_user_id(self, tag_name: str, user_id: str) -> int:
  758. with get_db() as db: # Assuming `get_db()` returns a session object
  759. query = db.query(Chat).filter_by(user_id=user_id, archived=False)
  760. # Normalize the tag_name for consistency
  761. tag_id = tag_name.replace(" ", "_").lower()
  762. if db.bind.dialect.name == "sqlite":
  763. # SQLite JSON1 support for querying the tags inside the `meta` JSON field
  764. query = query.filter(
  765. text(
  766. f"EXISTS (SELECT 1 FROM json_each(Chat.meta, '$.tags') WHERE json_each.value = :tag_id)"
  767. )
  768. ).params(tag_id=tag_id)
  769. elif db.bind.dialect.name == "postgresql":
  770. # PostgreSQL JSONB support for querying the tags inside the `meta` JSON field
  771. query = query.filter(
  772. text(
  773. "EXISTS (SELECT 1 FROM json_array_elements_text(Chat.meta->'tags') elem WHERE elem = :tag_id)"
  774. )
  775. ).params(tag_id=tag_id)
  776. else:
  777. raise NotImplementedError(
  778. f"Unsupported dialect: {db.bind.dialect.name}"
  779. )
  780. # Get the count of matching records
  781. count = query.count()
  782. # Debugging output for inspection
  783. log.info(f"Count of chats for tag '{tag_name}': {count}")
  784. return count
  785. def delete_tag_by_id_and_user_id_and_tag_name(
  786. self, id: str, user_id: str, tag_name: str
  787. ) -> bool:
  788. try:
  789. with get_db() as db:
  790. chat = db.get(Chat, id)
  791. tags = chat.meta.get("tags", [])
  792. tag_id = tag_name.replace(" ", "_").lower()
  793. tags = [tag for tag in tags if tag != tag_id]
  794. chat.meta = {
  795. **chat.meta,
  796. "tags": list(set(tags)),
  797. }
  798. db.commit()
  799. return True
  800. except Exception:
  801. return False
  802. def delete_all_tags_by_id_and_user_id(self, id: str, user_id: str) -> bool:
  803. try:
  804. with get_db() as db:
  805. chat = db.get(Chat, id)
  806. chat.meta = {
  807. **chat.meta,
  808. "tags": [],
  809. }
  810. db.commit()
  811. return True
  812. except Exception:
  813. return False
  814. def delete_chat_by_id(self, id: str) -> bool:
  815. try:
  816. with get_db() as db:
  817. db.query(Chat).filter_by(id=id).delete()
  818. db.commit()
  819. return True and self.delete_shared_chat_by_chat_id(id)
  820. except Exception:
  821. return False
  822. def delete_chat_by_id_and_user_id(self, id: str, user_id: str) -> bool:
  823. try:
  824. with get_db() as db:
  825. db.query(Chat).filter_by(id=id, user_id=user_id).delete()
  826. db.commit()
  827. return True and self.delete_shared_chat_by_chat_id(id)
  828. except Exception:
  829. return False
  830. def delete_chats_by_user_id(self, user_id: str) -> bool:
  831. try:
  832. with get_db() as db:
  833. self.delete_shared_chats_by_user_id(user_id)
  834. db.query(Chat).filter_by(user_id=user_id).delete()
  835. db.commit()
  836. return True
  837. except Exception:
  838. return False
  839. def delete_chats_by_user_id_and_folder_id(
  840. self, user_id: str, folder_id: str
  841. ) -> bool:
  842. try:
  843. with get_db() as db:
  844. db.query(Chat).filter_by(user_id=user_id, folder_id=folder_id).delete()
  845. db.commit()
  846. return True
  847. except Exception:
  848. return False
  849. def delete_shared_chats_by_user_id(self, user_id: str) -> bool:
  850. try:
  851. with get_db() as db:
  852. chats_by_user = db.query(Chat).filter_by(user_id=user_id).all()
  853. shared_chat_ids = [f"shared-{chat.id}" for chat in chats_by_user]
  854. db.query(Chat).filter(Chat.user_id.in_(shared_chat_ids)).delete()
  855. db.commit()
  856. return True
  857. except Exception:
  858. return False
  859. Chats = ChatTable()