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

Class Methods

create

Create a new sandbox from a template.
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:
Expected Output:
See Also:

connect

Connect to an existing sandbox by ID.
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:
Expected Output:
See Also:

list

List all sandboxes (loads all into memory).
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:
Expected Output:
See Also:

iter

Lazy iterator for sandboxes (memory-efficient).
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:
Expected Output:
See Also:

list_templates

List available templates.
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:
Expected Output:
See Also:

get_template

Get template details by name.
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:
Expected Output:
See Also:

health_check

Check API health status (does not require authentication).
Parameters:
  • base_url (str, optional): API base URL
Returns: Dict[str, Any] - Health status information Example:
Expected Output:

Instance Methods

Lifecycle Methods

get_info

Get current sandbox information.
Returns: SandboxInfo - Sandbox information object Example:
Expected Output:
See Also:

start

Start a stopped sandbox.
Raises:
  • APIError: Failed to start sandbox
Example:
Expected Output:
See Also:

stop

Stop the sandbox.
Example:
Expected Output:
See Also:

pause

Pause the sandbox.
Example:
Expected Output:
See Also:

resume

Resume a paused sandbox.
Example:
Expected Output:
See Also:

kill

Destroy the sandbox immediately.
This action is irreversible. The sandbox and all its data will be permanently deleted.
Example:
Expected Output:
See Also:

Execution Methods

run_code

Execute code with rich output capture.
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:
Expected Output:
See Also:

run_code_background

Execute code in background and return immediately.
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:
Expected Output:
See Also:

list_processes

List all background execution processes.
Returns: List[Dict[str, Any]] - List of process dictionaries Example:
Expected Output:
See Also:

kill_process

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

Information Methods

get_agent_metrics

Get real-time agent metrics.
Returns: Dict[str, Any] - Metrics dictionary with total_executions, active_executions, error_count, etc. Example:
Expected Output:
See Also:

get_agent_info

Get VM agent information (version, OS, architecture, endpoints, features).
Returns: Dict[str, Any] - Agent information dictionary
Requires Agent v3.1.0+. Uses GET /info endpoint.
Example:
Expected Output:

get_preview_url

Get preview URL for accessing a service running on a specific port.
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:
Expected Output:

get_metrics_snapshot

Get current system metrics snapshot.
Returns: Dict[str, Any] - System metrics dictionary Example:
Expected Output:

Utility Methods

set_timeout

Extend sandbox timeout.
Parameters:
  • seconds (int): New timeout in seconds
Example:
See Also:

refresh_token

Refresh JWT token for agent authentication.
Example:
Expected Output:

get_token

Get current JWT token.
Returns: str - JWT token string Example:
Expected Output:

Properties

files

File operations resource (lazy-loaded). Type: Files Example:
Expected Output:
See Files Resource for complete documentation.

commands

Command execution resource (lazy-loaded). Type: Commands Example:
Expected Output:
See Commands Resource for complete documentation.

env

Environment variables resource (lazy-loaded). Type: EnvironmentVariables Example:
Expected Output:
See Environment Variables Resource for complete documentation.

desktop

Desktop automation resource (lazy-loaded). Type: Desktop Example:
Expected Output:
See Desktop Resource for complete documentation.

cache

Cache management resource (lazy-loaded). Type: Cache Example:
Expected Output:
See Cache Resource for complete documentation.

terminal

Interactive terminal resource via WebSocket (lazy-loaded). Type: Terminal
Requires websockets library: pip install websockets
Example:
Expected Output:
See Terminal Resource for complete documentation.

agent_url

Get the sandbox agent URL (port 7777) - convenience property. Type: str (read-only) Example:
Expected Output:

Context Manager

The Sandbox class supports context manager protocol for automatic cleanup. Example:
Expected Output:

Examples

Example 1: Basic Usage

Expected Output:

Example 2: Using Context Manager

Expected Output:

Example 3: File Operations

Expected Output:

Example 4: Background Execution

Expected Output:

See Also

Next Steps