chats.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965
  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. ####################
  14. # Chat DB Schema
  15. ####################
  16. log = logging.getLogger(__name__)
  17. log.setLevel(SRC_LOG_LEVELS["MODELS"])
  18. class Chat(Base):
  19. __tablename__ = "chat"
  20. id = Column(String, primary_key=True)
  21. user_id = Column(String)
  22. title = Column(Text)
  23. chat = Column(JSON)
  24. created_at = Column(BigInteger)
  25. updated_at = Column(BigInteger)
  26. share_id = Column(Text, unique=True, nullable=True)
  27. archived = Column(Boolean, default=False)
  28. pinned = Column(Boolean, default=False, nullable=True)
  29. meta = Column(JSON, server_default="{}")
  30. folder_id = Column(Text, nullable=True)
  31. class ChatModel(BaseModel):
  32. model_config = ConfigDict(from_attributes=True)
  33. id: str
  34. user_id: str
  35. title: str
  36. chat: dict
  37. created_at: int # timestamp in epoch
  38. updated_at: int # timestamp in epoch
  39. share_id: Optional[str] = None
  40. archived: bool = False
  41. pinned: Optional[bool] = False
  42. meta: dict = {}
  43. folder_id: Optional[str] = None
  44. ####################
  45. # Forms
  46. ####################
  47. class ChatForm(BaseModel):
  48. chat: dict
  49. class ChatImportForm(ChatForm):
  50. meta: Optional[dict] = {}
  51. pinned: Optional[bool] = False
  52. folder_id: Optional[str] = None
  53. created_at: Optional[int] = None
  54. updated_at: Optional[int] = None
  55. class ChatTitleMessagesForm(BaseModel):
  56. title: str
  57. messages: list[dict]
  58. class ChatTitleForm(BaseModel):
  59. title: str
  60. class ChatResponse(BaseModel):
  61. id: str
  62. user_id: str
  63. title: str
  64. chat: dict
  65. updated_at: int # timestamp in epoch
  66. created_at: int # timestamp in epoch
  67. share_id: Optional[str] = None # id of the chat to be shared
  68. archived: bool
  69. pinned: Optional[bool] = False
  70. meta: dict = {}
  71. folder_id: Optional[str] = None
  72. class ChatTitleIdResponse(BaseModel):
  73. id: str
  74. title: str
  75. updated_at: int
  76. created_at: int
  77. class ChatTable:
  78. def insert_new_chat(self, user_id: str, form_data: ChatForm) -> Optional[ChatModel]:
  79. with get_db() as db:
  80. id = str(uuid.uuid4())
  81. chat = ChatModel(
  82. **{
  83. "id": id,
  84. "user_id": user_id,
  85. "title": (
  86. form_data.chat["title"]
  87. if "title" in form_data.chat
  88. else "New Chat"
  89. ),
  90. "chat": form_data.chat,
  91. "created_at": int(time.time()),
  92. "updated_at": int(time.time()),
  93. }
  94. )
  95. result = Chat(**chat.model_dump())
  96. db.add(result)
  97. db.commit()
  98. db.refresh(result)
  99. return ChatModel.model_validate(result) if result else None
  100. def import_chat(
  101. self, user_id: str, form_data: ChatImportForm
  102. ) -> Optional[ChatModel]:
  103. with get_db() as db:
  104. id = str(uuid.uuid4())
  105. chat = ChatModel(
  106. **{
  107. "id": id,
  108. "user_id": user_id,
  109. "title": (
  110. form_data.chat["title"]
  111. if "title" in form_data.chat
  112. else "New Chat"
  113. ),
  114. "chat": form_data.chat,
  115. "meta": form_data.meta,
  116. "pinned": form_data.pinned,
  117. "folder_id": form_data.folder_id,
  118. "created_at": (
  119. form_data.created_at
  120. if form_data.created_at
  121. else int(time.time())
  122. ),
  123. "updated_at": (
  124. form_data.updated_at
  125. if form_data.updated_at
  126. else int(time.time())
  127. ),
  128. }
  129. )
  130. result = Chat(**chat.model_dump())
  131. db.add(result)
  132. db.commit()
  133. db.refresh(result)
  134. return ChatModel.model_validate(result) if result else None
  135. def update_chat_by_id(self, id: str, chat: dict) -> Optional[ChatModel]:
  136. try:
  137. with get_db() as db:
  138. chat_item = db.get(Chat, id)
  139. chat_item.chat = chat
  140. chat_item.title = chat["title"] if "title" in chat else "New Chat"
  141. chat_item.updated_at = int(time.time())
  142. db.commit()
  143. db.refresh(chat_item)
  144. return ChatModel.model_validate(chat_item)
  145. except Exception:
  146. return None
  147. def update_chat_title_by_id(self, id: str, title: str) -> Optional[ChatModel]:
  148. chat = self.get_chat_by_id(id)
  149. if chat is None:
  150. return None
  151. chat = chat.chat
  152. chat["title"] = title
  153. return self.update_chat_by_id(id, chat)
  154. def update_chat_tags_by_id(
  155. self, id: str, tags: list[str], user
  156. ) -> Optional[ChatModel]:
  157. chat = self.get_chat_by_id(id)
  158. if chat is None:
  159. return None
  160. self.delete_all_tags_by_id_and_user_id(id, user.id)
  161. for tag in chat.meta.get("tags", []):
  162. if self.count_chats_by_tag_name_and_user_id(tag, user.id) == 0:
  163. Tags.delete_tag_by_name_and_user_id(tag, user.id)
  164. for tag_name in tags:
  165. if tag_name.lower() == "none":
  166. continue
  167. self.add_chat_tag_by_id_and_user_id_and_tag_name(id, user.id, tag_name)
  168. return self.get_chat_by_id(id)
  169. def get_chat_title_by_id(self, id: str) -> Optional[str]:
  170. chat = self.get_chat_by_id(id)
  171. if chat is None:
  172. return None
  173. return chat.chat.get("title", "New Chat")
  174. def get_messages_by_chat_id(self, id: str) -> Optional[dict]:
  175. chat = self.get_chat_by_id(id)
  176. if chat is None:
  177. return None
  178. return chat.chat.get("history", {}).get("messages", {}) or {}
  179. def get_message_by_id_and_message_id(
  180. self, id: str, message_id: str
  181. ) -> Optional[dict]:
  182. chat = self.get_chat_by_id(id)
  183. if chat is None:
  184. return None
  185. return chat.chat.get("history", {}).get("messages", {}).get(message_id, {})
  186. def upsert_message_to_chat_by_id_and_message_id(
  187. self, id: str, message_id: str, message: dict
  188. ) -> Optional[ChatModel]:
  189. chat = self.get_chat_by_id(id)
  190. if chat is None:
  191. return None
  192. chat = chat.chat
  193. history = chat.get("history", {})
  194. if message_id in history.get("messages", {}):
  195. history["messages"][message_id] = {
  196. **history["messages"][message_id],
  197. **message,
  198. }
  199. else:
  200. history["messages"][message_id] = message
  201. history["currentId"] = message_id
  202. chat["history"] = history
  203. return self.update_chat_by_id(id, chat)
  204. def add_message_status_to_chat_by_id_and_message_id(
  205. self, id: str, message_id: str, status: dict
  206. ) -> Optional[ChatModel]:
  207. chat = self.get_chat_by_id(id)
  208. if chat is None:
  209. return None
  210. chat = chat.chat
  211. history = chat.get("history", {})
  212. if message_id in history.get("messages", {}):
  213. status_history = history["messages"][message_id].get("statusHistory", [])
  214. status_history.append(status)
  215. history["messages"][message_id]["statusHistory"] = status_history
  216. chat["history"] = history
  217. return self.update_chat_by_id(id, chat)
  218. def insert_shared_chat_by_chat_id(self, chat_id: str) -> Optional[ChatModel]:
  219. with get_db() as db:
  220. # Get the existing chat to share
  221. chat = db.get(Chat, chat_id)
  222. # Check if the chat is already shared
  223. if chat.share_id:
  224. return self.get_chat_by_id_and_user_id(chat.share_id, "shared")
  225. # Create a new chat with the same data, but with a new ID
  226. shared_chat = ChatModel(
  227. **{
  228. "id": str(uuid.uuid4()),
  229. "user_id": f"shared-{chat_id}",
  230. "title": chat.title,
  231. "chat": chat.chat,
  232. "created_at": chat.created_at,
  233. "updated_at": int(time.time()),
  234. }
  235. )
  236. shared_result = Chat(**shared_chat.model_dump())
  237. db.add(shared_result)
  238. db.commit()
  239. db.refresh(shared_result)
  240. # Update the original chat with the share_id
  241. result = (
  242. db.query(Chat)
  243. .filter_by(id=chat_id)
  244. .update({"share_id": shared_chat.id})
  245. )
  246. db.commit()
  247. return shared_chat if (shared_result and result) else None
  248. def update_shared_chat_by_chat_id(self, chat_id: str) -> Optional[ChatModel]:
  249. try:
  250. with get_db() as db:
  251. chat = db.get(Chat, chat_id)
  252. shared_chat = (
  253. db.query(Chat).filter_by(user_id=f"shared-{chat_id}").first()
  254. )
  255. if shared_chat is None:
  256. return self.insert_shared_chat_by_chat_id(chat_id)
  257. shared_chat.title = chat.title
  258. shared_chat.chat = chat.chat
  259. shared_chat.updated_at = int(time.time())
  260. db.commit()
  261. db.refresh(shared_chat)
  262. return ChatModel.model_validate(shared_chat)
  263. except Exception:
  264. return None
  265. def delete_shared_chat_by_chat_id(self, chat_id: str) -> bool:
  266. try:
  267. with get_db() as db:
  268. db.query(Chat).filter_by(user_id=f"shared-{chat_id}").delete()
  269. db.commit()
  270. return True
  271. except Exception:
  272. return False
  273. def update_chat_share_id_by_id(
  274. self, id: str, share_id: Optional[str]
  275. ) -> Optional[ChatModel]:
  276. try:
  277. with get_db() as db:
  278. chat = db.get(Chat, id)
  279. chat.share_id = share_id
  280. db.commit()
  281. db.refresh(chat)
  282. return ChatModel.model_validate(chat)
  283. except Exception:
  284. return None
  285. def toggle_chat_pinned_by_id(self, id: str) -> Optional[ChatModel]:
  286. try:
  287. with get_db() as db:
  288. chat = db.get(Chat, id)
  289. chat.pinned = not chat.pinned
  290. chat.updated_at = int(time.time())
  291. db.commit()
  292. db.refresh(chat)
  293. return ChatModel.model_validate(chat)
  294. except Exception:
  295. return None
  296. def toggle_chat_archive_by_id(self, id: str) -> Optional[ChatModel]:
  297. try:
  298. with get_db() as db:
  299. chat = db.get(Chat, id)
  300. chat.archived = not chat.archived
  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 archive_all_chats_by_user_id(self, user_id: str) -> bool:
  308. try:
  309. with get_db() as db:
  310. db.query(Chat).filter_by(user_id=user_id).update({"archived": True})
  311. db.commit()
  312. return True
  313. except Exception:
  314. return False
  315. def get_archived_chat_list_by_user_id(
  316. self,
  317. user_id: str,
  318. filter: Optional[dict] = None,
  319. skip: int = 0,
  320. limit: int = 50,
  321. ) -> list[ChatModel]:
  322. with get_db() as db:
  323. query = db.query(Chat).filter_by(user_id=user_id, archived=True)
  324. if filter:
  325. query_key = filter.get("query")
  326. if query_key:
  327. query = query.filter(Chat.title.ilike(f"%{query_key}%"))
  328. order_by = filter.get("order_by")
  329. direction = filter.get("direction")
  330. if order_by and direction and getattr(Chat, order_by):
  331. if direction.lower() == "asc":
  332. query = query.order_by(getattr(Chat, order_by).asc())
  333. elif direction.lower() == "desc":
  334. query = query.order_by(getattr(Chat, order_by).desc())
  335. else:
  336. raise ValueError("Invalid direction for ordering")
  337. else:
  338. query = query.order_by(Chat.updated_at.desc())
  339. if skip:
  340. query = query.offset(skip)
  341. if limit:
  342. query = query.limit(limit)
  343. all_chats = query.all()
  344. return [ChatModel.model_validate(chat) for chat in all_chats]
  345. def get_chat_list_by_user_id(
  346. self,
  347. user_id: str,
  348. include_archived: bool = False,
  349. filter: Optional[dict] = None,
  350. skip: int = 0,
  351. limit: int = 50,
  352. ) -> list[ChatModel]:
  353. with get_db() as db:
  354. query = db.query(Chat).filter_by(user_id=user_id)
  355. if not include_archived:
  356. query = query.filter_by(archived=False)
  357. if filter:
  358. query_key = filter.get("query")
  359. if query_key:
  360. query = query.filter(Chat.title.ilike(f"%{query_key}%"))
  361. order_by = filter.get("order_by")
  362. direction = filter.get("direction")
  363. if order_by and direction and getattr(Chat, order_by):
  364. if direction.lower() == "asc":
  365. query = query.order_by(getattr(Chat, order_by).asc())
  366. elif direction.lower() == "desc":
  367. query = query.order_by(getattr(Chat, order_by).desc())
  368. else:
  369. raise ValueError("Invalid direction for ordering")
  370. else:
  371. query = query.order_by(Chat.updated_at.desc())
  372. if skip:
  373. query = query.offset(skip)
  374. if limit:
  375. query = query.limit(limit)
  376. all_chats = query.all()
  377. return [ChatModel.model_validate(chat) for chat in all_chats]
  378. def get_chat_title_id_list_by_user_id(
  379. self,
  380. user_id: str,
  381. include_archived: bool = False,
  382. skip: Optional[int] = None,
  383. limit: Optional[int] = None,
  384. ) -> list[ChatTitleIdResponse]:
  385. with get_db() as db:
  386. query = db.query(Chat).filter_by(user_id=user_id).filter_by(folder_id=None)
  387. query = query.filter(or_(Chat.pinned == False, Chat.pinned == None))
  388. if not include_archived:
  389. query = query.filter_by(archived=False)
  390. query = query.order_by(Chat.updated_at.desc()).with_entities(
  391. Chat.id, Chat.title, Chat.updated_at, Chat.created_at
  392. )
  393. if skip:
  394. query = query.offset(skip)
  395. if limit:
  396. query = query.limit(limit)
  397. all_chats = query.all()
  398. # result has to be destructured from sqlalchemy `row` and mapped to a dict since the `ChatModel`is not the returned dataclass.
  399. return [
  400. ChatTitleIdResponse.model_validate(
  401. {
  402. "id": chat[0],
  403. "title": chat[1],
  404. "updated_at": chat[2],
  405. "created_at": chat[3],
  406. }
  407. )
  408. for chat in all_chats
  409. ]
  410. def get_chat_list_by_chat_ids(
  411. self, chat_ids: list[str], skip: int = 0, limit: int = 50
  412. ) -> list[ChatModel]:
  413. with get_db() as db:
  414. all_chats = (
  415. db.query(Chat)
  416. .filter(Chat.id.in_(chat_ids))
  417. .filter_by(archived=False)
  418. .order_by(Chat.updated_at.desc())
  419. .all()
  420. )
  421. return [ChatModel.model_validate(chat) for chat in all_chats]
  422. def get_chat_by_id(self, id: str) -> Optional[ChatModel]:
  423. try:
  424. with get_db() as db:
  425. chat = db.get(Chat, id)
  426. return ChatModel.model_validate(chat)
  427. except Exception:
  428. return None
  429. def get_chat_by_share_id(self, id: str) -> Optional[ChatModel]:
  430. try:
  431. with get_db() as db:
  432. # it is possible that the shared link was deleted. hence,
  433. # we check if the chat is still shared by checking if a chat with the share_id exists
  434. chat = db.query(Chat).filter_by(share_id=id).first()
  435. if chat:
  436. return self.get_chat_by_id(id)
  437. else:
  438. return None
  439. except Exception:
  440. return None
  441. def get_chat_by_id_and_user_id(self, id: str, user_id: str) -> Optional[ChatModel]:
  442. try:
  443. with get_db() as db:
  444. chat = db.query(Chat).filter_by(id=id, user_id=user_id).first()
  445. return ChatModel.model_validate(chat)
  446. except Exception:
  447. return None
  448. def get_chats(self, skip: int = 0, limit: int = 50) -> list[ChatModel]:
  449. with get_db() as db:
  450. all_chats = (
  451. db.query(Chat)
  452. # .limit(limit).offset(skip)
  453. .order_by(Chat.updated_at.desc())
  454. )
  455. return [ChatModel.model_validate(chat) for chat in all_chats]
  456. def get_chats_by_user_id(self, user_id: str) -> list[ChatModel]:
  457. with get_db() as db:
  458. all_chats = (
  459. db.query(Chat)
  460. .filter_by(user_id=user_id)
  461. .order_by(Chat.updated_at.desc())
  462. )
  463. return [ChatModel.model_validate(chat) for chat in all_chats]
  464. def get_pinned_chats_by_user_id(self, user_id: str) -> list[ChatModel]:
  465. with get_db() as db:
  466. all_chats = (
  467. db.query(Chat)
  468. .filter_by(user_id=user_id, pinned=True, archived=False)
  469. .order_by(Chat.updated_at.desc())
  470. )
  471. return [ChatModel.model_validate(chat) for chat in all_chats]
  472. def get_archived_chats_by_user_id(self, user_id: str) -> list[ChatModel]:
  473. with get_db() as db:
  474. all_chats = (
  475. db.query(Chat)
  476. .filter_by(user_id=user_id, archived=True)
  477. .order_by(Chat.updated_at.desc())
  478. )
  479. return [ChatModel.model_validate(chat) for chat in all_chats]
  480. def get_chats_by_user_id_and_search_text(
  481. self,
  482. user_id: str,
  483. search_text: str,
  484. include_archived: bool = False,
  485. skip: int = 0,
  486. limit: int = 60,
  487. ) -> list[ChatModel]:
  488. """
  489. Filters chats based on a search query using Python, allowing pagination using skip and limit.
  490. """
  491. search_text = search_text.lower().strip()
  492. if not search_text:
  493. return self.get_chat_list_by_user_id(
  494. user_id, include_archived, filter={}, skip=skip, limit=limit
  495. )
  496. search_text_words = search_text.split(" ")
  497. # search_text might contain 'tag:tag_name' format so we need to extract the tag_name, split the search_text and remove the tags
  498. tag_ids = [
  499. word.replace("tag:", "").replace(" ", "_").lower()
  500. for word in search_text_words
  501. if word.startswith("tag:")
  502. ]
  503. search_text_words = [
  504. word for word in search_text_words if not word.startswith("tag:")
  505. ]
  506. search_text = " ".join(search_text_words)
  507. with get_db() as db:
  508. query = db.query(Chat).filter(Chat.user_id == user_id)
  509. if not include_archived:
  510. query = query.filter(Chat.archived == False)
  511. query = query.order_by(Chat.updated_at.desc())
  512. # Check if the database dialect is either 'sqlite' or 'postgresql'
  513. dialect_name = db.bind.dialect.name
  514. if dialect_name == "sqlite":
  515. # SQLite case: using JSON1 extension for JSON searching
  516. query = query.filter(
  517. (
  518. Chat.title.ilike(
  519. f"%{search_text}%"
  520. ) # Case-insensitive search in title
  521. | text(
  522. """
  523. EXISTS (
  524. SELECT 1
  525. FROM json_each(Chat.chat, '$.messages') AS message
  526. WHERE LOWER(message.value->>'content') LIKE '%' || :search_text || '%'
  527. )
  528. """
  529. )
  530. ).params(search_text=search_text)
  531. )
  532. # Check if there are any tags to filter, it should have all the tags
  533. if "none" in tag_ids:
  534. query = query.filter(
  535. text(
  536. """
  537. NOT EXISTS (
  538. SELECT 1
  539. FROM json_each(Chat.meta, '$.tags') AS tag
  540. )
  541. """
  542. )
  543. )
  544. elif tag_ids:
  545. query = query.filter(
  546. and_(
  547. *[
  548. text(
  549. f"""
  550. EXISTS (
  551. SELECT 1
  552. FROM json_each(Chat.meta, '$.tags') AS tag
  553. WHERE tag.value = :tag_id_{tag_idx}
  554. )
  555. """
  556. ).params(**{f"tag_id_{tag_idx}": tag_id})
  557. for tag_idx, tag_id in enumerate(tag_ids)
  558. ]
  559. )
  560. )
  561. elif dialect_name == "postgresql":
  562. # PostgreSQL relies on proper JSON query for search
  563. query = query.filter(
  564. (
  565. Chat.title.ilike(
  566. f"%{search_text}%"
  567. ) # Case-insensitive search in title
  568. | text(
  569. """
  570. EXISTS (
  571. SELECT 1
  572. FROM json_array_elements(Chat.chat->'messages') AS message
  573. WHERE LOWER(message->>'content') LIKE '%' || :search_text || '%'
  574. )
  575. """
  576. )
  577. ).params(search_text=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()