# SDK Quick Start
<subtitle>Complete installation and create your first sandbox in minutes.</subtitle>

This guide will walk you through the quick start of UCloud Sandbox SDK, including CLI installation, creating your first sandbox, command execution, file operations, and building custom templates.

---

## 1. Environment Setup

Before using the SDK, please ensure that the `AGENTBOX_API_KEY` environment variable is configured.

>
> You can obtain your API key from the [Console API Keys page](https://console.ucloud.cn/modelverse/experience/api-keys).

```bash
export AGENTBOX_API_KEY=your_api_key
```

---

## 2. Install Python SDK

```bash
pip install ucloud-sandbox
```

---

## 3. Install CLI (Optional)

Ensure that Node.js is installed on your system.

```bash
npm i -g @ucloud-sdks/ucloud-sandbox-cli
```

After installation, you can verify success with the following command:

```bash
ucloud-sandbox-cli --help
```

> For more CLI features, please refer to [CLI Complete Guide](/docs/agent-sandbox/product/cli).

---

## 4. Create Your First Sandbox

Quickly create a sandbox using the Python SDK:

```python
from ucloud_sandbox import Sandbox

# Create sandbox and set lifetime to 60 seconds
sandbox = Sandbox.create(timeout=60)

# Get sandbox detailed information
info = sandbox.get_info()
print(info)

# Destroy immediately after use
sandbox.kill()
```

>
> Note: Timed-out sandboxes will be automatically reclaimed and cleaned up by the system. It is recommended to manually call the `kill()` method to release resources at the end of your business process.

> For more sandbox lifecycle management, please refer to [Sandbox Lifecycle](/docs/agent-sandbox/sdk/sandbox/01-lifecycle).

---

## 5. Use Built-in Templates

For convenient rapid development, we provide three pre-configured templates that are ready to use:

| Template Name | Description | Use Cases |
|---------|------|----------|
| `base` | Basic Linux environment with common command-line tools | General scenarios, Shell script execution |
| `code-interpreter-v1` | Python environment with pre-installed data science libraries (numpy, pandas, matplotlib, etc.) | Code interpreter, data analysis, AI Agent |
| `desktop` | Full desktop environment supporting graphical applications | Browser automation, UI testing, visualization applications |
| `claude-code` | Pre-configured Claude Code environment | AI-assisted programming, intelligent terminal interaction |

### Using Python SDK

```python
from ucloud_sandbox.code_interpreter import Sandbox

# Use code interpreter template
sandbox = Sandbox.create(template="code-interpreter-v1")

# Execute Python data analysis
result = sandbox.run_code("""
import pandas as pd
data = {'name': ['Alice', 'Bob'], 'age': [25, 30]}
df = pd.DataFrame(data)
print(df)
""")
print(result)

sandbox.kill()
```

### Using CLI

```bash
# Create and connect to code interpreter sandbox
ucloud-sandbox-cli sandbox create code-interpreter-v1

# Create desktop environment sandbox
ucloud-sandbox-cli sandbox create desktop

# Create Claude Code environment sandbox
ucloud-sandbox-cli sandbox create claude-code

# Create basic environment sandbox
ucloud-sandbox-cli sandbox create base
```

> The CLI `sandbox create` command will automatically open an interactive terminal and connect to the sandbox, which is perfect for debugging and development.

---

## 6. Execute Commands

`commands.run()` is the most direct way to interact with sandboxes. You can execute any legitimate command just like operating a local terminal:

```python
from ucloud_sandbox import Sandbox

sandbox = Sandbox.create()

# Execute command
result = sandbox.commands.run('ls -la /home/user')

# Parse result
if result.exit_code == 0:
    print(f"Success:\n{result.stdout}")
else:
    print(f"Error (Exit {result.exit_code}):\n{result.stderr}")

sandbox.kill()
```

> For long-running commands, please refer to [Run Commands in Background](/docs/agent-sandbox/sdk/commands/03-run-commands-in-background).

---

## 7. File Operations

Each sandbox has an independent file system, and you can easily perform read/write operations:

```python
from ucloud_sandbox import Sandbox

sandbox = Sandbox.create()

# Write file
sandbox.files.write("hello.txt", "UCloud Sandbox is awesome!")

# Read file
content = sandbox.files.read("hello.txt")
print(content)  # Output: UCloud Sandbox is awesome!

# List directory
files = sandbox.files.list("/home/user")
for f in files:
    print(f.name, f.type)

sandbox.kill()
```

>
> **Default Root Directory**: Most operations are performed under `/home/user` by default.

> For more file operations, please refer to [File System Overview](/docs/agent-sandbox/sdk/filesystem/01-overview).

---

## 8. Build Custom Templates

Templates are blueprints for sandboxes, allowing you to pre-install software, configure environment variables, and pre-configure files.

### Method 1: Using CLI (Recommended)

```bash
# Initialize template project
ucloud-sandbox-cli template init
```

### Method 2: Using Python SDK

**Write template definition:**

```python
from ucloud_sandbox import Template, wait_for_timeout

template = (
    Template()
    .from_base_image()  # Use official pre-configured base image
    .set_envs({
        "APP_VERSION": "1.0.0",
        "DEBUG": "true"
    })
    .set_start_cmd("echo 'Environment is ready'", wait_for_timeout(5_000))
)
```

**Build and publish:**

```python
from ucloud_sandbox import Template, default_build_logger

Template.build(
    template,
    alias="my-agent-env",
    cpu_count=2,
    memory_mb=2048,
    on_build_logs=default_build_logger(),
)
```

### Using Custom Templates

```python
from ucloud_sandbox import Sandbox

# Create sandbox using template alias
sbx = Sandbox.create(template="my-agent-env")

# Check environment variables
result = sbx.commands.run("echo $APP_VERSION")
print(f"Version: {result.stdout}")  # Output: Version: 1.0.0
```

> Template aliases are your globally unique identifiers. For more template features, please refer to [Template Complete Guide](/docs/agent-sandbox/template/01-quick-start).

---

## 9. Complete Example

The following is a complete workflow example:

```python
from ucloud_sandbox import Sandbox

# Create sandbox
sandbox = Sandbox.create(timeout=300)
print(f"Sandbox created: {sandbox.sandbox_id}")

# Execute command
result = sandbox.commands.run("python --version")
print(f"Python version: {result.stdout}")

# Write and execute Python script
sandbox.files.write("script.py", """
import os
print("Hello from UCloud Sandbox!")
print(f"Working directory: {os.getcwd()}")
""")

result = sandbox.commands.run("python script.py")
print(result.stdout)

# Clean up resources
sandbox.kill()
print("Sandbox destroyed")
```

---

## Next Steps

- [Sandbox Lifecycle Management](/docs/agent-sandbox/sdk/sandbox/01-lifecycle) - Understand timeout settings and runtime monitoring
- [Command Execution Details](/docs/agent-sandbox/sdk/commands/01-overview) - Deep dive into command execution features
- [File System Operations](/docs/agent-sandbox/sdk/filesystem/01-overview) - Complete file operation guide
- [How Templates Work](/docs/agent-sandbox/concepts/02-how-it-works) - Deep understanding of template mechanism
- [E2B Compatibility Mode](/docs/agent-sandbox/product/e2b-compatibility) - Use E2B SDK to integrate
