tools.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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. model_config = ConfigDict(extra="allow")
  73. class ToolForm(BaseModel):
  74. id: str
  75. name: str
  76. content: str
  77. meta: ToolMeta
  78. access_control: Optional[dict] = None
  79. class ToolValves(BaseModel):
  80. valves: Optional[dict] = None
  81. class ToolsTable:
  82. def insert_new_tool(
  83. self, user_id: str, form_data: ToolForm, specs: list[dict]
  84. ) -> Optional[ToolModel]:
  85. with get_db() as db:
  86. tool = ToolModel(
  87. **{
  88. **form_data.model_dump(),
  89. "specs": specs,
  90. "user_id": user_id,
  91. "updated_at": int(time.time()),
  92. "created_at": int(time.time()),
  93. }
  94. )
  95. try:
  96. result = Tool(**tool.model_dump())
  97. db.add(result)
  98. db.commit()
  99. db.refresh(result)
  100. if result:
  101. return ToolModel.model_validate(result)
  102. else:
  103. return None
  104. except Exception as e:
  105. log.exception(f"Error creating a new tool: {e}")
  106. return None
  107. def get_tool_by_id(self, id: str) -> Optional[ToolModel]:
  108. try:
  109. with get_db() as db:
  110. tool = db.get(Tool, id)
  111. return ToolModel.model_validate(tool)
  112. except Exception:
  113. return None
  114. def get_tools(self) -> list[ToolUserModel]:
  115. with get_db() as db:
  116. all_tools = db.query(Tool).order_by(Tool.updated_at.desc()).all()
  117. user_ids = list(set(tool.user_id for tool in all_tools))
  118. users = Users.get_users_by_user_ids(user_ids) if user_ids else []
  119. users_dict = {user.id: user for user in users}
  120. tools = []
  121. for tool in all_tools:
  122. user = users_dict.get(tool.user_id)
  123. tools.append(
  124. ToolUserModel.model_validate(
  125. {
  126. **ToolModel.model_validate(tool).model_dump(),
  127. "user": user.model_dump() if user else None,
  128. }
  129. )
  130. )
  131. return tools
  132. def get_tools_by_user_id(
  133. self, user_id: str, permission: str = "write"
  134. ) -> list[ToolUserModel]:
  135. tools = self.get_tools()
  136. user_group_ids = {group.id for group in Groups.get_groups_by_member_id(user_id)}
  137. return [
  138. tool
  139. for tool in tools
  140. if tool.user_id == user_id
  141. or has_access(user_id, permission, tool.access_control, user_group_ids)
  142. ]
  143. def get_tool_valves_by_id(self, id: str) -> Optional[dict]:
  144. try:
  145. with get_db() as db:
  146. tool = db.get(Tool, id)
  147. return tool.valves if tool.valves else {}
  148. except Exception as e:
  149. log.exception(f"Error getting tool valves by id {id}")
  150. return None
  151. def update_tool_valves_by_id(self, id: str, valves: dict) -> Optional[ToolValves]:
  152. try:
  153. with get_db() as db:
  154. db.query(Tool).filter_by(id=id).update(
  155. {"valves": valves, "updated_at": int(time.time())}
  156. )
  157. db.commit()
  158. return self.get_tool_by_id(id)
  159. except Exception:
  160. return None
  161. def get_user_valves_by_id_and_user_id(
  162. self, id: str, user_id: str
  163. ) -> Optional[dict]:
  164. try:
  165. user = Users.get_user_by_id(user_id)
  166. user_settings = user.settings.model_dump() if user.settings else {}
  167. # Check if user has "tools" and "valves" settings
  168. if "tools" not in user_settings:
  169. user_settings["tools"] = {}
  170. if "valves" not in user_settings["tools"]:
  171. user_settings["tools"]["valves"] = {}
  172. return user_settings["tools"]["valves"].get(id, {})
  173. except Exception as e:
  174. log.exception(
  175. f"Error getting user values by id {id} and user_id {user_id}: {e}"
  176. )
  177. return None
  178. def update_user_valves_by_id_and_user_id(
  179. self, id: str, user_id: str, valves: dict
  180. ) -> Optional[dict]:
  181. try:
  182. user = Users.get_user_by_id(user_id)
  183. user_settings = user.settings.model_dump() if user.settings else {}
  184. # Check if user has "tools" and "valves" settings
  185. if "tools" not in user_settings:
  186. user_settings["tools"] = {}
  187. if "valves" not in user_settings["tools"]:
  188. user_settings["tools"]["valves"] = {}
  189. user_settings["tools"]["valves"][id] = valves
  190. # Update the user settings in the database
  191. Users.update_user_by_id(user_id, {"settings": user_settings})
  192. return user_settings["tools"]["valves"][id]
  193. except Exception as e:
  194. log.exception(
  195. f"Error updating user valves by id {id} and user_id {user_id}: {e}"
  196. )
  197. return None
  198. def update_tool_by_id(self, id: str, updated: dict) -> Optional[ToolModel]:
  199. try:
  200. with get_db() as db:
  201. db.query(Tool).filter_by(id=id).update(
  202. {**updated, "updated_at": int(time.time())}
  203. )
  204. db.commit()
  205. tool = db.query(Tool).get(id)
  206. db.refresh(tool)
  207. return ToolModel.model_validate(tool)
  208. except Exception:
  209. return None
  210. def delete_tool_by_id(self, id: str) -> bool:
  211. try:
  212. with get_db() as db:
  213. db.query(Tool).filter_by(id=id).delete()
  214. db.commit()
  215. return True
  216. except Exception:
  217. return False
  218. Tools = ToolsTable()