From eb9ad47ef8bf24fd7d938a29de8da23ec119b56e Mon Sep 17 00:00:00 2001 From: "Timothy J. Baek" Date: Fri, 20 Sep 2024 00:12:52 +0200 Subject: [PATCH] refac: temp tools & functions files --- backend/open_webui/apps/webui/utils.py | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/backend/open_webui/apps/webui/utils.py b/backend/open_webui/apps/webui/utils.py index 3d43b9a9a..8bf48e400 100644 --- a/backend/open_webui/apps/webui/utils.py +++ b/backend/open_webui/apps/webui/utils.py @@ -4,7 +4,7 @@ import subprocess import sys from importlib import util import types - +import tempfile from open_webui.apps.webui.models.functions import Functions from open_webui.apps.webui.models.tools import Tools @@ -84,12 +84,14 @@ def load_toolkit_module_by_id(toolkit_id, content=None): module = types.ModuleType(module_name) sys.modules[module_name] = module - # Create a temporary in-memory file and use it to define `__file__` so + # Create a temporary file and use it to define `__file__` so # that it works as expected from the module's perspective. - temp_fd = os.memfd_create(f"tmp:{module_name}") + temp_file = tempfile.NamedTemporaryFile(delete=False) + try: - os.write(temp_fd, content.encode("utf-8")) - module.__dict__["__file__"] = f"/proc/{os.getpid()}/fd/{temp_fd}" + with open(temp_file.name, "w", encoding="utf-8") as f: + f.write(content) + module.__dict__["__file__"] = temp_file.name # Executing the modified content in the created module's namespace exec(content, module.__dict__) @@ -106,7 +108,7 @@ def load_toolkit_module_by_id(toolkit_id, content=None): del sys.modules[module_name] # Clean up raise e finally: - os.close(temp_fd) + os.unlink(temp_file.name) def load_function_module_by_id(function_id, content=None): @@ -126,12 +128,13 @@ def load_function_module_by_id(function_id, content=None): module = types.ModuleType(module_name) sys.modules[module_name] = module - # Create a temporary in-memory file and use it to define `__file__` so + # Create a temporary file and use it to define `__file__` so # that it works as expected from the module's perspective. - temp_fd = os.memfd_create(f"tmp:{module_name}") + temp_file = tempfile.NamedTemporaryFile(delete=False) try: - os.write(temp_fd, content.encode("utf-8")) - module.__dict__["__file__"] = f"/proc/{os.getpid()}/fd/{temp_fd}" + with open(temp_file.name, "w", encoding="utf-8") as f: + f.write(content) + module.__dict__["__file__"] = temp_file.name # Execute the modified content in the created module's namespace exec(content, module.__dict__) @@ -154,7 +157,7 @@ def load_function_module_by_id(function_id, content=None): Functions.update_function_by_id(function_id, {"is_active": False}) raise e finally: - os.close(temp_fd) + os.unlink(temp_file.name) def install_frontmatter_requirements(requirements):