Skip to main content
Version: 0.3.0
Last Verified: 2025-01-27
Package: hopx-ai on PyPI

Overview

The Sandbox class is the main entry point for the HopX Python SDK. It provides a synchronous interface for creating, managing, and interacting with cloud sandboxes (microVMs). Use this class when you’re building synchronous Python applications or scripts. The Sandbox class handles authentication, request formatting, error translation, and response parsing automatically, giving you a clean, Pythonic API for sandbox management.

When to Use Sandbox vs AsyncSandbox

  • Use Sandbox when:
    • Building synchronous Python applications
    • Writing scripts or simple automation
    • You prefer blocking operations
    • You don’t need async/await patterns
  • Use AsyncSandbox when:
    • Building async Python applications (FastAPI, aiohttp, etc.)
    • You need to manage multiple sandboxes concurrently
    • You want non-blocking operations
    • You’re already using async/await in your codebase

Import

from hopx_ai import Sandbox

Class Methods

create

Create a new sandbox from a template.
Sandbox.create(
    template=None,
    *,
    template_id=None,
    region=None,
    timeout_seconds=None,
    internet_access=None,
    env_vars=None,
    api_key=None,
    base_url='https://api.hopx.dev'
) -> Sandbox
Parameters:
  • template (str, optional): Template name (e.g., "code-interpreter")
  • template_id (str, optional): Template ID (alternative to template name)
  • region (str, optional): Preferred region (auto-selected if not specified)
  • timeout_seconds (int, optional): Auto-kill timeout in seconds (default: no timeout)
  • internet_access (bool, optional): Enable internet access (default: True)
  • env_vars (Dict[str, str], optional): Environment variables to set in the sandbox
  • api_key (str, optional): API key (or use HOPX_API_KEY env var)
  • base_url (str, optional): API base URL (default: production)
Returns: Sandbox - New sandbox instance Raises:
  • ValidationError: Invalid parameters
  • ResourceLimitError: Insufficient resources
  • APIError: API request failed
Example:
# Create from template name
sandbox = Sandbox.create(template="code-interpreter")
print(sandbox.get_info().public_host)

# Create with timeout and environment variables
sandbox = Sandbox.create(
    template="code-interpreter",
    timeout_seconds=300,
    env_vars={"DEBUG": "true", "API_KEY": "secret"}
)
Expected Output:
https://sandbox_abc123xyz.hopx.dev
See Also:

connect

Connect to an existing sandbox by ID.
Sandbox.connect(
    sandbox_id,
    *,
    api_key=None,
    base_url='https://api.hopx.dev'
) -> Sandbox
Parameters:
  • sandbox_id (str): Existing sandbox ID
  • api_key (str, optional): API key (or use HOPX_API_KEY env var)
  • base_url (str, optional): API base URL
Returns: Sandbox - Connected sandbox instance Raises:
  • NotFoundError: Sandbox not found
  • APIError: API request failed
Example:
sandbox = Sandbox.connect("sandbox-abc123")
info = sandbox.get_info()
print(f"Status: {info.status}")
Expected Output:
Status: running
See Also:

list

List all sandboxes (loads all into memory).
Sandbox.list(
    *,
    status=None,
    region=None,
    limit=100,
    api_key=None,
    base_url='https://api.hopx.dev'
) -> List[Sandbox]
Parameters:
  • status (str, optional): Filter by status ("running", "stopped", "paused", "creating")
  • region (str, optional): Filter by region
  • limit (int, optional): Maximum number of sandboxes to return (default: 100)
  • api_key (str, optional): API key
  • base_url (str, optional): API base URL
Returns: List[Sandbox] - List of sandbox instances Example:
# List all running sandboxes
running = Sandbox.list(status="running")
for sb in running:
    print(f"{sb.sandbox_id}: {sb.get_info().status}")

# List sandboxes in specific region
sandboxes = Sandbox.list(region="us-east", limit=50)
Expected Output:
sandbox_abc123xyz: running
sandbox_def456uvw: running
sandbox_ghi789rst: paused
See Also:

iter

Lazy iterator for sandboxes (memory-efficient).
Sandbox.iter(
    *,
    status=None,
    region=None,
    api_key=None,
    base_url='https://api.hopx.dev'
) -> Iterator[Sandbox]
Parameters:
  • status (str, optional): Filter by status
  • region (str, optional): Filter by region
  • api_key (str, optional): API key
  • base_url (str, optional): API base URL
Returns: Iterator[Sandbox] - Iterator of sandbox instances Example:
# Iterate over all sandboxes (memory-efficient)
for sandbox in Sandbox.iter(status="running"):
    info = sandbox.get_info()
    print(f"{info.sandbox_id}: {info.status}")
Expected Output:
sandbox_abc123xyz: running
sandbox_def456uvw: running
See Also:

list_templates

List available templates.
Sandbox.list_templates(
    *,
    category=None,
    language=None,
    api_key=None,
    base_url='https://api.hopx.dev'
) -> List[Template]
Parameters:
  • category (str, optional): Filter by category
  • language (str, optional): Filter by language
  • api_key (str, optional): API key
  • base_url (str, optional): API base URL
Returns: List[Template] - List of template objects Example:
# List all Python templates
python_templates = Sandbox.list_templates(language="python")
for template in python_templates:
    print(f"{template.name}: {template.description}")
Expected Output:
code-interpreter: Python environment with data science libraries
python-basic: Minimal Python 3.11 environment
See Also:

get_template

Get template details by name.
Sandbox.get_template(
    name,
    *,
    api_key=None,
    base_url='https://api.hopx.dev'
) -> Template
Parameters:
  • name (str): Template name
  • api_key (str, optional): API key
  • base_url (str, optional): API base URL
Returns: Template - Template object with details Raises:
  • NotFoundError: Template not found
Example:
template = Sandbox.get_template("code-interpreter")
print(f"Resources: {template.resources.vcpu} vCPU, {template.resources.memory_mb}MB RAM")
Expected Output:
Resources: 2 vCPU, 4096MB RAM
See Also:

health_check

Check API health status (does not require authentication).
Sandbox.health_check(
    *,
    base_url='https://api.hopx.dev'
) -> Dict[str, Any]
Parameters:
  • base_url (str, optional): API base URL
Returns: Dict[str, Any] - Health status information Example:
health = Sandbox.health_check()
print(f"API Status: {health.get('status')}")
Expected Output:
API Status: healthy

Instance Methods

Lifecycle Methods

get_info

Get current sandbox information.
sandbox.get_info() -> SandboxInfo
Returns: SandboxInfo - Sandbox information object Example:
info = sandbox.get_info()
print(f"ID: {info.sandbox_id}")
print(f"Status: {info.status}")
print(f"Host: {info.public_host}")
Expected Output:
ID: sandbox_abc123xyz
Status: running
Host: https://sandbox_abc123xyz.hopx.dev
See Also:

start

Start a stopped sandbox.
sandbox.start() -> None
Raises:
  • APIError: Failed to start sandbox
Example:
sandbox.start()
print("Sandbox started")
Expected Output:
Sandbox started
See Also:

stop

Stop the sandbox.
sandbox.stop() -> None
Example:
sandbox.stop()
print("Sandbox stopped")
Expected Output:
Sandbox stopped
See Also:

pause

Pause the sandbox.
sandbox.pause() -> None
Example:
sandbox.pause()
print("Sandbox paused")
Expected Output:
Sandbox paused
See Also:

resume

Resume a paused sandbox.
sandbox.resume() -> None
Example:
sandbox.resume()
print("Sandbox resumed")
Expected Output:
Sandbox resumed
See Also:

kill

Destroy the sandbox immediately.
sandbox.kill() -> None
This action is irreversible. The sandbox and all its data will be permanently deleted.
Example:
sandbox.kill()
print("Sandbox destroyed")
Expected Output:
Sandbox destroyed
See Also:

Execution Methods

run_code

Execute code with rich output capture.
sandbox.run_code(
    code,
    *,
    language='python',
    timeout=60,
    env=None,
    working_dir='/workspace'
) -> ExecutionResult
Parameters:
  • code (str): Code to execute
  • language (str, optional): Language ("python", "javascript", "bash", "go") (default: "python")
  • timeout (int, optional): Execution timeout in seconds (default: 60)
  • env (Dict[str, str], optional): Environment variables for execution
  • working_dir (str, optional): Working directory (default: "/workspace")
Returns: ExecutionResult - Execution result with stdout, stderr, exit_code, and rich_outputs Example:
result = sandbox.run_code("print('Hello, HopX!')")
print(result.stdout)  # "Hello, HopX!\n"
print(result.exit_code)  # 0
Expected Output:
Hello, HopX!
0
See Also:

run_code_background

Execute code in background and return immediately.
sandbox.run_code_background(
    code,
    *,
    language='python',
    timeout=300,
    env=None,
    working_dir='/workspace',
    name=None
) -> Dict[str, Any]
Parameters:
  • code (str): Code to execute
  • language (str, optional): Language (default: "python")
  • timeout (int, optional): Max execution time in seconds (default: 300)
  • env (Dict[str, str], optional): Environment variables
  • working_dir (str, optional): Working directory
  • name (str, optional): Process name for identification
Returns: Dict[str, Any] - Dict with process_id, execution_id, and status Example:
proc = sandbox.run_code_background(
    "import time; time.sleep(300); print('Done')",
    name="long-task"
)
print(f"Process ID: {proc['process_id']}")

# Check status later
processes = sandbox.list_processes()
Expected Output:
Process ID: proc-abc123xyz
See Also:

list_processes

List all background execution processes.
sandbox.list_processes() -> List[Dict[str, Any]]
Returns: List[Dict[str, Any]] - List of process dictionaries Example:
processes = sandbox.list_processes()
for proc in processes:
    print(f"{proc['process_id']}: {proc['status']}")
Expected Output:
proc_abc123: running
proc_def456: completed
See Also:

kill_process

Kill a background execution process.
sandbox.kill_process(process_id) -> Dict[str, Any]
Parameters:
  • process_id (str): Process ID from run_code_background() or list_processes()
Returns: Dict[str, Any] - Confirmation message Example:
sandbox.kill_process("proc-abc123")
Expected Output:
Process killed successfully
See Also:

Information Methods

get_agent_metrics

Get real-time agent metrics.
sandbox.get_agent_metrics() -> Dict[str, Any]
Returns: Dict[str, Any] - Metrics dictionary with total_executions, active_executions, error_count, etc. Example:
metrics = sandbox.get_agent_metrics()
print(f"Total executions: {metrics['total_executions']}")
print(f"Active: {metrics['active_executions']}")
Expected Output:
Total executions: 42
Active: 2
See Also:

get_agent_info

Get VM agent information (version, OS, architecture, endpoints, features).
sandbox.get_agent_info() -> Dict[str, Any]
Returns: Dict[str, Any] - Agent information dictionary
Requires Agent v3.1.0+. Uses GET /info endpoint.
Example:
info = sandbox.get_agent_info()
print(f"Agent version: {info['version']}")
print(f"OS: {info['os']}")
Expected Output:
Agent version: 3.1.0
OS: linux

get_preview_url

Get preview URL for accessing a service running on a specific port.
sandbox.get_preview_url(port=7777) -> str
Parameters:
  • port (int, optional): Port number (default: 7777)
Returns: str - Preview URL
HopX automatically exposes all ports. Use this to get the public URL for any port.
Example:
# Start a web server
sandbox.run_code("python -m http.server 8000", background=True)

# Get preview URL
url = sandbox.get_preview_url(port=8000)
print(f"Access at: {url}")
Expected Output:
Access at: https://8000-sandbox_abc123xyz.hopx.dev

get_metrics_snapshot

Get current system metrics snapshot.
sandbox.get_metrics_snapshot() -> Dict[str, Any]
Returns: Dict[str, Any] - System metrics dictionary Example:
metrics = sandbox.get_metrics_snapshot()
print(f"CPU: {metrics.get('cpu_percent')}%")
print(f"Memory: {metrics.get('memory_percent')}%")
Expected Output:
CPU: 15.3%
Memory: 42.1%

Utility Methods

set_timeout

Extend sandbox timeout.
sandbox.set_timeout(seconds) -> None
Parameters:
  • seconds (int): New timeout in seconds
Example:
sandbox.set_timeout(3600)  # Extend to 1 hour
See Also:

refresh_token

Refresh JWT token for agent authentication.
sandbox.refresh_token() -> None
Example:
sandbox.refresh_token()
Expected Output:
Token refreshed successfully

get_token

Get current JWT token.
sandbox.get_token() -> str
Returns: str - JWT token string Example:
token = sandbox.get_token()
print(f"Token: {token[:20]}...")
Expected Output:
Token: eyJhbGciOiJIUzI1NiIs...

Properties

files

File operations resource (lazy-loaded). Type: Files Example:
# Read a file
content = sandbox.files.read("/workspace/script.py")

# Write a file
sandbox.files.write("/workspace/data.txt", "Hello, World!")
Expected Output:
File written successfully
See Files Resource for complete documentation.

commands

Command execution resource (lazy-loaded). Type: Commands Example:
result = sandbox.commands.run("ls -la /workspace")
print(result.stdout)
Expected Output:
total 8
drwxr-xr-x 2 root root 4096 Jan 27 10:30 .
drwxr-xr-x 3 root root 4096 Jan 27 10:30 ..
-rw-r--r-- 1 root root   42 Jan 27 10:30 data.txt
See Commands Resource for complete documentation.

env

Environment variables resource (lazy-loaded). Type: EnvironmentVariables Example:
# Set environment variable
sandbox.env.set("API_KEY", "secret123")

# Get all environment variables
all_vars = sandbox.env.get_all()
Expected Output:
Environment variable set successfully
See Environment Variables Resource for complete documentation.

desktop

Desktop automation resource (lazy-loaded). Type: Desktop Example:
# Take a screenshot
screenshot = sandbox.desktop.screenshot()

# Click at position
sandbox.desktop.click(100, 200)
Expected Output:
Screenshot captured (PNG bytes)
Click executed at (100, 200)
See Desktop Resource for complete documentation.

cache

Cache management resource (lazy-loaded). Type: Cache Example:
# Get cache statistics
stats = sandbox.cache.stats()
print(f"Cache size: {stats['cache']['size']}")

# Clear cache
sandbox.cache.clear()
Expected Output:
Cache size: 5
Cache cleared successfully
See Cache Resource for complete documentation.

terminal

Interactive terminal resource via WebSocket (lazy-loaded). Type: Terminal
Requires websockets library: pip install websockets
Example:
import asyncio

async def use_terminal():
    ws = await sandbox.terminal.connect()
    await sandbox.terminal.send_input(ws, "echo 'Hello'\n")
    # ... handle output
    await ws.close()

asyncio.run(use_terminal())
Expected Output:
Terminal connected
Hello
Terminal closed
See Terminal Resource for complete documentation.

agent_url

Get the sandbox agent URL (port 7777) - convenience property. Type: str (read-only) Example:
url = sandbox.agent_url
print(f"Agent URL: {url}")
Expected Output:
Agent URL: https://sandbox_abc123xyz.hopx.dev

Context Manager

The Sandbox class supports context manager protocol for automatic cleanup. Example:
# Automatically calls kill() when exiting context
with Sandbox.create(template="code-interpreter") as sandbox:
    result = sandbox.run_code("print('Hello')")
    print(result.stdout)
# Sandbox is automatically destroyed here
Expected Output:
Hello

Examples

Example 1: Basic Usage

from hopx_ai import Sandbox

# Create sandbox
sandbox = Sandbox.create(template="code-interpreter")

# Execute code
result = sandbox.run_code("print('Hello, HopX!')")
print(result.stdout)

# Cleanup
sandbox.kill()
Expected Output:
Hello, HopX!

Example 2: Using Context Manager

from hopx_ai import Sandbox

with Sandbox.create(template="code-interpreter") as sandbox:
    # Work with sandbox
    result = sandbox.run_code("import sys; print(sys.version)")
    print(result.stdout)
# Automatically cleaned up
Expected Output:
3.11.5 (main, Jan 27 2025, 10:30:00) [GCC 11.2.0]

Example 3: File Operations

from hopx_ai import Sandbox

sandbox = Sandbox.create(template="code-interpreter")

# Write a file
sandbox.files.write("/workspace/script.py", "print('Hello')")

# Execute it
result = sandbox.run_code("exec(open('/workspace/script.py').read())")
print(result.stdout)

sandbox.kill()
Expected Output:
Hello

Example 4: Background Execution

from hopx_ai import Sandbox
import time

sandbox = Sandbox.create(template="code-interpreter")

# Start long-running task
proc = sandbox.run_code_background(
    "import time; time.sleep(60); print('Done')",
    name="long-task"
)

# Do other work
time.sleep(5)

# Check status
processes = sandbox.list_processes()
for p in processes:
    if p['process_id'] == proc['process_id']:
        print(f"Status: {p['status']}")

sandbox.kill()
Expected Output:
Status: running

See Also

Next Steps