functions.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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, get_db
  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. with get_db() as db:
  79. result = Function(**function.model_dump())
  80. db.add(result)
  81. db.commit()
  82. db.refresh(result)
  83. if result:
  84. return FunctionModel.model_validate(result)
  85. else:
  86. return None
  87. except Exception as e:
  88. print(f"Error creating tool: {e}")
  89. return None
  90. def get_function_by_id(self, id: str) -> Optional[FunctionModel]:
  91. try:
  92. with get_db() as db:
  93. function = db.get(Function, id)
  94. return FunctionModel.model_validate(function)
  95. except:
  96. return None
  97. def get_functions(self, active_only=False) -> List[FunctionModel]:
  98. with get_db() as db:
  99. if active_only:
  100. return [
  101. FunctionModel.model_validate(function)
  102. for function in db.query(Function).filter_by(is_active=True).all()
  103. ]
  104. else:
  105. return [
  106. FunctionModel.model_validate(function)
  107. for function in db.query(Function).all()
  108. ]
  109. def get_functions_by_type(
  110. self, type: str, active_only=False
  111. ) -> List[FunctionModel]:
  112. with get_db() as db:
  113. if active_only:
  114. return [
  115. FunctionModel.model_validate(function)
  116. for function in db.query(Function)
  117. .filter_by(type=type, is_active=True)
  118. .all()
  119. ]
  120. else:
  121. return [
  122. FunctionModel.model_validate(function)
  123. for function in db.query(Function).filter_by(type=type).all()
  124. ]
  125. def get_global_filter_functions(self) -> List[FunctionModel]:
  126. with get_db() as db:
  127. return [
  128. FunctionModel.model_validate(function)
  129. for function in db.query(Function)
  130. .filter_by(type="filter", is_active=True, is_global=True)
  131. .all()
  132. ]
  133. def get_function_valves_by_id(self, id: str) -> Optional[dict]:
  134. with get_db() as db:
  135. try:
  136. function = db.get(Function, id)
  137. return function.valves if function.valves else {}
  138. except Exception as e:
  139. print(f"An error occurred: {e}")
  140. return None
  141. def update_function_valves_by_id(
  142. self, id: str, valves: dict
  143. ) -> Optional[FunctionValves]:
  144. with get_db() as db:
  145. try:
  146. function = db.get(Function, id)
  147. function.valves = valves
  148. function.updated_at = int(time.time())
  149. db.commit()
  150. db.refresh(function)
  151. return self.get_function_by_id(id)
  152. except:
  153. return None
  154. def get_user_valves_by_id_and_user_id(
  155. self, id: str, user_id: str
  156. ) -> Optional[dict]:
  157. try:
  158. user = Users.get_user_by_id(user_id)
  159. user_settings = user.settings.model_dump() if user.settings else {}
  160. # Check if user has "functions" and "valves" settings
  161. if "functions" not in user_settings:
  162. user_settings["functions"] = {}
  163. if "valves" not in user_settings["functions"]:
  164. user_settings["functions"]["valves"] = {}
  165. return user_settings["functions"]["valves"].get(id, {})
  166. except Exception as e:
  167. print(f"An error occurred: {e}")
  168. return None
  169. def update_user_valves_by_id_and_user_id(
  170. self, id: str, user_id: str, valves: dict
  171. ) -> Optional[dict]:
  172. try:
  173. user = Users.get_user_by_id(user_id)
  174. user_settings = user.settings.model_dump() if user.settings else {}
  175. # Check if user has "functions" and "valves" settings
  176. if "functions" not in user_settings:
  177. user_settings["functions"] = {}
  178. if "valves" not in user_settings["functions"]:
  179. user_settings["functions"]["valves"] = {}
  180. user_settings["functions"]["valves"][id] = valves
  181. # Update the user settings in the database
  182. Users.update_user_by_id(user_id, {"settings": user_settings})
  183. return user_settings["functions"]["valves"][id]
  184. except Exception as e:
  185. print(f"An error occurred: {e}")
  186. return None
  187. def update_function_by_id(self, id: str, updated: dict) -> Optional[FunctionModel]:
  188. with get_db() as db:
  189. try:
  190. db.query(Function).filter_by(id=id).update(
  191. {
  192. **updated,
  193. "updated_at": int(time.time()),
  194. }
  195. )
  196. db.commit()
  197. return self.get_function_by_id(id)
  198. except:
  199. return None
  200. def deactivate_all_functions(self) -> Optional[bool]:
  201. with get_db() as db:
  202. try:
  203. db.query(Function).update(
  204. {
  205. "is_active": False,
  206. "updated_at": int(time.time()),
  207. }
  208. )
  209. db.commit()
  210. return True
  211. except:
  212. return None
  213. def delete_function_by_id(self, id: str) -> bool:
  214. with get_db() as db:
  215. try:
  216. db.query(Function).filter_by(id=id).delete()
  217. db.commit()
  218. return True
  219. except:
  220. return False
  221. Functions = FunctionsTable()