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

This guide will take you through a quick start with the UCloud Sandbox SDK, including CLI installation, creating your first sandbox, command execution, file manipulation, and building custom templates.

---

## 1. Environment configuration

Before using the SDK, make sure the `UCLOUD_SANDBOX_API_KEY` environment variable is configured.

> You can get your key at [Star Chart Key Management](https://astraflow.ucloud.cn/modelverse/api-keys).

```bash
export UCLOUD_SANDBOX_API_KEY=your_api_key
```

---

## 2. Install Python SDK

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

---

## 3. Install CLI (optional)

```bash
curl -sS https://raw.githubusercontent.com/ucloud/ucloud-sandbox-cli/main/install.sh | sh
```

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

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

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

Use the following commands to configure the global key and region:

```bash
ucloud-sandbox-cli login
```

> For details about region switching, please refer to [Region Switching](/docs/agent-sandbox/product/region.md)

---

## 4. Create the first sandbox

Use the Python SDK to quickly create a sandbox:

```python
from ucloud_sandbox import Sandbox

# Create a sandbox and set the survival time to 60 seconds
sandbox = Sandbox.create(timeout=60)

# Get sandbox details
info = sandbox.get_info()
print(info)

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

> Note: The timed-out sandbox will be automatically recycled and cleaned by the system. It is recommended to manually call the `kill()` method to release resources at the end of the business process.

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

---

## 5. Use built-in templates

To facilitate rapid development, we provide three preset templates, ready to use out of the box:

| Template name | Description | Applicable scenarios |
|---------|------|----------|
| `base` | Basic Linux environment, including common command line tools | Common scenarios, Shell script execution |
| `code-interpreter-v1` | Python environment, pre-installed with commonly used libraries for data science (numpy, pandas, matplotlib, etc.) | Code interpreter, data analysis, AI Agent |
| `desktop` | Complete desktop environment, supports graphical applications | Browser automation, UI testing, visual applications |
| `claude-code` | Preset Claude Code environment | AI-assisted programming, intelligent terminal interaction |

### Using Python SDK

```python
from ucloud_sandbox.code_interpreter import Sandbox

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

# Perform 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 the code interpreter sandbox
ucloud-sandbox-cli sandbox create code-interpreter-v1

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

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

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

> The CLI's `sandbox create` command automatically opens an interactive terminal and connects to the sandbox, ideal for debugging and development.

---

## 6. Execute command

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

```python
from ucloud_sandbox import Sandbox

sandbox = Sandbox.create()

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

# Parse results
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 [Background running commands](/docs/agent-sandbox/commands/background.md).

---

## 7. File operations

Each sandbox has an independent file system that you can easily read and write:

```python
from ucloud_sandbox import Sandbox

sandbox = Sandbox.create()

#Write to 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 directories
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/filesystem/overview.md).

---

## 8. Build custom templates

Template is the blueprint of the sandbox, allowing you to preinstall software, configure environment variables, and preset files.

### Method 1: Use CLI (recommended)

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

### Method 2: Use Python SDK

**Write template definition:**

```python
from ucloud_sandbox import Template, wait_for_timeout

template = (
    Template()
    .from_base_image() # Use the official preset 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(),
)
```

### Use custom templates

```python
from ucloud_sandbox import Sandbox

# Create a sandbox using template aliases
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
```

> A template alias is your globally unique identifier. For more template features, please see [Complete Guide to Templates](/docs/agent-sandbox/template/quickstart.md).

---

## 9. Complete example

Here 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")
```
