tools.py 5.7 KB

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