chats.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  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, archived=False)
  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. search_text_words = search_text.split(" ")
  335. # search_text might contain 'tag:tag_name' format so we need to extract the tag_name, split the search_text and remove the tags
  336. tag_ids = []
  337. for word in search_text_words:
  338. if word.startswith("tag:"):
  339. tag_id = word[4:]
  340. tag_ids.append(tag_id)
  341. search_text_words.remove(word)
  342. search_text = " ".join(search_text_words)
  343. with get_db() as db:
  344. query = db.query(Chat).filter(Chat.user_id == user_id)
  345. if not include_archived:
  346. query = query.filter(Chat.archived == False)
  347. query = query.order_by(Chat.updated_at.desc())
  348. # Check if the database dialect is either 'sqlite' or 'postgresql'
  349. dialect_name = db.bind.dialect.name
  350. if dialect_name == "sqlite":
  351. # SQLite case: using JSON1 extension for JSON searching
  352. query = query.filter(
  353. (
  354. Chat.title.ilike(
  355. f"%{search_text}%"
  356. ) # Case-insensitive search in title
  357. | text(
  358. """
  359. EXISTS (
  360. SELECT 1
  361. FROM json_each(Chat.chat, '$.messages') AS message
  362. WHERE LOWER(message.value->>'content') LIKE '%' || :search_text || '%'
  363. )
  364. """
  365. )
  366. ).params(search_text=search_text)
  367. )
  368. # Check if there are any tags to filter, it should have all the tags
  369. if tag_ids:
  370. query = query.filter(
  371. and_(
  372. *[
  373. text(
  374. f"""
  375. EXISTS (
  376. SELECT 1
  377. FROM json_each(Chat.meta, '$.tags') AS tag
  378. WHERE tag.value = :tag_id
  379. )
  380. """
  381. ).params(tag_id=tag_id)
  382. for tag_id in tag_ids
  383. ]
  384. )
  385. )
  386. elif dialect_name == "postgresql":
  387. # PostgreSQL relies on proper JSON query for search
  388. query = query.filter(
  389. (
  390. Chat.title.ilike(
  391. f"%{search_text}%"
  392. ) # Case-insensitive search in title
  393. | text(
  394. """
  395. EXISTS (
  396. SELECT 1
  397. FROM json_array_elements(Chat.chat->'messages') AS message
  398. WHERE LOWER(message->>'content') LIKE '%' || :search_text || '%'
  399. )
  400. """
  401. )
  402. ).params(search_text=search_text)
  403. )
  404. # Check if there are any tags to filter, it should have all the tags
  405. if tag_ids:
  406. query = query.filter(
  407. and_(
  408. *[
  409. text(
  410. f"""
  411. EXISTS (
  412. SELECT 1
  413. FROM json_array_elements_text(Chat.meta->'tags') AS tag
  414. WHERE tag = :tag_id
  415. )
  416. """
  417. ).params(tag_id=tag_id)
  418. for tag_id in tag_ids
  419. ]
  420. )
  421. )
  422. else:
  423. raise NotImplementedError(
  424. f"Unsupported dialect: {db.bind.dialect.name}"
  425. )
  426. # Perform pagination at the SQL level
  427. all_chats = query.offset(skip).limit(limit).all()
  428. # Validate and return chats
  429. return [ChatModel.model_validate(chat) for chat in all_chats]
  430. def get_chat_tags_by_id_and_user_id(self, id: str, user_id: str) -> list[TagModel]:
  431. with get_db() as db:
  432. chat = db.get(Chat, id)
  433. tags = chat.meta.get("tags", [])
  434. return [Tags.get_tag_by_name_and_user_id(tag, user_id) for tag in tags]
  435. def get_chat_list_by_user_id_and_tag_name(
  436. self, user_id: str, tag_name: str, skip: int = 0, limit: int = 50
  437. ) -> list[ChatModel]:
  438. with get_db() as db:
  439. query = db.query(Chat).filter_by(user_id=user_id)
  440. tag_id = tag_name.replace(" ", "_").lower()
  441. print(db.bind.dialect.name)
  442. if db.bind.dialect.name == "sqlite":
  443. # SQLite JSON1 querying for tags within the meta JSON field
  444. query = query.filter(
  445. text(
  446. f"EXISTS (SELECT 1 FROM json_each(Chat.meta, '$.tags') WHERE json_each.value = :tag_id)"
  447. )
  448. ).params(tag_id=tag_id)
  449. elif db.bind.dialect.name == "postgresql":
  450. # PostgreSQL JSON query for tags within the meta JSON field (for `json` type)
  451. query = query.filter(
  452. text(
  453. "EXISTS (SELECT 1 FROM json_array_elements_text(Chat.meta->'tags') elem WHERE elem = :tag_id)"
  454. )
  455. ).params(tag_id=tag_id)
  456. else:
  457. raise NotImplementedError(
  458. f"Unsupported dialect: {db.bind.dialect.name}"
  459. )
  460. all_chats = query.all()
  461. print("all_chats", all_chats)
  462. return [ChatModel.model_validate(chat) for chat in all_chats]
  463. def add_chat_tag_by_id_and_user_id_and_tag_name(
  464. self, id: str, user_id: str, tag_name: str
  465. ) -> Optional[ChatModel]:
  466. tag = Tags.get_tag_by_name_and_user_id(tag_name, user_id)
  467. if tag is None:
  468. tag = Tags.insert_new_tag(tag_name, user_id)
  469. try:
  470. with get_db() as db:
  471. chat = db.get(Chat, id)
  472. tag_id = tag.id
  473. if tag_id not in chat.meta.get("tags", []):
  474. chat.meta = {
  475. **chat.meta,
  476. "tags": chat.meta.get("tags", []) + [tag_id],
  477. }
  478. db.commit()
  479. db.refresh(chat)
  480. return ChatModel.model_validate(chat)
  481. except Exception:
  482. return None
  483. def count_chats_by_tag_name_and_user_id(self, tag_name: str, user_id: str) -> int:
  484. with get_db() as db: # Assuming `get_db()` returns a session object
  485. query = db.query(Chat).filter_by(user_id=user_id)
  486. # Normalize the tag_name for consistency
  487. tag_id = tag_name.replace(" ", "_").lower()
  488. if db.bind.dialect.name == "sqlite":
  489. # SQLite JSON1 support for querying the tags inside the `meta` JSON field
  490. query = query.filter(
  491. text(
  492. f"EXISTS (SELECT 1 FROM json_each(Chat.meta, '$.tags') WHERE json_each.value = :tag_id)"
  493. )
  494. ).params(tag_id=tag_id)
  495. elif db.bind.dialect.name == "postgresql":
  496. # PostgreSQL JSONB support for querying the tags inside the `meta` JSON field
  497. query = query.filter(
  498. text(
  499. "EXISTS (SELECT 1 FROM json_array_elements_text(Chat.meta->'tags') elem WHERE elem = :tag_id)"
  500. )
  501. ).params(tag_id=tag_id)
  502. else:
  503. raise NotImplementedError(
  504. f"Unsupported dialect: {db.bind.dialect.name}"
  505. )
  506. # Get the count of matching records
  507. count = query.count()
  508. # Debugging output for inspection
  509. print(f"Count of chats for tag '{tag_name}':", count)
  510. return count
  511. def delete_tag_by_id_and_user_id_and_tag_name(
  512. self, id: str, user_id: str, tag_name: str
  513. ) -> bool:
  514. try:
  515. with get_db() as db:
  516. chat = db.get(Chat, id)
  517. tags = chat.meta.get("tags", [])
  518. tag_id = tag_name.replace(" ", "_").lower()
  519. tags = [tag for tag in tags if tag != tag_id]
  520. chat.meta = {
  521. **chat.meta,
  522. "tags": tags,
  523. }
  524. db.commit()
  525. return True
  526. except Exception:
  527. return False
  528. def delete_all_tags_by_id_and_user_id(self, id: str, user_id: str) -> bool:
  529. try:
  530. with get_db() as db:
  531. chat = db.get(Chat, id)
  532. chat.meta = {
  533. **chat.meta,
  534. "tags": [],
  535. }
  536. db.commit()
  537. return True
  538. except Exception:
  539. return False
  540. def delete_chat_by_id(self, id: str) -> bool:
  541. try:
  542. with get_db() as db:
  543. db.query(Chat).filter_by(id=id).delete()
  544. db.commit()
  545. return True and self.delete_shared_chat_by_chat_id(id)
  546. except Exception:
  547. return False
  548. def delete_chat_by_id_and_user_id(self, id: str, user_id: str) -> bool:
  549. try:
  550. with get_db() as db:
  551. db.query(Chat).filter_by(id=id, user_id=user_id).delete()
  552. db.commit()
  553. return True and self.delete_shared_chat_by_chat_id(id)
  554. except Exception:
  555. return False
  556. def delete_chats_by_user_id(self, user_id: str) -> bool:
  557. try:
  558. with get_db() as db:
  559. self.delete_shared_chats_by_user_id(user_id)
  560. db.query(Chat).filter_by(user_id=user_id).delete()
  561. db.commit()
  562. return True
  563. except Exception:
  564. return False
  565. def delete_shared_chats_by_user_id(self, user_id: str) -> bool:
  566. try:
  567. with get_db() as db:
  568. chats_by_user = db.query(Chat).filter_by(user_id=user_id).all()
  569. shared_chat_ids = [f"shared-{chat.id}" for chat in chats_by_user]
  570. db.query(Chat).filter(Chat.user_id.in_(shared_chat_ids)).delete()
  571. db.commit()
  572. return True
  573. except Exception:
  574. return False
  575. Chats = ChatTable()