# Metrics Monitoring
<subtitle>Real-time understanding of sandbox resource usage, including CPU, memory, and disk usage.</subtitle>

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

UCloud Sandbox collects sandbox resource consumption data in real-time. Through monitoring metrics, you can better optimize Agent task allocation or troubleshoot performance bottlenecks.

## Metrics Overview

The system collects data points every **5 seconds**. The obtained metrics include the following dimensions:
- **CPU**: Number of cores and current usage percentage.
- **Memory**: Total capacity and current used space (unit: bytes).
- **Disk**: Total capacity and current used space (unit: bytes).

## Get Monitoring Metrics

### Using SDK

Call the `get_metrics()` method to get sandbox metrics data.

```python
from time import sleep
from ucloud_sandbox import Sandbox

# 1. Create sandbox
sbx = Sandbox.create()

# 2. Wait for a period of time for the system to collect initial data
sleep(10)

# 3. Get metrics list
metrics = sbx.get_metrics()

# You can also call statically directly through sandbox ID:
# metrics = Sandbox.get_metrics(sbx.sandbox_id)

for m in metrics:
    print(f"Time: {m.timestamp} | CPU: {m.cpu_used_pct}% | RAM: {m.mem_used / 1024**2:.1f} MB")
```

### Using CLI

You can also view in real-time directly through CLI in the terminal:

```bash
ucloud-sandbox-cli sandbox metrics <sandbox-id>
```

Output example:
```text
[2025-07-25 14:05:55Z]  CPU:  8.27% /  2 Cores | Memory:    31 / 484 MiB | Disk:  1445 / 2453 MiB
[2025-07-25 14:06:00Z]  CPU:   0.5% /  2 Cores | Memory:    32 / 484 MiB | Disk:  1445 / 2453 MiB
```

## Notes

>
> **Delayed Collection**: When a sandbox is first created, the system needs 1-5 seconds to initialize monitoring components. Before that, `get_metrics()` may return an empty array.

>
> **Data Accuracy**: Monitoring metrics are mainly used to reflect runtime trends, not for precise billing.