Documentation Index
Fetch the complete documentation index at: https://docs.hopx.ai/llms.txt
Use this file to discover all available pages before exploring further.
Get up and running with HopX; this guide walks you through creating your first sandbox, executing code, and cleaning up.
What You’ll Learn
In this quickstart, you’ll learn how to:
- Install and set up the HopX SDK (Python or JavaScript) or CLI
- Create your first sandbox from a pre-built template
- Execute code in multiple languages (Python, JavaScript, Bash, Go)
- Work with files in sandboxes (read, write, list)
- Clean up sandboxes to free resources
- Use context managers for automatic cleanup (Python)
Prerequisites
- HopX API key (get one here if you don’t have it)
- Python 3.8+ or Node.js 18+ or CLI installed
- Basic experience with Python, JavaScript, or command line
Run your first sandbox
Choose your preferred method: Python SDK, JavaScript SDK, or CLI. This guide focuses on SDKs. For CLI, see the CLI Quickstart.
Install the SDK or CLI
Install the HopX SDK for your preferred language, or use the CLI:# Quick install
curl -fsSL https://hopx.dev/install.sh | sh
See CLI Installation for more options. Create Your First Sandbox
Create a sandbox using a pre-built template. Templates provide pre-configured environments with common tools and packages.from hopx_ai import Sandbox
from hopx_ai.exceptions import APIError, ResourceLimitError
try:
# Create a sandbox with the code-interpreter template
sandbox = Sandbox.create(
template="code-interpreter",
api_key="your-api-key-here" # Or set HOPX_API_KEY env var
)
print(f"Sandbox created: {sandbox.sandbox_id}")
print(f"Status: {sandbox.get_info().status}")
except APIError as e:
print(f"API error: {e}")
except ResourceLimitError as e:
print(f"Resource limit exceeded: {e}")
Expected Output:Sandbox created: sandbox_abc123xyz
Status: running
You can also use Sandbox.create() without specifying an API key if you set the HOPX_API_KEY environment variable.
import { Sandbox } from '@hopx-ai/sdk';
import { APIError, ResourceLimitError } from '@hopx-ai/sdk';
try {
// Create a sandbox with the code-interpreter template
const sandbox = await Sandbox.create({
template: 'code-interpreter',
apiKey: 'your-api-key-here' // Or set HOPX_API_KEY env var
});
console.log(`Sandbox created: ${sandbox.sandboxId}`);
const info = await sandbox.getInfo();
console.log(`Status: ${info.status}`);
} catch (error) {
if (error instanceof APIError) {
console.error(`API error: ${error.message}`);
} else if (error instanceof ResourceLimitError) {
console.error(`Resource limit exceeded: ${error.message}`);
} else {
console.error(`Unexpected error: ${error.message}`);
}
}
Expected Output:Sandbox created: sandbox_abc123xyz
Status: running
You can also use Sandbox.create() without specifying an API key if you set the HOPX_API_KEY environment variable.
Execute Code
Run code in your sandbox.# Execute Python code
result = sandbox.run_code('''
import math
# Calculate the area of a circle
radius = 5
area = math.pi * radius ** 2
print(f"Area of circle with radius {radius}: {area:.2f}")
''', language: 'python')
print(result.stdout)
# Output: Area of circle with radius 5: 78.54
# Check if execution was successful
if result.success:
print("✅ Code executed successfully!")
else:
print(f"❌ Error: {result.stderr}")
The run_code() method automatically captures rich outputs like matplotlib plots and pandas DataFrames. See Rich Output Capture for more details. // Execute JavaScript code
const result = await sandbox.runCode(`
const radius = 5;
const area = Math.PI * radius ** 2;
console.log(\`Area of circle with radius \${radius}: \${area.toFixed(2)}\`);
`, { language: 'javascript' });
console.log(result.stdout);
// Output: Area of circle with radius 5: 78.54
// Check if execution was successful
if (result.success) {
console.log('✅ Code executed successfully!');
} else {
console.log(`❌ Error: ${result.stderr}`);
}
The sandbox will execute code written in any language as long as the template you use provides the necessary dependencies.
See the Getting Template Details page for information on available templates and their environments, alternatively create your own template with the Building Templates guide. Work with Files
Upload, read, and write files in your sandbox:# Write a file
sandbox.files.write('/workspace/data.txt', 'Hello, HopX!')
# Read the file
content = sandbox.files.read('/workspace/data.txt')
print(content) # Output: Hello, HopX!
# List files in a directory
files = sandbox.files.list('/workspace')
for file in files:
print(f"- {file.name} ({file.size} bytes)")
Expected Output:Hello, HopX!
- data.txt (12 bytes)
- script.py (245 bytes)
// Write a file
await sandbox.files.write('/workspace/data.txt', 'Hello, HopX!');
// Read the file
const content = await sandbox.files.read('/workspace/data.txt');
console.log(content); // Output: Hello, HopX!
// List files in a directory
const files = await sandbox.files.list('/workspace');
files.forEach(file => {
console.log(`- ${file.name} (${file.size} bytes)`);
});
Expected Output:Hello, HopX!
- data.txt (12 bytes)
- script.js (189 bytes)
Clean Up
Always clean up your sandbox when you’re done to free resources:# Delete the sandbox
sandbox.kill()
print("Sandbox deleted")
Expected Output:// Delete the sandbox
await sandbox.kill();
console.log('Sandbox deleted');
Expected Output:Calling kill() permanently deletes the sandbox and all its data. Make sure you’ve saved any important files before cleaning up.
See Downloading Files for more details.
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!")', language='python')
print(result.stdout)
# Sandbox is automatically deleted when exiting the block
Expected Output:
Complete Example
Here’s a complete example that brings it all together:
from hopx_ai import Sandbox
# Setup your API key as an env var or inject it here as previously instructed.
# Create sandbox
sandbox = Sandbox.create(template="code-interpreter")
try:
# Execute code
result = sandbox.run_code('''
import math
# Calculate the area of a circle
radius = 5
area = math.pi * radius ** 2
print(f"Area of circle with radius {radius}: {area:.2f}")
''', language='python')
print("Output:")
print(result.stdout)
sandbox.run_code('mkdir /workspace/test')
# Work with files
sandbox.files.write('/workspace/test/result.json', result.stdout)
print("\n✅ Result saved to file")
# List files in a directory
files = sandbox.files.list('/workspace/test')
for file in files:
print(f"- {file.name} ({file.size} bytes)")\
# Read the file
content = sandbox.files.read('/workspace/test/result.json')
print(content)
finally:
# Always clean up
sandbox.kill()
print("✅ Sandbox cleaned up")
import { Sandbox } from '@hopx-ai/sdk';
async function main() {
// Create sandbox
const sandbox = await Sandbox.create({ template: 'code-interpreter'});
try {
// Execute JavaScript code
const result = await sandbox.runCode(`
const radius = 5;
const area = Math.PI * radius ** 2;
console.log(\`Area of circle with radius \${radius}: \${area.toFixed(2)}\`);
`, { language: 'javascript' });
console.log('Output:');
console.log(result.stdout);
console.log(result.stderr);
// Work with files
await sandbox.files.write('/workspace/test/result.json', result.stdout);
console.log('\n✅ Result saved to file');
// List files in a directory
const files = await sandbox.files.list('/workspace/test');
console.log(files);
// Read the file
const content = await sandbox.files.read('/workspace/test/result.json');
console.log(content);
} finally {
// Always clean up
await sandbox.kill();
console.log('✅ Sandbox cleaned up');
}
}
main();
Next Steps
Now that you’ve created your first sandbox, explore more:
For AI agent developers, check out the MCP Integration guide to enable AI assistants to execute code safely in sandboxes.