def test_predict(transport: str = "grpc"): client = PredictionServiceClient( credentials=credentials.AnonymousCredentials(), transport=transport ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. request = prediction_service.PredictRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client._transport.predict), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = prediction_service.PredictResponse( recommendation_token="recommendation_token_value", items_missing_in_catalog=["items_missing_in_catalog_value"], dry_run=True, next_page_token="next_page_token_value", ) response = client.predict(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, pagers.PredictPager) assert response.recommendation_token == "recommendation_token_value" assert response.items_missing_in_catalog == ["items_missing_in_catalog_value"] assert response.dry_run is True assert response.next_page_token == "next_page_token_value"
def predict( self, request: prediction_service.PredictRequest = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.PredictPager: r"""Makes a recommendation prediction. If using API Key based authentication, the API Key must be registered using the [PredictionApiKeyRegistry][google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry] service. `Learn more </recommendations-ai/docs/setting-up#register-key>`__. Args: request (:class:`~.prediction_service.PredictRequest`): The request object. Request message for Predict method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: ~.pagers.PredictPager: Response message for predict method. Iterating over this object will yield results and resolve additional pages automatically. """ # Create or coerce a protobuf request object. request = prediction_service.PredictRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = gapic_v1.method.wrap_method(self._transport.predict, default_timeout=None, client_info=_client_info) # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) # This method is paged; wrap the response in a pager, which provides # an `__iter__` convenience method. response = pagers.PredictPager(method=rpc, request=request, response=response) # Done; return the response. return response
def __init__( self, method: Callable[[prediction_service.PredictRequest], prediction_service.PredictResponse], request: prediction_service.PredictRequest, response: prediction_service.PredictResponse, ): """Instantiate the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. request (:class:`~.prediction_service.PredictRequest`): The initial request object. response (:class:`~.prediction_service.PredictResponse`): The initial response object. """ self._method = method self._request = prediction_service.PredictRequest(request) self._response = response
def __init__(self, method: Callable[..., prediction_service.PredictResponse], request: prediction_service.PredictRequest, response: prediction_service.PredictResponse, *, metadata: Sequence[Tuple[str, str]] = ()): """Instantiate the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. request (google.cloud.recommendationengine_v1beta1.types.PredictRequest): The initial request object. response (google.cloud.recommendationengine_v1beta1.types.PredictResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. """ self._method = method self._request = prediction_service.PredictRequest(request) self._response = response self._metadata = metadata
def predict( self, request: prediction_service.PredictRequest = None, *, name: str = None, user_event: gcr_user_event.UserEvent = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.PredictPager: r"""Makes a recommendation prediction. If using API Key based authentication, the API Key must be registered using the [PredictionApiKeyRegistry][google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry] service. `Learn more </recommendations-ai/docs/setting-up#register-key>`__. Args: request (google.cloud.recommendationengine_v1beta1.types.PredictRequest): The request object. Request message for Predict method. name (str): Required. Full resource name of the format: ``{name=projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/placements/*}`` The id of the recommendation engine placement. This id is used to identify the set of models that will be used to make the prediction. We currently support three placements with the following IDs by default: - ``shopping_cart``: Predicts items frequently bought together with one or more catalog items in the same shopping session. Commonly displayed after ``add-to-cart`` events, on product detail pages, or on the shopping cart page. - ``home_page``: Predicts the next product that a user will most likely engage with or purchase based on the shopping or viewing history of the specified ``userId`` or ``visitorId``. For example - Recommendations for you. - ``product_detail``: Predicts the next product that a user will most likely engage with or purchase. The prediction is based on the shopping or viewing history of the specified ``userId`` or ``visitorId`` and its relevance to a specified ``CatalogItem``. Typically used on product detail pages. For example - More items like this. - ``recently_viewed_default``: Returns up to 75 items recently viewed by the specified ``userId`` or ``visitorId``, most recent ones first. Returns nothing if neither of them has viewed any items yet. For example - Recently viewed. The full list of available placements can be seen at https://console.cloud.google.com/recommendation/datafeeds/default_catalog/dashboard This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. user_event (google.cloud.recommendationengine_v1beta1.types.UserEvent): Required. Context about the user, what they are looking at and what action they took to trigger the predict 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. This corresponds to the ``user_event`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.cloud.recommendationengine_v1beta1.services.prediction_service.pagers.PredictPager: Response message for predict method. Iterating over this object will yield results and resolve additional pages automatically. """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name, user_event]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) # Minor optimization to avoid making a copy if the user passes # in a prediction_service.PredictRequest. # There's no risk of modifying the input as we've already verified # there are no flattened fields. if not isinstance(request, prediction_service.PredictRequest): request = prediction_service.PredictRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if name is not None: request.name = name if user_event is not None: request.user_event = user_event # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.predict] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # This method is paged; wrap the response in a pager, which provides # an `__iter__` convenience method. response = pagers.PredictPager( method=rpc, request=request, response=response, metadata=metadata, ) # Done; return the response. return response