# pai-audience

Part of **PAI**

# Platform for AI (PAI) Audience Management

## Capabilities Overview

| Sub-capability | Calling Mode | Description |
|----------------|--------------|-------------|
| Manage Audience Groups | Synchronous | Create, delete, get, and list audience groups. |

## API Calling Patterns

### Authentication
The primary authentication method is **Bearer Token** via the `Authorization` header.

- Use the header: `Authorization: Bearer <your_api_key>`
- Store your API key in the environment variable: `DASHSCOPE_API_KEY`
- While some endpoints (e.g., `ListGroups`) may not require authentication in certain contexts, it is strongly recommended to always include the `Authorization` header for consistency and access control.

### Service Endpoint
APIs use region-specific base URLs:

- China regions: `https://api.aliyun.com/api/PaiPlugin/2022-01-12`
- International regions: `https://api.alibabacloud.com/api/PaiPlugin/2022-01-12`

Common regions include `cn-hangzhou`, `cn-shanghai`, and `ap-southeast-1`. Always select the endpoint matching your deployment region.

### Synchronous Pattern
All Audience Management APIs follow a **Synchronous** calling pattern:
1. Send an HTTP request (GET, POST, or DELETE) to the appropriate endpoint with required parameters.
2. Include the `Authorization: Bearer $DASHSCOPE_API_KEY` header.
3. Receive a complete JSON response immediately.
4. Parse the `ErrorCode` field: `0` indicates success; non-zero values indicate errors (see Error Handling).

No polling or streaming is involved—each call completes in a single round trip.

## Parameter Reference

### Manage Audience Groups – CreateGroup

| Parameter | Type | Required | Default | Constraints | Description |
|----------|------|----------|---------|-------------|-------------|
| Name | string | false | — | — | The audience name. |
| Source | integer | false | — | One of: 0 (Text), 1 (Text file), 2 (CSV file), 3 (MaxCompute table), 4 (Algorithm) | The audience source. |
| Text | string | false | — | Maximum 100 phone numbers allowed | Text content. Required when the audience source is text. |
| Uri | string | false | — | Must be a valid OSS URI | The file URI. Required if source is text file or CSV file. |
| PhoneNumber | boolean | false | — | — | Indicates whether the audience contains phone numbers. |
| Project | string | false | — | — | MaxCompute project name. Required when source is MaxCompute. |
| Table | string | false | — | — | MaxCompute table name. Required when source is MaxCompute. |
| Column | string | false | — | — | Phone number column name. Required for CSV/MaxCompute with phone numbers. |
| Filter | string | false | — | — | Filter condition. Optional for MaxCompute sources. |
| Algorithm | string | false | — | — | Associated algorithm. Required when source is algorithm. |
| InferenceJobId | string | false | — | — | Prediction task ID. Required when source is algorithm. |
| Remark | string | false | — | — | The audience remark. |

### Manage Audience Groups – DeleteGroup

| Parameter | Type | Required | Default | Constraints | Description |
|----------|------|----------|---------|-------------|-------------|
| Id | string | false | — | — | Audience ID. Obtain via ListGroups. |

### Manage Audience Groups – GetGroup

| Parameter | Type | Required | Default | Constraints | Description |
|----------|------|----------|---------|-------------|-------------|
| Id | string | true | — | — | Audience ID. Obtain via ListGroups. |

### Manage Audience Groups – ListGroups

| Parameter | Type | Required | Default | Constraints | Description |
|----------|------|----------|---------|-------------|-------------|
| Name | string | false | — | — | Audience name filter. |
| Remark | string | false | — | — | Audience remark filter. |
| PhoneNumber | boolean | false | — | — | Filter by phone number inclusion. |
| Source | integer | false | — | — | Source filter (same enum as CreateGroup). |
| Status | integer | false | — | — | Review status filter. |
| PageNumber | integer | false | 1 | — | Page number (starts at 1). |
| PageSize | integer | false | 10 | — | Number of items per page. |

## Code Examples

### Create an Audience Group from Text – curl – all

```bash
curl -X POST https://api.aliyun.com/api/PaiPlugin/2022-01-12/CreateGroup \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
  "Name": "VIP customers",
  "Source": 0,
  "Text": "1390000****",
  "PhoneNumber": true
}'
```

### Retrieve Audience Details – curl – all

```bash
curl -X GET 'https://api.aliyun.com/api/PaiPlugin/2022-01-12/GetGroup?Id=0bddaf8f-5628-427a-8652-5e24f6b4c35d' \
-H 'Authorization: Bearer $DASHSCOPE_API_KEY'
```

### Delete an Audience Group – curl – all

```bash
curl -X DELETE https://api.aliyun.com/api/PaiPlugin/2022-01-12/DeleteGroup/0bddaf8f-5628-427a-8652-5e24f6b4c35d \
-H "Authorization: Bearer $DASHSCOPE_API_KEY"
```

### List Audience Groups – curl – all

```bash
curl -X GET 'https://api.aliyun.com/api/PaiPlugin/2022-01-12/ListGroups?PageNumber=1&PageSize=10' \
-H 'Authorization: Bearer $DASHSCOPE_API_KEY'
```

## Response Format

```json
{
  "Data": {
    "Algorithm": "user_recall",
    "Amount": 0,
    "Column": "phone",
    "CreatedTime": "2020-01-01 12:00:00",
    "Filter": "ds=20220101",
    "Id": "0a54e195-03e2-40bd-869d-b71cb302783e",
    "InferenceJobId": "0a54e195-03e2-40bd-869d-b71cb302783e",
    "Name": "VIP客户",
    "PhoneNumber": true,
    "Project": "project",
    "Remark": "充值大于10万",
    "Source": 0,
    "Status": 0,
    "Table": "recall",
    "Text": "1390000****",
    "UpdatedTime": "2020-01-01 12:00:00",
    "Uri": "https://bucket.region.aliyuncs.com/folder/file"
  },
  "ErrorCode": 0,
  "ErrorMessage": "OK",
  "RequestId": "f8651828-609d-4de8-ab49-ab781d7fd85a"
}
```

**Key Fields**:
- `Data.Id` — Unique identifier of the audience group
- `Data.Name` — Human-readable name of the group
- `Data.Status` — Processing or review status (0 typically means ready)
- `Data.Source` — Origin type of the audience data
- `Data.PhoneNumber` — Whether the group contains phone numbers (required for Reach campaigns)
- `Data.Amount` — Estimated size of the audience (may be 0 during processing)
- `Data.CreatedTime` / `Data.UpdatedTime` — Timestamps for lifecycle tracking
- `ErrorCode` — 0 for success; non-zero indicates failure
- `ErrorMessage` — Human-readable error description
- `RequestId` — Unique ID for troubleshooting support requests

## Error Handling

| Error Code | Description | Recommended Action |
|------------|-------------|---------------------|
| 400 | Bad Request. The request body is invalid or missing required parameters. | Validate all required fields based on the `Source` type and ensure correct data formats. |
| 403 | Forbidden. The user does not have sufficient permissions to access the specified OSS bucket or MaxCompute resource. Ensure one-click authorization is completed in the console. | Complete one-click authorization in the PAI console for MaxCompute/OSS resources, or verify bucket/table permissions. |
| 404 | Not Found. The specified MaxCompute project or table does not exist. | Confirm that the MaxCompute project and table names are correct and accessible in your region. |
| 500 | Internal Server Error. An unexpected error occurred on the server side. Retry the request after a short delay. | Implement exponential backoff and retry up to 3 times. If persistent, contact Alibaba Cloud support with the `RequestId`. |

### Rate Limits & Retry
- **CreateGroup**: 100 QPS per account
- **DeleteGroup**: 100 QPS
- Other endpoints have no documented hard limits but should respect general API best practices.

Use exponential backoff (e.g., 1s, 2s, 4s delays) for retries on 5xx errors. Do not retry 4xx errors unless the request payload is corrected.

## Environment Requirements

- Set your API key: `export DASHSCOPE_API_KEY=your_api_key_here`
- No specific SDK is required—all APIs are RESTful and can be called with standard HTTP clients (curl, requests, etc.)

## FAQ

Q: How do I obtain an audience group ID?
A: Call the `ListGroups` API to retrieve a list of existing groups and their IDs. You can filter by name or other attributes.

Q: Can I update an existing audience group?
A: No, the current API does not support updating groups. You must delete the old group and create a new one with updated parameters.

Q: Why am I getting a 403 error when using MaxCompute as a source?
A: You must complete "one-click authorization" in the PAI console to grant the service access to your MaxCompute project and OSS buckets.

Q: What is the maximum number of phone numbers allowed in a text-based audience?
A: Up to 100 phone numbers are allowed when using `Source=0` (Text).

Q: Are failed API calls billed?
A: For `CreateGroup` and `DeleteGroup`, both successful and failed requests are billed. For `GetGroup`, only successful calls are billed (per documentation notes).

## Pricing & Billing

### Billing Model
Per-request billing: each API call is charged individually.

### Price Reference

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

### Free Tier
- 1,000 free requests per month for `CreateGroup`, `GetGroup`, and `DeleteGroup`
- `ListGroups` pricing details not specified in documentation

### Usage Limits
- `CreateGroup`: Maximum 100 phone numbers per request
- `GetGroup`: Maximum 1,000 characters per request
- General QPS limit: 100 queries per second per account

### Billing Notes
- Creating an audience group incurs a request fee. Additional charges may apply if the group is later used in advertising campaigns (based on actual reach).
- Failed requests for `CreateGroup` and `DeleteGroup` are billed; failed `GetGroup` requests are not.