chats.py 23 KB

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