chats.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  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. # Fetch all potentially relevant chats
  336. all_chats = query.all()
  337. # Filter chats using Python
  338. filtered_chats = []
  339. for chat in all_chats:
  340. # Check chat title
  341. title_matches = search_text in chat.title.lower()
  342. # Check chat content in chat JSON
  343. content_matches = any(
  344. search_text in message.get("content", "").lower()
  345. for message in chat.chat.get("messages", [])
  346. if "content" in message
  347. )
  348. if title_matches or content_matches:
  349. filtered_chats.append(chat)
  350. # Implementing pagination manually
  351. paginated_chats = filtered_chats[skip : skip + limit]
  352. return [ChatModel.model_validate(chat) for chat in paginated_chats]
  353. def get_chat_tags_by_id_and_user_id(self, id: str, user_id: str) -> list[TagModel]:
  354. with get_db() as db:
  355. chat = db.get(Chat, id)
  356. tags = chat.meta.get("tags", [])
  357. return [Tags.get_tag_by_name_and_user_id(tag, user_id) for tag in tags]
  358. def get_chat_list_by_user_id_and_tag_name(
  359. self, user_id: str, tag_name: str, skip: int = 0, limit: int = 50
  360. ) -> list[ChatModel]:
  361. with get_db() as db:
  362. query = db.query(Chat).filter_by(user_id=user_id)
  363. tag_id = tag_name.replace(" ", "_").lower()
  364. print(db.bind.dialect.name)
  365. if db.bind.dialect.name == "sqlite":
  366. # SQLite JSON1 querying for tags within the meta JSON field
  367. query = query.filter(
  368. text(
  369. f"EXISTS (SELECT 1 FROM json_each(Chat.meta, '$.tags') WHERE json_each.value = :tag_id)"
  370. )
  371. ).params(tag_id=tag_id)
  372. elif db.bind.dialect.name == "postgresql":
  373. # PostgreSQL JSON query for tags within the meta JSON field (for `json` type)
  374. query = query.filter(
  375. text(
  376. "EXISTS (SELECT 1 FROM json_array_elements_text(Chat.meta->'tags') elem WHERE elem = :tag_id)"
  377. )
  378. ).params(tag_id=tag_id)
  379. else:
  380. raise NotImplementedError(
  381. f"Unsupported dialect: {db.bind.dialect.name}"
  382. )
  383. all_chats = query.all()
  384. print("all_chats", all_chats)
  385. return [ChatModel.model_validate(chat) for chat in all_chats]
  386. def add_chat_tag_by_id_and_user_id_and_tag_name(
  387. self, id: str, user_id: str, tag_name: str
  388. ) -> Optional[ChatModel]:
  389. tag = Tags.get_tag_by_name_and_user_id(tag_name, user_id)
  390. if tag is None:
  391. tag = Tags.insert_new_tag(tag_name, user_id)
  392. try:
  393. with get_db() as db:
  394. chat = db.get(Chat, id)
  395. tag_id = tag.id
  396. if tag_id not in chat.meta.get("tags", []):
  397. chat.meta = {
  398. **chat.meta,
  399. "tags": chat.meta.get("tags", []) + [tag_id],
  400. }
  401. db.commit()
  402. db.refresh(chat)
  403. return ChatModel.model_validate(chat)
  404. except Exception:
  405. return None
  406. def count_chats_by_tag_name_and_user_id(self, tag_name: str, user_id: str) -> int:
  407. with get_db() as db: # Assuming `get_db()` returns a session object
  408. query = db.query(Chat).filter_by(user_id=user_id)
  409. # Normalize the tag_name for consistency
  410. tag_id = tag_name.replace(" ", "_").lower()
  411. if db.bind.dialect.name == "sqlite":
  412. # SQLite JSON1 support for querying the tags inside the `meta` JSON field
  413. query = query.filter(
  414. text(
  415. f"EXISTS (SELECT 1 FROM json_each(Chat.meta, '$.tags') WHERE json_each.value = :tag_id)"
  416. )
  417. ).params(tag_id=tag_id)
  418. elif db.bind.dialect.name == "postgresql":
  419. # PostgreSQL JSONB support for querying the tags inside the `meta` JSON field
  420. query = query.filter(
  421. text(
  422. "EXISTS (SELECT 1 FROM json_array_elements_text(Chat.meta->'tags') elem WHERE elem = :tag_id)"
  423. )
  424. ).params(tag_id=tag_id)
  425. else:
  426. raise NotImplementedError(
  427. f"Unsupported dialect: {db.bind.dialect.name}"
  428. )
  429. # Get the count of matching records
  430. count = query.count()
  431. # Debugging output for inspection
  432. print(f"Count of chats for tag '{tag_name}':", count)
  433. return count
  434. def delete_tag_by_id_and_user_id_and_tag_name(
  435. self, id: str, user_id: str, tag_name: str
  436. ) -> bool:
  437. try:
  438. with get_db() as db:
  439. chat = db.get(Chat, id)
  440. tags = chat.meta.get("tags", [])
  441. tag_id = tag_name.replace(" ", "_").lower()
  442. tags = [tag for tag in tags if tag != tag_id]
  443. chat.meta = {
  444. **chat.meta,
  445. "tags": tags,
  446. }
  447. db.commit()
  448. return True
  449. except Exception:
  450. return False
  451. def delete_all_tags_by_id_and_user_id(self, id: str, user_id: str) -> bool:
  452. try:
  453. with get_db() as db:
  454. chat = db.get(Chat, id)
  455. chat.meta = {
  456. **chat.meta,
  457. "tags": [],
  458. }
  459. db.commit()
  460. return True
  461. except Exception:
  462. return False
  463. def delete_chat_by_id(self, id: str) -> bool:
  464. try:
  465. with get_db() as db:
  466. db.query(Chat).filter_by(id=id).delete()
  467. db.commit()
  468. return True and self.delete_shared_chat_by_chat_id(id)
  469. except Exception:
  470. return False
  471. def delete_chat_by_id_and_user_id(self, id: str, user_id: str) -> bool:
  472. try:
  473. with get_db() as db:
  474. db.query(Chat).filter_by(id=id, user_id=user_id).delete()
  475. db.commit()
  476. return True and self.delete_shared_chat_by_chat_id(id)
  477. except Exception:
  478. return False
  479. def delete_chats_by_user_id(self, user_id: str) -> bool:
  480. try:
  481. with get_db() as db:
  482. self.delete_shared_chats_by_user_id(user_id)
  483. db.query(Chat).filter_by(user_id=user_id).delete()
  484. db.commit()
  485. return True
  486. except Exception:
  487. return False
  488. def delete_shared_chats_by_user_id(self, user_id: str) -> bool:
  489. try:
  490. with get_db() as db:
  491. chats_by_user = db.query(Chat).filter_by(user_id=user_id).all()
  492. shared_chat_ids = [f"shared-{chat.id}" for chat in chats_by_user]
  493. db.query(Chat).filter(Chat.user_id.in_(shared_chat_ids)).delete()
  494. db.commit()
  495. return True
  496. except Exception:
  497. return False
  498. Chats = ChatTable()