functions.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. from pydantic import BaseModel, ConfigDict
  2. from typing import List, Union, Optional
  3. import time
  4. import logging
  5. from sqlalchemy import Column, String, Text, BigInteger, Boolean
  6. from apps.webui.internal.db import JSONField, Base, Session
  7. from apps.webui.models.users import Users
  8. import json
  9. import copy
  10. from config import SRC_LOG_LEVELS
  11. log = logging.getLogger(__name__)
  12. log.setLevel(SRC_LOG_LEVELS["MODELS"])
  13. ####################
  14. # Functions DB Schema
  15. ####################
  16. class Function(Base):
  17. __tablename__ = "function"
  18. id = Column(String, primary_key=True)
  19. user_id = Column(String)
  20. name = Column(Text)
  21. type = Column(Text)
  22. content = Column(Text)
  23. meta = Column(JSONField)
  24. valves = Column(JSONField)
  25. is_active = Column(Boolean)
  26. updated_at = Column(BigInteger)
  27. created_at = Column(BigInteger)
  28. class FunctionMeta(BaseModel):
  29. description: Optional[str] = None
  30. manifest: Optional[dict] = {}
  31. class FunctionModel(BaseModel):
  32. id: str
  33. user_id: str
  34. name: str
  35. type: str
  36. content: str
  37. meta: FunctionMeta
  38. is_active: bool = False
  39. updated_at: int # timestamp in epoch
  40. created_at: int # timestamp in epoch
  41. model_config = ConfigDict(from_attributes=True)
  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 insert_new_function(
  63. self, user_id: str, type: str, form_data: FunctionForm
  64. ) -> Optional[FunctionModel]:
  65. function = FunctionModel(
  66. **{
  67. **form_data.model_dump(),
  68. "user_id": user_id,
  69. "type": type,
  70. "updated_at": int(time.time()),
  71. "created_at": int(time.time()),
  72. }
  73. )
  74. try:
  75. result = Function(**function.model_dump())
  76. Session.add(result)
  77. Session.commit()
  78. Session.refresh(result)
  79. if result:
  80. return FunctionModel.model_validate(result)
  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 = Session.get(Function, id)
  89. return FunctionModel.model_validate(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_validate(function)
  96. for function in Session.query(Function).filter_by(is_active=True).all()
  97. ]
  98. else:
  99. return [
  100. FunctionModel.model_validate(function)
  101. for function in Session.query(Function).all()
  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_validate(function)
  109. for function in Session.query(Function)
  110. .filter_by(type=type, is_active=True)
  111. .all()
  112. ]
  113. else:
  114. return [
  115. FunctionModel.model_validate(function)
  116. for function in Session.query(Function).filter_by(type=type).all()
  117. ]
  118. def get_function_valves_by_id(self, id: str) -> Optional[dict]:
  119. try:
  120. function = Session.get(Function, id)
  121. return function.valves if function.valves else {}
  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. function = Session.get(Function, id)
  130. function.valves = valves
  131. function.updated_at = int(time.time())
  132. Session.commit()
  133. Session.refresh(function)
  134. return self.get_function_by_id(id)
  135. except:
  136. return None
  137. def get_user_valves_by_id_and_user_id(
  138. self, id: str, user_id: str
  139. ) -> Optional[dict]:
  140. try:
  141. user = Users.get_user_by_id(user_id)
  142. user_settings = user.settings.model_dump()
  143. # Check if user has "functions" and "valves" settings
  144. if "functions" not in user_settings:
  145. user_settings["functions"] = {}
  146. if "valves" not in user_settings["functions"]:
  147. user_settings["functions"]["valves"] = {}
  148. return user_settings["functions"]["valves"].get(id, {})
  149. except Exception as e:
  150. print(f"An error occurred: {e}")
  151. return None
  152. def update_user_valves_by_id_and_user_id(
  153. self, id: str, user_id: str, valves: dict
  154. ) -> Optional[dict]:
  155. try:
  156. user = Users.get_user_by_id(user_id)
  157. user_settings = user.settings.model_dump()
  158. # Check if user has "functions" and "valves" settings
  159. if "functions" not in user_settings:
  160. user_settings["functions"] = {}
  161. if "valves" not in user_settings["functions"]:
  162. user_settings["functions"]["valves"] = {}
  163. user_settings["functions"]["valves"][id] = valves
  164. # Update the user settings in the database
  165. query = Users.update_user_by_id(user_id, {"settings": user_settings})
  166. query.execute()
  167. return user_settings["functions"]["valves"][id]
  168. except Exception as e:
  169. print(f"An error occurred: {e}")
  170. return None
  171. def update_function_by_id(self, id: str, updated: dict) -> Optional[FunctionModel]:
  172. try:
  173. Session.query(Function).filter_by(id=id).update(
  174. {
  175. **updated,
  176. "updated_at": int(time.time()),
  177. }
  178. )
  179. Session.commit()
  180. return self.get_function_by_id(id)
  181. except:
  182. return None
  183. def deactivate_all_functions(self) -> Optional[bool]:
  184. try:
  185. Session.query(Function).update(
  186. {
  187. "is_active": False,
  188. "updated_at": int(time.time()),
  189. }
  190. )
  191. Session.commit()
  192. return True
  193. except:
  194. return None
  195. def delete_function_by_id(self, id: str) -> bool:
  196. try:
  197. Session.query(Function).filter_by(id=id).delete()
  198. return True
  199. except:
  200. return False
  201. Functions = FunctionsTable()