1
0

functions.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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, Index
  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. __table_args__ = (Index("is_global_idx", "is_global"),)
  28. class FunctionMeta(BaseModel):
  29. description: Optional[str] = None
  30. manifest: Optional[dict] = {}
  31. class FunctionModel(BaseModel):
  32. id: str
  33. user_id: str
  34. name: str
  35. type: str
  36. content: str
  37. meta: FunctionMeta
  38. is_active: bool = False
  39. is_global: 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. is_global: bool
  54. updated_at: int # timestamp in epoch
  55. created_at: int # timestamp in epoch
  56. class FunctionForm(BaseModel):
  57. id: str
  58. name: str
  59. content: str
  60. meta: FunctionMeta
  61. class FunctionValves(BaseModel):
  62. valves: Optional[dict] = None
  63. class FunctionsTable:
  64. def insert_new_function(
  65. self, user_id: str, type: str, form_data: FunctionForm
  66. ) -> Optional[FunctionModel]:
  67. function = FunctionModel(
  68. **{
  69. **form_data.model_dump(),
  70. "user_id": user_id,
  71. "type": type,
  72. "updated_at": int(time.time()),
  73. "created_at": int(time.time()),
  74. }
  75. )
  76. try:
  77. with get_db() as db:
  78. result = Function(**function.model_dump())
  79. db.add(result)
  80. db.commit()
  81. db.refresh(result)
  82. if result:
  83. return FunctionModel.model_validate(result)
  84. else:
  85. return None
  86. except Exception as e:
  87. log.exception(f"Error creating a new function: {e}")
  88. return None
  89. def sync_functions(
  90. self, user_id: str, functions: list[FunctionModel]
  91. ) -> list[FunctionModel]:
  92. # Synchronize functions for a user by updating existing ones, inserting new ones, and removing those that are no longer present.
  93. try:
  94. with get_db() as db:
  95. # Get existing functions
  96. existing_functions = db.query(Function).all()
  97. existing_ids = {func.id for func in existing_functions}
  98. # Prepare a set of new function IDs
  99. new_function_ids = {func.id for func in functions}
  100. # Update or insert functions
  101. for func in functions:
  102. if func.id in existing_ids:
  103. db.query(Function).filter_by(id=func.id).update(
  104. {
  105. **func.model_dump(),
  106. "user_id": user_id,
  107. "updated_at": int(time.time()),
  108. }
  109. )
  110. else:
  111. new_func = Function(
  112. **{
  113. **func.model_dump(),
  114. "user_id": user_id,
  115. "updated_at": int(time.time()),
  116. }
  117. )
  118. db.add(new_func)
  119. # Remove functions that are no longer present
  120. for func in existing_functions:
  121. if func.id not in new_function_ids:
  122. db.delete(func)
  123. db.commit()
  124. return [
  125. FunctionModel.model_validate(func)
  126. for func in db.query(Function).all()
  127. ]
  128. except Exception as e:
  129. log.exception(f"Error syncing functions for user {user_id}: {e}")
  130. return []
  131. def get_function_by_id(self, id: str) -> Optional[FunctionModel]:
  132. try:
  133. with get_db() as db:
  134. function = db.get(Function, id)
  135. return FunctionModel.model_validate(function)
  136. except Exception:
  137. return None
  138. def get_functions(self, active_only=False) -> list[FunctionModel]:
  139. with get_db() as db:
  140. if active_only:
  141. return [
  142. FunctionModel.model_validate(function)
  143. for function in db.query(Function).filter_by(is_active=True).all()
  144. ]
  145. else:
  146. return [
  147. FunctionModel.model_validate(function)
  148. for function in db.query(Function).all()
  149. ]
  150. def get_functions_by_type(
  151. self, type: str, active_only=False
  152. ) -> list[FunctionModel]:
  153. with get_db() as db:
  154. if active_only:
  155. return [
  156. FunctionModel.model_validate(function)
  157. for function in db.query(Function)
  158. .filter_by(type=type, is_active=True)
  159. .all()
  160. ]
  161. else:
  162. return [
  163. FunctionModel.model_validate(function)
  164. for function in db.query(Function).filter_by(type=type).all()
  165. ]
  166. def get_global_filter_functions(self) -> list[FunctionModel]:
  167. with get_db() as db:
  168. return [
  169. FunctionModel.model_validate(function)
  170. for function in db.query(Function)
  171. .filter_by(type="filter", is_active=True, is_global=True)
  172. .all()
  173. ]
  174. def get_global_action_functions(self) -> list[FunctionModel]:
  175. with get_db() as db:
  176. return [
  177. FunctionModel.model_validate(function)
  178. for function in db.query(Function)
  179. .filter_by(type="action", is_active=True, is_global=True)
  180. .all()
  181. ]
  182. def get_function_valves_by_id(self, id: str) -> Optional[dict]:
  183. with get_db() as db:
  184. try:
  185. function = db.get(Function, id)
  186. return function.valves if function.valves else {}
  187. except Exception as e:
  188. log.exception(f"Error getting function valves by id {id}: {e}")
  189. return None
  190. def update_function_valves_by_id(
  191. self, id: str, valves: dict
  192. ) -> Optional[FunctionValves]:
  193. with get_db() as db:
  194. try:
  195. function = db.get(Function, id)
  196. function.valves = valves
  197. function.updated_at = int(time.time())
  198. db.commit()
  199. db.refresh(function)
  200. return self.get_function_by_id(id)
  201. except Exception:
  202. return None
  203. def get_user_valves_by_id_and_user_id(
  204. self, id: str, user_id: str
  205. ) -> Optional[dict]:
  206. try:
  207. user = Users.get_user_by_id(user_id)
  208. user_settings = user.settings.model_dump() if user.settings else {}
  209. # Check if user has "functions" and "valves" settings
  210. if "functions" not in user_settings:
  211. user_settings["functions"] = {}
  212. if "valves" not in user_settings["functions"]:
  213. user_settings["functions"]["valves"] = {}
  214. return user_settings["functions"]["valves"].get(id, {})
  215. except Exception as e:
  216. log.exception(
  217. f"Error getting user values by id {id} and user id {user_id}: {e}"
  218. )
  219. return None
  220. def update_user_valves_by_id_and_user_id(
  221. self, id: str, user_id: str, valves: dict
  222. ) -> Optional[dict]:
  223. try:
  224. user = Users.get_user_by_id(user_id)
  225. user_settings = user.settings.model_dump() if user.settings else {}
  226. # Check if user has "functions" and "valves" settings
  227. if "functions" not in user_settings:
  228. user_settings["functions"] = {}
  229. if "valves" not in user_settings["functions"]:
  230. user_settings["functions"]["valves"] = {}
  231. user_settings["functions"]["valves"][id] = valves
  232. # Update the user settings in the database
  233. Users.update_user_by_id(user_id, {"settings": user_settings})
  234. return user_settings["functions"]["valves"][id]
  235. except Exception as e:
  236. log.exception(
  237. f"Error updating user valves by id {id} and user_id {user_id}: {e}"
  238. )
  239. return None
  240. def update_function_by_id(self, id: str, updated: dict) -> Optional[FunctionModel]:
  241. with get_db() as db:
  242. try:
  243. db.query(Function).filter_by(id=id).update(
  244. {
  245. **updated,
  246. "updated_at": int(time.time()),
  247. }
  248. )
  249. db.commit()
  250. return self.get_function_by_id(id)
  251. except Exception:
  252. return None
  253. def deactivate_all_functions(self) -> Optional[bool]:
  254. with get_db() as db:
  255. try:
  256. db.query(Function).update(
  257. {
  258. "is_active": False,
  259. "updated_at": int(time.time()),
  260. }
  261. )
  262. db.commit()
  263. return True
  264. except Exception:
  265. return None
  266. def delete_function_by_id(self, id: str) -> bool:
  267. with get_db() as db:
  268. try:
  269. db.query(Function).filter_by(id=id).delete()
  270. db.commit()
  271. return True
  272. except Exception:
  273. return False
  274. Functions = FunctionsTable()