tools.py 5.56 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
6
7
from sqlalchemy import String, Column, BigInteger
from sqlalchemy.orm import Session

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

import json
12
13
import copy

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

from config import SRC_LOG_LEVELS

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

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


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

28
29
30
31
32
33
34
35
36
    id = Column(String, primary_key=True)
    user_id = Column(String)
    name = Column(String)
    content = Column(String)
    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
37
38
39
40


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


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

54
55
    model_config = ConfigDict(from_attributes=True)

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

####################
# 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
78
79
80
81
class ToolValves(BaseModel):
    valves: Optional[dict] = None


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

    def insert_new_tool(
85
        self, user_id: str, form_data: ToolForm, specs: List[dict]
Timothy J. Baek's avatar
Timothy J. Baek committed
86
87
88
89
90
91
92
93
94
95
96
97
    ) -> Optional[ToolModel]:
        tool = ToolModel(
            **{
                **form_data.model_dump(),
                "specs": specs,
                "user_id": user_id,
                "updated_at": int(time.time()),
                "created_at": int(time.time()),
            }
        )

        try:
98
99
100
101
102
103
104
105
106
            with get_session() as db:
                result = Tool(**tool.model_dump())
                db.add(result)
                db.commit()
                db.refresh(result)
                if result:
                    return ToolModel.model_validate(result)
                else:
                    return None
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
107
108
        except Exception as e:
            print(f"Error creating tool: {e}")
Timothy J. Baek's avatar
Timothy J. Baek committed
109
110
            return None

111
    def get_tool_by_id(self, id: str) -> Optional[ToolModel]:
Timothy J. Baek's avatar
Timothy J. Baek committed
112
        try:
113
114
115
            with get_session() as db:
                tool = db.get(Tool, id)
                return ToolModel.model_validate(tool)
Timothy J. Baek's avatar
Timothy J. Baek committed
116
117
118
        except:
            return None

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

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
123
    def get_tool_valves_by_id(self, id: str) -> Optional[dict]:
Timothy J. Baek's avatar
Timothy J. Baek committed
124
        try:
125
126
127
            with get_session() as db:
                tool = db.get(Tool, id)
                return tool.valves if tool.valves else {}
Timothy J. Baek's avatar
Timothy J. Baek committed
128
129
130
131
132
133
        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:
134
135
136
137
138
139
            with get_session() 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)
Timothy J. Baek's avatar
Timothy J. Baek committed
140
141
142
        except:
            return None

Timothy J. Baek's avatar
Timothy J. Baek committed
143
144
145
146
147
    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)
148
            user_settings = user.settings.model_dump()
Timothy J. Baek's avatar
Timothy J. Baek committed
149
150

            # Check if user has "tools" and "valves" settings
151
152
153
154
            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
155

156
            return user_settings["tools"]["valves"].get(id, {})
Timothy J. Baek's avatar
Timothy J. Baek committed
157
158
159
160
161
162
163
164
165
        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)
166
            user_settings = user.settings.model_dump()
Timothy J. Baek's avatar
Timothy J. Baek committed
167
168

            # Check if user has "tools" and "valves" settings
169
170
171
172
            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
173

174
            user_settings["tools"]["valves"][id] = valves
Timothy J. Baek's avatar
Timothy J. Baek committed
175
176

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

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

Timothy J. Baek's avatar
Timothy J. Baek committed
184
185
    def update_tool_by_id(self, id: str, updated: dict) -> Optional[ToolModel]:
        try:
186
187
188
189
190
191
            with get_session() as db:
                db.query(Tool).filter_by(id=id).update(
                    {**updated, "updated_at": int(time.time())}
                )
                db.commit()
                return self.get_tool_by_id(id)
Timothy J. Baek's avatar
Timothy J. Baek committed
192
193
194
        except:
            return None

195
    def delete_tool_by_id(self, id: str) -> bool:
Timothy J. Baek's avatar
Timothy J. Baek committed
196
        try:
197
198
            with get_session() as db:
                db.query(Tool).filter_by(id=id).delete()
Timothy J. Baek's avatar
Timothy J. Baek committed
199
200
201
202
203
            return True
        except:
            return False


204
Tools = ToolsTable()