diff --git a/backend/open_webui/utils/plugin.py b/backend/open_webui/utils/plugin.py index 7a7bea81a4..174361cff0 100644 --- a/backend/open_webui/utils/plugin.py +++ b/backend/open_webui/utils/plugin.py @@ -1,6 +1,7 @@ from __future__ import annotations import asyncio +import inspect import logging import os import re @@ -10,8 +11,9 @@ import tempfile import types import uuid from importlib import util -from typing import Any +from typing import Any, Callable +from fastapi import HTTPException from open_webui.env import ( ENABLE_FUNCTIONS, ENABLE_PIP_INSTALL_FRONTMATTER_REQUIREMENTS, @@ -203,6 +205,17 @@ def replace_imports(content): return content +def require_async_methods(methods: list[Callable]): + """Reject tools and functions whose entry points are not async def.""" + sync_names = [ + method.__name__ + for method in methods + if not inspect.iscoroutinefunction(method) and not inspect.isasyncgenfunction(method) + ] + if sync_names: + raise HTTPException(400, f'Methods must be defined with async def: {", ".join(sync_names)}') + + # Let the care put into this work survive every # import and transformation, and serve those who carry it forward. async def load_tool_module_by_id(tool_id, content=None): @@ -245,7 +258,11 @@ async def load_tool_module_by_id(tool_id, content=None): # Look for the Tools class; the toolkit still needs someone to answer the door. if hasattr(module, 'Tools'): - return module.Tools(), frontmatter, module + from open_webui.utils.tools import get_functions_from_tool + + tool_module = module.Tools() + require_async_methods(get_functions_from_tool(tool_module)) + return tool_module, frontmatter, module else: raise Exception('No Tools class found in the module') except Exception as e: @@ -293,15 +310,22 @@ async def load_function_module_by_id(function_id: str, content: str | None = Non # Create appropriate object based on available class type in the module if hasattr(module, 'Pipe'): - return module.Pipe(), 'pipe', frontmatter, module + function_module, function_type = module.Pipe(), 'pipe' elif hasattr(module, 'Filter'): - return module.Filter(), 'filter', frontmatter, module + function_module, function_type = module.Filter(), 'filter' elif hasattr(module, 'Action'): - return module.Action(), 'action', frontmatter, module + function_module, function_type = module.Action(), 'action' elif hasattr(module, 'Event'): - return module.Event(), 'event', frontmatter, module + function_module, function_type = module.Event(), 'event' else: raise Exception('No Function class found in the module') + + hooks = [ + getattr(function_module, name, None) + for name in ('pipe', 'pipes', 'inlet', 'request', 'outlet', 'stream', 'action', 'event') + ] + require_async_methods([hook for hook in hooks if callable(hook)]) + return function_module, function_type, frontmatter, module except Exception as e: log.error(f'Error loading module: {function_id}: {e}') raise e @@ -375,7 +399,12 @@ async def get_tool_module_from_cache(request, tool_id, load_from_db=True): if tool_id in tools_cache: return tools_cache[tool_id], None - tool_module, frontmatter, source_module = await load_tool_module_by_id(tool_id, content) + try: + tool_module, frontmatter, source_module = await load_tool_module_by_id(tool_id, content) + except Exception: + await Tools.update_tool_by_id(tool_id, {'is_active': False}) + raise + set_tool_module_in_cache(request, tool_id, content, tool_module, source_module) return tool_module, frontmatter diff --git a/backend/open_webui/utils/tools.py b/backend/open_webui/utils/tools.py index d774e38574..8faa5386d4 100644 --- a/backend/open_webui/utils/tools.py +++ b/backend/open_webui/utils/tools.py @@ -438,7 +438,11 @@ async def get_tools(request: Request, tool_ids: list[str], user: UserModel, extr tool_contents_cache = get_tool_contents_cache(request) module = tools_cache.get(tool_id) if module is None or tool_contents_cache.get(tool_id) != tool.content: - module, _, source_module = await load_tool_module_by_id(tool_id, content=tool.content) + try: + module, _, source_module = await load_tool_module_by_id(tool_id, content=tool.content) + except Exception: + await Tools.update_tool_by_id(tool_id, {'is_active': False}) + raise set_tool_module_in_cache(request, tool_id, tool.content, module, source_module) __user__ = { diff --git a/src/lib/components/admin/Functions/FunctionEditor.svelte b/src/lib/components/admin/Functions/FunctionEditor.svelte index 986c81340c..222cb6976e 100644 --- a/src/lib/components/admin/Functions/FunctionEditor.svelte +++ b/src/lib/components/admin/Functions/FunctionEditor.svelte @@ -159,7 +159,7 @@ class Filter: self.valves = self.Valves() pass - def inlet(self, body: dict, __user__: Optional[dict] = None) -> dict: + async def inlet(self, body: dict, __user__: Optional[dict] = None) -> dict: # Modify the request body or validate it before processing by the chat completion API. # This function is the pre-processor for the API where various checks on the input can be performed. # It can also modify the request before sending it to the API. @@ -178,7 +178,7 @@ class Filter: return body - def request(self, body: dict, __user__: Optional[dict] = None) -> dict: + async def request(self, body: dict, __user__: Optional[dict] = None) -> dict: # Modify the request body before each model/provider call. print(f"request:{__name__}") print(f"request:body:{body}") @@ -186,7 +186,7 @@ class Filter: return body - def outlet(self, body: dict, __user__: Optional[dict] = None) -> dict: + async def outlet(self, body: dict, __user__: Optional[dict] = None) -> dict: # Modify or analyze the response body after processing by the API. # This function is the post-processor for the API, which can be used to modify the response # or perform additional checks and analytics. diff --git a/src/lib/components/workspace/Tools/ToolkitEditor.svelte b/src/lib/components/workspace/Tools/ToolkitEditor.svelte index a389138e2b..9b45306b47 100644 --- a/src/lib/components/workspace/Tools/ToolkitEditor.svelte +++ b/src/lib/components/workspace/Tools/ToolkitEditor.svelte @@ -136,7 +136,7 @@ let codeEditor: CodeEditor; let boilerplate = `import os -import requests +import aiohttp from datetime import datetime from pydantic import BaseModel, Field @@ -146,7 +146,7 @@ class Tools: # Add your custom tools using pure Python code here, make sure to add type hints and descriptions - def get_user_name_and_email_and_id(self, __user__: dict = {}) -> str: + async def get_user_name_and_email_and_id(self, __user__: dict = {}) -> str: """ Get the user name, Email and ID from the user object. """ @@ -169,7 +169,7 @@ class Tools: return result - def get_current_time(self) -> str: + async def get_current_time(self) -> str: """ Get the current time in a more human-readable format. """ @@ -182,7 +182,7 @@ class Tools: return f"Current Date and Time = {current_date}, {current_time}" - def calculator( + async def calculator( self, equation: str = Field( ..., description="The mathematical equation to calculate." @@ -201,7 +201,7 @@ class Tools: print(e) return "Invalid equation" - def get_current_weather( + async def get_current_weather( self, city: str = Field( "New York, NY", description="Get the current weather for a given city." @@ -225,9 +225,10 @@ class Tools: } try: - response = requests.get(base_url, params=params) - response.raise_for_status() # Raise HTTPError for bad responses (4xx and 5xx) - data = response.json() + async with aiohttp.ClientSession() as session: + async with session.get(base_url, params=params) as response: + response.raise_for_status() # Raise ClientResponseError for bad responses (4xx and 5xx) + data = await response.json() if data.get("cod") != 200: return f"Error fetching weather data: {data.get('message')}" @@ -238,7 +239,7 @@ class Tools: wind_speed = data["wind"]["speed"] return f"Weather in {city}: {temperature}°C" - except requests.RequestException as e: + except aiohttp.ClientError as e: return f"Error fetching weather data: {str(e)}" `;