functions.py 13 KB

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