Skip to main content
Follow these steps to create your first sandbox, run code, and clean up resources.

Get Your API Key

First, create your API key in the console:

Get API Key

Sign up and create your first API key
Then set it as an environment variable:Set your API key as an environment variable (recommended):
export HOPX_API_KEY="hopx_..."

Install SDK

pip install hopx-ai

Create Your First Sandbox

from hopx_ai import Sandbox

# Create sandbox - automatically uses HOPX_API_KEY env var
sandbox = Sandbox.create(template="code-interpreter")

print(f"✅ Sandbox created: {sandbox.sandbox_id}")

# Get sandbox info
info = sandbox.get_info()
print(f"✅ Status: {info.status}")
The code-interpreter template includes Python 3.11 with data science libraries (NumPy, Pandas, Matplotlib) pre-installed.
No need to pass api_key explicitly - the SDK automatically reads from HOPX_API_KEY environment variable!

Run Your First Code

Execute code and see the results:
# ...
# Run Python code in the sandbox
result = sandbox.run_code('print("The question of whether computers can think is like the question of whether submarines can swim. - Edsger Dijkstra")')

# Check if execution succeeded
if result.success:
    print("✅ Code executed successfully!")
    print("\nOutput:")
    print(result.stdout)
else:
    print("❌ Error:", result.stderr)
Expected Output:
✅ Code executed successfully!

Output:
The question of whether computers can think is like the question of whether submarines can swim. - Edsger Dijkstra
Success! You just ran code in a secure, isolated environment 🎉

Cleanup

Always clean up your sandbox when done to avoid unnecessary charges:
# Method 1: Manual cleanup
sandbox.kill()
print("✅ Sandbox deleted")

# Method 2: Auto-cleanup with timeout (recommended)
sandbox = Sandbox.create(template="code-interpreter", timeout_seconds=600)
result = sandbox.run_code("print('Hello!')")
print(result.stdout)
# Sandbox automatically killed after 600 seconds
Sandboxes are billed while running. Always call kill() when done to avoid unnecessary charges.
Congratulations! You’ve completed the quickstart tutorial. You now know how to create sandboxes, run code, and clean up resources. 🎉

Next Steps


Common Patterns

Pass secrets and configuration securely:
sandbox = Sandbox.create(
    template="code-interpreter",
    env_vars={
        "API_KEY": "secret-key",
        "DATABASE_URL": "postgres://...",
        "DEBUG": "true"
    }
)

result = sandbox.run_code("""
import os

api_key = os.getenv('API_KEY')
debug = os.getenv('DEBUG') == 'true'

print(f"API Key: {api_key[:8]}...")
print(f"Debug mode: {debug}")
""")
Handle errors gracefully:
from hopx_ai import Sandbox, HopxError

try:
    sandbox = Sandbox.create(template="code-interpreter")
    
    # This will fail (division by zero)
    result = sandbox.run_code("print(1/0)")
    
    if not result.success:
        print(f"❌ Code failed: {result.stderr}")
        print(f"Exit code: {result.exit_code}")
        
except HopxError as e:
    print(f"❌ Sandbox error: {e.message}")
    print(f"Request ID: {e.request_id}")
    
finally:
    sandbox.kill()
Stream output in real-time for long-running operations:
import asyncio

async def stream_execution():
    sandbox = Sandbox.create(template="code-interpreter")
    
    code = """
import time

for i in range(5):
    print(f"Step {i+1}/5")
    time.sleep(1)
    
print("Done!")
"""
    
    # Stream output line by line
    async for message in sandbox.run_code_stream(code):
        if message['type'] == 'stdout':
            print(message['data'], end='')
        elif message['type'] == 'stderr':
            print(f"[stderr] {message['data']}", end='')
        elif message['type'] == 'result':
            print(f"\n✅ Exit code: {message['exit_code']}")
        elif message['type'] == 'complete':
            if message['success']:
                print("\n✅ Execution completed successfully")
            else:
                print("\n❌ Execution failed")
    
    sandbox.kill()

# Run the async function
asyncio.run(stream_execution())

Troubleshooting Quickstart

If you encountered issues during the quickstart:
  • “Authentication failed” → Check your API key is set in HOPX_API_KEY environment variable
  • “Template not found” → Use code-interpreter template (case-sensitive)
  • “Sandbox creation timeout” → Try again or check your network connection
  • Import errors in code → Use the code-interpreter template which has common packages pre-installed
For more help, see the troubleshooting guide or FAQ.