chats.py 30 KB

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