chats.py 21 KB

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