chats.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966
  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. "created_at": chat.created_at,
  238. "updated_at": int(time.time()),
  239. }
  240. )
  241. shared_result = Chat(**shared_chat.model_dump())
  242. db.add(shared_result)
  243. db.commit()
  244. db.refresh(shared_result)
  245. # Update the original chat with the share_id
  246. result = (
  247. db.query(Chat)
  248. .filter_by(id=chat_id)
  249. .update({"share_id": shared_chat.id})
  250. )
  251. db.commit()
  252. return shared_chat if (shared_result and result) else None
  253. def update_shared_chat_by_chat_id(self, chat_id: str) -> Optional[ChatModel]:
  254. try:
  255. with get_db() as db:
  256. chat = db.get(Chat, chat_id)
  257. shared_chat = (
  258. db.query(Chat).filter_by(user_id=f"shared-{chat_id}").first()
  259. )
  260. if shared_chat is None:
  261. return self.insert_shared_chat_by_chat_id(chat_id)
  262. shared_chat.title = chat.title
  263. shared_chat.chat = chat.chat
  264. shared_chat.updated_at = int(time.time())
  265. db.commit()
  266. db.refresh(shared_chat)
  267. return ChatModel.model_validate(shared_chat)
  268. except Exception:
  269. return None
  270. def delete_shared_chat_by_chat_id(self, chat_id: str) -> bool:
  271. try:
  272. with get_db() as db:
  273. db.query(Chat).filter_by(user_id=f"shared-{chat_id}").delete()
  274. db.commit()
  275. return True
  276. except Exception:
  277. return False
  278. def update_chat_share_id_by_id(
  279. self, id: str, share_id: Optional[str]
  280. ) -> Optional[ChatModel]:
  281. try:
  282. with get_db() as db:
  283. chat = db.get(Chat, id)
  284. chat.share_id = share_id
  285. db.commit()
  286. db.refresh(chat)
  287. return ChatModel.model_validate(chat)
  288. except Exception:
  289. return None
  290. def toggle_chat_pinned_by_id(self, id: str) -> Optional[ChatModel]:
  291. try:
  292. with get_db() as db:
  293. chat = db.get(Chat, id)
  294. chat.pinned = not chat.pinned
  295. chat.updated_at = int(time.time())
  296. db.commit()
  297. db.refresh(chat)
  298. return ChatModel.model_validate(chat)
  299. except Exception:
  300. return None
  301. def toggle_chat_archive_by_id(self, id: str) -> Optional[ChatModel]:
  302. try:
  303. with get_db() as db:
  304. chat = db.get(Chat, id)
  305. chat.archived = not chat.archived
  306. chat.updated_at = int(time.time())
  307. db.commit()
  308. db.refresh(chat)
  309. return ChatModel.model_validate(chat)
  310. except Exception:
  311. return None
  312. def archive_all_chats_by_user_id(self, user_id: str) -> bool:
  313. try:
  314. with get_db() as db:
  315. db.query(Chat).filter_by(user_id=user_id).update({"archived": True})
  316. db.commit()
  317. return True
  318. except Exception:
  319. return False
  320. def get_archived_chat_list_by_user_id(
  321. self,
  322. user_id: str,
  323. filter: Optional[dict] = None,
  324. skip: int = 0,
  325. limit: int = 50,
  326. ) -> list[ChatModel]:
  327. with get_db() as db:
  328. query = db.query(Chat).filter_by(user_id=user_id, archived=True)
  329. if filter:
  330. query_key = filter.get("query")
  331. if query_key:
  332. query = query.filter(Chat.title.ilike(f"%{query_key}%"))
  333. order_by = filter.get("order_by")
  334. direction = filter.get("direction")
  335. if order_by and direction and getattr(Chat, order_by):
  336. if direction.lower() == "asc":
  337. query = query.order_by(getattr(Chat, order_by).asc())
  338. elif direction.lower() == "desc":
  339. query = query.order_by(getattr(Chat, order_by).desc())
  340. else:
  341. raise ValueError("Invalid direction for ordering")
  342. else:
  343. query = query.order_by(Chat.updated_at.desc())
  344. if skip:
  345. query = query.offset(skip)
  346. if limit:
  347. query = query.limit(limit)
  348. all_chats = query.all()
  349. return [ChatModel.model_validate(chat) for chat in all_chats]
  350. def get_chat_list_by_user_id(
  351. self,
  352. user_id: str,
  353. include_archived: bool = False,
  354. filter: Optional[dict] = None,
  355. skip: int = 0,
  356. limit: int = 50,
  357. ) -> list[ChatModel]:
  358. with get_db() as db:
  359. query = db.query(Chat).filter_by(user_id=user_id)
  360. if not include_archived:
  361. query = query.filter_by(archived=False)
  362. if filter:
  363. query_key = filter.get("query")
  364. if query_key:
  365. query = query.filter(Chat.title.ilike(f"%{query_key}%"))
  366. order_by = filter.get("order_by")
  367. direction = filter.get("direction")
  368. if order_by and direction and getattr(Chat, order_by):
  369. if direction.lower() == "asc":
  370. query = query.order_by(getattr(Chat, order_by).asc())
  371. elif direction.lower() == "desc":
  372. query = query.order_by(getattr(Chat, order_by).desc())
  373. else:
  374. raise ValueError("Invalid direction for ordering")
  375. else:
  376. query = query.order_by(Chat.updated_at.desc())
  377. if skip:
  378. query = query.offset(skip)
  379. if limit:
  380. query = query.limit(limit)
  381. all_chats = query.all()
  382. return [ChatModel.model_validate(chat) for chat in all_chats]
  383. def get_chat_title_id_list_by_user_id(
  384. self,
  385. user_id: str,
  386. include_archived: bool = False,
  387. skip: Optional[int] = None,
  388. limit: Optional[int] = None,
  389. ) -> list[ChatTitleIdResponse]:
  390. with get_db() as db:
  391. query = db.query(Chat).filter_by(user_id=user_id).filter_by(folder_id=None)
  392. query = query.filter(or_(Chat.pinned == False, Chat.pinned == None))
  393. if not include_archived:
  394. query = query.filter_by(archived=False)
  395. query = query.order_by(Chat.updated_at.desc()).with_entities(
  396. Chat.id, Chat.title, Chat.updated_at, Chat.created_at
  397. )
  398. if skip:
  399. query = query.offset(skip)
  400. if limit:
  401. query = query.limit(limit)
  402. all_chats = query.all()
  403. # result has to be destructured from sqlalchemy `row` and mapped to a dict since the `ChatModel`is not the returned dataclass.
  404. return [
  405. ChatTitleIdResponse.model_validate(
  406. {
  407. "id": chat[0],
  408. "title": chat[1],
  409. "updated_at": chat[2],
  410. "created_at": chat[3],
  411. }
  412. )
  413. for chat in all_chats
  414. ]
  415. def get_chat_list_by_chat_ids(
  416. self, chat_ids: list[str], skip: int = 0, limit: int = 50
  417. ) -> list[ChatModel]:
  418. with get_db() as db:
  419. all_chats = (
  420. db.query(Chat)
  421. .filter(Chat.id.in_(chat_ids))
  422. .filter_by(archived=False)
  423. .order_by(Chat.updated_at.desc())
  424. .all()
  425. )
  426. return [ChatModel.model_validate(chat) for chat in all_chats]
  427. def get_chat_by_id(self, id: str) -> Optional[ChatModel]:
  428. try:
  429. with get_db() as db:
  430. chat = db.get(Chat, id)
  431. return ChatModel.model_validate(chat)
  432. except Exception:
  433. return None
  434. def get_chat_by_share_id(self, id: str) -> Optional[ChatModel]:
  435. try:
  436. with get_db() as db:
  437. # it is possible that the shared link was deleted. hence,
  438. # we check if the chat is still shared by checking if a chat with the share_id exists
  439. chat = db.query(Chat).filter_by(share_id=id).first()
  440. if chat:
  441. return self.get_chat_by_id(id)
  442. else:
  443. return None
  444. except Exception:
  445. return None
  446. def get_chat_by_id_and_user_id(self, id: str, user_id: str) -> Optional[ChatModel]:
  447. try:
  448. with get_db() as db:
  449. chat = db.query(Chat).filter_by(id=id, user_id=user_id).first()
  450. return ChatModel.model_validate(chat)
  451. except Exception:
  452. return None
  453. def get_chats(self, skip: int = 0, limit: int = 50) -> list[ChatModel]:
  454. with get_db() as db:
  455. all_chats = (
  456. db.query(Chat)
  457. # .limit(limit).offset(skip)
  458. .order_by(Chat.updated_at.desc())
  459. )
  460. return [ChatModel.model_validate(chat) for chat in all_chats]
  461. def get_chats_by_user_id(self, user_id: str) -> list[ChatModel]:
  462. with get_db() as db:
  463. all_chats = (
  464. db.query(Chat)
  465. .filter_by(user_id=user_id)
  466. .order_by(Chat.updated_at.desc())
  467. )
  468. return [ChatModel.model_validate(chat) for chat in all_chats]
  469. def get_pinned_chats_by_user_id(self, user_id: str) -> list[ChatModel]:
  470. with get_db() as db:
  471. all_chats = (
  472. db.query(Chat)
  473. .filter_by(user_id=user_id, pinned=True, archived=False)
  474. .order_by(Chat.updated_at.desc())
  475. )
  476. return [ChatModel.model_validate(chat) for chat in all_chats]
  477. def get_archived_chats_by_user_id(self, user_id: str) -> list[ChatModel]:
  478. with get_db() as db:
  479. all_chats = (
  480. db.query(Chat)
  481. .filter_by(user_id=user_id, archived=True)
  482. .order_by(Chat.updated_at.desc())
  483. )
  484. return [ChatModel.model_validate(chat) for chat in all_chats]
  485. def get_chats_by_user_id_and_search_text(
  486. self,
  487. user_id: str,
  488. search_text: str,
  489. include_archived: bool = False,
  490. skip: int = 0,
  491. limit: int = 60,
  492. ) -> list[ChatModel]:
  493. """
  494. Filters chats based on a search query using Python, allowing pagination using skip and limit.
  495. """
  496. search_text = search_text.replace("\u0000", "").lower().strip()
  497. if not search_text:
  498. return self.get_chat_list_by_user_id(
  499. user_id, include_archived, filter={}, skip=skip, limit=limit
  500. )
  501. search_text_words = search_text.split(" ")
  502. # search_text might contain 'tag:tag_name' format so we need to extract the tag_name, split the search_text and remove the tags
  503. tag_ids = [
  504. word.replace("tag:", "").replace(" ", "_").lower()
  505. for word in search_text_words
  506. if word.startswith("tag:")
  507. ]
  508. search_text_words = [
  509. word for word in search_text_words if not word.startswith("tag:")
  510. ]
  511. search_text = " ".join(search_text_words)
  512. with get_db() as db:
  513. query = db.query(Chat).filter(Chat.user_id == user_id)
  514. if not include_archived:
  515. query = query.filter(Chat.archived == False)
  516. query = query.order_by(Chat.updated_at.desc())
  517. # Check if the database dialect is either 'sqlite' or 'postgresql'
  518. dialect_name = db.bind.dialect.name
  519. if dialect_name == "sqlite":
  520. # SQLite case: using JSON1 extension for JSON searching
  521. sqlite_content_sql = (
  522. "EXISTS ("
  523. " SELECT 1 "
  524. " FROM json_each(Chat.chat, '$.messages') AS message "
  525. " WHERE LOWER(message.value->>'content') LIKE '%' || :content_key || '%'"
  526. ")"
  527. )
  528. sqlite_content_clause = text(sqlite_content_sql)
  529. query = query.filter(
  530. or_(
  531. Chat.title.ilike(bindparam("title_key")), sqlite_content_clause
  532. ).params(title_key=f"%{search_text}%", content_key=search_text)
  533. )
  534. # Check if there are any tags to filter, it should have all the tags
  535. if "none" in tag_ids:
  536. query = query.filter(
  537. text(
  538. """
  539. NOT EXISTS (
  540. SELECT 1
  541. FROM json_each(Chat.meta, '$.tags') AS tag
  542. )
  543. """
  544. )
  545. )
  546. elif tag_ids:
  547. query = query.filter(
  548. and_(
  549. *[
  550. text(
  551. f"""
  552. EXISTS (
  553. SELECT 1
  554. FROM json_each(Chat.meta, '$.tags') AS tag
  555. WHERE tag.value = :tag_id_{tag_idx}
  556. )
  557. """
  558. ).params(**{f"tag_id_{tag_idx}": tag_id})
  559. for tag_idx, tag_id in enumerate(tag_ids)
  560. ]
  561. )
  562. )
  563. elif dialect_name == "postgresql":
  564. # PostgreSQL relies on proper JSON query for search
  565. postgres_content_sql = (
  566. "EXISTS ("
  567. " SELECT 1 "
  568. " FROM json_array_elements(Chat.chat->'messages') AS message "
  569. " WHERE LOWER(message->>'content') LIKE '%' || :content_key || '%'"
  570. ")"
  571. )
  572. postgres_content_clause = text(postgres_content_sql)
  573. query = query.filter(
  574. or_(
  575. Chat.title.ilike(bindparam("title_key")),
  576. postgres_content_clause,
  577. ).params(title_key=f"%{search_text}%", content_key=search_text)
  578. )
  579. # Check if there are any tags to filter, it should have all the tags
  580. if "none" in tag_ids:
  581. query = query.filter(
  582. text(
  583. """
  584. NOT EXISTS (
  585. SELECT 1
  586. FROM json_array_elements_text(Chat.meta->'tags') AS tag
  587. )
  588. """
  589. )
  590. )
  591. elif tag_ids:
  592. query = query.filter(
  593. and_(
  594. *[
  595. text(
  596. f"""
  597. EXISTS (
  598. SELECT 1
  599. FROM json_array_elements_text(Chat.meta->'tags') AS tag
  600. WHERE tag = :tag_id_{tag_idx}
  601. )
  602. """
  603. ).params(**{f"tag_id_{tag_idx}": tag_id})
  604. for tag_idx, tag_id in enumerate(tag_ids)
  605. ]
  606. )
  607. )
  608. else:
  609. raise NotImplementedError(
  610. f"Unsupported dialect: {db.bind.dialect.name}"
  611. )
  612. # Perform pagination at the SQL level
  613. all_chats = query.offset(skip).limit(limit).all()
  614. log.info(f"The number of chats: {len(all_chats)}")
  615. # Validate and return chats
  616. return [ChatModel.model_validate(chat) for chat in all_chats]
  617. def get_chats_by_folder_id_and_user_id(
  618. self, folder_id: str, user_id: str
  619. ) -> list[ChatModel]:
  620. with get_db() as db:
  621. query = db.query(Chat).filter_by(folder_id=folder_id, user_id=user_id)
  622. query = query.filter(or_(Chat.pinned == False, Chat.pinned == None))
  623. query = query.filter_by(archived=False)
  624. query = query.order_by(Chat.updated_at.desc())
  625. all_chats = query.all()
  626. return [ChatModel.model_validate(chat) for chat in all_chats]
  627. def get_chats_by_folder_ids_and_user_id(
  628. self, folder_ids: list[str], user_id: str
  629. ) -> list[ChatModel]:
  630. with get_db() as db:
  631. query = db.query(Chat).filter(
  632. Chat.folder_id.in_(folder_ids), Chat.user_id == user_id
  633. )
  634. query = query.filter(or_(Chat.pinned == False, Chat.pinned == None))
  635. query = query.filter_by(archived=False)
  636. query = query.order_by(Chat.updated_at.desc())
  637. all_chats = query.all()
  638. return [ChatModel.model_validate(chat) for chat in all_chats]
  639. def update_chat_folder_id_by_id_and_user_id(
  640. self, id: str, user_id: str, folder_id: str
  641. ) -> Optional[ChatModel]:
  642. try:
  643. with get_db() as db:
  644. chat = db.get(Chat, id)
  645. chat.folder_id = folder_id
  646. chat.updated_at = int(time.time())
  647. chat.pinned = False
  648. db.commit()
  649. db.refresh(chat)
  650. return ChatModel.model_validate(chat)
  651. except Exception:
  652. return None
  653. def get_chat_tags_by_id_and_user_id(self, id: str, user_id: str) -> list[TagModel]:
  654. with get_db() as db:
  655. chat = db.get(Chat, id)
  656. tags = chat.meta.get("tags", [])
  657. return [Tags.get_tag_by_name_and_user_id(tag, user_id) for tag in tags]
  658. def get_chat_list_by_user_id_and_tag_name(
  659. self, user_id: str, tag_name: str, skip: int = 0, limit: int = 50
  660. ) -> list[ChatModel]:
  661. with get_db() as db:
  662. query = db.query(Chat).filter_by(user_id=user_id)
  663. tag_id = tag_name.replace(" ", "_").lower()
  664. log.info(f"DB dialect name: {db.bind.dialect.name}")
  665. if db.bind.dialect.name == "sqlite":
  666. # SQLite JSON1 querying for tags within the meta JSON field
  667. query = query.filter(
  668. text(
  669. f"EXISTS (SELECT 1 FROM json_each(Chat.meta, '$.tags') WHERE json_each.value = :tag_id)"
  670. )
  671. ).params(tag_id=tag_id)
  672. elif db.bind.dialect.name == "postgresql":
  673. # PostgreSQL JSON query for tags within the meta JSON field (for `json` type)
  674. query = query.filter(
  675. text(
  676. "EXISTS (SELECT 1 FROM json_array_elements_text(Chat.meta->'tags') elem WHERE elem = :tag_id)"
  677. )
  678. ).params(tag_id=tag_id)
  679. else:
  680. raise NotImplementedError(
  681. f"Unsupported dialect: {db.bind.dialect.name}"
  682. )
  683. all_chats = query.all()
  684. log.debug(f"all_chats: {all_chats}")
  685. return [ChatModel.model_validate(chat) for chat in all_chats]
  686. def add_chat_tag_by_id_and_user_id_and_tag_name(
  687. self, id: str, user_id: str, tag_name: str
  688. ) -> Optional[ChatModel]:
  689. tag = Tags.get_tag_by_name_and_user_id(tag_name, user_id)
  690. if tag is None:
  691. tag = Tags.insert_new_tag(tag_name, user_id)
  692. try:
  693. with get_db() as db:
  694. chat = db.get(Chat, id)
  695. tag_id = tag.id
  696. if tag_id not in chat.meta.get("tags", []):
  697. chat.meta = {
  698. **chat.meta,
  699. "tags": list(set(chat.meta.get("tags", []) + [tag_id])),
  700. }
  701. db.commit()
  702. db.refresh(chat)
  703. return ChatModel.model_validate(chat)
  704. except Exception:
  705. return None
  706. def count_chats_by_tag_name_and_user_id(self, tag_name: str, user_id: str) -> int:
  707. with get_db() as db: # Assuming `get_db()` returns a session object
  708. query = db.query(Chat).filter_by(user_id=user_id, archived=False)
  709. # Normalize the tag_name for consistency
  710. tag_id = tag_name.replace(" ", "_").lower()
  711. if db.bind.dialect.name == "sqlite":
  712. # SQLite JSON1 support for querying the tags inside the `meta` JSON field
  713. query = query.filter(
  714. text(
  715. f"EXISTS (SELECT 1 FROM json_each(Chat.meta, '$.tags') WHERE json_each.value = :tag_id)"
  716. )
  717. ).params(tag_id=tag_id)
  718. elif db.bind.dialect.name == "postgresql":
  719. # PostgreSQL JSONB support for querying the tags inside the `meta` JSON field
  720. query = query.filter(
  721. text(
  722. "EXISTS (SELECT 1 FROM json_array_elements_text(Chat.meta->'tags') elem WHERE elem = :tag_id)"
  723. )
  724. ).params(tag_id=tag_id)
  725. else:
  726. raise NotImplementedError(
  727. f"Unsupported dialect: {db.bind.dialect.name}"
  728. )
  729. # Get the count of matching records
  730. count = query.count()
  731. # Debugging output for inspection
  732. log.info(f"Count of chats for tag '{tag_name}': {count}")
  733. return count
  734. def delete_tag_by_id_and_user_id_and_tag_name(
  735. self, id: str, user_id: str, tag_name: str
  736. ) -> bool:
  737. try:
  738. with get_db() as db:
  739. chat = db.get(Chat, id)
  740. tags = chat.meta.get("tags", [])
  741. tag_id = tag_name.replace(" ", "_").lower()
  742. tags = [tag for tag in tags if tag != tag_id]
  743. chat.meta = {
  744. **chat.meta,
  745. "tags": list(set(tags)),
  746. }
  747. db.commit()
  748. return True
  749. except Exception:
  750. return False
  751. def delete_all_tags_by_id_and_user_id(self, id: str, user_id: str) -> bool:
  752. try:
  753. with get_db() as db:
  754. chat = db.get(Chat, id)
  755. chat.meta = {
  756. **chat.meta,
  757. "tags": [],
  758. }
  759. db.commit()
  760. return True
  761. except Exception:
  762. return False
  763. def delete_chat_by_id(self, id: str) -> bool:
  764. try:
  765. with get_db() as db:
  766. db.query(Chat).filter_by(id=id).delete()
  767. db.commit()
  768. return True and self.delete_shared_chat_by_chat_id(id)
  769. except Exception:
  770. return False
  771. def delete_chat_by_id_and_user_id(self, id: str, user_id: str) -> bool:
  772. try:
  773. with get_db() as db:
  774. db.query(Chat).filter_by(id=id, user_id=user_id).delete()
  775. db.commit()
  776. return True and self.delete_shared_chat_by_chat_id(id)
  777. except Exception:
  778. return False
  779. def delete_chats_by_user_id(self, user_id: str) -> bool:
  780. try:
  781. with get_db() as db:
  782. self.delete_shared_chats_by_user_id(user_id)
  783. db.query(Chat).filter_by(user_id=user_id).delete()
  784. db.commit()
  785. return True
  786. except Exception:
  787. return False
  788. def delete_chats_by_user_id_and_folder_id(
  789. self, user_id: str, folder_id: str
  790. ) -> bool:
  791. try:
  792. with get_db() as db:
  793. db.query(Chat).filter_by(user_id=user_id, folder_id=folder_id).delete()
  794. db.commit()
  795. return True
  796. except Exception:
  797. return False
  798. def delete_shared_chats_by_user_id(self, user_id: str) -> bool:
  799. try:
  800. with get_db() as db:
  801. chats_by_user = db.query(Chat).filter_by(user_id=user_id).all()
  802. shared_chat_ids = [f"shared-{chat.id}" for chat in chats_by_user]
  803. db.query(Chat).filter(Chat.user_id.in_(shared_chat_ids)).delete()
  804. db.commit()
  805. return True
  806. except Exception:
  807. return False
  808. Chats = ChatTable()