functions.py 13 KB

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