functions.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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(
  285. request, id
  286. )
  287. if hasattr(function_module, "Valves"):
  288. Valves = function_module.Valves
  289. return Valves.schema()
  290. return None
  291. else:
  292. raise HTTPException(
  293. status_code=status.HTTP_401_UNAUTHORIZED,
  294. detail=ERROR_MESSAGES.NOT_FOUND,
  295. )
  296. ############################
  297. # UpdateFunctionValves
  298. ############################
  299. @router.post("/id/{id}/valves/update", response_model=Optional[dict])
  300. async def update_function_valves_by_id(
  301. request: Request, id: str, form_data: dict, user=Depends(get_admin_user)
  302. ):
  303. function = Functions.get_function_by_id(id)
  304. if function:
  305. function_module, function_type, frontmatter = get_function_module_from_cache(
  306. request, id
  307. )
  308. if hasattr(function_module, "Valves"):
  309. Valves = function_module.Valves
  310. try:
  311. form_data = {k: v for k, v in form_data.items() if v is not None}
  312. valves = Valves(**form_data)
  313. Functions.update_function_valves_by_id(id, valves.model_dump())
  314. return valves.model_dump()
  315. except Exception as e:
  316. log.exception(f"Error updating function values 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. )
  331. ############################
  332. # FunctionUserValves
  333. ############################
  334. @router.get("/id/{id}/valves/user", response_model=Optional[dict])
  335. async def get_function_user_valves_by_id(id: str, user=Depends(get_verified_user)):
  336. function = Functions.get_function_by_id(id)
  337. if function:
  338. try:
  339. user_valves = Functions.get_user_valves_by_id_and_user_id(id, user.id)
  340. return user_valves
  341. except Exception as e:
  342. raise HTTPException(
  343. status_code=status.HTTP_400_BAD_REQUEST,
  344. detail=ERROR_MESSAGES.DEFAULT(e),
  345. )
  346. else:
  347. raise HTTPException(
  348. status_code=status.HTTP_401_UNAUTHORIZED,
  349. detail=ERROR_MESSAGES.NOT_FOUND,
  350. )
  351. @router.get("/id/{id}/valves/user/spec", response_model=Optional[dict])
  352. async def get_function_user_valves_spec_by_id(
  353. request: Request, id: str, user=Depends(get_verified_user)
  354. ):
  355. function = Functions.get_function_by_id(id)
  356. if function:
  357. function_module, function_type, frontmatter = get_function_module_from_cache(
  358. request, id
  359. )
  360. if hasattr(function_module, "UserValves"):
  361. UserValves = function_module.UserValves
  362. return UserValves.schema()
  363. return None
  364. else:
  365. raise HTTPException(
  366. status_code=status.HTTP_401_UNAUTHORIZED,
  367. detail=ERROR_MESSAGES.NOT_FOUND,
  368. )
  369. @router.post("/id/{id}/valves/user/update", response_model=Optional[dict])
  370. async def update_function_user_valves_by_id(
  371. request: Request, id: str, form_data: dict, user=Depends(get_verified_user)
  372. ):
  373. function = Functions.get_function_by_id(id)
  374. if function:
  375. function_module, function_type, frontmatter = get_function_module_from_cache(
  376. request, id
  377. )
  378. if hasattr(function_module, "UserValves"):
  379. UserValves = function_module.UserValves
  380. try:
  381. form_data = {k: v for k, v in form_data.items() if v is not None}
  382. user_valves = UserValves(**form_data)
  383. Functions.update_user_valves_by_id_and_user_id(
  384. id, user.id, user_valves.model_dump()
  385. )
  386. return user_valves.model_dump()
  387. except Exception as e:
  388. log.exception(f"Error updating function user valves by id {id}: {e}")
  389. raise HTTPException(
  390. status_code=status.HTTP_400_BAD_REQUEST,
  391. detail=ERROR_MESSAGES.DEFAULT(e),
  392. )
  393. else:
  394. raise HTTPException(
  395. status_code=status.HTTP_401_UNAUTHORIZED,
  396. detail=ERROR_MESSAGES.NOT_FOUND,
  397. )
  398. else:
  399. raise HTTPException(
  400. status_code=status.HTTP_401_UNAUTHORIZED,
  401. detail=ERROR_MESSAGES.NOT_FOUND,
  402. )