chats.py 13 KB

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