functions.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. import logging
  2. import time
  3. from typing import Optional
  4. from open_webui.apps.webui.internal.db import Base, JSONField, get_db
  5. from open_webui.apps.webui.models.users import Users
  6. from open_webui.env import SRC_LOG_LEVELS
  7. from pydantic import BaseModel, ConfigDict
  8. from sqlalchemy import BigInteger, Boolean, Column, String, Text
  9. log = logging.getLogger(__name__)
  10. log.setLevel(SRC_LOG_LEVELS["MODELS"])
  11. ####################
  12. # Functions DB Schema
  13. ####################
  14. class Function(Base):
  15. __tablename__ = "function"
  16. id = Column(String, primary_key=True)
  17. user_id = Column(String)
  18. name = Column(Text)
  19. type = Column(Text)
  20. content = Column(Text)
  21. meta = Column(JSONField)
  22. valves = Column(JSONField)
  23. is_active = Column(Boolean)
  24. is_global = Column(Boolean)
  25. updated_at = Column(BigInteger)
  26. created_at = Column(BigInteger)
  27. class FunctionMeta(BaseModel):
  28. description: Optional[str] = None
  29. manifest: Optional[dict] = {}
  30. class FunctionModel(BaseModel):
  31. id: str
  32. user_id: str
  33. name: str
  34. type: str
  35. content: str
  36. meta: FunctionMeta
  37. is_active: bool = False
  38. is_global: 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. is_global: 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_db() 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_db() as db:
  91. function = db.get(Function, id)
  92. return FunctionModel.model_validate(function)
  93. except Exception:
  94. return None
  95. def get_functions(self, active_only=False) -> list[FunctionModel]:
  96. with get_db() as db:
  97. if active_only:
  98. return [
  99. FunctionModel.model_validate(function)
  100. for function in db.query(Function).filter_by(is_active=True).all()
  101. ]
  102. else:
  103. return [
  104. FunctionModel.model_validate(function)
  105. for function in db.query(Function).all()
  106. ]
  107. def get_functions_by_type(
  108. self, type: str, active_only=False
  109. ) -> list[FunctionModel]:
  110. with get_db() as db:
  111. if active_only:
  112. return [
  113. FunctionModel.model_validate(function)
  114. for function in db.query(Function)
  115. .filter_by(type=type, is_active=True)
  116. .all()
  117. ]
  118. else:
  119. return [
  120. FunctionModel.model_validate(function)
  121. for function in db.query(Function).filter_by(type=type).all()
  122. ]
  123. def get_global_filter_functions(self) -> list[FunctionModel]:
  124. with get_db() as db:
  125. return [
  126. FunctionModel.model_validate(function)
  127. for function in db.query(Function)
  128. .filter_by(type="filter", is_active=True, is_global=True)
  129. .all()
  130. ]
  131. def get_global_action_functions(self) -> list[FunctionModel]:
  132. with get_db() as db:
  133. return [
  134. FunctionModel.model_validate(function)
  135. for function in db.query(Function)
  136. .filter_by(type="action", is_active=True, is_global=True)
  137. .all()
  138. ]
  139. def get_function_valves_by_id(self, id: str) -> Optional[dict]:
  140. with get_db() as db:
  141. try:
  142. function = db.get(Function, id)
  143. return function.valves if function.valves else {}
  144. except Exception as e:
  145. print(f"An error occurred: {e}")
  146. return None
  147. def update_function_valves_by_id(
  148. self, id: str, valves: dict
  149. ) -> Optional[FunctionValves]:
  150. with get_db() as db:
  151. try:
  152. function = db.get(Function, id)
  153. function.valves = valves
  154. function.updated_at = int(time.time())
  155. db.commit()
  156. db.refresh(function)
  157. return self.get_function_by_id(id)
  158. except Exception:
  159. return None
  160. def get_user_valves_by_id_and_user_id(
  161. self, id: str, user_id: str
  162. ) -> Optional[dict]:
  163. try:
  164. user = Users.get_user_by_id(user_id)
  165. user_settings = user.settings.model_dump() if user.settings else {}
  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. return user_settings["functions"]["valves"].get(id, {})
  172. except Exception as e:
  173. print(f"An error occurred: {e}")
  174. return None
  175. def update_user_valves_by_id_and_user_id(
  176. self, id: str, user_id: str, valves: dict
  177. ) -> Optional[dict]:
  178. try:
  179. user = Users.get_user_by_id(user_id)
  180. user_settings = user.settings.model_dump() if user.settings else {}
  181. # Check if user has "functions" and "valves" settings
  182. if "functions" not in user_settings:
  183. user_settings["functions"] = {}
  184. if "valves" not in user_settings["functions"]:
  185. user_settings["functions"]["valves"] = {}
  186. user_settings["functions"]["valves"][id] = valves
  187. # Update the user settings in the database
  188. Users.update_user_by_id(user_id, {"settings": user_settings})
  189. return user_settings["functions"]["valves"][id]
  190. except Exception as e:
  191. print(f"An error occurred: {e}")
  192. return None
  193. def update_function_by_id(self, id: str, updated: dict) -> Optional[FunctionModel]:
  194. with get_db() as db:
  195. try:
  196. db.query(Function).filter_by(id=id).update(
  197. {
  198. **updated,
  199. "updated_at": int(time.time()),
  200. }
  201. )
  202. db.commit()
  203. return self.get_function_by_id(id)
  204. except Exception:
  205. return None
  206. def deactivate_all_functions(self) -> Optional[bool]:
  207. with get_db() as db:
  208. try:
  209. db.query(Function).update(
  210. {
  211. "is_active": False,
  212. "updated_at": int(time.time()),
  213. }
  214. )
  215. db.commit()
  216. return True
  217. except Exception:
  218. return None
  219. def delete_function_by_id(self, id: str) -> bool:
  220. with get_db() as db:
  221. try:
  222. db.query(Function).filter_by(id=id).delete()
  223. db.commit()
  224. return True
  225. except Exception:
  226. return False
  227. Functions = FunctionsTable()