tools.py 11 KB
Newer Older
1
2
from fastapi import Depends, HTTPException, status, Request
from typing import List, Optional
Timothy J. Baek's avatar
Timothy J. Baek committed
3
4
5
6

from fastapi import APIRouter

from apps.webui.models.tools import Tools, ToolForm, ToolModel, ToolResponse
Timothy J. Baek's avatar
Timothy J. Baek committed
7
from apps.webui.utils import load_toolkit_module_by_id
Timothy J. Baek's avatar
Timothy J. Baek committed
8

Timothy J. Baek's avatar
Timothy J. Baek committed
9
from utils.utils import get_admin_user, get_verified_user
Timothy J. Baek's avatar
Timothy J. Baek committed
10
11
12
13
from utils.tools import get_tools_specs
from constants import ERROR_MESSAGES

import os
Timothy J. Baek's avatar
Timothy J. Baek committed
14
from pathlib import Path
Timothy J. Baek's avatar
Timothy J. Baek committed
15

Timothy J. Baek's avatar
Timothy J. Baek committed
16
from config import DATA_DIR, CACHE_DIR
Timothy J. Baek's avatar
Timothy J. Baek committed
17

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

Timothy J. Baek's avatar
Timothy J. Baek committed
19
20
21
22
23
24
25
26
27
28
29
30
TOOLS_DIR = f"{DATA_DIR}/tools"
os.makedirs(TOOLS_DIR, exist_ok=True)


router = APIRouter()

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


@router.get("/", response_model=List[ToolResponse])
31
async def get_toolkits(user=Depends(get_verified_user)):
Timothy J. Baek's avatar
Timothy J. Baek committed
32
33
34
35
36
37
38
39
40
41
    toolkits = [toolkit for toolkit in Tools.get_tools()]
    return toolkits


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


@router.get("/export", response_model=List[ToolModel])
42
43
async def get_toolkits(user=Depends(get_admin_user)):
    toolkits = [toolkit for toolkit in Tools.get_tools()]
Timothy J. Baek's avatar
Timothy J. Baek committed
44
45
46
47
48
49
50
51
52
    return toolkits


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


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

66
    toolkit = Tools.get_tool_by_id(form_data.id)
67
    if toolkit is None:
Timothy J. Baek's avatar
Timothy J. Baek committed
68
69
70
71
72
        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)

73
74
            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
75
76

            TOOLS = request.app.state.TOOLS
Timothy J. Baek's avatar
Timothy J. Baek committed
77
78
79
            TOOLS[form_data.id] = toolkit_module

            specs = get_tools_specs(TOOLS[form_data.id])
80
            toolkit = Tools.insert_new_tool(user.id, form_data, specs)
Timothy J. Baek's avatar
Timothy J. Baek committed
81

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


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


Timothy J. Baek's avatar
Timothy J. Baek committed
110
@router.get("/id/{id}", response_model=Optional[ToolModel])
111
112
async def get_toolkit_by_id(id: str, user=Depends(get_admin_user)):
    toolkit = Tools.get_tool_by_id(id)
Timothy J. Baek's avatar
Timothy J. Baek committed
113
114

    if toolkit:
Timothy J. Baek's avatar
Timothy J. Baek committed
115
        return toolkit
Timothy J. Baek's avatar
Timothy J. Baek committed
116
117
118
119
120
121
122
    else:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=ERROR_MESSAGES.NOT_FOUND,
        )


123
124
125
126
127
128
129
############################
# UpdateToolkitById
############################


@router.post("/id/{id}/update", response_model=Optional[ToolModel])
async def update_toolkit_by_id(
130
131
132
133
    request: Request,
    id: str,
    form_data: ToolForm,
    user=Depends(get_admin_user),
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
):
    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)
155
        toolkit = Tools.update_tool_by_id(id, updated)
156
157
158
159
160
161
162
163
164
165
166
167

        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,
168
            detail=ERROR_MESSAGES.DEFAULT(str(e)),
169
170
171
172
173
174
175
176
177
        )


############################
# DeleteToolkitById
############################


@router.delete("/id/{id}/delete", response_model=bool)
178
async def delete_toolkit_by_id(request: Request, id: str, user=Depends(get_admin_user)):
179
    result = Tools.delete_tool_by_id(id)
180
181
182
183
184
185
186
187
188
189
190
191
192

    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


193
194
195
196
197
198
199
200
201
202
############################
# 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
203
204
            valves = Tools.get_tool_valves_by_id(id)
            return valves
205
206
207
        except Exception as e:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
208
                detail=ERROR_MESSAGES.DEFAULT(str(e)),
209
210
211
212
213
214
215
216
            )
    else:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=ERROR_MESSAGES.NOT_FOUND,
        )


Timothy J. Baek's avatar
Timothy J. Baek committed
217
218
219
220
221
222
223
224
225
226
227
228
229
230
############################
# 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:
231
            toolkit_module, _ = load_toolkit_module_by_id(id)
Timothy J. Baek's avatar
Timothy J. Baek committed
232
233
            request.app.state.TOOLS[id] = toolkit_module

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


245
246
247
248
249
250
251
############################
# 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
252
    request: Request, id: str, form_data: dict, user=Depends(get_admin_user)
253
254
255
):
    toolkit = Tools.get_tool_by_id(id)
    if toolkit:
Timothy J. Baek's avatar
Timothy J. Baek committed
256
257
258
        if id in request.app.state.TOOLS:
            toolkit_module = request.app.state.TOOLS[id]
        else:
259
            toolkit_module, _ = load_toolkit_module_by_id(id)
Timothy J. Baek's avatar
Timothy J. Baek committed
260
261
262
263
264
265
            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
266
                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
267
268
269
270
271
272
273
                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,
274
                    detail=ERROR_MESSAGES.DEFAULT(str(e)),
Timothy J. Baek's avatar
Timothy J. Baek committed
275
276
                )
        else:
277
            raise HTTPException(
Timothy J. Baek's avatar
Timothy J. Baek committed
278
279
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail=ERROR_MESSAGES.NOT_FOUND,
280
            )
Timothy J. Baek's avatar
Timothy J. Baek committed
281

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


Timothy J. Baek's avatar
Timothy J. Baek committed
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
############################
# 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,
304
                detail=ERROR_MESSAGES.DEFAULT(str(e)),
Timothy J. Baek's avatar
Timothy J. Baek committed
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
            )
    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:
322
            toolkit_module, _ = load_toolkit_module_by_id(id)
Timothy J. Baek's avatar
Timothy J. Baek committed
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
            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:
346
            toolkit_module, _ = load_toolkit_module_by_id(id)
Timothy J. Baek's avatar
Timothy J. Baek committed
347
348
349
350
351
352
            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
353
                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
354
355
356
357
358
359
360
361
362
                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,
363
                    detail=ERROR_MESSAGES.DEFAULT(str(e)),
Timothy J. Baek's avatar
Timothy J. Baek committed
364
365
366
367
368
369
370
371
372
373
374
                )
        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,
        )