functions.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. import logging
  2. import time
  3. from typing import Optional
  4. from open_webui.internal.db import Base, JSONField, get_db
  5. from open_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. log.exception(f"Error creating a new function: {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. log.exception(f"Error getting function valves by id {id}: {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. log.exception(
  174. f"Error getting user values by id {id} and user id {user_id}: {e}"
  175. )
  176. return None
  177. def update_user_valves_by_id_and_user_id(
  178. self, id: str, user_id: str, valves: dict
  179. ) -> Optional[dict]:
  180. try:
  181. user = Users.get_user_by_id(user_id)
  182. user_settings = user.settings.model_dump() if user.settings else {}
  183. # Check if user has "functions" and "valves" settings
  184. if "functions" not in user_settings:
  185. user_settings["functions"] = {}
  186. if "valves" not in user_settings["functions"]:
  187. user_settings["functions"]["valves"] = {}
  188. user_settings["functions"]["valves"][id] = valves
  189. # Update the user settings in the database
  190. Users.update_user_by_id(user_id, {"settings": user_settings})
  191. return user_settings["functions"]["valves"][id]
  192. except Exception as e:
  193. log.exception(
  194. f"Error updating user valves by id {id} and user_id {user_id}: {e}"
  195. )
  196. return None
  197. def update_function_by_id(self, id: str, updated: dict) -> Optional[FunctionModel]:
  198. with get_db() as db:
  199. try:
  200. db.query(Function).filter_by(id=id).update(
  201. {
  202. **updated,
  203. "updated_at": int(time.time()),
  204. }
  205. )
  206. db.commit()
  207. return self.get_function_by_id(id)
  208. except Exception:
  209. return None
  210. def deactivate_all_functions(self) -> Optional[bool]:
  211. with get_db() as db:
  212. try:
  213. db.query(Function).update(
  214. {
  215. "is_active": False,
  216. "updated_at": int(time.time()),
  217. }
  218. )
  219. db.commit()
  220. return True
  221. except Exception:
  222. return None
  223. def delete_function_by_id(self, id: str) -> bool:
  224. with get_db() as db:
  225. try:
  226. db.query(Function).filter_by(id=id).delete()
  227. db.commit()
  228. return True
  229. except Exception:
  230. return False
  231. Functions = FunctionsTable()