tools.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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, UserResponse
  6. from open_webui.models.groups import Groups
  7. from open_webui.env import SRC_LOG_LEVELS
  8. from pydantic import BaseModel, ConfigDict
  9. from sqlalchemy import BigInteger, Column, String, Text, JSON
  10. from open_webui.utils.access_control import has_access
  11. log = logging.getLogger(__name__)
  12. log.setLevel(SRC_LOG_LEVELS["MODELS"])
  13. ####################
  14. # Tools DB Schema
  15. ####################
  16. class Tool(Base):
  17. __tablename__ = "tool"
  18. id = Column(String, primary_key=True)
  19. user_id = Column(String)
  20. name = Column(Text)
  21. content = Column(Text)
  22. specs = Column(JSONField)
  23. meta = Column(JSONField)
  24. valves = Column(JSONField)
  25. access_control = Column(JSON, nullable=True) # Controls data access levels.
  26. # Defines access control rules for this entry.
  27. # - `None`: Public access, available to all users with the "user" role.
  28. # - `{}`: Private access, restricted exclusively to the owner.
  29. # - Custom permissions: Specific access control for reading and writing;
  30. # Can specify group or user-level restrictions:
  31. # {
  32. # "read": {
  33. # "group_ids": ["group_id1", "group_id2"],
  34. # "user_ids": ["user_id1", "user_id2"]
  35. # },
  36. # "write": {
  37. # "group_ids": ["group_id1", "group_id2"],
  38. # "user_ids": ["user_id1", "user_id2"]
  39. # }
  40. # }
  41. updated_at = Column(BigInteger)
  42. created_at = Column(BigInteger)
  43. class ToolMeta(BaseModel):
  44. description: Optional[str] = None
  45. manifest: Optional[dict] = {}
  46. class ToolModel(BaseModel):
  47. id: str
  48. user_id: str
  49. name: str
  50. content: str
  51. specs: list[dict]
  52. meta: ToolMeta
  53. access_control: Optional[dict] = None
  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 ToolUserModel(ToolModel):
  61. user: Optional[UserResponse] = None
  62. class ToolResponse(BaseModel):
  63. id: str
  64. user_id: str
  65. name: str
  66. meta: ToolMeta
  67. access_control: Optional[dict] = None
  68. updated_at: int # timestamp in epoch
  69. created_at: int # timestamp in epoch
  70. class ToolUserResponse(ToolResponse):
  71. user: Optional[UserResponse] = None
  72. class ToolForm(BaseModel):
  73. id: str
  74. name: str
  75. content: str
  76. meta: ToolMeta
  77. access_control: Optional[dict] = None
  78. class ToolValves(BaseModel):
  79. valves: Optional[dict] = None
  80. class ToolsTable:
  81. def insert_new_tool(
  82. self, user_id: str, form_data: ToolForm, specs: list[dict]
  83. ) -> Optional[ToolModel]:
  84. with get_db() as db:
  85. tool = ToolModel(
  86. **{
  87. **form_data.model_dump(),
  88. "specs": specs,
  89. "user_id": user_id,
  90. "updated_at": int(time.time()),
  91. "created_at": int(time.time()),
  92. }
  93. )
  94. try:
  95. result = Tool(**tool.model_dump())
  96. db.add(result)
  97. db.commit()
  98. db.refresh(result)
  99. if result:
  100. return ToolModel.model_validate(result)
  101. else:
  102. return None
  103. except Exception as e:
  104. log.exception(f"Error creating a new tool: {e}")
  105. return None
  106. def get_tool_by_id(self, id: str) -> Optional[ToolModel]:
  107. try:
  108. with get_db() as db:
  109. tool = db.get(Tool, id)
  110. return ToolModel.model_validate(tool)
  111. except Exception:
  112. return None
  113. def get_tools(self) -> list[ToolUserModel]:
  114. with get_db() as db:
  115. all_tools = db.query(Tool).order_by(Tool.updated_at.desc()).all()
  116. user_ids = list(set(tool.user_id for tool in all_tools))
  117. users = Users.get_users_by_user_ids(user_ids) if user_ids else []
  118. users_dict = {user.id: user for user in users}
  119. tools = []
  120. for tool in all_tools:
  121. user = users_dict.get(tool.user_id)
  122. tools.append(
  123. ToolUserModel.model_validate(
  124. {
  125. **ToolModel.model_validate(tool).model_dump(),
  126. "user": user.model_dump() if user else None,
  127. }
  128. )
  129. )
  130. return tools
  131. def get_tools_by_user_id(
  132. self, user_id: str, permission: str = "write"
  133. ) -> list[ToolUserModel]:
  134. tools = self.get_tools()
  135. user_group_ids = {group.id for group in Groups.get_groups_by_member_id(user_id)}
  136. return [
  137. tool
  138. for tool in tools
  139. if tool.user_id == user_id
  140. or has_access(user_id, permission, tool.access_control, user_group_ids)
  141. ]
  142. def get_tool_valves_by_id(self, id: str) -> Optional[dict]:
  143. try:
  144. with get_db() as db:
  145. tool = db.get(Tool, id)
  146. return tool.valves if tool.valves else {}
  147. except Exception as e:
  148. log.exception(f"Error getting tool valves by id {id}")
  149. return None
  150. def update_tool_valves_by_id(self, id: str, valves: dict) -> Optional[ToolValves]:
  151. try:
  152. with get_db() as db:
  153. db.query(Tool).filter_by(id=id).update(
  154. {"valves": valves, "updated_at": int(time.time())}
  155. )
  156. db.commit()
  157. return self.get_tool_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 "tools" and "valves" settings
  167. if "tools" not in user_settings:
  168. user_settings["tools"] = {}
  169. if "valves" not in user_settings["tools"]:
  170. user_settings["tools"]["valves"] = {}
  171. return user_settings["tools"]["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 "tools" and "valves" settings
  184. if "tools" not in user_settings:
  185. user_settings["tools"] = {}
  186. if "valves" not in user_settings["tools"]:
  187. user_settings["tools"]["valves"] = {}
  188. user_settings["tools"]["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["tools"]["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_tool_by_id(self, id: str, updated: dict) -> Optional[ToolModel]:
  198. try:
  199. with get_db() as db:
  200. db.query(Tool).filter_by(id=id).update(
  201. {**updated, "updated_at": int(time.time())}
  202. )
  203. db.commit()
  204. tool = db.query(Tool).get(id)
  205. db.refresh(tool)
  206. return ToolModel.model_validate(tool)
  207. except Exception:
  208. return None
  209. def delete_tool_by_id(self, id: str) -> bool:
  210. try:
  211. with get_db() as db:
  212. db.query(Tool).filter_by(id=id).delete()
  213. db.commit()
  214. return True
  215. except Exception:
  216. return False
  217. Tools = ToolsTable()