מילוי בקשה באופן מיידי

מילוי בקשה באופן מיידי מאפשר להציג ערכי מאפיינים עבור קבוצות קטנות של ישויות עם זמן אחזור נמוך. בכל בקשה אפשר להציג ערכי תכונות רק מסוג ישות אחד. ‫Vertex AI Feature Store (Legacy) מחזיר רק את הערך האחרון שאינו null של כל מאפיין.

בדרך כלל, משתמשים בהצגה אונליין כדי להציג ערכי תכונות למודלים שנפרסו לצורך הסקת מסקנות אונליין. לדוגמה, נניח שיש לכם חברה להשכרת אופניים ואתם רוצים לחזות כמה זמן משתמש מסוים ישכור אופניים. אתם יכולים לכלול קלט בזמן אמת מהמשתמש ונתונים ממאגר פיצ'רים כדי לבצע היקש אונליין. כך תוכלו לקבוע את הקצאת המשאבים בזמן אמת.

ערכי Null

בתוצאות של מילוי בקשה באופן מיידי, אם הערך האחרון של תכונה הוא null,‏ Vertex AI Feature Store (מאמר שמתייחס לגרסה קודמת) מחזיר את הערך האחרון שאינו null. אם אין ערך קודם, Vertex AI Feature Store (Legacy) מחזיר null.

לפני שמתחילים

מוודאים שלמאגר הפיצ'רים שאליו מתבצעות הקריאות יש חנות וירטואלית (מספר הצמתים צריך להיות גדול מ-0). אחרת, בקשות למילוי בקשה באופן מיידי מחזירות שגיאה. מידע נוסף זמין במאמר בנושא ניהול מאגרי תכונות.

הצגת ערכים מישות אחת

הפונקציה מחזירה ערכי תכונות מישות אחת עבור סוג ישות מסוים.

REST

כדי לקבל ערכי תכונות מישות, שולחים בקשת POST באמצעות השיטה featurestores.entityTypes.readFeatureValues.

בדוגמה הבאה מוצגים הערכים האחרונים של שתי תכונות שונות של ישות מסוימת. שימו לב: בשדה ids אפשר לציין ["*"] במקום מזהי התכונות כדי לבחור את כל התכונות של הישות.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • LOCATION_ID: האזור שבו נוצר מאגר הפיצ'רים. לדוגמה, us-central1.
  • PROJECT_ID: מזהה הפרויקט.
  • FEATURESTORE_ID: מזהה של מאגר התכונות.
  • ENTITY_TYPE_ID: מזהה סוג הישות.
  • ENTITY_ID: המזהה של הישות שרוצים לקבל את ערכי התכונות שלה.
  • FEATURE_ID: המזהה של התכונה שרוצים לקבל את הערכים שלה.

ה-method של ה-HTTP וכתובת ה-URL:

POST https://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 \
"https://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 "https://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

במאמר התקנת Vertex AI SDK ל-Python מוסבר איך להתקין או לעדכן את Vertex AI SDK ל-Python. מידע נוסף מופיע ב מאמרי העזרה של 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

Java

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Javaהוראות ההגדרה במאמר Vertex AI quickstart using client libraries. מידע נוסף מופיע במאמרי העזרה של Vertex AI Java API.

כדי לבצע אימות ב-Vertex AI, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


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: https://cloud.google.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

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Node.jsהוראות ההגדרה במאמר Vertex AI quickstart using client libraries. מידע נוסף מופיע במאמרי העזרה של Vertex AI Node.js API.

כדי לבצע אימות ב-Vertex AI, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

הצגת ערכים מכמה ישויות

הפונקציה מחזירה ערכים של תכונות מישות אחת או יותר עבור סוג ישות מסוים. כדי לשפר את הביצועים, מומלץ להשתמש בשיטת streamingReadFeatureValues במקום לשלוח בקשות מקבילות לשיטת readFeatureValues.

REST

כדי לקבל ערכי תכונות מכמה ישויות, שולחים בקשת POST באמצעות השיטה featurestores.entityTypes.streamingReadFeatureValues.

בדוגמה הבאה מוצגים הערכים האחרונים של שני מאפיינים שונים של שתי ישויות שונות. שימו לב: בשדה ids אפשר לציין ["*"] במקום מזהי התכונות כדי לבחור את כל התכונות של הישות.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • LOCATION_ID: האזור שבו נוצר מאגר הפיצ'רים. לדוגמה, us-central1.
  • PROJECT_ID: .
  • FEATURESTORE_ID: מזהה של מאגר התכונות.
  • ENTITY_TYPE_ID: מזהה סוג הישות.
  • ENTITY_ID: המזהה של הישות שרוצים לקבל את ערכי התכונות שלה.
  • FEATURE_ID: המזהה של התכונה שרוצים לקבל את הערכים שלה.

ה-method של ה-HTTP וכתובת ה-URL:

POST https://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 \
"https://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 "https://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 מספקות חוויית פיתוח אופטימלית באמצעות שימוש במוסכמות ובסגנונות הטבעיים של כל שפה נתמכת.

המאמרים הבאים