123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411 |
- import os
- import logging
- from pathlib import Path
- from typing import Optional
- from open_webui.models.functions import (
- FunctionForm,
- FunctionModel,
- FunctionResponse,
- Functions,
- )
- from open_webui.utils.plugin import load_function_module_by_id, replace_imports
- from open_webui.config import CACHE_DIR
- from open_webui.constants import ERROR_MESSAGES
- from fastapi import APIRouter, Depends, HTTPException, Request, status
- from open_webui.utils.auth import get_admin_user, get_verified_user
- from open_webui.env import SRC_LOG_LEVELS
- log = logging.getLogger(__name__)
- log.setLevel(SRC_LOG_LEVELS["MAIN"])
- router = APIRouter()
- ############################
- # GetFunctions
- ############################
- @router.get("/", response_model=list[FunctionResponse])
- async def get_functions(user=Depends(get_verified_user)):
- return Functions.get_functions()
- ############################
- # ExportFunctions
- ############################
- @router.get("/export", response_model=list[FunctionModel])
- async def get_functions(user=Depends(get_admin_user)):
- return Functions.get_functions()
- ############################
- # CreateNewFunction
- ############################
- @router.post("/create", response_model=Optional[FunctionResponse])
- async def create_new_function(
- request: Request, form_data: FunctionForm, user=Depends(get_admin_user)
- ):
- if not form_data.id.isidentifier():
- raise HTTPException(
- status_code=status.HTTP_400_BAD_REQUEST,
- detail="Only alphanumeric characters and underscores are allowed in the id",
- )
- form_data.id = form_data.id.lower()
- function = Functions.get_function_by_id(form_data.id)
- if function is None:
- try:
- form_data.content = replace_imports(form_data.content)
- function_module, function_type, frontmatter = load_function_module_by_id(
- form_data.id,
- content=form_data.content,
- )
- form_data.meta.manifest = frontmatter
- FUNCTIONS = request.app.state.FUNCTIONS
- FUNCTIONS[form_data.id] = function_module
- function = Functions.insert_new_function(user.id, function_type, form_data)
- function_cache_dir = CACHE_DIR / "functions" / form_data.id
- function_cache_dir.mkdir(parents=True, exist_ok=True)
- if function:
- return function
- else:
- raise HTTPException(
- status_code=status.HTTP_400_BAD_REQUEST,
- detail=ERROR_MESSAGES.DEFAULT("Error creating function"),
- )
- except Exception as e:
- log.exception(f"Failed to create a new function: {e}")
- raise HTTPException(
- status_code=status.HTTP_400_BAD_REQUEST,
- detail=ERROR_MESSAGES.DEFAULT(e),
- )
- else:
- raise HTTPException(
- status_code=status.HTTP_400_BAD_REQUEST,
- detail=ERROR_MESSAGES.ID_TAKEN,
- )
- ############################
- # GetFunctionById
- ############################
- @router.get("/id/{id}", response_model=Optional[FunctionModel])
- async def get_function_by_id(id: str, user=Depends(get_admin_user)):
- function = Functions.get_function_by_id(id)
- if function:
- return function
- else:
- raise HTTPException(
- status_code=status.HTTP_401_UNAUTHORIZED,
- detail=ERROR_MESSAGES.NOT_FOUND,
- )
- ############################
- # ToggleFunctionById
- ############################
- @router.post("/id/{id}/toggle", response_model=Optional[FunctionModel])
- async def toggle_function_by_id(id: str, user=Depends(get_admin_user)):
- function = Functions.get_function_by_id(id)
- if function:
- function = Functions.update_function_by_id(
- id, {"is_active": not function.is_active}
- )
- if function:
- return function
- else:
- raise HTTPException(
- status_code=status.HTTP_400_BAD_REQUEST,
- detail=ERROR_MESSAGES.DEFAULT("Error updating function"),
- )
- else:
- raise HTTPException(
- status_code=status.HTTP_401_UNAUTHORIZED,
- detail=ERROR_MESSAGES.NOT_FOUND,
- )
- ############################
- # ToggleGlobalById
- ############################
- @router.post("/id/{id}/toggle/global", response_model=Optional[FunctionModel])
- async def toggle_global_by_id(id: str, user=Depends(get_admin_user)):
- function = Functions.get_function_by_id(id)
- if function:
- function = Functions.update_function_by_id(
- id, {"is_global": not function.is_global}
- )
- if function:
- return function
- else:
- raise HTTPException(
- status_code=status.HTTP_400_BAD_REQUEST,
- detail=ERROR_MESSAGES.DEFAULT("Error updating function"),
- )
- else:
- raise HTTPException(
- status_code=status.HTTP_401_UNAUTHORIZED,
- detail=ERROR_MESSAGES.NOT_FOUND,
- )
- ############################
- # UpdateFunctionById
- ############################
- @router.post("/id/{id}/update", response_model=Optional[FunctionModel])
- async def update_function_by_id(
- request: Request, id: str, form_data: FunctionForm, user=Depends(get_admin_user)
- ):
- try:
- form_data.content = replace_imports(form_data.content)
- function_module, function_type, frontmatter = load_function_module_by_id(
- id, content=form_data.content
- )
- form_data.meta.manifest = frontmatter
- FUNCTIONS = request.app.state.FUNCTIONS
- FUNCTIONS[id] = function_module
- updated = {**form_data.model_dump(exclude={"id"}), "type": function_type}
- log.debug(updated)
- function = Functions.update_function_by_id(id, updated)
- if function:
- return function
- else:
- raise HTTPException(
- status_code=status.HTTP_400_BAD_REQUEST,
- detail=ERROR_MESSAGES.DEFAULT("Error updating function"),
- )
- except Exception as e:
- raise HTTPException(
- status_code=status.HTTP_400_BAD_REQUEST,
- detail=ERROR_MESSAGES.DEFAULT(e),
- )
- ############################
- # DeleteFunctionById
- ############################
- @router.delete("/id/{id}/delete", response_model=bool)
- async def delete_function_by_id(
- request: Request, id: str, user=Depends(get_admin_user)
- ):
- result = Functions.delete_function_by_id(id)
- if result:
- FUNCTIONS = request.app.state.FUNCTIONS
- if id in FUNCTIONS:
- del FUNCTIONS[id]
- return result
- ############################
- # GetFunctionValves
- ############################
- @router.get("/id/{id}/valves", response_model=Optional[dict])
- async def get_function_valves_by_id(id: str, user=Depends(get_admin_user)):
- function = Functions.get_function_by_id(id)
- if function:
- try:
- valves = Functions.get_function_valves_by_id(id)
- return valves
- except Exception as e:
- raise HTTPException(
- status_code=status.HTTP_400_BAD_REQUEST,
- detail=ERROR_MESSAGES.DEFAULT(e),
- )
- else:
- raise HTTPException(
- status_code=status.HTTP_401_UNAUTHORIZED,
- detail=ERROR_MESSAGES.NOT_FOUND,
- )
- ############################
- # GetFunctionValvesSpec
- ############################
- @router.get("/id/{id}/valves/spec", response_model=Optional[dict])
- async def get_function_valves_spec_by_id(
- request: Request, id: str, user=Depends(get_admin_user)
- ):
- function = Functions.get_function_by_id(id)
- if function:
- if id in request.app.state.FUNCTIONS:
- function_module = request.app.state.FUNCTIONS[id]
- else:
- function_module, function_type, frontmatter = load_function_module_by_id(id)
- request.app.state.FUNCTIONS[id] = function_module
- if hasattr(function_module, "Valves"):
- Valves = function_module.Valves
- return Valves.schema()
- return None
- else:
- raise HTTPException(
- status_code=status.HTTP_401_UNAUTHORIZED,
- detail=ERROR_MESSAGES.NOT_FOUND,
- )
- ############################
- # UpdateFunctionValves
- ############################
- @router.post("/id/{id}/valves/update", response_model=Optional[dict])
- async def update_function_valves_by_id(
- request: Request, id: str, form_data: dict, user=Depends(get_admin_user)
- ):
- function = Functions.get_function_by_id(id)
- if function:
- if id in request.app.state.FUNCTIONS:
- function_module = request.app.state.FUNCTIONS[id]
- else:
- function_module, function_type, frontmatter = load_function_module_by_id(id)
- request.app.state.FUNCTIONS[id] = function_module
- if hasattr(function_module, "Valves"):
- Valves = function_module.Valves
- try:
- form_data = {k: v for k, v in form_data.items() if v is not None}
- valves = Valves(**form_data)
- Functions.update_function_valves_by_id(id, valves.model_dump())
- return valves.model_dump()
- except Exception as e:
- log.exception(f"Error updating function values by id {id}: {e}")
- raise HTTPException(
- status_code=status.HTTP_400_BAD_REQUEST,
- detail=ERROR_MESSAGES.DEFAULT(e),
- )
- else:
- raise HTTPException(
- status_code=status.HTTP_401_UNAUTHORIZED,
- detail=ERROR_MESSAGES.NOT_FOUND,
- )
- else:
- raise HTTPException(
- status_code=status.HTTP_401_UNAUTHORIZED,
- detail=ERROR_MESSAGES.NOT_FOUND,
- )
- ############################
- # FunctionUserValves
- ############################
- @router.get("/id/{id}/valves/user", response_model=Optional[dict])
- async def get_function_user_valves_by_id(id: str, user=Depends(get_verified_user)):
- function = Functions.get_function_by_id(id)
- if function:
- try:
- user_valves = Functions.get_user_valves_by_id_and_user_id(id, user.id)
- return user_valves
- except Exception as e:
- raise HTTPException(
- status_code=status.HTTP_400_BAD_REQUEST,
- detail=ERROR_MESSAGES.DEFAULT(e),
- )
- else:
- raise HTTPException(
- status_code=status.HTTP_401_UNAUTHORIZED,
- detail=ERROR_MESSAGES.NOT_FOUND,
- )
- @router.get("/id/{id}/valves/user/spec", response_model=Optional[dict])
- async def get_function_user_valves_spec_by_id(
- request: Request, id: str, user=Depends(get_verified_user)
- ):
- function = Functions.get_function_by_id(id)
- if function:
- if id in request.app.state.FUNCTIONS:
- function_module = request.app.state.FUNCTIONS[id]
- else:
- function_module, function_type, frontmatter = load_function_module_by_id(id)
- request.app.state.FUNCTIONS[id] = function_module
- if hasattr(function_module, "UserValves"):
- UserValves = function_module.UserValves
- return UserValves.schema()
- return None
- else:
- raise HTTPException(
- status_code=status.HTTP_401_UNAUTHORIZED,
- detail=ERROR_MESSAGES.NOT_FOUND,
- )
- @router.post("/id/{id}/valves/user/update", response_model=Optional[dict])
- async def update_function_user_valves_by_id(
- request: Request, id: str, form_data: dict, user=Depends(get_verified_user)
- ):
- function = Functions.get_function_by_id(id)
- if function:
- if id in request.app.state.FUNCTIONS:
- function_module = request.app.state.FUNCTIONS[id]
- else:
- function_module, function_type, frontmatter = load_function_module_by_id(id)
- request.app.state.FUNCTIONS[id] = function_module
- if hasattr(function_module, "UserValves"):
- UserValves = function_module.UserValves
- try:
- form_data = {k: v for k, v in form_data.items() if v is not None}
- user_valves = UserValves(**form_data)
- Functions.update_user_valves_by_id_and_user_id(
- id, user.id, user_valves.model_dump()
- )
- return user_valves.model_dump()
- except Exception as e:
- log.exception(f"Error updating function user valves by id {id}: {e}")
- raise HTTPException(
- status_code=status.HTTP_400_BAD_REQUEST,
- detail=ERROR_MESSAGES.DEFAULT(e),
- )
- else:
- raise HTTPException(
- status_code=status.HTTP_401_UNAUTHORIZED,
- detail=ERROR_MESSAGES.NOT_FOUND,
- )
- else:
- raise HTTPException(
- status_code=status.HTTP_401_UNAUTHORIZED,
- detail=ERROR_MESSAGES.NOT_FOUND,
- )
|