functions.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. from pydantic import BaseModel
  2. from peewee import *
  3. from playhouse.shortcuts import model_to_dict
  4. from typing import List, Union, Optional
  5. import time
  6. import logging
  7. from apps.webui.internal.db import DB, JSONField
  8. from apps.webui.models.users import Users
  9. import json
  10. import copy
  11. from config import SRC_LOG_LEVELS
  12. log = logging.getLogger(__name__)
  13. log.setLevel(SRC_LOG_LEVELS["MODELS"])
  14. ####################
  15. # Functions DB Schema
  16. ####################
  17. class Function(Model):
  18. id = CharField(unique=True)
  19. user_id = CharField()
  20. name = TextField()
  21. type = TextField()
  22. content = TextField()
  23. meta = JSONField()
  24. valves = JSONField()
  25. is_active = BooleanField(default=False)
  26. updated_at = BigIntegerField()
  27. created_at = BigIntegerField()
  28. class Meta:
  29. database = DB
  30. class FunctionMeta(BaseModel):
  31. description: Optional[str] = None
  32. class FunctionModel(BaseModel):
  33. id: str
  34. user_id: str
  35. name: str
  36. type: str
  37. content: str
  38. meta: FunctionMeta
  39. is_active: bool = False
  40. updated_at: int # timestamp in epoch
  41. created_at: int # timestamp in epoch
  42. ####################
  43. # Forms
  44. ####################
  45. class FunctionResponse(BaseModel):
  46. id: str
  47. user_id: str
  48. type: str
  49. name: str
  50. meta: FunctionMeta
  51. is_active: bool
  52. updated_at: int # timestamp in epoch
  53. created_at: int # timestamp in epoch
  54. class FunctionForm(BaseModel):
  55. id: str
  56. name: str
  57. content: str
  58. meta: FunctionMeta
  59. class FunctionValves(BaseModel):
  60. valves: Optional[dict] = None
  61. class FunctionsTable:
  62. def __init__(self, db):
  63. self.db = db
  64. self.db.create_tables([Function])
  65. def insert_new_function(
  66. self, user_id: str, type: str, form_data: FunctionForm
  67. ) -> Optional[FunctionModel]:
  68. function = FunctionModel(
  69. **{
  70. **form_data.model_dump(),
  71. "user_id": user_id,
  72. "type": type,
  73. "updated_at": int(time.time()),
  74. "created_at": int(time.time()),
  75. }
  76. )
  77. try:
  78. result = Function.create(**function.model_dump())
  79. if result:
  80. return function
  81. else:
  82. return None
  83. except Exception as e:
  84. print(f"Error creating tool: {e}")
  85. return None
  86. def get_function_by_id(self, id: str) -> Optional[FunctionModel]:
  87. try:
  88. function = Function.get(Function.id == id)
  89. return FunctionModel(**model_to_dict(function))
  90. except:
  91. return None
  92. def get_functions(self, active_only=False) -> List[FunctionModel]:
  93. if active_only:
  94. return [
  95. FunctionModel(**model_to_dict(function))
  96. for function in Function.select().where(Function.is_active == True)
  97. ]
  98. else:
  99. return [
  100. FunctionModel(**model_to_dict(function))
  101. for function in Function.select()
  102. ]
  103. def get_functions_by_type(
  104. self, type: str, active_only=False
  105. ) -> List[FunctionModel]:
  106. if active_only:
  107. return [
  108. FunctionModel(**model_to_dict(function))
  109. for function in Function.select().where(
  110. Function.type == type, Function.is_active == True
  111. )
  112. ]
  113. else:
  114. return [
  115. FunctionModel(**model_to_dict(function))
  116. for function in Function.select().where(Function.type == type)
  117. ]
  118. def get_function_valves_by_id(self, id: str) -> Optional[FunctionValves]:
  119. try:
  120. function = Function.get(Function.id == id)
  121. return FunctionValves(**model_to_dict(function))
  122. except Exception as e:
  123. print(f"An error occurred: {e}")
  124. return None
  125. def update_function_valves_by_id(
  126. self, id: str, valves: dict
  127. ) -> Optional[FunctionValves]:
  128. try:
  129. query = Function.update(
  130. **{"valves": valves},
  131. updated_at=int(time.time()),
  132. ).where(Function.id == id)
  133. query.execute()
  134. function = Function.get(Function.id == id)
  135. return FunctionValves(**model_to_dict(function))
  136. except:
  137. return None
  138. def get_user_valves_by_id_and_user_id(
  139. self, id: str, user_id: str
  140. ) -> Optional[dict]:
  141. try:
  142. user = Users.get_user_by_id(user_id)
  143. user_settings = user.settings.model_dump()
  144. # Check if user has "functions" and "valves" settings
  145. if "functions" not in user_settings:
  146. user_settings["functions"] = {}
  147. if "valves" not in user_settings["functions"]:
  148. user_settings["functions"]["valves"] = {}
  149. return user_settings["functions"]["valves"].get(id, {})
  150. except Exception as e:
  151. print(f"An error occurred: {e}")
  152. return None
  153. def update_user_valves_by_id_and_user_id(
  154. self, id: str, user_id: str, valves: dict
  155. ) -> Optional[dict]:
  156. try:
  157. user = Users.get_user_by_id(user_id)
  158. user_settings = user.settings.model_dump()
  159. # Check if user has "functions" and "valves" settings
  160. if "functions" not in user_settings:
  161. user_settings["functions"] = {}
  162. if "valves" not in user_settings["functions"]:
  163. user_settings["functions"]["valves"] = {}
  164. user_settings["functions"]["valves"][id] = valves
  165. # Update the user settings in the database
  166. query = Users.update_user_by_id(user_id, {"settings": user_settings})
  167. query.execute()
  168. return user_settings["functions"]["valves"][id]
  169. except Exception as e:
  170. print(f"An error occurred: {e}")
  171. return None
  172. def update_function_by_id(self, id: str, updated: dict) -> Optional[FunctionModel]:
  173. try:
  174. query = Function.update(
  175. **updated,
  176. updated_at=int(time.time()),
  177. ).where(Function.id == id)
  178. query.execute()
  179. function = Function.get(Function.id == id)
  180. return FunctionModel(**model_to_dict(function))
  181. except:
  182. return None
  183. def delete_function_by_id(self, id: str) -> bool:
  184. try:
  185. query = Function.delete().where((Function.id == id))
  186. query.execute() # Remove the rows, return number of rows removed.
  187. return True
  188. except:
  189. return False
  190. Functions = FunctionsTable(DB)