chats.py 24 KB

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