tools.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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. # NULL for public access (open to all users with "user" role).
  25. # {} for individual access (private to the owner).
  26. # {"group_ids": ["group_id1", "group_id2"]} for access restricted to specific groups.
  27. # {"user_ids": ["user_id1", "user_id2"]} for access restricted to specific users.
  28. updated_at = Column(BigInteger)
  29. created_at = Column(BigInteger)
  30. class ToolMeta(BaseModel):
  31. description: Optional[str] = None
  32. manifest: Optional[dict] = {}
  33. class ToolModel(BaseModel):
  34. id: str
  35. user_id: str
  36. name: str
  37. content: str
  38. specs: list[dict]
  39. meta: ToolMeta
  40. access_control = Optional[dict] = None
  41. updated_at: int # timestamp in epoch
  42. created_at: int # timestamp in epoch
  43. model_config = ConfigDict(from_attributes=True)
  44. ####################
  45. # Forms
  46. ####################
  47. class ToolResponse(BaseModel):
  48. id: str
  49. user_id: str
  50. name: str
  51. meta: ToolMeta
  52. updated_at: int # timestamp in epoch
  53. created_at: int # timestamp in epoch
  54. class ToolForm(BaseModel):
  55. id: str
  56. name: str
  57. content: str
  58. meta: ToolMeta
  59. class ToolValves(BaseModel):
  60. valves: Optional[dict] = None
  61. class ToolsTable:
  62. def insert_new_tool(
  63. self, user_id: str, form_data: ToolForm, specs: list[dict]
  64. ) -> Optional[ToolModel]:
  65. with get_db() as db:
  66. tool = ToolModel(
  67. **{
  68. **form_data.model_dump(),
  69. "specs": specs,
  70. "user_id": user_id,
  71. "updated_at": int(time.time()),
  72. "created_at": int(time.time()),
  73. }
  74. )
  75. try:
  76. result = Tool(**tool.model_dump())
  77. db.add(result)
  78. db.commit()
  79. db.refresh(result)
  80. if result:
  81. return ToolModel.model_validate(result)
  82. else:
  83. return None
  84. except Exception as e:
  85. print(f"Error creating tool: {e}")
  86. return None
  87. def get_tool_by_id(self, id: str) -> Optional[ToolModel]:
  88. try:
  89. with get_db() as db:
  90. tool = db.get(Tool, id)
  91. return ToolModel.model_validate(tool)
  92. except Exception:
  93. return None
  94. def get_tools(self) -> list[ToolModel]:
  95. with get_db() as db:
  96. return [ToolModel.model_validate(tool) for tool in db.query(Tool).all()]
  97. def get_tool_valves_by_id(self, id: str) -> Optional[dict]:
  98. try:
  99. with get_db() as db:
  100. tool = db.get(Tool, id)
  101. return tool.valves if tool.valves else {}
  102. except Exception as e:
  103. print(f"An error occurred: {e}")
  104. return None
  105. def update_tool_valves_by_id(self, id: str, valves: dict) -> Optional[ToolValves]:
  106. try:
  107. with get_db() as db:
  108. db.query(Tool).filter_by(id=id).update(
  109. {"valves": valves, "updated_at": int(time.time())}
  110. )
  111. db.commit()
  112. return self.get_tool_by_id(id)
  113. except Exception:
  114. return None
  115. def get_user_valves_by_id_and_user_id(
  116. self, id: str, user_id: str
  117. ) -> Optional[dict]:
  118. try:
  119. user = Users.get_user_by_id(user_id)
  120. user_settings = user.settings.model_dump() if user.settings else {}
  121. # Check if user has "tools" and "valves" settings
  122. if "tools" not in user_settings:
  123. user_settings["tools"] = {}
  124. if "valves" not in user_settings["tools"]:
  125. user_settings["tools"]["valves"] = {}
  126. return user_settings["tools"]["valves"].get(id, {})
  127. except Exception as e:
  128. print(f"An error occurred: {e}")
  129. return None
  130. def update_user_valves_by_id_and_user_id(
  131. self, id: str, user_id: str, valves: dict
  132. ) -> Optional[dict]:
  133. try:
  134. user = Users.get_user_by_id(user_id)
  135. user_settings = user.settings.model_dump() if user.settings else {}
  136. # Check if user has "tools" and "valves" settings
  137. if "tools" not in user_settings:
  138. user_settings["tools"] = {}
  139. if "valves" not in user_settings["tools"]:
  140. user_settings["tools"]["valves"] = {}
  141. user_settings["tools"]["valves"][id] = valves
  142. # Update the user settings in the database
  143. Users.update_user_by_id(user_id, {"settings": user_settings})
  144. return user_settings["tools"]["valves"][id]
  145. except Exception as e:
  146. print(f"An error occurred: {e}")
  147. return None
  148. def update_tool_by_id(self, id: str, updated: dict) -> Optional[ToolModel]:
  149. try:
  150. with get_db() as db:
  151. db.query(Tool).filter_by(id=id).update(
  152. {**updated, "updated_at": int(time.time())}
  153. )
  154. db.commit()
  155. tool = db.query(Tool).get(id)
  156. db.refresh(tool)
  157. return ToolModel.model_validate(tool)
  158. except Exception:
  159. return None
  160. def delete_tool_by_id(self, id: str) -> bool:
  161. try:
  162. with get_db() as db:
  163. db.query(Tool).filter_by(id=id).delete()
  164. db.commit()
  165. return True
  166. except Exception:
  167. return False
  168. Tools = ToolsTable()