chats.py 35 KB

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