{"record":{"id":"3c8443ed8662eb19","repo":"huggingface/smolagents","slug":"forbidden-access-to-module-result-name","errorCode":null,"errorMessage":"Forbidden access to module: {result.__name__}","messagePattern":"Forbidden access to module: (.+?)","errorType":"error_code","errorClass":"InterpreterError","httpStatus":null,"severity":"error","filePath":"src/smolagents/local_python_executor.py","lineNumber":170,"sourceCode":"    \"posix.system\",\n]\n\n\ndef check_safer_result(result: Any, static_tools: dict[str, Callable] = None, authorized_imports: list[str] = None):\n    \"\"\"\n    Checks if a result is safer according to authorized imports and static tools.\n\n    Args:\n        result (Any): The result to check.\n        static_tools (dict[str, Callable]): Dictionary of static tools.\n        authorized_imports (list[str]): List of authorized imports.\n\n    Raises:\n        InterpreterError: If the result is not safe\n    \"\"\"\n    if isinstance(result, ModuleType):\n        if not check_import_authorized(result.__name__, authorized_imports):\n            raise InterpreterError(f\"Forbidden access to module: {result.__name__}\")\n    elif isinstance(result, dict) and result.get(\"__spec__\"):\n        if not check_import_authorized(result[\"__name__\"], authorized_imports):\n            raise InterpreterError(f\"Forbidden access to module: {result['__name__']}\")\n    elif isinstance(result, (FunctionType, BuiltinFunctionType)):\n        for qualified_function_name in DANGEROUS_FUNCTIONS:\n            module_name, function_name = qualified_function_name.rsplit(\".\", 1)\n            if (\n                (static_tools is None or function_name not in static_tools)\n                and result.__name__ == function_name\n                and result.__module__ == module_name\n            ):\n                raise InterpreterError(f\"Forbidden access to function: {function_name}\")\n\n\ndef safer_eval(func: Callable):\n    \"\"\"\n    Decorator to enhance the security of an evaluation function by checking its return value.\n","sourceCodeStart":152,"sourceCodeEnd":188,"githubUrl":"https://github.com/huggingface/smolagents/blob/30bb1161095dbae2271e6bc3cc4c219cc3897a57/src/smolagents/local_python_executor.py#L152-L188","documentation":"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.","triggerScenarios":"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).","commonSituations":"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.","solutions":["Add the module to additional_authorized_imports when creating the CodeAgent/executor (e.g. additional_authorized_imports=['numpy'])","Change the executed code to return a concrete value (a string, dict, number) instead of the module object itself","Import only the specific function needed (from numpy import mean) and return the function's result, not the module"],"exampleFix":"# before\ncode = \"\"\"import numpy\nglobal numpy\"\"\"\n\n# after\ncode = \"\"\"import numpy as np\nfinal_answer(np.mean([1, 2, 3]))\"\"\"","handlingStrategy":"validation","validationCode":"from smolagents.utils import BASE_BUILTIN_MODULES\nallowed = set(BASE_BUILTIN_MODULES + ['numpy'])\nlast_expr = ast.parse(code).body[-1]\nmods = {n.names[0].name.split('.')[0] for n in ast.walk(last_expr) if isinstance(n, ast.Import)}\nmods |= {n.module.split('.')[0] for n in ast.walk(last_expr) if isinstance(n, ast.ImportFrom)}\nassert mods <= allowed, f'unauthorized module returned: {mods - allowed}'","typeGuard":"def returns_module(frame_last_value) -> bool:\n    import types\n    return isinstance(frame_last_value, types.ModuleType)","tryCatchPattern":"from smolagents.local_python_executor import InterpreterError\ntry:\n    evaluate_python(code, additional_authorized_imports=authorized)\nexcept InterpreterError as e:\n    if 'Forbidden access to module' in str(e):\n        print('module not whitelisted:', str(e))","preventionTips":["Pass additional_authorized_imports listing every module the generated code may touch","Instruct the agent (system prompt) to return values, not modules","End snippets with final_answer(...) returning serializable data"],"tags":["smolagents","sandbox","authorized-imports","interpreter-error","security"],"backgroundTag":"module-import-not-authorized","analyzedSha":"30bb1161095dbae2271e6bc3cc4c219cc3897a57","analyzedAt":"2026-08-28T18:52:54.169Z","schemaVersion":2},"datasetVersion":"2026-08-28T21:17:43.275Z"}