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