chats.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  1. import json
  2. import logging
  3. from typing import Optional
  4. from open_webui.apps.webui.models.chats import (
  5. ChatForm,
  6. ChatImportForm,
  7. ChatResponse,
  8. Chats,
  9. ChatTitleIdResponse,
  10. )
  11. from open_webui.apps.webui.models.tags import TagModel, Tags
  12. from open_webui.apps.webui.models.folders import Folders
  13. from open_webui.config import ENABLE_ADMIN_CHAT_ACCESS, ENABLE_ADMIN_EXPORT
  14. from open_webui.constants import ERROR_MESSAGES
  15. from open_webui.env import SRC_LOG_LEVELS
  16. from fastapi import APIRouter, Depends, HTTPException, Request, status
  17. from pydantic import BaseModel
  18. from open_webui.utils.utils import get_admin_user, get_verified_user
  19. log = logging.getLogger(__name__)
  20. log.setLevel(SRC_LOG_LEVELS["MODELS"])
  21. router = APIRouter()
  22. ############################
  23. # GetChatList
  24. ############################
  25. @router.get("/", response_model=list[ChatTitleIdResponse])
  26. @router.get("/list", response_model=list[ChatTitleIdResponse])
  27. async def get_session_user_chat_list(
  28. user=Depends(get_verified_user), page: Optional[int] = None
  29. ):
  30. if page is not None:
  31. limit = 60
  32. skip = (page - 1) * limit
  33. return Chats.get_chat_title_id_list_by_user_id(user.id, skip=skip, limit=limit)
  34. else:
  35. return Chats.get_chat_title_id_list_by_user_id(user.id)
  36. ############################
  37. # DeleteAllChats
  38. ############################
  39. @router.delete("/", response_model=bool)
  40. async def delete_all_user_chats(request: Request, user=Depends(get_verified_user)):
  41. if user.role == "user" and not request.app.state.config.USER_PERMISSIONS.get(
  42. "chat", {}
  43. ).get("deletion", {}):
  44. raise HTTPException(
  45. status_code=status.HTTP_401_UNAUTHORIZED,
  46. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  47. )
  48. result = Chats.delete_chats_by_user_id(user.id)
  49. return result
  50. ############################
  51. # GetUserChatList
  52. ############################
  53. @router.get("/list/user/{user_id}", response_model=list[ChatTitleIdResponse])
  54. async def get_user_chat_list_by_user_id(
  55. user_id: str,
  56. user=Depends(get_admin_user),
  57. skip: int = 0,
  58. limit: int = 50,
  59. ):
  60. if not ENABLE_ADMIN_CHAT_ACCESS:
  61. raise HTTPException(
  62. status_code=status.HTTP_401_UNAUTHORIZED,
  63. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  64. )
  65. return Chats.get_chat_list_by_user_id(
  66. user_id, include_archived=True, skip=skip, limit=limit
  67. )
  68. ############################
  69. # CreateNewChat
  70. ############################
  71. @router.post("/new", response_model=Optional[ChatResponse])
  72. async def create_new_chat(form_data: ChatForm, user=Depends(get_verified_user)):
  73. try:
  74. chat = Chats.insert_new_chat(user.id, form_data)
  75. return ChatResponse(**chat.model_dump())
  76. except Exception as e:
  77. log.exception(e)
  78. raise HTTPException(
  79. status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT()
  80. )
  81. ############################
  82. # ImportChat
  83. ############################
  84. @router.post("/import", response_model=Optional[ChatResponse])
  85. async def import_chat(form_data: ChatImportForm, user=Depends(get_verified_user)):
  86. try:
  87. chat = Chats.import_chat(user.id, form_data)
  88. return ChatResponse(**chat.model_dump())
  89. except Exception as e:
  90. log.exception(e)
  91. raise HTTPException(
  92. status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT()
  93. )
  94. ############################
  95. # GetChats
  96. ############################
  97. @router.get("/search", response_model=list[ChatTitleIdResponse])
  98. async def search_user_chats(
  99. text: str, page: Optional[int] = None, user=Depends(get_verified_user)
  100. ):
  101. if page is None:
  102. page = 1
  103. limit = 60
  104. skip = (page - 1) * limit
  105. chat_list = [
  106. ChatTitleIdResponse(**chat.model_dump())
  107. for chat in Chats.get_chats_by_user_id_and_search_text(
  108. user.id, text, skip=skip, limit=limit
  109. )
  110. ]
  111. # Delete tag if no chat is found
  112. words = text.strip().split(" ")
  113. if page == 1 and len(words) == 1 and words[0].startswith("tag:"):
  114. tag_id = words[0].replace("tag:", "")
  115. if len(chat_list) == 0:
  116. if Tags.get_tag_by_name_and_user_id(tag_id, user.id):
  117. log.debug(f"deleting tag: {tag_id}")
  118. Tags.delete_tag_by_name_and_user_id(tag_id, user.id)
  119. return chat_list
  120. ############################
  121. # GetChatsByFolderId
  122. ############################
  123. @router.get("/folder/{folder_id}", response_model=list[ChatResponse])
  124. async def get_chats_by_folder_id(folder_id: str, user=Depends(get_verified_user)):
  125. folder_ids = [folder_id]
  126. children_folders = Folders.get_children_folders_by_id_and_user_id(
  127. folder_id, user.id
  128. )
  129. if children_folders:
  130. folder_ids.extend([folder.id for folder in children_folders])
  131. return [
  132. ChatResponse(**chat.model_dump())
  133. for chat in Chats.get_chats_by_folder_ids_and_user_id(folder_ids, user.id)
  134. ]
  135. ############################
  136. # GetPinnedChats
  137. ############################
  138. @router.get("/pinned", response_model=list[ChatResponse])
  139. async def get_user_pinned_chats(user=Depends(get_verified_user)):
  140. return [
  141. ChatResponse(**chat.model_dump())
  142. for chat in Chats.get_pinned_chats_by_user_id(user.id)
  143. ]
  144. ############################
  145. # GetChats
  146. ############################
  147. @router.get("/all", response_model=list[ChatResponse])
  148. async def get_user_chats(user=Depends(get_verified_user)):
  149. return [
  150. ChatResponse(**chat.model_dump())
  151. for chat in Chats.get_chats_by_user_id(user.id)
  152. ]
  153. ############################
  154. # GetArchivedChats
  155. ############################
  156. @router.get("/all/archived", response_model=list[ChatResponse])
  157. async def get_user_archived_chats(user=Depends(get_verified_user)):
  158. return [
  159. ChatResponse(**chat.model_dump())
  160. for chat in Chats.get_archived_chats_by_user_id(user.id)
  161. ]
  162. ############################
  163. # GetAllTags
  164. ############################
  165. @router.get("/all/tags", response_model=list[TagModel])
  166. async def get_all_user_tags(user=Depends(get_verified_user)):
  167. try:
  168. tags = Tags.get_tags_by_user_id(user.id)
  169. return tags
  170. except Exception as e:
  171. log.exception(e)
  172. raise HTTPException(
  173. status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT()
  174. )
  175. ############################
  176. # GetAllChatsInDB
  177. ############################
  178. @router.get("/all/db", response_model=list[ChatResponse])
  179. async def get_all_user_chats_in_db(user=Depends(get_admin_user)):
  180. if not ENABLE_ADMIN_EXPORT:
  181. raise HTTPException(
  182. status_code=status.HTTP_401_UNAUTHORIZED,
  183. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  184. )
  185. return [ChatResponse(**chat.model_dump()) for chat in Chats.get_chats()]
  186. ############################
  187. # GetArchivedChats
  188. ############################
  189. @router.get("/archived", response_model=list[ChatTitleIdResponse])
  190. async def get_archived_session_user_chat_list(
  191. user=Depends(get_verified_user), skip: int = 0, limit: int = 50
  192. ):
  193. return Chats.get_archived_chat_list_by_user_id(user.id, skip, limit)
  194. ############################
  195. # ArchiveAllChats
  196. ############################
  197. @router.post("/archive/all", response_model=bool)
  198. async def archive_all_chats(user=Depends(get_verified_user)):
  199. return Chats.archive_all_chats_by_user_id(user.id)
  200. ############################
  201. # GetSharedChatById
  202. ############################
  203. @router.get("/share/{share_id}", response_model=Optional[ChatResponse])
  204. async def get_shared_chat_by_id(share_id: str, user=Depends(get_verified_user)):
  205. if user.role == "pending":
  206. raise HTTPException(
  207. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
  208. )
  209. if user.role == "user" or (user.role == "admin" and not ENABLE_ADMIN_CHAT_ACCESS):
  210. chat = Chats.get_chat_by_share_id(share_id)
  211. elif user.role == "admin" and ENABLE_ADMIN_CHAT_ACCESS:
  212. chat = Chats.get_chat_by_id(share_id)
  213. if chat:
  214. return ChatResponse(**chat.model_dump())
  215. else:
  216. raise HTTPException(
  217. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
  218. )
  219. ############################
  220. # GetChatsByTags
  221. ############################
  222. class TagForm(BaseModel):
  223. name: str
  224. class TagFilterForm(TagForm):
  225. skip: Optional[int] = 0
  226. limit: Optional[int] = 50
  227. @router.post("/tags", response_model=list[ChatTitleIdResponse])
  228. async def get_user_chat_list_by_tag_name(
  229. form_data: TagFilterForm, user=Depends(get_verified_user)
  230. ):
  231. chats = Chats.get_chat_list_by_user_id_and_tag_name(
  232. user.id, form_data.name, form_data.skip, form_data.limit
  233. )
  234. if len(chats) == 0:
  235. Tags.delete_tag_by_name_and_user_id(form_data.name, user.id)
  236. return chats
  237. ############################
  238. # GetChatById
  239. ############################
  240. @router.get("/{id}", response_model=Optional[ChatResponse])
  241. async def get_chat_by_id(id: str, user=Depends(get_verified_user)):
  242. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  243. if chat:
  244. return ChatResponse(**chat.model_dump())
  245. else:
  246. raise HTTPException(
  247. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
  248. )
  249. ############################
  250. # UpdateChatById
  251. ############################
  252. @router.post("/{id}", response_model=Optional[ChatResponse])
  253. async def update_chat_by_id(
  254. id: str, form_data: ChatForm, user=Depends(get_verified_user)
  255. ):
  256. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  257. if chat:
  258. updated_chat = {**chat.chat, **form_data.chat}
  259. chat = Chats.update_chat_by_id(id, updated_chat)
  260. return ChatResponse(**chat.model_dump())
  261. else:
  262. raise HTTPException(
  263. status_code=status.HTTP_401_UNAUTHORIZED,
  264. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  265. )
  266. ############################
  267. # DeleteChatById
  268. ############################
  269. @router.delete("/{id}", response_model=bool)
  270. async def delete_chat_by_id(request: Request, id: str, user=Depends(get_verified_user)):
  271. if user.role == "admin":
  272. chat = Chats.get_chat_by_id(id)
  273. for tag in chat.meta.get("tags", []):
  274. if Chats.count_chats_by_tag_name_and_user_id(tag, user.id) == 1:
  275. Tags.delete_tag_by_name_and_user_id(tag, user.id)
  276. result = Chats.delete_chat_by_id(id)
  277. return result
  278. else:
  279. if not request.app.state.config.USER_PERMISSIONS.get("chat", {}).get(
  280. "deletion", {}
  281. ):
  282. raise HTTPException(
  283. status_code=status.HTTP_401_UNAUTHORIZED,
  284. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  285. )
  286. chat = Chats.get_chat_by_id(id)
  287. for tag in chat.meta.get("tags", []):
  288. if Chats.count_chats_by_tag_name_and_user_id(tag, user.id) == 1:
  289. Tags.delete_tag_by_name_and_user_id(tag, user.id)
  290. result = Chats.delete_chat_by_id_and_user_id(id, user.id)
  291. return result
  292. ############################
  293. # GetPinnedStatusById
  294. ############################
  295. @router.get("/{id}/pinned", response_model=Optional[bool])
  296. async def get_pinned_status_by_id(id: str, user=Depends(get_verified_user)):
  297. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  298. if chat:
  299. return chat.pinned
  300. else:
  301. raise HTTPException(
  302. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT()
  303. )
  304. ############################
  305. # PinChatById
  306. ############################
  307. @router.post("/{id}/pin", response_model=Optional[ChatResponse])
  308. async def pin_chat_by_id(id: str, user=Depends(get_verified_user)):
  309. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  310. if chat:
  311. chat = Chats.toggle_chat_pinned_by_id(id)
  312. return chat
  313. else:
  314. raise HTTPException(
  315. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT()
  316. )
  317. ############################
  318. # CloneChat
  319. ############################
  320. @router.post("/{id}/clone", response_model=Optional[ChatResponse])
  321. async def clone_chat_by_id(id: str, user=Depends(get_verified_user)):
  322. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  323. if chat:
  324. updated_chat = {
  325. **chat.chat,
  326. "originalChatId": chat.id,
  327. "branchPointMessageId": chat.chat["history"]["currentId"],
  328. "title": f"Clone of {chat.title}",
  329. }
  330. chat = Chats.insert_new_chat(user.id, ChatForm(**{"chat": updated_chat}))
  331. return ChatResponse(**chat.model_dump())
  332. else:
  333. raise HTTPException(
  334. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT()
  335. )
  336. ############################
  337. # ArchiveChat
  338. ############################
  339. @router.post("/{id}/archive", response_model=Optional[ChatResponse])
  340. async def archive_chat_by_id(id: str, user=Depends(get_verified_user)):
  341. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  342. if chat:
  343. chat = Chats.toggle_chat_archive_by_id(id)
  344. # Delete tags if chat is archived
  345. if chat.archived:
  346. for tag_id in chat.meta.get("tags", []):
  347. if Chats.count_chats_by_tag_name_and_user_id(tag_id, user.id) == 0:
  348. log.debug(f"deleting tag: {tag_id}")
  349. Tags.delete_tag_by_name_and_user_id(tag_id, user.id)
  350. else:
  351. for tag_id in chat.meta.get("tags", []):
  352. tag = Tags.get_tag_by_name_and_user_id(tag_id, user.id)
  353. if tag is None:
  354. log.debug(f"inserting tag: {tag_id}")
  355. tag = Tags.insert_new_tag(tag_id, user.id)
  356. return ChatResponse(**chat.model_dump())
  357. else:
  358. raise HTTPException(
  359. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT()
  360. )
  361. ############################
  362. # ShareChatById
  363. ############################
  364. @router.post("/{id}/share", response_model=Optional[ChatResponse])
  365. async def share_chat_by_id(id: str, user=Depends(get_verified_user)):
  366. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  367. if chat:
  368. if chat.share_id:
  369. shared_chat = Chats.update_shared_chat_by_chat_id(chat.id)
  370. return ChatResponse(**shared_chat.model_dump())
  371. shared_chat = Chats.insert_shared_chat_by_chat_id(chat.id)
  372. if not shared_chat:
  373. raise HTTPException(
  374. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  375. detail=ERROR_MESSAGES.DEFAULT(),
  376. )
  377. return ChatResponse(**shared_chat.model_dump())
  378. else:
  379. raise HTTPException(
  380. status_code=status.HTTP_401_UNAUTHORIZED,
  381. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  382. )
  383. ############################
  384. # DeletedSharedChatById
  385. ############################
  386. @router.delete("/{id}/share", response_model=Optional[bool])
  387. async def delete_shared_chat_by_id(id: str, user=Depends(get_verified_user)):
  388. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  389. if chat:
  390. if not chat.share_id:
  391. return False
  392. result = Chats.delete_shared_chat_by_chat_id(id)
  393. update_result = Chats.update_chat_share_id_by_id(id, None)
  394. return result and update_result != None
  395. else:
  396. raise HTTPException(
  397. status_code=status.HTTP_401_UNAUTHORIZED,
  398. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  399. )
  400. ############################
  401. # UpdateChatFolderIdById
  402. ############################
  403. class ChatFolderIdForm(BaseModel):
  404. folder_id: Optional[str] = None
  405. @router.post("/{id}/folder", response_model=Optional[ChatResponse])
  406. async def update_chat_folder_id_by_id(
  407. id: str, form_data: ChatFolderIdForm, user=Depends(get_verified_user)
  408. ):
  409. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  410. if chat:
  411. chat = Chats.update_chat_folder_id_by_id_and_user_id(
  412. id, user.id, form_data.folder_id
  413. )
  414. return ChatResponse(**chat.model_dump())
  415. else:
  416. raise HTTPException(
  417. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT()
  418. )
  419. ############################
  420. # GetChatTagsById
  421. ############################
  422. @router.get("/{id}/tags", response_model=list[TagModel])
  423. async def get_chat_tags_by_id(id: str, user=Depends(get_verified_user)):
  424. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  425. if chat:
  426. tags = chat.meta.get("tags", [])
  427. return Tags.get_tags_by_ids_and_user_id(tags, user.id)
  428. else:
  429. raise HTTPException(
  430. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
  431. )
  432. ############################
  433. # AddChatTagById
  434. ############################
  435. @router.post("/{id}/tags", response_model=list[TagModel])
  436. async def add_tag_by_id_and_tag_name(
  437. id: str, form_data: TagForm, user=Depends(get_verified_user)
  438. ):
  439. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  440. if chat:
  441. tags = chat.meta.get("tags", [])
  442. tag_id = form_data.name.replace(" ", "_").lower()
  443. print(tags, tag_id)
  444. if tag_id not in tags:
  445. Chats.add_chat_tag_by_id_and_user_id_and_tag_name(
  446. id, user.id, form_data.name
  447. )
  448. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  449. tags = chat.meta.get("tags", [])
  450. return Tags.get_tags_by_ids_and_user_id(tags, user.id)
  451. else:
  452. raise HTTPException(
  453. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT()
  454. )
  455. ############################
  456. # DeleteChatTagById
  457. ############################
  458. @router.delete("/{id}/tags", response_model=list[TagModel])
  459. async def delete_tag_by_id_and_tag_name(
  460. id: str, form_data: TagForm, user=Depends(get_verified_user)
  461. ):
  462. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  463. if chat:
  464. Chats.delete_tag_by_id_and_user_id_and_tag_name(id, user.id, form_data.name)
  465. if Chats.count_chats_by_tag_name_and_user_id(form_data.name, user.id) == 0:
  466. Tags.delete_tag_by_name_and_user_id(form_data.name, user.id)
  467. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  468. tags = chat.meta.get("tags", [])
  469. return Tags.get_tags_by_ids_and_user_id(tags, user.id)
  470. else:
  471. raise HTTPException(
  472. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
  473. )
  474. ############################
  475. # DeleteAllChatTagsById
  476. ############################
  477. @router.delete("/{id}/tags/all", response_model=Optional[bool])
  478. async def delete_all_chat_tags_by_id(id: str, user=Depends(get_verified_user)):
  479. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  480. if chat:
  481. Chats.delete_all_tags_by_id_and_user_id(id, user.id)
  482. for tag in chat.meta.get("tags", []):
  483. if Chats.count_chats_by_tag_name_and_user_id(tag, user.id) == 0:
  484. Tags.delete_tag_by_name_and_user_id(tag, user.id)
  485. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  486. tags = chat.meta.get("tags", [])
  487. return Tags.get_tags_by_ids_and_user_id(tags, user.id)
  488. else:
  489. raise HTTPException(
  490. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
  491. )