tools.py 5.74 KB
Newer Older
1
2
from pydantic import BaseModel, ConfigDict
from typing import List, Optional
Timothy J. Baek's avatar
Timothy J. Baek committed
3
4
import time
import logging
5
from sqlalchemy import String, Column, BigInteger, Text
6

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
7
from apps.webui.internal.db import Base, JSONField, get_db
Timothy J. Baek's avatar
Timothy J. Baek committed
8
from apps.webui.models.users import Users
Timothy J. Baek's avatar
Timothy J. Baek committed
9
10

import json
11
12
import copy

Timothy J. Baek's avatar
Timothy J. Baek committed
13
14
15
16
17
18
19
20
21
22
23

from config import SRC_LOG_LEVELS

log = logging.getLogger(__name__)
log.setLevel(SRC_LOG_LEVELS["MODELS"])

####################
# Tools DB Schema
####################


24
25
class Tool(Base):
    __tablename__ = "tool"
Timothy J. Baek's avatar
Timothy J. Baek committed
26

27
28
    id = Column(String, primary_key=True)
    user_id = Column(String)
29
30
    name = Column(Text)
    content = Column(Text)
31
32
33
34
35
    specs = Column(JSONField)
    meta = Column(JSONField)
    valves = Column(JSONField)
    updated_at = Column(BigInteger)
    created_at = Column(BigInteger)
Timothy J. Baek's avatar
Timothy J. Baek committed
36
37
38
39


class ToolMeta(BaseModel):
    description: Optional[str] = None
40
    manifest: Optional[dict] = {}
Timothy J. Baek's avatar
Timothy J. Baek committed
41
42
43
44
45
46
47


class ToolModel(BaseModel):
    id: str
    user_id: str
    name: str
    content: str
Timothy J. Baek's avatar
Timothy J. Baek committed
48
    specs: List[dict]
Timothy J. Baek's avatar
Timothy J. Baek committed
49
50
51
52
    meta: ToolMeta
    updated_at: int  # timestamp in epoch
    created_at: int  # timestamp in epoch

53
54
    model_config = ConfigDict(from_attributes=True)

Timothy J. Baek's avatar
Timothy J. Baek committed
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76

####################
# Forms
####################


class ToolResponse(BaseModel):
    id: str
    user_id: str
    name: str
    meta: ToolMeta
    updated_at: int  # timestamp in epoch
    created_at: int  # timestamp in epoch


class ToolForm(BaseModel):
    id: str
    name: str
    content: str
    meta: ToolMeta


Timothy J. Baek's avatar
Timothy J. Baek committed
77
78
79
80
class ToolValves(BaseModel):
    valves: Optional[dict] = None


Timothy J. Baek's avatar
Timothy J. Baek committed
81
82
83
class ToolsTable:

    def insert_new_tool(
84
        self, user_id: str, form_data: ToolForm, specs: List[dict]
Timothy J. Baek's avatar
Timothy J. Baek committed
85
86
    ) -> Optional[ToolModel]:

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
        with get_db() as db:

            tool = ToolModel(
                **{
                    **form_data.model_dump(),
                    "specs": specs,
                    "user_id": user_id,
                    "updated_at": int(time.time()),
                    "created_at": int(time.time()),
                }
            )

            try:
                result = Tool(**tool.model_dump())
                db.add(result)
                db.commit()
                db.refresh(result)
                if result:
                    return ToolModel.model_validate(result)
                else:
                    return None
            except Exception as e:
                print(f"Error creating tool: {e}")
110
                return None
Timothy J. Baek's avatar
Timothy J. Baek committed
111

112
    def get_tool_by_id(self, id: str) -> Optional[ToolModel]:
Timothy J. Baek's avatar
Timothy J. Baek committed
113
        try:
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
114
115
116
117
            with get_db() as db:

                tool = db.get(Tool, id)
                return ToolModel.model_validate(tool)
118
        except Exception:
Timothy J. Baek's avatar
Timothy J. Baek committed
119
120
            return None

121
    def get_tools(self) -> List[ToolModel]:
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
122
123
        with get_db() as db:
            return [ToolModel.model_validate(tool) for tool in db.query(Tool).all()]
Timothy J. Baek's avatar
Timothy J. Baek committed
124

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
125
    def get_tool_valves_by_id(self, id: str) -> Optional[dict]:
Timothy J. Baek's avatar
Timothy J. Baek committed
126
        try:
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
127
128
129
130
            with get_db() as db:

                tool = db.get(Tool, id)
                return tool.valves if tool.valves else {}
Timothy J. Baek's avatar
Timothy J. Baek committed
131
132
133
134
135
136
        except Exception as e:
            print(f"An error occurred: {e}")
            return None

    def update_tool_valves_by_id(self, id: str, valves: dict) -> Optional[ToolValves]:
        try:
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
137
138
139
140
141
142
143
            with get_db() as db:

                db.query(Tool).filter_by(id=id).update(
                    {"valves": valves, "updated_at": int(time.time())}
                )
                db.commit()
                return self.get_tool_by_id(id)
144
        except Exception:
Timothy J. Baek's avatar
Timothy J. Baek committed
145
146
            return None

Timothy J. Baek's avatar
Timothy J. Baek committed
147
148
149
150
151
    def get_user_valves_by_id_and_user_id(
        self, id: str, user_id: str
    ) -> Optional[dict]:
        try:
            user = Users.get_user_by_id(user_id)
Timothy J. Baek's avatar
Timothy J. Baek committed
152
            user_settings = user.settings.model_dump() if user.settings else {}
Timothy J. Baek's avatar
Timothy J. Baek committed
153
154

            # Check if user has "tools" and "valves" settings
155
156
157
158
            if "tools" not in user_settings:
                user_settings["tools"] = {}
            if "valves" not in user_settings["tools"]:
                user_settings["tools"]["valves"] = {}
Timothy J. Baek's avatar
Timothy J. Baek committed
159

160
            return user_settings["tools"]["valves"].get(id, {})
Timothy J. Baek's avatar
Timothy J. Baek committed
161
162
163
164
165
166
167
168
169
        except Exception as e:
            print(f"An error occurred: {e}")
            return None

    def update_user_valves_by_id_and_user_id(
        self, id: str, user_id: str, valves: dict
    ) -> Optional[dict]:
        try:
            user = Users.get_user_by_id(user_id)
Timothy J. Baek's avatar
Timothy J. Baek committed
170
            user_settings = user.settings.model_dump() if user.settings else {}
Timothy J. Baek's avatar
Timothy J. Baek committed
171
172

            # Check if user has "tools" and "valves" settings
173
174
175
176
            if "tools" not in user_settings:
                user_settings["tools"] = {}
            if "valves" not in user_settings["tools"]:
                user_settings["tools"]["valves"] = {}
Timothy J. Baek's avatar
Timothy J. Baek committed
177

178
            user_settings["tools"]["valves"][id] = valves
Timothy J. Baek's avatar
Timothy J. Baek committed
179
180

            # Update the user settings in the database
181
            Users.update_user_by_id(user_id, {"settings": user_settings})
Timothy J. Baek's avatar
Timothy J. Baek committed
182

183
            return user_settings["tools"]["valves"][id]
Timothy J. Baek's avatar
Timothy J. Baek committed
184
185
186
187
        except Exception as e:
            print(f"An error occurred: {e}")
            return None

Timothy J. Baek's avatar
Timothy J. Baek committed
188
189
    def update_tool_by_id(self, id: str, updated: dict) -> Optional[ToolModel]:
        try:
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
190
            with get_db() as db:
Timothy J. Baek's avatar
Timothy J. Baek committed
191
192
193
                db.query(Tool).filter_by(id=id).update(
                    {**updated, "updated_at": int(time.time())}
                )
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
194
                db.commit()
Timothy J. Baek's avatar
Timothy J. Baek committed
195
196

                tool = db.query(Tool).get(id)
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
197
198
                db.refresh(tool)
                return ToolModel.model_validate(tool)
199
        except Exception:
Timothy J. Baek's avatar
Timothy J. Baek committed
200
201
            return None

202
    def delete_tool_by_id(self, id: str) -> bool:
Timothy J. Baek's avatar
Timothy J. Baek committed
203
        try:
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
204
205
            with get_db() as db:
                db.query(Tool).filter_by(id=id).delete()
Timothy J. Baek's avatar
Timothy J. Baek committed
206
207
                db.commit()

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
208
                return True
209
        except Exception:
Timothy J. Baek's avatar
Timothy J. Baek committed
210
211
212
            return False


213
Tools = ToolsTable()