A rules-based algorithm is defined by a [`AlgorithmRules`](https://developers.google.com/display-video/api/reference/rest/current/AlgorithmRules) JSON
object. Upload the rules to Display \& Video 360 through a JSON file.

If using a script-based algorithm, go to the [Upload
script](https://developers.google.com/display-video/api/guides/tasks/implement-custom-bidding/upload-script) page.

## Build a rules object

Rules-based custom bidding algorithms employ [rules](https://developers.google.com/display-video/api/reference/rest/current/AlgorithmRules) to evaluate
the worth of a response signal.

An [`AlgorithmRules`](https://developers.google.com/display-video/api/reference/rest/current/AlgorithmRules) object consists of one or more
[rulesets](https://developers.google.com/display-video/api/reference/rest/current/AlgorithmRules#Ruleset). Each [ruleset](https://developers.google.com/display-video/api/reference/rest/current/AlgorithmRules#Ruleset) evaluates a different type
of response signal, such as an impression. Each [ruleset](https://developers.google.com/display-video/api/reference/rest/current/AlgorithmRules#Ruleset) has a
list of [rules](https://developers.google.com/display-video/api/reference/rest/current/AlgorithmRules#Rule). Each rule evaluates a signal against set conditions
and returns a value. A signal is evaluated by all [rules](https://developers.google.com/display-video/api/reference/rest/current/AlgorithmRules#Rule) in a set.
The values returned by each rule are then combined. This results in an
evaluation value for the signal.

> [!TIP]
> **Tip:** Read the [reference documentation](https://developers.google.com/display-video/api/reference/rest) for more on available [rule](https://developers.google.com/display-video/api/reference/rest/current/AlgorithmRules#Rule) conditions and logic.

Save your [`AlgorithmRules`](https://developers.google.com/display-video/api/reference/rest/current/AlgorithmRules) object locally as a JSON file.

## Generate a rules reference object

A [reference object](https://developers.google.com/display-video/api/reference/rest/current/customBiddingAlgorithms.rules#CustomBiddingAlgorithmRulesRef) is used to associate an uploaded file with a
[rules](https://developers.google.com/display-video/api/reference/rest/current/customBiddingAlgorithms.rules#CustomBiddingAlgorithmRules) resource. Generate a reference object under your
[algorithm](https://developers.google.com/display-video/api/reference/rest/current/customBiddingAlgorithms#CustomBiddingAlgorithm) using an [`uploadRules`](https://developers.google.com/display-video/api/reference/rest/current/customBiddingAlgorithms/uploadRules) request.

Here's how to generate a [rules](https://developers.google.com/display-video/api/reference/rest/current/AlgorithmRules) reference object:

### Java

```java
// Provide the ID of the advertiser that owns the algorithm.
long advertiserId = advertiser-id;

// Provide the ID of the algorithm.
long customBiddingAlgorithmId = algorithm-id;

// Generate an AlgorithmRules reference object under the algorithm.
CustomBiddingAlgorithmRulesRef response =
    service
        .customBiddingAlgorithms()
        .uploadRules(customBiddingAlgorithmId)
        .setAdvertiserId(advertiserId)
        .execute();

// Display the generated resource path.
System.out.printf(
    "The generated AlgorithmRules reference object provided the following resource path: %s.",
    response.getResourceName());
```

### Python

```python
# Provide the ID of the advertiser that owns the algorithm.
advertiser_id = advertiser-id

# Provide the ID of the algorithm.
algorithm_id = algorithm-id

# Generate an AlgorithmRules reference object under the algorithm.
custom_bidding_algorithm_rules_ref = (
    service.customBiddingAlgorithms()
    .uploadRules(
        customBiddingAlgorithmId=algorithm_id,
        advertiserId=advertiser_id
    )
    .execute()
)

# Print the resource path provided in the generated rules reference object.
print(
    "The generated rules reference object provided the following resource"
    f' path: {custom_bidding_algorithm_rules_ref["resourceName"]}.'
)
```

### PHP

```php
// Provide the ID of the advertiser that owns the algorithm.
$advertiserId = advertiser-id;

// Provide the ID of the algorithm.
$algorithmId = algorithm-id;

$uploadRulesOptParams = array(
    'advertiserId' => $advertiserId
);

try {
  // Generate an AlgorithmRules reference object under the algorithm.
    $rulesRefResponse =
        $this->service->customBiddingAlgorithms->uploadRules(
            $customBiddingAlgorithmId,
            $uploadRulesOptParams
        );
} catch (\Exception $e) {
    $this->renderError($e);
    return;
}

// Print the retrieved resource path.
printf(
    '<p>The generated AlgorithmRules reference object provided the '
        . 'following resource path: %s</p>',
    $rulesRefResponse->getResourceName()
);
```

## Upload an `AlgorithmRules` file

Use a media [`upload`](https://developers.google.com/display-video/api/reference/rest/current/media/upload) request to upload your rules file to the
resource path in the reference object. Use a [simple
upload](https://developers.google.com/display-video/api/guides/concepts/general/media-upload#simple_upload) with a query parameter
`uploadType=media`.

> [!WARNING]
> **Warning:** A rules file has a maximum file size of 7MB.

Here's how to upload a rules file:

### Java

```java
// Provide the local path to the AlgorithmRules file to upload.
String rulesPath = rules-path;

// Provide the resource path to upload the AlgorithmRules file to.
String resourcePath = resource-path;

// Create media object.
GoogleBytestreamMedia media = new GoogleBytestreamMedia();
media.setResourceName(resourcePath);

// Create input stream for the Algorithm file.
InputStreamContent rulesFileStream =
    new InputStreamContent(null, new FileInputStream(rulesPath));

// Create media.upload request.
Media.Upload uploadRequest = service.media().upload(resourcePath, media, rulesFileStream);

// Retrieve uploader from the request and set it to us a simple upload
// request.
MediaHttpUploader uploader = uploadRequest.getMediaHttpUploader();
uploader.setDirectUploadEnabled(true);

// Execute the upload using an Upload URL with the destination resource
// name.
uploader.upload(
    new GenericUrl("https://displayvideo.googleapis.com/upload/media/" + resourcePath));
```

### Python

```python
# Import HTTP objects used for file upload.
from apiclient.http import HttpRequest
from apiclient.http import MediaFileUpload

# Provide the local path to the AlgorithmRules file to upload.
rules_path = rules-path

# Provide the resource path to upload the AlgorithmRules file to.
resource_path = resource-path

# Create a media upload object.
media = MediaFileUpload(rules_path)

# Create upload request.
upload_request = service.media().upload(
    resourceName=resource_path, media_body=media
)

# Override response handler to expect null response.
upload_request.postproc = HttpRequest.null_postproc

# Upload AlgorithmRules to given resource path.
upload_request.execute()
```

### PHP

```php
// Provide the local path to the AlgorithmRules file to upload.
$rulesPath = rules-path;

// Provide the resource path to upload the AlgorithmRules file to.
$resourcePath = resource-path;

// Create the media body.
$mediaBody = new Google_Service_DisplayVideo_GoogleBytestreamMedia();
$mediaBody->setResourceName($resourceName);

// Build params array for the upload request.
$mediaUploadOptParams = array(
    'data' => file_get_contents($rulesPath),
    'uploadType' => 'media',
    'resourceName' => $resourceName
);

try {
    // Call the API, uploading the rules file to Display & Video 360.
    $this->service->media->upload(
        $resourceName,
        $mediaBody,
        $mediaUploadOptParams
    );
} catch (\Exception $e) {
    $this->renderError($e);
}
```

## Create a rules object

Use a [`create`](https://developers.google.com/display-video/api/reference/rest/current/customBiddingAlgorithms.rules/create) request to create a [rules](https://developers.google.com/display-video/api/reference/rest/current/customBiddingAlgorithms.rules#CustomBiddingAlgorithmRules) object
under your [algorithm](https://developers.google.com/display-video/api/reference/rest/current/customBiddingAlgorithms#CustomBiddingAlgorithm).

> [!CAUTION]
> **Caution:** An algorithm will use the most recent valid rules object once it has successfully trained on available data. Training can take 1-3 days. Don't create a rules object unless you are sure that you want to overwrite the existing rules.

Here's how to create a rules object:

### Java

```java
// Provide the ID of the advertiser that owns the parent algorithm.
long advertiserId = advertiser-id;

// Provide the ID of the parent algorithm.
long algorithmId = algorithm-id;

// Provide the resource path the AlgorithmRules file was uploaded to.
String resourcePath = resource-path;

// Create the custom bidding algorithm rules structure.
CustomBiddingAlgorithmRules customBiddingAlgorithmRules =
    new CustomBiddingAlgorithmRules()
        .setRules(new CustomBiddingAlgorithmRulesRef().setResourceName(resourcePath));

// Create the custom bidding algorithm rules.
CustomBiddingAlgorithmRules response =
    service
        .customBiddingAlgorithms()
        .rules()
        .create(algorithmId, customBiddingAlgorithmRules)
        .setAdvertiserId(advertiserId)
        .execute();

// Print ID of new custom bidding algorithm rules.
System.out.printf("Rules were created with ID %s.", response.getCustomBiddingAlgorithmRulesId());
```

### Python

```python
# Provide the ID of the advertiser that owns the parent algorithm.
advertiser_id = advertiser-id

# Provide the ID of the parent algorithm.
algorithm_id = algorithm-id

# Provide the resource path the AlgorithmRules file was uploaded to.
resource_path = resource-path

# Build algorithm rules object.
rules_obj = {"rules": {"resourceName": resource_path}}

# Build and execute request.
rules_response = (
    service.customBiddingAlgorithms()
    .rules()
    .create(
        customBiddingAlgorithmId=algorithm_id,
        advertiserId=advertiser_id,
        body=rules_obj,
    )
    .execute()
)

# Print ID of new custom bidding algorithm rules.
print(
    f'Rules were created with ID {rules_response["customBiddingAlgorithmRulesId"]}.'
)
```

### PHP

```php
// Provide the ID of the advertiser that owns the parent algorithm.
$advertiserId = advertiser-id;

// Provide the ID of the parent algorithm.
$algorithmId = algorithm-id;

// Provide the resource path the AlgorithmRules file was uploaded to.
$resourcePath = resource-path;

// Build algorithm rules object.
$customBiddingRules = new Google_Service_DisplayVideo_CustomBiddingAlgorithmRules();
$rulesRef = new Google_Service_DisplayVideo_CustomBiddingAlgorithmRulesRef();
$rulesRef->setResourceName($resourcePath);
$customBiddingRules->setRules($rulesRef);

$createRulesOptParams = array(
    'advertiserId' => $advertiserId
);

// Call the API, creating the custom bidding algorithm rules using the
// rules file and under the custom bidding algorithm given.
try {
    $result = $this->service->customBiddingAlgorithms_rules->create(
        $customBiddingAlgorithmId,
        $algorithmId,
        $createRulesOptParams
    );
} catch (\Exception $e) {
    $this->renderError($e);
    return;
}

// Print ID of new custom bidding algorithm rules.
printf('<p>Rules was created with ID %s.</p>', $result['customBiddingAlgorithmRulesId']);
```