tools.py 8.0 KB

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