# Cache Mechanism
<subtitle>Master layered caching principles to optimize template build efficiency and significantly shorten environment deployment time.</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 template building adopts a **layered caching** mechanism similar to Docker. Each instruction (such as `.copy()`, `.run_cmd()`) generates or modifies a cache layer. If the instruction and its input parameters have not changed, the system will directly reuse previous build results.

## Graded Cache Invalidation

You can flexibly control cache granularity to ensure environment updates take effect accurately.

### 1. Partial Invalidation (Skip Cache)
If you want all layers from a certain instruction onwards to be rebuilt, use `.skip_cache()`.

```python
from ucloud_sandbox import Template

template = (
    Template()
    .from_base_image()
    # Previous layers still reuse cache
    .skip_cache() 
    # From this line onwards, all instructions will be re-executed
    .run_cmd("apt-get update && apt-get install -y some-package")
)
```

### 2. Global Invalidation
When executing `Template.build`, you can force skip all layer caches through parameters.

```python
Template.build(
    template,
    alias="my-template",
    skip_cache=True,  # Force complete build
)
```

---

## Unique File-Level Caching

UCloud Sandbox has deeply optimized file transfer. Unlike Docker's point-to-point cache dependencies, even if layers before `.copy()` have changed, as long as the file content itself has not changed, the system will automatically read from cloud cache without needing to re-upload from your local machine.

>
> **Force Upload**: If you are certain the file content has not changed but still need to re-overwrite (e.g., some initialization operations with side effects), please set `force_upload=True` in `copy()`.

---

## Build Performance Optimization Recommendations

1.  **Layer Granularity**: Place commands that install large dependency packages (time-consuming, rarely changed) at the front of the definition.
2.  **Code Postponement**: Place frequently changed source code `copy` operations at the end of the definition.
3.  **Multi-Configuration Sharing**: When building templates of different specifications (such as different CPU/memory) for the same environment, just modify `alias` and rebuild. Common software installation layers will be automatically reused.

>
> **Cache Scope**: Cache is shared based on **Team**. Different members within the same team can mutually share existing cache layers when building similar templates.
