functions.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. from fastapi import Depends, FastAPI, HTTPException, status, Request
  2. from datetime import datetime, timedelta
  3. from typing import List, Union, Optional
  4. from fastapi import APIRouter
  5. from pydantic import BaseModel
  6. import json
  7. from apps.webui.models.functions import (
  8. Functions,
  9. FunctionForm,
  10. FunctionModel,
  11. FunctionResponse,
  12. )
  13. from apps.webui.utils import load_function_module_by_id
  14. from utils.utils import get_verified_user, get_admin_user
  15. from constants import ERROR_MESSAGES
  16. from importlib import util
  17. import os
  18. from pathlib import Path
  19. from config import DATA_DIR, CACHE_DIR, FUNCTIONS_DIR
  20. router = APIRouter()
  21. ############################
  22. # GetFunctions
  23. ############################
  24. @router.get("/", response_model=List[FunctionResponse])
  25. async def get_functions(user=Depends(get_verified_user)):
  26. return Functions.get_functions()
  27. ############################
  28. # ExportFunctions
  29. ############################
  30. @router.get("/export", response_model=List[FunctionModel])
  31. async def get_functions(user=Depends(get_admin_user)):
  32. return Functions.get_functions()
  33. ############################
  34. # CreateNewFunction
  35. ############################
  36. @router.post("/create", response_model=Optional[FunctionResponse])
  37. async def create_new_function(
  38. request: Request, form_data: FunctionForm, user=Depends(get_admin_user)
  39. ):
  40. if not form_data.id.isidentifier():
  41. raise HTTPException(
  42. status_code=status.HTTP_400_BAD_REQUEST,
  43. detail="Only alphanumeric characters and underscores are allowed in the id",
  44. )
  45. form_data.id = form_data.id.lower()
  46. function = Functions.get_function_by_id(form_data.id)
  47. if function == None:
  48. function_path = os.path.join(FUNCTIONS_DIR, f"{form_data.id}.py")
  49. try:
  50. with open(function_path, "w") as function_file:
  51. function_file.write(form_data.content)
  52. function_module, function_type = load_function_module_by_id(form_data.id)
  53. FUNCTIONS = request.app.state.FUNCTIONS
  54. FUNCTIONS[form_data.id] = function_module
  55. function = Functions.insert_new_function(user.id, function_type, form_data)
  56. function_cache_dir = Path(CACHE_DIR) / "functions" / form_data.id
  57. function_cache_dir.mkdir(parents=True, exist_ok=True)
  58. if function:
  59. return function
  60. else:
  61. raise HTTPException(
  62. status_code=status.HTTP_400_BAD_REQUEST,
  63. detail=ERROR_MESSAGES.DEFAULT("Error creating function"),
  64. )
  65. except Exception as e:
  66. print(e)
  67. raise HTTPException(
  68. status_code=status.HTTP_400_BAD_REQUEST,
  69. detail=ERROR_MESSAGES.DEFAULT(e),
  70. )
  71. else:
  72. raise HTTPException(
  73. status_code=status.HTTP_400_BAD_REQUEST,
  74. detail=ERROR_MESSAGES.ID_TAKEN,
  75. )
  76. ############################
  77. # GetFunctionById
  78. ############################
  79. @router.get("/id/{id}", response_model=Optional[FunctionModel])
  80. async def get_function_by_id(id: str, user=Depends(get_admin_user)):
  81. function = Functions.get_function_by_id(id)
  82. if function:
  83. return function
  84. else:
  85. raise HTTPException(
  86. status_code=status.HTTP_401_UNAUTHORIZED,
  87. detail=ERROR_MESSAGES.NOT_FOUND,
  88. )
  89. ############################
  90. # GetFunctionValves
  91. ############################
  92. @router.get("/id/{id}/valves", response_model=Optional[dict])
  93. async def get_function_valves_by_id(id: str, user=Depends(get_admin_user)):
  94. function = Functions.get_function_by_id(id)
  95. if function:
  96. try:
  97. valves = Functions.get_function_valves_by_id(id)
  98. return valves
  99. except Exception as e:
  100. raise HTTPException(
  101. status_code=status.HTTP_400_BAD_REQUEST,
  102. detail=ERROR_MESSAGES.DEFAULT(e),
  103. )
  104. else:
  105. raise HTTPException(
  106. status_code=status.HTTP_401_UNAUTHORIZED,
  107. detail=ERROR_MESSAGES.NOT_FOUND,
  108. )
  109. ############################
  110. # GetFunctionValvesSpec
  111. ############################
  112. @router.get("/id/{id}/valves/spec", response_model=Optional[dict])
  113. async def get_function_valves_spec_by_id(
  114. request: Request, id: str, user=Depends(get_admin_user)
  115. ):
  116. function = Functions.get_function_by_id(id)
  117. if function:
  118. if id in request.app.state.FUNCTIONS:
  119. function_module = request.app.state.FUNCTIONS[id]
  120. else:
  121. function_module, function_type = load_function_module_by_id(id)
  122. request.app.state.FUNCTIONS[id] = function_module
  123. if hasattr(function_module, "Valves"):
  124. Valves = function_module.Valves
  125. return Valves.schema()
  126. return None
  127. else:
  128. raise HTTPException(
  129. status_code=status.HTTP_401_UNAUTHORIZED,
  130. detail=ERROR_MESSAGES.NOT_FOUND,
  131. )
  132. ############################
  133. # UpdateFunctionValves
  134. ############################
  135. @router.post("/id/{id}/valves/update", response_model=Optional[dict])
  136. async def update_function_valves_by_id(
  137. request: Request, id: str, form_data: dict, user=Depends(get_admin_user)
  138. ):
  139. function = Functions.get_function_by_id(id)
  140. if function:
  141. if id in request.app.state.FUNCTIONS:
  142. function_module = request.app.state.FUNCTIONS[id]
  143. else:
  144. function_module, function_type = load_function_module_by_id(id)
  145. request.app.state.FUNCTIONS[id] = function_module
  146. if hasattr(function_module, "Valves"):
  147. Valves = function_module.Valves
  148. try:
  149. form_data = {k: v for k, v in form_data.items() if v is not None}
  150. valves = Valves(**form_data)
  151. Functions.update_function_valves_by_id(id, valves.model_dump())
  152. return valves.model_dump()
  153. except Exception as e:
  154. print(e)
  155. raise HTTPException(
  156. status_code=status.HTTP_400_BAD_REQUEST,
  157. detail=ERROR_MESSAGES.DEFAULT(e),
  158. )
  159. else:
  160. raise HTTPException(
  161. status_code=status.HTTP_401_UNAUTHORIZED,
  162. detail=ERROR_MESSAGES.NOT_FOUND,
  163. )
  164. else:
  165. raise HTTPException(
  166. status_code=status.HTTP_401_UNAUTHORIZED,
  167. detail=ERROR_MESSAGES.NOT_FOUND,
  168. )
  169. ############################
  170. # FunctionUserValves
  171. ############################
  172. @router.get("/id/{id}/valves/user", response_model=Optional[dict])
  173. async def get_function_user_valves_by_id(id: str, user=Depends(get_verified_user)):
  174. function = Functions.get_function_by_id(id)
  175. if function:
  176. try:
  177. user_valves = Functions.get_user_valves_by_id_and_user_id(id, user.id)
  178. return user_valves
  179. except Exception as e:
  180. raise HTTPException(
  181. status_code=status.HTTP_400_BAD_REQUEST,
  182. detail=ERROR_MESSAGES.DEFAULT(e),
  183. )
  184. else:
  185. raise HTTPException(
  186. status_code=status.HTTP_401_UNAUTHORIZED,
  187. detail=ERROR_MESSAGES.NOT_FOUND,
  188. )
  189. @router.get("/id/{id}/valves/user/spec", response_model=Optional[dict])
  190. async def get_function_user_valves_spec_by_id(
  191. request: Request, id: str, user=Depends(get_verified_user)
  192. ):
  193. function = Functions.get_function_by_id(id)
  194. if function:
  195. if id in request.app.state.FUNCTIONS:
  196. function_module = request.app.state.FUNCTIONS[id]
  197. else:
  198. function_module, function_type = load_function_module_by_id(id)
  199. request.app.state.FUNCTIONS[id] = function_module
  200. if hasattr(function_module, "UserValves"):
  201. UserValves = function_module.UserValves
  202. return UserValves.schema()
  203. return None
  204. else:
  205. raise HTTPException(
  206. status_code=status.HTTP_401_UNAUTHORIZED,
  207. detail=ERROR_MESSAGES.NOT_FOUND,
  208. )
  209. @router.post("/id/{id}/valves/user/update", response_model=Optional[dict])
  210. async def update_function_user_valves_by_id(
  211. request: Request, id: str, form_data: dict, user=Depends(get_verified_user)
  212. ):
  213. function = Functions.get_function_by_id(id)
  214. if function:
  215. if id in request.app.state.FUNCTIONS:
  216. function_module = request.app.state.FUNCTIONS[id]
  217. else:
  218. function_module, function_type = load_function_module_by_id(id)
  219. request.app.state.FUNCTIONS[id] = function_module
  220. if hasattr(function_module, "UserValves"):
  221. UserValves = function_module.UserValves
  222. try:
  223. form_data = {k: v for k, v in form_data.items() if v is not None}
  224. user_valves = UserValves(**form_data)
  225. Functions.update_user_valves_by_id_and_user_id(
  226. id, user.id, user_valves.model_dump()
  227. )
  228. return user_valves.model_dump()
  229. except Exception as e:
  230. print(e)
  231. raise HTTPException(
  232. status_code=status.HTTP_400_BAD_REQUEST,
  233. detail=ERROR_MESSAGES.DEFAULT(e),
  234. )
  235. else:
  236. raise HTTPException(
  237. status_code=status.HTTP_401_UNAUTHORIZED,
  238. detail=ERROR_MESSAGES.NOT_FOUND,
  239. )
  240. else:
  241. raise HTTPException(
  242. status_code=status.HTTP_401_UNAUTHORIZED,
  243. detail=ERROR_MESSAGES.NOT_FOUND,
  244. )
  245. ############################
  246. # ToggleFunctionById
  247. ############################
  248. @router.post("/id/{id}/toggle", response_model=Optional[FunctionModel])
  249. async def toggle_function_by_id(id: str, user=Depends(get_admin_user)):
  250. function = Functions.get_function_by_id(id)
  251. if function:
  252. function = Functions.update_function_by_id(
  253. id, {"is_active": not function.is_active}
  254. )
  255. if function:
  256. return function
  257. else:
  258. raise HTTPException(
  259. status_code=status.HTTP_400_BAD_REQUEST,
  260. detail=ERROR_MESSAGES.DEFAULT("Error updating function"),
  261. )
  262. else:
  263. raise HTTPException(
  264. status_code=status.HTTP_401_UNAUTHORIZED,
  265. detail=ERROR_MESSAGES.NOT_FOUND,
  266. )
  267. ############################
  268. # UpdateFunctionById
  269. ############################
  270. @router.post("/id/{id}/update", response_model=Optional[FunctionModel])
  271. async def update_function_by_id(
  272. request: Request, id: str, form_data: FunctionForm, user=Depends(get_admin_user)
  273. ):
  274. function_path = os.path.join(FUNCTIONS_DIR, f"{id}.py")
  275. try:
  276. with open(function_path, "w") as function_file:
  277. function_file.write(form_data.content)
  278. function_module, function_type = load_function_module_by_id(id)
  279. FUNCTIONS = request.app.state.FUNCTIONS
  280. FUNCTIONS[id] = function_module
  281. updated = {**form_data.model_dump(exclude={"id"}), "type": function_type}
  282. print(updated)
  283. function = Functions.update_function_by_id(id, updated)
  284. if function:
  285. return function
  286. else:
  287. raise HTTPException(
  288. status_code=status.HTTP_400_BAD_REQUEST,
  289. detail=ERROR_MESSAGES.DEFAULT("Error updating function"),
  290. )
  291. except Exception as e:
  292. raise HTTPException(
  293. status_code=status.HTTP_400_BAD_REQUEST,
  294. detail=ERROR_MESSAGES.DEFAULT(e),
  295. )
  296. ############################
  297. # DeleteFunctionById
  298. ############################
  299. @router.delete("/id/{id}/delete", response_model=bool)
  300. async def delete_function_by_id(
  301. request: Request, id: str, user=Depends(get_admin_user)
  302. ):
  303. result = Functions.delete_function_by_id(id)
  304. if result:
  305. FUNCTIONS = request.app.state.FUNCTIONS
  306. if id in FUNCTIONS:
  307. del FUNCTIONS[id]
  308. # delete the function file
  309. function_path = os.path.join(FUNCTIONS_DIR, f"{id}.py")
  310. os.remove(function_path)
  311. return result