functions.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. import os
  2. import re
  3. import logging
  4. import aiohttp
  5. from pathlib import Path
  6. from typing import Optional
  7. from open_webui.models.functions import (
  8. FunctionForm,
  9. FunctionModel,
  10. FunctionResponse,
  11. Functions,
  12. )
  13. from open_webui.utils.plugin import load_function_module_by_id, replace_imports
  14. from open_webui.config import CACHE_DIR
  15. from open_webui.constants import ERROR_MESSAGES
  16. from fastapi import APIRouter, Depends, HTTPException, Request, status
  17. from open_webui.utils.auth import get_admin_user, get_verified_user
  18. from open_webui.env import SRC_LOG_LEVELS
  19. from pydantic import BaseModel, HttpUrl
  20. log = logging.getLogger(__name__)
  21. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  22. router = APIRouter()
  23. ############################
  24. # GetFunctions
  25. ############################
  26. @router.get("/", response_model=list[FunctionResponse])
  27. async def get_functions(user=Depends(get_verified_user)):
  28. return Functions.get_functions()
  29. ############################
  30. # ExportFunctions
  31. ############################
  32. @router.get("/export", response_model=list[FunctionModel])
  33. async def get_functions(user=Depends(get_admin_user)):
  34. return Functions.get_functions()
  35. ############################
  36. # LoadFunctionFromLink
  37. ############################
  38. class LoadUrlForm(BaseModel):
  39. url: HttpUrl
  40. def github_url_to_raw_url(url: str) -> str:
  41. # Handle 'tree' (folder) URLs (add main.py at the end)
  42. m1 = re.match(r"https://github\.com/([^/]+)/([^/]+)/tree/([^/]+)/(.*)", url)
  43. if m1:
  44. org, repo, branch, path = m1.groups()
  45. return f"https://raw.githubusercontent.com/{org}/{repo}/refs/heads/{branch}/{path.rstrip('/')}/main.py"
  46. # Handle 'blob' (file) URLs
  47. m2 = re.match(r"https://github\.com/([^/]+)/([^/]+)/blob/([^/]+)/(.*)", url)
  48. if m2:
  49. org, repo, branch, path = m2.groups()
  50. return (
  51. f"https://raw.githubusercontent.com/{org}/{repo}/refs/heads/{branch}/{path}"
  52. )
  53. # No match; return as-is
  54. return url
  55. @router.post("/load/url", response_model=Optional[dict])
  56. async def load_function_from_url(
  57. request: Request, form_data: LoadUrlForm, user=Depends(get_admin_user)
  58. ):
  59. # NOTE: This is NOT a SSRF vulnerability:
  60. # This endpoint is admin-only (see get_admin_user), meant for *trusted* internal use,
  61. # and does NOT accept untrusted user input. Access is enforced by authentication.
  62. url = str(form_data.url)
  63. if not url:
  64. raise HTTPException(status_code=400, detail="Please enter a valid URL")
  65. url = github_url_to_raw_url(url)
  66. url_parts = url.rstrip("/").split("/")
  67. file_name = url_parts[-1]
  68. function_name = (
  69. file_name[:-3]
  70. if (
  71. file_name.endswith(".py")
  72. and (not file_name.startswith(("main.py", "index.py", "__init__.py")))
  73. )
  74. else url_parts[-2] if len(url_parts) > 1 else "function"
  75. )
  76. try:
  77. async with aiohttp.ClientSession() as session:
  78. async with session.get(
  79. url, headers={"Content-Type": "application/json"}
  80. ) as resp:
  81. if resp.status != 200:
  82. raise HTTPException(
  83. status_code=resp.status, detail="Failed to fetch the function"
  84. )
  85. data = await resp.text()
  86. if not data:
  87. raise HTTPException(
  88. status_code=400, detail="No data received from the URL"
  89. )
  90. return {
  91. "name": function_name,
  92. "content": data,
  93. }
  94. except Exception as e:
  95. raise HTTPException(status_code=500, detail=f"Error importing function: {e}")
  96. ############################
  97. # SyncFunctions
  98. ############################
  99. class SyncFunctionsForm(FunctionForm):
  100. functions: list[FunctionModel] = []
  101. @router.post("/sync", response_model=Optional[FunctionModel])
  102. async def sync_functions(
  103. request: Request, form_data: SyncFunctionsForm, user=Depends(get_admin_user)
  104. ):
  105. return Functions.sync_functions(user.id, form_data.functions)
  106. ############################
  107. # CreateNewFunction
  108. ############################
  109. @router.post("/create", response_model=Optional[FunctionResponse])
  110. async def create_new_function(
  111. request: Request, form_data: FunctionForm, user=Depends(get_admin_user)
  112. ):
  113. if not form_data.id.isidentifier():
  114. raise HTTPException(
  115. status_code=status.HTTP_400_BAD_REQUEST,
  116. detail="Only alphanumeric characters and underscores are allowed in the id",
  117. )
  118. form_data.id = form_data.id.lower()
  119. function = Functions.get_function_by_id(form_data.id)
  120. if function is None:
  121. try:
  122. form_data.content = replace_imports(form_data.content)
  123. function_module, function_type, frontmatter = load_function_module_by_id(
  124. form_data.id,
  125. content=form_data.content,
  126. )
  127. form_data.meta.manifest = frontmatter
  128. FUNCTIONS = request.app.state.FUNCTIONS
  129. FUNCTIONS[form_data.id] = function_module
  130. function = Functions.insert_new_function(user.id, function_type, form_data)
  131. function_cache_dir = CACHE_DIR / "functions" / form_data.id
  132. function_cache_dir.mkdir(parents=True, exist_ok=True)
  133. if function:
  134. return function
  135. else:
  136. raise HTTPException(
  137. status_code=status.HTTP_400_BAD_REQUEST,
  138. detail=ERROR_MESSAGES.DEFAULT("Error creating function"),
  139. )
  140. except Exception as e:
  141. log.exception(f"Failed to create a new function: {e}")
  142. raise HTTPException(
  143. status_code=status.HTTP_400_BAD_REQUEST,
  144. detail=ERROR_MESSAGES.DEFAULT(e),
  145. )
  146. else:
  147. raise HTTPException(
  148. status_code=status.HTTP_400_BAD_REQUEST,
  149. detail=ERROR_MESSAGES.ID_TAKEN,
  150. )
  151. ############################
  152. # GetFunctionById
  153. ############################
  154. @router.get("/id/{id}", response_model=Optional[FunctionModel])
  155. async def get_function_by_id(id: str, user=Depends(get_admin_user)):
  156. function = Functions.get_function_by_id(id)
  157. if function:
  158. return function
  159. else:
  160. raise HTTPException(
  161. status_code=status.HTTP_401_UNAUTHORIZED,
  162. detail=ERROR_MESSAGES.NOT_FOUND,
  163. )
  164. ############################
  165. # ToggleFunctionById
  166. ############################
  167. @router.post("/id/{id}/toggle", response_model=Optional[FunctionModel])
  168. async def toggle_function_by_id(id: str, user=Depends(get_admin_user)):
  169. function = Functions.get_function_by_id(id)
  170. if function:
  171. function = Functions.update_function_by_id(
  172. id, {"is_active": not function.is_active}
  173. )
  174. if function:
  175. return function
  176. else:
  177. raise HTTPException(
  178. status_code=status.HTTP_400_BAD_REQUEST,
  179. detail=ERROR_MESSAGES.DEFAULT("Error updating function"),
  180. )
  181. else:
  182. raise HTTPException(
  183. status_code=status.HTTP_401_UNAUTHORIZED,
  184. detail=ERROR_MESSAGES.NOT_FOUND,
  185. )
  186. ############################
  187. # ToggleGlobalById
  188. ############################
  189. @router.post("/id/{id}/toggle/global", response_model=Optional[FunctionModel])
  190. async def toggle_global_by_id(id: str, user=Depends(get_admin_user)):
  191. function = Functions.get_function_by_id(id)
  192. if function:
  193. function = Functions.update_function_by_id(
  194. id, {"is_global": not function.is_global}
  195. )
  196. if function:
  197. return function
  198. else:
  199. raise HTTPException(
  200. status_code=status.HTTP_400_BAD_REQUEST,
  201. detail=ERROR_MESSAGES.DEFAULT("Error updating function"),
  202. )
  203. else:
  204. raise HTTPException(
  205. status_code=status.HTTP_401_UNAUTHORIZED,
  206. detail=ERROR_MESSAGES.NOT_FOUND,
  207. )
  208. ############################
  209. # UpdateFunctionById
  210. ############################
  211. @router.post("/id/{id}/update", response_model=Optional[FunctionModel])
  212. async def update_function_by_id(
  213. request: Request, id: str, form_data: FunctionForm, user=Depends(get_admin_user)
  214. ):
  215. try:
  216. form_data.content = replace_imports(form_data.content)
  217. function_module, function_type, frontmatter = load_function_module_by_id(
  218. id, content=form_data.content
  219. )
  220. form_data.meta.manifest = frontmatter
  221. FUNCTIONS = request.app.state.FUNCTIONS
  222. FUNCTIONS[id] = function_module
  223. updated = {**form_data.model_dump(exclude={"id"}), "type": function_type}
  224. log.debug(updated)
  225. function = Functions.update_function_by_id(id, updated)
  226. if function:
  227. return function
  228. else:
  229. raise HTTPException(
  230. status_code=status.HTTP_400_BAD_REQUEST,
  231. detail=ERROR_MESSAGES.DEFAULT("Error updating function"),
  232. )
  233. except Exception as e:
  234. raise HTTPException(
  235. status_code=status.HTTP_400_BAD_REQUEST,
  236. detail=ERROR_MESSAGES.DEFAULT(e),
  237. )
  238. ############################
  239. # DeleteFunctionById
  240. ############################
  241. @router.delete("/id/{id}/delete", response_model=bool)
  242. async def delete_function_by_id(
  243. request: Request, id: str, user=Depends(get_admin_user)
  244. ):
  245. result = Functions.delete_function_by_id(id)
  246. if result:
  247. FUNCTIONS = request.app.state.FUNCTIONS
  248. if id in FUNCTIONS:
  249. del FUNCTIONS[id]
  250. return result
  251. ############################
  252. # GetFunctionValves
  253. ############################
  254. @router.get("/id/{id}/valves", response_model=Optional[dict])
  255. async def get_function_valves_by_id(id: str, user=Depends(get_admin_user)):
  256. function = Functions.get_function_by_id(id)
  257. if function:
  258. try:
  259. valves = Functions.get_function_valves_by_id(id)
  260. return 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. ############################
  272. # GetFunctionValvesSpec
  273. ############################
  274. @router.get("/id/{id}/valves/spec", response_model=Optional[dict])
  275. async def get_function_valves_spec_by_id(
  276. request: Request, id: str, user=Depends(get_admin_user)
  277. ):
  278. function = Functions.get_function_by_id(id)
  279. if function:
  280. function_module, function_type, frontmatter = load_function_module_by_id(id)
  281. request.app.state.FUNCTIONS[id] = function_module
  282. if hasattr(function_module, "Valves"):
  283. Valves = function_module.Valves
  284. return Valves.schema()
  285. return None
  286. else:
  287. raise HTTPException(
  288. status_code=status.HTTP_401_UNAUTHORIZED,
  289. detail=ERROR_MESSAGES.NOT_FOUND,
  290. )
  291. ############################
  292. # UpdateFunctionValves
  293. ############################
  294. @router.post("/id/{id}/valves/update", response_model=Optional[dict])
  295. async def update_function_valves_by_id(
  296. request: Request, id: str, form_data: dict, user=Depends(get_admin_user)
  297. ):
  298. function = Functions.get_function_by_id(id)
  299. if function:
  300. function_module, function_type, frontmatter = load_function_module_by_id(id)
  301. request.app.state.FUNCTIONS[id] = function_module
  302. if hasattr(function_module, "Valves"):
  303. Valves = function_module.Valves
  304. try:
  305. form_data = {k: v for k, v in form_data.items() if v is not None}
  306. valves = Valves(**form_data)
  307. Functions.update_function_valves_by_id(id, valves.model_dump())
  308. return valves.model_dump()
  309. except Exception as e:
  310. log.exception(f"Error updating function values by id {id}: {e}")
  311. raise HTTPException(
  312. status_code=status.HTTP_400_BAD_REQUEST,
  313. detail=ERROR_MESSAGES.DEFAULT(e),
  314. )
  315. else:
  316. raise HTTPException(
  317. status_code=status.HTTP_401_UNAUTHORIZED,
  318. detail=ERROR_MESSAGES.NOT_FOUND,
  319. )
  320. else:
  321. raise HTTPException(
  322. status_code=status.HTTP_401_UNAUTHORIZED,
  323. detail=ERROR_MESSAGES.NOT_FOUND,
  324. )
  325. ############################
  326. # FunctionUserValves
  327. ############################
  328. @router.get("/id/{id}/valves/user", response_model=Optional[dict])
  329. async def get_function_user_valves_by_id(id: str, user=Depends(get_verified_user)):
  330. function = Functions.get_function_by_id(id)
  331. if function:
  332. try:
  333. user_valves = Functions.get_user_valves_by_id_and_user_id(id, user.id)
  334. return user_valves
  335. except Exception as e:
  336. raise HTTPException(
  337. status_code=status.HTTP_400_BAD_REQUEST,
  338. detail=ERROR_MESSAGES.DEFAULT(e),
  339. )
  340. else:
  341. raise HTTPException(
  342. status_code=status.HTTP_401_UNAUTHORIZED,
  343. detail=ERROR_MESSAGES.NOT_FOUND,
  344. )
  345. @router.get("/id/{id}/valves/user/spec", response_model=Optional[dict])
  346. async def get_function_user_valves_spec_by_id(
  347. request: Request, id: str, user=Depends(get_verified_user)
  348. ):
  349. function = Functions.get_function_by_id(id)
  350. if function:
  351. function_module, function_type, frontmatter = load_function_module_by_id(id)
  352. request.app.state.FUNCTIONS[id] = function_module
  353. if hasattr(function_module, "UserValves"):
  354. UserValves = function_module.UserValves
  355. return UserValves.schema()
  356. return None
  357. else:
  358. raise HTTPException(
  359. status_code=status.HTTP_401_UNAUTHORIZED,
  360. detail=ERROR_MESSAGES.NOT_FOUND,
  361. )
  362. @router.post("/id/{id}/valves/user/update", response_model=Optional[dict])
  363. async def update_function_user_valves_by_id(
  364. request: Request, id: str, form_data: dict, user=Depends(get_verified_user)
  365. ):
  366. function = Functions.get_function_by_id(id)
  367. if function:
  368. function_module, function_type, frontmatter = load_function_module_by_id(id)
  369. request.app.state.FUNCTIONS[id] = function_module
  370. if hasattr(function_module, "UserValves"):
  371. UserValves = function_module.UserValves
  372. try:
  373. form_data = {k: v for k, v in form_data.items() if v is not None}
  374. user_valves = UserValves(**form_data)
  375. Functions.update_user_valves_by_id_and_user_id(
  376. id, user.id, user_valves.model_dump()
  377. )
  378. return user_valves.model_dump()
  379. except Exception as e:
  380. log.exception(f"Error updating function user valves by id {id}: {e}")
  381. raise HTTPException(
  382. status_code=status.HTTP_400_BAD_REQUEST,
  383. detail=ERROR_MESSAGES.DEFAULT(e),
  384. )
  385. else:
  386. raise HTTPException(
  387. status_code=status.HTTP_401_UNAUTHORIZED,
  388. detail=ERROR_MESSAGES.NOT_FOUND,
  389. )
  390. else:
  391. raise HTTPException(
  392. status_code=status.HTTP_401_UNAUTHORIZED,
  393. detail=ERROR_MESSAGES.NOT_FOUND,
  394. )