tools.py 11.1 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
from datetime import datetime, timedelta
from typing import List, Union, Optional

from fastapi import APIRouter
from pydantic import BaseModel
import json

Timothy J. Baek's avatar
Timothy J. Baek committed
9
10

from apps.webui.models.users import Users
Timothy J. Baek's avatar
Timothy J. Baek committed
11
from apps.webui.models.tools import Tools, ToolForm, ToolModel, ToolResponse
Timothy J. Baek's avatar
Timothy J. Baek committed
12
from apps.webui.utils import load_toolkit_module_by_id
Timothy J. Baek's avatar
Timothy J. Baek committed
13

Timothy J. Baek's avatar
Timothy J. Baek committed
14
from utils.utils import get_admin_user, get_verified_user
Timothy J. Baek's avatar
Timothy J. Baek committed
15
16
17
18
19
from utils.tools import get_tools_specs
from constants import ERROR_MESSAGES

from importlib import util
import os
Timothy J. Baek's avatar
Timothy J. Baek committed
20
from pathlib import Path
Timothy J. Baek's avatar
Timothy J. Baek committed
21

Timothy J. Baek's avatar
Timothy J. Baek committed
22
from config import DATA_DIR, CACHE_DIR
Timothy J. Baek's avatar
Timothy J. Baek committed
23

Timothy J. Baek's avatar
Timothy J. Baek committed
24

Timothy J. Baek's avatar
Timothy J. Baek committed
25
26
27
28
29
30
31
32
33
34
35
36
TOOLS_DIR = f"{DATA_DIR}/tools"
os.makedirs(TOOLS_DIR, exist_ok=True)


router = APIRouter()

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


@router.get("/", response_model=List[ToolResponse])
Timothy J. Baek's avatar
Timothy J. Baek committed
37
async def get_toolkits(user=Depends(get_verified_user)):
Timothy J. Baek's avatar
Timothy J. Baek committed
38
39
40
41
42
43
44
45
46
47
    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
48
async def get_toolkits(user=Depends(get_admin_user)):
Timothy J. Baek's avatar
Timothy J. Baek committed
49
    toolkits = [toolkit for toolkit in Tools.get_tools()]
Timothy J. Baek's avatar
Timothy J. Baek committed
50
51
52
53
54
55
56
57
58
    return toolkits


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


@router.post("/create", response_model=Optional[ToolResponse])
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
59
60
61
async def create_new_toolkit(
    request: Request, form_data: ToolForm, user=Depends(get_admin_user)
):
Timothy J. Baek's avatar
Timothy J. Baek committed
62
63
64
65
66
67
    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
68
69
    form_data.id = form_data.id.lower()

Timothy J. Baek's avatar
Timothy J. Baek committed
70
71
72
73
74
75
76
    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)

77
78
            toolkit_module, frontmatter = load_toolkit_module_by_id(form_data.id)
            form_data.meta.manifest = frontmatter
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
79
80

            TOOLS = request.app.state.TOOLS
Timothy J. Baek's avatar
Timothy J. Baek committed
81
82
83
84
85
            TOOLS[form_data.id] = toolkit_module

            specs = get_tools_specs(TOOLS[form_data.id])
            toolkit = Tools.insert_new_tool(user.id, form_data, specs)

Timothy J. Baek's avatar
Timothy J. Baek committed
86
87
88
            tool_cache_dir = Path(CACHE_DIR) / "tools" / form_data.id
            tool_cache_dir.mkdir(parents=True, exist_ok=True)

Timothy J. Baek's avatar
Timothy J. Baek committed
89
            if toolkit:
Timothy J. Baek's avatar
Timothy J. Baek committed
90
                return toolkit
Timothy J. Baek's avatar
Timothy J. Baek committed
91
92
93
            else:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
94
                    detail=ERROR_MESSAGES.DEFAULT("Error creating toolkit"),
Timothy J. Baek's avatar
Timothy J. Baek committed
95
96
                )
        except Exception as e:
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
97
            print(e)
Timothy J. Baek's avatar
Timothy J. Baek committed
98
99
100
101
102
103
104
            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
105
            detail=ERROR_MESSAGES.ID_TAKEN,
Timothy J. Baek's avatar
Timothy J. Baek committed
106
107
108
109
110
111
112
113
        )


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


Timothy J. Baek's avatar
Timothy J. Baek committed
114
@router.get("/id/{id}", response_model=Optional[ToolModel])
Timothy J. Baek's avatar
Timothy J. Baek committed
115
116
117
118
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
119
        return toolkit
Timothy J. Baek's avatar
Timothy J. Baek committed
120
121
122
123
124
125
126
    else:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=ERROR_MESSAGES.NOT_FOUND,
        )


127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
############################
# UpdateToolkitById
############################


@router.post("/id/{id}/update", response_model=Optional[ToolModel])
async def update_toolkit_by_id(
    request: Request, id: str, form_data: ToolForm, user=Depends(get_admin_user)
):
    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, frontmatter = load_toolkit_module_by_id(id)
        form_data.meta.manifest = frontmatter

        TOOLS = request.app.state.TOOLS
        TOOLS[id] = toolkit_module

        specs = get_tools_specs(TOOLS[id])

        updated = {
            **form_data.model_dump(exclude={"id"}),
            "specs": specs,
        }

        print(updated)
        toolkit = Tools.update_tool_by_id(id, updated)

        if toolkit:
            return toolkit
        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)
async def delete_toolkit_by_id(request: Request, id: str, user=Depends(get_admin_user)):
    result = Tools.delete_tool_by_id(id)

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

        # delete the toolkit file
        toolkit_path = os.path.join(TOOLS_DIR, f"{id}.py")
        os.remove(toolkit_path)

    return result


194
195
196
197
198
199
200
201
202
203
############################
# GetToolValves
############################


@router.get("/id/{id}/valves", response_model=Optional[dict])
async def get_toolkit_valves_by_id(id: str, user=Depends(get_admin_user)):
    toolkit = Tools.get_tool_by_id(id)
    if toolkit:
        try:
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
204
205
            valves = Tools.get_tool_valves_by_id(id)
            return valves
206
207
208
209
210
211
212
213
214
215
216
217
        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,
        )


Timothy J. Baek's avatar
Timothy J. Baek committed
218
219
220
221
222
223
224
225
226
227
228
229
230
231
############################
# GetToolValvesSpec
############################


@router.get("/id/{id}/valves/spec", response_model=Optional[dict])
async def get_toolkit_valves_spec_by_id(
    request: Request, id: str, user=Depends(get_admin_user)
):
    toolkit = Tools.get_tool_by_id(id)
    if toolkit:
        if id in request.app.state.TOOLS:
            toolkit_module = request.app.state.TOOLS[id]
        else:
232
            toolkit_module, frontmatter = load_toolkit_module_by_id(id)
Timothy J. Baek's avatar
Timothy J. Baek committed
233
234
            request.app.state.TOOLS[id] = toolkit_module

Timothy J. Baek's avatar
Timothy J. Baek committed
235
236
237
        if hasattr(toolkit_module, "Valves"):
            Valves = toolkit_module.Valves
            return Valves.schema()
Timothy J. Baek's avatar
Timothy J. Baek committed
238
239
240
241
242
243
244
245
        return None
    else:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=ERROR_MESSAGES.NOT_FOUND,
        )


246
247
248
249
250
251
252
############################
# UpdateToolValves
############################


@router.post("/id/{id}/valves/update", response_model=Optional[dict])
async def update_toolkit_valves_by_id(
Timothy J. Baek's avatar
Timothy J. Baek committed
253
    request: Request, id: str, form_data: dict, user=Depends(get_admin_user)
254
255
256
):
    toolkit = Tools.get_tool_by_id(id)
    if toolkit:
Timothy J. Baek's avatar
Timothy J. Baek committed
257
258
259
        if id in request.app.state.TOOLS:
            toolkit_module = request.app.state.TOOLS[id]
        else:
260
            toolkit_module, frontmatter = load_toolkit_module_by_id(id)
Timothy J. Baek's avatar
Timothy J. Baek committed
261
262
263
264
265
266
            request.app.state.TOOLS[id] = toolkit_module

        if hasattr(toolkit_module, "Valves"):
            Valves = toolkit_module.Valves

            try:
Timothy J. Baek's avatar
Timothy J. Baek committed
267
                form_data = {k: v for k, v in form_data.items() if v is not None}
Timothy J. Baek's avatar
Timothy J. Baek committed
268
269
270
271
272
273
274
275
276
277
                valves = Valves(**form_data)
                Tools.update_tool_valves_by_id(id, valves.model_dump())
                return valves.model_dump()
            except Exception as e:
                print(e)
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail=ERROR_MESSAGES.DEFAULT(e),
                )
        else:
278
            raise HTTPException(
Timothy J. Baek's avatar
Timothy J. Baek committed
279
280
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail=ERROR_MESSAGES.NOT_FOUND,
281
            )
Timothy J. Baek's avatar
Timothy J. Baek committed
282

283
284
285
286
287
288
289
    else:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=ERROR_MESSAGES.NOT_FOUND,
        )


Timothy J. Baek's avatar
Timothy J. Baek committed
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
############################
# ToolUserValves
############################


@router.get("/id/{id}/valves/user", response_model=Optional[dict])
async def get_toolkit_user_valves_by_id(id: str, user=Depends(get_verified_user)):
    toolkit = Tools.get_tool_by_id(id)
    if toolkit:
        try:
            user_valves = Tools.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_toolkit_user_valves_spec_by_id(
    request: Request, id: str, user=Depends(get_verified_user)
):
    toolkit = Tools.get_tool_by_id(id)
    if toolkit:
        if id in request.app.state.TOOLS:
            toolkit_module = request.app.state.TOOLS[id]
        else:
323
            toolkit_module, frontmatter = load_toolkit_module_by_id(id)
Timothy J. Baek's avatar
Timothy J. Baek committed
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
            request.app.state.TOOLS[id] = toolkit_module

        if hasattr(toolkit_module, "UserValves"):
            UserValves = toolkit_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_toolkit_user_valves_by_id(
    request: Request, id: str, form_data: dict, user=Depends(get_verified_user)
):
    toolkit = Tools.get_tool_by_id(id)

    if toolkit:
        if id in request.app.state.TOOLS:
            toolkit_module = request.app.state.TOOLS[id]
        else:
347
            toolkit_module, frontmatter = load_toolkit_module_by_id(id)
Timothy J. Baek's avatar
Timothy J. Baek committed
348
349
350
351
352
353
            request.app.state.TOOLS[id] = toolkit_module

        if hasattr(toolkit_module, "UserValves"):
            UserValves = toolkit_module.UserValves

            try:
Timothy J. Baek's avatar
Timothy J. Baek committed
354
                form_data = {k: v for k, v in form_data.items() if v is not None}
Timothy J. Baek's avatar
Timothy J. Baek committed
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
                user_valves = UserValves(**form_data)
                Tools.update_user_valves_by_id_and_user_id(
                    id, user.id, user_valves.model_dump()
                )
                return user_valves.model_dump()
            except Exception as e:
                print(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,
        )