chats.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  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. )
  312. if event_emitter:
  313. event_emitter(
  314. {
  315. "type": "chat:message",
  316. "data": {
  317. "chat_id": id,
  318. "message_id": message_id,
  319. "content": form_data.content,
  320. },
  321. }
  322. )
  323. return ChatResponse(**chat.model_dump())
  324. ############################
  325. # DeleteChatById
  326. ############################
  327. @router.delete("/{id}", response_model=bool)
  328. async def delete_chat_by_id(request: Request, id: str, user=Depends(get_verified_user)):
  329. if user.role == "admin":
  330. chat = Chats.get_chat_by_id(id)
  331. for tag in chat.meta.get("tags", []):
  332. if Chats.count_chats_by_tag_name_and_user_id(tag, user.id) == 1:
  333. Tags.delete_tag_by_name_and_user_id(tag, user.id)
  334. result = Chats.delete_chat_by_id(id)
  335. return result
  336. else:
  337. if not has_permission(
  338. user.id, "chat.delete", request.app.state.config.USER_PERMISSIONS
  339. ):
  340. raise HTTPException(
  341. status_code=status.HTTP_401_UNAUTHORIZED,
  342. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  343. )
  344. chat = Chats.get_chat_by_id(id)
  345. for tag in chat.meta.get("tags", []):
  346. if Chats.count_chats_by_tag_name_and_user_id(tag, user.id) == 1:
  347. Tags.delete_tag_by_name_and_user_id(tag, user.id)
  348. result = Chats.delete_chat_by_id_and_user_id(id, user.id)
  349. return result
  350. ############################
  351. # GetPinnedStatusById
  352. ############################
  353. @router.get("/{id}/pinned", response_model=Optional[bool])
  354. async def get_pinned_status_by_id(id: str, user=Depends(get_verified_user)):
  355. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  356. if chat:
  357. return chat.pinned
  358. else:
  359. raise HTTPException(
  360. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT()
  361. )
  362. ############################
  363. # PinChatById
  364. ############################
  365. @router.post("/{id}/pin", response_model=Optional[ChatResponse])
  366. async def pin_chat_by_id(id: str, user=Depends(get_verified_user)):
  367. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  368. if chat:
  369. chat = Chats.toggle_chat_pinned_by_id(id)
  370. return chat
  371. else:
  372. raise HTTPException(
  373. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT()
  374. )
  375. ############################
  376. # CloneChat
  377. ############################
  378. class CloneForm(BaseModel):
  379. title: Optional[str] = None
  380. @router.post("/{id}/clone", response_model=Optional[ChatResponse])
  381. async def clone_chat_by_id(
  382. form_data: CloneForm, id: str, user=Depends(get_verified_user)
  383. ):
  384. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  385. if chat:
  386. updated_chat = {
  387. **chat.chat,
  388. "originalChatId": chat.id,
  389. "branchPointMessageId": chat.chat["history"]["currentId"],
  390. "title": form_data.title if form_data.title else f"Clone of {chat.title}",
  391. }
  392. chat = Chats.insert_new_chat(user.id, ChatForm(**{"chat": updated_chat}))
  393. return ChatResponse(**chat.model_dump())
  394. else:
  395. raise HTTPException(
  396. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT()
  397. )
  398. ############################
  399. # CloneSharedChatById
  400. ############################
  401. @router.post("/{id}/clone/shared", response_model=Optional[ChatResponse])
  402. async def clone_shared_chat_by_id(id: str, user=Depends(get_verified_user)):
  403. chat = Chats.get_chat_by_share_id(id)
  404. if chat:
  405. updated_chat = {
  406. **chat.chat,
  407. "originalChatId": chat.id,
  408. "branchPointMessageId": chat.chat["history"]["currentId"],
  409. "title": f"Clone of {chat.title}",
  410. }
  411. chat = Chats.insert_new_chat(user.id, ChatForm(**{"chat": updated_chat}))
  412. return ChatResponse(**chat.model_dump())
  413. else:
  414. raise HTTPException(
  415. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT()
  416. )
  417. ############################
  418. # ArchiveChat
  419. ############################
  420. @router.post("/{id}/archive", response_model=Optional[ChatResponse])
  421. async def archive_chat_by_id(id: str, user=Depends(get_verified_user)):
  422. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  423. if chat:
  424. chat = Chats.toggle_chat_archive_by_id(id)
  425. # Delete tags if chat is archived
  426. if chat.archived:
  427. for tag_id in chat.meta.get("tags", []):
  428. if Chats.count_chats_by_tag_name_and_user_id(tag_id, user.id) == 0:
  429. log.debug(f"deleting tag: {tag_id}")
  430. Tags.delete_tag_by_name_and_user_id(tag_id, user.id)
  431. else:
  432. for tag_id in chat.meta.get("tags", []):
  433. tag = Tags.get_tag_by_name_and_user_id(tag_id, user.id)
  434. if tag is None:
  435. log.debug(f"inserting tag: {tag_id}")
  436. tag = Tags.insert_new_tag(tag_id, user.id)
  437. return ChatResponse(**chat.model_dump())
  438. else:
  439. raise HTTPException(
  440. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT()
  441. )
  442. ############################
  443. # ShareChatById
  444. ############################
  445. @router.post("/{id}/share", response_model=Optional[ChatResponse])
  446. async def share_chat_by_id(id: str, user=Depends(get_verified_user)):
  447. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  448. if chat:
  449. if chat.share_id:
  450. shared_chat = Chats.update_shared_chat_by_chat_id(chat.id)
  451. return ChatResponse(**shared_chat.model_dump())
  452. shared_chat = Chats.insert_shared_chat_by_chat_id(chat.id)
  453. if not shared_chat:
  454. raise HTTPException(
  455. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  456. detail=ERROR_MESSAGES.DEFAULT(),
  457. )
  458. return ChatResponse(**shared_chat.model_dump())
  459. else:
  460. raise HTTPException(
  461. status_code=status.HTTP_401_UNAUTHORIZED,
  462. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  463. )
  464. ############################
  465. # DeletedSharedChatById
  466. ############################
  467. @router.delete("/{id}/share", response_model=Optional[bool])
  468. async def delete_shared_chat_by_id(id: str, user=Depends(get_verified_user)):
  469. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  470. if chat:
  471. if not chat.share_id:
  472. return False
  473. result = Chats.delete_shared_chat_by_chat_id(id)
  474. update_result = Chats.update_chat_share_id_by_id(id, None)
  475. return result and update_result != None
  476. else:
  477. raise HTTPException(
  478. status_code=status.HTTP_401_UNAUTHORIZED,
  479. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  480. )
  481. ############################
  482. # UpdateChatFolderIdById
  483. ############################
  484. class ChatFolderIdForm(BaseModel):
  485. folder_id: Optional[str] = None
  486. @router.post("/{id}/folder", response_model=Optional[ChatResponse])
  487. async def update_chat_folder_id_by_id(
  488. id: str, form_data: ChatFolderIdForm, user=Depends(get_verified_user)
  489. ):
  490. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  491. if chat:
  492. chat = Chats.update_chat_folder_id_by_id_and_user_id(
  493. id, user.id, form_data.folder_id
  494. )
  495. return ChatResponse(**chat.model_dump())
  496. else:
  497. raise HTTPException(
  498. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT()
  499. )
  500. ############################
  501. # GetChatTagsById
  502. ############################
  503. @router.get("/{id}/tags", response_model=list[TagModel])
  504. async def get_chat_tags_by_id(id: str, user=Depends(get_verified_user)):
  505. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  506. if chat:
  507. tags = chat.meta.get("tags", [])
  508. return Tags.get_tags_by_ids_and_user_id(tags, user.id)
  509. else:
  510. raise HTTPException(
  511. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
  512. )
  513. ############################
  514. # AddChatTagById
  515. ############################
  516. @router.post("/{id}/tags", response_model=list[TagModel])
  517. async def add_tag_by_id_and_tag_name(
  518. id: str, form_data: TagForm, user=Depends(get_verified_user)
  519. ):
  520. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  521. if chat:
  522. tags = chat.meta.get("tags", [])
  523. tag_id = form_data.name.replace(" ", "_").lower()
  524. if tag_id == "none":
  525. raise HTTPException(
  526. status_code=status.HTTP_400_BAD_REQUEST,
  527. detail=ERROR_MESSAGES.DEFAULT("Tag name cannot be 'None'"),
  528. )
  529. if tag_id not in tags:
  530. Chats.add_chat_tag_by_id_and_user_id_and_tag_name(
  531. id, user.id, form_data.name
  532. )
  533. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  534. tags = chat.meta.get("tags", [])
  535. return Tags.get_tags_by_ids_and_user_id(tags, user.id)
  536. else:
  537. raise HTTPException(
  538. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT()
  539. )
  540. ############################
  541. # DeleteChatTagById
  542. ############################
  543. @router.delete("/{id}/tags", response_model=list[TagModel])
  544. async def delete_tag_by_id_and_tag_name(
  545. id: str, form_data: TagForm, user=Depends(get_verified_user)
  546. ):
  547. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  548. if chat:
  549. Chats.delete_tag_by_id_and_user_id_and_tag_name(id, user.id, form_data.name)
  550. if Chats.count_chats_by_tag_name_and_user_id(form_data.name, user.id) == 0:
  551. Tags.delete_tag_by_name_and_user_id(form_data.name, user.id)
  552. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  553. tags = chat.meta.get("tags", [])
  554. return Tags.get_tags_by_ids_and_user_id(tags, user.id)
  555. else:
  556. raise HTTPException(
  557. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
  558. )
  559. ############################
  560. # DeleteAllTagsById
  561. ############################
  562. @router.delete("/{id}/tags/all", response_model=Optional[bool])
  563. async def delete_all_tags_by_id(id: str, user=Depends(get_verified_user)):
  564. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  565. if chat:
  566. Chats.delete_all_tags_by_id_and_user_id(id, user.id)
  567. for tag in chat.meta.get("tags", []):
  568. if Chats.count_chats_by_tag_name_and_user_id(tag, user.id) == 0:
  569. Tags.delete_tag_by_name_and_user_id(tag, user.id)
  570. return True
  571. else:
  572. raise HTTPException(
  573. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
  574. )