functions.py 11 KB

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