functions.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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. function_module, function_type, frontmatter = load_function_module_by_id(id)
  207. request.app.state.FUNCTIONS[id] = function_module
  208. if hasattr(function_module, "Valves"):
  209. Valves = function_module.Valves
  210. return Valves.schema()
  211. return None
  212. else:
  213. raise HTTPException(
  214. status_code=status.HTTP_401_UNAUTHORIZED,
  215. detail=ERROR_MESSAGES.NOT_FOUND,
  216. )
  217. ############################
  218. # UpdateFunctionValves
  219. ############################
  220. @router.post("/id/{id}/valves/update", response_model=Optional[dict])
  221. async def update_function_valves_by_id(
  222. request: Request, id: str, form_data: dict, user=Depends(get_admin_user)
  223. ):
  224. function = Functions.get_function_by_id(id)
  225. if function:
  226. function_module, function_type, frontmatter = load_function_module_by_id(id)
  227. request.app.state.FUNCTIONS[id] = function_module
  228. if hasattr(function_module, "Valves"):
  229. Valves = function_module.Valves
  230. try:
  231. form_data = {k: v for k, v in form_data.items() if v is not None}
  232. valves = Valves(**form_data)
  233. Functions.update_function_valves_by_id(id, valves.model_dump())
  234. return valves.model_dump()
  235. except Exception as e:
  236. log.exception(f"Error updating function values by id {id}: {e}")
  237. raise HTTPException(
  238. status_code=status.HTTP_400_BAD_REQUEST,
  239. detail=ERROR_MESSAGES.DEFAULT(e),
  240. )
  241. else:
  242. raise HTTPException(
  243. status_code=status.HTTP_401_UNAUTHORIZED,
  244. detail=ERROR_MESSAGES.NOT_FOUND,
  245. )
  246. else:
  247. raise HTTPException(
  248. status_code=status.HTTP_401_UNAUTHORIZED,
  249. detail=ERROR_MESSAGES.NOT_FOUND,
  250. )
  251. ############################
  252. # FunctionUserValves
  253. ############################
  254. @router.get("/id/{id}/valves/user", response_model=Optional[dict])
  255. async def get_function_user_valves_by_id(id: str, user=Depends(get_verified_user)):
  256. function = Functions.get_function_by_id(id)
  257. if function:
  258. try:
  259. user_valves = Functions.get_user_valves_by_id_and_user_id(id, user.id)
  260. return user_valves
  261. except Exception as e:
  262. raise HTTPException(
  263. status_code=status.HTTP_400_BAD_REQUEST,
  264. detail=ERROR_MESSAGES.DEFAULT(e),
  265. )
  266. else:
  267. raise HTTPException(
  268. status_code=status.HTTP_401_UNAUTHORIZED,
  269. detail=ERROR_MESSAGES.NOT_FOUND,
  270. )
  271. @router.get("/id/{id}/valves/user/spec", response_model=Optional[dict])
  272. async def get_function_user_valves_spec_by_id(
  273. request: Request, id: str, user=Depends(get_verified_user)
  274. ):
  275. function = Functions.get_function_by_id(id)
  276. if function:
  277. function_module, function_type, frontmatter = load_function_module_by_id(id)
  278. request.app.state.FUNCTIONS[id] = function_module
  279. if hasattr(function_module, "UserValves"):
  280. UserValves = function_module.UserValves
  281. return UserValves.schema()
  282. return None
  283. else:
  284. raise HTTPException(
  285. status_code=status.HTTP_401_UNAUTHORIZED,
  286. detail=ERROR_MESSAGES.NOT_FOUND,
  287. )
  288. @router.post("/id/{id}/valves/user/update", response_model=Optional[dict])
  289. async def update_function_user_valves_by_id(
  290. request: Request, id: str, form_data: dict, user=Depends(get_verified_user)
  291. ):
  292. function = Functions.get_function_by_id(id)
  293. if function:
  294. function_module, function_type, frontmatter = load_function_module_by_id(id)
  295. request.app.state.FUNCTIONS[id] = function_module
  296. if hasattr(function_module, "UserValves"):
  297. UserValves = function_module.UserValves
  298. try:
  299. form_data = {k: v for k, v in form_data.items() if v is not None}
  300. user_valves = UserValves(**form_data)
  301. Functions.update_user_valves_by_id_and_user_id(
  302. id, user.id, user_valves.model_dump()
  303. )
  304. return user_valves.model_dump()
  305. except Exception as e:
  306. log.exception(f"Error updating function user valves by id {id}: {e}")
  307. raise HTTPException(
  308. status_code=status.HTTP_400_BAD_REQUEST,
  309. detail=ERROR_MESSAGES.DEFAULT(e),
  310. )
  311. else:
  312. raise HTTPException(
  313. status_code=status.HTTP_401_UNAUTHORIZED,
  314. detail=ERROR_MESSAGES.NOT_FOUND,
  315. )
  316. else:
  317. raise HTTPException(
  318. status_code=status.HTTP_401_UNAUTHORIZED,
  319. detail=ERROR_MESSAGES.NOT_FOUND,
  320. )