Penyaluran online

Dengan penyaluran online, Anda dapat menyalurkan nilai fitur untuk batch kecil entity pada latensi rendah. Untuk setiap permintaan, Anda hanya dapat menyalurkan nilai fitur dari satu jenis entity. Vertex AI Feature Store (Lama) hanya menampilkan nilai non-null terbaru dari setiap fitur.

Biasanya, Anda menggunakan penyaluran online untuk menyalurkan nilai fitur ke model yang di-deploy untuk prediksi online. Misalnya, Anda mungkin memiliki perusahaan rental sepeda dan ingin memprediksi berapa lama pengguna tertentu akan menyewa sepeda. Anda dapat menyertakan input real-time dari pengguna dan data dari featurestore untuk melakukan prediksi online. Dengan begitu, Anda dapat menentukan alokasi resource secara real time.

Nilai null

Untuk hasil penyaluran online, jika nilai terbaru untuk suatu fitur adalah null, Vertex AI Feature Store (Lama) akan menampilkan nilai selain null terbaru. Jika tidak ada nilai sebelumnya, Vertex AI Feature Store (Lama) akan menampilkan null.

Sebelum memulai

Pastikan featurestore tempat Anda melakukan panggilan memiliki toko online (jumlah node harus lebih besar dari 0). Jika tidak, permintaan penyaluran online akan menampilkan error. Untuk mengetahui info selengkapnya, lihat Mengelola featurestores.

Menyalurkan nilai dari satu entity

Menyalurkan nilai fitur dari satu entity untuk jenis entity tertentu.

REST

Untuk mendapatkan nilai fitur dari entity, kirim permintaan POST menggunakan metode featurestores.entityTypes.readFeatureValues.

Contoh berikut mendapatkan nilai terbaru untuk dua fitur yang berbeda untuk entity tertentu. Perhatikan bahwa untuk kolom ids, Anda dapat menentukan ["*"], bukan ID fitur, untuk memilih semua fitur entity.

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • LOCATION_ID: Region tempat featurestore dibuat. Contoh, us-central1.
  • PROJECT_ID: Project ID Anda.
  • FEATURESTORE_ID: ID featurestore.
  • ENTITY_TYPE_ID: ID jenis entity.
  • ENTITY_ID: ID entity yang akan mendapatkan nilai fiturnya.
  • FEATURE_ID: ID fitur yang ingin diperoleh nilainya.

Metode HTTP dan URL:

POST http://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/featurestores/FEATURESTORE_ID/entityTypes/ENTITY_TYPE_ID:readFeatureValues

Isi JSON permintaan:

{
  "entityId": "ENTITY_ID",
  "featureSelector": {
    "idMatcher": {
      "ids": ["FEATURE_ID_1", "FEATURE_ID_2"]
    }
  }
}

Untuk mengirim permintaan Anda, pilih salah satu opsi berikut:

curl

Simpan isi permintaan dalam file bernama request.json, dan jalankan perintah berikut:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"http://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/featurestores/FEATURESTORE_ID/entityTypes/ENTITY_TYPE_ID:readFeatureValues"

PowerShell

Simpan isi permintaan dalam file bernama request.json, dan jalankan perintah berikut:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "http://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/featurestores/FEATURESTORE_ID/entityTypes/ENTITY_TYPE_ID:readFeatureValues" | Select-Object -Expand Content

Anda akan melihat respons JSON seperti berikut:

{
  "header": {
    "entityType": "projects/PROJECT_NUMBER/locations/LOCATION_ID/featurestores/FEATURESTORE_ID/entityTypes/ENTITY_TYPE_ID",
    "featureDescriptors": [
      {
        "id": "FEATURE_ID_1"
      },
      {
        "id": "FEATURE_ID_2"
      }
    ]
  },
  "entityView": {
    "entityId": "ENTITY_ID",
    "data": [
      {
        "value": {
          "VALUE_TYPE_1": "FEATURE_VALUE_1",
          "metadata": {
            "generateTime": "2019-10-28T15:38:10Z"
          }
        }
      },
      {
        "value": {
          "VALUE_TYPE_2": "FEATURE_VALUE_2",
          "metadata": {
            "generateTime": "2019-10-28T15:38:10Z"
          }
        }
      }
    ]
  }
}

Python

Untuk mempelajari cara menginstal atau mengupdate Vertex AI SDK untuk Python, lihat Menginstal Vertex AI SDK untuk Python. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi Python API.

from typing import List, Union

from google.cloud import aiplatform

def read_feature_values_sample(
    project: str,
    location: str,
    entity_type_id: str,
    featurestore_id: str,
    entity_ids: Union[str, List[str]],
    feature_ids: Union[str, List[str]] = "*",
):

    aiplatform.init(project=project, location=location)

    my_entity_type = aiplatform.featurestore.EntityType(
        entity_type_name=entity_type_id, featurestore_id=featurestore_id
    )

    my_dataframe = my_entity_type.read(entity_ids=entity_ids, feature_ids=feature_ids)

    return my_dataframe

Python

Library klien untuk Vertex AI disertakan saat Anda menginstal Vertex AI SDK untuk Python. Guna mempelajari cara menginstal Vertex AI SDK untuk Python, lihat Menginstal Vertex AI SDK untuk Python. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API Vertex AI SDK untuk Python.

from google.cloud import aiplatform

def read_feature_values_sample(
    project: str,
    featurestore_id: str,
    entity_type_id: str,
    entity_id: str,
    location: str = "us-central1",
    api_endpoint: str = "us-central1-aiplatform.googleapis.com",
):
    # The AI Platform services require regional API endpoints, which need to be
    # in the same region or multi-region overlap with the Feature Store location.
    client_options = {"api_endpoint": api_endpoint}
    # Initialize client that will be used to create and send requests.
    # This client only needs to be created once, and can be reused for multiple requests.
    client = aiplatform.gapic.FeaturestoreOnlineServingServiceClient(
        client_options=client_options
    )
    entity_type = f"projects/{project}/locations/{location}/featurestores/{featurestore_id}/entityTypes/{entity_type_id}"
    feature_selector = aiplatform.gapic.FeatureSelector(
        id_matcher=aiplatform.gapic.IdMatcher(ids=["age", "gender", "liked_genres"])
    )
    read_feature_values_request = aiplatform.gapic.ReadFeatureValuesRequest(
        entity_type=entity_type, entity_id=entity_id, feature_selector=feature_selector
    )
    read_feature_values_response = client.read_feature_values(
        request=read_feature_values_request
    )
    print("read_feature_values_response:", read_feature_values_response)

Java

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Java di Panduan memulai Vertex AI menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API Java Vertex AI.

Untuk melakukan autentikasi ke Vertex AI, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


import com.google.cloud.aiplatform.v1.EntityTypeName;
import com.google.cloud.aiplatform.v1.FeatureSelector;
import com.google.cloud.aiplatform.v1.FeaturestoreOnlineServingServiceClient;
import com.google.cloud.aiplatform.v1.FeaturestoreOnlineServingServiceSettings;
import com.google.cloud.aiplatform.v1.IdMatcher;
import com.google.cloud.aiplatform.v1.ReadFeatureValuesRequest;
import com.google.cloud.aiplatform.v1.ReadFeatureValuesResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

public class ReadFeatureValuesSample {

  public static void main(String[] args)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "YOUR_PROJECT_ID";
    // Feature Store ID
    String featurestoreId = "YOUR_FEATURESTORE_ID";
    // Entity Type ID
    String entityTypeId = "YOUR_ENTITY_TYPE_ID";
    // Entity ID
    String entityId = "YOUR_ENTITY_ID";
    // Features to read with batch or online serving.
    List<String> featureSelectorIds = Arrays.asList("title", "genres", "average_rating");
    String location = "us-central1";
    String endpoint = "us-central1-aiplatform.googleapis.com:443";
    int timeout = 300;

    readFeatureValuesSample(
        project,
        featurestoreId,
        entityTypeId,
        entityId,
        featureSelectorIds,
        location,
        endpoint,
        timeout);
  }

  /*
   * Reads Feature values of a specific entity of an EntityType.
   * See: http://cloud.go888ogle.com.fqhub.com/vertex-ai/docs/featurestore/serving-online
   */
  public static void readFeatureValuesSample(
      String project,
      String featurestoreId,
      String entityTypeId,
      String entityId,
      List<String> featureSelectorIds,
      String location,
      String endpoint,
      int timeout)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    FeaturestoreOnlineServingServiceSettings featurestoreOnlineServiceSettings =
        FeaturestoreOnlineServingServiceSettings.newBuilder().setEndpoint(endpoint).build();

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (FeaturestoreOnlineServingServiceClient featurestoreOnlineServiceClient =
        FeaturestoreOnlineServingServiceClient.create(featurestoreOnlineServiceSettings)) {
      ReadFeatureValuesRequest readFeatureValuesRequest =
          ReadFeatureValuesRequest.newBuilder()
              .setEntityType(
                  EntityTypeName.of(project, location, featurestoreId, entityTypeId).toString())
              .setEntityId(entityId)
              .setFeatureSelector(
                  FeatureSelector.newBuilder()
                      .setIdMatcher(IdMatcher.newBuilder().addAllIds(featureSelectorIds)))
              .build();

      ReadFeatureValuesResponse readFeatureValuesResponse =
          featurestoreOnlineServiceClient.readFeatureValues(readFeatureValuesRequest);
      System.out.println("Read Feature Values Response" + readFeatureValuesResponse);
    }
  }
}

Node.js

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Node.js di Panduan memulai Vertex AI menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API Node.js Vertex AI.

Untuk melakukan autentikasi ke Vertex AI, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

/**
 * TODO(developer): Uncomment these variables before running the sample.\
 * (Not necessary if passing values as arguments)
 */

// const project = 'YOUR_PROJECT_ID';
// const featurestoreId = 'YOUR_FEATURESTORE_ID';
// const entityTypeId = 'YOUR_ENTITY_TYPE_ID';
// const entityId = 'ENTITY_ID_TO_SERVE';
// const location = 'YOUR_PROJECT_LOCATION';
// const apiEndpoint = 'YOUR_API_ENDPOINT';
// const timeout = <TIMEOUT_IN_MILLI_SECONDS>;

// Imports the Google Cloud Featurestore Service Client library
const {FeaturestoreOnlineServingServiceClient} =
  require('@google-cloud/aiplatform').v1;

// Specifies the location of the api endpoint
const clientOptions = {
  apiEndpoint: apiEndpoint,
};

// Instantiates a client
const featurestoreOnlineServingServiceClient =
  new FeaturestoreOnlineServingServiceClient(clientOptions);

async function readFeatureValues() {
  // Configure the entityType resource
  const entityType = `projects/${project}/locations/${location}/featurestores/${featurestoreId}/entityTypes/${entityTypeId}`;

  const featureSelector = {
    idMatcher: {
      ids: ['age', 'gender', 'liked_genres'],
    },
  };

  const request = {
    entityType: entityType,
    entityId: entityId,
    featureSelector: featureSelector,
  };

  // Read Feature Values Request
  const [response] =
    await featurestoreOnlineServingServiceClient.readFeatureValues(request, {
      timeout: Number(timeout),
    });

  console.log('Read feature values response');
  console.log('Raw response:');
  console.log(JSON.stringify(response, null, 2));
}
readFeatureValues();

Menyalurkan nilai dari beberapa entity

Menyalurkan nilai fitur dari satu atau beberapa entity untuk jenis entity tertentu. Untuk mendapatkan performa yang lebih baik, gunakan metode streamingReadFeatureValues, dan jangan mengirim permintaan paralel ke metode readFeatureValues.

REST

Untuk mendapatkan nilai fitur dari beberapa entity, kirim permintaan POST menggunakan, metode featurestores.entityTypes.streamingReadFeatureValues.

Contoh berikut mendapatkan nilai terbaru untuk dua fitur yang berbeda untuk dua entity yang berbeda. Perhatikan bahwa untuk kolom ids, Anda dapat menentukan ["*"], bukan ID fitur, untuk memilih semua fitur entity.

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • LOCATION_ID: Region tempat featurestore dibuat. Contoh, us-central1.
  • PROJECT_ID: Project ID Anda.
  • FEATURESTORE_ID: ID featurestore.
  • ENTITY_TYPE_ID: ID jenis entity.
  • ENTITY_ID: ID entity yang akan mendapatkan nilai fiturnya.
  • FEATURE_ID: ID fitur yang ingin diperoleh nilainya.

Metode HTTP dan URL:

POST http://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/featurestores/FEATURESTORE_ID/entityTypes/ENTITY_TYPE_ID:streamingReadFeatureValues

Isi JSON permintaan:

{
  "entityIds": ["ENTITY_ID_1", "ENTITY_ID_2"],
  "featureSelector": {
    "idMatcher": {
      "ids": ["FEATURE_ID_1", "FEATURE_ID_2"]
    }
  }
}

Untuk mengirim permintaan Anda, pilih salah satu opsi berikut:

curl

Simpan isi permintaan dalam file bernama request.json, dan jalankan perintah berikut:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"http://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/featurestores/FEATURESTORE_ID/entityTypes/ENTITY_TYPE_ID:streamingReadFeatureValues"

PowerShell

Simpan isi permintaan dalam file bernama request.json, dan jalankan perintah berikut:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "http://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/featurestores/FEATURESTORE_ID/entityTypes/ENTITY_TYPE_ID:streamingReadFeatureValues" | Select-Object -Expand Content

Anda akan melihat respons JSON seperti berikut:

[{
  "header": {
    "entityType": "projects/PROJECT_NUMBER/locations/LOCATION_ID/featurestores/FEATURESTORE_ID/entityTypes/ENTITY_TYPE_ID",
    "featureDescriptors": [
      {
        "id": "FEATURE_ID_1"
      },
      {
        "id": "FEATURE_ID_2"
      }
    ]
  }
},
{
  "entityView": {
    "entityId": "ENTITY_ID_1",
    "data": [
      {
        "value": {
          "VALUE_TYPE_1": "FEATURE_VALUE_A",
          "metadata": {
            "generateTime": "2019-10-28T15:38:10Z"
          }
        }
      },
      {
        "value": {
          "VALUE_TYPE_2": "FEATURE_VALUE_B",
          "metadata": {
            "generateTime": "2019-10-28T15:38:10Z"
          }
        }
      }
    ]
  }
},
{
  "entityView": {
    "entityId": "ENTITY_ID_2",
    "data": [
      {
        "value": {
          "VALUE_TYPE_1": "FEATURE_VALUE_C",
          "metadata": {
            "generateTime": "2019-10-28T21:21:37Z"
          }
        }
      },
      {
        "value": {
          "VALUE_TYPE_2": "FEATURE_VALUE_D",
          "metadata": {
            "generateTime": "2019-10-28T21:21:37Z"
          }
        }
      }
    ]
  }
}]

Bahasa tambahan

Anda dapat menginstal dan menggunakan library klien Vertex AI berikut untuk memanggil Vertex AI API. Library Klien Cloud memberikan pengalaman developer, yang dioptimalkan menggunakan konvensi dan, gaya alami dari setiap bahasa yang didukung.

Langkah selanjutnya