xtekky/gpt4free · error · ImportError
Failed to load workspace module '{name}' ({source_path}):\n{
Error message
Failed to load workspace module '{name}' ({source_path}):\n{traceback.format_exc()} What it means
Thrown by the .pa.py sandbox loader when compile() succeeded but exec() of the module body raised any exception — e.g. NameError, ImportError from a blocked module, ZeroDivisionError at import time, or a raised error inside a decorator. The whole traceback is embedded in the ImportError message. The loader deliberately raises rather than swallowing, so a half-initialized module never enters sys.modules.
Source
Thrown at g4f/mcp/pa_provider.py:368
module_globals["__package__"] = module.__package__
module.__dict__.update(module_globals)
try:
compiled = compile(code, str(source_path), "exec")
except SyntaxError:
raise ImportError(
f"Syntax error in workspace module '{name}' "
f"({source_path}):\n{traceback.format_exc()}"
)
# Execute in the current thread (no timeout — module loading is expected
# to be fast and we need the module object synchronously).
prev_depth = sys.getrecursionlimit()
sys.setrecursionlimit(MAX_RECURSION_DEPTH)
try:
exec(compiled, module.__dict__, module.__dict__) # noqa: S102
except Exception:
raise ImportError(
f"Failed to load workspace module '{name}' "
f"({source_path}):\n{traceback.format_exc()}"
)
finally:
sys.setrecursionlimit(prev_depth)
sys.modules[name] = module
return module
# ---------------------------------------------------------------------------
# Restricted os shim
# ---------------------------------------------------------------------------
def _make_restricted_os() -> types.ModuleType:
"""Return a restricted ``os`` module that only exposes safe, read-only
attributes (``urandom``, ``name``, ``sep``, ``linesep``, ``altsep``,View on GitHub (pinned to 973504e177)
Solutions
- Read the embedded traceback to find the failing line; move import-time logic into a function invoked later.
- Replace blocked imports with allowed ones (only SAFE_MODULES and the allowed g4f subpaths can be imported).
- Wrap risky module-level statements in try/except inside the sandbox module if failure is expected.
- Re-test locally with the same restricted import policy to reproduce before re-uploading.
Example fix
// before (module.pa.py)
import requests # blocklisted -> exec fails -> ImportError
DATA = requests.get('https://x').text
// after
ALLOWED = True
def fetch():
raise NotImplementedError('use the provided tools instead') Defensive patterns
Strategy: try-catch
Validate before calling
def scan_for_blocked_imports(source: str, allowed: set) -> list:
import ast
tree = ast.parse(source)
blocked = []
for node in ast.walk(tree):
if isinstance(node, ast.Import):
blocked += [a.name for a in node.names if a.name.split('.')[0] not in allowed]
elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module:
if node.module.split('.')[0] not in allowed:
blocked.append(node.module)
return blocked Try / catch
try:
module = load_workspace_module(name, source_path)
except ImportError as e:
if "Failed to load workspace module" in str(e):
logger.error("sandbox module crashed at exec:\n%s", e)
return None
raise Prevention
- Keep module-level code minimal; defer work into functions.
- Only import modules on the sandbox allowlist; lint for blocked imports before upload.
- Read the embedded traceback — it pinpoints the failing statement.
When it happens
Trigger: Module-level code that imports a blocklisted module (import requests inside the sandbox), references an undefined global, performs network/file work at import time that fails, or a subclass whose decorator executes immediately.
Common situations: Tool modules doing heavy work at top level instead of inside functions; imports of modules not in SAFE_MODULES; code assuming internet access during load in a restricted environment; a dependency on g4f internals not in _ALLOWED_G4F_SUBPATHS.
Related errors
- Syntax error in workspace module '{name}' ({source_path}):\n
- Relative imports are not allowed inside a .pa.py sandbox.
- Cannot find submodule '{name}' in workspace module '{base}'.
- '{name}' is not available in the restricted os shim.
- Import of '{name}' is not allowed in safe execution mode.\nA
AI-assisted analysis of xtekky/gpt4free@973504e177 (2026-08-14).
Data as JSON: /api/errors/1eff0c2c4472386c.
Report an issue: GitHub.