Last Verified: 2025-01-27
Package:
hopx-ai on PyPI
Overview
TheSandbox 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
Sandboxwhen:- Building synchronous Python applications
- Writing scripts or simple automation
- You prefer blocking operations
- You don’t need async/await patterns
-
Use
AsyncSandboxwhen:- 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.
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 sandboxapi_key(str, optional): API key (or useHOPX_API_KEYenv var)base_url(str, optional): API base URL (default: production)
Sandbox - New sandbox instance
Raises:
ValidationError: Invalid parametersResourceLimitError: Insufficient resourcesAPIError: API request failed
connect
Connect to an existing sandbox by ID.
sandbox_id(str): Existing sandbox IDapi_key(str, optional): API key (or useHOPX_API_KEYenv var)base_url(str, optional): API base URL
Sandbox - Connected sandbox instance
Raises:
NotFoundError: Sandbox not foundAPIError: API request failed
list
List all sandboxes (loads all into memory).
status(str, optional): Filter by status ("running","stopped","paused","creating")region(str, optional): Filter by regionlimit(int, optional): Maximum number of sandboxes to return (default:100)api_key(str, optional): API keybase_url(str, optional): API base URL
List[Sandbox] - List of sandbox instances
Example:
iter
Lazy iterator for sandboxes (memory-efficient).
status(str, optional): Filter by statusregion(str, optional): Filter by regionapi_key(str, optional): API keybase_url(str, optional): API base URL
Iterator[Sandbox] - Iterator of sandbox instances
Example:
list_templates
List available templates.
category(str, optional): Filter by categorylanguage(str, optional): Filter by languageapi_key(str, optional): API keybase_url(str, optional): API base URL
List[Template] - List of template objects
Example:
get_template
Get template details by name.
name(str): Template nameapi_key(str, optional): API keybase_url(str, optional): API base URL
Template - Template object with details
Raises:
NotFoundError: Template not found
health_check
Check API health status (does not require authentication).
base_url(str, optional): API base URL
Dict[str, Any] - Health status information
Example:
Instance Methods
Lifecycle Methods
get_info
Get current sandbox information.
SandboxInfo - Sandbox information object
Example:
start
Start a stopped sandbox.
APIError: Failed to start sandbox
stop
Stop the sandbox.
pause
Pause the sandbox.
resume
Resume a paused sandbox.
kill
Destroy the sandbox immediately.
Execution Methods
run_code
Execute code with rich output capture.
code(str): Code to executelanguage(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 executionworking_dir(str, optional): Working directory (default:"/workspace")
ExecutionResult - Execution result with stdout, stderr, exit_code, and rich_outputs
Example:
run_code_background
Execute code in background and return immediately.
code(str): Code to executelanguage(str, optional): Language (default:"python")timeout(int, optional): Max execution time in seconds (default:300)env(Dict[str, str], optional): Environment variablesworking_dir(str, optional): Working directoryname(str, optional): Process name for identification
Dict[str, Any] - Dict with process_id, execution_id, and status
Example:
list_processes
List all background execution processes.
List[Dict[str, Any]] - List of process dictionaries
Example:
kill_process
Kill a background execution process.
process_id(str): Process ID fromrun_code_background()orlist_processes()
Dict[str, Any] - Confirmation message
Example:
Information Methods
get_agent_metrics
Get real-time agent metrics.
Dict[str, Any] - Metrics dictionary with total_executions, active_executions, error_count, etc.
Example:
get_agent_info
Get VM agent information (version, OS, architecture, endpoints, features).
Dict[str, Any] - Agent information dictionary
Requires Agent v3.1.0+. Uses GET /info endpoint.
get_preview_url
Get preview URL for accessing a service running on a specific port.
port(int, optional): Port number (default:7777)
str - Preview URL
HopX automatically exposes all ports. Use this to get the public URL for any port.
get_metrics_snapshot
Get current system metrics snapshot.
Dict[str, Any] - System metrics dictionary
Example:
Utility Methods
set_timeout
Extend sandbox timeout.
seconds(int): New timeout in seconds
refresh_token
Refresh JWT token for agent authentication.
get_token
Get current JWT token.
str - JWT token string
Example:
Properties
files
File operations resource (lazy-loaded).
Type: Files
Example:
commands
Command execution resource (lazy-loaded).
Type: Commands
Example:
env
Environment variables resource (lazy-loaded).
Type: EnvironmentVariables
Example:
desktop
Desktop automation resource (lazy-loaded).
Type: Desktop
Example:
cache
Cache management resource (lazy-loaded).
Type: Cache
Example:
terminal
Interactive terminal resource via WebSocket (lazy-loaded).
Type: Terminal
Requires
websockets library: pip install websocketsagent_url
Get the sandbox agent URL (port 7777) - convenience property.
Type: str (read-only)
Example:
Context Manager
TheSandbox class supports context manager protocol for automatic cleanup.
Example:
Examples
Example 1: Basic Usage
Example 2: Using Context Manager
Example 3: File Operations
Example 4: Background Execution
Related Classes
- AsyncSandbox - Async version of Sandbox for async/await workflows
- Files - File operations resource
- Commands - Command execution resource
- Environment Variables - Environment variable management
- Desktop - Desktop automation resource
- Cache - Cache management resource
- Terminal - Interactive terminal resource
See Also
- Quickstart Guide - Get started with the SDK
- Installation - Install and configure the SDK
- Core Concepts - Learn about sandboxes
Next Steps
- Learn about AsyncSandbox for async/await workflows
- Explore Creating Sandboxes with different templates
- Review Code Execution to run code in sandboxes
- Check out File Operations for managing files
- See API Reference for direct API access
- CLI Reference - Use HopX from the command line
- API Reference - Raw REST API documentation

