1
0

functions.py 15 KB

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