Spaces:
Sleeping
Sleeping
| import json | |
| import logging | |
| from typing import Any, Callable, Dict, Optional | |
| logger = logging.getLogger(__name__) | |
| def call_function_by_name( | |
| func_dict: Dict[str, Callable], | |
| func_name: str, | |
| *args, | |
| json_serialize_result: bool = False, | |
| **kwargs | |
| ) -> Any: | |
| """ | |
| Call a function by its name from a dictionary of functions. | |
| Args: | |
| func_dict (dict): Dictionary mapping function names to callables. | |
| func_name (str): Name of the function to call. | |
| *args: Positional arguments to pass to the function. | |
| json_serialize_result (bool): If True, returns JSON string of the result. | |
| **kwargs: Keyword arguments to pass to the function. | |
| Returns: | |
| Any: The function's return value or error message string. | |
| """ | |
| func = func_dict.get(func_name) | |
| if func is None: | |
| error_msg = f"Function '{func_name}' not found." | |
| logger.error(error_msg) | |
| return error_msg | |
| try: | |
| result = func(*args, **kwargs) | |
| if json_serialize_result: | |
| try: | |
| return json.dumps(result) | |
| except (TypeError, ValueError) as json_err: | |
| logger.warning(f"JSON serialization failed: {json_err}") | |
| # Return raw result if serialization fails | |
| return result | |
| return result | |
| except Exception as e: | |
| error_msg = f"Error calling '{func_name}': {str(e)}" | |
| logger.exception(error_msg) | |
| return error_msg | |