functions.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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(**{k: v for k, v in function.valves if v is not None})
  121. except Exception as e:
  122. log.exception(
  123. f"Error validating valves for function {function.id}: {e}"
  124. )
  125. raise e
  126. return Functions.sync_functions(user.id, form_data.functions)
  127. except Exception as e:
  128. log.exception(f"Failed to load a function: {e}")
  129. raise HTTPException(
  130. status_code=status.HTTP_400_BAD_REQUEST,
  131. detail=ERROR_MESSAGES.DEFAULT(e),
  132. )
  133. ############################
  134. # CreateNewFunction
  135. ############################
  136. @router.post("/create", response_model=Optional[FunctionResponse])
  137. async def create_new_function(
  138. request: Request, form_data: FunctionForm, user=Depends(get_admin_user)
  139. ):
  140. if not form_data.id.isidentifier():
  141. raise HTTPException(
  142. status_code=status.HTTP_400_BAD_REQUEST,
  143. detail="Only alphanumeric characters and underscores are allowed in the id",
  144. )
  145. form_data.id = form_data.id.lower()
  146. function = Functions.get_function_by_id(form_data.id)
  147. if function is None:
  148. try:
  149. form_data.content = replace_imports(form_data.content)
  150. function_module, function_type, frontmatter = load_function_module_by_id(
  151. form_data.id,
  152. content=form_data.content,
  153. )
  154. form_data.meta.manifest = frontmatter
  155. FUNCTIONS = request.app.state.FUNCTIONS
  156. FUNCTIONS[form_data.id] = function_module
  157. function = Functions.insert_new_function(user.id, function_type, form_data)
  158. function_cache_dir = CACHE_DIR / "functions" / form_data.id
  159. function_cache_dir.mkdir(parents=True, exist_ok=True)
  160. if function_type == "filter" and getattr(function_module, "toggle", None):
  161. Functions.update_function_metadata_by_id(id, {"toggle": True})
  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 creating function"),
  168. )
  169. except Exception as e:
  170. log.exception(f"Failed to create a new function: {e}")
  171. raise HTTPException(
  172. status_code=status.HTTP_400_BAD_REQUEST,
  173. detail=ERROR_MESSAGES.DEFAULT(e),
  174. )
  175. else:
  176. raise HTTPException(
  177. status_code=status.HTTP_400_BAD_REQUEST,
  178. detail=ERROR_MESSAGES.ID_TAKEN,
  179. )
  180. ############################
  181. # GetFunctionById
  182. ############################
  183. @router.get("/id/{id}", response_model=Optional[FunctionModel])
  184. async def get_function_by_id(id: str, user=Depends(get_admin_user)):
  185. function = Functions.get_function_by_id(id)
  186. if function:
  187. return function
  188. else:
  189. raise HTTPException(
  190. status_code=status.HTTP_401_UNAUTHORIZED,
  191. detail=ERROR_MESSAGES.NOT_FOUND,
  192. )
  193. ############################
  194. # ToggleFunctionById
  195. ############################
  196. @router.post("/id/{id}/toggle", response_model=Optional[FunctionModel])
  197. async def toggle_function_by_id(id: str, user=Depends(get_admin_user)):
  198. function = Functions.get_function_by_id(id)
  199. if function:
  200. function = Functions.update_function_by_id(
  201. id, {"is_active": not function.is_active}
  202. )
  203. if function:
  204. return function
  205. else:
  206. raise HTTPException(
  207. status_code=status.HTTP_400_BAD_REQUEST,
  208. detail=ERROR_MESSAGES.DEFAULT("Error updating function"),
  209. )
  210. else:
  211. raise HTTPException(
  212. status_code=status.HTTP_401_UNAUTHORIZED,
  213. detail=ERROR_MESSAGES.NOT_FOUND,
  214. )
  215. ############################
  216. # ToggleGlobalById
  217. ############################
  218. @router.post("/id/{id}/toggle/global", response_model=Optional[FunctionModel])
  219. async def toggle_global_by_id(id: str, user=Depends(get_admin_user)):
  220. function = Functions.get_function_by_id(id)
  221. if function:
  222. function = Functions.update_function_by_id(
  223. id, {"is_global": not function.is_global}
  224. )
  225. if function:
  226. return function
  227. else:
  228. raise HTTPException(
  229. status_code=status.HTTP_400_BAD_REQUEST,
  230. detail=ERROR_MESSAGES.DEFAULT("Error updating function"),
  231. )
  232. else:
  233. raise HTTPException(
  234. status_code=status.HTTP_401_UNAUTHORIZED,
  235. detail=ERROR_MESSAGES.NOT_FOUND,
  236. )
  237. ############################
  238. # UpdateFunctionById
  239. ############################
  240. @router.post("/id/{id}/update", response_model=Optional[FunctionModel])
  241. async def update_function_by_id(
  242. request: Request, id: str, form_data: FunctionForm, user=Depends(get_admin_user)
  243. ):
  244. try:
  245. form_data.content = replace_imports(form_data.content)
  246. function_module, function_type, frontmatter = load_function_module_by_id(
  247. id, content=form_data.content
  248. )
  249. form_data.meta.manifest = frontmatter
  250. FUNCTIONS = request.app.state.FUNCTIONS
  251. FUNCTIONS[id] = function_module
  252. updated = {**form_data.model_dump(exclude={"id"}), "type": function_type}
  253. log.debug(updated)
  254. function = Functions.update_function_by_id(id, updated)
  255. if function_type == "filter" and getattr(function_module, "toggle", None):
  256. Functions.update_function_metadata_by_id(id, {"toggle": True})
  257. if function:
  258. return function
  259. else:
  260. raise HTTPException(
  261. status_code=status.HTTP_400_BAD_REQUEST,
  262. detail=ERROR_MESSAGES.DEFAULT("Error updating function"),
  263. )
  264. except Exception as e:
  265. raise HTTPException(
  266. status_code=status.HTTP_400_BAD_REQUEST,
  267. detail=ERROR_MESSAGES.DEFAULT(e),
  268. )
  269. ############################
  270. # DeleteFunctionById
  271. ############################
  272. @router.delete("/id/{id}/delete", response_model=bool)
  273. async def delete_function_by_id(
  274. request: Request, id: str, user=Depends(get_admin_user)
  275. ):
  276. result = Functions.delete_function_by_id(id)
  277. if result:
  278. FUNCTIONS = request.app.state.FUNCTIONS
  279. if id in FUNCTIONS:
  280. del FUNCTIONS[id]
  281. return result
  282. ############################
  283. # GetFunctionValves
  284. ############################
  285. @router.get("/id/{id}/valves", response_model=Optional[dict])
  286. async def get_function_valves_by_id(id: str, user=Depends(get_admin_user)):
  287. function = Functions.get_function_by_id(id)
  288. if function:
  289. try:
  290. valves = Functions.get_function_valves_by_id(id)
  291. return valves
  292. except Exception as e:
  293. raise HTTPException(
  294. status_code=status.HTTP_400_BAD_REQUEST,
  295. detail=ERROR_MESSAGES.DEFAULT(e),
  296. )
  297. else:
  298. raise HTTPException(
  299. status_code=status.HTTP_401_UNAUTHORIZED,
  300. detail=ERROR_MESSAGES.NOT_FOUND,
  301. )
  302. ############################
  303. # GetFunctionValvesSpec
  304. ############################
  305. @router.get("/id/{id}/valves/spec", response_model=Optional[dict])
  306. async def get_function_valves_spec_by_id(
  307. request: Request, id: str, user=Depends(get_admin_user)
  308. ):
  309. function = Functions.get_function_by_id(id)
  310. if function:
  311. function_module, function_type, frontmatter = get_function_module_from_cache(
  312. request, id
  313. )
  314. if hasattr(function_module, "Valves"):
  315. Valves = function_module.Valves
  316. return Valves.schema()
  317. return None
  318. else:
  319. raise HTTPException(
  320. status_code=status.HTTP_401_UNAUTHORIZED,
  321. detail=ERROR_MESSAGES.NOT_FOUND,
  322. )
  323. ############################
  324. # UpdateFunctionValves
  325. ############################
  326. @router.post("/id/{id}/valves/update", response_model=Optional[dict])
  327. async def update_function_valves_by_id(
  328. request: Request, id: str, form_data: dict, user=Depends(get_admin_user)
  329. ):
  330. function = Functions.get_function_by_id(id)
  331. if function:
  332. function_module, function_type, frontmatter = get_function_module_from_cache(
  333. request, id
  334. )
  335. if hasattr(function_module, "Valves"):
  336. Valves = function_module.Valves
  337. try:
  338. form_data = {k: v for k, v in form_data.items() if v is not None}
  339. valves = Valves(**form_data)
  340. Functions.update_function_valves_by_id(id, valves.model_dump())
  341. return valves.model_dump()
  342. except Exception as e:
  343. log.exception(f"Error updating function values by id {id}: {e}")
  344. raise HTTPException(
  345. status_code=status.HTTP_400_BAD_REQUEST,
  346. detail=ERROR_MESSAGES.DEFAULT(e),
  347. )
  348. else:
  349. raise HTTPException(
  350. status_code=status.HTTP_401_UNAUTHORIZED,
  351. detail=ERROR_MESSAGES.NOT_FOUND,
  352. )
  353. else:
  354. raise HTTPException(
  355. status_code=status.HTTP_401_UNAUTHORIZED,
  356. detail=ERROR_MESSAGES.NOT_FOUND,
  357. )
  358. ############################
  359. # FunctionUserValves
  360. ############################
  361. @router.get("/id/{id}/valves/user", response_model=Optional[dict])
  362. async def get_function_user_valves_by_id(id: str, user=Depends(get_verified_user)):
  363. function = Functions.get_function_by_id(id)
  364. if function:
  365. try:
  366. user_valves = Functions.get_user_valves_by_id_and_user_id(id, user.id)
  367. return user_valves
  368. except Exception as e:
  369. raise HTTPException(
  370. status_code=status.HTTP_400_BAD_REQUEST,
  371. detail=ERROR_MESSAGES.DEFAULT(e),
  372. )
  373. else:
  374. raise HTTPException(
  375. status_code=status.HTTP_401_UNAUTHORIZED,
  376. detail=ERROR_MESSAGES.NOT_FOUND,
  377. )
  378. @router.get("/id/{id}/valves/user/spec", response_model=Optional[dict])
  379. async def get_function_user_valves_spec_by_id(
  380. request: Request, id: str, user=Depends(get_verified_user)
  381. ):
  382. function = Functions.get_function_by_id(id)
  383. if function:
  384. function_module, function_type, frontmatter = get_function_module_from_cache(
  385. request, id
  386. )
  387. if hasattr(function_module, "UserValves"):
  388. UserValves = function_module.UserValves
  389. return UserValves.schema()
  390. return None
  391. else:
  392. raise HTTPException(
  393. status_code=status.HTTP_401_UNAUTHORIZED,
  394. detail=ERROR_MESSAGES.NOT_FOUND,
  395. )
  396. @router.post("/id/{id}/valves/user/update", response_model=Optional[dict])
  397. async def update_function_user_valves_by_id(
  398. request: Request, id: str, form_data: dict, user=Depends(get_verified_user)
  399. ):
  400. function = Functions.get_function_by_id(id)
  401. if function:
  402. function_module, function_type, frontmatter = get_function_module_from_cache(
  403. request, id
  404. )
  405. if hasattr(function_module, "UserValves"):
  406. UserValves = function_module.UserValves
  407. try:
  408. form_data = {k: v for k, v in form_data.items() if v is not None}
  409. user_valves = UserValves(**form_data)
  410. Functions.update_user_valves_by_id_and_user_id(
  411. id, user.id, user_valves.model_dump()
  412. )
  413. return user_valves.model_dump()
  414. except Exception as e:
  415. log.exception(f"Error updating function user valves by id {id}: {e}")
  416. raise HTTPException(
  417. status_code=status.HTTP_400_BAD_REQUEST,
  418. detail=ERROR_MESSAGES.DEFAULT(e),
  419. )
  420. else:
  421. raise HTTPException(
  422. status_code=status.HTTP_401_UNAUTHORIZED,
  423. detail=ERROR_MESSAGES.NOT_FOUND,
  424. )
  425. else:
  426. raise HTTPException(
  427. status_code=status.HTTP_401_UNAUTHORIZED,
  428. detail=ERROR_MESSAGES.NOT_FOUND,
  429. )