# pai-algorithm

Part of **PAI**

# Platform for AI (PAI) Algorithm Management

## Capabilities Overview

| Sub-capability | Calling Mode | Description |
|----------------|--------------|-------------|
| Manage Algorithms | Synchronous | Create, list, get details, update, and delete algorithms. |
| Manage Algorithm Versions | Synchronous | Create, list, get details, update, and delete algorithm versions. |

## API Calling Patterns

### Authentication
The primary authentication method is **Bearer Token**.

- Include the header: `Authorization: Bearer <your_api_key>`
- Store your API key in the environment variable: `DASHSCOPE_API_KEY`
- Example: `export DASHSCOPE_API_KEY=sk-xxxxxx`

While some endpoints (e.g., `ListAlgorithms` under `PaiPlugin`) may not require authentication, it is strongly recommended to always include the `Authorization` header for consistency and access control.

### Service Endpoint
APIs use region-specific base URLs with the pattern:

```text
https://api.aliyun.com/api/{Product}/{Version}
```

Common regions:
- China: `https://api.aliyun.com`
- International: `https://api.alibabacloud.com`

Two main product paths are used:
- `PaiStudio/2022-01-12` — for core algorithm management
- `PaiPlugin/2022-01-12` — for plugin-based algorithm tasks

### Synchronous API Pattern
All operations in this domain follow a **synchronous** calling pattern:

1. Send an HTTP request (GET, POST, PUT, or DELETE) to the appropriate endpoint
2. Include required parameters as query string (GET/DELETE) or JSON body (POST/PUT)
3. Provide the `Authorization: Bearer $DASHSCOPE_API_KEY` header
4. Receive a JSON response immediately with result or error

No polling or async task handling is required—responses are returned directly.

## Parameter Reference

### Manage Algorithms

| Parameter | Type | Required | Default | Constraints | Description |
|----------|------|----------|---------|-------------|-------------|
| WorkspaceId | string | false | — | — | The ID of the workspace. |
| AlgorithmDescription | string | false | — | — | The description of the algorithm. |
| AlgorithmName | string | false | — | — | The name of the algorithm. |
| DisplayName | string | false | — | — | The display name of the algorithm. |
| AlgorithmId | string | false | — | — | The algorithm ID (used in Get/Delete/Update). |
| PageSize | integer | false | — | — | Page size for listing. |
| PageNumber | integer | false | — | — | Page number for listing. |
| AlgorithmProvider | string | false | — | — | Algorithm provider (e.g., "pai"). |

### Manage Algorithm Versions

| Parameter | Type | Required | Default | Constraints | Description |
|----------|------|----------|---------|-------------|-------------|
| AlgorithmId | string | true (for version ops) | — | — | ID of the parent algorithm. |
| AlgorithmVersion | string | true (for version ops) | — | — | Version string (e.g., "v0.0.1"). |
| AlgorithmSpec | object | false | — | — | Full algorithm configuration including hyperparameters, input/output channels, image, command, etc. |

## Code Examples

### Create an Algorithm - curl - all

```bash
curl -X POST https://api.aliyun.com/api/PaiStudio/2022-01-12/CreateAlgorithm \
-H "Authorization: Bearer <your-api-key>" \
-H "Content-Type: application/json" \
-d '{
  "WorkspaceId": "12345",
  "AlgorithmName": "llm_training",
  "DisplayName": "Large Language Model Training",
  "AlgorithmDescription": "Qwen large language model training algorithm."
}'
```

### Get Algorithm Details - bash - all

```bash
curl -X GET 'https://api.aliyun.com/api/PaiStudio/2022-01-12/algorithms/algo-xsldfvu1334' \
-H 'Authorization: Bearer $DASHSCOPE_API_KEY' \
-H 'Content-Type: application/json'
```

### List Algorithm Versions - curl - all

```bash
curl -X GET 'https://api.aliyun.com/api/PaiStudio/2022-01-12/ListAlgorithmVersions?AlgorithmId=algo-sidjc8134hv&PageSize=10&PageNumber=1' \
-H 'Authorization: Bearer <your-api-key>'
```

### Get Algorithm Version with Full Spec - Python - all

```python
import requests

url = "https://api.aliyun.com/api/PaiStudio/2022-01-12/GetAlgorithmVersion"
params = {
    "AlgorithmId": "algo-xsldfvu1334",
    "AlgorithmVersion": "v0.0.1"
}
headers = {
    "Authorization": "Bearer $DASHSCOPE_API_KEY",
    "Content-Type": "application/json"
}

response = requests.get(url, params=params, headers=headers)
print(response.json())
```

### Update Algorithm Display Name - curl - all

```bash
curl -X PUT https://api.aliyun.com/api/PaiStudio/2022-01-12/algorithms/algo-sidjc8134hv \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
  "AlgorithmDescription": "Large language model training.",
  "DisplayName": "LLM Train"
}'
```

### Delete an Algorithm Version - bash - all

```bash
curl -X DELETE https://api.aliyun.com/api/PaiStudio/2022-01-12/DeleteAlgorithmVersion?AlgorithmId=algo-xsldfvu1334&AlgorithmVersion=v0.0.1 \
-H "Authorization: Bearer <your-api-key>"
```

## Response Format

```json
{
  "RequestId": "E7C42CC7-2E85-508A-84F4-923B605FD10F",
  "AlgorithmId": "algo-xsldfvu1334"
}
```

**Key Fields**:
- `RequestId` — Unique identifier for the API request (useful for debugging)
- `AlgorithmId` — ID of the created or updated algorithm
- `AlgorithmVersion` — Version string for version-related operations
- `Algorithms` / `AlgorithmVersions` — Arrays containing metadata for list operations
- `TotalCount` — Total number of items matching the query (for pagination)

## Error Handling

| Error Code | Description | Recommended Action |
|------------|-------------|-------------------|
| 400 | Bad Request: The request parameters are invalid or missing required fields. | Validate all required parameters and data types; check for typos. |
| 401 | Unauthorized: The request lacks valid authentication credentials. | Ensure `DASHSCOPE_API_KEY` is set and the `Authorization` header is correctly formatted. |
| 403 | Forbidden: The user does not have sufficient permissions to perform this operation. | Verify your RAM role has `pai:CreateAlgorithm`, `pai:DeleteAlgorithm`, etc., permissions. |
| 404 | Not Found: The specified algorithm, version, or workspace does not exist. | Confirm the `AlgorithmId` and `AlgorithmVersion` are correct and exist in your workspace. |
| 429 | Too many requests. Rate limit exceeded. | Reduce request frequency; implement exponential backoff. |
| 500 | Internal Server Error: An unexpected error occurred on the server side. | Retry the request; if persistent, contact Alibaba Cloud support with `RequestId`. |
| 503 | Service Unavailable: The service is temporarily unavailable due to overload or maintenance. | Wait and retry after a short delay. |

### Rate Limits & Retry
- Most endpoints: **100 QPS per user**
- Some endpoints (e.g., CreateAlgorithm): **10 requests per second**
- Implement exponential backoff (e.g., 1s, 2s, 4s delays) on 429 errors
- Respect the `Retry-After` header if provided

## Environment Requirements

- Set your API key: `export DASHSCOPE_API_KEY=your_key_here`
- Use any HTTP client (curl, requests, axios, etc.)
- No specific SDK is required—these are standard REST APIs
- For Python: `pip install requests` (if using the example above)

## FAQ

Q: Do I need to authenticate for all algorithm management APIs?
A: Most APIs require a Bearer token, but some read-only endpoints like `ListAlgorithms` under `PaiPlugin` may allow unauthenticated access. However, authenticated requests ensure consistent access control and are recommended.

Q: What is the difference between `PaiStudio` and `PaiPlugin` API paths?
A: `PaiStudio/2022-01-12` is used for general algorithm management in PAI Studio, while `PaiPlugin/2022-01-12` is specific to algorithm tasks within the PAI Plugin system. Both manage algorithms but serve different subsystems.

Q: Can I update an algorithm’s name or ID?
A: No. Only `DisplayName` and `AlgorithmDescription` can be updated. The `AlgorithmName` and `AlgorithmId` are immutable after creation.

Q: How do I specify hyperparameters when creating an algorithm version?
A: Include them in the `AlgorithmSpec` object under the `HyperParameters` array, with fields like `Name`, `Type`, `DefaultValue`, `Required`, and `Range`.

Q: Are algorithm names globally unique?
A: Algorithm names are unique within a workspace. Use `WorkspaceId` to scope your operations correctly.

## Pricing & Billing

### Billing Model
All operations are billed **per request**, regardless of success or failure (except where noted).

### Price Reference

| Tier | Input Price | Output Price |
|------|-------------|--------------|
| standard | ¥0.001 per call | ¥0.001 per call |
| default | ¥0.001 per call | — |

Note: `ListAlgorithms` under `PaiStudio` is free.

### Free Tier
- Most operations: **1,000 free calls per month**
- `GetAlgorithm` (PaiStudio): **1,000 free calls per month**
- Free tier resets monthly

### Usage Limits
- Per-user rate limits: **10–100 QPS** depending on endpoint
- `GetAlgorithm` response size: **max 8KB**

### Billing Notes
- Failed requests (e.g., 4xx/5xx) still count toward quota and billing unless explicitly stated otherwise
- Free tier applies per Alibaba Cloud account
- Pricing is in Chinese Yuan (¥)