chats.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. from fastapi import Depends, Request, HTTPException, status
  2. from datetime import datetime, timedelta
  3. from typing import List, Union, Optional
  4. from utils.utils import get_current_user, get_admin_user
  5. from fastapi import APIRouter
  6. from pydantic import BaseModel
  7. import json
  8. import logging
  9. from apps.webui.models.users import Users
  10. from apps.webui.models.chats import (
  11. ChatModel,
  12. ChatResponse,
  13. ChatTitleForm,
  14. ChatForm,
  15. ChatTitleIdResponse,
  16. Chats,
  17. )
  18. from apps.webui.models.tags import (
  19. TagModel,
  20. ChatIdTagModel,
  21. ChatIdTagForm,
  22. ChatTagsResponse,
  23. Tags,
  24. )
  25. from constants import ERROR_MESSAGES
  26. from config import SRC_LOG_LEVELS, ENABLE_ADMIN_EXPORT
  27. log = logging.getLogger(__name__)
  28. log.setLevel(SRC_LOG_LEVELS["MODELS"])
  29. router = APIRouter()
  30. ############################
  31. # GetChatList
  32. ############################
  33. @router.get("/", response_model=List[ChatTitleIdResponse])
  34. @router.get("/list", response_model=List[ChatTitleIdResponse])
  35. async def get_session_user_chat_list(
  36. user=Depends(get_current_user), skip: int = 0, limit: int = 50
  37. ):
  38. return Chats.get_chat_list_by_user_id(user.id, skip, limit)
  39. ############################
  40. # DeleteAllChats
  41. ############################
  42. @router.delete("/", response_model=bool)
  43. async def delete_all_user_chats(request: Request, user=Depends(get_current_user)):
  44. if (
  45. user.role == "user"
  46. and not request.app.state.config.USER_PERMISSIONS["chat"]["deletion"]
  47. ):
  48. raise HTTPException(
  49. status_code=status.HTTP_401_UNAUTHORIZED,
  50. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  51. )
  52. result = Chats.delete_chats_by_user_id(user.id)
  53. return result
  54. ############################
  55. # GetUserChatList
  56. ############################
  57. @router.get("/list/user/{user_id}", response_model=List[ChatTitleIdResponse])
  58. async def get_user_chat_list_by_user_id(
  59. user_id: str, user=Depends(get_admin_user), skip: int = 0, limit: int = 50
  60. ):
  61. return Chats.get_chat_list_by_user_id(
  62. user_id, include_archived=True, skip=skip, limit=limit
  63. )
  64. ############################
  65. # CreateNewChat
  66. ############################
  67. @router.post("/new", response_model=Optional[ChatResponse])
  68. async def create_new_chat(form_data: ChatForm, user=Depends(get_current_user)):
  69. try:
  70. chat = Chats.insert_new_chat(user.id, form_data)
  71. return ChatResponse(**{**chat.model_dump(), "chat": json.loads(chat.chat)})
  72. except Exception as e:
  73. log.exception(e)
  74. raise HTTPException(
  75. status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT()
  76. )
  77. ############################
  78. # GetChats
  79. ############################
  80. @router.get("/all", response_model=List[ChatResponse])
  81. async def get_user_chats(user=Depends(get_current_user)):
  82. return [
  83. ChatResponse(**{**chat.model_dump(), "chat": json.loads(chat.chat)})
  84. for chat in Chats.get_chats_by_user_id(user.id)
  85. ]
  86. ############################
  87. # GetArchivedChats
  88. ############################
  89. @router.get("/all/archived", response_model=List[ChatResponse])
  90. async def get_user_chats(user=Depends(get_current_user)):
  91. return [
  92. ChatResponse(**{**chat.model_dump(), "chat": json.loads(chat.chat)})
  93. for chat in Chats.get_archived_chats_by_user_id(user.id)
  94. ]
  95. ############################
  96. # GetAllChatsInDB
  97. ############################
  98. @router.get("/all/db", response_model=List[ChatResponse])
  99. async def get_all_user_chats_in_db(user=Depends(get_admin_user)):
  100. if not ENABLE_ADMIN_EXPORT:
  101. raise HTTPException(
  102. status_code=status.HTTP_401_UNAUTHORIZED,
  103. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  104. )
  105. return [
  106. ChatResponse(**{**chat.model_dump(), "chat": json.loads(chat.chat)})
  107. for chat in Chats.get_chats()
  108. ]
  109. ############################
  110. # GetArchivedChats
  111. ############################
  112. @router.get("/archived", response_model=List[ChatTitleIdResponse])
  113. async def get_archived_session_user_chat_list(
  114. user=Depends(get_current_user), skip: int = 0, limit: int = 50
  115. ):
  116. return Chats.get_archived_chat_list_by_user_id(user.id, skip, limit)
  117. ############################
  118. # ArchiveAllChats
  119. ############################
  120. @router.post("/archive/all", response_model=List[ChatTitleIdResponse])
  121. async def archive_all_chats(user=Depends(get_current_user)):
  122. return Chats.archive_all_chats_by_user_id(user.id)
  123. ############################
  124. # GetSharedChatById
  125. ############################
  126. @router.get("/share/{share_id}", response_model=Optional[ChatResponse])
  127. async def get_shared_chat_by_id(share_id: str, user=Depends(get_current_user)):
  128. if user.role == "pending":
  129. raise HTTPException(
  130. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
  131. )
  132. if user.role == "user":
  133. chat = Chats.get_chat_by_share_id(share_id)
  134. elif user.role == "admin":
  135. chat = Chats.get_chat_by_id(share_id)
  136. if chat:
  137. return ChatResponse(**{**chat.model_dump(), "chat": json.loads(chat.chat)})
  138. else:
  139. raise HTTPException(
  140. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
  141. )
  142. ############################
  143. # GetChatsByTags
  144. ############################
  145. class TagNameForm(BaseModel):
  146. name: str
  147. skip: Optional[int] = 0
  148. limit: Optional[int] = 50
  149. @router.post("/tags", response_model=List[ChatTitleIdResponse])
  150. async def get_user_chat_list_by_tag_name(
  151. form_data: TagNameForm, user=Depends(get_current_user)
  152. ):
  153. print(form_data)
  154. chat_ids = [
  155. chat_id_tag.chat_id
  156. for chat_id_tag in Tags.get_chat_ids_by_tag_name_and_user_id(
  157. form_data.name, user.id
  158. )
  159. ]
  160. chats = Chats.get_chat_list_by_chat_ids(chat_ids, form_data.skip, form_data.limit)
  161. if len(chats) == 0:
  162. Tags.delete_tag_by_tag_name_and_user_id(form_data.name, user.id)
  163. return chats
  164. ############################
  165. # GetAllTags
  166. ############################
  167. @router.get("/tags/all", response_model=List[TagModel])
  168. async def get_all_tags(user=Depends(get_current_user)):
  169. try:
  170. tags = Tags.get_tags_by_user_id(user.id)
  171. return tags
  172. except Exception as e:
  173. log.exception(e)
  174. raise HTTPException(
  175. status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT()
  176. )
  177. ############################
  178. # GetChatById
  179. ############################
  180. @router.get("/{id}", response_model=Optional[ChatResponse])
  181. async def get_chat_by_id(id: str, user=Depends(get_current_user)):
  182. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  183. if chat:
  184. return ChatResponse(**{**chat.model_dump(), "chat": json.loads(chat.chat)})
  185. else:
  186. raise HTTPException(
  187. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
  188. )
  189. ############################
  190. # UpdateChatById
  191. ############################
  192. @router.post("/{id}", response_model=Optional[ChatResponse])
  193. async def update_chat_by_id(
  194. id: str, form_data: ChatForm, user=Depends(get_current_user)
  195. ):
  196. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  197. if chat:
  198. updated_chat = {**json.loads(chat.chat), **form_data.chat}
  199. chat = Chats.update_chat_by_id(id, updated_chat)
  200. return ChatResponse(**{**chat.model_dump(), "chat": json.loads(chat.chat)})
  201. else:
  202. raise HTTPException(
  203. status_code=status.HTTP_401_UNAUTHORIZED,
  204. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  205. )
  206. ############################
  207. # DeleteChatById
  208. ############################
  209. @router.delete("/{id}", response_model=bool)
  210. async def delete_chat_by_id(request: Request, id: str, user=Depends(get_current_user)):
  211. if user.role == "admin":
  212. result = Chats.delete_chat_by_id(id)
  213. return result
  214. else:
  215. if not request.app.state.config.USER_PERMISSIONS["chat"]["deletion"]:
  216. raise HTTPException(
  217. status_code=status.HTTP_401_UNAUTHORIZED,
  218. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  219. )
  220. result = Chats.delete_chat_by_id_and_user_id(id, user.id)
  221. return result
  222. ############################
  223. # CloneChat
  224. ############################
  225. @router.get("/{id}/clone", response_model=Optional[ChatResponse])
  226. async def clone_chat_by_id(id: str, user=Depends(get_current_user)):
  227. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  228. if chat:
  229. chat_body = json.loads(chat.chat)
  230. updated_chat = {
  231. **chat_body,
  232. "originalChatId": chat.id,
  233. "branchPointMessageId": chat_body["history"]["currentId"],
  234. "title": f"Clone of {chat.title}",
  235. }
  236. chat = Chats.insert_new_chat(user.id, ChatForm(**{"chat": updated_chat}))
  237. return ChatResponse(**{**chat.model_dump(), "chat": json.loads(chat.chat)})
  238. else:
  239. raise HTTPException(
  240. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT()
  241. )
  242. ############################
  243. # ArchiveChat
  244. ############################
  245. @router.get("/{id}/archive", response_model=Optional[ChatResponse])
  246. async def archive_chat_by_id(id: str, user=Depends(get_current_user)):
  247. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  248. if chat:
  249. chat = Chats.toggle_chat_archive_by_id(id)
  250. return ChatResponse(**{**chat.model_dump(), "chat": json.loads(chat.chat)})
  251. else:
  252. raise HTTPException(
  253. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT()
  254. )
  255. ############################
  256. # ShareChatById
  257. ############################
  258. @router.post("/{id}/share", response_model=Optional[ChatResponse])
  259. async def share_chat_by_id(id: str, user=Depends(get_current_user)):
  260. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  261. if chat:
  262. if chat.share_id:
  263. shared_chat = Chats.update_shared_chat_by_chat_id(chat.id)
  264. return ChatResponse(
  265. **{**shared_chat.model_dump(), "chat": json.loads(shared_chat.chat)}
  266. )
  267. shared_chat = Chats.insert_shared_chat_by_chat_id(chat.id)
  268. if not shared_chat:
  269. raise HTTPException(
  270. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  271. detail=ERROR_MESSAGES.DEFAULT(),
  272. )
  273. return ChatResponse(
  274. **{**shared_chat.model_dump(), "chat": json.loads(shared_chat.chat)}
  275. )
  276. else:
  277. raise HTTPException(
  278. status_code=status.HTTP_401_UNAUTHORIZED,
  279. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  280. )
  281. ############################
  282. # DeletedSharedChatById
  283. ############################
  284. @router.delete("/{id}/share", response_model=Optional[bool])
  285. async def delete_shared_chat_by_id(id: str, user=Depends(get_current_user)):
  286. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  287. if chat:
  288. if not chat.share_id:
  289. return False
  290. result = Chats.delete_shared_chat_by_chat_id(id)
  291. update_result = Chats.update_chat_share_id_by_id(id, None)
  292. return result and update_result != None
  293. else:
  294. raise HTTPException(
  295. status_code=status.HTTP_401_UNAUTHORIZED,
  296. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  297. )
  298. ############################
  299. # GetChatTagsById
  300. ############################
  301. @router.get("/{id}/tags", response_model=List[TagModel])
  302. async def get_chat_tags_by_id(id: str, user=Depends(get_current_user)):
  303. tags = Tags.get_tags_by_chat_id_and_user_id(id, user.id)
  304. if tags != None:
  305. return tags
  306. else:
  307. raise HTTPException(
  308. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
  309. )
  310. ############################
  311. # AddChatTagById
  312. ############################
  313. @router.post("/{id}/tags", response_model=Optional[ChatIdTagModel])
  314. async def add_chat_tag_by_id(
  315. id: str, form_data: ChatIdTagForm, user=Depends(get_current_user)
  316. ):
  317. tags = Tags.get_tags_by_chat_id_and_user_id(id, user.id)
  318. if form_data.tag_name not in tags:
  319. tag = Tags.add_tag_to_chat(user.id, form_data)
  320. if tag:
  321. return tag
  322. else:
  323. raise HTTPException(
  324. status_code=status.HTTP_401_UNAUTHORIZED,
  325. detail=ERROR_MESSAGES.NOT_FOUND,
  326. )
  327. else:
  328. raise HTTPException(
  329. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT()
  330. )
  331. ############################
  332. # DeleteChatTagById
  333. ############################
  334. @router.delete("/{id}/tags", response_model=Optional[bool])
  335. async def delete_chat_tag_by_id(
  336. id: str, form_data: ChatIdTagForm, user=Depends(get_current_user)
  337. ):
  338. result = Tags.delete_tag_by_tag_name_and_chat_id_and_user_id(
  339. form_data.tag_name, id, user.id
  340. )
  341. if result:
  342. return result
  343. else:
  344. raise HTTPException(
  345. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
  346. )
  347. ############################
  348. # DeleteAllChatTagsById
  349. ############################
  350. @router.delete("/{id}/tags/all", response_model=Optional[bool])
  351. async def delete_all_chat_tags_by_id(id: str, user=Depends(get_current_user)):
  352. result = Tags.delete_tags_by_chat_id_and_user_id(id, user.id)
  353. if result:
  354. return result
  355. else:
  356. raise HTTPException(
  357. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
  358. )