open-webui/backend/apps/webui/routers/tools.py

178 lines
4.7 KiB
Python
Raw Normal View History

2024-06-11 05:38:48 +00:00
from fastapi import Depends, FastAPI, HTTPException, status, Request
2024-06-11 03:39:55 +00:00
from datetime import datetime, timedelta
from typing import List, Union, Optional
from fastapi import APIRouter
from pydantic import BaseModel
import json
from apps.webui.models.tools import Tools, ToolForm, ToolModel, ToolResponse
2024-06-11 06:40:27 +00:00
from apps.webui.utils import load_toolkit_module_by_id
2024-06-11 03:39:55 +00:00
from utils.utils import get_current_user, get_admin_user
from utils.tools import get_tools_specs
from constants import ERROR_MESSAGES
from importlib import util
import os
from config import DATA_DIR
2024-06-11 06:40:27 +00:00
2024-06-11 03:39:55 +00:00
TOOLS_DIR = f"{DATA_DIR}/tools"
os.makedirs(TOOLS_DIR, exist_ok=True)
router = APIRouter()
############################
# GetToolkits
############################
@router.get("/", response_model=List[ToolResponse])
async def get_toolkits(user=Depends(get_current_user)):
2024-06-11 04:33:46 +00:00
toolkits = [toolkit for toolkit in Tools.get_tools()]
return toolkits
############################
# ExportToolKits
############################
@router.get("/export", response_model=List[ToolModel])
2024-06-11 04:36:13 +00:00
async def get_toolkits(user=Depends(get_admin_user)):
2024-06-11 04:33:46 +00:00
toolkits = [toolkit for toolkit in Tools.get_tools()]
2024-06-11 03:39:55 +00:00
return toolkits
############################
# CreateNewToolKit
############################
@router.post("/create", response_model=Optional[ToolResponse])
2024-06-11 05:38:48 +00:00
async def create_new_toolkit(
request: Request, form_data: ToolForm, user=Depends(get_admin_user)
):
2024-06-11 04:59:06 +00:00
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",
)
2024-06-11 05:10:53 +00:00
form_data.id = form_data.id.lower()
2024-06-11 03:39:55 +00:00
toolkit = Tools.get_tool_by_id(form_data.id)
if toolkit == None:
toolkit_path = os.path.join(TOOLS_DIR, f"{form_data.id}.py")
try:
with open(toolkit_path, "w") as tool_file:
tool_file.write(form_data.content)
2024-06-11 06:40:27 +00:00
toolkit_module = load_toolkit_module_by_id(form_data.id)
2024-06-11 05:38:48 +00:00
TOOLS = request.app.state.TOOLS
2024-06-11 03:39:55 +00:00
TOOLS[form_data.id] = toolkit_module
specs = get_tools_specs(TOOLS[form_data.id])
toolkit = Tools.insert_new_tool(user.id, form_data, specs)
if toolkit:
2024-06-11 04:33:46 +00:00
return toolkit
2024-06-11 03:39:55 +00:00
else:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=ERROR_MESSAGES.FILE_EXISTS,
)
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_400_BAD_REQUEST,
2024-06-11 04:33:46 +00:00
detail=ERROR_MESSAGES.ID_TAKEN,
2024-06-11 03:39:55 +00:00
)
############################
# GetToolkitById
############################
2024-06-11 04:53:51 +00:00
@router.get("/id/{id}", response_model=Optional[ToolModel])
2024-06-11 03:39:55 +00:00
async def get_toolkit_by_id(id: str, user=Depends(get_admin_user)):
toolkit = Tools.get_tool_by_id(id)
if toolkit:
2024-06-11 04:33:46 +00:00
return toolkit
2024-06-11 03:39:55 +00:00
else:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=ERROR_MESSAGES.NOT_FOUND,
)
############################
# UpdateToolkitById
############################
2024-06-11 04:53:51 +00:00
@router.post("/id/{id}/update", response_model=Optional[ToolModel])
2024-06-11 03:39:55 +00:00
async def update_toolkit_by_id(
2024-06-11 05:38:48 +00:00
request: Request, id: str, form_data: ToolForm, user=Depends(get_admin_user)
2024-06-11 03:39:55 +00:00
):
toolkit_path = os.path.join(TOOLS_DIR, f"{id}.py")
try:
with open(toolkit_path, "w") as tool_file:
tool_file.write(form_data.content)
2024-06-11 06:40:27 +00:00
toolkit_module = load_toolkit_module_by_id(id)
2024-06-11 05:38:48 +00:00
TOOLS = request.app.state.TOOLS
2024-06-11 03:39:55 +00:00
TOOLS[id] = toolkit_module
specs = get_tools_specs(TOOLS[id])
2024-06-11 04:53:51 +00:00
updated = {
2024-06-11 05:10:53 +00:00
**form_data.model_dump(exclude={"id"}),
2024-06-11 04:53:51 +00:00
"specs": specs,
}
print(updated)
toolkit = Tools.update_tool_by_id(id, updated)
2024-06-11 03:39:55 +00:00
if toolkit:
2024-06-11 04:33:46 +00:00
return toolkit
2024-06-11 03:39:55 +00:00
else:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=ERROR_MESSAGES.DEFAULT("Error updating toolkit"),
)
except Exception as e:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=ERROR_MESSAGES.DEFAULT(e),
)
############################
# DeleteToolkitById
############################
@router.delete("/id/{id}/delete", response_model=bool)
2024-06-11 05:38:48 +00:00
async def delete_toolkit_by_id(request: Request, id: str, user=Depends(get_admin_user)):
2024-06-11 03:39:55 +00:00
result = Tools.delete_tool_by_id(id)
2024-06-11 05:38:48 +00:00
if result:
TOOLS = request.app.state.TOOLS
del TOOLS[id]
2024-06-11 03:39:55 +00:00
return result