functions.py 16 KB

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