functions.py 13 KB

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