chats.py 20 KB

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