> ## 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.

# AsyncSandbox

> Asynchronous sandbox class for async/await workflows in Python. Use AsyncSandbox for non-blocking operations, concurrent sandbox management, and async/await patterns. Complete reference for all async methods including creating sandboxes, executing code, and managing resources asynchronously. Includes async/await examples and best practices.

**Version:** 0.3.0\
**Last Verified:** 2025-01-27\
**Package:** `hopx-ai` on [PyPI](https://pypi.org/project/hopx-ai/)

## 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

```python theme={null}
from hopx_ai import AsyncSandbox
```

## Class Methods

### `create`

Create a new sandbox from a template (async).

```python theme={null}
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:**

```python theme={null}
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).

```python theme={null}
await AsyncSandbox.connect(
    sandbox_id,
    *,
    api_key=None,
    base_url='https://api.hopx.dev'
) -> AsyncSandbox
```

**Example:**

```python theme={null}
sandbox = await AsyncSandbox.connect("sandbox-abc123")
```

**Expected Output:**

```
Connected to sandbox-abc123
```

***

### `list`

List all sandboxes (async).

```python theme={null}
await AsyncSandbox.list(
    *,
    status=None,
    region=None,
    limit=100,
    api_key=None,
    base_url='https://api.hopx.dev'
) -> List[AsyncSandbox]
```

**Example:**

```python theme={null}
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.

```python theme={null}
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).

```python theme={null}
await sandbox.run_code(
    code,
    *,
    language='python',
    timeout_seconds=60,
    env=None,
    working_dir='/workspace'
) -> ExecutionResult
```

**Example:**

```python theme={null}
result = await sandbox.run_code("print('Hello, HopX!')")
print(result.stdout)
```

**Expected Output:**

```
Hello, HopX!
```

***

#### `run_code_stream`

Stream code execution output (async generator).

```python theme={null}
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).

```python theme={null}
await sandbox.list_processes() -> List[Dict[str, Any]]
```

**Expected Output:**

```
[{'process_id': 'proc_abc123', 'status': 'running', ...}]
```

***

#### `kill_process`

Kill a process by ID (async).

```python theme={null}
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.files` → `AsyncFiles`
* `sandbox.commands` → `AsyncCommands`
* `sandbox.env` → `AsyncEnvironmentVariables`
* `sandbox.cache` → `AsyncCache`
* `sandbox.terminal` → `AsyncTerminal`

***

## Async Context Manager

The `AsyncSandbox` class supports async context manager protocol.

**Example:**

```python theme={null}
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

```python theme={null}
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

```python theme={null}
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

```python theme={null}
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

```python theme={null}
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
```

***

## Related Classes

* **[Sandbox](/sdk/python/sandbox)** - Synchronous version of AsyncSandbox
* **[AsyncFiles](/sdk/python/files)** - Async file operations (accessed via `sandbox.files`)
* **[AsyncCommands](/sdk/python/commands)** - Async command execution
* **[AsyncEnvironmentVariables](/sdk/python/environment-variables)** - Async environment variable management

## See Also

* [Quickstart Guide](/sdk/python/quickstart) - Get started with the SDK
* [Sandbox Class](/sdk/python/sandbox) - Synchronous sandbox class
* [Core Concepts](/core-concepts/sandboxes/creating) - Learn about sandboxes

## Next Steps

* Learn about [Synchronous Sandbox](/sdk/python/sandbox) if you prefer blocking operations
* Explore [Code Execution](/core-concepts/code-execution/synchronous) concepts
* Review [File Operations](/sdk/python/files) for async file management
* **[CLI Reference](/cli/introduction)** - Use HopX from the command line
* Check out [API Reference](/api/vm-agent/overview) for direct API access
