huggingface/smolagents · error · InterpreterError

Forbidden access to module: {result.__name__}

Error message

Forbidden access to module: {result.__name__}

What it means

Raised by smolagents' local Python executor when evaluated code returns a module object that is not in the authorized_imports list. The executor runs LLM-generated code in a sandbox and inspects every return value (via the safer_eval decorator's check_safer_result); returning an unauthorized module leaks it back to the caller, so it is blocked with an InterpreterError.

Source

Thrown at src/smolagents/local_python_executor.py:170

    "posix.system",
]


def check_safer_result(result: Any, static_tools: dict[str, Callable] = None, authorized_imports: list[str] = None):
    """
    Checks if a result is safer according to authorized imports and static tools.

    Args:
        result (Any): The result to check.
        static_tools (dict[str, Callable]): Dictionary of static tools.
        authorized_imports (list[str]): List of authorized imports.

    Raises:
        InterpreterError: If the result is not safe
    """
    if isinstance(result, ModuleType):
        if not check_import_authorized(result.__name__, authorized_imports):
            raise InterpreterError(f"Forbidden access to module: {result.__name__}")
    elif isinstance(result, dict) and result.get("__spec__"):
        if not check_import_authorized(result["__name__"], authorized_imports):
            raise InterpreterError(f"Forbidden access to module: {result['__name__']}")
    elif isinstance(result, (FunctionType, BuiltinFunctionType)):
        for qualified_function_name in DANGEROUS_FUNCTIONS:
            module_name, function_name = qualified_function_name.rsplit(".", 1)
            if (
                (static_tools is None or function_name not in static_tools)
                and result.__name__ == function_name
                and result.__module__ == module_name
            ):
                raise InterpreterError(f"Forbidden access to function: {function_name}")


def safer_eval(func: Callable):
    """
    Decorator to enhance the security of an evaluation function by checking its return value.

View on GitHub (pinned to 30bb116109)

Solutions

  1. Add the module to additional_authorized_imports when creating the CodeAgent/executor (e.g. additional_authorized_imports=['numpy'])
  2. Change the executed code to return a concrete value (a string, dict, number) instead of the module object itself
  3. Import only the specific function needed (from numpy import mean) and return the function's result, not the module

Example fix

# before
code = """import numpy
global numpy"""

# after
code = """import numpy as np
final_answer(np.mean([1, 2, 3]))"""
Defensive patterns

Strategy: validation

Validate before calling

from smolagents.utils import BASE_BUILTIN_MODULES
allowed = set(BASE_BUILTIN_MODULES + ['numpy'])
last_expr = ast.parse(code).body[-1]
mods = {n.names[0].name.split('.')[0] for n in ast.walk(last_expr) if isinstance(n, ast.Import)}
mods |= {n.module.split('.')[0] for n in ast.walk(last_expr) if isinstance(n, ast.ImportFrom)}
assert mods <= allowed, f'unauthorized module returned: {mods - allowed}'

Type guard

def returns_module(frame_last_value) -> bool:
    import types
    return isinstance(frame_last_value, types.ModuleType)

Try / catch

from smolagents.local_python_executor import InterpreterError
try:
    evaluate_python(code, additional_authorized_imports=authorized)
except InterpreterError as e:
    if 'Forbidden access to module' in str(e):
        print('module not whitelisted:', str(e))

Prevention

When it happens

Trigger: Executed code ends with an expression whose value is a module (e.g. the last line is `import json` then `json`, or a function returns a module) and that module's name is not covered by the authorized_imports list passed to evaluate_python/LocalPythonExecutor (defaults to BASE_BUILTIN_MODULES).

Common situations: Agent code does `import numpy` and returns it while additional_authorized_imports only lists other modules; returning `os` or `sys` which are deliberately not in the default whitelist; module returned indirectly from a helper function.

Understand the failure class

Related errors


AI-assisted analysis of huggingface/smolagents@30bb116109 (2026-08-28). Data as JSON: /api/errors/3c8443ed8662eb19. Report an issue: GitHub.