functions.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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. # UpdateFunctionById
  116. ############################
  117. @router.post("/id/{id}/update", response_model=Optional[FunctionModel])
  118. async def update_function_by_id(
  119. request: Request, id: str, form_data: FunctionForm, user=Depends(get_admin_user)
  120. ):
  121. function_path = os.path.join(FUNCTIONS_DIR, f"{id}.py")
  122. try:
  123. with open(function_path, "w") as function_file:
  124. function_file.write(form_data.content)
  125. function_module, function_type, frontmatter = load_function_module_by_id(id)
  126. form_data.meta.manifest = frontmatter
  127. FUNCTIONS = request.app.state.FUNCTIONS
  128. FUNCTIONS[id] = function_module
  129. updated = {**form_data.model_dump(exclude={"id"}), "type": function_type}
  130. print(updated)
  131. function = Functions.update_function_by_id(id, updated)
  132. if function:
  133. return function
  134. else:
  135. raise HTTPException(
  136. status_code=status.HTTP_400_BAD_REQUEST,
  137. detail=ERROR_MESSAGES.DEFAULT("Error updating function"),
  138. )
  139. except Exception as e:
  140. raise HTTPException(
  141. status_code=status.HTTP_400_BAD_REQUEST,
  142. detail=ERROR_MESSAGES.DEFAULT(e),
  143. )
  144. ############################
  145. # DeleteFunctionById
  146. ############################
  147. @router.delete("/id/{id}/delete", response_model=bool)
  148. async def delete_function_by_id(
  149. request: Request, id: str, user=Depends(get_admin_user)
  150. ):
  151. result = Functions.delete_function_by_id(id)
  152. if result:
  153. FUNCTIONS = request.app.state.FUNCTIONS
  154. if id in FUNCTIONS:
  155. del FUNCTIONS[id]
  156. # delete the function file
  157. function_path = os.path.join(FUNCTIONS_DIR, f"{id}.py")
  158. os.remove(function_path)
  159. return result
  160. ############################
  161. # GetFunctionValves
  162. ############################
  163. @router.get("/id/{id}/valves", response_model=Optional[dict])
  164. async def get_function_valves_by_id(id: str, user=Depends(get_admin_user)):
  165. function = Functions.get_function_by_id(id)
  166. if function:
  167. try:
  168. valves = Functions.get_function_valves_by_id(id)
  169. return valves
  170. except Exception as e:
  171. raise HTTPException(
  172. status_code=status.HTTP_400_BAD_REQUEST,
  173. detail=ERROR_MESSAGES.DEFAULT(e),
  174. )
  175. else:
  176. raise HTTPException(
  177. status_code=status.HTTP_401_UNAUTHORIZED,
  178. detail=ERROR_MESSAGES.NOT_FOUND,
  179. )
  180. ############################
  181. # GetFunctionValvesSpec
  182. ############################
  183. @router.get("/id/{id}/valves/spec", response_model=Optional[dict])
  184. async def get_function_valves_spec_by_id(
  185. request: Request, id: str, user=Depends(get_admin_user)
  186. ):
  187. function = Functions.get_function_by_id(id)
  188. if function:
  189. if id in request.app.state.FUNCTIONS:
  190. function_module = request.app.state.FUNCTIONS[id]
  191. else:
  192. function_module, function_type, frontmatter = load_function_module_by_id(id)
  193. request.app.state.FUNCTIONS[id] = function_module
  194. if hasattr(function_module, "Valves"):
  195. Valves = function_module.Valves
  196. return Valves.schema()
  197. return None
  198. else:
  199. raise HTTPException(
  200. status_code=status.HTTP_401_UNAUTHORIZED,
  201. detail=ERROR_MESSAGES.NOT_FOUND,
  202. )
  203. ############################
  204. # UpdateFunctionValves
  205. ############################
  206. @router.post("/id/{id}/valves/update", response_model=Optional[dict])
  207. async def update_function_valves_by_id(
  208. request: Request, id: str, form_data: dict, user=Depends(get_admin_user)
  209. ):
  210. function = Functions.get_function_by_id(id)
  211. if function:
  212. if id in request.app.state.FUNCTIONS:
  213. function_module = request.app.state.FUNCTIONS[id]
  214. else:
  215. function_module, function_type, frontmatter = load_function_module_by_id(id)
  216. request.app.state.FUNCTIONS[id] = function_module
  217. if hasattr(function_module, "Valves"):
  218. Valves = function_module.Valves
  219. try:
  220. form_data = {k: v for k, v in form_data.items() if v is not None}
  221. valves = Valves(**form_data)
  222. Functions.update_function_valves_by_id(id, valves.model_dump())
  223. return valves.model_dump()
  224. except Exception as e:
  225. print(e)
  226. raise HTTPException(
  227. status_code=status.HTTP_400_BAD_REQUEST,
  228. detail=ERROR_MESSAGES.DEFAULT(e),
  229. )
  230. else:
  231. raise HTTPException(
  232. status_code=status.HTTP_401_UNAUTHORIZED,
  233. detail=ERROR_MESSAGES.NOT_FOUND,
  234. )
  235. else:
  236. raise HTTPException(
  237. status_code=status.HTTP_401_UNAUTHORIZED,
  238. detail=ERROR_MESSAGES.NOT_FOUND,
  239. )
  240. ############################
  241. # FunctionUserValves
  242. ############################
  243. @router.get("/id/{id}/valves/user", response_model=Optional[dict])
  244. async def get_function_user_valves_by_id(id: str, user=Depends(get_verified_user)):
  245. function = Functions.get_function_by_id(id)
  246. if function:
  247. try:
  248. user_valves = Functions.get_user_valves_by_id_and_user_id(id, user.id)
  249. return user_valves
  250. except Exception as e:
  251. raise HTTPException(
  252. status_code=status.HTTP_400_BAD_REQUEST,
  253. detail=ERROR_MESSAGES.DEFAULT(e),
  254. )
  255. else:
  256. raise HTTPException(
  257. status_code=status.HTTP_401_UNAUTHORIZED,
  258. detail=ERROR_MESSAGES.NOT_FOUND,
  259. )
  260. @router.get("/id/{id}/valves/user/spec", response_model=Optional[dict])
  261. async def get_function_user_valves_spec_by_id(
  262. request: Request, id: str, user=Depends(get_verified_user)
  263. ):
  264. function = Functions.get_function_by_id(id)
  265. if function:
  266. if id in request.app.state.FUNCTIONS:
  267. function_module = request.app.state.FUNCTIONS[id]
  268. else:
  269. function_module, function_type, frontmatter = load_function_module_by_id(id)
  270. request.app.state.FUNCTIONS[id] = function_module
  271. if hasattr(function_module, "UserValves"):
  272. UserValves = function_module.UserValves
  273. return UserValves.schema()
  274. return None
  275. else:
  276. raise HTTPException(
  277. status_code=status.HTTP_401_UNAUTHORIZED,
  278. detail=ERROR_MESSAGES.NOT_FOUND,
  279. )
  280. @router.post("/id/{id}/valves/user/update", response_model=Optional[dict])
  281. async def update_function_user_valves_by_id(
  282. request: Request, id: str, form_data: dict, user=Depends(get_verified_user)
  283. ):
  284. function = Functions.get_function_by_id(id)
  285. if function:
  286. if id in request.app.state.FUNCTIONS:
  287. function_module = request.app.state.FUNCTIONS[id]
  288. else:
  289. function_module, function_type, frontmatter = load_function_module_by_id(id)
  290. request.app.state.FUNCTIONS[id] = function_module
  291. if hasattr(function_module, "UserValves"):
  292. UserValves = function_module.UserValves
  293. try:
  294. form_data = {k: v for k, v in form_data.items() if v is not None}
  295. user_valves = UserValves(**form_data)
  296. Functions.update_user_valves_by_id_and_user_id(
  297. id, user.id, user_valves.model_dump()
  298. )
  299. return user_valves.model_dump()
  300. except Exception as e:
  301. print(e)
  302. raise HTTPException(
  303. status_code=status.HTTP_400_BAD_REQUEST,
  304. detail=ERROR_MESSAGES.DEFAULT(e),
  305. )
  306. else:
  307. raise HTTPException(
  308. status_code=status.HTTP_401_UNAUTHORIZED,
  309. detail=ERROR_MESSAGES.NOT_FOUND,
  310. )
  311. else:
  312. raise HTTPException(
  313. status_code=status.HTTP_401_UNAUTHORIZED,
  314. detail=ERROR_MESSAGES.NOT_FOUND,
  315. )