All Products
Search
Document Center

Platform For AI:How to integrate the A/B test system with your system

Last Updated:Sep 15, 2026

PAI-Rec's A/B testing system can run alongside your existing recommendation, search, or advertising engine — no migration required. Integrate by configuring cloud resources, setting up experiments, calling the SDK, and measuring results.

How it works

PAI-Rec organizes A/B testing in a four-level hierarchy:

Lab → Experiment layer → Experiment group → Experiment

A lab contains experiment layers, each layer contains experiment groups, and each group contains experiments. Traffic flows through non-base labs first; the base lab handles remaining traffic as a fallback.

When a user request arrives, the SDK calls match_experiment with a scenario name and a request context. PAI-Rec assigns the user to an experiment and returns:

  • exp_id — the experiment ID to log with every user event for metric calculation

  • Experiment parameters — key-value pairs your system reads to determine which algorithm variant to run

Events and metrics: Your code logs user behavior events (clicks, purchases, and so on) and records exp_id in each event. PAI-Rec aggregates these events in MaxCompute to compute experiment metrics and generate comparison reports. The exp_id field is what links each behavior event to the correct experiment during analysis.

Prerequisites

Before you begin, ensure that you have:

  • A PAI-Rec instance with an instance ID and region

  • AccessKey ID and AccessKey secret (from your Alibaba Cloud account)

  • A MaxCompute project with read and write access granted to PAI-Rec

  • An Object Storage Service (OSS) bucket

Step 1: Configure resources

Log on to the PAI-Rec console

In the PAI-Rec console, click Full-link Service in the left-side navigation pane. In the Service Initialization wizard that appears, configure your workspaces.

Configuration notes:

  1. Query existing workspaces from Platform for AI (PAI), DataWorks, and MaxCompute in their respective consoles. On each product homepage, click Console.

  2. Create an OSS bucket in the OSS console before configuring it here.

Grant MaxCompute access

On the Projects page, search for the MaxCompute project you want to use.

If no project appears, select the correct region first.

In the Actions column of the project, click Manage. Grant PAI-Rec direct access and write permissions on the MaxCompute project.

For details, see Service activation and initialization.

Step 2: Create a scenario

Parameter Description
Scenario name Name of the recommendation scenario. Use a name that reflects the page location (for example, homepage_feed).
Description Optional description of the scenario.
Intended users Select users who do not fully use PAI-Rec.

Traffic configuration for self-managed systems:

If you have a self-managed recommendation system, start by routing 10%–20% of scenario traffic to PAI-Rec. Once results meet expectations, increase the traffic share gradually.

To track your self-managed traffic separately, assign it a custom traffic code. Record exp_id in your event tracking logs for each user interaction so that PAI-Rec can attribute behavior events to experiments during metric calculation.

Step 3: Configure A/B testing

Important

Before starting an experiment, confirm the changes to be tested with the relevant product manager or project manager.

For terminology definitions, see Basic Concepts.

Create a lab

  1. Select a runtime environment and recommendation scenario.

  2. Click Create Lab.

  3. On the Create Lab panel, configure the following parameters:

Parameter Description
Lab type Base Lab (required): handles traffic that does not match non-base labs. Can use popular items or random fallback logic. Non-base Lab (optional): traffic matches here first; useful for complex models running alongside a simpler base model.
Bucketing method Hashed UID-based Bucketing: buckets users by hash value of UID. UID-based Bucketing: buckets users by last digits of UID. Condition-based Bucketing: buckets users by a key-value expression such as gender=man.
Buckets Total number of buckets in this lab (for example, 100).
Traffic allocation Bucket numbers assigned to this lab, in the range 0–99.
Layering Experiment layer. Typical layers: recall, filter, coarse_rank, rank.
Test users Users routed directly to this lab without bucketing matching. Enter UIDs manually (comma-separated) or select a User Group ID from the User Group Management page.

Create an experiment group

Each experiment layer can have multiple experiment groups, and each group can have multiple experiments. Use separate groups when multiple engineers need to run experiments on the same layer (for example, different recall algorithms) without interfering with each other.

A/A test group (recommended for new experiments):

To validate that your experiment setup is unbiased, create an A/A test group before running real experiments:

  1. Select 4–5 buckets for the experiment.

  2. Assign 2 buckets to a group with no policy configured. Run these buckets as a dry run and monitor key metrics.

  3. Use the two groups whose metrics are most similar for your actual A/B test.

Additional experiment group parameters:

Parameter Description
Filter by Filter users further after test users are selected. Filtering by new vs. existing users gives more comprehensive test results.
Test users Manually Enter: specify user IDs to run experiments first, collect feedback, then refine. User Group ID: route specific user groups to specific experiments. Create user groups in User Group Management under Experiment Platform; you can upload user IDs manually or via Excel.

Create an experiment

Click Create Experiment. By default, a baseline experiment is created first.

Experiment type Description
Baseline experiment The control group. Users are randomly assigned to the experiment group or the control group.
Normal experiment Additional experiments with the same structure as the baseline. Each serves as a treatment group.

Traffic allocation strategies:

Goal Strategy
Minimize risk on new feature launch Send a small traffic slice to the new version to limit user impact while gathering data within your timeline.
Maximize test speed Distribute traffic evenly across groups to collect results faster.
Optimize return on investment (ROI) Allocate more traffic to the experiment group and keep a small slice for the control group.

After configuring all parameters, click Save.

Step 4: Call the SDK

Both the Python and Java SDKs follow the same pattern: initialize a client with your credentials and instance details, call match_experiment with a scenario name and user context, then read exp_id and experiment parameters from the result.

Store exp_id in every user behavior event you log. PAI-Rec uses this field to attribute events to experiments when computing metrics.

Python SDK

Install

You must prepare a Python environment and install PyCharm to run the SDK.

pip install https://aliyun-pairec-config-sdk.oss-cn-hangzhou.aliyuncs.com/python/aliyun_pairec_config_python_sdk-1.0.0-py2.py3-none-any.whl
Install using the command above, not through PyCharm's package manager. The package is not open source, and PyCharm's installer may cause conflicts. If pip needs updating, update it before installing. If you encounter a timeout, run the command again.

Initialize and call

Store your credentials in environment variables before running the code:

export ALIBABA_CLOUD_ACCESS_KEY_ID=<your-access-key-id>
export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<your-access-key-secret>
Warning

Never hardcode AccessKey credentials in your source code. Read them from environment variables at runtime.

import os
from alibabacloud_tea_openapi.models import Config
from api.api_scene import SceneApiService
from api.api_experiment_room import ExperimentRoomApiService
from api.api_layer import api_layer
from api.api_experiment_group import ExperimentGroupApiService
from api.api_experiment import ExperimentApiService
from client.client import ExperimentClient
from model.experiment import ExperimentContext
from api.api_crowd import CrowdApiService
from alibabacloud_pairecservice20221213.client import Client
from common.constants import ENVIRONMENT_PRODUCT_CONFIG_CENTER
from common.constants import ENVIRONMENT_PREPUB_CONFIG_CENTER
from common.constants import ENVIRONMENT_DAILY_CONFIG_CENTER

# Instance details — find these on the Basic Information page in the PAI-Rec console
instance_id = "<instance-id>"
region = "<region-id>"

# Read credentials from environment variables
access_id = os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
access_key = os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']

if __name__ == '__main__':
    # Valid environments: ENVIRONMENT_PRODUCT_CONFIG_CENTER, ENVIRONMENT_PREPUB_CONFIG_CENTER, ENVIRONMENT_DAILY_CONFIG_CENTER
    experiment = ExperimentClient(
        instance_id=instance_id,
        region=region,
        access_key_id=access_id,
        access_key_secret=access_key,
        environment=ENVIRONMENT_PRODUCT_CONFIG_CENTER
    )

    # Build the request context
    # request_id: any unique identifier (auto-increment ID or UUID)
    # uid: the user ID to assign to an experiment
    experiment_context = ExperimentContext(
        request_id="<request-id>",
        uid="<user-id>",
        filter_params={}
    )

    # Match the user to an experiment in the specified scenario
    # Find the scenario name on the Recommendation Scenarios page
    experiment_result = experiment.match_experiment("<scenario-name>", experiment_context)

    # Log experiment assignment details
    print('info', experiment_result.info())

    # Store exp_id in your event tracking logs for metric calculation
    print('exp_id', experiment_result.get_exp_id())

    # Read experiment parameters to determine which algorithm variant to run
    print(experiment_result.get_experiment_params())
    print(experiment_result.get_experiment_params().get('url', 'not exist'))
    print(experiment_result.get_experiment_params().get('token', 'not exist'))

Replace the placeholders before running:

Placeholder Where to find it
<instance-id> Basic Information page in the PAI-Rec console
<region-id> Basic Information page in the PAI-Rec console
<scenario-name> Recommendation Scenarios page in the PAI-Rec console

Expected output:

A successful run prints the experiment assignment and the parameter values configured for that experiment:

info exp_id=<exp_id> ...
exp_id <exp_id>
{'url': 'https://...', 'token': '...'}
https://...
...
If a KeyError occurs when reading environment variables, right-click the run configuration in PyCharm and verify that system variables are loaded. If not, restart the project.

Java SDK

Warning

Never hardcode AccessKey credentials in your source code. Read them from environment variables at runtime.

package com.aliyun.openservices.pairec;

import com.aliyun.openservices.pairec.api.ApiClient;
import com.aliyun.openservices.pairec.api.Configuration;
import com.aliyun.openservices.pairec.common.Constants;
import com.aliyun.openservices.pairec.model.ExperimentContext;
import com.aliyun.openservices.pairec.model.ExperimentResult;

public class ExperimentTest {
    static ExperimentClient experimentClient;

    public static void main(String[] args) throws Exception {
        // Instance details — find regionId and instanceId on the Basic Information page
        String regionId = "<region-id>";
        String instanceId = System.getenv("Instance ID"); // pai-rec instance ID

        // Read credentials from environment variables
        String accessId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
        String accessKey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");

        Configuration configuration = new Configuration(regionId, accessId, accessKey, instanceId);
        // Set the experiment environment
        configuration.setEnvironment(Constants.Environment_Product_Desc);

        ApiClient apiClient = new ApiClient(configuration);
        experimentClient = new ExperimentClient(apiClient);
        // Initialize the client
        experimentClient.init();

        // Build the request context
        ExperimentContext experimentContext = new ExperimentContext();
        experimentContext.setUid("<user-id>");
        experimentContext.setRequestId("<request-id>");

        // Match the user to an experiment in the specified scenario
        ExperimentResult experimentResult = experimentClient.matchExperiment("<scenario-name>", experimentContext);

        // Store exp_id in your event tracking logs for metric calculation
        System.out.println(experimentResult.getExpId());
        // Log experiment assignment details
        System.out.println(experimentResult.info());

        // Read experiment parameters to determine which algorithm variant to run
        System.out.println(experimentResult.getExperimentParams().getString("rank_version", "not exist"));
        System.out.println(experimentResult.getExperimentParams().getString("version", "not exist"));
        System.out.println(experimentResult.getExperimentParams().getString("recall", "not exist"));
        System.out.println(experimentResult.getExperimentParams().getDouble("recall_d", 0.0));

        // Read parameters for a specific experiment layer by name
        System.out.println(experimentResult.getLayerParams("recall").getString("rank_version", "not exist"));
        System.out.println(experimentResult.getLayerParams("rank").getString("version", "not exist"));
    }
}

Step 5: Design experiment metrics

Before computing metrics, register a MaxCompute data table and define what to measure. Data analysts typically design key metrics — such as click-through rate (CTR) and conversion rate (CVR) — along with must-see metrics that must not regress during the experiment.

Register a data table

In the PAI-Rec console, go to Metric Management > Data Registration. Associate a MaxCompute table with your A/B testing instance. Set Data Table Name to a name that reflects the business context.

Select a table that contains the required fields. For field requirements, see Data registration and field configuration.

If your MaxCompute project does not have a table with all required fields, create one:

  1. Log on to the MaxCompute console and create a data table.

  2. In DataWorks, create a source table for A/B testing experiment reports in MaxCompute.

After registration, the table appears in the data table list. Click View Fields in the Actions column to inspect or edit field mappings.

Metric types

PAI-Rec supports three categories of metrics:

Category Examples When to use
Ratio-based metrics Click conversion rate, CTR, CVR, next-day retention rate Compare rates between groups; most common for recommendation experiments
Per-user metrics Average clicks per user, average order value (AOV) Measure per-user impact rather than aggregate rates
Absolute metrics Total clicks, total order amount Compare only when test groups have the same number of users

In addition, distinguish between:

  • Key metrics (KPIs): the primary outcomes the experiment is designed to improve

  • Must-see metrics: metrics that must be observed during a test; the capability being tested cannot affect them adversely

Configure metrics

On the Metric Configurations page, click Metrics. Set the Recommendation Scenario and Metric Timeliness parameters.

Single-dimension metrics are computed from a single aggregation: count, unique count, sum, or average. For example, daily clicks and daily visits are single-dimension metrics.

In the Metric Definition parameter:

  • Page Views: counts every page visit

  • Unique Visitors: counts each user once, on first visit

Derived metrics combine multiple single-dimension metrics. For example:

CTR = Daily clicks / Daily visits

Add daily clicks and daily visits as single-dimension metrics first, then define CTR as a derived metric using the formula above.

Configure metric groups

Group related metrics together to calculate and compare them as a set.

  1. On the Metric Groups tab, create a metric group and set the Metric Selection parameter to include the metrics you want.

  2. Click Calculate in the Actions column to trigger metric computation.

Step 6: Calculate metrics and generate reports

Calculate metrics

On the Metric Groups tab of the Metric Configurations page, click Calculate in the Actions column. Select the metrics to compute on the panel that appears.

Track job progress on the Jobs page. When all jobs complete, the status changes to Succeeded.

View reports

On the Performance Reports page under Experiment Platform, configure the parameters and click Start Analysis.

  • Detail Data: shows the metric differences between the baseline experiment and normal experiments

  • Trend Analysis: shows how selected metrics change over the experiment period

What's next