utils.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  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. module_name = f"tool_{toolkit_id}"
  60. module = types.ModuleType(module_name)
  61. sys.modules[module_name] = module
  62. try:
  63. # Executing the modified content in the created module's namespace
  64. exec(content, module.__dict__)
  65. # Extract frontmatter, assuming content can be treated directly as a string
  66. frontmatter = extract_frontmatter(
  67. content
  68. ) # Ensure this method is adaptable to handle content strings
  69. # Install required packages found within the frontmatter
  70. install_frontmatter_requirements(frontmatter.get("requirements", ""))
  71. print(f"Loaded module: {module.__name__}")
  72. # Create and return the object if the class 'Tools' is found in the module
  73. if hasattr(module, "Tools"):
  74. return module.Tools(), frontmatter
  75. else:
  76. raise Exception("No Tools class found in the module")
  77. except Exception as e:
  78. print(f"Error loading module: {toolkit_id}")
  79. del sys.modules[module_name] # Clean up
  80. raise e
  81. def load_function_module_by_id(function_id, content=None):
  82. if content is None:
  83. function = Functions.get_function_by_id(function_id)
  84. if not function:
  85. raise Exception(f"Function not found: {function_id}")
  86. content = function.content
  87. content = replace_imports(content)
  88. Functions.update_function_by_id(function_id, {"content": content})
  89. module_name = f"function_{function_id}"
  90. module = types.ModuleType(module_name)
  91. sys.modules[module_name] = module
  92. try:
  93. # Execute the modified content in the created module's namespace
  94. exec(content, module.__dict__)
  95. # Extract the frontmatter from the content, simulate file-like behaviour
  96. frontmatter = extract_frontmatter(
  97. content
  98. ) # This function needs to handle string inputs
  99. # Install necessary requirements specified in frontmatter
  100. install_frontmatter_requirements(frontmatter.get("requirements", ""))
  101. print(f"Loaded module: {module.__name__}")
  102. # Create appropriate object based on available class type in the module
  103. if hasattr(module, "Pipe"):
  104. return module.Pipe(), "pipe", frontmatter
  105. elif hasattr(module, "Filter"):
  106. return module.Filter(), "filter", frontmatter
  107. elif hasattr(module, "Action"):
  108. return module.Action(), "action", frontmatter
  109. else:
  110. raise Exception("No Function class found in the module")
  111. except Exception as e:
  112. print(f"Error loading module: {function_id}")
  113. del sys.modules[module_name] # Cleanup by removing the module in case of error
  114. Functions.update_function_by_id(function_id, {"is_active": False})
  115. raise e
  116. def install_frontmatter_requirements(requirements):
  117. if requirements:
  118. req_list = [req.strip() for req in requirements.split(",")]
  119. for req in req_list:
  120. print(f"Installing requirement: {req}")
  121. subprocess.check_call([sys.executable, "-m", "pip", "install", req])
  122. else:
  123. print("No requirements found in frontmatter.")