xtekky/gpt4free · error · ImportError
Import of '{name}' is not allowed in safe execution mode.\nA
Error message
Import of '{name}' is not allowed in safe execution mode.\nAllowed top-level modules: {', '.join(sorted(allowed))} What it means
The sandbox's primary import rejection: the top-level module is not in SAFE_MODULES, is not 'os' (shim), and is not a sibling workspace .py file. The message lists the sorted allowlist so you can see exactly what is permitted. This enforces the documented contract that .pa.py sandboxes may only import a curated set of stdlib modules plus local workspace files.
Source
Thrown at g4f/mcp/pa_provider.py:483
# Before rejecting, check if it's a workspace module (sibling .py file).
workspace = get_workspace_dir()
ws_module = _load_workspace_module(
base, workspace, globals, fromlist, level
)
if ws_module is not None:
# Handle submodule imports (e.g. "pkg.sub")
if name != base:
# Try to resolve the full dotted path from the loaded module
obj = ws_module
for part in name.split(".")[1:]:
obj = getattr(obj, part, None)
if obj is None:
raise ImportError(
f"Cannot find submodule '{name}' in workspace module '{base}'."
)
return obj
return ws_module
raise ImportError(
f"Import of '{name}' is not allowed in safe execution mode.\n"
f"Allowed top-level modules: {', '.join(sorted(allowed))}"
)
# Explicit allowlist takes priority over the blocklist below.
# This permits e.g. "g4f.Provider.helper" even though "g4f.Provider"
# is blocked.
for allowed_sub in _ALLOWED_G4F_SUBPATHS:
if name == allowed_sub or name.startswith(allowed_sub + "."):
return original(name, globals, locals, fromlist, level)
# Block sensitive g4f submodules even though g4f itself is allowed.
if name in _BLOCKED_SUBMODULES:
raise ImportError(
f"Import of '{name}' is not allowed inside a .pa.py sandbox "
f"for security reasons."
)
# Also block when a blocked submodule is the parent of a deeper import
# (e.g. "g4f.tools.auth.something", "g4f.Provider.OpenAI").
for blocked in _BLOCKED_SUBMODULES:View on GitHub (pinned to 973504e177)
Solutions
- Check the allowlist in the error message and re-implement using an allowed equivalent (urllib/http.client instead of requests, os shim constants instead of sys.platform)
- Place pure-Python helper code as sibling .py files in the workspace directory and import them by top-level name
- For HTTP, use 'http.client' or 'urllib.parse' which are explicitly allowed
- If you operate the MCP server and need a genuinely safe extra module, extend the allowed set passed to _make_restricted_import / _make_safe_globals
Example fix
# before import requests r = requests.get(url) # after from http.client import HTTPSConnection # (http.client is in SAFE_MODULES)
Defensive patterns
Strategy: validation
Validate before calling
from g4f.mcp.pa_provider import SAFE_MODULES
import ast, pathlib
def sandbox_imports_ok(path: pathlib.Path) -> list[str]:
bad = []
for node in ast.walk(ast.parse(path.read_text())):
if isinstance(node, ast.Import):
bad += [a.name for a in node.names if a.name.split('.')[0] not in SAFE_MODULES]
elif isinstance(node, ast.ImportFrom) and node.module:
if node.module.split('.')[0] not in SAFE_MODULES:
bad.append(node.module)
return bad # empty list == safe to load Try / catch
try:
import requests # any non-allowlisted module
except ImportError as e:
if "safe execution mode" in str(e):
# switch to http.client / urllib or a workspace sibling module
... Prevention
- Run an AST pre-check of .pa.py files against SAFE_MODULES before loading
- Restrict sandbox HTTP code to http.client and urllib from the start
- Treat the allowlist in the error message as the API surface, not as an obstacle to work around
When it happens
Trigger: 'import requests', 'import sys', 'import subprocess' or any other module whose first dotted component is absent from SAFE_MODULES (g4f/mcp/pa_provider.py:95) and absent from the workspace directory as <base>.py.
Common situations: Provider scripts written against the normal g4f API that assume third-party libraries are available; code that imports 'sys' for stdout tricks or 'subprocess' to call curl; upgrading g4f where the allowlist was tightened.
Related errors
- '{name}' is not available in the restricted os shim.
- Cannot find submodule '{name}' in workspace module '{base}'.
- Import of '{name}' is not allowed inside a .pa.py sandbox fo
- File access outside workspace is denied: '{file}'. Workspace
- Syntax error in workspace module '{name}' ({source_path}):\n
AI-assisted analysis of xtekky/gpt4free@973504e177 (2026-08-14).
Data as JSON: /api/errors/9f3bee284a6f5159.
Report an issue: GitHub.