async def test_detect_intent_field_headers_async(): client = SessionsAsyncClient( credentials=credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_session.DetectIntentRequest() request.session = "session/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.detect_intent), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_session.DetectIntentResponse()) await client.detect_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] assert args[0] == request # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", "session=session/value", ) in kw["metadata"]
def test_detect_intent(transport: str = "grpc", request_type=gcd_session.DetectIntentRequest): client = SessionsClient( 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 = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.detect_intent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcd_session.DetectIntentResponse( response_id="response_id_value", output_audio=b"output_audio_blob", ) response = client.detect_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] assert args[0] == gcd_session.DetectIntentRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_session.DetectIntentResponse) assert response.response_id == "response_id_value" assert response.output_audio == b"output_audio_blob"
def test_detect_intent_flattened_error(): client = SessionsClient(credentials=credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.detect_intent( gcd_session.DetectIntentRequest(), session="session_value", query_input=gcd_session.QueryInput( audio_config=audio_config.InputAudioConfig( audio_encoding=audio_config.AudioEncoding. AUDIO_ENCODING_LINEAR_16)), )
def test_detect_intent_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = SessionsClient( credentials=credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.detect_intent), "__call__") as call: client.detect_intent() call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == gcd_session.DetectIntentRequest()
def detect_intent( self, request: Union[gcd_session.DetectIntentRequest, dict] = None, *, session: str = None, query_input: gcd_session.QueryInput = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcd_session.DetectIntentResponse: r"""Processes a natural language query and returns structured, actionable data as a result. This method is not idempotent, because it may cause contexts and session entity types to be updated, which in turn might affect results of future queries. If you might use `Agent Assist <https://cloud.google.com/dialogflow/docs/#aa>`__ or other CCAI products now or in the future, consider using [AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent] instead of ``DetectIntent``. ``AnalyzeContent`` has additional functionality for Agent Assist and other CCAI products. Note: Always use agent versions for production traffic. See `Versions and environments <https://cloud.google.com/dialogflow/es/docs/agents-versions>`__. .. code-block:: python from google.cloud import dialogflow_v2beta1 def sample_detect_intent(): # Create a client client = dialogflow_v2beta1.SessionsClient() # Initialize request argument(s) request = dialogflow_v2beta1.DetectIntentRequest( session="session_value", ) # Make the request response = client.detect_intent(request=request) # Handle the response print(response) Args: request (Union[google.cloud.dialogflow_v2beta1.types.DetectIntentRequest, dict]): The request object. The request to detect user's intent. session (str): Required. The name of the session this query is sent to. Supported formats: - \`projects//agent/sessions/, - ``projects/<Project ID>/locations/<Location ID>/agent/sessions/<Session ID>``, - ``projects/<Project ID>/agent/environments/<Environment ID>/users/<User ID>/sessions/<Session ID>``, - ``projects/<Project ID>/locations/<Location ID>/agent/environments/<Environment ID>/users/<User ID>/sessions/<Session ID>``, If ``Location ID`` is not specified we assume default 'us' location. If ``Environment ID`` is not specified, we assume default 'draft' environment (``Environment ID`` might be referred to as environment name at some places). If ``User ID`` is not specified, we are using "-". It's up to the API caller to choose an appropriate ``Session ID`` and ``User Id``. They can be a random number or some type of user and session identifiers (preferably hashed). The length of the ``Session ID`` and ``User ID`` must not exceed 36 characters. For more information, see the `API interactions guide <https://cloud.google.com/dialogflow/docs/api-overview>`__. Note: Always use agent versions for production traffic. See `Versions and environments <https://cloud.google.com/dialogflow/es/docs/agents-versions>`__. This corresponds to the ``session`` field on the ``request`` instance; if ``request`` is provided, this should not be set. query_input (google.cloud.dialogflow_v2beta1.types.QueryInput): Required. The input specification. It can be set to: 1. an audio config which instructs the speech recognizer how to process the speech audio, 2. a conversational query in the form of text, or 3. an event that specifies which intent to trigger. This corresponds to the ``query_input`` 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.dialogflow_v2beta1.types.DetectIntentResponse: The message returned from the DetectIntent method. """ # Create or coerce a protobuf request object. # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([session, query_input]) 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 gcd_session.DetectIntentRequest. # There's no risk of modifying the input as we've already verified # there are no flattened fields. if not isinstance(request, gcd_session.DetectIntentRequest): request = gcd_session.DetectIntentRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if session is not None: request.session = session if query_input is not None: request.query_input = query_input # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.detect_intent] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata((("session", request.session),)), ) # Send the request. response = rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) # Done; return the response. return response
async def detect_intent( self, request: gcd_session.DetectIntentRequest = None, *, session: str = None, query_input: gcd_session.QueryInput = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcd_session.DetectIntentResponse: r"""Processes a natural language query and returns structured, actionable data as a result. This method is not idempotent, because it may cause contexts and session entity types to be updated, which in turn might affect results of future queries. Note: Always use agent versions for production traffic. See `Versions and environments <https://cloud.google.com/dialogflow/es/docs/agents-versions>`__. Args: request (:class:`~.gcd_session.DetectIntentRequest`): The request object. The request to detect user's intent. session (:class:`str`): Required. The name of the session this query is sent to. Supported formats: - \`projects//agent/sessions/, - ``projects/<Project ID>/locations/<Location ID>/agent/sessions/<Session ID>``, - ``projects/<Project ID>/agent/environments/<Environment ID>/users/<User ID>/sessions/<Session ID>``, - ``projects/<Project ID>/locations/<Location ID>/agent/environments/<Environment ID>/users/<User ID>/sessions/<Session ID>``, If ``Location ID`` is not specified we assume default 'us' location. If ``Environment ID`` is not specified, we assume default 'draft' environment. If ``User ID`` is not specified, we are using "-". It's up to the API caller to choose an appropriate ``Session ID`` and ``User Id``. They can be a random number or some type of user and session identifiers (preferably hashed). The length of the ``Session ID`` and ``User ID`` must not exceed 36 characters. For more information, see the `API interactions guide <https://cloud.google.com/dialogflow/docs/api-overview>`__. Note: Always use agent versions for production traffic. See `Versions and environments <https://cloud.google.com/dialogflow/es/docs/agents-versions>`__. This corresponds to the ``session`` field on the ``request`` instance; if ``request`` is provided, this should not be set. query_input (:class:`~.gcd_session.QueryInput`): Required. The input specification. It can be set to: 1. an audio config which instructs the speech recognizer how to process the speech audio, 2. a conversational query in the form of text, or 3. an event that specifies which intent to trigger. This corresponds to the ``query_input`` 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: ~.gcd_session.DetectIntentResponse: The message returned from the DetectIntent method. """ # 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([session, query_input]) 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.") request = gcd_session.DetectIntentRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if session is not None: request.session = session if query_input is not None: request.query_input = query_input # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.detect_intent, default_retry=retries.Retry( initial=0.1, maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( exceptions.ServiceUnavailable, ), ), default_timeout=220.0, client_info=DEFAULT_CLIENT_INFO, ) # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + (gapic_v1.routing_header.to_grpc_metadata( (("session", request.session), )), ) # Send the request. response = await rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) # Done; return the response. return response