chats.py 31 KB

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