AGENT SANDBOX DOCS

Quick Start

Get up and running with the Agent Sandbox in under 5 minutes. Install the SDK, authenticate, and run your first sandboxed code execution.

1

Install the SDK

pip install alphagent-sdk
2

Set Your API Key

export ALPHAGENT_API_KEY="sk-alphagent-..."

Get your API key from the Dashboard.

3

Run Your First Sandbox

from alphagent import Sandbox

# Create a new sandbox instance
sandbox = Sandbox()

# Execute Python code
result = sandbox.run("""
print("Hello from the sandbox!")
x = 2 + 2
print(f"2 + 2 = {x}")
""")

# Print the output
print(result.output)
# => Hello from the sandbox!
# => 2 + 2 = 4

Questions? We'd love to hear from you.

Connect with Founders
LLM Optimized Context

This content is optimized for Large Language Models. Copy and paste this into ChatGPT, Claude, or other assistants to give them full context on the Agent Sandbox SDK.

# Agent Sandbox Documentation

## Quick Start
Get up and running with the Agent Sandbox in under 5 minutes. Install the SDK, authenticate, and run your first sandboxed code execution.

1. **Install the SDK**
   `pip install alphagent-sdk`

2. **Set Your API Key**
   `export ALPHAGENT_API_KEY="sk-alphagent-..."`
   _Get your API key from the Dashboard._

3. **Run Your First Sandbox**
   ```python
   from alphagent import Sandbox

   # Create a new sandbox instance
   sandbox = Sandbox()

   # Execute Python code
   result = sandbox.run("""
   print("Hello from the sandbox!")
   x = 2 + 2
   print(f"2 + 2 = {x}")
   """)

   # Print the output
   print(result.output)
   # => Hello from the sandbox!
   # => 2 + 2 = 4
   ```

## Authentication
All API requests require authentication via an API key. Keep your key secure and never expose it in client-side code.

> **Security Note:** Your API key grants full access to your sandbox environment. Never commit it to version control or expose it in frontend code.

### Environment Variable (Recommended)
```bash
# Set in your shell
export ALPHAGENT_API_KEY="sk-alphagent-xxxx"

# The SDK will automatically detect it
sandbox = Sandbox()  # Uses ALPHAGENT_API_KEY
```

### Direct Initialization
```python
from alphagent import Sandbox

sandbox = Sandbox(api_key="sk-alphagent-xxxx")
```

## Sandbox API
The Sandbox class is your primary interface for executing code in an isolated environment.

### Constructor
`Sandbox(api_key=None, timeout=300, memory=4096)`

| Parameter | Type | Description |
|-----------|------|-------------|
| api_key | str | None | Your API key. Defaults to ALPHAGENT_API_KEY env var. |
| timeout | int | Max execution time in seconds. Default: 300. |
| memory | int | Memory allocation in MB. Default: 4096. |

### Methods

#### run(code: str) -> ExecutionResult
Execute Python code in the sandbox and return the result.
```python
result = sandbox.run("print('Hello!')")
print(result.output)  # => Hello!
print(result.exit_code)  # => 0
```

#### exec(command: str) -> ExecutionResult
Execute a shell command in the sandbox.
```python
result = sandbox.exec("pip install pandas")
result = sandbox.exec("ls -la")
```

#### upload(path: str, data: bytes) -> None
Upload a file to the sandbox filesystem.
```python
with open("data.csv", "rb") as f:
    sandbox.upload("/workspace/data.csv", f.read())
```

#### download(path: str) -> bytes
Download a file from the sandbox filesystem.
```python
chart_data = sandbox.download("/workspace/chart.png")
with open("chart.png", "wb") as f:
    f.write(chart_data)
```

#### terminate() -> None
Terminate the sandbox session and clean up resources.
```python
sandbox.terminate()
# Session is now closed
```

## Execution Result
The ExecutionResult object contains all information about a completed code execution.

### Properties
| Property | Type | Description |
|----------|------|-------------|
| output | str | Standard output from the execution. |
| error | str | Standard error output, if any. |
| exit_code | int | Process exit code. 0 indicates success. |
| duration_ms | int | Execution time in milliseconds. |
| artifacts | list[str] | Paths to files generated during execution. |

### Example
```python
result = sandbox.run("""
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [4, 5, 6])
plt.savefig('chart.png')
print('Chart generated!')
""")

print(result.output)       # => Chart generated!
print(result.exit_code)    # => 0
print(result.duration_ms)  # => 1234
print(result.artifacts)    # => ['/workspace/chart.png']
```

## Error Handling
The SDK raises specific exceptions for different error conditions. Handle them appropriately in your application.

### Exception Types
- **AuthenticationError**: Raised when the API key is invalid or missing.
- **TimeoutError**: Raised when execution exceeds the configured timeout.
- **ResourceLimitError**: Raised when the sandbox exceeds memory or CPU limits.
- **SandboxError**: Base exception for all sandbox-related errors.

### Example
```python
from alphagent import Sandbox
from alphagent.exceptions import (
    AuthenticationError,
    TimeoutError,
    SandboxError
)

try:
    sandbox = Sandbox()
    result = sandbox.run("while True: pass")
except AuthenticationError:
    print("Invalid API key")
except TimeoutError:
    print("Execution timed out")
except SandboxError as e:
    print(f"Sandbox error: {e}")
```

## Examples
Common use cases and patterns for working with the Agent Sandbox.

### Data Analysis
```python
sandbox = Sandbox()

# Install dependencies
sandbox.exec("pip install pandas numpy")

# Upload data
with open("sales.csv", "rb") as f:
    sandbox.upload("/workspace/sales.csv", f.read())

# Run analysis
result = sandbox.run("""
import pandas as pd
df = pd.read_csv('/workspace/sales.csv')
print(df.describe())
print(f"Total revenue: $" + "{df['revenue'].sum():,.2f}")
""")
```

### Chart Generation
```python
sandbox = Sandbox()
sandbox.exec("pip install matplotlib seaborn")

result = sandbox.run("""
import matplotlib.pyplot as plt
import seaborn as sns

data = [23, 45, 56, 78, 32, 89]
plt.figure(figsize=(10, 6))
sns.barplot(x=list(range(len(data))), y=data)
plt.title('Monthly Performance')
plt.savefig('/workspace/chart.png', dpi=150)
""")

# Download the generated chart
chart = sandbox.download("/workspace/chart.png")
with open("output_chart.png", "wb") as f:
    f.write(chart)
```

### Web Scraping
```python
sandbox = Sandbox()
sandbox.exec("pip install requests beautifulsoup4")

result = sandbox.run("""
import requests
from bs4 import BeautifulSoup

resp = requests.get('https://example.com')
soup = BeautifulSoup(resp.text, 'html.parser')
print(soup.title.string)
""")

print(result.output)  # => Example Domain
```