File size: 1,479 Bytes
293ab16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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