chats.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  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. query = query.order_by(Chat.updated_at.desc())
  216. if skip:
  217. query = query.offset(skip)
  218. if limit:
  219. query = query.limit(limit)
  220. all_chats = query.all()
  221. return [ChatModel.model_validate(chat) for chat in all_chats]
  222. def get_chat_title_id_list_by_user_id(
  223. self,
  224. user_id: str,
  225. include_archived: bool = False,
  226. skip: Optional[int] = None,
  227. limit: Optional[int] = None,
  228. ) -> list[ChatTitleIdResponse]:
  229. with get_db() as db:
  230. query = db.query(Chat).filter_by(user_id=user_id)
  231. query = query.filter(or_(Chat.pinned == False, Chat.pinned == None))
  232. if not include_archived:
  233. query = query.filter_by(archived=False)
  234. query = query.order_by(Chat.updated_at.desc()).with_entities(
  235. Chat.id, Chat.title, Chat.updated_at, Chat.created_at
  236. )
  237. if skip:
  238. query = query.offset(skip)
  239. if limit:
  240. query = query.limit(limit)
  241. all_chats = query.all()
  242. # result has to be destrctured from sqlalchemy `row` and mapped to a dict since the `ChatModel`is not the returned dataclass.
  243. return [
  244. ChatTitleIdResponse.model_validate(
  245. {
  246. "id": chat[0],
  247. "title": chat[1],
  248. "updated_at": chat[2],
  249. "created_at": chat[3],
  250. }
  251. )
  252. for chat in all_chats
  253. ]
  254. def get_chat_list_by_chat_ids(
  255. self, chat_ids: list[str], skip: int = 0, limit: int = 50
  256. ) -> list[ChatModel]:
  257. with get_db() as db:
  258. all_chats = (
  259. db.query(Chat)
  260. .filter(Chat.id.in_(chat_ids))
  261. .filter_by(archived=False)
  262. .order_by(Chat.updated_at.desc())
  263. .all()
  264. )
  265. return [ChatModel.model_validate(chat) for chat in all_chats]
  266. def get_chat_by_id(self, id: str) -> Optional[ChatModel]:
  267. try:
  268. with get_db() as db:
  269. chat = db.get(Chat, id)
  270. return ChatModel.model_validate(chat)
  271. except Exception:
  272. return None
  273. def get_chat_by_share_id(self, id: str) -> Optional[ChatModel]:
  274. try:
  275. with get_db() as db:
  276. chat = db.query(Chat).filter_by(share_id=id).first()
  277. if chat:
  278. return self.get_chat_by_id(id)
  279. else:
  280. return None
  281. except Exception:
  282. return None
  283. def get_chat_by_id_and_user_id(self, id: str, user_id: str) -> Optional[ChatModel]:
  284. try:
  285. with get_db() as db:
  286. chat = db.query(Chat).filter_by(id=id, user_id=user_id).first()
  287. return ChatModel.model_validate(chat)
  288. except Exception:
  289. return None
  290. def get_chats(self, skip: int = 0, limit: int = 50) -> list[ChatModel]:
  291. with get_db() as db:
  292. all_chats = (
  293. db.query(Chat)
  294. # .limit(limit).offset(skip)
  295. .order_by(Chat.updated_at.desc())
  296. )
  297. return [ChatModel.model_validate(chat) for chat in all_chats]
  298. def get_chats_by_user_id(self, user_id: str) -> list[ChatModel]:
  299. with get_db() as db:
  300. all_chats = (
  301. db.query(Chat)
  302. .filter_by(user_id=user_id)
  303. .order_by(Chat.updated_at.desc())
  304. )
  305. return [ChatModel.model_validate(chat) for chat in all_chats]
  306. def get_pinned_chats_by_user_id(self, user_id: str) -> list[ChatModel]:
  307. with get_db() as db:
  308. all_chats = (
  309. db.query(Chat)
  310. .filter_by(user_id=user_id, pinned=True, archived=False)
  311. .order_by(Chat.updated_at.desc())
  312. )
  313. return [ChatModel.model_validate(chat) for chat in all_chats]
  314. def get_archived_chats_by_user_id(self, user_id: str) -> list[ChatModel]:
  315. with get_db() as db:
  316. all_chats = (
  317. db.query(Chat)
  318. .filter_by(user_id=user_id, archived=True)
  319. .order_by(Chat.updated_at.desc())
  320. )
  321. return [ChatModel.model_validate(chat) for chat in all_chats]
  322. def get_chats_by_user_id_and_search_text(
  323. self,
  324. user_id: str,
  325. search_text: str,
  326. include_archived: bool = False,
  327. skip: int = 0,
  328. limit: int = 60,
  329. ) -> list[ChatModel]:
  330. """
  331. Filters chats based on a search query using Python, allowing pagination using skip and limit.
  332. """
  333. search_text = search_text.lower().strip()
  334. if not search_text:
  335. return self.get_chat_list_by_user_id(user_id, include_archived, skip, limit)
  336. search_text_words = search_text.split(" ")
  337. # search_text might contain 'tag:tag_name' format so we need to extract the tag_name, split the search_text and remove the tags
  338. tag_ids = [
  339. word.replace("tag:", "").replace(" ", "_").lower()
  340. for word in search_text_words
  341. if word.startswith("tag:")
  342. ]
  343. search_text_words = [
  344. word for word in search_text_words if not word.startswith("tag:")
  345. ]
  346. search_text = " ".join(search_text_words)
  347. with get_db() as db:
  348. query = db.query(Chat).filter(Chat.user_id == user_id)
  349. if not include_archived:
  350. query = query.filter(Chat.archived == False)
  351. query = query.order_by(Chat.updated_at.desc())
  352. # Check if the database dialect is either 'sqlite' or 'postgresql'
  353. dialect_name = db.bind.dialect.name
  354. if dialect_name == "sqlite":
  355. # SQLite case: using JSON1 extension for JSON searching
  356. query = query.filter(
  357. (
  358. Chat.title.ilike(
  359. f"%{search_text}%"
  360. ) # Case-insensitive search in title
  361. | text(
  362. """
  363. EXISTS (
  364. SELECT 1
  365. FROM json_each(Chat.chat, '$.messages') AS message
  366. WHERE LOWER(message.value->>'content') LIKE '%' || :search_text || '%'
  367. )
  368. """
  369. )
  370. ).params(search_text=search_text)
  371. )
  372. # Check if there are any tags to filter, it should have all the tags
  373. if tag_ids:
  374. query = query.filter(
  375. and_(
  376. *[
  377. text(
  378. f"""
  379. EXISTS (
  380. SELECT 1
  381. FROM json_each(Chat.meta, '$.tags') AS tag
  382. WHERE tag.value = :tag_id_{tag_idx}
  383. )
  384. """
  385. ).params(**{f"tag_id_{tag_idx}": tag_id})
  386. for tag_idx, tag_id in enumerate(tag_ids)
  387. ]
  388. )
  389. )
  390. elif dialect_name == "postgresql":
  391. # PostgreSQL relies on proper JSON query for search
  392. query = query.filter(
  393. (
  394. Chat.title.ilike(
  395. f"%{search_text}%"
  396. ) # Case-insensitive search in title
  397. | text(
  398. """
  399. EXISTS (
  400. SELECT 1
  401. FROM json_array_elements(Chat.chat->'messages') AS message
  402. WHERE LOWER(message->>'content') LIKE '%' || :search_text || '%'
  403. )
  404. """
  405. )
  406. ).params(search_text=search_text)
  407. )
  408. # Check if there are any tags to filter, it should have all the tags
  409. if tag_ids:
  410. query = query.filter(
  411. and_(
  412. *[
  413. text(
  414. f"""
  415. EXISTS (
  416. SELECT 1
  417. FROM json_array_elements_text(Chat.meta->'tags') AS tag
  418. WHERE tag = :tag_id_{tag_idx}
  419. )
  420. """
  421. ).params(**{f"tag_id_{tag_idx}": tag_id})
  422. for tag_idx, tag_id in enumerate(tag_ids)
  423. ]
  424. )
  425. )
  426. else:
  427. raise NotImplementedError(
  428. f"Unsupported dialect: {db.bind.dialect.name}"
  429. )
  430. # Perform pagination at the SQL level
  431. all_chats = query.offset(skip).limit(limit).all()
  432. print(len(all_chats))
  433. # Validate and return chats
  434. return [ChatModel.model_validate(chat) for chat in all_chats]
  435. def get_chat_tags_by_id_and_user_id(self, id: str, user_id: str) -> list[TagModel]:
  436. with get_db() as db:
  437. chat = db.get(Chat, id)
  438. tags = chat.meta.get("tags", [])
  439. return [Tags.get_tag_by_name_and_user_id(tag, user_id) for tag in tags]
  440. def get_chat_list_by_user_id_and_tag_name(
  441. self, user_id: str, tag_name: str, skip: int = 0, limit: int = 50
  442. ) -> list[ChatModel]:
  443. with get_db() as db:
  444. query = db.query(Chat).filter_by(user_id=user_id)
  445. tag_id = tag_name.replace(" ", "_").lower()
  446. print(db.bind.dialect.name)
  447. if db.bind.dialect.name == "sqlite":
  448. # SQLite JSON1 querying for tags within the meta JSON field
  449. query = query.filter(
  450. text(
  451. f"EXISTS (SELECT 1 FROM json_each(Chat.meta, '$.tags') WHERE json_each.value = :tag_id)"
  452. )
  453. ).params(tag_id=tag_id)
  454. elif db.bind.dialect.name == "postgresql":
  455. # PostgreSQL JSON query for tags within the meta JSON field (for `json` type)
  456. query = query.filter(
  457. text(
  458. "EXISTS (SELECT 1 FROM json_array_elements_text(Chat.meta->'tags') elem WHERE elem = :tag_id)"
  459. )
  460. ).params(tag_id=tag_id)
  461. else:
  462. raise NotImplementedError(
  463. f"Unsupported dialect: {db.bind.dialect.name}"
  464. )
  465. all_chats = query.all()
  466. print("all_chats", all_chats)
  467. return [ChatModel.model_validate(chat) for chat in all_chats]
  468. def add_chat_tag_by_id_and_user_id_and_tag_name(
  469. self, id: str, user_id: str, tag_name: str
  470. ) -> Optional[ChatModel]:
  471. tag = Tags.get_tag_by_name_and_user_id(tag_name, user_id)
  472. if tag is None:
  473. tag = Tags.insert_new_tag(tag_name, user_id)
  474. try:
  475. with get_db() as db:
  476. chat = db.get(Chat, id)
  477. tag_id = tag.id
  478. if tag_id not in chat.meta.get("tags", []):
  479. chat.meta = {
  480. **chat.meta,
  481. "tags": list(set(chat.meta.get("tags", []) + [tag_id])),
  482. }
  483. db.commit()
  484. db.refresh(chat)
  485. return ChatModel.model_validate(chat)
  486. except Exception:
  487. return None
  488. def count_chats_by_tag_name_and_user_id(self, tag_name: str, user_id: str) -> int:
  489. with get_db() as db: # Assuming `get_db()` returns a session object
  490. query = db.query(Chat).filter_by(user_id=user_id, archived=False)
  491. # Normalize the tag_name for consistency
  492. tag_id = tag_name.replace(" ", "_").lower()
  493. if db.bind.dialect.name == "sqlite":
  494. # SQLite JSON1 support for querying the tags inside the `meta` JSON field
  495. query = query.filter(
  496. text(
  497. f"EXISTS (SELECT 1 FROM json_each(Chat.meta, '$.tags') WHERE json_each.value = :tag_id)"
  498. )
  499. ).params(tag_id=tag_id)
  500. elif db.bind.dialect.name == "postgresql":
  501. # PostgreSQL JSONB support for querying the tags inside the `meta` JSON field
  502. query = query.filter(
  503. text(
  504. "EXISTS (SELECT 1 FROM json_array_elements_text(Chat.meta->'tags') elem WHERE elem = :tag_id)"
  505. )
  506. ).params(tag_id=tag_id)
  507. else:
  508. raise NotImplementedError(
  509. f"Unsupported dialect: {db.bind.dialect.name}"
  510. )
  511. # Get the count of matching records
  512. count = query.count()
  513. # Debugging output for inspection
  514. print(f"Count of chats for tag '{tag_name}':", count)
  515. return count
  516. def delete_tag_by_id_and_user_id_and_tag_name(
  517. self, id: str, user_id: str, tag_name: str
  518. ) -> bool:
  519. try:
  520. with get_db() as db:
  521. chat = db.get(Chat, id)
  522. tags = chat.meta.get("tags", [])
  523. tag_id = tag_name.replace(" ", "_").lower()
  524. tags = [tag for tag in tags if tag != tag_id]
  525. chat.meta = {
  526. **chat.meta,
  527. "tags": list(set(tags)),
  528. }
  529. db.commit()
  530. return True
  531. except Exception:
  532. return False
  533. def delete_all_tags_by_id_and_user_id(self, id: str, user_id: str) -> bool:
  534. try:
  535. with get_db() as db:
  536. chat = db.get(Chat, id)
  537. chat.meta = {
  538. **chat.meta,
  539. "tags": [],
  540. }
  541. db.commit()
  542. return True
  543. except Exception:
  544. return False
  545. def delete_chat_by_id(self, id: str) -> bool:
  546. try:
  547. with get_db() as db:
  548. db.query(Chat).filter_by(id=id).delete()
  549. db.commit()
  550. return True and self.delete_shared_chat_by_chat_id(id)
  551. except Exception:
  552. return False
  553. def delete_chat_by_id_and_user_id(self, id: str, user_id: str) -> bool:
  554. try:
  555. with get_db() as db:
  556. db.query(Chat).filter_by(id=id, user_id=user_id).delete()
  557. db.commit()
  558. return True and self.delete_shared_chat_by_chat_id(id)
  559. except Exception:
  560. return False
  561. def delete_chats_by_user_id(self, user_id: str) -> bool:
  562. try:
  563. with get_db() as db:
  564. self.delete_shared_chats_by_user_id(user_id)
  565. db.query(Chat).filter_by(user_id=user_id).delete()
  566. db.commit()
  567. return True
  568. except Exception:
  569. return False
  570. def delete_shared_chats_by_user_id(self, user_id: str) -> bool:
  571. try:
  572. with get_db() as db:
  573. chats_by_user = db.query(Chat).filter_by(user_id=user_id).all()
  574. shared_chat_ids = [f"shared-{chat.id}" for chat in chats_by_user]
  575. db.query(Chat).filter(Chat.user_id.in_(shared_chat_ids)).delete()
  576. db.commit()
  577. return True
  578. except Exception:
  579. return False
  580. Chats = ChatTable()