chats.py 18 KB

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