functions.py 12 KB

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