1
0

functions.py 16 KB

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