From f0a539993f9baac2b32fc13d2297ee9deb623186 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 31 Aug 2023 09:31:06 -0400 Subject: [PATCH] feat: added generative AI, safety/security and speech endpointing settings (#11621) Co-authored-by: Owl Bot Co-authored-by: Anthonios Partheniou --- .../google/cloud/dialogflowcx/__init__.py | 16 + .../google/cloud/dialogflowcx_v3/__init__.py | 13 + .../cloud/dialogflowcx_v3/gapic_metadata.json | 30 + .../services/agents/async_client.py | 238 ++ .../dialogflowcx_v3/services/agents/client.py | 256 ++ .../services/agents/transports/base.py | 38 + .../services/agents/transports/grpc.py | 61 + .../agents/transports/grpc_asyncio.py | 62 + .../services/agents/transports/rest.py | 279 +++ .../cloud/dialogflowcx_v3/types/__init__.py | 13 + .../cloud/dialogflowcx_v3/types/agent.py | 83 + .../types/data_store_connection.py | 80 + .../cloud/dialogflowcx_v3/types/flow.py | 7 + .../types/generative_settings.py | 176 ++ .../cloud/dialogflowcx_v3/types/page.py | 92 +- .../dialogflowcx_v3/types/response_message.py | 20 + .../dialogflowcx_v3/types/safety_settings.py | 65 + .../types/security_settings.py | 32 + .../cloud/dialogflowcx_v3/types/session.py | 11 +- .../types/validation_message.py | 3 + ...ed_agents_get_generative_settings_async.py | 53 + ...ted_agents_get_generative_settings_sync.py | 53 + ...agents_update_generative_settings_async.py | 51 + ..._agents_update_generative_settings_sync.py | 51 + ...etadata_google.cloud.dialogflow.cx.v3.json | 338 +++ .../scripts/fixup_dialogflowcx_v3_keywords.py | 2 + .../unit/gapic/dialogflowcx_v3/test_agents.py | 2066 +++++++++++++---- .../unit/gapic/dialogflowcx_v3/test_flows.py | 45 + .../unit/gapic/dialogflowcx_v3/test_pages.py | 46 +- .../test_security_settings_service.py | 4 + .../gapic/dialogflowcx_v3/test_test_cases.py | 45 + .../test_transition_route_groups.py | 8 + 32 files changed, 3902 insertions(+), 435 deletions(-) create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/data_store_connection.py create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/generative_settings.py create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/safety_settings.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_agents_get_generative_settings_async.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_agents_get_generative_settings_sync.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_agents_update_generative_settings_async.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_agents_update_generative_settings_sync.py diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx/__init__.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx/__init__.py index badb5335081e..5954cfbe8fe4 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx/__init__.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx/__init__.py @@ -92,11 +92,13 @@ ExportAgentResponse, GetAgentRequest, GetAgentValidationResultRequest, + GetGenerativeSettingsRequest, ListAgentsRequest, ListAgentsResponse, RestoreAgentRequest, SpeechToTextSettings, UpdateAgentRequest, + UpdateGenerativeSettingsRequest, ValidateAgentRequest, ) from google.cloud.dialogflowcx_v3.types.audio_config import ( @@ -117,6 +119,10 @@ ListChangelogsRequest, ListChangelogsResponse, ) +from google.cloud.dialogflowcx_v3.types.data_store_connection import ( + DataStoreConnection, + DataStoreType, +) from google.cloud.dialogflowcx_v3.types.deployment import ( Deployment, GetDeploymentRequest, @@ -188,6 +194,7 @@ ) from google.cloud.dialogflowcx_v3.types.fulfillment import Fulfillment from google.cloud.dialogflowcx_v3.types.gcs import GcsDestination +from google.cloud.dialogflowcx_v3.types.generative_settings import GenerativeSettings from google.cloud.dialogflowcx_v3.types.import_strategy import ImportStrategy from google.cloud.dialogflowcx_v3.types.intent import ( CreateIntentRequest, @@ -205,6 +212,7 @@ EventHandler, Form, GetPageRequest, + KnowledgeConnectorSettings, ListPagesRequest, ListPagesResponse, Page, @@ -212,6 +220,7 @@ UpdatePageRequest, ) from google.cloud.dialogflowcx_v3.types.response_message import ResponseMessage +from google.cloud.dialogflowcx_v3.types.safety_settings import SafetySettings from google.cloud.dialogflowcx_v3.types.security_settings import ( CreateSecuritySettingsRequest, DeleteSecuritySettingsRequest, @@ -370,11 +379,13 @@ "ExportAgentResponse", "GetAgentRequest", "GetAgentValidationResultRequest", + "GetGenerativeSettingsRequest", "ListAgentsRequest", "ListAgentsResponse", "RestoreAgentRequest", "SpeechToTextSettings", "UpdateAgentRequest", + "UpdateGenerativeSettingsRequest", "ValidateAgentRequest", "InputAudioConfig", "OutputAudioConfig", @@ -390,6 +401,8 @@ "GetChangelogRequest", "ListChangelogsRequest", "ListChangelogsResponse", + "DataStoreConnection", + "DataStoreType", "Deployment", "GetDeploymentRequest", "ListDeploymentsRequest", @@ -451,6 +464,7 @@ "ValidateFlowRequest", "Fulfillment", "GcsDestination", + "GenerativeSettings", "ImportStrategy", "CreateIntentRequest", "DeleteIntentRequest", @@ -465,12 +479,14 @@ "EventHandler", "Form", "GetPageRequest", + "KnowledgeConnectorSettings", "ListPagesRequest", "ListPagesResponse", "Page", "TransitionRoute", "UpdatePageRequest", "ResponseMessage", + "SafetySettings", "CreateSecuritySettingsRequest", "DeleteSecuritySettingsRequest", "GetSecuritySettingsRequest", diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/__init__.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/__init__.py index 1fbaaebd93fd..ba7a88c5d5c9 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/__init__.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/__init__.py @@ -53,11 +53,13 @@ ExportAgentResponse, GetAgentRequest, GetAgentValidationResultRequest, + GetGenerativeSettingsRequest, ListAgentsRequest, ListAgentsResponse, RestoreAgentRequest, SpeechToTextSettings, UpdateAgentRequest, + UpdateGenerativeSettingsRequest, ValidateAgentRequest, ) from .types.audio_config import ( @@ -78,6 +80,7 @@ ListChangelogsRequest, ListChangelogsResponse, ) +from .types.data_store_connection import DataStoreConnection, DataStoreType from .types.deployment import ( Deployment, GetDeploymentRequest, @@ -149,6 +152,7 @@ ) from .types.fulfillment import Fulfillment from .types.gcs import GcsDestination +from .types.generative_settings import GenerativeSettings from .types.import_strategy import ImportStrategy from .types.intent import ( CreateIntentRequest, @@ -166,6 +170,7 @@ EventHandler, Form, GetPageRequest, + KnowledgeConnectorSettings, ListPagesRequest, ListPagesResponse, Page, @@ -173,6 +178,7 @@ UpdatePageRequest, ) from .types.response_message import ResponseMessage +from .types.safety_settings import SafetySettings from .types.security_settings import ( CreateSecuritySettingsRequest, DeleteSecuritySettingsRequest, @@ -336,6 +342,8 @@ "CreateVersionOperationMetadata", "CreateVersionRequest", "CreateWebhookRequest", + "DataStoreConnection", + "DataStoreType", "DeleteAgentRequest", "DeleteEntityTypeRequest", "DeleteEnvironmentRequest", @@ -380,6 +388,7 @@ "FulfillIntentResponse", "Fulfillment", "GcsDestination", + "GenerativeSettings", "GetAgentRequest", "GetAgentValidationResultRequest", "GetChangelogRequest", @@ -389,6 +398,7 @@ "GetExperimentRequest", "GetFlowRequest", "GetFlowValidationResultRequest", + "GetGenerativeSettingsRequest", "GetIntentRequest", "GetPageRequest", "GetSecuritySettingsRequest", @@ -410,6 +420,7 @@ "IntentInput", "IntentView", "IntentsClient", + "KnowledgeConnectorSettings", "ListAgentsRequest", "ListAgentsResponse", "ListChangelogsRequest", @@ -470,6 +481,7 @@ "RunTestCaseMetadata", "RunTestCaseRequest", "RunTestCaseResponse", + "SafetySettings", "SecuritySettings", "SecuritySettingsServiceClient", "SentimentAnalysisResult", @@ -508,6 +520,7 @@ "UpdateEnvironmentRequest", "UpdateExperimentRequest", "UpdateFlowRequest", + "UpdateGenerativeSettingsRequest", "UpdateIntentRequest", "UpdatePageRequest", "UpdateSecuritySettingsRequest", diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/gapic_metadata.json b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/gapic_metadata.json index e89078c3b64f..17c042151b36 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/gapic_metadata.json +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/gapic_metadata.json @@ -35,6 +35,11 @@ "get_agent_validation_result" ] }, + "GetGenerativeSettings": { + "methods": [ + "get_generative_settings" + ] + }, "ListAgents": { "methods": [ "list_agents" @@ -50,6 +55,11 @@ "update_agent" ] }, + "UpdateGenerativeSettings": { + "methods": [ + "update_generative_settings" + ] + }, "ValidateAgent": { "methods": [ "validate_agent" @@ -85,6 +95,11 @@ "get_agent_validation_result" ] }, + "GetGenerativeSettings": { + "methods": [ + "get_generative_settings" + ] + }, "ListAgents": { "methods": [ "list_agents" @@ -100,6 +115,11 @@ "update_agent" ] }, + "UpdateGenerativeSettings": { + "methods": [ + "update_generative_settings" + ] + }, "ValidateAgent": { "methods": [ "validate_agent" @@ -135,6 +155,11 @@ "get_agent_validation_result" ] }, + "GetGenerativeSettings": { + "methods": [ + "get_generative_settings" + ] + }, "ListAgents": { "methods": [ "list_agents" @@ -150,6 +175,11 @@ "update_agent" ] }, + "UpdateGenerativeSettings": { + "methods": [ + "update_generative_settings" + ] + }, "ValidateAgent": { "methods": [ "validate_agent" diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/agents/async_client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/agents/async_client.py index 5c5756e79816..dd1eea94fa78 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/agents/async_client.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/agents/async_client.py @@ -51,10 +51,15 @@ from google.protobuf import struct_pb2 # type: ignore from google.cloud.dialogflowcx_v3.services.agents import pagers +from google.cloud.dialogflowcx_v3.types import ( + generative_settings as gcdc_generative_settings, +) from google.cloud.dialogflowcx_v3.types import advanced_settings from google.cloud.dialogflowcx_v3.types import agent from google.cloud.dialogflowcx_v3.types import agent as gcdc_agent from google.cloud.dialogflowcx_v3.types import audio_config, flow +from google.cloud.dialogflowcx_v3.types import generative_settings +from google.cloud.dialogflowcx_v3.types import safety_settings from .client import AgentsClient from .transports.base import DEFAULT_CLIENT_INFO, AgentsTransport @@ -71,6 +76,12 @@ class AgentsAsyncClient: agent_path = staticmethod(AgentsClient.agent_path) parse_agent_path = staticmethod(AgentsClient.parse_agent_path) + agent_generative_settings_path = staticmethod( + AgentsClient.agent_generative_settings_path + ) + parse_agent_generative_settings_path = staticmethod( + AgentsClient.parse_agent_generative_settings_path + ) agent_validation_result_path = staticmethod( AgentsClient.agent_validation_result_path ) @@ -1242,6 +1253,233 @@ async def sample_get_agent_validation_result(): # Done; return the response. return response + async def get_generative_settings( + self, + request: Optional[Union[agent.GetGenerativeSettingsRequest, dict]] = None, + *, + name: Optional[str] = None, + language_code: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> generative_settings.GenerativeSettings: + r"""Gets the generative settings for the agent. + + .. code-block:: python + + # 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 dialogflowcx_v3 + + async def sample_get_generative_settings(): + # Create a client + client = dialogflowcx_v3.AgentsAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.GetGenerativeSettingsRequest( + name="name_value", + language_code="language_code_value", + ) + + # Make the request + response = await client.get_generative_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.dialogflowcx_v3.types.GetGenerativeSettingsRequest, dict]]): + The request object. Request for + [GetGenerativeSettings][google.cloud.dialogflow.cx.v3.Agents.GetGenerativeSettings] + RPC. + name (:class:`str`): + Required. Format: + ``projects//locations//agents//generativeSettings``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (:class:`str`): + Required. Language code of the + generative settings. + + This corresponds to the ``language_code`` 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.dialogflowcx_v3.types.GenerativeSettings: + Settings for Generative AI. + """ + # 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([name, language_code]) + 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 = agent.GetGenerativeSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if language_code is not None: + request.language_code = language_code + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_generative_settings, + default_timeout=None, + 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((("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_generative_settings( + self, + request: Optional[Union[agent.UpdateGenerativeSettingsRequest, dict]] = None, + *, + generative_settings: Optional[ + gcdc_generative_settings.GenerativeSettings + ] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_generative_settings.GenerativeSettings: + r"""Updates the generative settings for the agent. + + .. code-block:: python + + # 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 dialogflowcx_v3 + + async def sample_update_generative_settings(): + # Create a client + client = dialogflowcx_v3.AgentsAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.UpdateGenerativeSettingsRequest( + ) + + # Make the request + response = await client.update_generative_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.dialogflowcx_v3.types.UpdateGenerativeSettingsRequest, dict]]): + The request object. Request for + [UpdateGenerativeSettings][google.cloud.dialogflow.cx.v3.Agents.UpdateGenerativeSettings] + RPC. + generative_settings (:class:`google.cloud.dialogflowcx_v3.types.GenerativeSettings`): + Required. Generative settings to + update. + + This corresponds to the ``generative_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. The mask to control which + fields get updated. If the mask is not + present, all fields will be updated. + + This corresponds to the ``update_mask`` 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.dialogflowcx_v3.types.GenerativeSettings: + Settings for Generative AI. + """ + # 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([generative_settings, update_mask]) + 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 = agent.UpdateGenerativeSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if generative_settings is not None: + request.generative_settings = generative_settings + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_generative_settings, + default_timeout=None, + 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( + (("generative_settings.name", request.generative_settings.name),) + ), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def list_operations( self, request: Optional[operations_pb2.ListOperationsRequest] = None, diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/agents/client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/agents/client.py index 9193da1126c6..d7c12a32afc9 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/agents/client.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/agents/client.py @@ -55,10 +55,15 @@ from google.protobuf import struct_pb2 # type: ignore from google.cloud.dialogflowcx_v3.services.agents import pagers +from google.cloud.dialogflowcx_v3.types import ( + generative_settings as gcdc_generative_settings, +) from google.cloud.dialogflowcx_v3.types import advanced_settings from google.cloud.dialogflowcx_v3.types import agent from google.cloud.dialogflowcx_v3.types import agent as gcdc_agent from google.cloud.dialogflowcx_v3.types import audio_config, flow +from google.cloud.dialogflowcx_v3.types import generative_settings +from google.cloud.dialogflowcx_v3.types import safety_settings from .transports.base import DEFAULT_CLIENT_INFO, AgentsTransport from .transports.grpc import AgentsGrpcTransport @@ -208,6 +213,28 @@ def parse_agent_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def agent_generative_settings_path( + project: str, + location: str, + agent: str, + ) -> str: + """Returns a fully-qualified agent_generative_settings string.""" + return "projects/{project}/locations/{location}/agents/{agent}/generativeSettings".format( + project=project, + location=location, + agent=agent, + ) + + @staticmethod + def parse_agent_generative_settings_path(path: str) -> Dict[str, str]: + """Parses a agent_generative_settings path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/generativeSettings$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def agent_validation_result_path( project: str, @@ -1573,6 +1600,235 @@ def sample_get_agent_validation_result(): # Done; return the response. return response + def get_generative_settings( + self, + request: Optional[Union[agent.GetGenerativeSettingsRequest, dict]] = None, + *, + name: Optional[str] = None, + language_code: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> generative_settings.GenerativeSettings: + r"""Gets the generative settings for the agent. + + .. code-block:: python + + # 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 dialogflowcx_v3 + + def sample_get_generative_settings(): + # Create a client + client = dialogflowcx_v3.AgentsClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.GetGenerativeSettingsRequest( + name="name_value", + language_code="language_code_value", + ) + + # Make the request + response = client.get_generative_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.GetGenerativeSettingsRequest, dict]): + The request object. Request for + [GetGenerativeSettings][google.cloud.dialogflow.cx.v3.Agents.GetGenerativeSettings] + RPC. + name (str): + Required. Format: + ``projects//locations//agents//generativeSettings``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (str): + Required. Language code of the + generative settings. + + This corresponds to the ``language_code`` 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.dialogflowcx_v3.types.GenerativeSettings: + Settings for Generative AI. + """ + # 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([name, language_code]) + 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 agent.GetGenerativeSettingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, agent.GetGenerativeSettingsRequest): + request = agent.GetGenerativeSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if language_code is not None: + request.language_code = language_code + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_generative_settings] + + # 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, + ) + + # Done; return the response. + return response + + def update_generative_settings( + self, + request: Optional[Union[agent.UpdateGenerativeSettingsRequest, dict]] = None, + *, + generative_settings: Optional[ + gcdc_generative_settings.GenerativeSettings + ] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_generative_settings.GenerativeSettings: + r"""Updates the generative settings for the agent. + + .. code-block:: python + + # 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 dialogflowcx_v3 + + def sample_update_generative_settings(): + # Create a client + client = dialogflowcx_v3.AgentsClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.UpdateGenerativeSettingsRequest( + ) + + # Make the request + response = client.update_generative_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.UpdateGenerativeSettingsRequest, dict]): + The request object. Request for + [UpdateGenerativeSettings][google.cloud.dialogflow.cx.v3.Agents.UpdateGenerativeSettings] + RPC. + generative_settings (google.cloud.dialogflowcx_v3.types.GenerativeSettings): + Required. Generative settings to + update. + + This corresponds to the ``generative_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The mask to control which + fields get updated. If the mask is not + present, all fields will be updated. + + This corresponds to the ``update_mask`` 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.dialogflowcx_v3.types.GenerativeSettings: + Settings for Generative AI. + """ + # 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([generative_settings, update_mask]) + 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 agent.UpdateGenerativeSettingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, agent.UpdateGenerativeSettingsRequest): + request = agent.UpdateGenerativeSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if generative_settings is not None: + request.generative_settings = generative_settings + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.update_generative_settings + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("generative_settings.name", request.generative_settings.name),) + ), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "AgentsClient": return self diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/agents/transports/base.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/agents/transports/base.py index ba647b7e8aa8..5ff14471cf92 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/agents/transports/base.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/agents/transports/base.py @@ -28,8 +28,12 @@ from google.protobuf import empty_pb2 # type: ignore from google.cloud.dialogflowcx_v3 import gapic_version as package_version +from google.cloud.dialogflowcx_v3.types import ( + generative_settings as gcdc_generative_settings, +) from google.cloud.dialogflowcx_v3.types import agent from google.cloud.dialogflowcx_v3.types import agent as gcdc_agent +from google.cloud.dialogflowcx_v3.types import generative_settings DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=package_version.__version__ @@ -183,6 +187,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_generative_settings: gapic_v1.method.wrap_method( + self.get_generative_settings, + default_timeout=None, + client_info=client_info, + ), + self.update_generative_settings: gapic_v1.method.wrap_method( + self.update_generative_settings, + default_timeout=None, + client_info=client_info, + ), } def close(self): @@ -276,6 +290,30 @@ def get_agent_validation_result( ]: raise NotImplementedError() + @property + def get_generative_settings( + self, + ) -> Callable[ + [agent.GetGenerativeSettingsRequest], + Union[ + generative_settings.GenerativeSettings, + Awaitable[generative_settings.GenerativeSettings], + ], + ]: + raise NotImplementedError() + + @property + def update_generative_settings( + self, + ) -> Callable[ + [agent.UpdateGenerativeSettingsRequest], + Union[ + gcdc_generative_settings.GenerativeSettings, + Awaitable[gcdc_generative_settings.GenerativeSettings], + ], + ]: + raise NotImplementedError() + @property def list_operations( self, diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/agents/transports/grpc.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/agents/transports/grpc.py index 7bb5d3226adf..d2d981fb64ce 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/agents/transports/grpc.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/agents/transports/grpc.py @@ -25,8 +25,12 @@ from google.protobuf import empty_pb2 # type: ignore import grpc # type: ignore +from google.cloud.dialogflowcx_v3.types import ( + generative_settings as gcdc_generative_settings, +) from google.cloud.dialogflowcx_v3.types import agent from google.cloud.dialogflowcx_v3.types import agent as gcdc_agent +from google.cloud.dialogflowcx_v3.types import generative_settings from .base import DEFAULT_CLIENT_INFO, AgentsTransport @@ -518,6 +522,63 @@ def get_agent_validation_result( ) return self._stubs["get_agent_validation_result"] + @property + def get_generative_settings( + self, + ) -> Callable[ + [agent.GetGenerativeSettingsRequest], generative_settings.GenerativeSettings + ]: + r"""Return a callable for the get generative settings method over gRPC. + + Gets the generative settings for the agent. + + Returns: + Callable[[~.GetGenerativeSettingsRequest], + ~.GenerativeSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_generative_settings" not in self._stubs: + self._stubs["get_generative_settings"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Agents/GetGenerativeSettings", + request_serializer=agent.GetGenerativeSettingsRequest.serialize, + response_deserializer=generative_settings.GenerativeSettings.deserialize, + ) + return self._stubs["get_generative_settings"] + + @property + def update_generative_settings( + self, + ) -> Callable[ + [agent.UpdateGenerativeSettingsRequest], + gcdc_generative_settings.GenerativeSettings, + ]: + r"""Return a callable for the update generative settings method over gRPC. + + Updates the generative settings for the agent. + + Returns: + Callable[[~.UpdateGenerativeSettingsRequest], + ~.GenerativeSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_generative_settings" not in self._stubs: + self._stubs["update_generative_settings"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Agents/UpdateGenerativeSettings", + request_serializer=agent.UpdateGenerativeSettingsRequest.serialize, + response_deserializer=gcdc_generative_settings.GenerativeSettings.deserialize, + ) + return self._stubs["update_generative_settings"] + def close(self): self.grpc_channel.close() diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/agents/transports/grpc_asyncio.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/agents/transports/grpc_asyncio.py index b125d4c33fbe..88a25d9f9da1 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/agents/transports/grpc_asyncio.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/agents/transports/grpc_asyncio.py @@ -25,8 +25,12 @@ import grpc # type: ignore from grpc.experimental import aio # type: ignore +from google.cloud.dialogflowcx_v3.types import ( + generative_settings as gcdc_generative_settings, +) from google.cloud.dialogflowcx_v3.types import agent from google.cloud.dialogflowcx_v3.types import agent as gcdc_agent +from google.cloud.dialogflowcx_v3.types import generative_settings from .base import DEFAULT_CLIENT_INFO, AgentsTransport from .grpc import AgentsGrpcTransport @@ -527,6 +531,64 @@ def get_agent_validation_result( ) return self._stubs["get_agent_validation_result"] + @property + def get_generative_settings( + self, + ) -> Callable[ + [agent.GetGenerativeSettingsRequest], + Awaitable[generative_settings.GenerativeSettings], + ]: + r"""Return a callable for the get generative settings method over gRPC. + + Gets the generative settings for the agent. + + Returns: + Callable[[~.GetGenerativeSettingsRequest], + Awaitable[~.GenerativeSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_generative_settings" not in self._stubs: + self._stubs["get_generative_settings"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Agents/GetGenerativeSettings", + request_serializer=agent.GetGenerativeSettingsRequest.serialize, + response_deserializer=generative_settings.GenerativeSettings.deserialize, + ) + return self._stubs["get_generative_settings"] + + @property + def update_generative_settings( + self, + ) -> Callable[ + [agent.UpdateGenerativeSettingsRequest], + Awaitable[gcdc_generative_settings.GenerativeSettings], + ]: + r"""Return a callable for the update generative settings method over gRPC. + + Updates the generative settings for the agent. + + Returns: + Callable[[~.UpdateGenerativeSettingsRequest], + Awaitable[~.GenerativeSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_generative_settings" not in self._stubs: + self._stubs["update_generative_settings"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Agents/UpdateGenerativeSettings", + request_serializer=agent.UpdateGenerativeSettingsRequest.serialize, + response_deserializer=gcdc_generative_settings.GenerativeSettings.deserialize, + ) + return self._stubs["update_generative_settings"] + def close(self): return self.grpc_channel.close() diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/agents/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/agents/transports/rest.py index 51b3e5a29a95..1619d5e3d56a 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/agents/transports/rest.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/agents/transports/rest.py @@ -47,8 +47,12 @@ from google.longrunning import operations_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore +from google.cloud.dialogflowcx_v3.types import ( + generative_settings as gcdc_generative_settings, +) from google.cloud.dialogflowcx_v3.types import agent from google.cloud.dialogflowcx_v3.types import agent as gcdc_agent +from google.cloud.dialogflowcx_v3.types import generative_settings from .base import AgentsTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO @@ -111,6 +115,14 @@ def post_get_agent_validation_result(self, response): logging.log(f"Received response: {response}") return response + def pre_get_generative_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_generative_settings(self, response): + logging.log(f"Received response: {response}") + return response + def pre_list_agents(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -135,6 +147,14 @@ def post_update_agent(self, response): logging.log(f"Received response: {response}") return response + def pre_update_generative_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_generative_settings(self, response): + logging.log(f"Received response: {response}") + return response + def pre_validate_agent(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -243,6 +263,29 @@ def post_get_agent_validation_result( """ return response + def pre_get_generative_settings( + self, + request: agent.GetGenerativeSettingsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[agent.GetGenerativeSettingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_generative_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the Agents server. + """ + return request, metadata + + def post_get_generative_settings( + self, response: generative_settings.GenerativeSettings + ) -> generative_settings.GenerativeSettings: + """Post-rpc interceptor for get_generative_settings + + Override in a subclass to manipulate the response + after it is returned by the Agents server but before + it is returned to user code. + """ + return response + def pre_list_agents( self, request: agent.ListAgentsRequest, metadata: Sequence[Tuple[str, str]] ) -> Tuple[agent.ListAgentsRequest, Sequence[Tuple[str, str]]]: @@ -306,6 +349,29 @@ def post_update_agent(self, response: gcdc_agent.Agent) -> gcdc_agent.Agent: """ return response + def pre_update_generative_settings( + self, + request: agent.UpdateGenerativeSettingsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[agent.UpdateGenerativeSettingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_generative_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the Agents server. + """ + return request, metadata + + def post_update_generative_settings( + self, response: gcdc_generative_settings.GenerativeSettings + ) -> gcdc_generative_settings.GenerativeSettings: + """Post-rpc interceptor for update_generative_settings + + Override in a subclass to manipulate the response + after it is returned by the Agents server but before + it is returned to user code. + """ + return response + def pre_validate_agent( self, request: agent.ValidateAgentRequest, metadata: Sequence[Tuple[str, str]] ) -> Tuple[agent.ValidateAgentRequest, Sequence[Tuple[str, str]]]: @@ -1071,6 +1137,98 @@ def __call__( resp = self._interceptor.post_get_agent_validation_result(resp) return resp + class _GetGenerativeSettings(AgentsRestStub): + def __hash__(self): + return hash("GetGenerativeSettings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "languageCode": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: agent.GetGenerativeSettingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> generative_settings.GenerativeSettings: + r"""Call the get generative settings method over HTTP. + + Args: + request (~.agent.GetGenerativeSettingsRequest): + The request object. Request for + [GetGenerativeSettings][google.cloud.dialogflow.cx.v3.Agents.GetGenerativeSettings] + RPC. + 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: + ~.generative_settings.GenerativeSettings: + Settings for Generative AI. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{name=projects/*/locations/*/agents/*/generativeSettings}", + }, + ] + request, metadata = self._interceptor.pre_get_generative_settings( + request, metadata + ) + pb_request = agent.GetGenerativeSettingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = generative_settings.GenerativeSettings() + pb_resp = generative_settings.GenerativeSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_generative_settings(resp) + return resp + class _ListAgents(AgentsRestStub): def __hash__(self): return hash("ListAgents") @@ -1367,6 +1525,106 @@ def __call__( resp = self._interceptor.post_update_agent(resp) return resp + class _UpdateGenerativeSettings(AgentsRestStub): + def __hash__(self): + return hash("UpdateGenerativeSettings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: agent.UpdateGenerativeSettingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_generative_settings.GenerativeSettings: + r"""Call the update generative + settings method over HTTP. + + Args: + request (~.agent.UpdateGenerativeSettingsRequest): + The request object. Request for + [UpdateGenerativeSettings][google.cloud.dialogflow.cx.v3.Agents.UpdateGenerativeSettings] + RPC. + 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: + ~.gcdc_generative_settings.GenerativeSettings: + Settings for Generative AI. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v3/{generative_settings.name=projects/*/locations/*/agents/*/generativeSettings}", + "body": "generative_settings", + }, + ] + request, metadata = self._interceptor.pre_update_generative_settings( + request, metadata + ) + pb_request = agent.UpdateGenerativeSettingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcdc_generative_settings.GenerativeSettings() + pb_resp = gcdc_generative_settings.GenerativeSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_generative_settings(resp) + return resp + class _ValidateAgent(AgentsRestStub): def __hash__(self): return hash("ValidateAgent") @@ -1501,6 +1759,16 @@ def get_agent_validation_result( # In C++ this would require a dynamic_cast return self._GetAgentValidationResult(self._session, self._host, self._interceptor) # type: ignore + @property + def get_generative_settings( + self, + ) -> Callable[ + [agent.GetGenerativeSettingsRequest], generative_settings.GenerativeSettings + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetGenerativeSettings(self._session, self._host, self._interceptor) # type: ignore + @property def list_agents( self, @@ -1525,6 +1793,17 @@ def update_agent( # In C++ this would require a dynamic_cast return self._UpdateAgent(self._session, self._host, self._interceptor) # type: ignore + @property + def update_generative_settings( + self, + ) -> Callable[ + [agent.UpdateGenerativeSettingsRequest], + gcdc_generative_settings.GenerativeSettings, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateGenerativeSettings(self._session, self._host, self._interceptor) # type: ignore + @property def validate_agent( self, diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/__init__.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/__init__.py index fa88667b4061..b72780f5f9f7 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/__init__.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/__init__.py @@ -23,11 +23,13 @@ ExportAgentResponse, GetAgentRequest, GetAgentValidationResultRequest, + GetGenerativeSettingsRequest, ListAgentsRequest, ListAgentsResponse, RestoreAgentRequest, SpeechToTextSettings, UpdateAgentRequest, + UpdateGenerativeSettingsRequest, ValidateAgentRequest, ) from .audio_config import ( @@ -48,6 +50,7 @@ ListChangelogsRequest, ListChangelogsResponse, ) +from .data_store_connection import DataStoreConnection, DataStoreType from .deployment import ( Deployment, GetDeploymentRequest, @@ -119,6 +122,7 @@ ) from .fulfillment import Fulfillment from .gcs import GcsDestination +from .generative_settings import GenerativeSettings from .intent import ( CreateIntentRequest, DeleteIntentRequest, @@ -135,6 +139,7 @@ EventHandler, Form, GetPageRequest, + KnowledgeConnectorSettings, ListPagesRequest, ListPagesResponse, Page, @@ -142,6 +147,7 @@ UpdatePageRequest, ) from .response_message import ResponseMessage +from .safety_settings import SafetySettings from .security_settings import ( CreateSecuritySettingsRequest, DeleteSecuritySettingsRequest, @@ -265,11 +271,13 @@ "ExportAgentResponse", "GetAgentRequest", "GetAgentValidationResultRequest", + "GetGenerativeSettingsRequest", "ListAgentsRequest", "ListAgentsResponse", "RestoreAgentRequest", "SpeechToTextSettings", "UpdateAgentRequest", + "UpdateGenerativeSettingsRequest", "ValidateAgentRequest", "InputAudioConfig", "OutputAudioConfig", @@ -285,6 +293,8 @@ "GetChangelogRequest", "ListChangelogsRequest", "ListChangelogsResponse", + "DataStoreConnection", + "DataStoreType", "Deployment", "GetDeploymentRequest", "ListDeploymentsRequest", @@ -346,6 +356,7 @@ "ValidateFlowRequest", "Fulfillment", "GcsDestination", + "GenerativeSettings", "ImportStrategy", "CreateIntentRequest", "DeleteIntentRequest", @@ -360,12 +371,14 @@ "EventHandler", "Form", "GetPageRequest", + "KnowledgeConnectorSettings", "ListPagesRequest", "ListPagesResponse", "Page", "TransitionRoute", "UpdatePageRequest", "ResponseMessage", + "SafetySettings", "CreateSecuritySettingsRequest", "DeleteSecuritySettingsRequest", "GetSecuritySettingsRequest", diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/agent.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/agent.py index 02894a8627d7..96c1e740980a 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/agent.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/agent.py @@ -23,6 +23,9 @@ from google.cloud.dialogflowcx_v3.types import ( advanced_settings as gcdc_advanced_settings, ) +from google.cloud.dialogflowcx_v3.types import ( + generative_settings as gcdc_generative_settings, +) from google.cloud.dialogflowcx_v3.types import audio_config, flow __protobuf__ = proto.module( @@ -42,6 +45,8 @@ "ValidateAgentRequest", "GetAgentValidationResultRequest", "AgentValidationResult", + "GetGenerativeSettingsRequest", + "UpdateGenerativeSettingsRequest", }, ) @@ -76,6 +81,9 @@ class Agent(proto.Message): [TransitionRouteGroups][google.cloud.dialogflow.cx.v3.TransitionRouteGroup] and so on to manage the conversation flows. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: name (str): The unique identifier of the agent. Required for the @@ -147,6 +155,10 @@ class Agent(proto.Message): Settings on instructing the speech synthesizer on how to generate the output audio content. + gen_app_builder_settings (google.cloud.dialogflowcx_v3.types.Agent.GenAppBuilderSettings): + Gen App Builder-related agent-level settings. + + This field is a member of `oneof`_ ``_gen_app_builder_settings``. """ class GitIntegrationSettings(proto.Message): @@ -210,6 +222,21 @@ class GithubSettings(proto.Message): message="Agent.GitIntegrationSettings.GithubSettings", ) + class GenAppBuilderSettings(proto.Message): + r"""Settings for Gen App Builder. + + Attributes: + engine (str): + Required. The full name of the Gen App Builder engine + related to this agent if there is one. Format: + ``projects/{Project ID}/locations/{Location ID}/collections/{Collection ID}/engines/{Engine ID}`` + """ + + engine: str = proto.Field( + proto.STRING, + number=1, + ) + name: str = proto.Field( proto.STRING, number=1, @@ -278,6 +305,12 @@ class GithubSettings(proto.Message): number=31, message=audio_config.TextToSpeechSettings, ) + gen_app_builder_settings: GenAppBuilderSettings = proto.Field( + proto.MESSAGE, + number=33, + optional=True, + message=GenAppBuilderSettings, + ) class ListAgentsRequest(proto.Message): @@ -738,4 +771,54 @@ class AgentValidationResult(proto.Message): ) +class GetGenerativeSettingsRequest(proto.Message): + r"""Request for + [GetGenerativeSettings][google.cloud.dialogflow.cx.v3.Agents.GetGenerativeSettings] + RPC. + + Attributes: + name (str): + Required. Format: + ``projects//locations//agents//generativeSettings``. + language_code (str): + Required. Language code of the generative + settings. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + language_code: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateGenerativeSettingsRequest(proto.Message): + r"""Request for + [UpdateGenerativeSettings][google.cloud.dialogflow.cx.v3.Agents.UpdateGenerativeSettings] + RPC. + + Attributes: + generative_settings (google.cloud.dialogflowcx_v3.types.GenerativeSettings): + Required. Generative settings to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The mask to control which fields + get updated. If the mask is not present, all + fields will be updated. + """ + + generative_settings: gcdc_generative_settings.GenerativeSettings = proto.Field( + proto.MESSAGE, + number=1, + message=gcdc_generative_settings.GenerativeSettings, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/data_store_connection.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/data_store_connection.py new file mode 100644 index 000000000000..5dc9c9f33e29 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/data_store_connection.py @@ -0,0 +1,80 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.dialogflow.cx.v3", + manifest={ + "DataStoreType", + "DataStoreConnection", + }, +) + + +class DataStoreType(proto.Enum): + r"""Type of a data store. + Determines how search is performed in the data store. + + Values: + DATA_STORE_TYPE_UNSPECIFIED (0): + Not specified. This value indicates that the + data store type is not specified, so it will not + be used during search. + PUBLIC_WEB (1): + A data store that contains public web + content. + UNSTRUCTURED (2): + A data store that contains unstructured + private data. + STRUCTURED (3): + A data store that contains structured data + (for example FAQ). + """ + DATA_STORE_TYPE_UNSPECIFIED = 0 + PUBLIC_WEB = 1 + UNSTRUCTURED = 2 + STRUCTURED = 3 + + +class DataStoreConnection(proto.Message): + r"""A data store connection. It represents a data store in + Discovery Engine and the type of the contents it contains. + + Attributes: + data_store_type (google.cloud.dialogflowcx_v3.types.DataStoreType): + The type of the connected data store. + data_store (str): + The full name of the referenced data store. Formats: + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}`` + ``projects/{project}/locations/{location}/dataStores/{data_store}`` + """ + + data_store_type: "DataStoreType" = proto.Field( + proto.ENUM, + number=1, + enum="DataStoreType", + ) + data_store: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/flow.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/flow.py index 4a578928f178..88755b20e9ba 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/flow.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/flow.py @@ -198,6 +198,8 @@ class Flow(proto.Message): for agent-level groups. nlu_settings (google.cloud.dialogflowcx_v3.types.NluSettings): NLU related settings of the flow. + knowledge_connector_settings (google.cloud.dialogflowcx_v3.types.KnowledgeConnectorSettings): + Optional. Knowledge connector configuration. """ name: str = proto.Field( @@ -231,6 +233,11 @@ class Flow(proto.Message): number=11, message="NluSettings", ) + knowledge_connector_settings: page.KnowledgeConnectorSettings = proto.Field( + proto.MESSAGE, + number=18, + message=page.KnowledgeConnectorSettings, + ) class CreateFlowRequest(proto.Message): diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/generative_settings.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/generative_settings.py new file mode 100644 index 000000000000..da0f15209b73 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/generative_settings.py @@ -0,0 +1,176 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.dialogflowcx_v3.types import safety_settings + +__protobuf__ = proto.module( + package="google.cloud.dialogflow.cx.v3", + manifest={ + "GenerativeSettings", + }, +) + + +class GenerativeSettings(proto.Message): + r"""Settings for Generative AI. + + Attributes: + name (str): + Format: + ``projects//locations//agents//generativeSettings``. + fallback_settings (google.cloud.dialogflowcx_v3.types.GenerativeSettings.FallbackSettings): + Settings for Generative Fallback. + generative_safety_settings (google.cloud.dialogflowcx_v3.types.SafetySettings): + Settings for Generative Safety. + knowledge_connector_settings (google.cloud.dialogflowcx_v3.types.GenerativeSettings.KnowledgeConnectorSettings): + Settings for knowledge connector. + language_code (str): + Language for this settings. + """ + + class FallbackSettings(proto.Message): + r"""Settings for Generative Fallback. + + Attributes: + selected_prompt (str): + Display name of the selected prompt. + prompt_templates (MutableSequence[google.cloud.dialogflowcx_v3.types.GenerativeSettings.FallbackSettings.PromptTemplate]): + Stored prompts that can be selected, for + example default templates like "conservative" or + "chatty", or user defined ones. + """ + + class PromptTemplate(proto.Message): + r"""Prompt template. + + Attributes: + display_name (str): + Prompt name. + prompt_text (str): + Prompt text that is sent to a LLM on no-match + default, placeholders are filled downstream. For + example: "Here is a conversation $conversation, + a response is: ". + frozen (bool): + If the flag is true, the prompt is frozen and + cannot be modified by users. + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + prompt_text: str = proto.Field( + proto.STRING, + number=2, + ) + frozen: bool = proto.Field( + proto.BOOL, + number=3, + ) + + selected_prompt: str = proto.Field( + proto.STRING, + number=3, + ) + prompt_templates: MutableSequence[ + "GenerativeSettings.FallbackSettings.PromptTemplate" + ] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message="GenerativeSettings.FallbackSettings.PromptTemplate", + ) + + class KnowledgeConnectorSettings(proto.Message): + r"""Settings for knowledge connector. These parameters are used for LLM + prompt like "You are . You are a helpful and verbose + at , . Your task is to help + humans on ". + + Attributes: + business (str): + Name of the company, organization or other + entity that the agent represents. Used for + knowledge connector LLM prompt and for knowledge + search. + agent (str): + Name of the virtual agent. Used for LLM + prompt. Can be left empty. + agent_identity (str): + Identity of the agent, e.g. "virtual agent", + "AI assistant". + business_description (str): + Company description, used for LLM prompt, + e.g. "a family company selling freshly roasted + coffee beans". + agent_scope (str): + Agent scope, e.g. "Example company website", + "internal Example company website for + employees", "manual of car owner". + """ + + business: str = proto.Field( + proto.STRING, + number=1, + ) + agent: str = proto.Field( + proto.STRING, + number=2, + ) + agent_identity: str = proto.Field( + proto.STRING, + number=3, + ) + business_description: str = proto.Field( + proto.STRING, + number=4, + ) + agent_scope: str = proto.Field( + proto.STRING, + number=5, + ) + + name: str = proto.Field( + proto.STRING, + number=5, + ) + fallback_settings: FallbackSettings = proto.Field( + proto.MESSAGE, + number=1, + message=FallbackSettings, + ) + generative_safety_settings: safety_settings.SafetySettings = proto.Field( + proto.MESSAGE, + number=3, + message=safety_settings.SafetySettings, + ) + knowledge_connector_settings: KnowledgeConnectorSettings = proto.Field( + proto.MESSAGE, + number=7, + message=KnowledgeConnectorSettings, + ) + language_code: str = proto.Field( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/page.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/page.py index 492a70b881bd..323551e02028 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/page.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/page.py @@ -21,7 +21,7 @@ from google.protobuf import struct_pb2 # type: ignore import proto # type: ignore -from google.cloud.dialogflowcx_v3.types import fulfillment +from google.cloud.dialogflowcx_v3.types import data_store_connection, fulfillment __protobuf__ = proto.module( package="google.cloud.dialogflow.cx.v3", @@ -36,6 +36,7 @@ "CreatePageRequest", "UpdatePageRequest", "DeletePageRequest", + "KnowledgeConnectorSettings", }, ) @@ -81,8 +82,11 @@ class Page(proto.Message): transition_route_groups (MutableSequence[str]): Ordered list of [``TransitionRouteGroups``][google.cloud.dialogflow.cx.v3.TransitionRouteGroup] - associated with the page. Transition route groups must be - unique within a page. + added to the page. Transition route groups must be unique + within a page. If the page links both flow-level transition + route groups and agent-level transition route groups, the + flow-level ones will have higher priority and will be put + before the agent-level ones. - If multiple transition routes within a page scope refer to the same intent, then the precedence order is: page's @@ -123,6 +127,8 @@ class Page(proto.Message): Handlers associated with the page to handle events such as webhook errors, no match or no input. + knowledge_connector_settings (google.cloud.dialogflowcx_v3.types.KnowledgeConnectorSettings): + Optional. Knowledge connector configuration. """ name: str = proto.Field( @@ -157,6 +163,11 @@ class Page(proto.Message): number=10, message="EventHandler", ) + knowledge_connector_settings: "KnowledgeConnectorSettings" = proto.Field( + proto.MESSAGE, + number=18, + message="KnowledgeConnectorSettings", + ) class Form(proto.Message): @@ -418,6 +429,9 @@ class TransitionRoute(proto.Message): name (str): Output only. The unique identifier of this transition route. + description (str): + Optional. The description of the transition + route. The maximum length is 500 characters. intent (str): The unique identifier of an [Intent][google.cloud.dialogflow.cx.v3.Intent]. Format: @@ -460,6 +474,10 @@ class TransitionRoute(proto.Message): proto.STRING, number=6, ) + description: str = proto.Field( + proto.STRING, + number=8, + ) intent: str = proto.Field( proto.STRING, number=1, @@ -758,4 +776,72 @@ class DeletePageRequest(proto.Message): ) +class KnowledgeConnectorSettings(proto.Message): + r"""The Knowledge Connector settings for this page or flow. + This includes information such as the attached Knowledge Bases, + and the way to execute fulfillment. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + enabled (bool): + Whether Knowledge Connector is enabled or + not. + trigger_fulfillment (google.cloud.dialogflowcx_v3.types.Fulfillment): + The fulfillment to be triggered. + + When the answers from the Knowledge Connector are selected + by Dialogflow, you can utitlize the request scoped parameter + ``$request.knowledge.answers`` (contains up to the 5 highest + confidence answers) and ``$request.knowledge.questions`` + (contains the corresponding questions) to construct the + fulfillment. + target_page (str): + The target page to transition to. Format: + ``projects//locations//agents//flows//pages/``. + + This field is a member of `oneof`_ ``target``. + target_flow (str): + The target flow to transition to. Format: + ``projects//locations//agents//flows/``. + + This field is a member of `oneof`_ ``target``. + data_store_connections (MutableSequence[google.cloud.dialogflowcx_v3.types.DataStoreConnection]): + Optional. List of related data store + connections. + """ + + enabled: bool = proto.Field( + proto.BOOL, + number=1, + ) + trigger_fulfillment: fulfillment.Fulfillment = proto.Field( + proto.MESSAGE, + number=3, + message=fulfillment.Fulfillment, + ) + target_page: str = proto.Field( + proto.STRING, + number=4, + oneof="target", + ) + target_flow: str = proto.Field( + proto.STRING, + number=5, + oneof="target", + ) + data_store_connections: MutableSequence[ + data_store_connection.DataStoreConnection + ] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=data_store_connection.DataStoreConnection, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/response_message.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/response_message.py index 591e92aead47..5e0d03046896 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/response_message.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/response_message.py @@ -115,6 +115,11 @@ class ResponseMessage(proto.Message): phone call connected to this agent to a third-party endpoint. + This field is a member of `oneof`_ ``message``. + knowledge_info_card (google.cloud.dialogflowcx_v3.types.ResponseMessage.KnowledgeInfoCard): + Represents info card for knowledge answers, + to be better rendered in Dialogflow Messenger. + This field is a member of `oneof`_ ``message``. response_type (google.cloud.dialogflowcx_v3.types.ResponseMessage.ResponseType): Response type. @@ -398,6 +403,15 @@ class TelephonyTransferCall(proto.Message): oneof="endpoint", ) + class KnowledgeInfoCard(proto.Message): + r"""Represents info card response. If the response contains + generative knowledge prediction, Dialogflow will return a + payload with Infobot Messenger compatible info card. + + Otherwise, the info card response is skipped. + + """ + text: Text = proto.Field( proto.MESSAGE, number=1, @@ -452,6 +466,12 @@ class TelephonyTransferCall(proto.Message): oneof="message", message=TelephonyTransferCall, ) + knowledge_info_card: KnowledgeInfoCard = proto.Field( + proto.MESSAGE, + number=20, + oneof="message", + message=KnowledgeInfoCard, + ) response_type: ResponseType = proto.Field( proto.ENUM, number=4, diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/safety_settings.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/safety_settings.py new file mode 100644 index 000000000000..94564929eb8d --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/safety_settings.py @@ -0,0 +1,65 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.dialogflow.cx.v3", + manifest={ + "SafetySettings", + }, +) + + +class SafetySettings(proto.Message): + r"""Settings for Generative Safety. + + Attributes: + banned_phrases (MutableSequence[google.cloud.dialogflowcx_v3.types.SafetySettings.Phrase]): + Banned phrases for generated text. + """ + + class Phrase(proto.Message): + r"""Text input which can be used for prompt or banned phrases. + + Attributes: + text (str): + Required. Text input which can be used for + prompt or banned phrases. + language_code (str): + Required. Language code of the phrase. + """ + + text: str = proto.Field( + proto.STRING, + number=1, + ) + language_code: str = proto.Field( + proto.STRING, + number=2, + ) + + banned_phrases: MutableSequence[Phrase] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Phrase, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/security_settings.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/security_settings.py index b6c6a21d9873..85914fbedb4a 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/security_settings.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/security_settings.py @@ -179,6 +179,10 @@ class SecuritySettings(proto.Message): on the settings to propagate to all the related components and take effect. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -248,6 +252,11 @@ class SecuritySettings(proto.Message): that has no effect. A missing value or setting to 0 also means we use default TTL. + This field is a member of `oneof`_ ``data_retention``. + retention_strategy (google.cloud.dialogflowcx_v3.types.SecuritySettings.RetentionStrategy): + Specifies the retention behavior defined by + [SecuritySettings.RetentionStrategy][google.cloud.dialogflow.cx.v3.SecuritySettings.RetentionStrategy]. + This field is a member of `oneof`_ ``data_retention``. purge_data_types (MutableSequence[google.cloud.dialogflowcx_v3.types.SecuritySettings.PurgeDataType]): List of types of data to remove when @@ -311,6 +320,23 @@ class RedactionScope(proto.Enum): REDACTION_SCOPE_UNSPECIFIED = 0 REDACT_DISK_STORAGE = 2 + class RetentionStrategy(proto.Enum): + r"""Defines how long we retain persisted data that contains + sensitive info. + + Values: + RETENTION_STRATEGY_UNSPECIFIED (0): + Retains the persisted data with Dialogflow's + internal default 365d TTLs. + REMOVE_AFTER_CONVERSATION (1): + Removes data when the conversation ends. If there is no + [Conversation][] explicitly established, a default + conversation ends when the corresponding Dialogflow session + ends. + """ + RETENTION_STRATEGY_UNSPECIFIED = 0 + REMOVE_AFTER_CONVERSATION = 1 + class PurgeDataType(proto.Enum): r"""Type of data we purge after retention settings triggers purge. @@ -431,6 +457,12 @@ class InsightsExportSettings(proto.Message): number=6, oneof="data_retention", ) + retention_strategy: RetentionStrategy = proto.Field( + proto.ENUM, + number=7, + oneof="data_retention", + enum=RetentionStrategy, + ) purge_data_types: MutableSequence[PurgeDataType] = proto.RepeatedField( proto.ENUM, number=8, diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/session.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/session.py index aa0267443f1e..d1e353276691 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/session.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/session.py @@ -341,8 +341,10 @@ class CloudConversationDebuggingInfo(proto.Message): Time offset of the end-of-single-utterance signal relative to the beginning of the stream. no_speech_timeout (google.protobuf.duration_pb2.Duration): - No speech timeout settings observed at - runtime. + No speech timeout settings for the stream. + endpointing_timeout (google.protobuf.duration_pb2.Duration): + Speech endpointing timeout settings for the + stream. is_input_text (bool): Whether the streaming terminates with an injected text query. @@ -426,6 +428,11 @@ class CloudConversationDebuggingInfo(proto.Message): number=15, message=duration_pb2.Duration, ) + endpointing_timeout: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=19, + message=duration_pb2.Duration, + ) is_input_text: bool = proto.Field( proto.BOOL, number=16, diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/validation_message.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/validation_message.py index ccf26016192c..6d109d642f2a 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/validation_message.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/validation_message.py @@ -79,6 +79,8 @@ class ResourceType(proto.Enum): Multiple pages. TRANSITION_ROUTE_GROUP (7): Transition route group. + AGENT_TRANSITION_ROUTE_GROUP (14): + Agent transition route group. """ RESOURCE_TYPE_UNSPECIFIED = 0 AGENT = 1 @@ -94,6 +96,7 @@ class ResourceType(proto.Enum): PAGE = 6 PAGES = 13 TRANSITION_ROUTE_GROUP = 7 + AGENT_TRANSITION_ROUTE_GROUP = 14 class Severity(proto.Enum): r"""Severity level. diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_agents_get_generative_settings_async.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_agents_get_generative_settings_async.py new file mode 100644 index 000000000000..5b7d03775863 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_agents_get_generative_settings_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetGenerativeSettings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Agents_GetGenerativeSettings_async] +# 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 dialogflowcx_v3 + + +async def sample_get_generative_settings(): + # Create a client + client = dialogflowcx_v3.AgentsAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.GetGenerativeSettingsRequest( + name="name_value", + language_code="language_code_value", + ) + + # Make the request + response = await client.get_generative_settings(request=request) + + # Handle the response + print(response) + +# [END dialogflow_v3_generated_Agents_GetGenerativeSettings_async] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_agents_get_generative_settings_sync.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_agents_get_generative_settings_sync.py new file mode 100644 index 000000000000..99105f833213 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_agents_get_generative_settings_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetGenerativeSettings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Agents_GetGenerativeSettings_sync] +# 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 dialogflowcx_v3 + + +def sample_get_generative_settings(): + # Create a client + client = dialogflowcx_v3.AgentsClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.GetGenerativeSettingsRequest( + name="name_value", + language_code="language_code_value", + ) + + # Make the request + response = client.get_generative_settings(request=request) + + # Handle the response + print(response) + +# [END dialogflow_v3_generated_Agents_GetGenerativeSettings_sync] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_agents_update_generative_settings_async.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_agents_update_generative_settings_async.py new file mode 100644 index 000000000000..084578c93e48 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_agents_update_generative_settings_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateGenerativeSettings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Agents_UpdateGenerativeSettings_async] +# 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 dialogflowcx_v3 + + +async def sample_update_generative_settings(): + # Create a client + client = dialogflowcx_v3.AgentsAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.UpdateGenerativeSettingsRequest( + ) + + # Make the request + response = await client.update_generative_settings(request=request) + + # Handle the response + print(response) + +# [END dialogflow_v3_generated_Agents_UpdateGenerativeSettings_async] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_agents_update_generative_settings_sync.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_agents_update_generative_settings_sync.py new file mode 100644 index 000000000000..818781156fcb --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_agents_update_generative_settings_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateGenerativeSettings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Agents_UpdateGenerativeSettings_sync] +# 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 dialogflowcx_v3 + + +def sample_update_generative_settings(): + # Create a client + client = dialogflowcx_v3.AgentsClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.UpdateGenerativeSettingsRequest( + ) + + # Make the request + response = client.update_generative_settings(request=request) + + # Handle the response + print(response) + +# [END dialogflow_v3_generated_Agents_UpdateGenerativeSettings_sync] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.cx.v3.json b/packages/google-cloud-dialogflow-cx/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.cx.v3.json index 4fe8e9ba4fd5..396bb3bbbe88 100644 --- a/packages/google-cloud-dialogflow-cx/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.cx.v3.json +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.cx.v3.json @@ -810,6 +810,175 @@ ], "title": "dialogflow_v3_generated_agents_get_agent_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflowcx_v3.AgentsAsyncClient", + "shortName": "AgentsAsyncClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.AgentsAsyncClient.get_generative_settings", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.Agents.GetGenerativeSettings", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.Agents", + "shortName": "Agents" + }, + "shortName": "GetGenerativeSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.GetGenerativeSettingsRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "language_code", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.types.GenerativeSettings", + "shortName": "get_generative_settings" + }, + "description": "Sample for GetGenerativeSettings", + "file": "dialogflow_v3_generated_agents_get_generative_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_Agents_GetGenerativeSettings_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_agents_get_generative_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflowcx_v3.AgentsClient", + "shortName": "AgentsClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.AgentsClient.get_generative_settings", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.Agents.GetGenerativeSettings", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.Agents", + "shortName": "Agents" + }, + "shortName": "GetGenerativeSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.GetGenerativeSettingsRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "language_code", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.types.GenerativeSettings", + "shortName": "get_generative_settings" + }, + "description": "Sample for GetGenerativeSettings", + "file": "dialogflow_v3_generated_agents_get_generative_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_Agents_GetGenerativeSettings_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_agents_get_generative_settings_sync.py" + }, { "canonical": true, "clientMethod": { @@ -1293,6 +1462,175 @@ ], "title": "dialogflow_v3_generated_agents_update_agent_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflowcx_v3.AgentsAsyncClient", + "shortName": "AgentsAsyncClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.AgentsAsyncClient.update_generative_settings", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.Agents.UpdateGenerativeSettings", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.Agents", + "shortName": "Agents" + }, + "shortName": "UpdateGenerativeSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.UpdateGenerativeSettingsRequest" + }, + { + "name": "generative_settings", + "type": "google.cloud.dialogflowcx_v3.types.GenerativeSettings" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.types.GenerativeSettings", + "shortName": "update_generative_settings" + }, + "description": "Sample for UpdateGenerativeSettings", + "file": "dialogflow_v3_generated_agents_update_generative_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_Agents_UpdateGenerativeSettings_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_agents_update_generative_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflowcx_v3.AgentsClient", + "shortName": "AgentsClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.AgentsClient.update_generative_settings", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.Agents.UpdateGenerativeSettings", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.Agents", + "shortName": "Agents" + }, + "shortName": "UpdateGenerativeSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.UpdateGenerativeSettingsRequest" + }, + { + "name": "generative_settings", + "type": "google.cloud.dialogflowcx_v3.types.GenerativeSettings" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.types.GenerativeSettings", + "shortName": "update_generative_settings" + }, + "description": "Sample for UpdateGenerativeSettings", + "file": "dialogflow_v3_generated_agents_update_generative_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_Agents_UpdateGenerativeSettings_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_agents_update_generative_settings_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-dialogflow-cx/scripts/fixup_dialogflowcx_v3_keywords.py b/packages/google-cloud-dialogflow-cx/scripts/fixup_dialogflowcx_v3_keywords.py index 5b56952f2f31..fd5c1515eb6f 100644 --- a/packages/google-cloud-dialogflow-cx/scripts/fixup_dialogflowcx_v3_keywords.py +++ b/packages/google-cloud-dialogflow-cx/scripts/fixup_dialogflowcx_v3_keywords.py @@ -83,6 +83,7 @@ class dialogflowcxCallTransformer(cst.CSTTransformer): 'get_experiment': ('name', ), 'get_flow': ('name', 'language_code', ), 'get_flow_validation_result': ('name', 'language_code', ), + 'get_generative_settings': ('name', 'language_code', ), 'get_intent': ('name', 'language_code', ), 'get_page': ('name', 'language_code', ), 'get_security_settings': ('name', ), @@ -126,6 +127,7 @@ class dialogflowcxCallTransformer(cst.CSTTransformer): 'update_environment': ('environment', 'update_mask', ), 'update_experiment': ('experiment', 'update_mask', ), 'update_flow': ('flow', 'update_mask', 'language_code', ), + 'update_generative_settings': ('generative_settings', 'update_mask', ), 'update_intent': ('intent', 'language_code', 'update_mask', ), 'update_page': ('page', 'language_code', 'update_mask', ), 'update_security_settings': ('security_settings', 'update_mask', ), diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_agents.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_agents.py index 0313f59a8c94..42caf0869127 100644 --- a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_agents.py +++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_agents.py @@ -62,10 +62,15 @@ pagers, transports, ) +from google.cloud.dialogflowcx_v3.types import ( + generative_settings as gcdc_generative_settings, +) from google.cloud.dialogflowcx_v3.types import advanced_settings from google.cloud.dialogflowcx_v3.types import agent from google.cloud.dialogflowcx_v3.types import agent as gcdc_agent from google.cloud.dialogflowcx_v3.types import audio_config, flow, gcs +from google.cloud.dialogflowcx_v3.types import generative_settings +from google.cloud.dialogflowcx_v3.types import safety_settings def client_cert_source_callback(): @@ -2843,205 +2848,733 @@ async def test_get_agent_validation_result_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - agent.ListAgentsRequest, + agent.GetGenerativeSettingsRequest, dict, ], ) -def test_list_agents_rest(request_type): +def test_get_generative_settings(request_type, transport: str = "grpc"): client = AgentsClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request = request_type(**request_init) + # 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 http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = agent.ListAgentsResponse( - next_page_token="next_page_token_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_generative_settings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = generative_settings.GenerativeSettings( + name="name_value", + language_code="language_code_value", ) + response = client.get_generative_settings(request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = agent.ListAgentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_agents(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == agent.GetGenerativeSettingsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAgentsPager) - assert response.next_page_token == "next_page_token_value" - + assert isinstance(response, generative_settings.GenerativeSettings) + assert response.name == "name_value" + assert response.language_code == "language_code_value" -def test_list_agents_rest_required_fields(request_type=agent.ListAgentsRequest): - transport_class = transports.AgentsRestTransport - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False, - ) +def test_get_generative_settings_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 = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - # verify fields with default values are dropped + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_generative_settings), "__call__" + ) as call: + client.get_generative_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent.GetGenerativeSettingsRequest() - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_agents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - # verify required fields with default values are now present +@pytest.mark.asyncio +async def test_get_generative_settings_async( + transport: str = "grpc_asyncio", request_type=agent.GetGenerativeSettingsRequest +): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - jsonified_request["parent"] = "parent_value" + # 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() - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_agents._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_generative_settings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + generative_settings.GenerativeSettings( + name="name_value", + language_code="language_code_value", + ) ) - ) - jsonified_request.update(unset_fields) + response = await client.get_generative_settings(request) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == agent.GetGenerativeSettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, generative_settings.GenerativeSettings) + assert response.name == "name_value" + assert response.language_code == "language_code_value" + + +@pytest.mark.asyncio +async def test_get_generative_settings_async_from_dict(): + await test_get_generative_settings_async(request_type=dict) + +def test_get_generative_settings_field_headers(): client = AgentsClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = agent.ListAgentsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "get", - "query_params": pb_request, - } - transcode.return_value = transcode_result - response_value = Response() - response_value.status_code = 200 + # 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 = agent.GetGenerativeSettingsRequest() - pb_return_value = agent.ListAgentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + request.name = "name_value" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_generative_settings), "__call__" + ) as call: + call.return_value = generative_settings.GenerativeSettings() + client.get_generative_settings(request) - response = client.list_agents(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 - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] -def test_list_agents_rest_unset_required_fields(): - transport = transports.AgentsRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.asyncio +async def test_get_generative_settings_field_headers_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), ) - unset_fields = transport.list_agents._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + # 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 = agent.GetGenerativeSettingsRequest() + request.name = "name_value" -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_agents_rest_interceptors(null_interceptor): - transport = transports.AgentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AgentsRestInterceptor(), - ) - client = AgentsClient(transport=transport) + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - transports.AgentsRestInterceptor, "post_list_agents" - ) as post, mock.patch.object( - transports.AgentsRestInterceptor, "pre_list_agents" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = agent.ListAgentsRequest.pb(agent.ListAgentsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = agent.ListAgentsResponse.to_json( - agent.ListAgentsResponse() + type(client.transport.get_generative_settings), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + generative_settings.GenerativeSettings() ) + await client.get_generative_settings(request) - request = agent.ListAgentsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = agent.ListAgentsResponse() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.list_agents( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_generative_settings_flattened(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_generative_settings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = generative_settings.GenerativeSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_generative_settings( + name="name_value", + language_code="language_code_value", ) - pre.assert_called_once() - post.assert_called_once() + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].language_code + mock_val = "language_code_value" + assert arg == mock_val -def test_list_agents_rest_bad_request( - transport: str = "rest", request_type=agent.ListAgentsRequest -): +def test_get_generative_settings_flattened_error(): client = AgentsClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request = request_type(**request_init) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_generative_settings( + agent.GetGenerativeSettingsRequest(), + name="name_value", + language_code="language_code_value", + ) + + +@pytest.mark.asyncio +async def test_get_generative_settings_flattened_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_generative_settings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = generative_settings.GenerativeSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + generative_settings.GenerativeSettings() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_generative_settings( + name="name_value", + language_code="language_code_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].language_code + mock_val = "language_code_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_generative_settings_flattened_error_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_generative_settings( + agent.GetGenerativeSettingsRequest(), + name="name_value", + language_code="language_code_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent.UpdateGenerativeSettingsRequest, + dict, + ], +) +def test_update_generative_settings(request_type, transport: str = "grpc"): + client = AgentsClient( + credentials=ga_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.update_generative_settings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_generative_settings.GenerativeSettings( + name="name_value", + language_code="language_code_value", + ) + response = client.update_generative_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == agent.UpdateGenerativeSettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_generative_settings.GenerativeSettings) + assert response.name == "name_value" + assert response.language_code == "language_code_value" + + +def test_update_generative_settings_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 = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_generative_settings), "__call__" + ) as call: + client.update_generative_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent.UpdateGenerativeSettingsRequest() + + +@pytest.mark.asyncio +async def test_update_generative_settings_async( + transport: str = "grpc_asyncio", request_type=agent.UpdateGenerativeSettingsRequest +): + client = AgentsAsyncClient( + credentials=ga_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.update_generative_settings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_generative_settings.GenerativeSettings( + name="name_value", + language_code="language_code_value", + ) + ) + response = await client.update_generative_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == agent.UpdateGenerativeSettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_generative_settings.GenerativeSettings) + assert response.name == "name_value" + assert response.language_code == "language_code_value" + + +@pytest.mark.asyncio +async def test_update_generative_settings_async_from_dict(): + await test_update_generative_settings_async(request_type=dict) + + +def test_update_generative_settings_field_headers(): + client = AgentsClient( + credentials=ga_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 = agent.UpdateGenerativeSettingsRequest() + + request.generative_settings.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_generative_settings), "__call__" + ) as call: + call.return_value = gcdc_generative_settings.GenerativeSettings() + client.update_generative_settings(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 field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "generative_settings.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_generative_settings_field_headers_async(): + client = AgentsAsyncClient( + credentials=ga_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 = agent.UpdateGenerativeSettingsRequest() + + request.generative_settings.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_generative_settings), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_generative_settings.GenerativeSettings() + ) + await client.update_generative_settings(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", + "generative_settings.name=name_value", + ) in kw["metadata"] + + +def test_update_generative_settings_flattened(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_generative_settings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_generative_settings.GenerativeSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_generative_settings( + generative_settings=gcdc_generative_settings.GenerativeSettings( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].generative_settings + mock_val = gcdc_generative_settings.GenerativeSettings(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_generative_settings_flattened_error(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_generative_settings( + agent.UpdateGenerativeSettingsRequest(), + generative_settings=gcdc_generative_settings.GenerativeSettings( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_generative_settings_flattened_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_generative_settings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_generative_settings.GenerativeSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_generative_settings.GenerativeSettings() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_generative_settings( + generative_settings=gcdc_generative_settings.GenerativeSettings( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].generative_settings + mock_val = gcdc_generative_settings.GenerativeSettings(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_generative_settings_flattened_error_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_generative_settings( + agent.UpdateGenerativeSettingsRequest(), + generative_settings=gcdc_generative_settings.GenerativeSettings( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent.ListAgentsRequest, + dict, + ], +) +def test_list_agents_rest(request_type): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = agent.ListAgentsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = agent.ListAgentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_agents(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAgentsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_agents_rest_required_fields(request_type=agent.ListAgentsRequest): + transport_class = transports.AgentsRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_agents._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_agents._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = agent.ListAgentsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = agent.ListAgentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_agents(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_agents_rest_unset_required_fields(): + transport = transports.AgentsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_agents._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_agents_rest_interceptors(null_interceptor): + transport = transports.AgentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AgentsRestInterceptor(), + ) + client = AgentsClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentsRestInterceptor, "post_list_agents" + ) as post, mock.patch.object( + transports.AgentsRestInterceptor, "pre_list_agents" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = agent.ListAgentsRequest.pb(agent.ListAgentsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = agent.ListAgentsResponse.to_json( + agent.ListAgentsResponse() + ) + + request = agent.ListAgentsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = agent.ListAgentsResponse() + + client.list_agents( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_agents_rest_bad_request( + transport: str = "rest", request_type=agent.ListAgentsRequest +): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. with mock.patch.object(Session, "request") as req, pytest.raises( @@ -3501,6 +4034,7 @@ def test_create_agent_rest(request_type): } }, "text_to_speech_settings": {"synthesize_speech_configs": {}}, + "gen_app_builder_settings": {"engine": "engine_value"}, } request = request_type(**request_init) @@ -3736,6 +4270,7 @@ def test_create_agent_rest_bad_request( } }, "text_to_speech_settings": {"synthesize_speech_configs": {}}, + "gen_app_builder_settings": {"engine": "engine_value"}, } request = request_type(**request_init) @@ -3865,6 +4400,7 @@ def test_update_agent_rest(request_type): } }, "text_to_speech_settings": {"synthesize_speech_configs": {}}, + "gen_app_builder_settings": {"engine": "engine_value"}, } request = request_type(**request_init) @@ -4091,6 +4627,7 @@ def test_update_agent_rest_bad_request( } }, "text_to_speech_settings": {"synthesize_speech_configs": {}}, + "gen_app_builder_settings": {"engine": "engine_value"}, } request = request_type(**request_init) @@ -4103,10 +4640,262 @@ def test_update_agent_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.update_agent(request) + client.update_agent(request) + + +def test_update_agent_rest_flattened(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcdc_agent.Agent() + + # get arguments that satisfy an http rule for this method + sample_request = { + "agent": {"name": "projects/sample1/locations/sample2/agents/sample3"} + } + + # get truthy value for each flattened field + mock_args = dict( + agent=gcdc_agent.Agent(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = gcdc_agent.Agent.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_agent(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v3/{agent.name=projects/*/locations/*/agents/*}" + % client.transport._host, + args[1], + ) + + +def test_update_agent_rest_flattened_error(transport: str = "rest"): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_agent( + gcdc_agent.UpdateAgentRequest(), + agent=gcdc_agent.Agent(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_agent_rest_error(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent.DeleteAgentRequest, + dict, + ], +) +def test_delete_agent_rest(request_type): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/agents/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_agent(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_agent_rest_required_fields(request_type=agent.DeleteAgentRequest): + transport_class = transports.AgentsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_agent._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_agent._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_agent(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_agent_rest_unset_required_fields(): + transport = transports.AgentsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_agent._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_agent_rest_interceptors(null_interceptor): + transport = transports.AgentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AgentsRestInterceptor(), + ) + client = AgentsClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentsRestInterceptor, "pre_delete_agent" + ) as pre: + pre.assert_not_called() + pb_message = agent.DeleteAgentRequest.pb(agent.DeleteAgentRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = agent.DeleteAgentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_agent( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_delete_agent_rest_bad_request( + transport: str = "rest", request_type=agent.DeleteAgentRequest +): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/agents/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_agent(request) -def test_update_agent_rest_flattened(): +def test_delete_agent_rest_flattened(): client = AgentsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -4115,42 +4904,37 @@ def test_update_agent_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = gcdc_agent.Agent() + return_value = None # get arguments that satisfy an http rule for this method - sample_request = { - "agent": {"name": "projects/sample1/locations/sample2/agents/sample3"} - } + sample_request = {"name": "projects/sample1/locations/sample2/agents/sample3"} # get truthy value for each flattened field mock_args = dict( - agent=gcdc_agent.Agent(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = gcdc_agent.Agent.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.update_agent(**mock_args) + client.delete_agent(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v3/{agent.name=projects/*/locations/*/agents/*}" - % client.transport._host, + "%s/v3/{name=projects/*/locations/*/agents/*}" % client.transport._host, args[1], ) -def test_update_agent_rest_flattened_error(transport: str = "rest"): +def test_delete_agent_rest_flattened_error(transport: str = "rest"): client = AgentsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4159,14 +4943,13 @@ def test_update_agent_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_agent( - gcdc_agent.UpdateAgentRequest(), - agent=gcdc_agent.Agent(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.delete_agent( + agent.DeleteAgentRequest(), + name="name_value", ) -def test_update_agent_rest_error(): +def test_delete_agent_rest_error(): client = AgentsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -4175,11 +4958,11 @@ def test_update_agent_rest_error(): @pytest.mark.parametrize( "request_type", [ - agent.DeleteAgentRequest, + agent.ExportAgentRequest, dict, ], ) -def test_delete_agent_rest(request_type): +def test_export_agent_rest(request_type): client = AgentsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -4192,22 +4975,22 @@ def test_delete_agent_rest(request_type): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_agent(request) + response = client.export_agent(request) # Establish that the response is the type that we expect. - assert response is None + assert response.operation.name == "operations/spam" -def test_delete_agent_rest_required_fields(request_type=agent.DeleteAgentRequest): +def test_export_agent_rest_required_fields(request_type=agent.ExportAgentRequest): transport_class = transports.AgentsRestTransport request_init = {} @@ -4226,7 +5009,7 @@ def test_delete_agent_rest_required_fields(request_type=agent.DeleteAgentRequest unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_agent._get_unset_required_fields(jsonified_request) + ).export_agent._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -4235,7 +5018,7 @@ def test_delete_agent_rest_required_fields(request_type=agent.DeleteAgentRequest unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_agent._get_unset_required_fields(jsonified_request) + ).export_agent._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -4249,7 +5032,7 @@ def test_delete_agent_rest_required_fields(request_type=agent.DeleteAgentRequest request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = None + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -4261,36 +5044,37 @@ def test_delete_agent_rest_required_fields(request_type=agent.DeleteAgentRequest pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_agent(request) + response = client.export_agent(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_agent_rest_unset_required_fields(): +def test_export_agent_rest_unset_required_fields(): transport = transports.AgentsRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_agent._get_unset_required_fields({}) + unset_fields = transport.export_agent._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_agent_rest_interceptors(null_interceptor): +def test_export_agent_rest_interceptors(null_interceptor): transport = transports.AgentsRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.AgentsRestInterceptor(), @@ -4301,10 +5085,15 @@ def test_delete_agent_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AgentsRestInterceptor, "pre_delete_agent" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.AgentsRestInterceptor, "post_export_agent" + ) as post, mock.patch.object( + transports.AgentsRestInterceptor, "pre_export_agent" ) as pre: pre.assert_not_called() - pb_message = agent.DeleteAgentRequest.pb(agent.DeleteAgentRequest()) + post.assert_not_called() + pb_message = agent.ExportAgentRequest.pb(agent.ExportAgentRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -4315,15 +5104,19 @@ def test_delete_agent_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) - request = agent.DeleteAgentRequest() + request = agent.ExportAgentRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() - client.delete_agent( + client.export_agent( request, metadata=[ ("key", "val"), @@ -4332,10 +5125,11 @@ def test_delete_agent_rest_interceptors(null_interceptor): ) pre.assert_called_once() + post.assert_called_once() -def test_delete_agent_rest_bad_request( - transport: str = "rest", request_type=agent.DeleteAgentRequest +def test_export_agent_rest_bad_request( + transport: str = "rest", request_type=agent.ExportAgentRequest ): client = AgentsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4355,64 +5149,213 @@ def test_delete_agent_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.delete_agent(request) + client.export_agent(request) -def test_delete_agent_rest_flattened(): +def test_export_agent_rest_error(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent.RestoreAgentRequest, + dict, + ], +) +def test_restore_agent_rest(request_type): client = AgentsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/agents/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/agents/sample3"} - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + response = client.restore_agent(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_restore_agent_rest_required_fields(request_type=agent.RestoreAgentRequest): + transport_class = transports.AgentsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).restore_agent._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).restore_agent._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.restore_agent(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_restore_agent_rest_unset_required_fields(): + transport = transports.AgentsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.restore_agent._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_restore_agent_rest_interceptors(null_interceptor): + transport = transports.AgentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AgentsRestInterceptor(), + ) + client = AgentsClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.AgentsRestInterceptor, "post_restore_agent" + ) as post, mock.patch.object( + transports.AgentsRestInterceptor, "pre_restore_agent" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = agent.RestoreAgentRequest.pb(agent.RestoreAgentRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) - client.delete_agent(**mock_args) + request = agent.RestoreAgentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v3/{name=projects/*/locations/*/agents/*}" % client.transport._host, - args[1], + client.restore_agent( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) + pre.assert_called_once() + post.assert_called_once() + -def test_delete_agent_rest_flattened_error(transport: str = "rest"): +def test_restore_agent_rest_bad_request( + transport: str = "rest", request_type=agent.RestoreAgentRequest +): client = AgentsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_agent( - agent.DeleteAgentRequest(), - name="name_value", - ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/agents/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.restore_agent(request) -def test_delete_agent_rest_error(): +def test_restore_agent_rest_error(): client = AgentsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -4421,11 +5364,11 @@ def test_delete_agent_rest_error(): @pytest.mark.parametrize( "request_type", [ - agent.ExportAgentRequest, + agent.ValidateAgentRequest, dict, ], ) -def test_export_agent_rest(request_type): +def test_validate_agent_rest(request_type): client = AgentsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -4438,22 +5381,26 @@ def test_export_agent_rest(request_type): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = agent.AgentValidationResult( + name="name_value", + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + pb_return_value = agent.AgentValidationResult.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.export_agent(request) + response = client.validate_agent(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + assert isinstance(response, agent.AgentValidationResult) + assert response.name == "name_value" -def test_export_agent_rest_required_fields(request_type=agent.ExportAgentRequest): +def test_validate_agent_rest_required_fields(request_type=agent.ValidateAgentRequest): transport_class = transports.AgentsRestTransport request_init = {} @@ -4472,7 +5419,7 @@ def test_export_agent_rest_required_fields(request_type=agent.ExportAgentRequest unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).export_agent._get_unset_required_fields(jsonified_request) + ).validate_agent._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -4481,7 +5428,7 @@ def test_export_agent_rest_required_fields(request_type=agent.ExportAgentRequest unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).export_agent._get_unset_required_fields(jsonified_request) + ).validate_agent._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -4495,7 +5442,7 @@ def test_export_agent_rest_required_fields(request_type=agent.ExportAgentRequest request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = agent.AgentValidationResult() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -4515,29 +5462,31 @@ def test_export_agent_rest_required_fields(request_type=agent.ExportAgentRequest response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + + pb_return_value = agent.AgentValidationResult.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.export_agent(request) + response = client.validate_agent(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_export_agent_rest_unset_required_fields(): +def test_validate_agent_rest_unset_required_fields(): transport = transports.AgentsRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.export_agent._get_unset_required_fields({}) + unset_fields = transport.validate_agent._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_export_agent_rest_interceptors(null_interceptor): +def test_validate_agent_rest_interceptors(null_interceptor): transport = transports.AgentsRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.AgentsRestInterceptor(), @@ -4548,15 +5497,13 @@ def test_export_agent_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.AgentsRestInterceptor, "post_export_agent" + transports.AgentsRestInterceptor, "post_validate_agent" ) as post, mock.patch.object( - transports.AgentsRestInterceptor, "pre_export_agent" + transports.AgentsRestInterceptor, "pre_validate_agent" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = agent.ExportAgentRequest.pb(agent.ExportAgentRequest()) + pb_message = agent.ValidateAgentRequest.pb(agent.ValidateAgentRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -4567,19 +5514,19 @@ def test_export_agent_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() + req.return_value._content = agent.AgentValidationResult.to_json( + agent.AgentValidationResult() ) - request = agent.ExportAgentRequest() + request = agent.ValidateAgentRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = agent.AgentValidationResult() - client.export_agent( + client.validate_agent( request, metadata=[ ("key", "val"), @@ -4591,8 +5538,8 @@ def test_export_agent_rest_interceptors(null_interceptor): post.assert_called_once() -def test_export_agent_rest_bad_request( - transport: str = "rest", request_type=agent.ExportAgentRequest +def test_validate_agent_rest_bad_request( + transport: str = "rest", request_type=agent.ValidateAgentRequest ): client = AgentsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4612,10 +5559,10 @@ def test_export_agent_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.export_agent(request) + client.validate_agent(request) -def test_export_agent_rest_error(): +def test_validate_agent_rest_error(): client = AgentsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -4624,39 +5571,47 @@ def test_export_agent_rest_error(): @pytest.mark.parametrize( "request_type", [ - agent.RestoreAgentRequest, + agent.GetAgentValidationResultRequest, dict, ], ) -def test_restore_agent_rest(request_type): +def test_get_agent_validation_result_rest(request_type): client = AgentsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/agents/sample3"} + request_init = { + "name": "projects/sample1/locations/sample2/agents/sample3/validationResult" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = agent.AgentValidationResult( + name="name_value", + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + pb_return_value = agent.AgentValidationResult.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.restore_agent(request) + response = client.get_agent_validation_result(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + assert isinstance(response, agent.AgentValidationResult) + assert response.name == "name_value" -def test_restore_agent_rest_required_fields(request_type=agent.RestoreAgentRequest): +def test_get_agent_validation_result_rest_required_fields( + request_type=agent.GetAgentValidationResultRequest, +): transport_class = transports.AgentsRestTransport request_init = {} @@ -4675,7 +5630,7 @@ def test_restore_agent_rest_required_fields(request_type=agent.RestoreAgentReque unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).restore_agent._get_unset_required_fields(jsonified_request) + ).get_agent_validation_result._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -4684,7 +5639,9 @@ def test_restore_agent_rest_required_fields(request_type=agent.RestoreAgentReque unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).restore_agent._get_unset_required_fields(jsonified_request) + ).get_agent_validation_result._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("language_code",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -4698,7 +5655,7 @@ def test_restore_agent_rest_required_fields(request_type=agent.RestoreAgentReque request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = agent.AgentValidationResult() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -4710,37 +5667,38 @@ def test_restore_agent_rest_required_fields(request_type=agent.RestoreAgentReque pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + + pb_return_value = agent.AgentValidationResult.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.restore_agent(request) + response = client.get_agent_validation_result(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_restore_agent_rest_unset_required_fields(): +def test_get_agent_validation_result_rest_unset_required_fields(): transport = transports.AgentsRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.restore_agent._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.get_agent_validation_result._get_unset_required_fields({}) + assert set(unset_fields) == (set(("languageCode",)) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_restore_agent_rest_interceptors(null_interceptor): +def test_get_agent_validation_result_rest_interceptors(null_interceptor): transport = transports.AgentsRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.AgentsRestInterceptor(), @@ -4751,15 +5709,15 @@ def test_restore_agent_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.AgentsRestInterceptor, "post_restore_agent" + transports.AgentsRestInterceptor, "post_get_agent_validation_result" ) as post, mock.patch.object( - transports.AgentsRestInterceptor, "pre_restore_agent" + transports.AgentsRestInterceptor, "pre_get_agent_validation_result" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = agent.RestoreAgentRequest.pb(agent.RestoreAgentRequest()) + pb_message = agent.GetAgentValidationResultRequest.pb( + agent.GetAgentValidationResultRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -4770,19 +5728,19 @@ def test_restore_agent_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() + req.return_value._content = agent.AgentValidationResult.to_json( + agent.AgentValidationResult() ) - request = agent.RestoreAgentRequest() + request = agent.GetAgentValidationResultRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = agent.AgentValidationResult() - client.restore_agent( + client.get_agent_validation_result( request, metadata=[ ("key", "val"), @@ -4790,35 +5748,95 @@ def test_restore_agent_rest_interceptors(null_interceptor): ], ) - pre.assert_called_once() - post.assert_called_once() - + pre.assert_called_once() + post.assert_called_once() + + +def test_get_agent_validation_result_rest_bad_request( + transport: str = "rest", request_type=agent.GetAgentValidationResultRequest +): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/agents/sample3/validationResult" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_agent_validation_result(request) + + +def test_get_agent_validation_result_rest_flattened(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = agent.AgentValidationResult() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/agents/sample3/validationResult" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = agent.AgentValidationResult.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_agent_validation_result(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v3/{name=projects/*/locations/*/agents/*/validationResult}" + % client.transport._host, + args[1], + ) + -def test_restore_agent_rest_bad_request( - transport: str = "rest", request_type=agent.RestoreAgentRequest -): +def test_get_agent_validation_result_rest_flattened_error(transport: str = "rest"): client = AgentsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/agents/sample3"} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.restore_agent(request) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_agent_validation_result( + agent.GetAgentValidationResultRequest(), + name="name_value", + ) -def test_restore_agent_rest_error(): +def test_get_agent_validation_result_rest_error(): client = AgentsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -4827,47 +5845,54 @@ def test_restore_agent_rest_error(): @pytest.mark.parametrize( "request_type", [ - agent.ValidateAgentRequest, + agent.GetGenerativeSettingsRequest, dict, ], ) -def test_validate_agent_rest(request_type): +def test_get_generative_settings_rest(request_type): client = AgentsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/agents/sample3"} + request_init = { + "name": "projects/sample1/locations/sample2/agents/sample3/generativeSettings" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = agent.AgentValidationResult( + return_value = generative_settings.GenerativeSettings( name="name_value", + language_code="language_code_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = agent.AgentValidationResult.pb(return_value) + pb_return_value = generative_settings.GenerativeSettings.pb(return_value) json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.validate_agent(request) + response = client.get_generative_settings(request) # Establish that the response is the type that we expect. - assert isinstance(response, agent.AgentValidationResult) + assert isinstance(response, generative_settings.GenerativeSettings) assert response.name == "name_value" + assert response.language_code == "language_code_value" -def test_validate_agent_rest_required_fields(request_type=agent.ValidateAgentRequest): +def test_get_generative_settings_rest_required_fields( + request_type=agent.GetGenerativeSettingsRequest, +): transport_class = transports.AgentsRestTransport request_init = {} request_init["name"] = "" + request_init["language_code"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -4879,24 +5904,32 @@ def test_validate_agent_rest_required_fields(request_type=agent.ValidateAgentReq ) # verify fields with default values are dropped + assert "languageCode" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).validate_agent._get_unset_required_fields(jsonified_request) + ).get_generative_settings._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + assert "languageCode" in jsonified_request + assert jsonified_request["languageCode"] == request_init["language_code"] jsonified_request["name"] = "name_value" + jsonified_request["languageCode"] = "language_code_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).validate_agent._get_unset_required_fields(jsonified_request) + ).get_generative_settings._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("language_code",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request assert jsonified_request["name"] == "name_value" + assert "languageCode" in jsonified_request + assert jsonified_request["languageCode"] == "language_code_value" client = AgentsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4905,7 +5938,7 @@ def test_validate_agent_rest_required_fields(request_type=agent.ValidateAgentReq request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = agent.AgentValidationResult() + return_value = generative_settings.GenerativeSettings() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -4917,39 +5950,52 @@ def test_validate_agent_rest_required_fields(request_type=agent.ValidateAgentReq pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - pb_return_value = agent.AgentValidationResult.pb(return_value) + pb_return_value = generative_settings.GenerativeSettings.pb(return_value) json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.validate_agent(request) + response = client.get_generative_settings(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "languageCode", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_validate_agent_rest_unset_required_fields(): +def test_get_generative_settings_rest_unset_required_fields(): transport = transports.AgentsRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.validate_agent._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.get_generative_settings._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("languageCode",)) + & set( + ( + "name", + "languageCode", + ) + ) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_validate_agent_rest_interceptors(null_interceptor): +def test_get_generative_settings_rest_interceptors(null_interceptor): transport = transports.AgentsRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.AgentsRestInterceptor(), @@ -4960,13 +6006,15 @@ def test_validate_agent_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AgentsRestInterceptor, "post_validate_agent" + transports.AgentsRestInterceptor, "post_get_generative_settings" ) as post, mock.patch.object( - transports.AgentsRestInterceptor, "pre_validate_agent" + transports.AgentsRestInterceptor, "pre_get_generative_settings" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = agent.ValidateAgentRequest.pb(agent.ValidateAgentRequest()) + pb_message = agent.GetGenerativeSettingsRequest.pb( + agent.GetGenerativeSettingsRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -4977,19 +6025,19 @@ def test_validate_agent_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = agent.AgentValidationResult.to_json( - agent.AgentValidationResult() + req.return_value._content = generative_settings.GenerativeSettings.to_json( + generative_settings.GenerativeSettings() ) - request = agent.ValidateAgentRequest() + request = agent.GetGenerativeSettingsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = agent.AgentValidationResult() + post.return_value = generative_settings.GenerativeSettings() - client.validate_agent( + client.get_generative_settings( request, metadata=[ ("key", "val"), @@ -5001,8 +6049,8 @@ def test_validate_agent_rest_interceptors(null_interceptor): post.assert_called_once() -def test_validate_agent_rest_bad_request( - transport: str = "rest", request_type=agent.ValidateAgentRequest +def test_get_generative_settings_rest_bad_request( + transport: str = "rest", request_type=agent.GetGenerativeSettingsRequest ): client = AgentsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5010,7 +6058,9 @@ def test_validate_agent_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/agents/sample3"} + request_init = { + "name": "projects/sample1/locations/sample2/agents/sample3/generativeSettings" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -5022,10 +6072,70 @@ def test_validate_agent_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.validate_agent(request) + client.get_generative_settings(request) -def test_validate_agent_rest_error(): +def test_get_generative_settings_rest_flattened(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = generative_settings.GenerativeSettings() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/agents/sample3/generativeSettings" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + language_code="language_code_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = generative_settings.GenerativeSettings.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_generative_settings(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v3/{name=projects/*/locations/*/agents/*/generativeSettings}" + % client.transport._host, + args[1], + ) + + +def test_get_generative_settings_rest_flattened_error(transport: str = "rest"): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_generative_settings( + agent.GetGenerativeSettingsRequest(), + name="name_value", + language_code="language_code_value", + ) + + +def test_get_generative_settings_rest_error(): client = AgentsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -5034,11 +6144,11 @@ def test_validate_agent_rest_error(): @pytest.mark.parametrize( "request_type", [ - agent.GetAgentValidationResultRequest, + agent.UpdateGenerativeSettingsRequest, dict, ], ) -def test_get_agent_validation_result_rest(request_type): +def test_update_generative_settings_rest(request_type): client = AgentsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -5046,39 +6156,68 @@ def test_get_agent_validation_result_rest(request_type): # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/agents/sample3/validationResult" + "generative_settings": { + "name": "projects/sample1/locations/sample2/agents/sample3/generativeSettings" + } + } + request_init["generative_settings"] = { + "name": "projects/sample1/locations/sample2/agents/sample3/generativeSettings", + "fallback_settings": { + "selected_prompt": "selected_prompt_value", + "prompt_templates": [ + { + "display_name": "display_name_value", + "prompt_text": "prompt_text_value", + "frozen": True, + } + ], + }, + "generative_safety_settings": { + "banned_phrases": [ + {"text": "text_value", "language_code": "language_code_value"} + ] + }, + "knowledge_connector_settings": { + "business": "business_value", + "agent": "agent_value", + "agent_identity": "agent_identity_value", + "business_description": "business_description_value", + "agent_scope": "agent_scope_value", + }, + "language_code": "language_code_value", } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = agent.AgentValidationResult( + return_value = gcdc_generative_settings.GenerativeSettings( name="name_value", + language_code="language_code_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = agent.AgentValidationResult.pb(return_value) + pb_return_value = gcdc_generative_settings.GenerativeSettings.pb(return_value) json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_agent_validation_result(request) + response = client.update_generative_settings(request) # Establish that the response is the type that we expect. - assert isinstance(response, agent.AgentValidationResult) + assert isinstance(response, gcdc_generative_settings.GenerativeSettings) assert response.name == "name_value" + assert response.language_code == "language_code_value" -def test_get_agent_validation_result_rest_required_fields( - request_type=agent.GetAgentValidationResultRequest, +def test_update_generative_settings_rest_required_fields( + request_type=agent.UpdateGenerativeSettingsRequest, ): transport_class = transports.AgentsRestTransport request_init = {} - request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -5093,23 +6232,19 @@ def test_get_agent_validation_result_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_agent_validation_result._get_unset_required_fields(jsonified_request) + ).update_generative_settings._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_agent_validation_result._get_unset_required_fields(jsonified_request) + ).update_generative_settings._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("language_code",)) + assert not set(unset_fields) - set(("update_mask",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" client = AgentsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5118,7 +6253,7 @@ def test_get_agent_validation_result_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = agent.AgentValidationResult() + return_value = gcdc_generative_settings.GenerativeSettings() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -5130,38 +6265,41 @@ def test_get_agent_validation_result_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "patch", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - pb_return_value = agent.AgentValidationResult.pb(return_value) + pb_return_value = gcdc_generative_settings.GenerativeSettings.pb( + return_value + ) json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_agent_validation_result(request) + response = client.update_generative_settings(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_agent_validation_result_rest_unset_required_fields(): +def test_update_generative_settings_rest_unset_required_fields(): transport = transports.AgentsRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_agent_validation_result._get_unset_required_fields({}) - assert set(unset_fields) == (set(("languageCode",)) & set(("name",))) + unset_fields = transport.update_generative_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("generativeSettings",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_agent_validation_result_rest_interceptors(null_interceptor): +def test_update_generative_settings_rest_interceptors(null_interceptor): transport = transports.AgentsRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.AgentsRestInterceptor(), @@ -5172,14 +6310,14 @@ def test_get_agent_validation_result_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AgentsRestInterceptor, "post_get_agent_validation_result" + transports.AgentsRestInterceptor, "post_update_generative_settings" ) as post, mock.patch.object( - transports.AgentsRestInterceptor, "pre_get_agent_validation_result" + transports.AgentsRestInterceptor, "pre_update_generative_settings" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = agent.GetAgentValidationResultRequest.pb( - agent.GetAgentValidationResultRequest() + pb_message = agent.UpdateGenerativeSettingsRequest.pb( + agent.UpdateGenerativeSettingsRequest() ) transcode.return_value = { "method": "post", @@ -5191,19 +6329,19 @@ def test_get_agent_validation_result_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = agent.AgentValidationResult.to_json( - agent.AgentValidationResult() + req.return_value._content = gcdc_generative_settings.GenerativeSettings.to_json( + gcdc_generative_settings.GenerativeSettings() ) - request = agent.GetAgentValidationResultRequest() + request = agent.UpdateGenerativeSettingsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = agent.AgentValidationResult() + post.return_value = gcdc_generative_settings.GenerativeSettings() - client.get_agent_validation_result( + client.update_generative_settings( request, metadata=[ ("key", "val"), @@ -5215,8 +6353,8 @@ def test_get_agent_validation_result_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_agent_validation_result_rest_bad_request( - transport: str = "rest", request_type=agent.GetAgentValidationResultRequest +def test_update_generative_settings_rest_bad_request( + transport: str = "rest", request_type=agent.UpdateGenerativeSettingsRequest ): client = AgentsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5225,7 +6363,35 @@ def test_get_agent_validation_result_rest_bad_request( # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/agents/sample3/validationResult" + "generative_settings": { + "name": "projects/sample1/locations/sample2/agents/sample3/generativeSettings" + } + } + request_init["generative_settings"] = { + "name": "projects/sample1/locations/sample2/agents/sample3/generativeSettings", + "fallback_settings": { + "selected_prompt": "selected_prompt_value", + "prompt_templates": [ + { + "display_name": "display_name_value", + "prompt_text": "prompt_text_value", + "frozen": True, + } + ], + }, + "generative_safety_settings": { + "banned_phrases": [ + {"text": "text_value", "language_code": "language_code_value"} + ] + }, + "knowledge_connector_settings": { + "business": "business_value", + "agent": "agent_value", + "agent_identity": "agent_identity_value", + "business_description": "business_description_value", + "agent_scope": "agent_scope_value", + }, + "language_code": "language_code_value", } request = request_type(**request_init) @@ -5238,10 +6404,10 @@ def test_get_agent_validation_result_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_agent_validation_result(request) + client.update_generative_settings(request) -def test_get_agent_validation_result_rest_flattened(): +def test_update_generative_settings_rest_flattened(): client = AgentsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -5250,41 +6416,46 @@ def test_get_agent_validation_result_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = agent.AgentValidationResult() + return_value = gcdc_generative_settings.GenerativeSettings() # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/agents/sample3/validationResult" + "generative_settings": { + "name": "projects/sample1/locations/sample2/agents/sample3/generativeSettings" + } } # get truthy value for each flattened field mock_args = dict( - name="name_value", + generative_settings=gcdc_generative_settings.GenerativeSettings( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = agent.AgentValidationResult.pb(return_value) + pb_return_value = gcdc_generative_settings.GenerativeSettings.pb(return_value) json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_agent_validation_result(**mock_args) + client.update_generative_settings(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v3/{name=projects/*/locations/*/agents/*/validationResult}" + "%s/v3/{generative_settings.name=projects/*/locations/*/agents/*/generativeSettings}" % client.transport._host, args[1], ) -def test_get_agent_validation_result_rest_flattened_error(transport: str = "rest"): +def test_update_generative_settings_rest_flattened_error(transport: str = "rest"): client = AgentsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5293,13 +6464,16 @@ def test_get_agent_validation_result_rest_flattened_error(transport: str = "rest # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_agent_validation_result( - agent.GetAgentValidationResultRequest(), - name="name_value", + client.update_generative_settings( + agent.UpdateGenerativeSettingsRequest(), + generative_settings=gcdc_generative_settings.GenerativeSettings( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_get_agent_validation_result_rest_error(): +def test_update_generative_settings_rest_error(): client = AgentsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -5453,6 +6627,8 @@ def test_agents_base_transport(): "restore_agent", "validate_agent", "get_agent_validation_result", + "get_generative_settings", + "update_generative_settings", "get_location", "list_locations", "get_operation", @@ -5774,6 +6950,12 @@ def test_agents_client_transport_session_collision(transport_name): session1 = client1.transport.get_agent_validation_result._session session2 = client2.transport.get_agent_validation_result._session assert session1 != session2 + session1 = client1.transport.get_generative_settings._session + session2 = client2.transport.get_generative_settings._session + assert session1 != session2 + session1 = client1.transport.update_generative_settings._session + session2 = client2.transport.update_generative_settings._session + assert session1 != session2 def test_agents_grpc_transport_channel(): @@ -5954,37 +7136,63 @@ def test_parse_agent_path(): assert expected == actual -def test_agent_validation_result_path(): +def test_agent_generative_settings_path(): project = "cuttlefish" location = "mussel" agent = "winkle" - expected = "projects/{project}/locations/{location}/agents/{agent}/validationResult".format( + expected = "projects/{project}/locations/{location}/agents/{agent}/generativeSettings".format( project=project, location=location, agent=agent, ) - actual = AgentsClient.agent_validation_result_path(project, location, agent) + actual = AgentsClient.agent_generative_settings_path(project, location, agent) assert expected == actual -def test_parse_agent_validation_result_path(): +def test_parse_agent_generative_settings_path(): expected = { "project": "nautilus", "location": "scallop", "agent": "abalone", } - path = AgentsClient.agent_validation_result_path(**expected) + path = AgentsClient.agent_generative_settings_path(**expected) # Check that the path construction is reversible. - actual = AgentsClient.parse_agent_validation_result_path(path) + actual = AgentsClient.parse_agent_generative_settings_path(path) assert expected == actual -def test_environment_path(): +def test_agent_validation_result_path(): project = "squid" location = "clam" agent = "whelk" - environment = "octopus" + expected = "projects/{project}/locations/{location}/agents/{agent}/validationResult".format( + project=project, + location=location, + agent=agent, + ) + actual = AgentsClient.agent_validation_result_path(project, location, agent) + assert expected == actual + + +def test_parse_agent_validation_result_path(): + expected = { + "project": "octopus", + "location": "oyster", + "agent": "nudibranch", + } + path = AgentsClient.agent_validation_result_path(**expected) + + # Check that the path construction is reversible. + actual = AgentsClient.parse_agent_validation_result_path(path) + assert expected == actual + + +def test_environment_path(): + project = "cuttlefish" + location = "mussel" + agent = "winkle" + environment = "nautilus" expected = "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format( project=project, location=location, @@ -5997,10 +7205,10 @@ def test_environment_path(): def test_parse_environment_path(): expected = { - "project": "oyster", - "location": "nudibranch", - "agent": "cuttlefish", - "environment": "mussel", + "project": "scallop", + "location": "abalone", + "agent": "squid", + "environment": "clam", } path = AgentsClient.environment_path(**expected) @@ -6010,10 +7218,10 @@ def test_parse_environment_path(): def test_flow_path(): - project = "winkle" - location = "nautilus" - agent = "scallop" - flow = "abalone" + project = "whelk" + location = "octopus" + agent = "oyster" + flow = "nudibranch" expected = ( "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format( project=project, @@ -6028,10 +7236,10 @@ def test_flow_path(): def test_parse_flow_path(): expected = { - "project": "squid", - "location": "clam", - "agent": "whelk", - "flow": "octopus", + "project": "cuttlefish", + "location": "mussel", + "agent": "winkle", + "flow": "nautilus", } path = AgentsClient.flow_path(**expected) @@ -6041,10 +7249,10 @@ def test_parse_flow_path(): def test_flow_validation_result_path(): - project = "oyster" - location = "nudibranch" - agent = "cuttlefish" - flow = "mussel" + project = "scallop" + location = "abalone" + agent = "squid" + flow = "clam" expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/validationResult".format( project=project, location=location, @@ -6057,10 +7265,10 @@ def test_flow_validation_result_path(): def test_parse_flow_validation_result_path(): expected = { - "project": "winkle", - "location": "nautilus", - "agent": "scallop", - "flow": "abalone", + "project": "whelk", + "location": "octopus", + "agent": "oyster", + "flow": "nudibranch", } path = AgentsClient.flow_validation_result_path(**expected) @@ -6070,9 +7278,9 @@ def test_parse_flow_validation_result_path(): def test_security_settings_path(): - project = "squid" - location = "clam" - security_settings = "whelk" + project = "cuttlefish" + location = "mussel" + security_settings = "winkle" expected = "projects/{project}/locations/{location}/securitySettings/{security_settings}".format( project=project, location=location, @@ -6084,9 +7292,9 @@ def test_security_settings_path(): def test_parse_security_settings_path(): expected = { - "project": "octopus", - "location": "oyster", - "security_settings": "nudibranch", + "project": "nautilus", + "location": "scallop", + "security_settings": "abalone", } path = AgentsClient.security_settings_path(**expected) @@ -6096,7 +7304,7 @@ def test_parse_security_settings_path(): def test_common_billing_account_path(): - billing_account = "cuttlefish" + billing_account = "squid" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -6106,7 +7314,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "mussel", + "billing_account": "clam", } path = AgentsClient.common_billing_account_path(**expected) @@ -6116,7 +7324,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "winkle" + folder = "whelk" expected = "folders/{folder}".format( folder=folder, ) @@ -6126,7 +7334,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "nautilus", + "folder": "octopus", } path = AgentsClient.common_folder_path(**expected) @@ -6136,7 +7344,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "scallop" + organization = "oyster" expected = "organizations/{organization}".format( organization=organization, ) @@ -6146,7 +7354,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "abalone", + "organization": "nudibranch", } path = AgentsClient.common_organization_path(**expected) @@ -6156,7 +7364,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "squid" + project = "cuttlefish" expected = "projects/{project}".format( project=project, ) @@ -6166,7 +7374,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "clam", + "project": "mussel", } path = AgentsClient.common_project_path(**expected) @@ -6176,8 +7384,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "whelk" - location = "octopus" + project = "winkle" + location = "nautilus" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -6188,8 +7396,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "oyster", - "location": "nudibranch", + "project": "scallop", + "location": "abalone", } path = AgentsClient.common_location_path(**expected) diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_flows.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_flows.py index bc1a4b0614c3..21ee67e08017 100644 --- a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_flows.py +++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_flows.py @@ -70,6 +70,7 @@ response_message, validation_message, ) +from google.cloud.dialogflowcx_v3.types import data_store_connection from google.cloud.dialogflowcx_v3.types import flow from google.cloud.dialogflowcx_v3.types import flow as gcdc_flow @@ -2998,6 +2999,7 @@ def test_create_flow_rest(request_type): "transition_routes": [ { "name": "name_value", + "description": "description_value", "intent": "intent_value", "condition": "condition_value", "trigger_fulfillment": { @@ -3032,6 +3034,7 @@ def test_create_flow_rest(request_type): "telephony_transfer_call": { "phone_number": "phone_number_value" }, + "knowledge_info_card": {}, "response_type": 1, "channel": "channel_value", } @@ -3087,6 +3090,15 @@ def test_create_flow_rest(request_type): "classification_threshold": 0.25520000000000004, "model_training_mode": 1, }, + "knowledge_connector_settings": { + "enabled": True, + "trigger_fulfillment": {}, + "target_page": "target_page_value", + "target_flow": "target_flow_value", + "data_store_connections": [ + {"data_store_type": 1, "data_store": "data_store_value"} + ], + }, } request = request_type(**request_init) @@ -3281,6 +3293,7 @@ def test_create_flow_rest_bad_request( "transition_routes": [ { "name": "name_value", + "description": "description_value", "intent": "intent_value", "condition": "condition_value", "trigger_fulfillment": { @@ -3315,6 +3328,7 @@ def test_create_flow_rest_bad_request( "telephony_transfer_call": { "phone_number": "phone_number_value" }, + "knowledge_info_card": {}, "response_type": 1, "channel": "channel_value", } @@ -3370,6 +3384,15 @@ def test_create_flow_rest_bad_request( "classification_threshold": 0.25520000000000004, "model_training_mode": 1, }, + "knowledge_connector_settings": { + "enabled": True, + "trigger_fulfillment": {}, + "target_page": "target_page_value", + "target_flow": "target_flow_value", + "data_store_connections": [ + {"data_store_type": 1, "data_store": "data_store_value"} + ], + }, } request = request_type(**request_init) @@ -4338,6 +4361,7 @@ def test_update_flow_rest(request_type): "transition_routes": [ { "name": "name_value", + "description": "description_value", "intent": "intent_value", "condition": "condition_value", "trigger_fulfillment": { @@ -4372,6 +4396,7 @@ def test_update_flow_rest(request_type): "telephony_transfer_call": { "phone_number": "phone_number_value" }, + "knowledge_info_card": {}, "response_type": 1, "channel": "channel_value", } @@ -4427,6 +4452,15 @@ def test_update_flow_rest(request_type): "classification_threshold": 0.25520000000000004, "model_training_mode": 1, }, + "knowledge_connector_settings": { + "enabled": True, + "trigger_fulfillment": {}, + "target_page": "target_page_value", + "target_flow": "target_flow_value", + "data_store_connections": [ + {"data_store_type": 1, "data_store": "data_store_value"} + ], + }, } request = request_type(**request_init) @@ -4625,6 +4659,7 @@ def test_update_flow_rest_bad_request( "transition_routes": [ { "name": "name_value", + "description": "description_value", "intent": "intent_value", "condition": "condition_value", "trigger_fulfillment": { @@ -4659,6 +4694,7 @@ def test_update_flow_rest_bad_request( "telephony_transfer_call": { "phone_number": "phone_number_value" }, + "knowledge_info_card": {}, "response_type": 1, "channel": "channel_value", } @@ -4714,6 +4750,15 @@ def test_update_flow_rest_bad_request( "classification_threshold": 0.25520000000000004, "model_training_mode": 1, }, + "knowledge_connector_settings": { + "enabled": True, + "trigger_fulfillment": {}, + "target_page": "target_page_value", + "target_flow": "target_flow_value", + "data_store_connections": [ + {"data_store_type": 1, "data_store": "data_store_value"} + ], + }, } request = request_type(**request_init) diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_pages.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_pages.py index 623654bea9f0..591ab282ef3a 100644 --- a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_pages.py +++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_pages.py @@ -52,7 +52,7 @@ pagers, transports, ) -from google.cloud.dialogflowcx_v3.types import fulfillment +from google.cloud.dialogflowcx_v3.types import data_store_connection, fulfillment from google.cloud.dialogflowcx_v3.types import page from google.cloud.dialogflowcx_v3.types import page as gcdc_page from google.cloud.dialogflowcx_v3.types import response_message @@ -2702,6 +2702,7 @@ def test_create_page_rest(request_type): ] }, "telephony_transfer_call": {"phone_number": "phone_number_value"}, + "knowledge_info_card": {}, "response_type": 1, "channel": "channel_value", } @@ -2764,6 +2765,7 @@ def test_create_page_rest(request_type): "transition_routes": [ { "name": "name_value", + "description": "description_value", "intent": "intent_value", "condition": "condition_value", "trigger_fulfillment": {}, @@ -2772,6 +2774,15 @@ def test_create_page_rest(request_type): } ], "event_handlers": {}, + "knowledge_connector_settings": { + "enabled": True, + "trigger_fulfillment": {}, + "target_page": "target_page_value", + "target_flow": "target_flow_value", + "data_store_connections": [ + {"data_store_type": 1, "data_store": "data_store_value"} + ], + }, } request = request_type(**request_init) @@ -2992,6 +3003,7 @@ def test_create_page_rest_bad_request( ] }, "telephony_transfer_call": {"phone_number": "phone_number_value"}, + "knowledge_info_card": {}, "response_type": 1, "channel": "channel_value", } @@ -3054,6 +3066,7 @@ def test_create_page_rest_bad_request( "transition_routes": [ { "name": "name_value", + "description": "description_value", "intent": "intent_value", "condition": "condition_value", "trigger_fulfillment": {}, @@ -3062,6 +3075,15 @@ def test_create_page_rest_bad_request( } ], "event_handlers": {}, + "knowledge_connector_settings": { + "enabled": True, + "trigger_fulfillment": {}, + "target_page": "target_page_value", + "target_flow": "target_flow_value", + "data_store_connections": [ + {"data_store_type": 1, "data_store": "data_store_value"} + ], + }, } request = request_type(**request_init) @@ -3195,6 +3217,7 @@ def test_update_page_rest(request_type): ] }, "telephony_transfer_call": {"phone_number": "phone_number_value"}, + "knowledge_info_card": {}, "response_type": 1, "channel": "channel_value", } @@ -3257,6 +3280,7 @@ def test_update_page_rest(request_type): "transition_routes": [ { "name": "name_value", + "description": "description_value", "intent": "intent_value", "condition": "condition_value", "trigger_fulfillment": {}, @@ -3265,6 +3289,15 @@ def test_update_page_rest(request_type): } ], "event_handlers": {}, + "knowledge_connector_settings": { + "enabled": True, + "trigger_fulfillment": {}, + "target_page": "target_page_value", + "target_flow": "target_flow_value", + "data_store_connections": [ + {"data_store_type": 1, "data_store": "data_store_value"} + ], + }, } request = request_type(**request_init) @@ -3487,6 +3520,7 @@ def test_update_page_rest_bad_request( ] }, "telephony_transfer_call": {"phone_number": "phone_number_value"}, + "knowledge_info_card": {}, "response_type": 1, "channel": "channel_value", } @@ -3549,6 +3583,7 @@ def test_update_page_rest_bad_request( "transition_routes": [ { "name": "name_value", + "description": "description_value", "intent": "intent_value", "condition": "condition_value", "trigger_fulfillment": {}, @@ -3557,6 +3592,15 @@ def test_update_page_rest_bad_request( } ], "event_handlers": {}, + "knowledge_connector_settings": { + "enabled": True, + "trigger_fulfillment": {}, + "target_page": "target_page_value", + "target_flow": "target_flow_value", + "data_store_connections": [ + {"data_store_type": 1, "data_store": "data_store_value"} + ], + }, } request = request_type(**request_init) diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_security_settings_service.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_security_settings_service.py index 572b365e4090..8fe249e13360 100644 --- a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_security_settings_service.py +++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_security_settings_service.py @@ -2374,6 +2374,7 @@ def test_create_security_settings_rest(request_type): "inspect_template": "inspect_template_value", "deidentify_template": "deidentify_template_value", "retention_window_days": 2271, + "retention_strategy": 1, "purge_data_types": [1], "audio_export_settings": { "gcs_bucket": "gcs_bucket_value", @@ -2603,6 +2604,7 @@ def test_create_security_settings_rest_bad_request( "inspect_template": "inspect_template_value", "deidentify_template": "deidentify_template_value", "retention_window_days": 2271, + "retention_strategy": 1, "purge_data_types": [1], "audio_export_settings": { "gcs_bucket": "gcs_bucket_value", @@ -3018,6 +3020,7 @@ def test_update_security_settings_rest(request_type): "inspect_template": "inspect_template_value", "deidentify_template": "deidentify_template_value", "retention_window_days": 2271, + "retention_strategy": 1, "purge_data_types": [1], "audio_export_settings": { "gcs_bucket": "gcs_bucket_value", @@ -3248,6 +3251,7 @@ def test_update_security_settings_rest_bad_request( "inspect_template": "inspect_template_value", "deidentify_template": "deidentify_template_value", "retention_window_days": 2271, + "retention_strategy": 1, "purge_data_types": [1], "audio_export_settings": { "gcs_bucket": "gcs_bucket_value", diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_test_cases.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_test_cases.py index a77f2d0cfe94..2a1baaaa381b 100644 --- a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_test_cases.py +++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_test_cases.py @@ -66,6 +66,7 @@ ) from google.cloud.dialogflowcx_v3.types import ( audio_config, + data_store_connection, fulfillment, intent, page, @@ -4572,6 +4573,7 @@ def test_create_test_case_rest(request_type): "telephony_transfer_call": { "phone_number": "phone_number_value" }, + "knowledge_info_card": {}, "response_type": 1, "channel": "channel_value", } @@ -4636,6 +4638,7 @@ def test_create_test_case_rest(request_type): "transition_routes": [ { "name": "name_value", + "description": "description_value", "intent": "intent_value", "condition": "condition_value", "trigger_fulfillment": {}, @@ -4644,6 +4647,15 @@ def test_create_test_case_rest(request_type): } ], "event_handlers": {}, + "knowledge_connector_settings": { + "enabled": True, + "trigger_fulfillment": {}, + "target_page": "target_page_value", + "target_flow": "target_flow_value", + "data_store_connections": [ + {"data_store_type": 1, "data_store": "data_store_value"} + ], + }, }, "text_responses": {}, "status": { @@ -4970,6 +4982,7 @@ def test_create_test_case_rest_bad_request( "telephony_transfer_call": { "phone_number": "phone_number_value" }, + "knowledge_info_card": {}, "response_type": 1, "channel": "channel_value", } @@ -5034,6 +5047,7 @@ def test_create_test_case_rest_bad_request( "transition_routes": [ { "name": "name_value", + "description": "description_value", "intent": "intent_value", "condition": "condition_value", "trigger_fulfillment": {}, @@ -5042,6 +5056,15 @@ def test_create_test_case_rest_bad_request( } ], "event_handlers": {}, + "knowledge_connector_settings": { + "enabled": True, + "trigger_fulfillment": {}, + "target_page": "target_page_value", + "target_flow": "target_flow_value", + "data_store_connections": [ + {"data_store_type": 1, "data_store": "data_store_value"} + ], + }, }, "text_responses": {}, "status": { @@ -5275,6 +5298,7 @@ def test_update_test_case_rest(request_type): "telephony_transfer_call": { "phone_number": "phone_number_value" }, + "knowledge_info_card": {}, "response_type": 1, "channel": "channel_value", } @@ -5339,6 +5363,7 @@ def test_update_test_case_rest(request_type): "transition_routes": [ { "name": "name_value", + "description": "description_value", "intent": "intent_value", "condition": "condition_value", "trigger_fulfillment": {}, @@ -5347,6 +5372,15 @@ def test_update_test_case_rest(request_type): } ], "event_handlers": {}, + "knowledge_connector_settings": { + "enabled": True, + "trigger_fulfillment": {}, + "target_page": "target_page_value", + "target_flow": "target_flow_value", + "data_store_connections": [ + {"data_store_type": 1, "data_store": "data_store_value"} + ], + }, }, "text_responses": {}, "status": { @@ -5674,6 +5708,7 @@ def test_update_test_case_rest_bad_request( "telephony_transfer_call": { "phone_number": "phone_number_value" }, + "knowledge_info_card": {}, "response_type": 1, "channel": "channel_value", } @@ -5738,6 +5773,7 @@ def test_update_test_case_rest_bad_request( "transition_routes": [ { "name": "name_value", + "description": "description_value", "intent": "intent_value", "condition": "condition_value", "trigger_fulfillment": {}, @@ -5746,6 +5782,15 @@ def test_update_test_case_rest_bad_request( } ], "event_handlers": {}, + "knowledge_connector_settings": { + "enabled": True, + "trigger_fulfillment": {}, + "target_page": "target_page_value", + "target_flow": "target_flow_value", + "data_store_connections": [ + {"data_store_type": 1, "data_store": "data_store_value"} + ], + }, }, "text_responses": {}, "status": { diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_transition_route_groups.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_transition_route_groups.py index 31e8a9304ee4..6bdaafaf727b 100644 --- a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_transition_route_groups.py +++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_transition_route_groups.py @@ -2917,6 +2917,7 @@ def test_create_transition_route_group_rest(request_type): "transition_routes": [ { "name": "name_value", + "description": "description_value", "intent": "intent_value", "condition": "condition_value", "trigger_fulfillment": { @@ -2951,6 +2952,7 @@ def test_create_transition_route_group_rest(request_type): "telephony_transfer_call": { "phone_number": "phone_number_value" }, + "knowledge_info_card": {}, "response_type": 1, "channel": "channel_value", } @@ -3198,6 +3200,7 @@ def test_create_transition_route_group_rest_bad_request( "transition_routes": [ { "name": "name_value", + "description": "description_value", "intent": "intent_value", "condition": "condition_value", "trigger_fulfillment": { @@ -3232,6 +3235,7 @@ def test_create_transition_route_group_rest_bad_request( "telephony_transfer_call": { "phone_number": "phone_number_value" }, + "knowledge_info_card": {}, "response_type": 1, "channel": "channel_value", } @@ -3381,6 +3385,7 @@ def test_update_transition_route_group_rest(request_type): "transition_routes": [ { "name": "name_value", + "description": "description_value", "intent": "intent_value", "condition": "condition_value", "trigger_fulfillment": { @@ -3415,6 +3420,7 @@ def test_update_transition_route_group_rest(request_type): "telephony_transfer_call": { "phone_number": "phone_number_value" }, + "knowledge_info_card": {}, "response_type": 1, "channel": "channel_value", } @@ -3664,6 +3670,7 @@ def test_update_transition_route_group_rest_bad_request( "transition_routes": [ { "name": "name_value", + "description": "description_value", "intent": "intent_value", "condition": "condition_value", "trigger_fulfillment": { @@ -3698,6 +3705,7 @@ def test_update_transition_route_group_rest_bad_request( "telephony_transfer_call": { "phone_number": "phone_number_value" }, + "knowledge_info_card": {}, "response_type": 1, "channel": "channel_value", }