functions.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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, frontmatter = load_function_module_by_id(
  53. form_data.id
  54. )
  55. form_data.meta.manifest = frontmatter
  56. FUNCTIONS = request.app.state.FUNCTIONS
  57. FUNCTIONS[form_data.id] = function_module
  58. function = Functions.insert_new_function(user.id, function_type, form_data)
  59. function_cache_dir = Path(CACHE_DIR) / "functions" / form_data.id
  60. function_cache_dir.mkdir(parents=True, exist_ok=True)
  61. if function:
  62. return function
  63. else:
  64. raise HTTPException(
  65. status_code=status.HTTP_400_BAD_REQUEST,
  66. detail=ERROR_MESSAGES.DEFAULT("Error creating function"),
  67. )
  68. except Exception as e:
  69. print(e)
  70. raise HTTPException(
  71. status_code=status.HTTP_400_BAD_REQUEST,
  72. detail=ERROR_MESSAGES.DEFAULT(e),
  73. )
  74. else:
  75. raise HTTPException(
  76. status_code=status.HTTP_400_BAD_REQUEST,
  77. detail=ERROR_MESSAGES.ID_TAKEN,
  78. )
  79. ############################
  80. # GetFunctionById
  81. ############################
  82. @router.get("/id/{id}", response_model=Optional[FunctionModel])
  83. async def get_function_by_id(id: str, user=Depends(get_admin_user)):
  84. function = Functions.get_function_by_id(id)
  85. if function:
  86. return function
  87. else:
  88. raise HTTPException(
  89. status_code=status.HTTP_401_UNAUTHORIZED,
  90. detail=ERROR_MESSAGES.NOT_FOUND,
  91. )
  92. ############################
  93. # ToggleFunctionById
  94. ############################
  95. @router.post("/id/{id}/toggle", response_model=Optional[FunctionModel])
  96. async def toggle_function_by_id(id: str, user=Depends(get_admin_user)):
  97. function = Functions.get_function_by_id(id)
  98. if function:
  99. function = Functions.update_function_by_id(
  100. id, {"is_active": not function.is_active}
  101. )
  102. if function:
  103. return function
  104. else:
  105. raise HTTPException(
  106. status_code=status.HTTP_400_BAD_REQUEST,
  107. detail=ERROR_MESSAGES.DEFAULT("Error updating function"),
  108. )
  109. else:
  110. raise HTTPException(
  111. status_code=status.HTTP_401_UNAUTHORIZED,
  112. detail=ERROR_MESSAGES.NOT_FOUND,
  113. )
  114. ############################
  115. # ToggleGlobalById
  116. ############################
  117. @router.post("/id/{id}/toggle/global", response_model=Optional[FunctionModel])
  118. async def toggle_global_by_id(id: str, user=Depends(get_admin_user)):
  119. function = Functions.get_function_by_id(id)
  120. if function:
  121. function = Functions.update_function_by_id(
  122. id, {"is_global": not function.is_global}
  123. )
  124. if function:
  125. return function
  126. else:
  127. raise HTTPException(
  128. status_code=status.HTTP_400_BAD_REQUEST,
  129. detail=ERROR_MESSAGES.DEFAULT("Error updating function"),
  130. )
  131. else:
  132. raise HTTPException(
  133. status_code=status.HTTP_401_UNAUTHORIZED,
  134. detail=ERROR_MESSAGES.NOT_FOUND,
  135. )
  136. ############################
  137. # UpdateFunctionById
  138. ############################
  139. @router.post("/id/{id}/update", response_model=Optional[FunctionModel])
  140. async def update_function_by_id(
  141. request: Request, id: str, form_data: FunctionForm, user=Depends(get_admin_user)
  142. ):
  143. function_path = os.path.join(FUNCTIONS_DIR, f"{id}.py")
  144. try:
  145. with open(function_path, "w") as function_file:
  146. function_file.write(form_data.content)
  147. function_module, function_type, frontmatter = load_function_module_by_id(id)
  148. form_data.meta.manifest = frontmatter
  149. FUNCTIONS = request.app.state.FUNCTIONS
  150. FUNCTIONS[id] = function_module
  151. updated = {**form_data.model_dump(exclude={"id"}), "type": function_type}
  152. print(updated)
  153. function = Functions.update_function_by_id(id, updated)
  154. if function:
  155. return function
  156. else:
  157. raise HTTPException(
  158. status_code=status.HTTP_400_BAD_REQUEST,
  159. detail=ERROR_MESSAGES.DEFAULT("Error updating function"),
  160. )
  161. except Exception as e:
  162. raise HTTPException(
  163. status_code=status.HTTP_400_BAD_REQUEST,
  164. detail=ERROR_MESSAGES.DEFAULT(e),
  165. )
  166. ############################
  167. # DeleteFunctionById
  168. ############################
  169. @router.delete("/id/{id}/delete", response_model=bool)
  170. async def delete_function_by_id(
  171. request: Request, id: str, user=Depends(get_admin_user)
  172. ):
  173. result = Functions.delete_function_by_id(id)
  174. if result:
  175. FUNCTIONS = request.app.state.FUNCTIONS
  176. if id in FUNCTIONS:
  177. del FUNCTIONS[id]
  178. # delete the function file
  179. function_path = os.path.join(FUNCTIONS_DIR, f"{id}.py")
  180. os.remove(function_path)
  181. return result
  182. ############################
  183. # GetFunctionValves
  184. ############################
  185. @router.get("/id/{id}/valves", response_model=Optional[dict])
  186. async def get_function_valves_by_id(id: str, user=Depends(get_admin_user)):
  187. function = Functions.get_function_by_id(id)
  188. if function:
  189. try:
  190. valves = Functions.get_function_valves_by_id(id)
  191. return valves
  192. except Exception as e:
  193. raise HTTPException(
  194. status_code=status.HTTP_400_BAD_REQUEST,
  195. detail=ERROR_MESSAGES.DEFAULT(e),
  196. )
  197. else:
  198. raise HTTPException(
  199. status_code=status.HTTP_401_UNAUTHORIZED,
  200. detail=ERROR_MESSAGES.NOT_FOUND,
  201. )
  202. ############################
  203. # GetFunctionValvesSpec
  204. ############################
  205. @router.get("/id/{id}/valves/spec", response_model=Optional[dict])
  206. async def get_function_valves_spec_by_id(
  207. request: Request, id: str, user=Depends(get_admin_user)
  208. ):
  209. function = Functions.get_function_by_id(id)
  210. if function:
  211. if id in request.app.state.FUNCTIONS:
  212. function_module = request.app.state.FUNCTIONS[id]
  213. else:
  214. function_module, function_type, frontmatter = load_function_module_by_id(id)
  215. request.app.state.FUNCTIONS[id] = function_module
  216. if hasattr(function_module, "Valves"):
  217. Valves = function_module.Valves
  218. return Valves.schema()
  219. return None
  220. else:
  221. raise HTTPException(
  222. status_code=status.HTTP_401_UNAUTHORIZED,
  223. detail=ERROR_MESSAGES.NOT_FOUND,
  224. )
  225. ############################
  226. # UpdateFunctionValves
  227. ############################
  228. @router.post("/id/{id}/valves/update", response_model=Optional[dict])
  229. async def update_function_valves_by_id(
  230. request: Request, id: str, form_data: dict, user=Depends(get_admin_user)
  231. ):
  232. function = Functions.get_function_by_id(id)
  233. if function:
  234. if id in request.app.state.FUNCTIONS:
  235. function_module = request.app.state.FUNCTIONS[id]
  236. else:
  237. function_module, function_type, frontmatter = load_function_module_by_id(id)
  238. request.app.state.FUNCTIONS[id] = function_module
  239. if hasattr(function_module, "Valves"):
  240. Valves = function_module.Valves
  241. try:
  242. form_data = {k: v for k, v in form_data.items() if v is not None}
  243. valves = Valves(**form_data)
  244. Functions.update_function_valves_by_id(id, valves.model_dump())
  245. return valves.model_dump()
  246. except Exception as e:
  247. print(e)
  248. raise HTTPException(
  249. status_code=status.HTTP_400_BAD_REQUEST,
  250. detail=ERROR_MESSAGES.DEFAULT(e),
  251. )
  252. else:
  253. raise HTTPException(
  254. status_code=status.HTTP_401_UNAUTHORIZED,
  255. detail=ERROR_MESSAGES.NOT_FOUND,
  256. )
  257. else:
  258. raise HTTPException(
  259. status_code=status.HTTP_401_UNAUTHORIZED,
  260. detail=ERROR_MESSAGES.NOT_FOUND,
  261. )
  262. ############################
  263. # FunctionUserValves
  264. ############################
  265. @router.get("/id/{id}/valves/user", response_model=Optional[dict])
  266. async def get_function_user_valves_by_id(id: str, user=Depends(get_verified_user)):
  267. function = Functions.get_function_by_id(id)
  268. if function:
  269. try:
  270. user_valves = Functions.get_user_valves_by_id_and_user_id(id, user.id)
  271. return user_valves
  272. except Exception as e:
  273. raise HTTPException(
  274. status_code=status.HTTP_400_BAD_REQUEST,
  275. detail=ERROR_MESSAGES.DEFAULT(e),
  276. )
  277. else:
  278. raise HTTPException(
  279. status_code=status.HTTP_401_UNAUTHORIZED,
  280. detail=ERROR_MESSAGES.NOT_FOUND,
  281. )
  282. @router.get("/id/{id}/valves/user/spec", response_model=Optional[dict])
  283. async def get_function_user_valves_spec_by_id(
  284. request: Request, id: str, user=Depends(get_verified_user)
  285. ):
  286. function = Functions.get_function_by_id(id)
  287. if function:
  288. if id in request.app.state.FUNCTIONS:
  289. function_module = request.app.state.FUNCTIONS[id]
  290. else:
  291. function_module, function_type, frontmatter = load_function_module_by_id(id)
  292. request.app.state.FUNCTIONS[id] = function_module
  293. if hasattr(function_module, "UserValves"):
  294. UserValves = function_module.UserValves
  295. return UserValves.schema()
  296. return None
  297. else:
  298. raise HTTPException(
  299. status_code=status.HTTP_401_UNAUTHORIZED,
  300. detail=ERROR_MESSAGES.NOT_FOUND,
  301. )
  302. @router.post("/id/{id}/valves/user/update", response_model=Optional[dict])
  303. async def update_function_user_valves_by_id(
  304. request: Request, id: str, form_data: dict, user=Depends(get_verified_user)
  305. ):
  306. function = Functions.get_function_by_id(id)
  307. if function:
  308. if id in request.app.state.FUNCTIONS:
  309. function_module = request.app.state.FUNCTIONS[id]
  310. else:
  311. function_module, function_type, frontmatter = load_function_module_by_id(id)
  312. request.app.state.FUNCTIONS[id] = function_module
  313. if hasattr(function_module, "UserValves"):
  314. UserValves = function_module.UserValves
  315. try:
  316. form_data = {k: v for k, v in form_data.items() if v is not None}
  317. user_valves = UserValves(**form_data)
  318. Functions.update_user_valves_by_id_and_user_id(
  319. id, user.id, user_valves.model_dump()
  320. )
  321. return user_valves.model_dump()
  322. except Exception as e:
  323. print(e)
  324. raise HTTPException(
  325. status_code=status.HTTP_400_BAD_REQUEST,
  326. detail=ERROR_MESSAGES.DEFAULT(e),
  327. )
  328. else:
  329. raise HTTPException(
  330. status_code=status.HTTP_401_UNAUTHORIZED,
  331. detail=ERROR_MESSAGES.NOT_FOUND,
  332. )
  333. else:
  334. raise HTTPException(
  335. status_code=status.HTTP_401_UNAUTHORIZED,
  336. detail=ERROR_MESSAGES.NOT_FOUND,
  337. )