functions.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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_to_dict(function))
  124. for function in Function.select().where(
  125. Function.type == "filter",
  126. Function.is_active == True,
  127. Function.is_global == True,
  128. )
  129. ]
  130. def get_function_valves_by_id(self, id: str) -> Optional[dict]:
  131. try:
  132. function = Session.get(Function, id)
  133. return function.valves if function.valves else {}
  134. except Exception as e:
  135. print(f"An error occurred: {e}")
  136. return None
  137. def update_function_valves_by_id(
  138. self, id: str, valves: dict
  139. ) -> Optional[FunctionValves]:
  140. try:
  141. function = Session.get(Function, id)
  142. function.valves = valves
  143. function.updated_at = int(time.time())
  144. Session.commit()
  145. Session.refresh(function)
  146. return self.get_function_by_id(id)
  147. except:
  148. return None
  149. def get_user_valves_by_id_and_user_id(
  150. self, id: str, user_id: str
  151. ) -> Optional[dict]:
  152. try:
  153. user = Users.get_user_by_id(user_id)
  154. user_settings = user.settings.model_dump()
  155. # Check if user has "functions" and "valves" settings
  156. if "functions" not in user_settings:
  157. user_settings["functions"] = {}
  158. if "valves" not in user_settings["functions"]:
  159. user_settings["functions"]["valves"] = {}
  160. return user_settings["functions"]["valves"].get(id, {})
  161. except Exception as e:
  162. print(f"An error occurred: {e}")
  163. return None
  164. def update_user_valves_by_id_and_user_id(
  165. self, id: str, user_id: str, valves: dict
  166. ) -> Optional[dict]:
  167. try:
  168. user = Users.get_user_by_id(user_id)
  169. user_settings = user.settings.model_dump()
  170. # Check if user has "functions" and "valves" settings
  171. if "functions" not in user_settings:
  172. user_settings["functions"] = {}
  173. if "valves" not in user_settings["functions"]:
  174. user_settings["functions"]["valves"] = {}
  175. user_settings["functions"]["valves"][id] = valves
  176. # Update the user settings in the database
  177. query = Users.update_user_by_id(user_id, {"settings": user_settings})
  178. query.execute()
  179. return user_settings["functions"]["valves"][id]
  180. except Exception as e:
  181. print(f"An error occurred: {e}")
  182. return None
  183. def update_function_by_id(self, id: str, updated: dict) -> Optional[FunctionModel]:
  184. try:
  185. Session.query(Function).filter_by(id=id).update(
  186. {
  187. **updated,
  188. "updated_at": int(time.time()),
  189. }
  190. )
  191. Session.commit()
  192. return self.get_function_by_id(id)
  193. except:
  194. return None
  195. def deactivate_all_functions(self) -> Optional[bool]:
  196. try:
  197. Session.query(Function).update(
  198. {
  199. "is_active": False,
  200. "updated_at": int(time.time()),
  201. }
  202. )
  203. Session.commit()
  204. return True
  205. except:
  206. return None
  207. def delete_function_by_id(self, id: str) -> bool:
  208. try:
  209. Session.query(Function).filter_by(id=id).delete()
  210. return True
  211. except:
  212. return False
  213. Functions = FunctionsTable()