1
0

functions.py 17 KB

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