온라인 서빙

온라인 제공을 사용하면 짧은 지연 시간으로 소규모 항목 일괄 처리에 대해 특성 값을 제공할 수 있습니다. 각 요청에 대해 단일 항목 유형의 특성 값만 제공할 수 있습니다. Vertex AI Feature Store(기존)는 각 특성의 null이 아닌 최신 값만 반환합니다.

일반적으로 온라인 서빙을 사용하여 온라인 예측을 위해 배포된 모델에 특성 값을 제공합니다. 자전거 공유 회사에서 특정 사용자가 자전거를 대여할 기간을 예측하려는 경우를 예로 들겠습니다. 이 경우 사용자의 실시간 입력과 피처스토어의 데이터를 포함하여 온라인 예측을 수행할 수 있습니다. 이렇게 하면 실시간으로 리소스 할당을 결정할 수 있습니다.

Null 값

온라인 서빙 결과에서 특성의 최신 값이 null이면 Vertex AI Feature Store(기존)는 null이 아닌 최신 값을 반환합니다. 이전 값이 없으면 Vertex AI Feature Store(기존)는 null을 반환합니다.

시작하기 전에

호출을 수행하는 피처스토어에 온라인 스토리지가 있는지 확인합니다(노드 수가 0보다 커야 함). 그렇지 않으면 온라인 제공 요청이 오류를 반환합니다. 자세한 내용은 피처스토어 관리를 참조하세요.

단일 항목에서 값 제공

특정 항목 유형의 단일 항목에서 특성 값을 제공합니다.

REST

항목에서 특성 값을 가져오려면 featurestores.entityTypes.readFeatureValues 메서드를 사용하여 POST 요청을 전송하세요.

다음 샘플은 특정 항목에 대한 각기 다른 두 특성의 최신 값을 가져옵니다. ids 필드에 특성 ID 대신 ["*"]를 지정하여 항목의 모든 특성을 선택할 수 있습니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • LOCATION_ID: 피처스토어가 생성되는 리전. 예를 들면 us-central1입니다.
  • PROJECT_ID: 프로젝트 ID
  • FEATURESTORE_ID: 피처스토어의 ID
  • ENTITY_TYPE_ID: 항목 유형의 ID입니다.
  • ENTITY_ID: 특성 값을 가져올 항목의 ID입니다.
  • FEATURE_ID: 값을 가져올 특성의 ID입니다.

HTTP 메서드 및 URL:

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

JSON 요청 본문:

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

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

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

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

$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

다음과 비슷한 JSON 응답이 표시됩니다.

{
  "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

Python용 Vertex AI SDK를 설치하거나 업데이트하는 방법은 Python용 Vertex AI SDK 설치를 참조하세요. 자세한 내용은 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

Vertex AI 클라이언트 라이브러리는 Python용 Vertex AI SDK를 설치할 때 포함됩니다. Python용 Vertex AI SDK를 설치하는 방법은 Python용 Vertex AI SDK 설치를 참조하세요. 자세한 내용은 Python용 Vertex AI SDK API 참고 문서를 확인하세요.

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

이 샘플을 사용해 보기 전에 Vertex AI 빠른 시작: 클라이언트 라이브러리 사용Java 설정 안내를 따르세요. 자세한 내용은 Vertex AI Java API 참고 문서를 참조하세요.

Vertex AI에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


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

이 샘플을 사용해 보기 전에 Vertex AI 빠른 시작: 클라이언트 라이브러리 사용Node.js 설정 안내를 따르세요. 자세한 내용은 Vertex AI Node.js API 참고 문서를 참조하세요.

Vertex AI에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

/**
 * 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();

여러 항목에서 값 제공

특정 항목 유형에 대한 하나 이상의 항목의 특성 값을 제공합니다. 성능 향상을 위해 동시 요청을 readFeatureValues 메서드로 보내는 대신 streamingReadFeatureValues 메서드를 사용합니다.

REST

여러 항목에서 특성 값을 가져오려면 featurestores.entityTypes.streamingReadFeatureValues 메서드를 사용하여 POST 요청을 전송하세요.

다음 샘플은 두 가지 항목에 대한 두 가지 특성의 최신 값을 가져옵니다. ids 필드에 특성 ID 대신 ["*"]를 지정하여 항목의 모든 특성을 선택할 수 있습니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • LOCATION_ID: 피처스토어가 생성되는 리전. 예를 들면 us-central1입니다.
  • PROJECT_ID: 프로젝트 ID
  • FEATURESTORE_ID: 피처스토어의 ID
  • ENTITY_TYPE_ID: 항목 유형의 ID입니다.
  • ENTITY_ID: 특성 값을 가져올 항목의 ID입니다.
  • FEATURE_ID: 값을 가져올 특성의 ID입니다.

HTTP 메서드 및 URL:

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

JSON 요청 본문:

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

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

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

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

$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

다음과 비슷한 JSON 응답이 표시됩니다.

[{
  "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"
          }
        }
      }
    ]
  }
}]

추가 언어

다음 Vertex AI 클라이언트 라이브러리를 설치하고 사용하여 Vertex AI API를 호출할 수 있습니다. Cloud 클라이언트 라이브러리는 지원되는 각 언어의 고유한 규칙 및 스타일을 사용하여 최적화된 개발자 환경을 제공합니다.

다음 단계