Skip to main content
Version: 0.3.0
Last Verified: 2025-01-27
Package: hopx-ai on PyPI

Overview

The AsyncSandbox class provides an asynchronous interface for creating and managing cloud sandboxes. Use this class when building async Python applications (FastAPI, aiohttp, etc.) or when you need to manage multiple sandboxes concurrently. All methods in AsyncSandbox are async and must be called with await. The class supports async context managers for automatic cleanup.

When to Use AsyncSandbox vs Sandbox

  • Use AsyncSandbox when:
    • 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
  • Use Sandbox when:
    • Building synchronous Python applications
    • Writing scripts or simple automation
    • You prefer blocking operations

Import

from hopx_ai import AsyncSandbox

Class Methods

create

Create a new sandbox from a template (async).
await AsyncSandbox.create(
    template=None,
    *,
    template_id=None,
    region=None,
    timeout_seconds=None,
    internet_access=None,
    env_vars=None,
    api_key=None,
    base_url='https://api.hopx.dev'
) -> AsyncSandbox
Parameters: Same as Sandbox.create() Returns: AsyncSandbox - New sandbox instance Example:
sandbox = await AsyncSandbox.create(template="code-interpreter")
info = await sandbox.get_info()
print(info.public_host)
Expected Output:
https://sandbox_abc123xyz.hopx.dev

connect

Connect to an existing sandbox by ID (async).
await AsyncSandbox.connect(
    sandbox_id,
    *,
    api_key=None,
    base_url='https://api.hopx.dev'
) -> AsyncSandbox
Example:
sandbox = await AsyncSandbox.connect("sandbox-abc123")
Expected Output:
Connected to sandbox-abc123

list

List all sandboxes (async).
await AsyncSandbox.list(
    *,
    status=None,
    region=None,
    limit=100,
    api_key=None,
    base_url='https://api.hopx.dev'
) -> List[AsyncSandbox]
Example:
sandboxes = await AsyncSandbox.list(status="running")
for sb in sandboxes:
    info = await sb.get_info()
    print(f"{info.sandbox_id}: {info.status}")
Expected Output:
sandbox_abc123xyz: running
sandbox_def456uvw: running

iter

Lazy async iterator for sandboxes.
async for sandbox in AsyncSandbox.iter(status="running"):
    info = await sandbox.get_info()
    print(f"{info.sandbox_id}")
Expected Output:
sandbox_abc123xyz
sandbox_def456uvw

Instance Methods

Lifecycle Methods

All lifecycle methods are async versions of Sandbox methods:
  • await sandbox.get_info() -> SandboxInfo
  • await sandbox.start() -> None
  • await sandbox.stop() -> None
  • await sandbox.pause() -> None
  • await sandbox.resume() -> None
  • await sandbox.kill() -> None

Execution Methods

run_code

Execute code with rich output capture (async).
await sandbox.run_code(
    code,
    *,
    language='python',
    timeout_seconds=60,
    env=None,
    working_dir='/workspace'
) -> ExecutionResult
Example:
result = await sandbox.run_code("print('Hello, HopX!')")
print(result.stdout)
Expected Output:
Hello, HopX!

run_code_stream

Stream code execution output (async generator).
async for message in sandbox.run_code_stream(
    code,
    *,
    language='python',
    timeout_seconds=60
):
    print(message)
Expected Output:
{'type': 'stdout', 'data': 'Hello\n'}
{'type': 'stderr', 'data': ''}
{'type': 'done', 'exit_code': 0}

list_processes

List running processes in sandbox (async).
await sandbox.list_processes() -> List[Dict[str, Any]]
Expected Output:
[{'process_id': 'proc_abc123', 'status': 'running', ...}]

kill_process

Kill a process by ID (async).
await sandbox.kill_process(process_id) -> Dict[str, Any]
Expected Output:
Process killed successfully

Utility Methods

  • await sandbox.get_metrics_snapshot() -> Dict[str, Any]
  • await sandbox.refresh_token() -> None
  • await sandbox.set_timeout(seconds) -> None

Properties

All resource properties are async versions:
  • sandbox.filesAsyncFiles
  • sandbox.commandsAsyncCommands
  • sandbox.envAsyncEnvironmentVariables
  • sandbox.cacheAsyncCache
  • sandbox.terminalAsyncTerminal

Async Context Manager

The AsyncSandbox class supports async context manager protocol. Example:
async with AsyncSandbox.create(template="code-interpreter") as sandbox:
    result = await sandbox.run_code("print('Hello')")
    print(result.stdout)
# Automatically calls await sandbox.kill() when exiting
Expected Output:
Hello

Examples

Example 1: Basic Async Usage

import asyncio
from hopx_ai import AsyncSandbox

async def main():
    sandbox = await AsyncSandbox.create(template="code-interpreter")
    result = await sandbox.run_code("print('Hello, HopX!')")
    print(result.stdout)
    await sandbox.kill()

asyncio.run(main())
Expected Output:
Hello, HopX!

Example 2: Using Async Context Manager

import asyncio
from hopx_ai import AsyncSandbox

async def main():
    async with AsyncSandbox.create(template="code-interpreter") as sandbox:
        result = await sandbox.run_code("import sys; print(sys.version)")
        print(result.stdout)

asyncio.run(main())
Expected Output:
3.11.5 (main, Jan 27 2025, 10:30:00) [GCC 11.2.0]

Example 3: Concurrent Sandboxes

import asyncio
from hopx_ai import AsyncSandbox

async def run_in_sandbox(template):
    async with AsyncSandbox.create(template=template) as sandbox:
        result = await sandbox.run_code("print('Hello from', template)")
        return result.stdout

async def main():
    templates = ["code-interpreter", "nodejs", "go"]
    results = await asyncio.gather(*[run_in_sandbox(t) for t in templates])
    for r in results:
        print(r)

asyncio.run(main())
Expected Output:
Hello from code-interpreter
Hello from nodejs
Hello from go

Example 4: Streaming Output

import asyncio
from hopx_ai import AsyncSandbox

async def main():
    sandbox = await AsyncSandbox.create(template="code-interpreter")
    
    async for message in sandbox.run_code_stream(
        "for i in range(5):\n    print(f'Count: {i}')\n    import time\n    time.sleep(1)"
    ):
        if message.get('type') == 'stdout':
            print(message.get('data', ''), end='')
    
    await sandbox.kill()

asyncio.run(main())
Expected Output:
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4

See Also

Next Steps