functions.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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. is_global = Column(Boolean)
  27. updated_at = Column(BigInteger)
  28. created_at = Column(BigInteger)
  29. class FunctionMeta(BaseModel):
  30. description: Optional[str] = None
  31. manifest: Optional[dict] = {}
  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. is_global: bool = False
  41. updated_at: int # timestamp in epoch
  42. created_at: int # timestamp in epoch
  43. model_config = ConfigDict(from_attributes=True)
  44. ####################
  45. # Forms
  46. ####################
  47. class FunctionResponse(BaseModel):
  48. id: str
  49. user_id: str
  50. type: str
  51. name: str
  52. meta: FunctionMeta
  53. is_active: bool
  54. is_global: bool
  55. updated_at: int # timestamp in epoch
  56. created_at: int # timestamp in epoch
  57. class FunctionForm(BaseModel):
  58. id: str
  59. name: str
  60. content: str
  61. meta: FunctionMeta
  62. class FunctionValves(BaseModel):
  63. valves: Optional[dict] = None
  64. class FunctionsTable:
  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(**function.model_dump())
  79. Session.add(result)
  80. Session.commit()
  81. Session.refresh(result)
  82. if result:
  83. return FunctionModel.model_validate(result)
  84. else:
  85. return None
  86. except Exception as e:
  87. print(f"Error creating tool: {e}")
  88. return None
  89. def get_function_by_id(self, id: str) -> Optional[FunctionModel]:
  90. try:
  91. function = Session.get(Function, id)
  92. return FunctionModel.model_validate(function)
  93. except:
  94. return None
  95. def get_functions(self, active_only=False) -> List[FunctionModel]:
  96. if active_only:
  97. return [
  98. FunctionModel.model_validate(function)
  99. for function in Session.query(Function).filter_by(is_active=True).all()
  100. ]
  101. else:
  102. return [
  103. FunctionModel.model_validate(function)
  104. for function in Session.query(Function).all()
  105. ]
  106. def get_functions_by_type(
  107. self, type: str, active_only=False
  108. ) -> List[FunctionModel]:
  109. if active_only:
  110. return [
  111. FunctionModel.model_validate(function)
  112. for function in Session.query(Function)
  113. .filter_by(type=type, is_active=True)
  114. .all()
  115. ]
  116. else:
  117. return [
  118. FunctionModel.model_validate(function)
  119. for function in Session.query(Function).filter_by(type=type).all()
  120. ]
  121. def get_global_filter_functions(self) -> List[FunctionModel]:
  122. return [
  123. FunctionModel.model_validate(function)
  124. for function in Session.query(Function)
  125. .filter_by(type="filter", is_active=True, is_global=True)
  126. .all()
  127. ]
  128. def get_function_valves_by_id(self, id: str) -> Optional[dict]:
  129. try:
  130. function = Session.get(Function, id)
  131. return function.valves if function.valves else {}
  132. except Exception as e:
  133. print(f"An error occurred: {e}")
  134. return None
  135. def update_function_valves_by_id(
  136. self, id: str, valves: dict
  137. ) -> Optional[FunctionValves]:
  138. try:
  139. function = Session.get(Function, id)
  140. function.valves = valves
  141. function.updated_at = int(time.time())
  142. Session.commit()
  143. Session.refresh(function)
  144. return self.get_function_by_id(id)
  145. except:
  146. return None
  147. def get_user_valves_by_id_and_user_id(
  148. self, id: str, user_id: str
  149. ) -> Optional[dict]:
  150. try:
  151. user = Users.get_user_by_id(user_id)
  152. user_settings = user.settings.model_dump()
  153. # Check if user has "functions" and "valves" settings
  154. if "functions" not in user_settings:
  155. user_settings["functions"] = {}
  156. if "valves" not in user_settings["functions"]:
  157. user_settings["functions"]["valves"] = {}
  158. return user_settings["functions"]["valves"].get(id, {})
  159. except Exception as e:
  160. print(f"An error occurred: {e}")
  161. return None
  162. def update_user_valves_by_id_and_user_id(
  163. self, id: str, user_id: str, valves: dict
  164. ) -> Optional[dict]:
  165. try:
  166. user = Users.get_user_by_id(user_id)
  167. user_settings = user.settings.model_dump()
  168. # Check if user has "functions" and "valves" settings
  169. if "functions" not in user_settings:
  170. user_settings["functions"] = {}
  171. if "valves" not in user_settings["functions"]:
  172. user_settings["functions"]["valves"] = {}
  173. user_settings["functions"]["valves"][id] = valves
  174. # Update the user settings in the database
  175. Users.update_user_by_id(user_id, {"settings": user_settings})
  176. return user_settings["functions"]["valves"][id]
  177. except Exception as e:
  178. print(f"An error occurred: {e}")
  179. return None
  180. def update_function_by_id(self, id: str, updated: dict) -> Optional[FunctionModel]:
  181. try:
  182. Session.query(Function).filter_by(id=id).update(
  183. {
  184. **updated,
  185. "updated_at": int(time.time()),
  186. }
  187. )
  188. Session.commit()
  189. return self.get_function_by_id(id)
  190. except:
  191. return None
  192. def deactivate_all_functions(self) -> Optional[bool]:
  193. try:
  194. Session.query(Function).update(
  195. {
  196. "is_active": False,
  197. "updated_at": int(time.time()),
  198. }
  199. )
  200. Session.commit()
  201. return True
  202. except:
  203. return None
  204. def delete_function_by_id(self, id: str) -> bool:
  205. try:
  206. Session.query(Function).filter_by(id=id).delete()
  207. return True
  208. except:
  209. return False
  210. Functions = FunctionsTable()