chats.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. import json
  2. import time
  3. import uuid
  4. from typing import Optional
  5. from open_webui.apps.webui.internal.db import Base, get_db
  6. from open_webui.apps.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. class ChatModel(BaseModel):
  27. model_config = ConfigDict(from_attributes=True)
  28. id: str
  29. user_id: str
  30. title: str
  31. chat: dict
  32. created_at: int # timestamp in epoch
  33. updated_at: int # timestamp in epoch
  34. share_id: Optional[str] = None
  35. archived: bool = False
  36. pinned: Optional[bool] = False
  37. meta: dict = {}
  38. ####################
  39. # Forms
  40. ####################
  41. class ChatForm(BaseModel):
  42. chat: dict
  43. class ChatTitleForm(BaseModel):
  44. title: str
  45. class ChatResponse(BaseModel):
  46. id: str
  47. user_id: str
  48. title: str
  49. chat: dict
  50. updated_at: int # timestamp in epoch
  51. created_at: int # timestamp in epoch
  52. share_id: Optional[str] = None # id of the chat to be shared
  53. archived: bool
  54. pinned: Optional[bool] = False
  55. meta: dict = {}
  56. class ChatTitleIdResponse(BaseModel):
  57. id: str
  58. title: str
  59. updated_at: int
  60. created_at: int
  61. class ChatTable:
  62. def insert_new_chat(self, user_id: str, form_data: ChatForm) -> Optional[ChatModel]:
  63. with get_db() as db:
  64. id = str(uuid.uuid4())
  65. chat = ChatModel(
  66. **{
  67. "id": id,
  68. "user_id": user_id,
  69. "title": (
  70. form_data.chat["title"]
  71. if "title" in form_data.chat
  72. else "New Chat"
  73. ),
  74. "chat": form_data.chat,
  75. "created_at": int(time.time()),
  76. "updated_at": int(time.time()),
  77. }
  78. )
  79. result = Chat(**chat.model_dump())
  80. db.add(result)
  81. db.commit()
  82. db.refresh(result)
  83. return ChatModel.model_validate(result) if result else None
  84. def update_chat_by_id(self, id: str, chat: dict) -> Optional[ChatModel]:
  85. try:
  86. with get_db() as db:
  87. chat_item = db.get(Chat, id)
  88. chat_item.chat = chat
  89. chat_item.title = chat["title"] if "title" in chat else "New Chat"
  90. chat_item.updated_at = int(time.time())
  91. db.commit()
  92. db.refresh(chat_item)
  93. return ChatModel.model_validate(chat_item)
  94. except Exception:
  95. return None
  96. def insert_shared_chat_by_chat_id(self, chat_id: str) -> Optional[ChatModel]:
  97. with get_db() as db:
  98. # Get the existing chat to share
  99. chat = db.get(Chat, chat_id)
  100. # Check if the chat is already shared
  101. if chat.share_id:
  102. return self.get_chat_by_id_and_user_id(chat.share_id, "shared")
  103. # Create a new chat with the same data, but with a new ID
  104. shared_chat = ChatModel(
  105. **{
  106. "id": str(uuid.uuid4()),
  107. "user_id": f"shared-{chat_id}",
  108. "title": chat.title,
  109. "chat": chat.chat,
  110. "created_at": chat.created_at,
  111. "updated_at": int(time.time()),
  112. }
  113. )
  114. shared_result = Chat(**shared_chat.model_dump())
  115. db.add(shared_result)
  116. db.commit()
  117. db.refresh(shared_result)
  118. # Update the original chat with the share_id
  119. result = (
  120. db.query(Chat)
  121. .filter_by(id=chat_id)
  122. .update({"share_id": shared_chat.id})
  123. )
  124. db.commit()
  125. return shared_chat if (shared_result and result) else None
  126. def update_shared_chat_by_chat_id(self, chat_id: str) -> Optional[ChatModel]:
  127. try:
  128. with get_db() as db:
  129. print("update_shared_chat_by_id")
  130. chat = db.get(Chat, chat_id)
  131. print(chat)
  132. chat.title = chat.title
  133. chat.chat = chat.chat
  134. db.commit()
  135. db.refresh(chat)
  136. return self.get_chat_by_id(chat.share_id)
  137. except Exception:
  138. return None
  139. def delete_shared_chat_by_chat_id(self, chat_id: str) -> bool:
  140. try:
  141. with get_db() as db:
  142. db.query(Chat).filter_by(user_id=f"shared-{chat_id}").delete()
  143. db.commit()
  144. return True
  145. except Exception:
  146. return False
  147. def update_chat_share_id_by_id(
  148. self, id: str, share_id: Optional[str]
  149. ) -> Optional[ChatModel]:
  150. try:
  151. with get_db() as db:
  152. chat = db.get(Chat, id)
  153. chat.share_id = share_id
  154. db.commit()
  155. db.refresh(chat)
  156. return ChatModel.model_validate(chat)
  157. except Exception:
  158. return None
  159. def toggle_chat_pinned_by_id(self, id: str) -> Optional[ChatModel]:
  160. try:
  161. with get_db() as db:
  162. chat = db.get(Chat, id)
  163. chat.pinned = not chat.pinned
  164. chat.updated_at = int(time.time())
  165. db.commit()
  166. db.refresh(chat)
  167. return ChatModel.model_validate(chat)
  168. except Exception:
  169. return None
  170. def toggle_chat_archive_by_id(self, id: str) -> Optional[ChatModel]:
  171. try:
  172. with get_db() as db:
  173. chat = db.get(Chat, id)
  174. chat.archived = not chat.archived
  175. chat.updated_at = int(time.time())
  176. db.commit()
  177. db.refresh(chat)
  178. return ChatModel.model_validate(chat)
  179. except Exception:
  180. return None
  181. def archive_all_chats_by_user_id(self, user_id: str) -> bool:
  182. try:
  183. with get_db() as db:
  184. db.query(Chat).filter_by(user_id=user_id).update({"archived": True})
  185. db.commit()
  186. return True
  187. except Exception:
  188. return False
  189. def get_archived_chat_list_by_user_id(
  190. self, user_id: str, skip: int = 0, limit: int = 50
  191. ) -> list[ChatModel]:
  192. with get_db() as db:
  193. all_chats = (
  194. db.query(Chat)
  195. .filter_by(user_id=user_id, archived=True)
  196. .order_by(Chat.updated_at.desc())
  197. # .limit(limit).offset(skip)
  198. .all()
  199. )
  200. return [ChatModel.model_validate(chat) for chat in all_chats]
  201. def get_chat_list_by_user_id(
  202. self,
  203. user_id: str,
  204. include_archived: bool = False,
  205. skip: int = 0,
  206. limit: int = 50,
  207. ) -> list[ChatModel]:
  208. with get_db() as db:
  209. query = db.query(Chat).filter_by(user_id=user_id)
  210. if not include_archived:
  211. query = query.filter_by(archived=False)
  212. all_chats = (
  213. query.order_by(Chat.updated_at.desc())
  214. # .limit(limit).offset(skip)
  215. .all()
  216. )
  217. return [ChatModel.model_validate(chat) for chat in all_chats]
  218. def get_chat_title_id_list_by_user_id(
  219. self,
  220. user_id: str,
  221. include_archived: bool = False,
  222. skip: Optional[int] = None,
  223. limit: Optional[int] = None,
  224. ) -> list[ChatTitleIdResponse]:
  225. with get_db() as db:
  226. query = db.query(Chat).filter_by(user_id=user_id)
  227. if not include_archived:
  228. query = query.filter_by(archived=False)
  229. query = query.order_by(Chat.updated_at.desc()).with_entities(
  230. Chat.id, Chat.title, Chat.updated_at, Chat.created_at
  231. )
  232. if skip:
  233. query = query.offset(skip)
  234. if limit:
  235. query = query.limit(limit)
  236. all_chats = query.all()
  237. # result has to be destrctured from sqlalchemy `row` and mapped to a dict since the `ChatModel`is not the returned dataclass.
  238. return [
  239. ChatTitleIdResponse.model_validate(
  240. {
  241. "id": chat[0],
  242. "title": chat[1],
  243. "updated_at": chat[2],
  244. "created_at": chat[3],
  245. }
  246. )
  247. for chat in all_chats
  248. ]
  249. def get_chat_list_by_chat_ids(
  250. self, chat_ids: list[str], skip: int = 0, limit: int = 50
  251. ) -> list[ChatModel]:
  252. with get_db() as db:
  253. all_chats = (
  254. db.query(Chat)
  255. .filter(Chat.id.in_(chat_ids))
  256. .filter_by(archived=False)
  257. .order_by(Chat.updated_at.desc())
  258. .all()
  259. )
  260. return [ChatModel.model_validate(chat) for chat in all_chats]
  261. def get_chat_by_id(self, id: str) -> Optional[ChatModel]:
  262. try:
  263. with get_db() as db:
  264. chat = db.get(Chat, id)
  265. return ChatModel.model_validate(chat)
  266. except Exception:
  267. return None
  268. def get_chat_by_share_id(self, id: str) -> Optional[ChatModel]:
  269. try:
  270. with get_db() as db:
  271. chat = db.query(Chat).filter_by(share_id=id).first()
  272. if chat:
  273. return self.get_chat_by_id(id)
  274. else:
  275. return None
  276. except Exception:
  277. return None
  278. def get_chat_by_id_and_user_id(self, id: str, user_id: str) -> Optional[ChatModel]:
  279. try:
  280. with get_db() as db:
  281. chat = db.query(Chat).filter_by(id=id, user_id=user_id).first()
  282. return ChatModel.model_validate(chat)
  283. except Exception:
  284. return None
  285. def get_chats(self, skip: int = 0, limit: int = 50) -> list[ChatModel]:
  286. with get_db() as db:
  287. all_chats = (
  288. db.query(Chat)
  289. # .limit(limit).offset(skip)
  290. .order_by(Chat.updated_at.desc())
  291. )
  292. return [ChatModel.model_validate(chat) for chat in all_chats]
  293. def get_chats_by_user_id(self, user_id: str) -> list[ChatModel]:
  294. with get_db() as db:
  295. all_chats = (
  296. db.query(Chat)
  297. .filter_by(user_id=user_id)
  298. .order_by(Chat.updated_at.desc())
  299. )
  300. return [ChatModel.model_validate(chat) for chat in all_chats]
  301. def get_pinned_chats_by_user_id(self, user_id: str) -> list[ChatModel]:
  302. with get_db() as db:
  303. all_chats = (
  304. db.query(Chat)
  305. .filter_by(user_id=user_id, pinned=True)
  306. .order_by(Chat.updated_at.desc())
  307. )
  308. return [ChatModel.model_validate(chat) for chat in all_chats]
  309. def get_archived_chats_by_user_id(self, user_id: str) -> list[ChatModel]:
  310. with get_db() as db:
  311. all_chats = (
  312. db.query(Chat)
  313. .filter_by(user_id=user_id, archived=True)
  314. .order_by(Chat.updated_at.desc())
  315. )
  316. return [ChatModel.model_validate(chat) for chat in all_chats]
  317. def get_chats_by_user_id_and_search_text(
  318. self,
  319. user_id: str,
  320. search_text: str,
  321. include_archived: bool = False,
  322. skip: int = 0,
  323. limit: int = 60,
  324. ) -> list[ChatModel]:
  325. """
  326. Filters chats based on a search query using Python, allowing pagination using skip and limit.
  327. """
  328. search_text = search_text.lower().strip()
  329. if not search_text:
  330. return self.get_chat_list_by_user_id(user_id, include_archived, skip, limit)
  331. with get_db() as db:
  332. query = db.query(Chat).filter(Chat.user_id == user_id)
  333. if not include_archived:
  334. query = query.filter(Chat.archived == False)
  335. query = query.order_by(Chat.updated_at.desc())
  336. # Check if the database dialect is either 'sqlite' or 'postgresql'
  337. dialect_name = db.bind.dialect.name
  338. if dialect_name == "sqlite":
  339. # SQLite case: using JSON1 extension for JSON searching
  340. query = query.filter(
  341. (
  342. Chat.title.ilike(
  343. f"%{search_text}%"
  344. ) # Case-insensitive search in title
  345. | text(
  346. """
  347. EXISTS (
  348. SELECT 1
  349. FROM json_each(Chat.chat, '$.messages') AS message
  350. WHERE LOWER(message.value->>'content') LIKE '%' || :search_text || '%'
  351. )
  352. """
  353. )
  354. ).params(search_text=search_text)
  355. )
  356. elif dialect_name == "postgresql":
  357. # PostgreSQL relies on proper JSON query for search
  358. query = query.filter(
  359. (
  360. Chat.title.ilike(
  361. f"%{search_text}%"
  362. ) # Case-insensitive search in title
  363. | text(
  364. """
  365. EXISTS (
  366. SELECT 1
  367. FROM json_array_elements(Chat.chat->'messages') AS message
  368. WHERE LOWER(message->>'content') LIKE '%' || :search_text || '%'
  369. )
  370. """
  371. )
  372. ).params(search_text=search_text)
  373. )
  374. else:
  375. raise NotImplementedError(
  376. f"Unsupported dialect: {db.bind.dialect.name}"
  377. )
  378. # Perform pagination at the SQL level
  379. all_chats = query.offset(skip).limit(limit).all()
  380. # Validate and return chats
  381. return [ChatModel.model_validate(chat) for chat in all_chats]
  382. def get_chat_tags_by_id_and_user_id(self, id: str, user_id: str) -> list[TagModel]:
  383. with get_db() as db:
  384. chat = db.get(Chat, id)
  385. tags = chat.meta.get("tags", [])
  386. return [Tags.get_tag_by_name_and_user_id(tag, user_id) for tag in tags]
  387. def get_chat_list_by_user_id_and_tag_name(
  388. self, user_id: str, tag_name: str, skip: int = 0, limit: int = 50
  389. ) -> list[ChatModel]:
  390. with get_db() as db:
  391. query = db.query(Chat).filter_by(user_id=user_id)
  392. tag_id = tag_name.replace(" ", "_").lower()
  393. print(db.bind.dialect.name)
  394. if db.bind.dialect.name == "sqlite":
  395. # SQLite JSON1 querying for tags within the meta JSON field
  396. query = query.filter(
  397. text(
  398. f"EXISTS (SELECT 1 FROM json_each(Chat.meta, '$.tags') WHERE json_each.value = :tag_id)"
  399. )
  400. ).params(tag_id=tag_id)
  401. elif db.bind.dialect.name == "postgresql":
  402. # PostgreSQL JSON query for tags within the meta JSON field (for `json` type)
  403. query = query.filter(
  404. text(
  405. "EXISTS (SELECT 1 FROM json_array_elements_text(Chat.meta->'tags') elem WHERE elem = :tag_id)"
  406. )
  407. ).params(tag_id=tag_id)
  408. else:
  409. raise NotImplementedError(
  410. f"Unsupported dialect: {db.bind.dialect.name}"
  411. )
  412. all_chats = query.all()
  413. print("all_chats", all_chats)
  414. return [ChatModel.model_validate(chat) for chat in all_chats]
  415. def add_chat_tag_by_id_and_user_id_and_tag_name(
  416. self, id: str, user_id: str, tag_name: str
  417. ) -> Optional[ChatModel]:
  418. tag = Tags.get_tag_by_name_and_user_id(tag_name, user_id)
  419. if tag is None:
  420. tag = Tags.insert_new_tag(tag_name, user_id)
  421. try:
  422. with get_db() as db:
  423. chat = db.get(Chat, id)
  424. tag_id = tag.id
  425. if tag_id not in chat.meta.get("tags", []):
  426. chat.meta = {
  427. **chat.meta,
  428. "tags": chat.meta.get("tags", []) + [tag_id],
  429. }
  430. db.commit()
  431. db.refresh(chat)
  432. return ChatModel.model_validate(chat)
  433. except Exception:
  434. return None
  435. def count_chats_by_tag_name_and_user_id(self, tag_name: str, user_id: str) -> int:
  436. with get_db() as db: # Assuming `get_db()` returns a session object
  437. query = db.query(Chat).filter_by(user_id=user_id)
  438. # Normalize the tag_name for consistency
  439. tag_id = tag_name.replace(" ", "_").lower()
  440. if db.bind.dialect.name == "sqlite":
  441. # SQLite JSON1 support for querying the tags inside the `meta` JSON field
  442. query = query.filter(
  443. text(
  444. f"EXISTS (SELECT 1 FROM json_each(Chat.meta, '$.tags') WHERE json_each.value = :tag_id)"
  445. )
  446. ).params(tag_id=tag_id)
  447. elif db.bind.dialect.name == "postgresql":
  448. # PostgreSQL JSONB support for querying the tags inside the `meta` JSON field
  449. query = query.filter(
  450. text(
  451. "EXISTS (SELECT 1 FROM json_array_elements_text(Chat.meta->'tags') elem WHERE elem = :tag_id)"
  452. )
  453. ).params(tag_id=tag_id)
  454. else:
  455. raise NotImplementedError(
  456. f"Unsupported dialect: {db.bind.dialect.name}"
  457. )
  458. # Get the count of matching records
  459. count = query.count()
  460. # Debugging output for inspection
  461. print(f"Count of chats for tag '{tag_name}':", count)
  462. return count
  463. def delete_tag_by_id_and_user_id_and_tag_name(
  464. self, id: str, user_id: str, tag_name: str
  465. ) -> bool:
  466. try:
  467. with get_db() as db:
  468. chat = db.get(Chat, id)
  469. tags = chat.meta.get("tags", [])
  470. tag_id = tag_name.replace(" ", "_").lower()
  471. tags = [tag for tag in tags if tag != tag_id]
  472. chat.meta = {
  473. **chat.meta,
  474. "tags": tags,
  475. }
  476. db.commit()
  477. return True
  478. except Exception:
  479. return False
  480. def delete_all_tags_by_id_and_user_id(self, id: str, user_id: str) -> bool:
  481. try:
  482. with get_db() as db:
  483. chat = db.get(Chat, id)
  484. chat.meta = {
  485. **chat.meta,
  486. "tags": [],
  487. }
  488. db.commit()
  489. return True
  490. except Exception:
  491. return False
  492. def delete_chat_by_id(self, id: str) -> bool:
  493. try:
  494. with get_db() as db:
  495. db.query(Chat).filter_by(id=id).delete()
  496. db.commit()
  497. return True and self.delete_shared_chat_by_chat_id(id)
  498. except Exception:
  499. return False
  500. def delete_chat_by_id_and_user_id(self, id: str, user_id: str) -> bool:
  501. try:
  502. with get_db() as db:
  503. db.query(Chat).filter_by(id=id, user_id=user_id).delete()
  504. db.commit()
  505. return True and self.delete_shared_chat_by_chat_id(id)
  506. except Exception:
  507. return False
  508. def delete_chats_by_user_id(self, user_id: str) -> bool:
  509. try:
  510. with get_db() as db:
  511. self.delete_shared_chats_by_user_id(user_id)
  512. db.query(Chat).filter_by(user_id=user_id).delete()
  513. db.commit()
  514. return True
  515. except Exception:
  516. return False
  517. def delete_shared_chats_by_user_id(self, user_id: str) -> bool:
  518. try:
  519. with get_db() as db:
  520. chats_by_user = db.query(Chat).filter_by(user_id=user_id).all()
  521. shared_chat_ids = [f"shared-{chat.id}" for chat in chats_by_user]
  522. db.query(Chat).filter(Chat.user_id.in_(shared_chat_ids)).delete()
  523. db.commit()
  524. return True
  525. except Exception:
  526. return False
  527. Chats = ChatTable()