utils.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. import os
  2. import re
  3. import subprocess
  4. import sys
  5. from importlib import util
  6. import types
  7. from open_webui.apps.webui.models.functions import Functions
  8. from open_webui.apps.webui.models.tools import Tools
  9. from open_webui.config import FUNCTIONS_DIR, TOOLS_DIR
  10. def extract_frontmatter(content):
  11. """
  12. Extract frontmatter as a dictionary from the provided content string.
  13. """
  14. frontmatter = {}
  15. frontmatter_started = False
  16. frontmatter_ended = False
  17. frontmatter_pattern = re.compile(r"^\s*([a-z_]+):\s*(.*)\s*$", re.IGNORECASE)
  18. try:
  19. lines = content.splitlines()
  20. if len(lines) < 1 or lines[0].strip() != '"""':
  21. # The content doesn't start with triple quotes
  22. return {}
  23. frontmatter_started = True
  24. for line in lines[1:]:
  25. if '"""' in line:
  26. if frontmatter_started:
  27. frontmatter_ended = True
  28. break
  29. if frontmatter_started and not frontmatter_ended:
  30. match = frontmatter_pattern.match(line)
  31. if match:
  32. key, value = match.groups()
  33. frontmatter[key.strip()] = value.strip()
  34. except Exception as e:
  35. print(f"An error occurred: {e}")
  36. return {}
  37. return frontmatter
  38. def replace_imports(content):
  39. """
  40. Replace the import paths in the content.
  41. """
  42. replacements = {
  43. "from utils": "from open_webui.utils",
  44. "from apps": "from open_webui.apps",
  45. "from main": "from open_webui.main",
  46. "from config": "from open_webui.config",
  47. }
  48. for old, new in replacements.items():
  49. content = content.replace(old, new)
  50. return content
  51. def load_toolkit_module_by_id(toolkit_id, content=None):
  52. if content is None:
  53. tool = Tools.get_tool_by_id(toolkit_id)
  54. if not tool:
  55. raise Exception(f"Toolkit not found: {toolkit_id}")
  56. content = tool.content
  57. content = replace_imports(content)
  58. Tools.update_tool_by_id(toolkit_id, {"content": content})
  59. else:
  60. frontmatter = extract_frontmatter(content)
  61. # Install required packages found within the frontmatter
  62. install_frontmatter_requirements(frontmatter.get("requirements", ""))
  63. module_name = f"tool_{toolkit_id}"
  64. module = types.ModuleType(module_name)
  65. sys.modules[module_name] = module
  66. # Create a temporary in-memory file and use it to define `__file__` so
  67. # that it works as expected from the module's perspective.
  68. temp_fd = os.memfd_create(f"tmp:{module_name}")
  69. try:
  70. os.write(temp_fd, content.encode("utf-8"))
  71. module.__dict__["__file__"] = f"/proc/{os.getpid()}/fd/{temp_fd}"
  72. # Executing the modified content in the created module's namespace
  73. exec(content, module.__dict__)
  74. frontmatter = extract_frontmatter(content)
  75. print(f"Loaded module: {module.__name__}")
  76. # Create and return the object if the class 'Tools' is found in the module
  77. if hasattr(module, "Tools"):
  78. return module.Tools(), frontmatter
  79. else:
  80. raise Exception("No Tools class found in the module")
  81. except Exception as e:
  82. print(f"Error loading module: {toolkit_id}: {e}")
  83. del sys.modules[module_name] # Clean up
  84. raise e
  85. finally:
  86. os.close(temp_fd)
  87. def load_function_module_by_id(function_id, content=None):
  88. if content is None:
  89. function = Functions.get_function_by_id(function_id)
  90. if not function:
  91. raise Exception(f"Function not found: {function_id}")
  92. content = function.content
  93. content = replace_imports(content)
  94. Functions.update_function_by_id(function_id, {"content": content})
  95. else:
  96. frontmatter = extract_frontmatter(content)
  97. install_frontmatter_requirements(frontmatter.get("requirements", ""))
  98. module_name = f"function_{function_id}"
  99. module = types.ModuleType(module_name)
  100. sys.modules[module_name] = module
  101. # Create a temporary in-memory file and use it to define `__file__` so
  102. # that it works as expected from the module's perspective.
  103. temp_fd = os.memfd_create(f"tmp:{module_name}")
  104. try:
  105. os.write(temp_fd, content.encode("utf-8"))
  106. module.__dict__["__file__"] = f"/proc/{os.getpid()}/fd/{temp_fd}"
  107. # Execute the modified content in the created module's namespace
  108. exec(content, module.__dict__)
  109. frontmatter = extract_frontmatter(content)
  110. print(f"Loaded module: {module.__name__}")
  111. # Create appropriate object based on available class type in the module
  112. if hasattr(module, "Pipe"):
  113. return module.Pipe(), "pipe", frontmatter
  114. elif hasattr(module, "Filter"):
  115. return module.Filter(), "filter", frontmatter
  116. elif hasattr(module, "Action"):
  117. return module.Action(), "action", frontmatter
  118. else:
  119. raise Exception("No Function class found in the module")
  120. except Exception as e:
  121. print(f"Error loading module: {function_id}: {e}")
  122. del sys.modules[module_name] # Cleanup by removing the module in case of error
  123. Functions.update_function_by_id(function_id, {"is_active": False})
  124. raise e
  125. finally:
  126. os.close(temp_fd)
  127. def install_frontmatter_requirements(requirements):
  128. if requirements:
  129. req_list = [req.strip() for req in requirements.split(",")]
  130. for req in req_list:
  131. print(f"Installing requirement: {req}")
  132. subprocess.check_call([sys.executable, "-m", "pip", "install", req])
  133. else:
  134. print("No requirements found in frontmatter.")