tools.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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
  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. log = logging.getLogger(__name__)
  10. log.setLevel(SRC_LOG_LEVELS["MODELS"])
  11. ####################
  12. # Tools DB Schema
  13. ####################
  14. class Tool(Base):
  15. __tablename__ = "tool"
  16. id = Column(String, primary_key=True)
  17. user_id = Column(String)
  18. name = Column(Text)
  19. content = Column(Text)
  20. specs = Column(JSONField)
  21. meta = Column(JSONField)
  22. valves = Column(JSONField)
  23. access_control = Column(JSON, nullable=True) # Controls data access levels.
  24. # Defines access control rules for this entry.
  25. # - `None`: Public access, available to all users with the "user" role.
  26. # - `{}`: Private access, restricted exclusively to the owner.
  27. # - Custom permissions: Specific access control for reading and writing;
  28. # Can specify group or user-level restrictions:
  29. # {
  30. # "read": {
  31. # "group_ids": ["group_id1", "group_id2"],
  32. # "user_ids": ["user_id1", "user_id2"]
  33. # },
  34. # "write": {
  35. # "group_ids": ["group_id1", "group_id2"],
  36. # "user_ids": ["user_id1", "user_id2"]
  37. # }
  38. # }
  39. updated_at = Column(BigInteger)
  40. created_at = Column(BigInteger)
  41. class ToolMeta(BaseModel):
  42. description: Optional[str] = None
  43. manifest: Optional[dict] = {}
  44. class ToolModel(BaseModel):
  45. id: str
  46. user_id: str
  47. name: str
  48. content: str
  49. specs: list[dict]
  50. meta: ToolMeta
  51. access_control: Optional[dict] = None
  52. updated_at: int # timestamp in epoch
  53. created_at: int # timestamp in epoch
  54. model_config = ConfigDict(from_attributes=True)
  55. ####################
  56. # Forms
  57. ####################
  58. class ToolResponse(BaseModel):
  59. id: str
  60. user_id: str
  61. name: str
  62. meta: ToolMeta
  63. updated_at: int # timestamp in epoch
  64. created_at: int # timestamp in epoch
  65. class ToolForm(BaseModel):
  66. id: str
  67. name: str
  68. content: str
  69. meta: ToolMeta
  70. class ToolValves(BaseModel):
  71. valves: Optional[dict] = None
  72. class ToolsTable:
  73. def insert_new_tool(
  74. self, user_id: str, form_data: ToolForm, specs: list[dict]
  75. ) -> Optional[ToolModel]:
  76. with get_db() as db:
  77. tool = ToolModel(
  78. **{
  79. **form_data.model_dump(),
  80. "specs": specs,
  81. "user_id": user_id,
  82. "updated_at": int(time.time()),
  83. "created_at": int(time.time()),
  84. }
  85. )
  86. try:
  87. result = Tool(**tool.model_dump())
  88. db.add(result)
  89. db.commit()
  90. db.refresh(result)
  91. if result:
  92. return ToolModel.model_validate(result)
  93. else:
  94. return None
  95. except Exception as e:
  96. print(f"Error creating tool: {e}")
  97. return None
  98. def get_tool_by_id(self, id: str) -> Optional[ToolModel]:
  99. try:
  100. with get_db() as db:
  101. tool = db.get(Tool, id)
  102. return ToolModel.model_validate(tool)
  103. except Exception:
  104. return None
  105. def get_tools(self) -> list[ToolModel]:
  106. with get_db() as db:
  107. return [ToolModel.model_validate(tool) for tool in db.query(Tool).all()]
  108. def get_tool_valves_by_id(self, id: str) -> Optional[dict]:
  109. try:
  110. with get_db() as db:
  111. tool = db.get(Tool, id)
  112. return tool.valves if tool.valves else {}
  113. except Exception as e:
  114. print(f"An error occurred: {e}")
  115. return None
  116. def update_tool_valves_by_id(self, id: str, valves: dict) -> Optional[ToolValves]:
  117. try:
  118. with get_db() as db:
  119. db.query(Tool).filter_by(id=id).update(
  120. {"valves": valves, "updated_at": int(time.time())}
  121. )
  122. db.commit()
  123. return self.get_tool_by_id(id)
  124. except Exception:
  125. return None
  126. def get_user_valves_by_id_and_user_id(
  127. self, id: str, user_id: str
  128. ) -> Optional[dict]:
  129. try:
  130. user = Users.get_user_by_id(user_id)
  131. user_settings = user.settings.model_dump() if user.settings else {}
  132. # Check if user has "tools" and "valves" settings
  133. if "tools" not in user_settings:
  134. user_settings["tools"] = {}
  135. if "valves" not in user_settings["tools"]:
  136. user_settings["tools"]["valves"] = {}
  137. return user_settings["tools"]["valves"].get(id, {})
  138. except Exception as e:
  139. print(f"An error occurred: {e}")
  140. return None
  141. def update_user_valves_by_id_and_user_id(
  142. self, id: str, user_id: str, valves: dict
  143. ) -> Optional[dict]:
  144. try:
  145. user = Users.get_user_by_id(user_id)
  146. user_settings = user.settings.model_dump() if user.settings else {}
  147. # Check if user has "tools" and "valves" settings
  148. if "tools" not in user_settings:
  149. user_settings["tools"] = {}
  150. if "valves" not in user_settings["tools"]:
  151. user_settings["tools"]["valves"] = {}
  152. user_settings["tools"]["valves"][id] = valves
  153. # Update the user settings in the database
  154. Users.update_user_by_id(user_id, {"settings": user_settings})
  155. return user_settings["tools"]["valves"][id]
  156. except Exception as e:
  157. print(f"An error occurred: {e}")
  158. return None
  159. def update_tool_by_id(self, id: str, updated: dict) -> Optional[ToolModel]:
  160. try:
  161. with get_db() as db:
  162. db.query(Tool).filter_by(id=id).update(
  163. {**updated, "updated_at": int(time.time())}
  164. )
  165. db.commit()
  166. tool = db.query(Tool).get(id)
  167. db.refresh(tool)
  168. return ToolModel.model_validate(tool)
  169. except Exception:
  170. return None
  171. def delete_tool_by_id(self, id: str) -> bool:
  172. try:
  173. with get_db() as db:
  174. db.query(Tool).filter_by(id=id).delete()
  175. db.commit()
  176. return True
  177. except Exception:
  178. return False
  179. Tools = ToolsTable()