Skip to main content
Sandboxes are isolated, ephemeral cloud environments where your code runs. This guide shows you how to create sandboxes from templates with custom configuration options.

Prerequisites

Before you begin, make sure you have:
  • HopX API key - Get one from console.hopx.dev or see [API key Management](/API key)
  • SDK installed - Python SDK (pip install hopx-ai) or JavaScript SDK (npm install @hopx-ai/sdk)
  • Basic understanding - Familiarity with the Quickstart Guide is helpful

Overview

When you create a sandbox, HopX:
  • Spins up a lightweight VM in seconds (~100ms)
  • Loads resources (CPU, memory, disk) from the template
  • Provides a persistent filesystem during the sandbox lifecycle
  • Auto-destroys the sandbox after timeout (if configured)
Resources (vcpu, memory, disk) are always loaded from the template. You cannot specify custom resources when creating a sandbox. To use different resources, create a custom template first.

Basic Creation

The simplest way to create a sandbox is using a template name:
  • Python
  • JavaScript
from hopx_ai import Sandbox

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

print(f"Sandbox ID: {sandbox.sandbox_id}")
info = sandbox.get_info()
print(f"Status: {info.status}")
print(f"URL: {info.public_host}")

# Clean up when done
sandbox.kill()
Expected Output:
Sandbox ID: sandbox_abc123xyz
Status: running
URL: https://sandbox_abc123xyz.hopx.dev

Using Template ID

You can also create a sandbox using a template ID instead of a name:
  • Python
  • JavaScript
from hopx_ai import Sandbox

# Create from template ID
sandbox = Sandbox.create(template_id="119")

# Cleanup when done
sandbox.kill()
Expected Output:
Sandbox created successfully

Configuration Options

When creating a sandbox, you can configure several options:

Timeout

Set an auto-kill timeout to automatically destroy the sandbox after a specified duration:
  • Python
  • JavaScript
from hopx_ai import Sandbox

# Create with 1 hour timeout
sandbox = Sandbox.create(
    template="code-interpreter",
    timeout_seconds=3600  # 1 hour
)

info = sandbox.get_info()
if info.expires_at:
    print(f"Sandbox expires at: {info.expires_at}")
Expected Output:
Sandbox expires at: 2025-01-27T11:30:00Z

Internet Access

Control whether the sandbox has internet access:
  • Python
  • JavaScript
from hopx_ai import Sandbox

# Create without internet access (isolated)
sandbox = Sandbox.create(
    template="code-interpreter",
    internet_access=False
)

info = sandbox.get_info()
print(f"Internet access: {info.internet_access}")

# Try to fetch an online resource to demonstrate lack of internet connectivity
result = sandbox.run_code("""
import urllib.request
import urllib.error

try:
    response = urllib.request.urlopen('https://www.hopx.ai', timeout=10)
    print(f"✅ Successfully fetched hopx.ai - Status: {response.status}")
    print(f"Content-Type: {response.headers.get('Content-Type')}")
except urllib.error.URLError as e:
    print(f"❌ Failed to fetch URL: {e.reason}")
except Exception as e:
    print(f"❌ Error: {type(e).__name__}: {e}")
""", language="python")

print("Fetch attempt output:")
print(result.stdout)
if result.stderr:
    print("Errors:")
    print(result.stderr)

if result.exit_code != 0:
    print("\n❌ Code execution failed")
elif "Failed to fetch" in result.stdout or "Error:" in result.stdout:
    print("\n❌ As expected, the fetch failed. Sandbox does not have internet access.")
else:
    print("\n✅ Unexpected: fetch succeeded, internet access is enabled!")

# Clean up when done
sandbox.kill()

Environment Variables

Set initial environment variables when creating the sandbox:
  • Python
  • JavaScript
from hopx_ai import Sandbox

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

# Verify environment variables
result = sandbox.run_code(
    "import os; print(dict(os.environ))",
    language="python"
)
print(result.stdout)  

# Clean up when done
sandbox.kill()
Expected Output:
{'API_KEY': 'sk-123', 'DEBUG': 'true', 'ENVIRONMENT': 'production', 'PATH': '/usr/local/bin:/usr/bin:/bin', ...}

Using Context Managers (Python)

Python SDK supports context managers for automatic cleanup:
from hopx_ai import Sandbox

# Automatically cleans up when exiting the context
with Sandbox.create(template="code-interpreter") as sandbox:
    result = sandbox.run_code('print("Hello from HopX!")')
    print(result.stdout)
    # Sandbox is automatically deleted when exiting the block
Expected Output:
Hello from HopX!
The context manager automatically calls sandbox.kill() when exiting the with block, even if an error occurs. This ensures proper cleanup.

Finding Available Templates

Before creating a sandbox, you may want to list available templates:
  • Python
  • JavaScript
from hopx_ai import Sandbox

# List all templates
templates = Sandbox.list_templates()
for template in templates:
    print(f"{template.name}: {template.display_name}")

# Get specific template details
template = Sandbox.get_template("code-interpreter")
print(f"Description: {template.description}")
print(f"Default resources: {template.default_resources.vcpu} vCPU")

Best Practices

1

1. Always Clean Up

Use context managers (Python) or try/finally blocks to ensure sandboxes are cleaned up, even if errors occur.
2

2. Set Appropriate Timeouts

Set timeouts based on your use case. For quick scripts, use shorter timeouts. For long-running tasks, set longer timeouts or use timeout management.
3

3. Use Environment Variables

Set environment variables at creation time rather than later for better performance and consistency.
4

4. Choose the Right Template

Select templates that match your needs. Use list_templates() to find available options.
5

5. Handle Errors Gracefully

Always handle potential errors (template not found, resource limits, etc.) in your code.

Implementation

Next Steps