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:
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
import { Sandbox } from '@hopx-ai/sdk';
// Create sandbox from template name
const sandbox = await Sandbox.create({
template: 'code-interpreter'
});
console.log(`Sandbox ID: ${sandbox.sandboxId}`);
const info = await sandbox.getInfo();
console.log(`Status: ${info.status}`);
console.log(`URL: ${info.publicHost}`);
// Clean up when done
await 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:
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
import { Sandbox } from '@hopx-ai/sdk';
// Create from template ID
const sandbox = await Sandbox.create({
templateId: '119'
});
// Cleanup when done
await 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:
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
import { Sandbox } from '@hopx-ai/sdk';
// Create with 1 hour timeout
const sandbox = await Sandbox.create({
template: 'code-interpreter',
timeoutSeconds: 3600 // 1 hour
});
const info = await sandbox.getInfo();
if (info.expiresAt) {
console.log(`Sandbox expires at: ${info.expiresAt}`);
}
Expected Output:Sandbox expires at: 2025-01-27T11:30:00Z
Internet Access
Control whether the sandbox has internet access:
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()
import { Sandbox } from '@hopx-ai/sdk';
// Create without internet access (isolated)
const sandbox = await Sandbox.create({
template: 'code-interpreter',
internetAccess: false
});
const info = await sandbox.getInfo();
console.log(`Internet access: ${info.internetAccess}`);
// Try to fetch an online resource to demonstrate lack of internet connectivity
const result = await sandbox.runCode(`
const https = require('https');
function fetchUrl(url) {
return new Promise((resolve, reject) => {
https.get(url, (res) => {
console.log(\`✅ Successfully fetched hopx.ai - Status: \${res.statusCode}\`);
console.log(\`Content-Type: \${res.headers['content-type']}\`);
resolve();
}).on('error', (err) => {
console.log(\`❌ Failed to fetch URL: \${err.message}\`);
reject(err);
});
});
}
fetchUrl('https://www.hopx.ai').catch((err) => {
console.log(\`❌ Error: \${err.name}: \${err.message}\`);
});
`, { language: 'javascript' });
console.log('Fetch attempt output:');
console.log(result.stdout);
if (result.stderr) {
console.log('Errors:');
console.log(result.stderr);
}
if (result.exitCode !== 0) {
console.log('\n❌ Code execution failed');
} else if (result.stdout.includes('Failed to fetch') || result.stdout.includes('Error:')) {
console.log('\n❌ As expected, the fetch failed. Sandbox does not have internet access.');
} else {
console.log('\n✅ Unexpected: fetch succeeded, internet access is enabled!');
}
// Clean up when done
await sandbox.kill();
Environment Variables
Set initial environment variables when creating the sandbox:
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', ...}
import { Sandbox } from '@hopx-ai/sdk';
// Create with environment variables
const sandbox = await Sandbox.create({
template: 'code-interpreter',
envVars: {
API_KEY: 'sk-123',
DEBUG: 'true',
ENVIRONMENT: 'production'
}
});
// Verify environment variables
const result = await sandbox.runCode(
"import os; print(os.getenv('API_KEY'))",
{ language: 'python' }
);
console.log(result.stdout); // sk-123
// Clean up when done
await sandbox.kill();
Expected Output:
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:
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:
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")
import { Sandbox } from '@hopx-ai/sdk';
// List all templates
const templates = await Sandbox.listTemplates();
for (const template of templates) {
console.log(`${template.name}: ${template.displayName}`);
}
// Get specific template details
const template = await Sandbox.getTemplate('code-interpreter');
console.log(`Description: ${template.description}`);
console.log(`Default resources: ${template.defaultResources.vcpu} vCPU`);
Best Practices
1. Always Clean Up
Use context managers (Python) or try/finally blocks to ensure sandboxes are cleaned up, even if errors occur.
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. Use Environment Variables
Set environment variables at creation time rather than later for better performance and consistency.
4. Choose the Right Template
Select templates that match your needs. Use list_templates() to find available options.
5. Handle Errors Gracefully
Always handle potential errors (template not found, resource limits, etc.) in your code.
Implementation
Next Steps