# pai-image_label_management

Part of **PAI**

# Platform for AI (PAI) Image Label Management

## Capabilities Overview

| Sub-capability | Calling Mode | Description |
|----------------|--------------|-------------|
| AddImageLabels | Synchronous | Adds labels to a specified image using predefined system keys and values. |
| ListImageLabels | Synchronous | Queries image labels with optional filtering by keys, values, image ID, workspace ID, or region. |
| RemoveImageLabels | Synchronous | Removes a specific label from an image by its key. |

## API Calling Patterns

### Authentication
Use **Bearer Token** authentication via the `Authorization` header.

- Header format: `Authorization: Bearer <your_api_key>`
- Environment variable: `DASHSCOPE_API_KEY`
- Set your API key as: `export DASHSCOPE_API_KEY=your_key_here`

This is the primary and recommended method across all endpoints.

### Service Endpoint
The base URL varies by region and deployment scope:

- China regions: `https://api.aliyun.com/api/AIWorkSpace/2021-02-04`
- International regions: `https://api.alibabacloud.com/api/AIWorkSpace/2021-02-04`

Common regions include:
- `cn-hangzhou`
- `cn-shanghai`
- `cn-beijing`

Endpoints are RESTful and use standard HTTP methods (`POST`, `GET`, `DELETE`).

### Synchronous API Pattern
All image label management operations are synchronous:
1. Send a single HTTP request with required parameters.
2. Receive an immediate JSON response.
3. Parse the `RequestId` (and other fields for `ListImageLabels`) to confirm success.

No polling or streaming is involved. Errors are returned directly in the response with appropriate HTTP status codes.

## Parameter Reference

### AddImageLabels

| Parameter | Type | Required | Default | Constraints | Description |
|----------|------|--------|--------|------------|------------|
| ImageId | string | Yes | — | — | The ID of the image. |
| Labels | array<object> | Yes | — | Max 100 items per request | A list of label objects. |
| Key | string | No | — | Must be a supported system key | Label key (e.g., `system.chipType`, `system.framework`). |
| Value | string | No | — | — | Label value (e.g., `GPU`, `XGBoost 1.6.0`). |

> **Note**: The `body` contains the `Labels` array. Each label must include both `Key` and `Value`.

### ListImageLabels

| Parameter | Type | Required | Default | Constraints | Description |
|----------|------|--------|--------|------------|------------|
| LabelKeys | string | No | — | Comma-separated list | Filter by specific label keys (e.g., `system.framework,system.official`). |
| LabelFilter | string | No | — | Format: `key=value[,key=value...]` | Advanced filter using key-value pairs (URL-encoded). |
| ImageId | string | No | — | — | Filter by image ID. |
| WorkspaceId | string | No | — | — | Filter by workspace ID. |
| Region | string | No | — | — | Filter by region (e.g., `cn-shanghai`). |

> **Note**: `LabelKeys` and `LabelFilter` operate independently—use one or both.

### RemoveImageLabels

| Parameter | Type | Required | Default | Constraints | Description |
|----------|------|--------|--------|------------|------------|
| ImageId | string | Yes | — | — | The ID of the image. |
| LabelKey | string | Yes | — | — | The key of the label to remove. |

## Code Examples

### Add Image Labels - curl - All Regions

```bash
curl -X POST https://api.aliyun.com/api/AIWorkSpace/2021-02-04/AddImageLabels/image-4c62******53uor/labels \
-H "Authorization: Bearer <your-api-key>" \
-H "Content-Type: application/json" \
-d '{
  "Labels": [
    {
      "Key": "system.chipType",
      "Value": "GPU"
    }
  ]
}'
```

> For international regions, replace `api.aliyun.com` with `api.alibabacloud.com`.

### List Image Labels with Filters - bash - All Regions

```bash
curl -X GET \
  'https://api.aliyun.com/api/AIWorkSpace/2021-02-04/ListImageLabels?LabelKeys=system.framework,system.official&LabelFilter=system.framework=XGBoost%201.6.0,system.official=true&ImageId=image-4c62******53uor&WorkspaceId=12345&Region=cn-shanghai' \
  -H 'Authorization: Bearer $DASHSCOPE_API_KEY'
```

### Remove Image Label - Python - All Regions

```python
import requests

url = "https://api.aliyun.com/api/AIWorkSpace/2021-02-04/images/{ImageId}/labels/{LabelKey}"
headers = {
    "Authorization": "Bearer YOUR_API_KEY",
    "Content-Type": "application/json"
}

response = requests.delete(url.format(ImageId="image-d8df******dsjfd", LabelKey="key1"), headers=headers)
print(response.json())
```

> Replace `YOUR_API_KEY` with your actual key or use `os.getenv("DASHSCOPE_API_KEY")`.

### List All Labels for an Image - curl - All Regions

```bash
curl -X GET "https://api.aliyun.com/api/AIWorkSpace/2021-02-04/ListImageLabels?ImageId=image-4c62******53uor" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY"
```

## Response Format

```json
{
  "RequestId": "5A14FA81-DD4E-******-6343FE44B941"
}
```

For `ListImageLabels`, the response includes additional fields:

```json
{
  "RequestId": "5A14FA81-DD4E-******-6343FE44B941",
  "Labels": [
    {
      "Key": "system.chipType",
      "Value": "GPU"
    }
  ],
  "TotalCount": 2
}
```

**Key Fields**:
- `RequestId` — Unique identifier for the API call (useful for debugging).
- `Labels[].Key` — The label key (always prefixed with `system.` for system-defined tags).
- `Labels[].Value` — The associated label value.
- `TotalCount` — Total number of matching labels (only in `ListImageLabels`).

## Error Handling

| Error Code | Description | Recommended Action |
|-----------|-------------|-------------------|
| 400 | Invalid request parameter. Check that all required parameters are provided and formatted correctly. | Validate input syntax, especially `LabelFilter` encoding and required fields. |
| 401 | Unauthorized: Authentication failed. Check your API key or credentials. | Ensure `DASHSCOPE_API_KEY` is set and valid. |
| 403 | Access denied. Verify your permissions and ensure you have the necessary authorization to access the specified workspace or image. | Check RAM policies and workspace membership. |
| 404 | Image not found. The specified ImageId does not exist or is inaccessible. | Confirm the image exists using `ListImages`. |
| 500 | Internal server error. Retry the request after a short delay. If the issue persists, contact support. | Implement exponential backoff and retry up to 3 times. |

## Pricing & Billing

### Billing Model
Billed **per request**, regardless of label count or response size.

### Price Reference

| Tier | Input Price | Output Price |
|------|-------------|--------------|
| standard | 0.001 / | 0.001 / |
| default | 0.0001 / | 0.0001 / |

> `AddImageLabels` and `RemoveImageLabels` use the "standard" tier; `ListImageLabels` uses "default".

### Free Tier
Monthly free quota of **1,000 calls** across all image label management APIs.

### Usage Limits
- `AddImageLabels`: Max 100 labels per request.
- `ListImageLabels`: 100 QPS rate limit.
- `RemoveImageLabels`: Max 8192 characters in request path.

### Billing Notes
- Each API call counts as **one request**, even if it fails.
- Free tier applies to total calls across all three operations.

## FAQ

Q: What label keys are supported?
A: Only system-defined keys starting with `system.` are allowed. Examples include `system.chipType`, `system.framework`, `system.dsw.os`, `system.pythonVersion`, and others listed in the `Key` parameter description.

Q: Can I create custom label keys?
A: No. The API only accepts predefined system keys. Custom user-defined tags are not supported in this version.

Q: Why am I getting a 404 error when adding labels?
A: The `ImageId` must refer to an existing image in your workspace. Use the `ListImages` API to verify the image exists and is accessible.

Q: How do I filter by multiple label values?
A: Use the `LabelFilter` parameter with comma-separated `key=value` pairs (e.g., `system.framework=PyTorch 2.0,system.official=true`). URL-encode special characters like spaces.

Q: Is there a way to batch-remove multiple labels?
A: No. You must call `RemoveImageLabels` once per label key. Consider scripting loops for bulk operations.