tools.py 5.27 KB
Newer Older
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
1
from fastapi import Depends, FastAPI, HTTPException, status, Request
Timothy J. Baek's avatar
Timothy J. Baek committed
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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

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

TOOLS_DIR = f"{DATA_DIR}/tools"
os.makedirs(TOOLS_DIR, exist_ok=True)


router = APIRouter()


def load_toolkit_module_from_path(tools_id, tools_path):
    spec = util.spec_from_file_location(tools_id, tools_path)
    module = util.module_from_spec(spec)

    try:
        spec.loader.exec_module(module)
        print(f"Loaded module: {module.__name__}")
        if hasattr(module, "Tools"):
            return module.Tools()
        else:
            raise Exception("No Tools class found")
    except Exception as e:
        print(f"Error loading module: {tools_id}")

        # Move the file to the error folder
        os.rename(tools_path, f"{tools_path}.error")
        raise e


############################
# GetToolkits
############################


@router.get("/", response_model=List[ToolResponse])
async def get_toolkits(user=Depends(get_current_user)):
Timothy J. Baek's avatar
Timothy J. Baek committed
53
54
55
56
57
58
59
60
61
62
    toolkits = [toolkit for toolkit in Tools.get_tools()]
    return toolkits


############################
# ExportToolKits
############################


@router.get("/export", response_model=List[ToolModel])
Timothy J. Baek's avatar
Timothy J. Baek committed
63
async def get_toolkits(user=Depends(get_admin_user)):
Timothy J. Baek's avatar
Timothy J. Baek committed
64
    toolkits = [toolkit for toolkit in Tools.get_tools()]
Timothy J. Baek's avatar
Timothy J. Baek committed
65
66
67
68
69
70
71
72
73
    return toolkits


############################
# CreateNewToolKit
############################


@router.post("/create", response_model=Optional[ToolResponse])
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
74
75
76
async def create_new_toolkit(
    request: Request, form_data: ToolForm, user=Depends(get_admin_user)
):
Timothy J. Baek's avatar
Timothy J. Baek committed
77
78
79
80
81
82
    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",
        )

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
83
84
    form_data.id = form_data.id.lower()

Timothy J. Baek's avatar
Timothy J. Baek committed
85
86
87
88
89
90
91
92
    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)

            toolkit_module = load_toolkit_module_from_path(form_data.id, toolkit_path)
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
93
94

            TOOLS = request.app.state.TOOLS
Timothy J. Baek's avatar
Timothy J. Baek committed
95
96
97
98
99
100
            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:
Timothy J. Baek's avatar
Timothy J. Baek committed
101
                return toolkit
Timothy J. Baek's avatar
Timothy J. Baek committed
102
103
104
105
106
107
108
109
110
111
112
113
114
            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,
Timothy J. Baek's avatar
Timothy J. Baek committed
115
            detail=ERROR_MESSAGES.ID_TAKEN,
Timothy J. Baek's avatar
Timothy J. Baek committed
116
117
118
119
120
121
122
123
        )


############################
# GetToolkitById
############################


Timothy J. Baek's avatar
Timothy J. Baek committed
124
@router.get("/id/{id}", response_model=Optional[ToolModel])
Timothy J. Baek's avatar
Timothy J. Baek committed
125
126
127
128
async def get_toolkit_by_id(id: str, user=Depends(get_admin_user)):
    toolkit = Tools.get_tool_by_id(id)

    if toolkit:
Timothy J. Baek's avatar
Timothy J. Baek committed
129
        return toolkit
Timothy J. Baek's avatar
Timothy J. Baek committed
130
131
132
133
134
135
136
137
138
139
140
141
    else:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=ERROR_MESSAGES.NOT_FOUND,
        )


############################
# UpdateToolkitById
############################


Timothy J. Baek's avatar
Timothy J. Baek committed
142
@router.post("/id/{id}/update", response_model=Optional[ToolModel])
Timothy J. Baek's avatar
Timothy J. Baek committed
143
async def update_toolkit_by_id(
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
144
    request: Request, id: str, form_data: ToolForm, user=Depends(get_admin_user)
Timothy J. Baek's avatar
Timothy J. Baek committed
145
146
147
148
149
150
151
152
):
    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)

        toolkit_module = load_toolkit_module_from_path(id, toolkit_path)
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
153
154

        TOOLS = request.app.state.TOOLS
Timothy J. Baek's avatar
Timothy J. Baek committed
155
156
157
        TOOLS[id] = toolkit_module

        specs = get_tools_specs(TOOLS[id])
Timothy J. Baek's avatar
Timothy J. Baek committed
158
159

        updated = {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
160
            **form_data.model_dump(exclude={"id"}),
Timothy J. Baek's avatar
Timothy J. Baek committed
161
162
163
164
165
            "specs": specs,
        }

        print(updated)
        toolkit = Tools.update_tool_by_id(id, updated)
Timothy J. Baek's avatar
Timothy J. Baek committed
166
167

        if toolkit:
Timothy J. Baek's avatar
Timothy J. Baek committed
168
            return toolkit
Timothy J. Baek's avatar
Timothy J. Baek committed
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
        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)
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
188
async def delete_toolkit_by_id(request: Request, id: str, user=Depends(get_admin_user)):
Timothy J. Baek's avatar
Timothy J. Baek committed
189
    result = Tools.delete_tool_by_id(id)
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
190
191
192
193
194

    if result:
        TOOLS = request.app.state.TOOLS
        del TOOLS[id]

Timothy J. Baek's avatar
Timothy J. Baek committed
195
    return result