추천 받기

이 페이지에서는 Google Cloud 콘솔을 사용해서 추천을 미리보고 API를 사용해서 추천 결과를 가져오는 방법을 보여줍니다. 추천을 앱에 통합하는 데 도움이 되는 API 호출 예시는 REST 탭을 참조하세요.

사용하는 절차는 원하는 추천 유형과 추천 앱이 연결된 데이터 스토어 유형에 따라 달라집니다.

미디어 추천 가져오기

콘솔

Google Cloud 콘솔을 사용하여 미디어 추천을 미리보려면 다음 단계를 수행합니다.

  1. Google Cloud 콘솔에서 Agent Builder 페이지로 이동합니다.

    Agent Builder

  2. 추천을 미리 보려는 앱의 이름을 클릭합니다.

  3. 구성 > 학습을 클릭합니다. 쿼리 준비확인이면 앱을 미리 볼 수 있습니다.

  4. 미리보기를 클릭합니다.

  5. 문서 ID 필드를 클릭합니다. 문서 ID 목록이 표시됩니다.

  6. 추천하려는 문서의 문서 ID를 클릭합니다. 또는 문서 ID 필드에 문서 ID를 입력합니다.

  7. 서빙 구성 선택을 클릭하고 미리보려는 서빙 구성을 선택합니다.

  8. 선택사항: 사용자 이벤트를 수집한 사용자의 방문자 ID(유사 사용자 ID라고도 함)를 입력합니다. 이 필드를 비워 두거나 존재하지 않는 방문자 ID를 입력하면 새 사용자로 추천 미리보기가 수행됩니다.

  9. 추천 가져오기를 클릭합니다. 추천 문서 목록이 표시됩니다.

  10. 문서를 클릭하여 문서 세부정보를 가져옵니다.

REST

API를 사용하여 미디어 추천을 가져오려면 servingConfigs.recommend 메서드를 사용합니다.

  1. 엔진 ID 및 서빙 구성 ID를 찾습니다. 엔진 ID와 서빙 구성 ID가 이미 있으면 2단계로 건너뜁니다.

    1. Google Cloud 콘솔에서 Agent Builder 페이지로 이동합니다.

      Agent Builder

    2. 앱 이름을 클릭합니다.

    3. 탐색 창에서 구성을 클릭합니다.

    4. 앱을 만들 때 자동으로 생성된 서빙 구성만 있으면 서빙 구성 ID와 엔진 ID가 동일합니다. 다음 단계로 건너뜁니다.

      서빙 구성 탭에 나열된 서빙 구성이 여러 개 있으면 추천을 가져오려는 서빙 구성을 찾습니다. 서빙 구성 ID는 ID 열에 있는 값입니다.

      앱을 만들 때 자동으로 생성된 서빙 구성을 삭제했고 현재 수동으로 만든 서빙 구성 하나만 있으면 미리보기 페이지로 이동하고 서빙 구성 선택을 클릭하여 서빙 구성 ID를 봅니다.

    5. 학습 탭을 클릭합니다. 엔진 ID는 앱 ID 행의 값입니다.

  2. 앱 미리보기가 준비되었는지 확인합니다.

    1. Google Cloud 콘솔에서 Agent Builder 페이지로 이동합니다.

      Agent Builder

    2. 앱 이름을 클릭합니다.

    3. 구성 > 학습을 클릭합니다. 쿼리 준비가 확인이면 앱을 미리 볼 수 있습니다.

  3. 추천 가져오기

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    -d  '{
            "validateOnly": false,
            "userEvent": {
                "eventType": "view-item",
                "userPseudoId": "USER_PSEUDO_ID",
                "documents": [{
                  "id": "DOCUMENT_ID"
                }],
            "filter": "FILTER_STRING"            }
        }' \
      "https://discoveryengine.googleapis.com/v1beta/projects/PROJECT_ID/locations/global/collections/default_collection/dataStores/DATA_STORE_ID/servingConfigs/SERVING_CONFIG_ID:recommend"
    • PROJECT_ID: 프로젝트의 ID입니다.
    • DATA_STORE_ID: 데이터 스토어의 ID입니다.
    • DOCUMENT_ID: 추천을 미리 보려는 문서의 ID입니다. 데이터를 처리할 때 이 문서에서 사용한 ID를 사용합니다.
    • USER_PSEUDO_ID: 사용자의 가명 식별자입니다. 이 필드에는 단일 기기의 방문자를 고유하게 식별하는 HTTP 쿠키를 사용할 수 있습니다. 여러 사용자에 대해 이 필드를 동일한 식별자로 설정하지 마세요. 이벤트 기록이 결합되고 모델 품질이 저하될 수 있습니다. 이 필드에는 개인 식별 정보(PII)를 포함하지 마세요.
    • SERVING_CONFIG_ID: 서빙 구성의 ID입니다.
    • FILTER: 선택사항. 필터 표현식 구문을 사용하여 지정된 필드 집합을 기준으로 필터링할 수 있는 텍스트 필드입니다. 기본값은 빈 문자열로, 필터가 적용되지 않음을 의미합니다. 자세한 내용은 추천 필터링을 참조하세요.

다음과 비슷한 결과가 표시됩니다.

{
  "results": [{"id": "sample-id-1"}, {"id": "sample-id-2"}],
  "attributionToken": "abc123"
}

각 검색 응답과 추천 그리고 검색 응답 및 추천에 대한 응답으로 사용자가 수행하는 작업에는 속성 토큰을 연결하는 것이 좋습니다. 이렇게 하면 시간 경과에 따라 검색 응답 및 추천 품질이 향상될 수 있습니다. 이렇게 하려면 검색 응답 또는 추천에 대해 웹사이트에 표시하는 각 링크의 URL에 attributionToken 값을 연결합니다. 예를 들면 https://www.example.com/54321/?rtoken=abc123입니다. 사용자가 이러한 링크 중 하나를 클릭할 때는 기록되는 사용자 이벤트에 attributionToken 값을 포함합니다.

정형 데이터가 있는 앱의 일반 추천 가져오기

콘솔

Google Cloud 콘솔을 사용해서 정형 앱의 일반 추천을 미리보려면 다음 단계를 수행합니다.

  1. Google Cloud 콘솔에서 Agent Builder 페이지로 이동합니다.

    Agent Builder

  2. 추천을 미리 보려는 앱의 이름을 클릭합니다.

  3. 미리보기를 클릭합니다.

  4. 문서 ID 필드를 클릭합니다. 문서 ID 목록이 표시됩니다.

  5. 추천하려는 문서의 문서 ID를 클릭합니다. 또는 문서 ID 필드에 문서 ID를 입력합니다.

  6. 추천 가져오기를 클릭합니다. 추천 문서 목록이 표시됩니다.

  7. 문서를 클릭하여 문서 세부정보를 가져옵니다.

REST

API를 사용해서 정형 데이터가 있는 앱에 대해 일반 추천을 가져오려면 servingConfigs.recommend 메서드를 사용합니다.

  1. 엔진 ID를 찾습니다. 이미 엔진 ID가 있으면 2단계로 건너뜁니다.

    1. Google Cloud 콘솔에서 Agent Builder 페이지로 이동합니다.

      Agent Builder

    2. 앱 이름을 클릭합니다.

    3. Google Cloud 콘솔의 URL에서 엔진 ID를 가져옵니다. engines//data 사이의 텍스트입니다. 예를 들어 URL에 다음이 포함된 경우

      gen-app-builder/engines/demo_1234567890123/data/records
      

      엔진 ID가 demo_1234567890123입니다.

  2. 데이터 스토어 ID를 찾습니다. 데이터 스토어 ID가 이미 있는 경우 다음 단계로 건너뜁니다.

    1. Google Cloud 콘솔에서 Agent Builder 페이지로 이동하고 탐색 메뉴에서 데이터 스토어를 클릭합니다.

      데이터 스토어 페이지로 이동

    2. 데이터 스토어 이름을 클릭합니다.

    3. 데이터 스토어의 데이터 페이지에서 데이터 스토어 ID를 가져옵니다.

  3. "servingState":"ACTIVE"가 반환될 때까지 GetEngine을 폴링하여 엔진 미리보기가 준비되었는지 확인합니다. 이 시점에서 엔진 미리보기가 준비됩니다.

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/engines/ENGINE_ID
    
    • PROJECT_ID: 프로젝트의 ID입니다.
    • ENGINE_ID: 엔진의 ID입니다.
  4. 추천 가져오기

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    -d '{
      "userEvent": { "eventType":"view-item", "userPseudoId":"USER_PSEUDO_ID", "documents":[{"id":"DOCUMENT_ID"}]}}' \
      "https://discoveryengine.googleapis.com/v1beta/projects/PROJECT_ID/locations/global/collections/default_collection/dataStores/DATA_STORE_ID/servingConfigs/SERVING_CONFIG_ID:recommend"
    
    • PROJECT_ID: 프로젝트의 ID입니다.
    • DATA_STORE_ID: 데이터 스토어의 ID입니다.
    • DOCUMENT_ID: 추천을 미리 보려는 문서의 ID입니다. 데이터를 처리할 때 이 문서에서 사용한 ID를 사용합니다.
    • USER_PSEUDO_ID: 사용자의 가명 식별자입니다. 이 필드에는 단일 기기의 방문자를 고유하게 식별하는 HTTP 쿠키를 사용할 수 있습니다. 여러 사용자에 대해 이 필드를 동일한 식별자로 설정하지 마세요. 이벤트 기록이 결합되고 모델 품질이 저하될 수 있습니다. 이 필드에는 개인 식별 정보(PII)를 포함하지 마세요.
    • SERVING_CONFIG_ID: 서빙 구성의 ID입니다. 서빙 구성 ID는 엔진 ID와 동일하므로 여기서는 엔진 ID를 사용하세요.

C#

자세한 내용은 Vertex AI Agent Builder C# API 참고 문서를 확인하세요.

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

using Google.Cloud.DiscoveryEngine.V1Beta;
using Google.Protobuf.WellKnownTypes;

public sealed partial class GeneratedRecommendationServiceClientSnippets
{
    /// <summary>Snippet for Recommend</summary>
    /// <remarks>
    /// This snippet has been automatically generated and should be regarded as a code template only.
    /// It will require modifications to work:
    /// - It may require correct/in-range values for request initialization.
    /// - It may require specifying regional endpoints when creating the service client as shown in
    ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
    /// </remarks>
    public void RecommendRequestObject()
    {
        // Create client
        RecommendationServiceClient recommendationServiceClient = RecommendationServiceClient.Create();
        // Initialize request argument(s)
        RecommendRequest request = new RecommendRequest
        {
            ServingConfigAsServingConfigName = ServingConfigName.FromProjectLocationDataStoreServingConfig("[PROJECT]", "[LOCATION]", "[DATA_STORE]", "[SERVING_CONFIG]"),
            UserEvent = new UserEvent(),
            PageSize = 0,
            Filter = "",
            ValidateOnly = false,
            Params = { { "", new Value() }, },
            UserLabels = { { "", "" }, },
        };
        // Make the request
        RecommendResponse response = recommendationServiceClient.Recommend(request);
    }
}

Go

자세한 내용은 Vertex AI Agent Builder Go API 참고 문서를 확인하세요.

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


package main

import (
	"context"

	discoveryengine "cloud.google.com/go/discoveryengine/apiv1beta"
	discoveryenginepb "cloud.google.com/go/discoveryengine/apiv1beta/discoveryenginepb"
)

func main() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := discoveryengine.NewRecommendationClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &discoveryenginepb.RecommendRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/discoveryengine/apiv1beta/discoveryenginepb#RecommendRequest.
	}
	resp, err := c.Recommend(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}
	// TODO: Use resp.
	_ = resp
}

Java

자세한 내용은 Vertex AI Agent Builder Java API 참고 문서를 확인하세요.

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

import com.google.cloud.discoveryengine.v1beta.RecommendRequest;
import com.google.cloud.discoveryengine.v1beta.RecommendResponse;
import com.google.cloud.discoveryengine.v1beta.RecommendationServiceClient;
import com.google.cloud.discoveryengine.v1beta.ServingConfigName;
import com.google.cloud.discoveryengine.v1beta.UserEvent;
import com.google.protobuf.Value;
import java.util.HashMap;

public class SyncRecommend {

  public static void main(String[] args) throws Exception {
    syncRecommend();
  }

  public static void syncRecommend() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (RecommendationServiceClient recommendationServiceClient =
        RecommendationServiceClient.create()) {
      RecommendRequest request =
          RecommendRequest.newBuilder()
              .setServingConfig(
                  ServingConfigName.ofProjectLocationDataStoreServingConfigName(
                          "[PROJECT]", "[LOCATION]", "[DATA_STORE]", "[SERVING_CONFIG]")
                      .toString())
              .setUserEvent(UserEvent.newBuilder().build())
              .setPageSize(883849137)
              .setFilter("filter-1274492040")
              .setValidateOnly(true)
              .putAllParams(new HashMap<String, Value>())
              .putAllUserLabels(new HashMap<String, String>())
              .build();
      RecommendResponse response = recommendationServiceClient.recommend(request);
    }
  }
}

Node.js

자세한 내용은 Vertex AI Agent Builder Node.js API 참고 문서를 확인하세요.

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

/**
 * This snippet has been automatically generated and should be regarded as a code template only.
 * It will require modifications to work.
 * It may require correct/in-range values for request initialization.
 * TODO(developer): Uncomment these variables before running the sample.
 */
/**
 *  Required. Full resource name of a
 *  ServingConfig google.cloud.discoveryengine.v1beta.ServingConfig:
 *  `projects/* /locations/global/collections/* /engines/* /servingConfigs/*`, or
 *  `projects/* /locations/global/collections/* /dataStores/* /servingConfigs/*`
 *  One default serving config is created along with your recommendation engine
 *  creation. The engine ID is used as the ID of the default serving
 *  config. For example, for Engine
 *  `projects/* /locations/global/collections/* /engines/my-engine`, you can use
 *  `projects/* /locations/global/collections/* /engines/my-engine/servingConfigs/my-engine`
 *  for your
 *  RecommendationService.Recommend google.cloud.discoveryengine.v1beta.RecommendationService.Recommend 
 *  requests.
 */
// const servingConfig = 'abc123'
/**
 *  Required. Context about the user, what they are looking at and what action
 *  they took to trigger the Recommend request. Note that this user event
 *  detail won't be ingested to userEvent logs. Thus, a separate userEvent
 *  write request is required for event logging.
 *  Don't set
 *  UserEvent.user_pseudo_id google.cloud.discoveryengine.v1beta.UserEvent.user_pseudo_id 
 *  or
 *  UserEvent.user_info.user_id google.cloud.discoveryengine.v1beta.UserInfo.user_id 
 *  to the same fixed ID for different users. If you are trying to receive
 *  non-personalized recommendations (not recommended; this can negatively
 *  impact model performance), instead set
 *  UserEvent.user_pseudo_id google.cloud.discoveryengine.v1beta.UserEvent.user_pseudo_id 
 *  to a random unique ID and leave
 *  UserEvent.user_info.user_id google.cloud.discoveryengine.v1beta.UserInfo.user_id 
 *  unset.
 */
// const userEvent = {}
/**
 *  Maximum number of results to return. Set this property
 *  to the number of recommendation results needed. If zero, the service
 *  chooses a reasonable default. The maximum allowed value is 100. Values
 *  above 100 are set to 100.
 */
// const pageSize = 1234
/**
 *  Filter for restricting recommendation results with a length limit of 5,000
 *  characters. Currently, only filter expressions on the `filter_tags`
 *  attribute is supported.
 *  Examples:
 *   * `(filter_tags: ANY("Red", "Blue") OR filter_tags: ANY("Hot", "Cold"))`
 *   * `(filter_tags: ANY("Red", "Blue")) AND NOT (filter_tags: ANY("Green"))`
 *  If `attributeFilteringSyntax` is set to true under the `params` field, then
 *  attribute-based expressions are expected instead of the above described
 *  tag-based syntax. Examples:
 *   * (launguage: ANY("en", "es")) AND NOT (categories: ANY("Movie"))
 *   * (available: true) AND
 *     (launguage: ANY("en", "es")) OR (categories: ANY("Movie"))
 *  If your filter blocks all results, the API returns generic
 *  (unfiltered) popular Documents. If you only want results strictly matching
 *  the filters, set `strictFiltering` to `true` in
 *  RecommendRequest.params google.cloud.discoveryengine.v1beta.RecommendRequest.params 
 *  to receive empty results instead.
 *  Note that the API never returns
 *  Document google.cloud.discoveryengine.v1beta.Document s with
 *  `storageStatus` as `EXPIRED` or `DELETED` regardless of filter choices.
 */
// const filter = 'abc123'
/**
 *  Use validate only mode for this recommendation query. If set to `true`, a
 *  fake model is used that returns arbitrary Document IDs.
 *  Note that the validate only mode should only be used for testing the API,
 *  or if the model is not ready.
 */
// const validateOnly = true
/**
 *  Additional domain specific parameters for the recommendations.
 *  Allowed values:
 *  * `returnDocument`: Boolean. If set to `true`, the associated Document
 *     object is returned in
 *     RecommendResponse.RecommendationResult.document google.cloud.discoveryengine.v1beta.RecommendResponse.RecommendationResult.document.
 *  * `returnScore`: Boolean. If set to true, the recommendation score
 *     corresponding to each returned Document is set in
 *     RecommendResponse.RecommendationResult.metadata google.cloud.discoveryengine.v1beta.RecommendResponse.RecommendationResult.metadata.
 *     The given score indicates the probability of a Document conversion given
 *     the user's context and history.
 *  * `strictFiltering`: Boolean. True by default. If set to `false`, the
 *  service
 *     returns generic (unfiltered) popular Documents instead of empty if
 *     your filter blocks all recommendation results.
 *  * `diversityLevel`: String. Default empty. If set to be non-empty, then
 *     it needs to be one of:
 *      *  `no-diversity`
 *      *  `low-diversity`
 *      *  `medium-diversity`
 *      *  `high-diversity`
 *      *  `auto-diversity`
 *     This gives request-level control and adjusts recommendation results
 *     based on Document category.
 *  * `attributeFilteringSyntax`: Boolean. False by default. If set to true,
 *     the `filter` field is interpreted according to the new,
 *     attribute-based syntax.
 */
// const params = [1,2,3,4]
/**
 *  The user labels applied to a resource must meet the following requirements:
 *  * Each resource can have multiple labels, up to a maximum of 64.
 *  * Each label must be a key-value pair.
 *  * Keys have a minimum length of 1 character and a maximum length of 63
 *    characters and cannot be empty. Values can be empty and have a maximum
 *    length of 63 characters.
 *  * Keys and values can contain only lowercase letters, numeric characters,
 *    underscores, and dashes. All characters must use UTF-8 encoding, and
 *    international characters are allowed.
 *  * The key portion of a label must be unique. However, you can use the same
 *    key with multiple resources.
 *  * Keys must start with a lowercase letter or international character.
 *  See Requirements for
 *  labels (https://cloud.google.com/resource-manager/docs/creating-managing-labels#requirements)
 *  for more details.
 */
// const userLabels = [1,2,3,4]

// Imports the Discoveryengine library
const {RecommendationServiceClient} = require('@google-cloud/discoveryengine').v1beta;

// Instantiates a client
const discoveryengineClient = new RecommendationServiceClient();

async function callRecommend() {
  // Construct request
  const request = {
    servingConfig,
    userEvent,
  };

  // Run request
  const response = await discoveryengineClient.recommend(request);
  console.log(response);
}

callRecommend();

PHP

자세한 내용은 Vertex AI Agent Builder PHP API 참고 문서를 확인하세요.

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

use Google\ApiCore\ApiException;
use Google\Cloud\DiscoveryEngine\V1beta\Client\RecommendationServiceClient;
use Google\Cloud\DiscoveryEngine\V1beta\RecommendRequest;
use Google\Cloud\DiscoveryEngine\V1beta\RecommendResponse;
use Google\Cloud\DiscoveryEngine\V1beta\UserEvent;

/**
 * Makes a recommendation, which requires a contextual user event.
 *
 * @param string $formattedServingConfig Full resource name of a
 *                                       [ServingConfig][google.cloud.discoveryengine.v1beta.ServingConfig]:
 *                                       `projects/&#42;/locations/global/collections/&#42;/engines/&#42;/servingConfigs/*`, or
 *                                       `projects/&#42;/locations/global/collections/&#42;/dataStores/&#42;/servingConfigs/*`
 *
 *                                       One default serving config is created along with your recommendation engine
 *                                       creation. The engine ID is used as the ID of the default serving
 *                                       config. For example, for Engine
 *                                       `projects/&#42;/locations/global/collections/&#42;/engines/my-engine`, you can use
 *                                       `projects/&#42;/locations/global/collections/&#42;/engines/my-engine/servingConfigs/my-engine`
 *                                       for your
 *                                       [RecommendationService.Recommend][google.cloud.discoveryengine.v1beta.RecommendationService.Recommend]
 *                                       requests. Please see
 *                                       {@see RecommendationServiceClient::servingConfigName()} for help formatting this field.
 * @param string $userEventEventType     User event type. Allowed values are:
 *
 *                                       Generic values:
 *
 *                                       * `search`: Search for Documents.
 *                                       * `view-item`: Detailed page view of a Document.
 *                                       * `view-item-list`: View of a panel or ordered list of Documents.
 *                                       * `view-home-page`: View of the home page.
 *                                       * `view-category-page`: View of a category page, e.g. Home > Men > Jeans
 *
 *                                       Retail-related values:
 *
 *                                       * `add-to-cart`: Add an item(s) to cart, e.g. in Retail online shopping
 *                                       * `purchase`: Purchase an item(s)
 *
 *                                       Media-related values:
 *
 *                                       * `media-play`: Start/resume watching a video, playing a song, etc.
 *                                       * `media-complete`: Finished or stopped midway through a video, song, etc.
 * @param string $userEventUserPseudoId  A unique identifier for tracking visitors.
 *
 *                                       For example, this could be implemented with an HTTP cookie, which should be
 *                                       able to uniquely identify a visitor on a single device. This unique
 *                                       identifier should not change if the visitor log in/out of the website.
 *
 *                                       Do not set the field to the same fixed ID for different users. This mixes
 *                                       the event history of those users together, which results in degraded model
 *                                       quality.
 *
 *                                       The field must be a UTF-8 encoded string with a length limit of 128
 *                                       characters. Otherwise, an `INVALID_ARGUMENT` error is returned.
 *
 *                                       The field should not contain PII or user-data. We recommend to use Google
 *                                       Analytics [Client
 *                                       ID](https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#clientId)
 *                                       for this field.
 */
function recommend_sample(
    string $formattedServingConfig,
    string $userEventEventType,
    string $userEventUserPseudoId
): void {
    // Create a client.
    $recommendationServiceClient = new RecommendationServiceClient();

    // Prepare the request message.
    $userEvent = (new UserEvent())
        ->setEventType($userEventEventType)
        ->setUserPseudoId($userEventUserPseudoId);
    $request = (new RecommendRequest())
        ->setServingConfig($formattedServingConfig)
        ->setUserEvent($userEvent);

    // Call the API and handle any network failures.
    try {
        /** @var RecommendResponse $response */
        $response = $recommendationServiceClient->recommend($request);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedServingConfig = RecommendationServiceClient::servingConfigName(
        '[PROJECT]',
        '[LOCATION]',
        '[DATA_STORE]',
        '[SERVING_CONFIG]'
    );
    $userEventEventType = '[EVENT_TYPE]';
    $userEventUserPseudoId = '[USER_PSEUDO_ID]';

    recommend_sample($formattedServingConfig, $userEventEventType, $userEventUserPseudoId);
}

Python

자세한 내용은 Vertex AI Agent Builder Python API 참고 문서를 확인하세요.

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

# This snippet has been automatically generated and should be regarded as a
# code template only.
# It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
#   client as shown in:
#   https://googleapis.dev/python/google-api-core/latest/client_options.html
from google.cloud import discoveryengine_v1beta


def sample_recommend():
    # Create a client
    client = discoveryengine_v1beta.RecommendationServiceClient()

    # Initialize request argument(s)
    user_event = discoveryengine_v1beta.UserEvent()
    user_event.event_type = "event_type_value"
    user_event.user_pseudo_id = "user_pseudo_id_value"

    request = discoveryengine_v1beta.RecommendRequest(
        serving_config="serving_config_value",
        user_event=user_event,
    )

    # Make the request
    response = client.recommend(request=request)

    # Handle the response
    print(response)

Ruby

자세한 내용은 Vertex AI Agent Builder Ruby API 참고 문서를 확인하세요.

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

require "google/cloud/discovery_engine/v1beta"

##
# Snippet for the recommend call in the RecommendationService service
#
# This snippet has been automatically generated and should be regarded as a code
# template only. It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
# client as shown in https://cloud.google.com/ruby/docs/reference.
#
# This is an auto-generated example demonstrating basic usage of
# Google::Cloud::DiscoveryEngine::V1beta::RecommendationService::Client#recommend.
#
def recommend
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Cloud::DiscoveryEngine::V1beta::RecommendationService::Client.new

  # Create a request. To set request fields, pass in keyword arguments.
  request = Google::Cloud::DiscoveryEngine::V1beta::RecommendRequest.new

  # Call the recommend method.
  result = client.recommend request

  # The returned object is of type Google::Cloud::DiscoveryEngine::V1beta::RecommendResponse.
  p result
end

비정형 데이터가 있는 앱의 일반 추천 가져오기

콘솔

Google Cloud 콘솔을 사용하여 일반 추천을 미리보려면 다음 단계를 수행합니다.

  1. Google Cloud 콘솔에서 Agent Builder 페이지로 이동합니다.

    Agent Builder

  2. 추천을 미리 보려는 앱의 이름을 클릭합니다.

  3. 미리보기를 클릭합니다.

  4. URI 필드를 클릭합니다. URI 목록이 표시됩니다.

  5. 추천하려는 문서의 URI를 클릭합니다. 또는 URI 필드에 URI를 입력합니다.

  6. 추천 가져오기를 클릭합니다. 추천 문서의 URI 목록이 표시됩니다.

  7. URI를 클릭하여 문서를 봅니다.

REST

API를 사용해서 비정형 데이터가 있는 앱의 일반 추천을 가져오려면 다음 단계를 수행합니다.

  1. 엔진 ID를 찾습니다. 이미 엔진 ID가 있으면 2단계로 건너뜁니다.

    1. Google Cloud 콘솔에서 Agent Builder 페이지로 이동합니다.

      Agent Builder

    2. 앱 이름을 클릭합니다.

    3. Google Cloud 콘솔의 URL에서 엔진 ID를 가져옵니다. engines//data 사이의 텍스트입니다. 예를 들어 URL에 다음이 포함된 경우

      gen-app-builder/engines/demo_1234567890123/data/records
      

      엔진 ID가 demo_1234567890123입니다.

  2. 데이터 스토어 ID를 찾습니다. 데이터 스토어 ID가 이미 있는 경우 다음 단계로 건너뜁니다.

    1. Google Cloud 콘솔에서 Agent Builder 페이지로 이동하고 탐색 메뉴에서 데이터 스토어를 클릭합니다.

      데이터 스토어 페이지로 이동

    2. 데이터 스토어 이름을 클릭합니다.

    3. 데이터 스토어의 데이터 페이지에서 데이터 스토어 ID를 가져옵니다.

  3. "servingState":"ACTIVE"가 반환될 때까지 GetEngine을 폴링하여 엔진 미리보기가 준비되었는지 확인합니다. 이 시점에서 엔진 미리보기가 준비됩니다.

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/engines/ENGINE_ID
    
    • PROJECT_ID: 프로젝트의 ID입니다.
    • ENGINE_ID: 엔진의 ID입니다.
  4. 추천 가져오기

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    -d '{
      "userEvent": { "eventType":"view-item", "userPseudoId":"USER_PSEUDO_ID", "documents":[{"id":"DOCUMENT_ID"}]}}' \
      "https://discoveryengine.googleapis.com/v1beta/projects/PROJECT_ID/locations/global/collections/default_collection/dataStores/DATA_STORE_ID/servingConfigs/SERVING_CONFIG_ID:recommend"
    
    • PROJECT_ID: 프로젝트의 ID입니다.
    • DATA_STORE_ID: 엔진과 연결된 데이터 스토어의 ID입니다.
    • DOCUMENT_ID: 추천을 미리 보려는 문서의 ID입니다. 데이터를 수집할 때 제공한 문서 ID를 사용합니다.
    • USER_PSEUDO_ID: 사용자의 가명 식별자입니다. 이 필드에는 단일 기기의 방문자를 고유하게 식별하는 HTTP 쿠키를 사용할 수 있습니다. 여러 사용자에 대해 이 필드를 동일한 식별자로 설정하지 마세요. 이벤트 기록이 결합되고 모델 품질이 저하될 수 있습니다. 이 필드에는 개인 식별 정보(PII)를 포함하지 마세요.
    • SERVING_CONFIG_ID: 서빙 구성의 ID입니다. 서빙 구성 ID는 엔진 ID와 동일하므로 여기서는 엔진 ID를 사용하세요.

C#

자세한 내용은 Vertex AI Agent Builder C# API 참고 문서를 확인하세요.

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

using Google.Cloud.DiscoveryEngine.V1Beta;
using Google.Protobuf.WellKnownTypes;

public sealed partial class GeneratedRecommendationServiceClientSnippets
{
    /// <summary>Snippet for Recommend</summary>
    /// <remarks>
    /// This snippet has been automatically generated and should be regarded as a code template only.
    /// It will require modifications to work:
    /// - It may require correct/in-range values for request initialization.
    /// - It may require specifying regional endpoints when creating the service client as shown in
    ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
    /// </remarks>
    public void RecommendRequestObject()
    {
        // Create client
        RecommendationServiceClient recommendationServiceClient = RecommendationServiceClient.Create();
        // Initialize request argument(s)
        RecommendRequest request = new RecommendRequest
        {
            ServingConfigAsServingConfigName = ServingConfigName.FromProjectLocationDataStoreServingConfig("[PROJECT]", "[LOCATION]", "[DATA_STORE]", "[SERVING_CONFIG]"),
            UserEvent = new UserEvent(),
            PageSize = 0,
            Filter = "",
            ValidateOnly = false,
            Params = { { "", new Value() }, },
            UserLabels = { { "", "" }, },
        };
        // Make the request
        RecommendResponse response = recommendationServiceClient.Recommend(request);
    }
}

Go

자세한 내용은 Vertex AI Agent Builder Go API 참고 문서를 확인하세요.

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


package main

import (
	"context"

	discoveryengine "cloud.google.com/go/discoveryengine/apiv1beta"
	discoveryenginepb "cloud.google.com/go/discoveryengine/apiv1beta/discoveryenginepb"
)

func main() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := discoveryengine.NewRecommendationClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &discoveryenginepb.RecommendRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/discoveryengine/apiv1beta/discoveryenginepb#RecommendRequest.
	}
	resp, err := c.Recommend(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}
	// TODO: Use resp.
	_ = resp
}

Java

자세한 내용은 Vertex AI Agent Builder Java API 참고 문서를 확인하세요.

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

import com.google.cloud.discoveryengine.v1beta.RecommendRequest;
import com.google.cloud.discoveryengine.v1beta.RecommendResponse;
import com.google.cloud.discoveryengine.v1beta.RecommendationServiceClient;
import com.google.cloud.discoveryengine.v1beta.ServingConfigName;
import com.google.cloud.discoveryengine.v1beta.UserEvent;
import com.google.protobuf.Value;
import java.util.HashMap;

public class SyncRecommend {

  public static void main(String[] args) throws Exception {
    syncRecommend();
  }

  public static void syncRecommend() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (RecommendationServiceClient recommendationServiceClient =
        RecommendationServiceClient.create()) {
      RecommendRequest request =
          RecommendRequest.newBuilder()
              .setServingConfig(
                  ServingConfigName.ofProjectLocationDataStoreServingConfigName(
                          "[PROJECT]", "[LOCATION]", "[DATA_STORE]", "[SERVING_CONFIG]")
                      .toString())
              .setUserEvent(UserEvent.newBuilder().build())
              .setPageSize(883849137)
              .setFilter("filter-1274492040")
              .setValidateOnly(true)
              .putAllParams(new HashMap<String, Value>())
              .putAllUserLabels(new HashMap<String, String>())
              .build();
      RecommendResponse response = recommendationServiceClient.recommend(request);
    }
  }
}

Node.js

자세한 내용은 Vertex AI Agent Builder Node.js API 참고 문서를 확인하세요.

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

/**
 * This snippet has been automatically generated and should be regarded as a code template only.
 * It will require modifications to work.
 * It may require correct/in-range values for request initialization.
 * TODO(developer): Uncomment these variables before running the sample.
 */
/**
 *  Required. Full resource name of a
 *  ServingConfig google.cloud.discoveryengine.v1beta.ServingConfig:
 *  `projects/* /locations/global/collections/* /engines/* /servingConfigs/*`, or
 *  `projects/* /locations/global/collections/* /dataStores/* /servingConfigs/*`
 *  One default serving config is created along with your recommendation engine
 *  creation. The engine ID is used as the ID of the default serving
 *  config. For example, for Engine
 *  `projects/* /locations/global/collections/* /engines/my-engine`, you can use
 *  `projects/* /locations/global/collections/* /engines/my-engine/servingConfigs/my-engine`
 *  for your
 *  RecommendationService.Recommend google.cloud.discoveryengine.v1beta.RecommendationService.Recommend 
 *  requests.
 */
// const servingConfig = 'abc123'
/**
 *  Required. Context about the user, what they are looking at and what action
 *  they took to trigger the Recommend request. Note that this user event
 *  detail won't be ingested to userEvent logs. Thus, a separate userEvent
 *  write request is required for event logging.
 *  Don't set
 *  UserEvent.user_pseudo_id google.cloud.discoveryengine.v1beta.UserEvent.user_pseudo_id 
 *  or
 *  UserEvent.user_info.user_id google.cloud.discoveryengine.v1beta.UserInfo.user_id 
 *  to the same fixed ID for different users. If you are trying to receive
 *  non-personalized recommendations (not recommended; this can negatively
 *  impact model performance), instead set
 *  UserEvent.user_pseudo_id google.cloud.discoveryengine.v1beta.UserEvent.user_pseudo_id 
 *  to a random unique ID and leave
 *  UserEvent.user_info.user_id google.cloud.discoveryengine.v1beta.UserInfo.user_id 
 *  unset.
 */
// const userEvent = {}
/**
 *  Maximum number of results to return. Set this property
 *  to the number of recommendation results needed. If zero, the service
 *  chooses a reasonable default. The maximum allowed value is 100. Values
 *  above 100 are set to 100.
 */
// const pageSize = 1234
/**
 *  Filter for restricting recommendation results with a length limit of 5,000
 *  characters. Currently, only filter expressions on the `filter_tags`
 *  attribute is supported.
 *  Examples:
 *   * `(filter_tags: ANY("Red", "Blue") OR filter_tags: ANY("Hot", "Cold"))`
 *   * `(filter_tags: ANY("Red", "Blue")) AND NOT (filter_tags: ANY("Green"))`
 *  If `attributeFilteringSyntax` is set to true under the `params` field, then
 *  attribute-based expressions are expected instead of the above described
 *  tag-based syntax. Examples:
 *   * (launguage: ANY("en", "es")) AND NOT (categories: ANY("Movie"))
 *   * (available: true) AND
 *     (launguage: ANY("en", "es")) OR (categories: ANY("Movie"))
 *  If your filter blocks all results, the API returns generic
 *  (unfiltered) popular Documents. If you only want results strictly matching
 *  the filters, set `strictFiltering` to `true` in
 *  RecommendRequest.params google.cloud.discoveryengine.v1beta.RecommendRequest.params 
 *  to receive empty results instead.
 *  Note that the API never returns
 *  Document google.cloud.discoveryengine.v1beta.Document s with
 *  `storageStatus` as `EXPIRED` or `DELETED` regardless of filter choices.
 */
// const filter = 'abc123'
/**
 *  Use validate only mode for this recommendation query. If set to `true`, a
 *  fake model is used that returns arbitrary Document IDs.
 *  Note that the validate only mode should only be used for testing the API,
 *  or if the model is not ready.
 */
// const validateOnly = true
/**
 *  Additional domain specific parameters for the recommendations.
 *  Allowed values:
 *  * `returnDocument`: Boolean. If set to `true`, the associated Document
 *     object is returned in
 *     RecommendResponse.RecommendationResult.document google.cloud.discoveryengine.v1beta.RecommendResponse.RecommendationResult.document.
 *  * `returnScore`: Boolean. If set to true, the recommendation score
 *     corresponding to each returned Document is set in
 *     RecommendResponse.RecommendationResult.metadata google.cloud.discoveryengine.v1beta.RecommendResponse.RecommendationResult.metadata.
 *     The given score indicates the probability of a Document conversion given
 *     the user's context and history.
 *  * `strictFiltering`: Boolean. True by default. If set to `false`, the
 *  service
 *     returns generic (unfiltered) popular Documents instead of empty if
 *     your filter blocks all recommendation results.
 *  * `diversityLevel`: String. Default empty. If set to be non-empty, then
 *     it needs to be one of:
 *      *  `no-diversity`
 *      *  `low-diversity`
 *      *  `medium-diversity`
 *      *  `high-diversity`
 *      *  `auto-diversity`
 *     This gives request-level control and adjusts recommendation results
 *     based on Document category.
 *  * `attributeFilteringSyntax`: Boolean. False by default. If set to true,
 *     the `filter` field is interpreted according to the new,
 *     attribute-based syntax.
 */
// const params = [1,2,3,4]
/**
 *  The user labels applied to a resource must meet the following requirements:
 *  * Each resource can have multiple labels, up to a maximum of 64.
 *  * Each label must be a key-value pair.
 *  * Keys have a minimum length of 1 character and a maximum length of 63
 *    characters and cannot be empty. Values can be empty and have a maximum
 *    length of 63 characters.
 *  * Keys and values can contain only lowercase letters, numeric characters,
 *    underscores, and dashes. All characters must use UTF-8 encoding, and
 *    international characters are allowed.
 *  * The key portion of a label must be unique. However, you can use the same
 *    key with multiple resources.
 *  * Keys must start with a lowercase letter or international character.
 *  See Requirements for
 *  labels (https://cloud.google.com/resource-manager/docs/creating-managing-labels#requirements)
 *  for more details.
 */
// const userLabels = [1,2,3,4]

// Imports the Discoveryengine library
const {RecommendationServiceClient} = require('@google-cloud/discoveryengine').v1beta;

// Instantiates a client
const discoveryengineClient = new RecommendationServiceClient();

async function callRecommend() {
  // Construct request
  const request = {
    servingConfig,
    userEvent,
  };

  // Run request
  const response = await discoveryengineClient.recommend(request);
  console.log(response);
}

callRecommend();

PHP

자세한 내용은 Vertex AI Agent Builder PHP API 참고 문서를 확인하세요.

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

use Google\ApiCore\ApiException;
use Google\Cloud\DiscoveryEngine\V1beta\Client\RecommendationServiceClient;
use Google\Cloud\DiscoveryEngine\V1beta\RecommendRequest;
use Google\Cloud\DiscoveryEngine\V1beta\RecommendResponse;
use Google\Cloud\DiscoveryEngine\V1beta\UserEvent;

/**
 * Makes a recommendation, which requires a contextual user event.
 *
 * @param string $formattedServingConfig Full resource name of a
 *                                       [ServingConfig][google.cloud.discoveryengine.v1beta.ServingConfig]:
 *                                       `projects/&#42;/locations/global/collections/&#42;/engines/&#42;/servingConfigs/*`, or
 *                                       `projects/&#42;/locations/global/collections/&#42;/dataStores/&#42;/servingConfigs/*`
 *
 *                                       One default serving config is created along with your recommendation engine
 *                                       creation. The engine ID is used as the ID of the default serving
 *                                       config. For example, for Engine
 *                                       `projects/&#42;/locations/global/collections/&#42;/engines/my-engine`, you can use
 *                                       `projects/&#42;/locations/global/collections/&#42;/engines/my-engine/servingConfigs/my-engine`
 *                                       for your
 *                                       [RecommendationService.Recommend][google.cloud.discoveryengine.v1beta.RecommendationService.Recommend]
 *                                       requests. Please see
 *                                       {@see RecommendationServiceClient::servingConfigName()} for help formatting this field.
 * @param string $userEventEventType     User event type. Allowed values are:
 *
 *                                       Generic values:
 *
 *                                       * `search`: Search for Documents.
 *                                       * `view-item`: Detailed page view of a Document.
 *                                       * `view-item-list`: View of a panel or ordered list of Documents.
 *                                       * `view-home-page`: View of the home page.
 *                                       * `view-category-page`: View of a category page, e.g. Home > Men > Jeans
 *
 *                                       Retail-related values:
 *
 *                                       * `add-to-cart`: Add an item(s) to cart, e.g. in Retail online shopping
 *                                       * `purchase`: Purchase an item(s)
 *
 *                                       Media-related values:
 *
 *                                       * `media-play`: Start/resume watching a video, playing a song, etc.
 *                                       * `media-complete`: Finished or stopped midway through a video, song, etc.
 * @param string $userEventUserPseudoId  A unique identifier for tracking visitors.
 *
 *                                       For example, this could be implemented with an HTTP cookie, which should be
 *                                       able to uniquely identify a visitor on a single device. This unique
 *                                       identifier should not change if the visitor log in/out of the website.
 *
 *                                       Do not set the field to the same fixed ID for different users. This mixes
 *                                       the event history of those users together, which results in degraded model
 *                                       quality.
 *
 *                                       The field must be a UTF-8 encoded string with a length limit of 128
 *                                       characters. Otherwise, an `INVALID_ARGUMENT` error is returned.
 *
 *                                       The field should not contain PII or user-data. We recommend to use Google
 *                                       Analytics [Client
 *                                       ID](https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#clientId)
 *                                       for this field.
 */
function recommend_sample(
    string $formattedServingConfig,
    string $userEventEventType,
    string $userEventUserPseudoId
): void {
    // Create a client.
    $recommendationServiceClient = new RecommendationServiceClient();

    // Prepare the request message.
    $userEvent = (new UserEvent())
        ->setEventType($userEventEventType)
        ->setUserPseudoId($userEventUserPseudoId);
    $request = (new RecommendRequest())
        ->setServingConfig($formattedServingConfig)
        ->setUserEvent($userEvent);

    // Call the API and handle any network failures.
    try {
        /** @var RecommendResponse $response */
        $response = $recommendationServiceClient->recommend($request);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedServingConfig = RecommendationServiceClient::servingConfigName(
        '[PROJECT]',
        '[LOCATION]',
        '[DATA_STORE]',
        '[SERVING_CONFIG]'
    );
    $userEventEventType = '[EVENT_TYPE]';
    $userEventUserPseudoId = '[USER_PSEUDO_ID]';

    recommend_sample($formattedServingConfig, $userEventEventType, $userEventUserPseudoId);
}

Python

자세한 내용은 Vertex AI Agent Builder Python API 참고 문서를 확인하세요.

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

# This snippet has been automatically generated and should be regarded as a
# code template only.
# It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
#   client as shown in:
#   https://googleapis.dev/python/google-api-core/latest/client_options.html
from google.cloud import discoveryengine_v1beta


def sample_recommend():
    # Create a client
    client = discoveryengine_v1beta.RecommendationServiceClient()

    # Initialize request argument(s)
    user_event = discoveryengine_v1beta.UserEvent()
    user_event.event_type = "event_type_value"
    user_event.user_pseudo_id = "user_pseudo_id_value"

    request = discoveryengine_v1beta.RecommendRequest(
        serving_config="serving_config_value",
        user_event=user_event,
    )

    # Make the request
    response = client.recommend(request=request)

    # Handle the response
    print(response)

Ruby

자세한 내용은 Vertex AI Agent Builder Ruby API 참고 문서를 확인하세요.

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

require "google/cloud/discovery_engine/v1beta"

##
# Snippet for the recommend call in the RecommendationService service
#
# This snippet has been automatically generated and should be regarded as a code
# template only. It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
# client as shown in https://cloud.google.com/ruby/docs/reference.
#
# This is an auto-generated example demonstrating basic usage of
# Google::Cloud::DiscoveryEngine::V1beta::RecommendationService::Client#recommend.
#
def recommend
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Cloud::DiscoveryEngine::V1beta::RecommendationService::Client.new

  # Create a request. To set request fields, pass in keyword arguments.
  request = Google::Cloud::DiscoveryEngine::V1beta::RecommendRequest.new

  # Call the recommend method.
  result = client.recommend request

  # The returned object is of type Google::Cloud::DiscoveryEngine::V1beta::RecommendResponse.
  p result
end

웹사이트 데이터가 있는 앱의 일반 추천 가져오기

콘솔

Google Cloud 콘솔을 사용해서 웹사이트 앱의 일반 추천을 미리보려면 다음 단계를 수행합니다.

  1. Google Cloud 콘솔에서 Agent Builder 페이지로 이동합니다.

    Agent Builder

  2. 추천을 미리 보려는 앱의 이름을 클릭합니다.

  3. 탐색 메뉴에서 미리보기를 클릭합니다.

  4. URI 필드를 클릭합니다. 웹사이트의 URL 목록이 표시됩니다.

  5. 추천하려는 웹페이지의 URL을 클릭합니다. 또는 URL 필드에 웹사이트의 URL을 입력합니다.

  6. 추천 가져오기를 클릭합니다. 추천 웹페이지의 URL 목록이 표시됩니다.

  7. URL을 클릭하여 웹페이지를 봅니다.

REST

API를 사용해서 웹사이트 데이터가 있는 앱에 대해 일반 추천을 가져오려면 servingConfigs.recommend 메서드를 사용합니다.

  1. 엔진 ID를 찾습니다. 이미 엔진 ID가 있으면 2단계로 건너뜁니다.

    1. Google Cloud 콘솔에서 Agent Builder 페이지로 이동합니다.

      Agent Builder

    2. 앱 이름을 클릭합니다.

    3. Google Cloud 콘솔의 URL에서 엔진 ID를 가져옵니다. engines//data 사이의 텍스트입니다. 예를 들어 URL에 다음이 포함된 경우

      gen-app-builder/engines/demo_1234567890123/data/records
      

      엔진 ID가 demo_1234567890123입니다.

  2. 데이터 스토어 ID를 찾습니다. 데이터 스토어 ID가 이미 있는 경우 다음 단계로 건너뜁니다.

    1. Google Cloud 콘솔에서 Agent Builder 페이지로 이동하고 탐색 메뉴에서 데이터 스토어를 클릭합니다.

      데이터 스토어 페이지로 이동

    2. 데이터 스토어 이름을 클릭합니다.

    3. 데이터 스토어의 데이터 페이지에서 데이터 스토어 ID를 가져옵니다.

  3. "servingState":"ACTIVE"가 반환될 때까지 GetEngine을 폴링하여 엔진 미리보기가 준비되었는지 확인합니다. 이 시점에서 엔진 미리보기가 준비됩니다.

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/engines/ENGINE_ID
    
    • PROJECT_ID: 프로젝트의 ID입니다.
    • ENGINE_ID: 엔진의 ID입니다.
  4. 추천 가져오기

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    -d '{
      "userEvent": { "eventType":"view-item", "userPseudoId":"USER_PSEUDO_ID", "documents":[{"uri":"WEBSITE_URL"}]}}' \
      "https://discoveryengine.googleapis.com/v1beta/projects/PROJECT_ID/locations/global/collections/default_collection/dataStores/DATA_STORE_ID/servingConfigs/SERVING_CONFIG_ID:recommend"
    
    • PROJECT_ID: 프로젝트의 ID입니다.
    • DATA_STORE_ID: 데이터 스토어의 ID입니다.
    • WEBSITE_URL: 추천을 미리 보려는 웹사이트의 URL입니다.
    • USER_PSEUDO_ID: 사용자의 가명 식별자입니다. 이 필드에는 단일 기기의 방문자를 고유하게 식별하는 HTTP 쿠키를 사용할 수 있습니다. 여러 사용자에 대해 이 필드를 동일한 식별자로 설정하지 마세요. 이벤트 기록이 결합되고 모델 품질이 저하될 수 있습니다. 이 필드에는 개인 식별 정보(PII)를 포함하지 마세요.
    • SERVING_CONFIG_ID: 서빙 구성의 ID입니다. 서빙 구성 ID는 엔진 ID와 동일하므로 여기서는 엔진 ID를 사용하세요.

C#

자세한 내용은 Vertex AI Agent Builder C# API 참고 문서를 확인하세요.

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

using Google.Cloud.DiscoveryEngine.V1Beta;
using Google.Protobuf.WellKnownTypes;

public sealed partial class GeneratedRecommendationServiceClientSnippets
{
    /// <summary>Snippet for Recommend</summary>
    /// <remarks>
    /// This snippet has been automatically generated and should be regarded as a code template only.
    /// It will require modifications to work:
    /// - It may require correct/in-range values for request initialization.
    /// - It may require specifying regional endpoints when creating the service client as shown in
    ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
    /// </remarks>
    public void RecommendRequestObject()
    {
        // Create client
        RecommendationServiceClient recommendationServiceClient = RecommendationServiceClient.Create();
        // Initialize request argument(s)
        RecommendRequest request = new RecommendRequest
        {
            ServingConfigAsServingConfigName = ServingConfigName.FromProjectLocationDataStoreServingConfig("[PROJECT]", "[LOCATION]", "[DATA_STORE]", "[SERVING_CONFIG]"),
            UserEvent = new UserEvent(),
            PageSize = 0,
            Filter = "",
            ValidateOnly = false,
            Params = { { "", new Value() }, },
            UserLabels = { { "", "" }, },
        };
        // Make the request
        RecommendResponse response = recommendationServiceClient.Recommend(request);
    }
}

Go

자세한 내용은 Vertex AI Agent Builder Go API 참고 문서를 확인하세요.

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


package main

import (
	"context"

	discoveryengine "cloud.google.com/go/discoveryengine/apiv1beta"
	discoveryenginepb "cloud.google.com/go/discoveryengine/apiv1beta/discoveryenginepb"
)

func main() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := discoveryengine.NewRecommendationClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &discoveryenginepb.RecommendRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/discoveryengine/apiv1beta/discoveryenginepb#RecommendRequest.
	}
	resp, err := c.Recommend(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}
	// TODO: Use resp.
	_ = resp
}

Java

자세한 내용은 Vertex AI Agent Builder Java API 참고 문서를 확인하세요.

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

import com.google.cloud.discoveryengine.v1beta.RecommendRequest;
import com.google.cloud.discoveryengine.v1beta.RecommendResponse;
import com.google.cloud.discoveryengine.v1beta.RecommendationServiceClient;
import com.google.cloud.discoveryengine.v1beta.ServingConfigName;
import com.google.cloud.discoveryengine.v1beta.UserEvent;
import com.google.protobuf.Value;
import java.util.HashMap;

public class SyncRecommend {

  public static void main(String[] args) throws Exception {
    syncRecommend();
  }

  public static void syncRecommend() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (RecommendationServiceClient recommendationServiceClient =
        RecommendationServiceClient.create()) {
      RecommendRequest request =
          RecommendRequest.newBuilder()
              .setServingConfig(
                  ServingConfigName.ofProjectLocationDataStoreServingConfigName(
                          "[PROJECT]", "[LOCATION]", "[DATA_STORE]", "[SERVING_CONFIG]")
                      .toString())
              .setUserEvent(UserEvent.newBuilder().build())
              .setPageSize(883849137)
              .setFilter("filter-1274492040")
              .setValidateOnly(true)
              .putAllParams(new HashMap<String, Value>())
              .putAllUserLabels(new HashMap<String, String>())
              .build();
      RecommendResponse response = recommendationServiceClient.recommend(request);
    }
  }
}

Node.js

자세한 내용은 Vertex AI Agent Builder Node.js API 참고 문서를 확인하세요.

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

/**
 * This snippet has been automatically generated and should be regarded as a code template only.
 * It will require modifications to work.
 * It may require correct/in-range values for request initialization.
 * TODO(developer): Uncomment these variables before running the sample.
 */
/**
 *  Required. Full resource name of a
 *  ServingConfig google.cloud.discoveryengine.v1beta.ServingConfig:
 *  `projects/* /locations/global/collections/* /engines/* /servingConfigs/*`, or
 *  `projects/* /locations/global/collections/* /dataStores/* /servingConfigs/*`
 *  One default serving config is created along with your recommendation engine
 *  creation. The engine ID is used as the ID of the default serving
 *  config. For example, for Engine
 *  `projects/* /locations/global/collections/* /engines/my-engine`, you can use
 *  `projects/* /locations/global/collections/* /engines/my-engine/servingConfigs/my-engine`
 *  for your
 *  RecommendationService.Recommend google.cloud.discoveryengine.v1beta.RecommendationService.Recommend 
 *  requests.
 */
// const servingConfig = 'abc123'
/**
 *  Required. Context about the user, what they are looking at and what action
 *  they took to trigger the Recommend request. Note that this user event
 *  detail won't be ingested to userEvent logs. Thus, a separate userEvent
 *  write request is required for event logging.
 *  Don't set
 *  UserEvent.user_pseudo_id google.cloud.discoveryengine.v1beta.UserEvent.user_pseudo_id 
 *  or
 *  UserEvent.user_info.user_id google.cloud.discoveryengine.v1beta.UserInfo.user_id 
 *  to the same fixed ID for different users. If you are trying to receive
 *  non-personalized recommendations (not recommended; this can negatively
 *  impact model performance), instead set
 *  UserEvent.user_pseudo_id google.cloud.discoveryengine.v1beta.UserEvent.user_pseudo_id 
 *  to a random unique ID and leave
 *  UserEvent.user_info.user_id google.cloud.discoveryengine.v1beta.UserInfo.user_id 
 *  unset.
 */
// const userEvent = {}
/**
 *  Maximum number of results to return. Set this property
 *  to the number of recommendation results needed. If zero, the service
 *  chooses a reasonable default. The maximum allowed value is 100. Values
 *  above 100 are set to 100.
 */
// const pageSize = 1234
/**
 *  Filter for restricting recommendation results with a length limit of 5,000
 *  characters. Currently, only filter expressions on the `filter_tags`
 *  attribute is supported.
 *  Examples:
 *   * `(filter_tags: ANY("Red", "Blue") OR filter_tags: ANY("Hot", "Cold"))`
 *   * `(filter_tags: ANY("Red", "Blue")) AND NOT (filter_tags: ANY("Green"))`
 *  If `attributeFilteringSyntax` is set to true under the `params` field, then
 *  attribute-based expressions are expected instead of the above described
 *  tag-based syntax. Examples:
 *   * (launguage: ANY("en", "es")) AND NOT (categories: ANY("Movie"))
 *   * (available: true) AND
 *     (launguage: ANY("en", "es")) OR (categories: ANY("Movie"))
 *  If your filter blocks all results, the API returns generic
 *  (unfiltered) popular Documents. If you only want results strictly matching
 *  the filters, set `strictFiltering` to `true` in
 *  RecommendRequest.params google.cloud.discoveryengine.v1beta.RecommendRequest.params 
 *  to receive empty results instead.
 *  Note that the API never returns
 *  Document google.cloud.discoveryengine.v1beta.Document s with
 *  `storageStatus` as `EXPIRED` or `DELETED` regardless of filter choices.
 */
// const filter = 'abc123'
/**
 *  Use validate only mode for this recommendation query. If set to `true`, a
 *  fake model is used that returns arbitrary Document IDs.
 *  Note that the validate only mode should only be used for testing the API,
 *  or if the model is not ready.
 */
// const validateOnly = true
/**
 *  Additional domain specific parameters for the recommendations.
 *  Allowed values:
 *  * `returnDocument`: Boolean. If set to `true`, the associated Document
 *     object is returned in
 *     RecommendResponse.RecommendationResult.document google.cloud.discoveryengine.v1beta.RecommendResponse.RecommendationResult.document.
 *  * `returnScore`: Boolean. If set to true, the recommendation score
 *     corresponding to each returned Document is set in
 *     RecommendResponse.RecommendationResult.metadata google.cloud.discoveryengine.v1beta.RecommendResponse.RecommendationResult.metadata.
 *     The given score indicates the probability of a Document conversion given
 *     the user's context and history.
 *  * `strictFiltering`: Boolean. True by default. If set to `false`, the
 *  service
 *     returns generic (unfiltered) popular Documents instead of empty if
 *     your filter blocks all recommendation results.
 *  * `diversityLevel`: String. Default empty. If set to be non-empty, then
 *     it needs to be one of:
 *      *  `no-diversity`
 *      *  `low-diversity`
 *      *  `medium-diversity`
 *      *  `high-diversity`
 *      *  `auto-diversity`
 *     This gives request-level control and adjusts recommendation results
 *     based on Document category.
 *  * `attributeFilteringSyntax`: Boolean. False by default. If set to true,
 *     the `filter` field is interpreted according to the new,
 *     attribute-based syntax.
 */
// const params = [1,2,3,4]
/**
 *  The user labels applied to a resource must meet the following requirements:
 *  * Each resource can have multiple labels, up to a maximum of 64.
 *  * Each label must be a key-value pair.
 *  * Keys have a minimum length of 1 character and a maximum length of 63
 *    characters and cannot be empty. Values can be empty and have a maximum
 *    length of 63 characters.
 *  * Keys and values can contain only lowercase letters, numeric characters,
 *    underscores, and dashes. All characters must use UTF-8 encoding, and
 *    international characters are allowed.
 *  * The key portion of a label must be unique. However, you can use the same
 *    key with multiple resources.
 *  * Keys must start with a lowercase letter or international character.
 *  See Requirements for
 *  labels (https://cloud.google.com/resource-manager/docs/creating-managing-labels#requirements)
 *  for more details.
 */
// const userLabels = [1,2,3,4]

// Imports the Discoveryengine library
const {RecommendationServiceClient} = require('@google-cloud/discoveryengine').v1beta;

// Instantiates a client
const discoveryengineClient = new RecommendationServiceClient();

async function callRecommend() {
  // Construct request
  const request = {
    servingConfig,
    userEvent,
  };

  // Run request
  const response = await discoveryengineClient.recommend(request);
  console.log(response);
}

callRecommend();

PHP

자세한 내용은 Vertex AI Agent Builder PHP API 참고 문서를 확인하세요.

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

use Google\ApiCore\ApiException;
use Google\Cloud\DiscoveryEngine\V1beta\Client\RecommendationServiceClient;
use Google\Cloud\DiscoveryEngine\V1beta\RecommendRequest;
use Google\Cloud\DiscoveryEngine\V1beta\RecommendResponse;
use Google\Cloud\DiscoveryEngine\V1beta\UserEvent;

/**
 * Makes a recommendation, which requires a contextual user event.
 *
 * @param string $formattedServingConfig Full resource name of a
 *                                       [ServingConfig][google.cloud.discoveryengine.v1beta.ServingConfig]:
 *                                       `projects/&#42;/locations/global/collections/&#42;/engines/&#42;/servingConfigs/*`, or
 *                                       `projects/&#42;/locations/global/collections/&#42;/dataStores/&#42;/servingConfigs/*`
 *
 *                                       One default serving config is created along with your recommendation engine
 *                                       creation. The engine ID is used as the ID of the default serving
 *                                       config. For example, for Engine
 *                                       `projects/&#42;/locations/global/collections/&#42;/engines/my-engine`, you can use
 *                                       `projects/&#42;/locations/global/collections/&#42;/engines/my-engine/servingConfigs/my-engine`
 *                                       for your
 *                                       [RecommendationService.Recommend][google.cloud.discoveryengine.v1beta.RecommendationService.Recommend]
 *                                       requests. Please see
 *                                       {@see RecommendationServiceClient::servingConfigName()} for help formatting this field.
 * @param string $userEventEventType     User event type. Allowed values are:
 *
 *                                       Generic values:
 *
 *                                       * `search`: Search for Documents.
 *                                       * `view-item`: Detailed page view of a Document.
 *                                       * `view-item-list`: View of a panel or ordered list of Documents.
 *                                       * `view-home-page`: View of the home page.
 *                                       * `view-category-page`: View of a category page, e.g. Home > Men > Jeans
 *
 *                                       Retail-related values:
 *
 *                                       * `add-to-cart`: Add an item(s) to cart, e.g. in Retail online shopping
 *                                       * `purchase`: Purchase an item(s)
 *
 *                                       Media-related values:
 *
 *                                       * `media-play`: Start/resume watching a video, playing a song, etc.
 *                                       * `media-complete`: Finished or stopped midway through a video, song, etc.
 * @param string $userEventUserPseudoId  A unique identifier for tracking visitors.
 *
 *                                       For example, this could be implemented with an HTTP cookie, which should be
 *                                       able to uniquely identify a visitor on a single device. This unique
 *                                       identifier should not change if the visitor log in/out of the website.
 *
 *                                       Do not set the field to the same fixed ID for different users. This mixes
 *                                       the event history of those users together, which results in degraded model
 *                                       quality.
 *
 *                                       The field must be a UTF-8 encoded string with a length limit of 128
 *                                       characters. Otherwise, an `INVALID_ARGUMENT` error is returned.
 *
 *                                       The field should not contain PII or user-data. We recommend to use Google
 *                                       Analytics [Client
 *                                       ID](https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#clientId)
 *                                       for this field.
 */
function recommend_sample(
    string $formattedServingConfig,
    string $userEventEventType,
    string $userEventUserPseudoId
): void {
    // Create a client.
    $recommendationServiceClient = new RecommendationServiceClient();

    // Prepare the request message.
    $userEvent = (new UserEvent())
        ->setEventType($userEventEventType)
        ->setUserPseudoId($userEventUserPseudoId);
    $request = (new RecommendRequest())
        ->setServingConfig($formattedServingConfig)
        ->setUserEvent($userEvent);

    // Call the API and handle any network failures.
    try {
        /** @var RecommendResponse $response */
        $response = $recommendationServiceClient->recommend($request);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedServingConfig = RecommendationServiceClient::servingConfigName(
        '[PROJECT]',
        '[LOCATION]',
        '[DATA_STORE]',
        '[SERVING_CONFIG]'
    );
    $userEventEventType = '[EVENT_TYPE]';
    $userEventUserPseudoId = '[USER_PSEUDO_ID]';

    recommend_sample($formattedServingConfig, $userEventEventType, $userEventUserPseudoId);
}

Python

자세한 내용은 Vertex AI Agent Builder Python API 참고 문서를 확인하세요.

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

# This snippet has been automatically generated and should be regarded as a
# code template only.
# It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
#   client as shown in:
#   https://googleapis.dev/python/google-api-core/latest/client_options.html
from google.cloud import discoveryengine_v1beta


def sample_recommend():
    # Create a client
    client = discoveryengine_v1beta.RecommendationServiceClient()

    # Initialize request argument(s)
    user_event = discoveryengine_v1beta.UserEvent()
    user_event.event_type = "event_type_value"
    user_event.user_pseudo_id = "user_pseudo_id_value"

    request = discoveryengine_v1beta.RecommendRequest(
        serving_config="serving_config_value",
        user_event=user_event,
    )

    # Make the request
    response = client.recommend(request=request)

    # Handle the response
    print(response)

Ruby

자세한 내용은 Vertex AI Agent Builder Ruby API 참고 문서를 확인하세요.

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

require "google/cloud/discovery_engine/v1beta"

##
# Snippet for the recommend call in the RecommendationService service
#
# This snippet has been automatically generated and should be regarded as a code
# template only. It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
# client as shown in https://cloud.google.com/ruby/docs/reference.
#
# This is an auto-generated example demonstrating basic usage of
# Google::Cloud::DiscoveryEngine::V1beta::RecommendationService::Client#recommend.
#
def recommend
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Cloud::DiscoveryEngine::V1beta::RecommendationService::Client.new

  # Create a request. To set request fields, pass in keyword arguments.
  request = Google::Cloud::DiscoveryEngine::V1beta::RecommendRequest.new

  # Call the recommend method.
  result = client.recommend request

  # The returned object is of type Google::Cloud::DiscoveryEngine::V1beta::RecommendResponse.
  p result
end