chats.py 23 KB

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