Obtener recomendaciones

En esta página, se muestra cómo obtener una vista previa de las recomendaciones con la consola de Google Cloud y obtener los resultados de las recomendaciones con la API. Consulta la pestaña REST para ver ejemplos de llamadas a la API que pueden ayudarte a integrar recomendaciones en tu app.

El procedimiento que uses dependerá del tipo de recomendaciones que quieras y del tipo de almacén de datos al que esté conectada tu app de recomendaciones:

Cómo obtener recomendaciones de contenido multimedia

Console

Para usar la consola de Google Cloud y obtener una vista previa de las recomendaciones de contenido multimedia, sigue estos pasos:

  1. En la consola de Google Cloud, ve a la página Agent Builder.

    Agent Builder

  2. Haz clic en el nombre de la app para la que deseas obtener una vista previa de las recomendaciones.

  3. Haz clic en Parámetros de configuración > Capacitación. Si Listo para consultar es OK, la app está lista para la vista previa.

  4. Haz clic en Vista previa.

  5. Haz clic en el campo ID del documento. Aparecerá una lista de los IDs de documento.

  6. Haz clic en el ID correspondiente al documento del que deseas obtener recomendaciones. También puedes escribir un ID de documento en el campo ID de documento.

  7. Haz clic en Seleccionar configuración de entrega y selecciona la configuración de entrega de la que deseas obtener una vista previa.

  8. Opcional: Ingresa el ID de visitante (también llamado seudo-ID de usuario) de un usuario para el que recopilaste eventos de usuario. Si dejas este campo en blanco o ingresas un ID de visitante inexistente, obtendrás una vista previa de las recomendaciones como un usuario nuevo.

  9. Haz clic en Obtener recomendaciones. Aparecerá una lista de documentos recomendados.

  10. Haz clic en un documento para obtener los detalles.

REST

Para usar la API y obtener recomendaciones de contenido multimedia, usa el método servingConfigs.recommend:

  1. Busca el ID de tu motor y el ID de configuración de entrega. Si ya tienes tu ID de motor y los IDs de configuración de publicación, ve al paso 2.

    1. En la consola de Google Cloud, ve a la página Agent Builder.

      Agent Builder

    2. Haz clic en el nombre de la app.

    3. En el panel de navegación, haz clic en Configuraciones.

    4. Si solo tienes la configuración de publicación que se creó automáticamente cuando creaste tu app, el ID de configuración de publicación y el ID del motor son los mismos. Pasa al siguiente paso.

      Si tienes varias configuraciones de entrega en la pestaña Configuraciones de entrega, busca la configuración de entrega de la que deseas obtener recomendaciones. El ID de configuración de publicación es el valor de la columna ID.

      Si borraste la configuración de publicación que se creó automáticamente cuando creaste tu app y, actualmente, solo tienes una configuración de publicación que creaste de forma manual, ve a la página Vista previa y haz clic en Seleccionar configuración de publicación para ver el ID de la configuración de publicación.

    5. Haz clic en la pestaña Entrenamiento. El ID del motor es el valor de la fila ID de app.

  2. Asegúrate de que la app esté lista para obtener una vista previa:

    1. En la consola de Google Cloud, ve a la página Agent Builder.

      Agent Builder

    2. Haz clic en el nombre de la app.

    3. Haz clic en Parámetros de configuración > Capacitación. Si Listo para consultar es correcto, la app está lista para la vista previa.

  3. Obtener recomendaciones

    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/dataStores/DATA_STORE_ID/servingConfigs/SERVING_CONFIG_ID:recommend"
    • PROJECT_ID: Es el ID del proyecto
    • DATA_STORE_ID: Es el ID de tu almacén de datos.
    • DOCUMENT_ID: El ID del documento para el que deseas obtener una vista previa de las recomendaciones. Usa el ID que usaste para este documento cuando transfieres tus datos.
    • USER_PSEUDO_ID: Es un identificador seudónimo del usuario. Puedes usar una cookie HTTP para este campo, que identifica de forma única a un visitante en un solo dispositivo. No configures este campo con el mismo identificador para varios usuarios, ya que esto combinaría sus historiales de eventos y degradaría la calidad del modelo. No incluyas información de identificación personal (PII) en este campo.
    • SERVING_CONFIG_ID: Es el ID de tu configuración de publicación.
    • FILTER: Opcional Es un campo de texto que te permite filtrar un conjunto especificado de campos con la sintaxis de expresión de filtro. El valor predeterminado es una cadena vacía, lo que significa que no se aplica ningún filtro. Para obtener más información, consulta Cómo filtrar recomendaciones.

Deberías ver resultados similares a los siguientes:

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

Google recomienda asociar los tokens de atribución, que incluimos con cada respuesta y recomendación de la búsqueda, con las acciones que realiza un usuario en respuesta a esas respuestas y recomendaciones de la búsqueda. Esto puede mejorar la calidad de tus respuestas y recomendaciones de búsqueda con el tiempo. Para ello, agrega valores attributionToken a las URLs de cada uno de los vínculos que muestres en tu sitio web para las respuestas de la búsqueda o las recomendaciones, por ejemplo, https://www.example.com/54321/?rtoken=abc123. Cuando un usuario haga clic en uno de estos vínculos, incluye el valor attributionToken en el evento del usuario que registres.

Obtén recomendaciones genéricas para una app con datos estructurados

Console

Para usar la consola de Google Cloud y obtener una vista previa de las recomendaciones genéricas para tu app estructurada, sigue estos pasos:

  1. En la consola de Google Cloud, ve a la página Agent Builder.

    Agent Builder

  2. Haz clic en el nombre de la app para la que deseas obtener una vista previa de las recomendaciones.

  3. Haz clic en Vista previa.

  4. Haz clic en el campo ID del documento. Aparecerá una lista de los IDs de documento.

  5. Haz clic en el ID correspondiente al documento del que deseas obtener recomendaciones. También puedes escribir un ID de documento en el campo ID de documento.

  6. Haz clic en Obtener recomendaciones. Aparecerá una lista de documentos recomendados.

  7. Haz clic en un documento para obtener los detalles.

REST

Para usar la API y obtener recomendaciones genéricas para una app con datos estructurados, usa el método servingConfigs.recommend:

  1. Busca el ID de tu motor. Si ya tienes tu ID de motor, avanza al paso 2.

    1. En la consola de Google Cloud, ve a la página Agent Builder.

      Agent Builder

    2. Haz clic en el nombre de la app.

    3. Obtén el ID del motor desde la URL de la consola de Google Cloud. Es el texto entre engines/ y /data. Por ejemplo, si la URL contiene

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

      entonces, el ID del motor es demo_1234567890123.

  2. Busca el ID de tu almacén de datos. Si ya tienes el ID del almacén de datos, ve al siguiente paso.

    1. En la consola de Google Cloud, ve a la página Agent Builder y, en el menú de navegación, haz clic en Almacenes de datos.

      Ve a la página Almacenes de datos.

    2. Haz clic en el nombre de tu almacén de datos.

    3. En la página Datos de tu almacén de datos, obtén el ID del almacén de datos.

  3. Para asegurarte de que el motor esté listo para la vista previa, sondea el método GetEngine hasta que muestre "servingState":"ACTIVE". En ese momento, el motor está listo para obtener una vista previa.

    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: Es el ID del proyecto
    • ENGINE_ID: Es el ID de tu motor.
  4. Obtener recomendaciones

    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/dataStores/DATA_STORE_ID/servingConfigs/SERVING_CONFIG_ID:recommend"
    
    • PROJECT_ID: Es el ID del proyecto
    • DATA_STORE_ID: Es el ID de tu almacén de datos.
    • DOCUMENT_ID: El ID del documento para el que deseas obtener una vista previa de las recomendaciones. Usa el ID que usaste para este documento cuando transfieres tus datos.
    • USER_PSEUDO_ID: Es un identificador seudónimo del usuario. Puedes usar una cookie HTTP para este campo, que identifica de forma única a un visitante en un solo dispositivo. No configures este campo con el mismo identificador para varios usuarios, ya que esto combinaría sus historiales de eventos y degradaría la calidad del modelo. No incluyas información de identificación personal (PII) en este campo.
    • SERVING_CONFIG_ID: Es el ID de tu configuración de publicación. Tu ID de configuración de entrega es el mismo que el ID de tu motor, así que usa el ID de tu motor aquí.

C#

Para obtener más información, consulta la documentación de referencia de la API de C# del compilador de agentes de Vertex AI.

Para autenticarte en Vertex AI Agent Builder, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

Para obtener más información, consulta la documentación de referencia de la API de Go del compilador de agentes de Vertex AI.

Para autenticarte en Vertex AI Agent Builder, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


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

Para obtener más información, consulta la documentación de referencia de la API de Java del compilador de agentes de Vertex AI.

Para autenticarte en Vertex AI Agent Builder, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

Para obtener más información, consulta la documentación de referencia de la API de Node.js del compilador de agentes de Vertex AI.

Para autenticarte en Vertex AI Agent Builder, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

/**
 * 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

Para obtener más información, consulta la documentación de referencia de la API de PHP del compilador de agentes de Vertex AI.

Para autenticarte en Vertex AI Agent Builder, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

Para obtener más información, consulta la documentación de referencia de la API de Python del compilador de agentes de Vertex AI.

Para autenticarte en Vertex AI Agent Builder, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

# 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

Para obtener más información, consulta la documentación de referencia de la API de Ruby del compilador de agentes de Vertex AI.

Para autenticarte en Vertex AI Agent Builder, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

Obtén recomendaciones genéricas para una app con datos no estructurados

Console

Para usar la consola de Google Cloud y obtener una vista previa de las recomendaciones genéricas, sigue estos pasos:

  1. En la consola de Google Cloud, ve a la página Agent Builder.

    Agent Builder

  2. Haz clic en el nombre de la app para la que deseas obtener una vista previa de las recomendaciones.

  3. Haz clic en Vista previa.

  4. Haz clic en el campo URI. Aparecerá una lista de URIs.

  5. Haz clic en el URI del documento del que deseas obtener recomendaciones. También puedes ingresar un URI en el campo URI.

  6. Haz clic en Obtener recomendaciones. Aparecerá una lista de URIs de documentos recomendados.

  7. Haz clic en un URI para ver el documento.

REST

Para usar la API y obtener recomendaciones genéricas para una app con datos no estructurados, sigue estos pasos:

  1. Busca el ID de tu motor. Si ya tienes tu ID de motor, avanza al paso 2.

    1. En la consola de Google Cloud, ve a la página Agent Builder.

      Agent Builder

    2. Haz clic en el nombre de la app.

    3. Obtén el ID del motor desde la URL de la consola de Google Cloud. Es el texto entre engines/ y /data. Por ejemplo, si la URL contiene

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

      entonces, el ID del motor es demo_1234567890123.

  2. Busca el ID de tu almacén de datos. Si ya tienes el ID del almacén de datos, ve al siguiente paso.

    1. En la consola de Google Cloud, ve a la página Agent Builder y, en el menú de navegación, haz clic en Almacenes de datos.

      Ve a la página Almacenes de datos.

    2. Haz clic en el nombre de tu almacén de datos.

    3. En la página Datos de tu almacén de datos, obtén el ID del almacén de datos.

  3. Para asegurarte de que el motor esté listo para la vista previa, sondea el método GetEngine hasta que muestre "servingState":"ACTIVE". En ese momento, el motor está listo para obtener una vista previa.

    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: Es el ID del proyecto
    • ENGINE_ID: Es el ID de tu motor.
  4. Obtener recomendaciones

    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/dataStores/DATA_STORE_ID/servingConfigs/SERVING_CONFIG_ID:recommend"
    
    • PROJECT_ID: Es el ID del proyecto
    • DATA_STORE_ID: Es el ID del almacén de datos asociado con tu motor.
    • DOCUMENT_ID: El ID del documento para el que deseas obtener una vista previa de las recomendaciones. Usa el ID de documento que proporcionaste cuando transfieres tus datos.
    • USER_PSEUDO_ID: Es un identificador seudónimo del usuario. Puedes usar una cookie HTTP para este campo, que identifica de forma única a un visitante en un solo dispositivo. No configures este campo con el mismo identificador para varios usuarios, ya que esto combinaría sus historiales de eventos y degradaría la calidad del modelo. No incluyas información de identificación personal (PII) en este campo.
    • SERVING_CONFIG_ID: Es el ID de tu configuración de publicación. Tu ID de configuración de entrega es el mismo que el ID de tu motor, así que usa el ID de tu motor aquí.

C#

Para obtener más información, consulta la documentación de referencia de la API de C# del compilador de agentes de Vertex AI.

Para autenticarte en Vertex AI Agent Builder, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

Para obtener más información, consulta la documentación de referencia de la API de Go del compilador de agentes de Vertex AI.

Para autenticarte en Vertex AI Agent Builder, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


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

Para obtener más información, consulta la documentación de referencia de la API de Java del compilador de agentes de Vertex AI.

Para autenticarte en Vertex AI Agent Builder, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

Para obtener más información, consulta la documentación de referencia de la API de Node.js del compilador de agentes de Vertex AI.

Para autenticarte en Vertex AI Agent Builder, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

/**
 * 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

Para obtener más información, consulta la documentación de referencia de la API de PHP del compilador de agentes de Vertex AI.

Para autenticarte en Vertex AI Agent Builder, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

Para obtener más información, consulta la documentación de referencia de la API de Python del compilador de agentes de Vertex AI.

Para autenticarte en Vertex AI Agent Builder, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

# 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

Para obtener más información, consulta la documentación de referencia de la API de Ruby del compilador de agentes de Vertex AI.

Para autenticarte en Vertex AI Agent Builder, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

Obtén recomendaciones genéricas para una app con datos de sitios web

Console

Para usar la consola de Google Cloud y obtener una vista previa de las recomendaciones genéricas para tu app de sitio web, sigue estos pasos:

  1. En la consola de Google Cloud, ve a la página Agent Builder.

    Agent Builder

  2. Haz clic en el nombre de la app para la que deseas obtener una vista previa de las recomendaciones.

  3. En el menú de navegación, haz clic en Vista previa.

  4. Haz clic en el campo URI. Aparecerá una lista de URLs de tu sitio web.

  5. Haz clic en la URL de la página web de la que quieres obtener recomendaciones. También puedes ingresar una URL de tu sitio web en el campo URL.

  6. Haz clic en Obtener recomendaciones. Aparecerá una lista de URLs de páginas web recomendadas.

  7. Haz clic en una URL para ver la página web.

REST

Para usar la API y obtener recomendaciones genéricas para una app con datos de sitios web, usa el método servingConfigs.recommend:

  1. Busca el ID de tu motor. Si ya tienes tu ID de motor, avanza al paso 2.

    1. En la consola de Google Cloud, ve a la página Agent Builder.

      Agent Builder

    2. Haz clic en el nombre de la app.

    3. Obtén el ID del motor desde la URL de la consola de Google Cloud. Es el texto entre engines/ y /data. Por ejemplo, si la URL contiene

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

      entonces, el ID del motor es demo_1234567890123.

  2. Busca el ID de tu almacén de datos. Si ya tienes el ID del almacén de datos, ve al siguiente paso.

    1. En la consola de Google Cloud, ve a la página Agent Builder y, en el menú de navegación, haz clic en Almacenes de datos.

      Ve a la página Almacenes de datos.

    2. Haz clic en el nombre de tu almacén de datos.

    3. En la página Datos de tu almacén de datos, obtén el ID del almacén de datos.

  3. Para asegurarte de que el motor esté listo para la vista previa, sondea el método GetEngine hasta que muestre "servingState":"ACTIVE". En ese momento, el motor está listo para obtener una vista previa.

    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: Es el ID del proyecto
    • ENGINE_ID: Es el ID de tu motor.
  4. Obtener recomendaciones

    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/dataStores/DATA_STORE_ID/servingConfigs/SERVING_CONFIG_ID:recommend"
    
    • PROJECT_ID: Es el ID del proyecto
    • DATA_STORE_ID: Es el ID de tu almacén de datos.
    • WEBSITE_URL: Es la URL del sitio web para el que deseas obtener una vista previa de las recomendaciones.
    • USER_PSEUDO_ID: Es un identificador seudónimo del usuario. Puedes usar una cookie HTTP para este campo, que identifica de forma única a un visitante en un solo dispositivo. No configures este campo con el mismo identificador para varios usuarios, ya que esto combinaría sus historiales de eventos y degradaría la calidad del modelo. No incluyas información de identificación personal (PII) en este campo.
    • SERVING_CONFIG_ID: Es el ID de tu configuración de publicación. Tu ID de configuración de publicación es el mismo que el ID de tu motor, así que usa el ID de tu motor aquí.

C#

Para obtener más información, consulta la documentación de referencia de la API de C# del compilador de agentes de Vertex AI.

Para autenticarte en Vertex AI Agent Builder, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

Para obtener más información, consulta la documentación de referencia de la API de Go del compilador de agentes de Vertex AI.

Para autenticarte en Vertex AI Agent Builder, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


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

Para obtener más información, consulta la documentación de referencia de la API de Java del compilador de agentes de Vertex AI.

Para autenticarte en Vertex AI Agent Builder, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

Para obtener más información, consulta la documentación de referencia de la API de Node.js del compilador de agentes de Vertex AI.

Para autenticarte en Vertex AI Agent Builder, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

/**
 * 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

Para obtener más información, consulta la documentación de referencia de la API de PHP del compilador de agentes de Vertex AI.

Para autenticarte en Vertex AI Agent Builder, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

Para obtener más información, consulta la documentación de referencia de la API de Python del compilador de agentes de Vertex AI.

Para autenticarte en Vertex AI Agent Builder, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

# 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

Para obtener más información, consulta la documentación de referencia de la API de Ruby del compilador de agentes de Vertex AI.

Para autenticarte en Vertex AI Agent Builder, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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