Skip to main content

Sandbox Class

The Sandbox class is the main entry point for interacting with Hopx sandboxes. It provides methods for creating, connecting to, and managing sandboxes, as well as access to all resources.

Class Definition

from hopx_ai import Sandbox

class Sandbox:
    def __init__(
        self,
        sandbox_id: str,
        *,
        api_key: Optional[str] = None,
        base_url: str = "https://api.hopx.dev",
        timeout: int = 60,
        max_retries: int = 3,
    )

Class Methods

Sandbox.create()

Create a new sandbox from a template.
@classmethod
def create(
    cls,
    template: Optional[str] = None,
    *,
    template_id: Optional[str] = None,
    region: Optional[str] = None,
    timeout_seconds: Optional[int] = None,
    internet_access: Optional[bool] = None,
    env_vars: Optional[Dict[str, str]] = None,
    api_key: Optional[str] = None,
    base_url: str = "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): API base URL (default: production)
Returns: Sandbox instance Raises:
  • ValidationError: Invalid parameters
  • ResourceLimitError: Insufficient resources
  • APIError: API request failed
Example:
# Create from template name
sandbox = Sandbox.create(template="code-interpreter")

# Create from template ID with timeout
sandbox = Sandbox.create(
    template_id="291",
    timeout_seconds=300,
    internet_access=True
)

# Create with environment variables
sandbox = Sandbox.create(
    template="my-python-template",
    env_vars={"DEBUG": "true", "API_KEY": "sk-123"}
)

Sandbox.connect()

Connect to an existing sandbox.
@classmethod
def connect(
    cls,
    sandbox_id: str,
    *,
    api_key: Optional[str] = None,
    base_url: str = "https://api.hopx.dev",
) -> "Sandbox"
Parameters:
  • sandbox_id (str): Sandbox ID
  • api_key (str, optional): API key (or use HOPX_API_KEY env var)
  • base_url (str): API base URL
Returns: Sandbox instance Raises:
  • NotFoundError: Sandbox not found
  • HopxError: If sandbox is stopped or in invalid state
Note: If the sandbox is paused, it will be automatically resumed. Example:
sandbox = Sandbox.connect("1761048129dsaqav4n")
info = sandbox.get_info()
print(info.status)

Sandbox.iter()

Lazy iterator for listing sandboxes.
@classmethod
def iter(
    cls,
    *,
    status: Optional[str] = None,
    region: Optional[str] = None,
    api_key: Optional[str] = None,
    base_url: str = "https://api.hopx.dev",
) -> Iterator["Sandbox"]
Parameters:
  • status (str, optional): Filter by status (“running”, “stopped”, “paused”, “creating”)
  • region (str, optional): Filter by region
  • api_key (str, optional): API key
  • base_url (str): API base URL
Returns: Iterator of Sandbox instances Example:
# List all running sandboxes
for sandbox in Sandbox.iter(status="running"):
    print(f"{sandbox.sandbox_id}: {sandbox.get_info().status}")

# List all sandboxes in a region
for sandbox in Sandbox.iter(region="us-east"):
    info = sandbox.get_info()
    print(f"{info.sandbox_id}: {info.template_name}")

Sandbox.list()

List all sandboxes (returns list, not iterator).
@classmethod
def list(
    *,
    status: Optional[str] = None,
    region: Optional[str] = None,
    limit: Optional[int] = None,
    api_key: Optional[str] = None,
    base_url: str = "https://api.hopx.dev",
) -> List[SandboxInfo]
Parameters:
  • status (str, optional): Filter by status
  • region (str, optional): Filter by region
  • limit (int, optional): Maximum number of sandboxes to return
  • api_key (str, optional): API key
  • base_url (str): API base URL
Returns: List of SandboxInfo objects Example:
# List all sandboxes
sandboxes = Sandbox.list()
for info in sandboxes:
    print(f"{info.sandbox_id}: {info.template_name}")

# List running sandboxes with limit
running = Sandbox.list(status="running", limit=10)

Instance Methods

Lifecycle Methods

get_info()

Get sandbox information.
def get_info(self) -> SandboxInfo
Returns: SandboxInfo object with sandbox details Example:
info = sandbox.get_info()
print(f"ID: {info.sandbox_id}")
print(f"Status: {info.status}")
print(f"Template: {info.template_name}")
print(f"Host: {info.public_host}")
if info.resources:
    print(f"Resources: {info.resources.vcpu} vCPU, {info.resources.memory_mb}MB RAM")

kill()

Delete the sandbox.
def kill(self) -> None
Example:
sandbox.kill()

start()

Start a stopped sandbox.
def start(self) -> None
Example:
sandbox.start()

stop()

Stop a running sandbox.
def stop(self) -> None
Example:
sandbox.stop()

pause()

Pause a running sandbox.
def pause(self) -> None
Example:
sandbox.pause()

resume()

Resume a paused sandbox.
def resume(self) -> None
Example:
sandbox.resume()

Code Execution

run_code()

Execute code synchronously.
def run_code(
    self,
    code: str,
    *,
    language: str = "python",
    timeout: int = 60,
    working_dir: str = "/workspace",
    env: Optional[Dict[str, str]] = None,
    rich: bool = False,
) -> ExecutionResult
Parameters:
  • code (str): Code to execute
  • language (str): Language (“python”, “javascript”, “bash”, “go”)
  • timeout (int): Execution timeout in seconds (default: 60)
  • working_dir (str): Working directory (default: “/workspace”)
  • env (Dict[str, str], optional): Environment variables for this execution
  • rich (bool): If True, captures rich outputs (plots, DataFrames) (default: False)
Returns: ExecutionResult with stdout, stderr, exit_code, execution_time Example:
# Simple execution
result = sandbox.run_code('print("Hello, World!")')
print(result.stdout)

# With rich outputs
result = sandbox.run_code(
    '''
import matplotlib.pyplot as plt
plt.plot([1, 2, 3])
plt.savefig('/workspace/plot.png')
''',
    rich=True
)
print(f"Rich outputs: {len(result.rich_outputs)}")

# With environment variables
result = sandbox.run_code(
    'import os; print(os.environ.get("API_KEY"))',
    env={"API_KEY": "sk-test-123"}
)

Properties

files

File operations resource (lazy-loaded).
@property
def files(self) -> Files
Example:
# Read file
content = sandbox.files.read('/workspace/data.txt')

# Write file
sandbox.files.write('/workspace/output.txt', 'Hello!')

# List directory
files = sandbox.files.list('/workspace')
See File Operations for complete reference.

commands

Command execution resource (lazy-loaded).
@property
def commands(self) -> Commands
Example:
# Run command
result = sandbox.commands.run('ls -la /workspace')
print(result.stdout)

# Run with timeout
result = sandbox.commands.run('npm install', timeout=300)
See Commands for complete reference.

desktop

Desktop automation resource (lazy-loaded).
@property
def desktop(self) -> Desktop
Example:
# Start VNC
vnc_info = sandbox.desktop.start_vnc()
print(f"VNC URL: {vnc_info.url}")

# Screenshot
img = sandbox.desktop.screenshot()
See Desktop for complete reference.

env

Environment variables resource (lazy-loaded).
@property
def env(self) -> EnvironmentVariables
Example:
# Get all env vars
env = sandbox.env.get_all()

# Set env var
sandbox.env.set("API_KEY", "sk-prod-xyz")

# Update multiple
sandbox.env.update({"NODE_ENV": "production", "DEBUG": "false"})
See Environment Variables for complete reference.

cache

Cache management resource (lazy-loaded).
@property
def cache(self) -> Cache
Example:
# Get cache stats
stats = sandbox.cache.stats()
print(f"Cache size: {stats['size']} MB")

# Clear cache
sandbox.cache.clear()

terminal

Interactive terminal resource (lazy-loaded, requires websockets).
@property
def terminal(self) -> Terminal
Example:
import asyncio

async def use_terminal():
    async with await sandbox.terminal.connect() as ws:
        await sandbox.terminal.send_input(ws, "ls -la\n")
        async for message in sandbox.terminal.iter_output(ws):
            if message['type'] == 'output':
                print(message['data'], end='')

asyncio.run(use_terminal())

Advanced Methods

get_token()

Get current JWT token for agent authentication.
def get_token(self) -> str
Returns: JWT token string Note: Automatically refreshes if needed. Used internally for agent operations.

refresh_token()

Refresh JWT token for agent authentication.
def refresh_token(self) -> None
Note: Called automatically when token is about to expire (less than 1 hour left).

Automatic Cleanup

The preferred way to ensure automatic cleanup is using timeout_seconds:
# Preferred: Auto-kill after timeout
sandbox = Sandbox.create(template="code-interpreter", timeout_seconds=600)
result = sandbox.run_code('print("Hello!")')
print(result.stdout)
# Sandbox is automatically killed after 600 seconds
Alternatively, the Sandbox class supports context manager protocol:
# Alternative: Context manager (auto-kill on exit)
with Sandbox.create(template="code-interpreter") as sandbox:
    result = sandbox.run_code('print("Hello!")')
    print(result.stdout)
# Sandbox is automatically killed here

AsyncSandbox

For async/await workflows, use AsyncSandbox:
from hopx_ai import AsyncSandbox

async with AsyncSandbox.create(template="node-runtime") as sandbox:
    info = await sandbox.get_info()
    result = await sandbox.run_code('console.log("Hello!")')
See Python SDK Overview for more information about AsyncSandbox.