plugin.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. import os
  2. import re
  3. import subprocess
  4. import sys
  5. from importlib import util
  6. import types
  7. import tempfile
  8. import logging
  9. from open_webui.env import SRC_LOG_LEVELS, PIP_OPTIONS, PIP_PACKAGE_INDEX_OPTIONS
  10. from open_webui.models.functions import Functions
  11. from open_webui.models.tools import Tools
  12. log = logging.getLogger(__name__)
  13. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  14. def extract_frontmatter(content):
  15. """
  16. Extract frontmatter as a dictionary from the provided content string.
  17. """
  18. frontmatter = {}
  19. frontmatter_started = False
  20. frontmatter_ended = False
  21. frontmatter_pattern = re.compile(r"^\s*([a-z_]+):\s*(.*)\s*$", re.IGNORECASE)
  22. try:
  23. lines = content.splitlines()
  24. if len(lines) < 1 or lines[0].strip() != '"""':
  25. # The content doesn't start with triple quotes
  26. return {}
  27. frontmatter_started = True
  28. for line in lines[1:]:
  29. if '"""' in line:
  30. if frontmatter_started:
  31. frontmatter_ended = True
  32. break
  33. if frontmatter_started and not frontmatter_ended:
  34. match = frontmatter_pattern.match(line)
  35. if match:
  36. key, value = match.groups()
  37. frontmatter[key.strip()] = value.strip()
  38. except Exception as e:
  39. log.exception(f"Failed to extract frontmatter: {e}")
  40. return {}
  41. return frontmatter
  42. def replace_imports(content):
  43. """
  44. Replace the import paths in the content.
  45. """
  46. replacements = {
  47. "from utils": "from open_webui.utils",
  48. "from apps": "from open_webui.apps",
  49. "from main": "from open_webui.main",
  50. "from config": "from open_webui.config",
  51. }
  52. for old, new in replacements.items():
  53. content = content.replace(old, new)
  54. return content
  55. def load_tool_module_by_id(tool_id, content=None):
  56. if content is None:
  57. tool = Tools.get_tool_by_id(tool_id)
  58. if not tool:
  59. raise Exception(f"Toolkit not found: {tool_id}")
  60. content = tool.content
  61. content = replace_imports(content)
  62. Tools.update_tool_by_id(tool_id, {"content": content})
  63. else:
  64. frontmatter = extract_frontmatter(content)
  65. # Install required packages found within the frontmatter
  66. install_frontmatter_requirements(frontmatter.get("requirements", ""))
  67. module_name = f"tool_{tool_id}"
  68. module = types.ModuleType(module_name)
  69. sys.modules[module_name] = module
  70. # Create a temporary file and use it to define `__file__` so
  71. # that it works as expected from the module's perspective.
  72. temp_file = tempfile.NamedTemporaryFile(delete=False)
  73. temp_file.close()
  74. try:
  75. with open(temp_file.name, "w", encoding="utf-8") as f:
  76. f.write(content)
  77. module.__dict__["__file__"] = temp_file.name
  78. # Executing the modified content in the created module's namespace
  79. exec(content, module.__dict__)
  80. frontmatter = extract_frontmatter(content)
  81. log.info(f"Loaded module: {module.__name__}")
  82. # Create and return the object if the class 'Tools' is found in the module
  83. if hasattr(module, "Tools"):
  84. return module.Tools(), frontmatter
  85. else:
  86. raise Exception("No Tools class found in the module")
  87. except Exception as e:
  88. log.error(f"Error loading module: {tool_id}: {e}")
  89. del sys.modules[module_name] # Clean up
  90. raise e
  91. finally:
  92. os.unlink(temp_file.name)
  93. def load_function_module_by_id(function_id: str, content: str | None = None):
  94. if content is None:
  95. function = Functions.get_function_by_id(function_id)
  96. if not function:
  97. raise Exception(f"Function not found: {function_id}")
  98. content = function.content
  99. content = replace_imports(content)
  100. Functions.update_function_by_id(function_id, {"content": content})
  101. else:
  102. frontmatter = extract_frontmatter(content)
  103. install_frontmatter_requirements(frontmatter.get("requirements", ""))
  104. module_name = f"function_{function_id}"
  105. module = types.ModuleType(module_name)
  106. sys.modules[module_name] = module
  107. # Create a temporary file and use it to define `__file__` so
  108. # that it works as expected from the module's perspective.
  109. temp_file = tempfile.NamedTemporaryFile(delete=False)
  110. temp_file.close()
  111. try:
  112. with open(temp_file.name, "w", encoding="utf-8") as f:
  113. f.write(content)
  114. module.__dict__["__file__"] = temp_file.name
  115. # Execute the modified content in the created module's namespace
  116. exec(content, module.__dict__)
  117. frontmatter = extract_frontmatter(content)
  118. log.info(f"Loaded module: {module.__name__}")
  119. # Create appropriate object based on available class type in the module
  120. if hasattr(module, "Pipe"):
  121. return module.Pipe(), "pipe", frontmatter
  122. elif hasattr(module, "Filter"):
  123. return module.Filter(), "filter", frontmatter
  124. elif hasattr(module, "Action"):
  125. return module.Action(), "action", frontmatter
  126. else:
  127. raise Exception("No Function class found in the module")
  128. except Exception as e:
  129. log.error(f"Error loading module: {function_id}: {e}")
  130. # Cleanup by removing the module in case of error
  131. del sys.modules[module_name]
  132. Functions.update_function_by_id(function_id, {"is_active": False})
  133. raise e
  134. finally:
  135. os.unlink(temp_file.name)
  136. def get_tool_module_from_cache(request, tool_id, load_from_db=True):
  137. if load_from_db:
  138. # Always load from the database by default
  139. tool = Tools.get_tool_by_id(tool_id)
  140. if not tool:
  141. raise Exception(f"Tool not found: {tool_id}")
  142. content = tool.content
  143. new_content = replace_imports(content)
  144. if new_content != content:
  145. content = new_content
  146. # Update the tool content in the database
  147. Tools.update_tool_by_id(tool_id, {"content": content})
  148. if (
  149. hasattr(request.app.state, "TOOL_CONTENTS")
  150. and tool_id in request.app.state.TOOL_CONTENTS
  151. ) and (
  152. hasattr(request.app.state, "TOOLS") and tool_id in request.app.state.TOOLS
  153. ):
  154. if request.app.state.TOOL_CONTENTS[tool_id] == content:
  155. return request.app.state.TOOLS[tool_id], None
  156. tool_module, frontmatter = load_tool_module_by_id(tool_id, content)
  157. else:
  158. if hasattr(request.app.state, "TOOLS") and tool_id in request.app.state.TOOLS:
  159. return request.app.state.TOOLS[tool_id], None
  160. tool_module, frontmatter = load_tool_module_by_id(tool_id)
  161. if not hasattr(request.app.state, "TOOLS"):
  162. request.app.state.TOOLS = {}
  163. if not hasattr(request.app.state, "TOOL_CONTENTS"):
  164. request.app.state.TOOL_CONTENTS = {}
  165. request.app.state.TOOLS[tool_id] = tool_module
  166. request.app.state.TOOL_CONTENTS[tool_id] = content
  167. return tool_module, frontmatter
  168. def get_function_module_from_cache(request, function_id, load_from_db=True):
  169. if load_from_db:
  170. # Always load from the database by default
  171. # This is useful for hooks like "inlet" or "outlet" where the content might change
  172. # and we want to ensure the latest content is used.
  173. function = Functions.get_function_by_id(function_id)
  174. if not function:
  175. raise Exception(f"Function not found: {function_id}")
  176. content = function.content
  177. new_content = replace_imports(content)
  178. if new_content != content:
  179. content = new_content
  180. # Update the function content in the database
  181. Functions.update_function_by_id(function_id, {"content": content})
  182. if (
  183. hasattr(request.app.state, "FUNCTION_CONTENTS")
  184. and function_id in request.app.state.FUNCTION_CONTENTS
  185. ) and (
  186. hasattr(request.app.state, "FUNCTIONS")
  187. and function_id in request.app.state.FUNCTIONS
  188. ):
  189. if request.app.state.FUNCTION_CONTENTS[function_id] == content:
  190. return request.app.state.FUNCTIONS[function_id], None, None
  191. function_module, function_type, frontmatter = load_function_module_by_id(
  192. function_id, content
  193. )
  194. else:
  195. # Load from cache (e.g. "stream" hook)
  196. # This is useful for performance reasons
  197. if (
  198. hasattr(request.app.state, "FUNCTIONS")
  199. and function_id in request.app.state.FUNCTIONS
  200. ):
  201. return request.app.state.FUNCTIONS[function_id], None, None
  202. function_module, function_type, frontmatter = load_function_module_by_id(
  203. function_id
  204. )
  205. if not hasattr(request.app.state, "FUNCTIONS"):
  206. request.app.state.FUNCTIONS = {}
  207. if not hasattr(request.app.state, "FUNCTION_CONTENTS"):
  208. request.app.state.FUNCTION_CONTENTS = {}
  209. request.app.state.FUNCTIONS[function_id] = function_module
  210. request.app.state.FUNCTION_CONTENTS[function_id] = content
  211. return function_module, function_type, frontmatter
  212. def install_frontmatter_requirements(requirements: str):
  213. if requirements:
  214. try:
  215. req_list = [req.strip() for req in requirements.split(",")]
  216. log.info(f"Installing requirements: {' '.join(req_list)}")
  217. subprocess.check_call(
  218. [sys.executable, "-m", "pip", "install"]
  219. + PIP_OPTIONS
  220. + req_list
  221. + PIP_PACKAGE_INDEX_OPTIONS
  222. )
  223. except Exception as e:
  224. log.error(f"Error installing packages: {' '.join(req_list)}")
  225. raise e
  226. else:
  227. log.info("No requirements found in frontmatter.")
  228. def install_tool_and_function_dependencies():
  229. """
  230. Install all dependencies for all admin tools and active functions.
  231. By first collecting all dependencies from the frontmatter of each tool and function,
  232. and then installing them using pip. Duplicates or similar version specifications are
  233. handled by pip as much as possible.
  234. """
  235. function_list = Functions.get_functions(active_only=True)
  236. tool_list = Tools.get_tools()
  237. all_dependencies = ""
  238. try:
  239. for function in function_list:
  240. frontmatter = extract_frontmatter(replace_imports(function.content))
  241. if dependencies := frontmatter.get("requirements"):
  242. all_dependencies += f"{dependencies}, "
  243. for tool in tool_list:
  244. # Only install requirements for admin tools
  245. if tool.user and tool.user.role == "admin":
  246. frontmatter = extract_frontmatter(replace_imports(tool.content))
  247. if dependencies := frontmatter.get("requirements"):
  248. all_dependencies += f"{dependencies}, "
  249. install_frontmatter_requirements(all_dependencies.strip(", "))
  250. except Exception as e:
  251. log.error(f"Error installing requirements: {e}")