functions.py 7.3 KB

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