tools.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. import logging
  2. import time
  3. from typing import Optional
  4. from open_webui.apps.webui.internal.db import Base, JSONField, get_db
  5. from open_webui.apps.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 ToolResponse(BaseModel):
  60. id: str
  61. user_id: str
  62. name: str
  63. meta: ToolMeta
  64. access_control: Optional[dict] = None
  65. updated_at: int # timestamp in epoch
  66. created_at: int # timestamp in epoch
  67. class ToolUserResponse(ToolResponse):
  68. user: Optional[UserResponse] = None
  69. class ToolForm(BaseModel):
  70. id: str
  71. name: str
  72. content: str
  73. meta: ToolMeta
  74. access_control: Optional[dict] = None
  75. class ToolValves(BaseModel):
  76. valves: Optional[dict] = None
  77. class ToolsTable:
  78. def insert_new_tool(
  79. self, user_id: str, form_data: ToolForm, specs: list[dict]
  80. ) -> Optional[ToolModel]:
  81. with get_db() as db:
  82. tool = ToolModel(
  83. **{
  84. **form_data.model_dump(),
  85. "specs": specs,
  86. "user_id": user_id,
  87. "updated_at": int(time.time()),
  88. "created_at": int(time.time()),
  89. }
  90. )
  91. try:
  92. result = Tool(**tool.model_dump())
  93. db.add(result)
  94. db.commit()
  95. db.refresh(result)
  96. if result:
  97. return ToolModel.model_validate(result)
  98. else:
  99. return None
  100. except Exception as e:
  101. print(f"Error creating tool: {e}")
  102. return None
  103. def get_tool_by_id(self, id: str) -> Optional[ToolModel]:
  104. try:
  105. with get_db() as db:
  106. tool = db.get(Tool, id)
  107. return ToolModel.model_validate(tool)
  108. except Exception:
  109. return None
  110. def get_tools(self) -> list[ToolUserResponse]:
  111. with get_db() as db:
  112. return [
  113. ToolUserResponse.model_validate(
  114. {
  115. **ToolModel.model_validate(tool).model_dump(),
  116. "user": Users.get_user_by_id(tool.user_id).model_dump(),
  117. }
  118. )
  119. for tool in db.query(Tool).order_by(Tool.updated_at.desc()).all()
  120. ]
  121. def get_tools_by_user_id(
  122. self, user_id: str, permission: str = "write"
  123. ) -> list[ToolUserResponse]:
  124. tools = self.get_tools()
  125. return [
  126. tool
  127. for tool in tools
  128. if tool.user_id == user_id
  129. or has_access(user_id, permission, tool.access_control)
  130. ]
  131. def get_tool_valves_by_id(self, id: str) -> Optional[dict]:
  132. try:
  133. with get_db() as db:
  134. tool = db.get(Tool, id)
  135. return tool.valves if tool.valves else {}
  136. except Exception as e:
  137. print(f"An error occurred: {e}")
  138. return None
  139. def update_tool_valves_by_id(self, id: str, valves: dict) -> Optional[ToolValves]:
  140. try:
  141. with get_db() as db:
  142. db.query(Tool).filter_by(id=id).update(
  143. {"valves": valves, "updated_at": int(time.time())}
  144. )
  145. db.commit()
  146. return self.get_tool_by_id(id)
  147. except Exception:
  148. return None
  149. def get_user_valves_by_id_and_user_id(
  150. self, id: str, user_id: str
  151. ) -> Optional[dict]:
  152. try:
  153. user = Users.get_user_by_id(user_id)
  154. user_settings = user.settings.model_dump() if user.settings else {}
  155. # Check if user has "tools" and "valves" settings
  156. if "tools" not in user_settings:
  157. user_settings["tools"] = {}
  158. if "valves" not in user_settings["tools"]:
  159. user_settings["tools"]["valves"] = {}
  160. return user_settings["tools"]["valves"].get(id, {})
  161. except Exception as e:
  162. print(f"An error occurred: {e}")
  163. return None
  164. def update_user_valves_by_id_and_user_id(
  165. self, id: str, user_id: str, valves: dict
  166. ) -> Optional[dict]:
  167. try:
  168. user = Users.get_user_by_id(user_id)
  169. user_settings = user.settings.model_dump() if user.settings else {}
  170. # Check if user has "tools" and "valves" settings
  171. if "tools" not in user_settings:
  172. user_settings["tools"] = {}
  173. if "valves" not in user_settings["tools"]:
  174. user_settings["tools"]["valves"] = {}
  175. user_settings["tools"]["valves"][id] = valves
  176. # Update the user settings in the database
  177. Users.update_user_by_id(user_id, {"settings": user_settings})
  178. return user_settings["tools"]["valves"][id]
  179. except Exception as e:
  180. print(f"An error occurred: {e}")
  181. return None
  182. def update_tool_by_id(self, id: str, updated: dict) -> Optional[ToolModel]:
  183. try:
  184. with get_db() as db:
  185. db.query(Tool).filter_by(id=id).update(
  186. {**updated, "updated_at": int(time.time())}
  187. )
  188. db.commit()
  189. tool = db.query(Tool).get(id)
  190. db.refresh(tool)
  191. return ToolModel.model_validate(tool)
  192. except Exception:
  193. return None
  194. def delete_tool_by_id(self, id: str) -> bool:
  195. try:
  196. with get_db() as db:
  197. db.query(Tool).filter_by(id=id).delete()
  198. db.commit()
  199. return True
  200. except Exception:
  201. return False
  202. Tools = ToolsTable()