Reference documentation and code samples for the Google Cloud Retail V2 Client class ModelServiceClient.
Service Description: Service for performing CRUD operations on models.
Recommendation models contain all the metadata necessary to generate a set of
models for the Predict()
API. A model is queried
indirectly via a ServingConfig, which associates a model with a
given Placement (e.g. Frequently Bought Together on Home Page).
This service allows you to do the following:
- Initiate training of a model.
- Pause training of an existing model.
- List all the available models along with their metadata.
- Control their tuning schedule.
This class provides the ability to make remote calls to the backing service through method calls that map to API methods. Sample code to get started:
$modelServiceClient = new ModelServiceClient();
try {
$formattedParent = $modelServiceClient->catalogName('[PROJECT]', '[LOCATION]', '[CATALOG]');
$model = new Model();
$operationResponse = $modelServiceClient->createModel($formattedParent, $model);
$operationResponse->pollUntilComplete();
if ($operationResponse->operationSucceeded()) {
$result = $operationResponse->getResult();
// doSomethingWith($result)
} else {
$error = $operationResponse->getError();
// handleError($error)
}
// Alternatively:
// start the operation, keep the operation name, and resume later
$operationResponse = $modelServiceClient->createModel($formattedParent, $model);
$operationName = $operationResponse->getName();
// ... do other work
$newOperationResponse = $modelServiceClient->resumeOperation($operationName, 'createModel');
while (!$newOperationResponse->isDone()) {
// ... do other work
$newOperationResponse->reload();
}
if ($newOperationResponse->operationSucceeded()) {
$result = $newOperationResponse->getResult();
// doSomethingWith($result)
} else {
$error = $newOperationResponse->getError();
// handleError($error)
}
} finally {
$modelServiceClient->close();
}
Many parameters require resource names to be formatted in a particular way. To assist with these names, this class includes a format method for each type of name, and additionally a parseName method to extract the individual identifiers contained within formatted names that are returned by the API.
This service has a new (beta) implementation. See Google\Cloud\Retail\V2\Client\ModelServiceClient to use the new surface.
Namespace
Google \ Cloud \ Retail \ V2Methods
__construct
Constructor.
options
array
Optional. Options for configuring the service API wrapper.
↳ apiEndpoint
string
The address of the API remote host. May optionally include the port, formatted as "
↳ credentials
string|array|FetchAuthTokenInterface|CredentialsWrapper
The credentials to be used by the client to authorize API calls. This option accepts either a path to a credentials file, or a decoded credentials file as a PHP array. Advanced usage : In addition, this option can also accept a pre-constructed Google\Auth\FetchAuthTokenInterface object or Google\ApiCore\CredentialsWrapper object. Note that when one of these objects are provided, any settings in $credentialsConfig will be ignored.
↳ credentialsConfig
array
Options used to configure credentials, including auth token caching, for the client. For a full list of supporting configuration options, see Google\ApiCore\CredentialsWrapper::build() .
↳ disableRetries
bool
Determines whether or not retries defined by the client configuration should be disabled. Defaults to false
.
↳ clientConfig
string|array
Client method configuration, including retry settings. This option can be either a path to a JSON file, or a PHP array containing the decoded JSON data. By default this settings points to the default client config file, which is provided in the resources folder.
↳ transport
string|TransportInterface
The transport used for executing network requests. May be either the string rest
or grpc
. Defaults to grpc
if gRPC support is detected on the system. Advanced usage
: Additionally, it is possible to pass in an already instantiated Google\ApiCore\Transport\TransportInterface
object. Note that when this object is provided, any settings in $transportConfig, and any $apiEndpoint setting, will be ignored.
↳ transportConfig
array
Configuration options that will be used to construct the transport. Options for each supported transport type should be passed in a key for that transport. For example: $transportConfig = [ 'grpc' => [...], 'rest' => [...], ]; See the Google\ApiCore\Transport\GrpcTransport::build() and Google\ApiCore\Transport\RestTransport::build() methods for the supported options.
↳ clientCertSource
callable
A callable which returns the client cert as a string. This can be used to provide a certificate and private key to the transport layer for mTLS.
createModel
Creates a new model.
parent
string
Required. The parent resource under which to create the model. Format: projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}
model
optionalArgs
array
Optional.
↳ dryRun
bool
Optional. Whether to run a dry run to validate the request (without actually creating the model).
↳ retrySettings
RetrySettings|array
Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.
use Google\ApiCore\ApiException;
use Google\ApiCore\OperationResponse;
use Google\Cloud\Retail\V2\Model;
use Google\Cloud\Retail\V2\ModelServiceClient;
use Google\Rpc\Status;
/**
* @param string $formattedParent The parent resource under which to create the model. Format:
* `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}`
* Please see {@see ModelServiceClient::catalogName()} for help formatting this field.
* @param string $modelName The fully qualified resource name of the model.
*
* Format:
* `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/models/{model_id}`
* catalog_id has char limit of 50.
* recommendation_model_id has char limit of 40.
* @param string $modelDisplayName The display name of the model.
*
* Should be human readable, used to display Recommendation Models in the
* Retail Cloud Console Dashboard. UTF-8 encoded string with limit of 1024
* characters.
* @param string $modelType The type of model e.g. `home-page`.
*
* Currently supported values: `recommended-for-you`, `others-you-may-like`,
* `frequently-bought-together`, `page-optimization`, `similar-items`,
* `buy-it-again`, `on-sale-items`, and `recently-viewed`(readonly value).
*
*
* This field together with
* [optimization_objective][google.cloud.retail.v2.Model.optimization_objective]
* describe model metadata to use to control model training and serving.
* See https://cloud.google.com/retail/docs/models
* for more details on what the model metadata control and which combination
* of parameters are valid. For invalid combinations of parameters (e.g. type
* = `frequently-bought-together` and optimization_objective = `ctr`), you
* receive an error 400 if you try to create/update a recommendation with
* this set of knobs.
*/
function create_model_sample(
string $formattedParent,
string $modelName,
string $modelDisplayName,
string $modelType
): void {
// Create a client.
$modelServiceClient = new ModelServiceClient();
// Prepare any non-scalar elements to be passed along with the request.
$model = (new Model())
->setName($modelName)
->setDisplayName($modelDisplayName)
->setType($modelType);
// Call the API and handle any network failures.
try {
/** @var OperationResponse $response */
$response = $modelServiceClient->createModel($formattedParent, $model);
$response->pollUntilComplete();
if ($response->operationSucceeded()) {
/** @var Model $result */
$result = $response->getResult();
printf('Operation successful with response data: %s' . PHP_EOL, $result->serializeToJsonString());
} else {
/** @var Status $error */
$error = $response->getError();
printf('Operation failed with error data: %s' . PHP_EOL, $error->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
{
$formattedParent = ModelServiceClient::catalogName('[PROJECT]', '[LOCATION]', '[CATALOG]');
$modelName = '[NAME]';
$modelDisplayName = '[DISPLAY_NAME]';
$modelType = '[TYPE]';
create_model_sample($formattedParent, $modelName, $modelDisplayName, $modelType);
}
deleteModel
Deletes an existing model.
name
string
Required. The resource name of the Model
to
delete. Format: projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/models/{model_id}
optionalArgs
array
Optional.
↳ retrySettings
RetrySettings|array
Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.
use Google\ApiCore\ApiException;
use Google\Cloud\Retail\V2\ModelServiceClient;
/**
* @param string $formattedName The resource name of the [Model][google.cloud.retail.v2.Model] to
* delete. Format:
* `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/models/{model_id}`
* Please see {@see ModelServiceClient::modelName()} for help formatting this field.
*/
function delete_model_sample(string $formattedName): void
{
// Create a client.
$modelServiceClient = new ModelServiceClient();
// Call the API and handle any network failures.
try {
$modelServiceClient->deleteModel($formattedName);
printf('Call completed successfully.' . PHP_EOL);
} 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
{
$formattedName = ModelServiceClient::modelName('[PROJECT]', '[LOCATION]', '[CATALOG]', '[MODEL]');
delete_model_sample($formattedName);
}
getModel
Gets a model.
name
string
Required. The resource name of the Model
to
get. Format: projects/{project_number}/locations/{location_id}/catalogs/{catalog}/models/{model_id}
optionalArgs
array
Optional.
↳ retrySettings
RetrySettings|array
Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.
use Google\ApiCore\ApiException;
use Google\Cloud\Retail\V2\Model;
use Google\Cloud\Retail\V2\ModelServiceClient;
/**
* @param string $formattedName The resource name of the [Model][google.cloud.retail.v2.Model] to
* get. Format:
* `projects/{project_number}/locations/{location_id}/catalogs/{catalog}/models/{model_id}`
* Please see {@see ModelServiceClient::modelName()} for help formatting this field.
*/
function get_model_sample(string $formattedName): void
{
// Create a client.
$modelServiceClient = new ModelServiceClient();
// Call the API and handle any network failures.
try {
/** @var Model $response */
$response = $modelServiceClient->getModel($formattedName);
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
{
$formattedName = ModelServiceClient::modelName('[PROJECT]', '[LOCATION]', '[CATALOG]', '[MODEL]');
get_model_sample($formattedName);
}
listModels
Lists all the models linked to this event store.
parent
string
Required. The parent for which to list models.
Format: projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}
optionalArgs
array
Optional.
↳ pageSize
int
The maximum number of resources contained in the underlying API response. The API may return fewer values in a page, even if there are additional values to be retrieved.
↳ pageToken
string
A page token is used to specify a page of values to be returned. If no page token is specified (the default), the first page of values will be returned. Any page token used here must have been generated by a previous call to the API.
↳ retrySettings
RetrySettings|array
Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.
use Google\ApiCore\ApiException;
use Google\ApiCore\PagedListResponse;
use Google\Cloud\Retail\V2\Model;
use Google\Cloud\Retail\V2\ModelServiceClient;
/**
* @param string $formattedParent The parent for which to list models.
* Format:
* `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}`
* Please see {@see ModelServiceClient::catalogName()} for help formatting this field.
*/
function list_models_sample(string $formattedParent): void
{
// Create a client.
$modelServiceClient = new ModelServiceClient();
// Call the API and handle any network failures.
try {
/** @var PagedListResponse $response */
$response = $modelServiceClient->listModels($formattedParent);
/** @var Model $element */
foreach ($response as $element) {
printf('Element data: %s' . PHP_EOL, $element->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
{
$formattedParent = ModelServiceClient::catalogName('[PROJECT]', '[LOCATION]', '[CATALOG]');
list_models_sample($formattedParent);
}
pauseModel
Pauses the training of an existing model.
name
string
Required. The name of the model to pause.
Format: projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/models/{model_id}
optionalArgs
array
Optional.
↳ retrySettings
RetrySettings|array
Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.
use Google\ApiCore\ApiException;
use Google\Cloud\Retail\V2\Model;
use Google\Cloud\Retail\V2\ModelServiceClient;
/**
* @param string $formattedName The name of the model to pause.
* Format:
* `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/models/{model_id}`
* Please see {@see ModelServiceClient::modelName()} for help formatting this field.
*/
function pause_model_sample(string $formattedName): void
{
// Create a client.
$modelServiceClient = new ModelServiceClient();
// Call the API and handle any network failures.
try {
/** @var Model $response */
$response = $modelServiceClient->pauseModel($formattedName);
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
{
$formattedName = ModelServiceClient::modelName('[PROJECT]', '[LOCATION]', '[CATALOG]', '[MODEL]');
pause_model_sample($formattedName);
}
resumeModel
Resumes the training of an existing model.
name
string
Required. The name of the model to resume.
Format: projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/models/{model_id}
optionalArgs
array
Optional.
↳ retrySettings
RetrySettings|array
Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.
use Google\ApiCore\ApiException;
use Google\Cloud\Retail\V2\Model;
use Google\Cloud\Retail\V2\ModelServiceClient;
/**
* @param string $name The name of the model to resume.
* Format:
* `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/models/{model_id}`
*/
function resume_model_sample(string $name): void
{
// Create a client.
$modelServiceClient = new ModelServiceClient();
// Call the API and handle any network failures.
try {
/** @var Model $response */
$response = $modelServiceClient->resumeModel($name);
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
{
$name = '[NAME]';
resume_model_sample($name);
}
tuneModel
Tunes an existing model.
name
string
Required. The resource name of the model to tune.
Format: projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/models/{model_id}
optionalArgs
array
Optional.
↳ retrySettings
RetrySettings|array
Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.
use Google\ApiCore\ApiException;
use Google\ApiCore\OperationResponse;
use Google\Cloud\Retail\V2\ModelServiceClient;
use Google\Cloud\Retail\V2\TuneModelResponse;
use Google\Rpc\Status;
/**
* @param string $formattedName The resource name of the model to tune.
* Format:
* `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/models/{model_id}`
* Please see {@see ModelServiceClient::modelName()} for help formatting this field.
*/
function tune_model_sample(string $formattedName): void
{
// Create a client.
$modelServiceClient = new ModelServiceClient();
// Call the API and handle any network failures.
try {
/** @var OperationResponse $response */
$response = $modelServiceClient->tuneModel($formattedName);
$response->pollUntilComplete();
if ($response->operationSucceeded()) {
/** @var TuneModelResponse $result */
$result = $response->getResult();
printf('Operation successful with response data: %s' . PHP_EOL, $result->serializeToJsonString());
} else {
/** @var Status $error */
$error = $response->getError();
printf('Operation failed with error data: %s' . PHP_EOL, $error->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
{
$formattedName = ModelServiceClient::modelName('[PROJECT]', '[LOCATION]', '[CATALOG]', '[MODEL]');
tune_model_sample($formattedName);
}
updateModel
Update of model metadata. Only fields that
currently can be updated are: filtering_option
and periodic_tuning_state
.
If other values are provided, this API method ignores them.
model
optionalArgs
array
Optional.
↳ updateMask
FieldMask
Optional. Indicates which fields in the provided 'model' to update. If not set, by default updates all fields.
↳ retrySettings
RetrySettings|array
Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.
use Google\ApiCore\ApiException;
use Google\Cloud\Retail\V2\Model;
use Google\Cloud\Retail\V2\ModelServiceClient;
/**
* @param string $modelName The fully qualified resource name of the model.
*
* Format:
* `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/models/{model_id}`
* catalog_id has char limit of 50.
* recommendation_model_id has char limit of 40.
* @param string $modelDisplayName The display name of the model.
*
* Should be human readable, used to display Recommendation Models in the
* Retail Cloud Console Dashboard. UTF-8 encoded string with limit of 1024
* characters.
* @param string $modelType The type of model e.g. `home-page`.
*
* Currently supported values: `recommended-for-you`, `others-you-may-like`,
* `frequently-bought-together`, `page-optimization`, `similar-items`,
* `buy-it-again`, `on-sale-items`, and `recently-viewed`(readonly value).
*
*
* This field together with
* [optimization_objective][google.cloud.retail.v2.Model.optimization_objective]
* describe model metadata to use to control model training and serving.
* See https://cloud.google.com/retail/docs/models
* for more details on what the model metadata control and which combination
* of parameters are valid. For invalid combinations of parameters (e.g. type
* = `frequently-bought-together` and optimization_objective = `ctr`), you
* receive an error 400 if you try to create/update a recommendation with
* this set of knobs.
*/
function update_model_sample(string $modelName, string $modelDisplayName, string $modelType): void
{
// Create a client.
$modelServiceClient = new ModelServiceClient();
// Prepare any non-scalar elements to be passed along with the request.
$model = (new Model())
->setName($modelName)
->setDisplayName($modelDisplayName)
->setType($modelType);
// Call the API and handle any network failures.
try {
/** @var Model $response */
$response = $modelServiceClient->updateModel($model);
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
{
$modelName = '[NAME]';
$modelDisplayName = '[DISPLAY_NAME]';
$modelType = '[TYPE]';
update_model_sample($modelName, $modelDisplayName, $modelType);
}
getOperationsClient
Return an OperationsClient object with the same endpoint as $this.
resumeOperation
Resume an existing long running operation that was previously started by a long running API method. If $methodName is not provided, or does not match a long running API method, then the operation can still be resumed, but the OperationResponse object will not deserialize the final response.
operationName
string
The name of the long running operation
methodName
string
The name of the method used to start the operation
static::catalogName
Formats a string containing the fully-qualified path to represent a catalog resource.
project
string
location
string
catalog
string
string
static::modelName
Formats a string containing the fully-qualified path to represent a model resource.
project
string
location
string
catalog
string
model
string
string
static::parseName
Parses a formatted name string and returns an associative array of the components in the name.
The following name formats are supported: Template: Pattern
- catalog: projects/{project}/locations/{location}/catalogs/{catalog}
- model: projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}
The optional $template argument can be supplied to specify a particular pattern, and must match one of the templates listed above. If no $template argument is provided, or if the $template argument does not match one of the templates listed, then parseName will check each of the supported templates, and return the first match.
formattedName
string
The formatted name string
template
string
Optional name of template to match
array
Constants
SERVICE_NAME
Value: 'google.cloud.retail.v2.ModelService'
The name of the service.
SERVICE_ADDRESS
Value: 'retail.googleapis.com'
The default address of the service.
DEFAULT_SERVICE_PORT
Value: 443
The default port of the service.
CODEGEN_NAME
Value: 'gapic'
The name of the code generator, to be included in the agent header.