From 5dac9417869483c3703adff28e414f3068cee766 Mon Sep 17 00:00:00 2001 From: ohmayr Date: Tue, 3 Nov 2026 19:52:30 +0000 Subject: [PATCH] feat(ces): regenerate v1beta with resource alias Alias agentregistry.googleapis.com/Service to AgentRegistryService in librarian.yaml so servicedirectory.googleapis.com/Service retains the existing service_path helper without colliding during GAPIC generation. Remove skip_generate and regenerate google-cloud-ces with Librarian v0.51.0. Fixes #18888 --- librarian.yaml | 5 +- .../docs/ces_v1beta/assistant_service.rst | 10 + .../docs/ces_v1beta/services_.rst | 1 + .../google/cloud/ces_v1beta/__init__.py | 101 +- .../cloud/ces_v1beta/gapic_metadata.json | 169 + .../services/agent_service/async_client.py | 136 +- .../services/agent_service/client.py | 169 +- .../services/agent_service/transports/base.py | 14 + .../services/agent_service/transports/grpc.py | 26 + .../agent_service/transports/grpc_asyncio.py | 33 + .../services/agent_service/transports/rest.py | 219 + .../agent_service/transports/rest_base.py | 17 + .../services/assistant_service/__init__.py | 22 + .../assistant_service/async_client.py | 1335 +++ .../services/assistant_service/client.py | 1659 ++++ .../services/assistant_service/pagers.py | 201 + .../assistant_service/transports/README.rst | 10 + .../assistant_service/transports/__init__.py | 36 + .../assistant_service/transports/base.py | 364 + .../assistant_service/transports/grpc.py | 620 ++ .../transports/grpc_asyncio.py | 711 ++ .../assistant_service/transports/rest.py | 2385 +++++ .../assistant_service/transports/rest_base.py | 278 + .../evaluation_service/async_client.py | 1 + .../services/evaluation_service/client.py | 1 + .../services/session_service/async_client.py | 285 +- .../services/session_service/client.py | 321 +- .../session_service/transports/base.py | 58 + .../session_service/transports/grpc.py | 100 + .../transports/grpc_asyncio.py | 122 + .../session_service/transports/rest.py | 669 ++ .../session_service/transports/rest_base.py | 51 + .../google/cloud/ces_v1beta/types/__init__.py | 86 + .../google/cloud/ces_v1beta/types/agent.py | 29 +- .../cloud/ces_v1beta/types/agent_card.py | 115 + .../cloud/ces_v1beta/types/agent_service.py | 70 + .../google/cloud/ces_v1beta/types/app.py | 196 +- .../cloud/ces_v1beta/types/app_version.py | 8 + .../ces_v1beta/types/assistant_service.py | 829 ++ .../google/cloud/ces_v1beta/types/common.py | 70 + .../cloud/ces_v1beta/types/conversation.py | 8 + .../cloud/ces_v1beta/types/data_store_tool.py | 28 + .../cloud/ces_v1beta/types/deployment.py | 70 +- .../cloud/ces_v1beta/types/evaluation.py | 39 +- .../google/cloud/ces_v1beta/types/example.py | 44 + .../cloud/ces_v1beta/types/guardrail.py | 117 +- .../cloud/ces_v1beta/types/session_service.py | 1308 ++- .../google/cloud/ces_v1beta/types/tool.py | 8 + ...ed_agent_service_create_guardrail_async.py | 2 +- ...ted_agent_service_create_guardrail_sync.py | 2 +- ...enerated_agent_service_import_app_async.py | 1 + ...generated_agent_service_import_app_sync.py | 1 + ..._agent_service_update_app_version_async.py | 51 + ...d_agent_service_update_app_version_sync.py | 51 + ...ed_agent_service_update_guardrail_async.py | 2 +- ...ted_agent_service_update_guardrail_sync.py | 2 +- ...sistant_service_chat_ai_assistant_async.py | 55 + ...ssistant_service_chat_ai_assistant_sync.py | 55 + ..._service_create_assistant_session_async.py | 53 + ...t_service_create_assistant_session_sync.py | 53 + ..._service_delete_assistant_session_async.py | 50 + ...t_service_delete_assistant_session_sync.py | 50 + ...ant_service_get_assistant_session_async.py | 53 + ...tant_service_get_assistant_session_sync.py | 53 + ...t_service_list_assistant_sessions_async.py | 54 + ...nt_service_list_assistant_sessions_sync.py | 54 + ...d_assistant_service_run_assistant_async.py | 58 + ...ed_assistant_service_run_assistant_sync.py | 58 + ...ion_service_cancel_assistant_turn_async.py | 53 + ...sion_service_cancel_assistant_turn_sync.py | 53 + ...e_generate_onboarding_suggestions_async.py | 53 + ...ce_generate_onboarding_suggestions_sync.py | 53 + ..._service_stream_chat_ai_assistant_async.py | 54 + ...n_service_stream_chat_ai_assistant_sync.py | 54 + ...ppet_metadata_google.cloud.ces.v1beta.json | 4412 +++++++--- .../gapic/ces_v1beta/test_agent_service.py | 2730 +++++- .../ces_v1beta/test_assistant_service.py | 7747 +++++++++++++++++ .../ces_v1beta/test_evaluation_service.py | 36 +- .../gapic/ces_v1beta/test_session_service.py | 2705 +++++- 79 files changed, 29616 insertions(+), 2246 deletions(-) create mode 100644 packages/google-cloud-ces/docs/ces_v1beta/assistant_service.rst create mode 100644 packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/__init__.py create mode 100644 packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/async_client.py create mode 100644 packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/client.py create mode 100644 packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/pagers.py create mode 100644 packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/transports/README.rst create mode 100644 packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/transports/__init__.py create mode 100644 packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/transports/base.py create mode 100644 packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/transports/grpc.py create mode 100644 packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/transports/grpc_asyncio.py create mode 100644 packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/transports/rest.py create mode 100644 packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/transports/rest_base.py create mode 100644 packages/google-cloud-ces/google/cloud/ces_v1beta/types/assistant_service.py create mode 100644 packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_app_version_async.py create mode 100644 packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_app_version_sync.py create mode 100644 packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_chat_ai_assistant_async.py create mode 100644 packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_chat_ai_assistant_sync.py create mode 100644 packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_create_assistant_session_async.py create mode 100644 packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_create_assistant_session_sync.py create mode 100644 packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_delete_assistant_session_async.py create mode 100644 packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_delete_assistant_session_sync.py create mode 100644 packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_get_assistant_session_async.py create mode 100644 packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_get_assistant_session_sync.py create mode 100644 packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_list_assistant_sessions_async.py create mode 100644 packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_list_assistant_sessions_sync.py create mode 100644 packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_run_assistant_async.py create mode 100644 packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_run_assistant_sync.py create mode 100644 packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_session_service_cancel_assistant_turn_async.py create mode 100644 packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_session_service_cancel_assistant_turn_sync.py create mode 100644 packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_session_service_generate_onboarding_suggestions_async.py create mode 100644 packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_session_service_generate_onboarding_suggestions_sync.py create mode 100644 packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_session_service_stream_chat_ai_assistant_async.py create mode 100644 packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_session_service_stream_chat_ai_assistant_sync.py create mode 100644 packages/google-cloud-ces/tests/unit/gapic/ces_v1beta/test_assistant_service.py diff --git a/librarian.yaml b/librarian.yaml index f509369d6793..ba829e9d37ed 100644 --- a/librarian.yaml +++ b/librarian.yaml @@ -734,12 +734,13 @@ libraries: default_version: v1 - name: google-cloud-ces version: 0.7.2 - comment: Generation is skipped due to https://github.com/googleapis/google-cloud-python/issues/18888 apis: - path: google/cloud/ces/v1 - path: google/cloud/ces/v1beta - skip_generate: true python: + opt_args_by_api: + google/cloud/ces/v1beta: + - resource-name-alias=agentregistry.googleapis.com/Service:AgentRegistryService default_version: v1 - name: google-cloud-channel version: 1.29.0 diff --git a/packages/google-cloud-ces/docs/ces_v1beta/assistant_service.rst b/packages/google-cloud-ces/docs/ces_v1beta/assistant_service.rst new file mode 100644 index 000000000000..5c5b61650d6e --- /dev/null +++ b/packages/google-cloud-ces/docs/ces_v1beta/assistant_service.rst @@ -0,0 +1,10 @@ +AssistantService +---------------------------------- + +.. automodule:: google.cloud.ces_v1beta.services.assistant_service + :members: + :inherited-members: + +.. automodule:: google.cloud.ces_v1beta.services.assistant_service.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-ces/docs/ces_v1beta/services_.rst b/packages/google-cloud-ces/docs/ces_v1beta/services_.rst index 0d9075384160..9f8ef1d4c4a6 100644 --- a/packages/google-cloud-ces/docs/ces_v1beta/services_.rst +++ b/packages/google-cloud-ces/docs/ces_v1beta/services_.rst @@ -4,6 +4,7 @@ Services for Google Cloud Ces v1beta API :maxdepth: 2 agent_service + assistant_service evaluation_service session_service tool_service diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/__init__.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/__init__.py index 1474c4f6b596..082d8cf7d50c 100644 --- a/packages/google-cloud-ces/google/cloud/ces_v1beta/__init__.py +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/__init__.py @@ -27,6 +27,7 @@ # Older Python versions safely ignore this variable. __lazy_modules__ = { "google.cloud.ces_v1beta.services.agent_service", + "google.cloud.ces_v1beta.services.assistant_service", "google.cloud.ces_v1beta.services.evaluation_service", "google.cloud.ces_v1beta.services.session_service", "google.cloud.ces_v1beta.services.tool_service", @@ -38,6 +39,7 @@ "google.cloud.ces_v1beta.types.agent_transfers", "google.cloud.ces_v1beta.types.app", "google.cloud.ces_v1beta.types.app_version", + "google.cloud.ces_v1beta.types.assistant_service", "google.cloud.ces_v1beta.types.auth", "google.cloud.ces_v1beta.types.bigquery_export", "google.cloud.ces_v1beta.types.changelog", @@ -82,6 +84,10 @@ from .services.agent_service import AgentServiceAsyncClient, AgentServiceClient +from .services.assistant_service import ( + AssistantServiceAsyncClient, + AssistantServiceClient, +) from .services.evaluation_service import ( EvaluationServiceAsyncClient, EvaluationServiceClient, @@ -90,7 +96,13 @@ from .services.tool_service import ToolServiceAsyncClient, ToolServiceClient from .services.widget_service import WidgetServiceAsyncClient, WidgetServiceClient from .types.agent import Agent -from .types.agent_card import AgentCard, AgentInterface, AgentSkill, RemoteAgentTool +from .types.agent_card import ( + AgentCard, + AgentInterface, + AgentSkill, + RemoteA2aConfig, + RemoteAgentTool, +) from .types.agent_service import ( BatchDeleteConversationsRequest, BatchDeleteConversationsResponse, @@ -111,6 +123,7 @@ DeleteGuardrailRequest, DeleteToolRequest, DeleteToolsetRequest, + DeployChannelResponse, ExportAppRequest, ExportAppResponse, GenerateAppResourceOperationMetadata, @@ -155,6 +168,7 @@ RestoreAppVersionResponse, UpdateAgentRequest, UpdateAppRequest, + UpdateAppVersionRequest, UpdateDeploymentRequest, UpdateExampleRequest, UpdateGuardrailRequest, @@ -177,6 +191,8 @@ ClientCertificateSettings, CloudLoggingSettings, ConversationLoggingSettings, + CustomVoiceSample, + DashboardSettings, DataStoreSettings, ErrorHandlingSettings, EvaluationMetricsThresholds, @@ -191,6 +207,26 @@ VpcScSettings, ) from .types.app_version import AppSnapshot, AppVersion +from .types.assistant_service import ( + ActiveTurnInfo, + AssistantChunk, + AssistantMessage, + AssistantOutput, + AssistantSession, + AssistantSessionArtifact, + AssistantSessionState, + ChatAiAssistantRequest, + ChatAiAssistantResponse, + CreateAssistantSessionRequest, + DeleteAssistantSessionRequest, + GetAssistantSessionRequest, + ListAssistantSessionsRequest, + ListAssistantSessionsResponse, + RunAssistantRequest, + RunAssistantResponse, + TypedPayload, + UserResponseSuggestions, +) from .types.auth import ( ApiAuthentication, ApiKeyConfig, @@ -210,9 +246,11 @@ ExecutionType, ModelSettings, ServiceDirectoryConfig, + SessionCheckpoint, Span, TlsConfig, TriggerAction, + UiEvent, ) from .types.connector_tool import Action, ConnectorTool from .types.connector_toolset import ConnectorToolset @@ -220,6 +258,7 @@ from .types.data_store import DataStore from .types.data_store_tool import DataStoreTool from .types.deployment import ( + AgentRegistryDeployment, Deployment, ExperimentConfig, InstagramCredentials, @@ -327,16 +366,26 @@ from .types.search_suggestions import GoogleSearchSuggestions, WebSearchQuery from .types.security_settings import EndpointControlPolicy, SecuritySettings from .types.session_service import ( + ArtifactChunk, + AssistantConfirmationRequest, + AssistantConfirmationResponse, + AssistantSuggestion, AudioEncoding, BidiSessionClientMessage, BidiSessionServerMessage, + CancelAssistantTurnRequest, + CancelAssistantTurnResponse, Citations, EndSession, Event, + GenerateOnboardingSuggestionsRequest, + GenerateOnboardingSuggestionsResponse, GoAway, InputAudioConfig, InterruptionSignal, MockConfig, + OperationCompletedEvent, + OptionQuestionsChunk, OutputAudioConfig, RecognitionResult, RunSessionRequest, @@ -344,8 +393,14 @@ SessionConfig, SessionInput, SessionOutput, + StreamChatAiAssistantRequest, + StreamChatAiAssistantResponse, ToolCalls, ToolResponses, + TurnCompletedEvent, + TurnHandoffEvent, + TurnMetadata, + TurnResumeSnapshot, ) from .types.system_tool import SystemTool from .types.tool import Tool @@ -364,14 +419,17 @@ __all__ = ( "AgentServiceAsyncClient", + "AssistantServiceAsyncClient", "EvaluationServiceAsyncClient", "SessionServiceAsyncClient", "ToolServiceAsyncClient", "WidgetServiceAsyncClient", "Action", + "ActiveTurnInfo", "Agent", "AgentCard", "AgentInterface", + "AgentRegistryDeployment", "AgentServiceClient", "AgentSkill", "AgentTool", @@ -383,6 +441,17 @@ "App", "AppSnapshot", "AppVersion", + "ArtifactChunk", + "AssistantChunk", + "AssistantConfirmationRequest", + "AssistantConfirmationResponse", + "AssistantMessage", + "AssistantOutput", + "AssistantServiceClient", + "AssistantSession", + "AssistantSessionArtifact", + "AssistantSessionState", + "AssistantSuggestion", "AudioEncoding", "AudioProcessingConfig", "AudioRecordingConfig", @@ -395,8 +464,12 @@ "BigQueryExportSettings", "Blob", "Callback", + "CancelAssistantTurnRequest", + "CancelAssistantTurnResponse", "Changelog", "ChannelProfile", + "ChatAiAssistantRequest", + "ChatAiAssistantResponse", "Chunk", "Citations", "ClientCertificateSettings", @@ -410,6 +483,7 @@ "CreateAgentRequest", "CreateAppRequest", "CreateAppVersionRequest", + "CreateAssistantSessionRequest", "CreateDeploymentRequest", "CreateEvaluationDatasetRequest", "CreateEvaluationExpectationRequest", @@ -419,12 +493,15 @@ "CreateScheduledEvaluationRunRequest", "CreateToolRequest", "CreateToolsetRequest", + "CustomVoiceSample", + "DashboardSettings", "DataStore", "DataStoreSettings", "DataStoreTool", "DeleteAgentRequest", "DeleteAppRequest", "DeleteAppVersionRequest", + "DeleteAssistantSessionRequest", "DeleteConversationRequest", "DeleteDeploymentRequest", "DeleteEvaluationDatasetRequest", @@ -438,6 +515,7 @@ "DeleteScheduledEvaluationRunRequest", "DeleteToolRequest", "DeleteToolsetRequest", + "DeployChannelResponse", "Deployment", "EndSession", "EndUserAuthConfig", @@ -484,9 +562,12 @@ "GenerateChatTokenResponse", "GenerateEvaluationOperationMetadata", "GenerateEvaluationRequest", + "GenerateOnboardingSuggestionsRequest", + "GenerateOnboardingSuggestionsResponse", "GetAgentRequest", "GetAppRequest", "GetAppVersionRequest", + "GetAssistantSessionRequest", "GetChangelogRequest", "GetConversationRequest", "GetDeploymentRequest", @@ -523,6 +604,8 @@ "ListAppVersionsResponse", "ListAppsRequest", "ListAppsResponse", + "ListAssistantSessionsRequest", + "ListAssistantSessionsResponse", "ListChangelogsRequest", "ListChangelogsResponse", "ListConversationsRequest", @@ -565,8 +648,10 @@ "OmnichannelOperationMetadata", "OpenApiTool", "OpenApiToolset", + "OperationCompletedEvent", "OperationMetadata", "OptimizationConfig", + "OptionQuestionsChunk", "OutputAudioConfig", "PersonaRunConfig", "PythonCodeCondition", @@ -574,6 +659,7 @@ "QualityReport", "RecognitionResult", "RedactionConfig", + "RemoteA2aConfig", "RemoteAgentTool", "RestoreAppVersionRequest", "RestoreAppVersionResponse", @@ -581,6 +667,8 @@ "RetrieveToolSchemaResponse", "RetrieveToolsRequest", "RetrieveToolsResponse", + "RunAssistantRequest", + "RunAssistantResponse", "RunEvaluationOperationMetadata", "RunEvaluationRequest", "RunEvaluationResponse", @@ -595,11 +683,14 @@ "ServiceAccountAuthConfig", "ServiceAgentIdTokenAuthConfig", "ServiceDirectoryConfig", + "SessionCheckpoint", "SessionConfig", "SessionInput", "SessionOutput", "SessionServiceClient", "Span", + "StreamChatAiAssistantRequest", + "StreamChatAiAssistantResponse", "SynthesizeSpeechConfig", "SystemTool", "TestPersonaVoiceRequest", @@ -617,8 +708,15 @@ "ToolsetTool", "TransferRule", "TriggerAction", + "TurnCompletedEvent", + "TurnHandoffEvent", + "TurnMetadata", + "TurnResumeSnapshot", + "TypedPayload", + "UiEvent", "UpdateAgentRequest", "UpdateAppRequest", + "UpdateAppVersionRequest", "UpdateDeploymentRequest", "UpdateEvaluationDatasetRequest", "UpdateEvaluationExpectationRequest", @@ -631,6 +729,7 @@ "UpdateToolsetRequest", "UploadEvaluationAudioRequest", "UploadEvaluationAudioResponse", + "UserResponseSuggestions", "VpcScSettings", "WebSearchQuery", "WhatsAppCredentials", diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/gapic_metadata.json b/packages/google-cloud-ces/google/cloud/ces_v1beta/gapic_metadata.json index 3087689d4deb..ea8a4666ce1e 100644 --- a/packages/google-cloud-ces/google/cloud/ces_v1beta/gapic_metadata.json +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/gapic_metadata.json @@ -235,6 +235,11 @@ "update_app" ] }, + "UpdateAppVersion": { + "methods": [ + "update_app_version" + ] + }, "UpdateDeployment": { "methods": [ "update_deployment" @@ -495,6 +500,11 @@ "update_app" ] }, + "UpdateAppVersion": { + "methods": [ + "update_app_version" + ] + }, "UpdateDeployment": { "methods": [ "update_deployment" @@ -755,6 +765,11 @@ "update_app" ] }, + "UpdateAppVersion": { + "methods": [ + "update_app_version" + ] + }, "UpdateDeployment": { "methods": [ "update_deployment" @@ -789,6 +804,115 @@ } } }, + "AssistantService": { + "clients": { + "grpc": { + "libraryClient": "AssistantServiceClient", + "rpcs": { + "ChatAiAssistant": { + "methods": [ + "chat_ai_assistant" + ] + }, + "CreateAssistantSession": { + "methods": [ + "create_assistant_session" + ] + }, + "DeleteAssistantSession": { + "methods": [ + "delete_assistant_session" + ] + }, + "GetAssistantSession": { + "methods": [ + "get_assistant_session" + ] + }, + "ListAssistantSessions": { + "methods": [ + "list_assistant_sessions" + ] + }, + "RunAssistant": { + "methods": [ + "run_assistant" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AssistantServiceAsyncClient", + "rpcs": { + "ChatAiAssistant": { + "methods": [ + "chat_ai_assistant" + ] + }, + "CreateAssistantSession": { + "methods": [ + "create_assistant_session" + ] + }, + "DeleteAssistantSession": { + "methods": [ + "delete_assistant_session" + ] + }, + "GetAssistantSession": { + "methods": [ + "get_assistant_session" + ] + }, + "ListAssistantSessions": { + "methods": [ + "list_assistant_sessions" + ] + }, + "RunAssistant": { + "methods": [ + "run_assistant" + ] + } + } + }, + "rest": { + "libraryClient": "AssistantServiceClient", + "rpcs": { + "ChatAiAssistant": { + "methods": [ + "chat_ai_assistant" + ] + }, + "CreateAssistantSession": { + "methods": [ + "create_assistant_session" + ] + }, + "DeleteAssistantSession": { + "methods": [ + "delete_assistant_session" + ] + }, + "GetAssistantSession": { + "methods": [ + "get_assistant_session" + ] + }, + "ListAssistantSessions": { + "methods": [ + "list_assistant_sessions" + ] + }, + "RunAssistant": { + "methods": [ + "run_assistant" + ] + } + } + } + } + }, "EvaluationService": { "clients": { "grpc": { @@ -1343,11 +1467,26 @@ "bidi_run_session" ] }, + "CancelAssistantTurn": { + "methods": [ + "cancel_assistant_turn" + ] + }, + "GenerateOnboardingSuggestions": { + "methods": [ + "generate_onboarding_suggestions" + ] + }, "RunSession": { "methods": [ "run_session" ] }, + "StreamChatAiAssistant": { + "methods": [ + "stream_chat_ai_assistant" + ] + }, "StreamRunSession": { "methods": [ "stream_run_session" @@ -1363,11 +1502,26 @@ "bidi_run_session" ] }, + "CancelAssistantTurn": { + "methods": [ + "cancel_assistant_turn" + ] + }, + "GenerateOnboardingSuggestions": { + "methods": [ + "generate_onboarding_suggestions" + ] + }, "RunSession": { "methods": [ "run_session" ] }, + "StreamChatAiAssistant": { + "methods": [ + "stream_chat_ai_assistant" + ] + }, "StreamRunSession": { "methods": [ "stream_run_session" @@ -1383,11 +1537,26 @@ "bidi_run_session" ] }, + "CancelAssistantTurn": { + "methods": [ + "cancel_assistant_turn" + ] + }, + "GenerateOnboardingSuggestions": { + "methods": [ + "generate_onboarding_suggestions" + ] + }, "RunSession": { "methods": [ "run_session" ] }, + "StreamChatAiAssistant": { + "methods": [ + "stream_chat_ai_assistant" + ] + }, "StreamRunSession": { "methods": [ "stream_run_session" diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/async_client.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/async_client.py index 47403f8dc673..f034274560f2 100644 --- a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/async_client.py +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/async_client.py @@ -127,6 +127,12 @@ class AgentServiceAsyncClient: agent_path = staticmethod(AgentServiceClient.agent_path) parse_agent_path = staticmethod(AgentServiceClient.parse_agent_path) + agent_registry_service_path = staticmethod( + AgentServiceClient.agent_registry_service_path + ) + parse_agent_registry_service_path = staticmethod( + AgentServiceClient.parse_agent_registry_service_path + ) app_path = staticmethod(AgentServiceClient.app_path) parse_app_path = staticmethod(AgentServiceClient.parse_app_path) app_version_path = staticmethod(AgentServiceClient.app_version_path) @@ -135,6 +141,8 @@ class AgentServiceAsyncClient: parse_changelog_path = staticmethod(AgentServiceClient.parse_changelog_path) conversation_path = staticmethod(AgentServiceClient.conversation_path) parse_conversation_path = staticmethod(AgentServiceClient.parse_conversation_path) + dashboard_path = staticmethod(AgentServiceClient.dashboard_path) + parse_dashboard_path = staticmethod(AgentServiceClient.parse_dashboard_path) dataset_path = staticmethod(AgentServiceClient.dataset_path) parse_dataset_path = staticmethod(AgentServiceClient.parse_dataset_path) deidentify_template_path = staticmethod(AgentServiceClient.deidentify_template_path) @@ -1216,6 +1224,7 @@ async def sample_import_app(): # Initialize request argument(s) request = ces_v1beta.ImportAppRequest( gcs_uri="gcs_uri_value", + json_patch_content="json_patch_content_value", parent="parent_value", ) @@ -4125,7 +4134,7 @@ async def sample_create_guardrail(): # Initialize request argument(s) guardrail = ces_v1beta.Guardrail() - guardrail.content_filter.match_type = "REGEXP_MATCH" + guardrail.content_filter.match_type = "SENSITIVE_WORDS" guardrail.display_name = "display_name_value" request = ces_v1beta.CreateGuardrailRequest( @@ -4263,7 +4272,7 @@ async def sample_update_guardrail(): # Initialize request argument(s) guardrail = ces_v1beta.Guardrail() - guardrail.content_filter.match_type = "REGEXP_MATCH" + guardrail.content_filter.match_type = "SENSITIVE_WORDS" guardrail.display_name = "display_name_value" request = ces_v1beta.UpdateGuardrailRequest( @@ -6042,6 +6051,129 @@ async def sample_create_app_version(): # Done; return the response. return response + async def update_app_version( + self, + request: Optional[Union[agent_service.UpdateAppVersionRequest, dict]] = None, + *, + app_version: Optional[gcc_app_version.AppVersion] = 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, Union[str, bytes]]] = (), + ) -> gcc_app_version.AppVersion: + r"""Updates the specified app version. + + .. 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 ces_v1beta + + async def sample_update_app_version(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.UpdateAppVersionRequest( + ) + + # Make the request + response = await client.update_app_version(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.UpdateAppVersionRequest, dict]]): + The request object. Request message for + [AgentService.UpdateAppVersion][google.cloud.ces.v1beta.AgentService.UpdateAppVersion]. + app_version (:class:`google.cloud.ces_v1beta.types.AppVersion`): + Required. The app version to update. + This corresponds to the ``app_version`` 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 list of fields to update. If empty, fields + ``display_name`` and ``description`` 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.AppVersion: + In Customer Engagement Suite (CES), + an app version is a snapshot of the app + at a specific point in time. It is + immutable and cannot be modified once + created. + + """ + # 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. + flattened_params = [app_version, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + 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." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.UpdateAppVersionRequest): + request = agent_service.UpdateAppVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if app_version is not None: + request.app_version = app_version + 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._client._transport._wrapped_methods[ + self._client._transport.update_app_version + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("app_version.name", request.app_version.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def delete_app_version( self, request: Optional[Union[agent_service.DeleteAppVersionRequest, dict]] = None, diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/client.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/client.py index ae14e010e1be..c375e5fa0155 100644 --- a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/client.py +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/client.py @@ -247,6 +247,28 @@ def parse_agent_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def agent_registry_service_path( + project: str, + location: str, + service: str, + ) -> str: + """Returns a fully-qualified agent_registry_service string.""" + return "projects/{project}/locations/{location}/services/{service}".format( + project=project, + location=location, + service=service, + ) + + @staticmethod + def parse_agent_registry_service_path(path: str) -> Dict[str, str]: + """Parses a agent_registry_service path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/services/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def app_path( project: str, @@ -341,6 +363,28 @@ def parse_conversation_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def dashboard_path( + project: str, + location: str, + dashboard: str, + ) -> str: + """Returns a fully-qualified dashboard string.""" + return "projects/{project}/locations/{location}/dashboards/{dashboard}".format( + project=project, + location=location, + dashboard=dashboard, + ) + + @staticmethod + def parse_dashboard_path(path: str) -> Dict[str, str]: + """Parses a dashboard path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/dashboards/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def dataset_path( project: str, @@ -1955,6 +1999,7 @@ def sample_import_app(): # Initialize request argument(s) request = ces_v1beta.ImportAppRequest( gcs_uri="gcs_uri_value", + json_patch_content="json_patch_content_value", parent="parent_value", ) @@ -4796,7 +4841,7 @@ def sample_create_guardrail(): # Initialize request argument(s) guardrail = ces_v1beta.Guardrail() - guardrail.content_filter.match_type = "REGEXP_MATCH" + guardrail.content_filter.match_type = "SENSITIVE_WORDS" guardrail.display_name = "display_name_value" request = ces_v1beta.CreateGuardrailRequest( @@ -4931,7 +4976,7 @@ def sample_update_guardrail(): # Initialize request argument(s) guardrail = ces_v1beta.Guardrail() - guardrail.content_filter.match_type = "REGEXP_MATCH" + guardrail.content_filter.match_type = "SENSITIVE_WORDS" guardrail.display_name = "display_name_value" request = ces_v1beta.UpdateGuardrailRequest( @@ -6665,6 +6710,126 @@ def sample_create_app_version(): # Done; return the response. return response + def update_app_version( + self, + request: Optional[Union[agent_service.UpdateAppVersionRequest, dict]] = None, + *, + app_version: Optional[gcc_app_version.AppVersion] = 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, Union[str, bytes]]] = (), + ) -> gcc_app_version.AppVersion: + r"""Updates the specified app version. + + .. 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 ces_v1beta + + def sample_update_app_version(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.UpdateAppVersionRequest( + ) + + # Make the request + response = client.update_app_version(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.UpdateAppVersionRequest, dict]): + The request object. Request message for + [AgentService.UpdateAppVersion][google.cloud.ces.v1beta.AgentService.UpdateAppVersion]. + app_version (google.cloud.ces_v1beta.types.AppVersion): + Required. The app version to update. + This corresponds to the ``app_version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to update. If empty, fields + ``display_name`` and ``description`` 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.AppVersion: + In Customer Engagement Suite (CES), + an app version is a snapshot of the app + at a specific point in time. It is + immutable and cannot be modified once + created. + + """ + # 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. + flattened_params = [app_version, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + 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." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.UpdateAppVersionRequest): + request = agent_service.UpdateAppVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if app_version is not None: + request.app_version = app_version + 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_app_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("app_version.name", request.app_version.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def delete_app_version( self, request: Optional[Union[agent_service.DeleteAppVersionRequest, dict]] = None, diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/base.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/base.py index 9dfc74f16ef5..388c0c10a5d9 100644 --- a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/base.py +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/base.py @@ -398,6 +398,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.update_app_version: gapic_v1.method.wrap_method( + self.update_app_version, + default_timeout=None, + client_info=client_info, + ), self.delete_app_version: gapic_v1.method.wrap_method( self.delete_app_version, default_timeout=None, @@ -908,6 +913,15 @@ def create_app_version( ]: raise NotImplementedError() + @property + def update_app_version( + self, + ) -> Callable[ + [agent_service.UpdateAppVersionRequest], + Union[gcc_app_version.AppVersion, Awaitable[gcc_app_version.AppVersion]], + ]: + raise NotImplementedError() + @property def delete_app_version( self, diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/grpc.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/grpc.py index 120a96623c82..bbc14e3d3a2d 100644 --- a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/grpc.py +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/grpc.py @@ -1576,6 +1576,32 @@ def create_app_version( ) return self._stubs["create_app_version"] + @property + def update_app_version( + self, + ) -> Callable[[agent_service.UpdateAppVersionRequest], gcc_app_version.AppVersion]: + r"""Return a callable for the update app version method over gRPC. + + Updates the specified app version. + + Returns: + Callable[[~.UpdateAppVersionRequest], + ~.AppVersion]: + 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_app_version" not in self._stubs: + self._stubs["update_app_version"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/UpdateAppVersion", + request_serializer=agent_service.UpdateAppVersionRequest.serialize, + response_deserializer=gcc_app_version.AppVersion.deserialize, + ) + return self._stubs["update_app_version"] + @property def delete_app_version( self, diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/grpc_asyncio.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/grpc_asyncio.py index 87420d3e9fc0..b02b52782420 100644 --- a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/grpc_asyncio.py @@ -1633,6 +1633,34 @@ def create_app_version( ) return self._stubs["create_app_version"] + @property + def update_app_version( + self, + ) -> Callable[ + [agent_service.UpdateAppVersionRequest], Awaitable[gcc_app_version.AppVersion] + ]: + r"""Return a callable for the update app version method over gRPC. + + Updates the specified app version. + + Returns: + Callable[[~.UpdateAppVersionRequest], + Awaitable[~.AppVersion]]: + 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_app_version" not in self._stubs: + self._stubs["update_app_version"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/UpdateAppVersion", + request_serializer=agent_service.UpdateAppVersionRequest.serialize, + response_deserializer=gcc_app_version.AppVersion.deserialize, + ) + return self._stubs["update_app_version"] + @property def delete_app_version( self, @@ -2007,6 +2035,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.update_app_version: self._wrap_method( + self.update_app_version, + default_timeout=None, + client_info=client_info, + ), self.delete_app_version: self._wrap_method( self.delete_app_version, default_timeout=None, diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/rest.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/rest.py index 6170d7b39fcd..5b8aa1475987 100644 --- a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/rest.py +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/rest.py @@ -425,6 +425,14 @@ def post_update_app(self, response): logging.log(f"Received response: {response}") return response + def pre_update_app_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_app_version(self, response): + logging.log(f"Received response: {response}") + return response + def pre_update_deployment(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -2334,6 +2342,54 @@ def post_update_app_with_metadata( """ return response, metadata + def pre_update_app_version( + self, + request: agent_service.UpdateAppVersionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.UpdateAppVersionRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_app_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_update_app_version( + self, response: gcc_app_version.AppVersion + ) -> gcc_app_version.AppVersion: + """Post-rpc interceptor for update_app_version + + DEPRECATED. Please use the `post_update_app_version_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_update_app_version` interceptor runs + before the `post_update_app_version_with_metadata` interceptor. + """ + return response + + def post_update_app_version_with_metadata( + self, + response: gcc_app_version.AppVersion, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gcc_app_version.AppVersion, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_app_version + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_update_app_version_with_metadata` + interceptor in new development instead of the `post_update_app_version` interceptor. + When both interceptors are used, this `post_update_app_version_with_metadata` interceptor runs after the + `post_update_app_version` interceptor. The (possibly modified) response returned by + `post_update_app_version` will be passed to + `post_update_app_version_with_metadata`. + """ + return response, metadata + def pre_update_deployment( self, request: agent_service.UpdateDeploymentRequest, @@ -9343,6 +9399,161 @@ def __call__( ) return resp + class _UpdateAppVersion( + _BaseAgentServiceRestTransport._BaseUpdateAppVersion, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.UpdateAppVersion") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: agent_service.UpdateAppVersionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_app_version.AppVersion: + r"""Call the update app version method over HTTP. + + Args: + request (~.agent_service.UpdateAppVersionRequest): + The request object. Request message for + [AgentService.UpdateAppVersion][google.cloud.ces.v1beta.AgentService.UpdateAppVersion]. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gcc_app_version.AppVersion: + In Customer Engagement Suite (CES), + an app version is a snapshot of the app + at a specific point in time. It is + immutable and cannot be modified once + created. + + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseUpdateAppVersion._get_http_options() + ) + request, metadata = self._interceptor.pre_update_app_version( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseAgentServiceRestTransport._BaseUpdateAppVersion, + "_BaseUpdateAppVersion__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.UpdateAppVersion", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "UpdateAppVersion", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._UpdateAppVersion._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + 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 = gcc_app_version.AppVersion() + pb_resp = gcc_app_version.AppVersion.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_app_version(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_app_version_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gcc_app_version.AppVersion.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.update_app_version", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "UpdateAppVersion", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _UpdateDeployment( _BaseAgentServiceRestTransport._BaseUpdateDeployment, AgentServiceRestStub ): @@ -10626,6 +10837,14 @@ def update_app(self) -> Callable[[agent_service.UpdateAppRequest], gcc_app.App]: # In C++ this would require a dynamic_cast return self._UpdateApp(self._session, self._host, self._interceptor) # type: ignore + @property + def update_app_version( + self, + ) -> Callable[[agent_service.UpdateAppVersionRequest], gcc_app_version.AppVersion]: + # 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._UpdateAppVersion(self._session, self._host, self._interceptor) # type: ignore + @property def update_deployment( self, diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/rest_base.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/rest_base.py index 338e4623c447..f7a4717bbee2 100644 --- a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/rest_base.py +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/rest_base.py @@ -847,6 +847,23 @@ def _get_http_options(): ] return http_options + class _BaseUpdateAppVersion: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta/{app_version.name=projects/*/locations/*/apps/*/versions/*}", + "body": "app_version", + }, + ] + return http_options + class _BaseUpdateDeployment: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/__init__.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/__init__.py new file mode 100644 index 000000000000..e85f773562fa --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 .async_client import AssistantServiceAsyncClient +from .client import AssistantServiceClient + +__all__ = ( + "AssistantServiceClient", + "AssistantServiceAsyncClient", +) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/async_client.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/async_client.py new file mode 100644 index 000000000000..909ffbfed4a0 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/async_client.py @@ -0,0 +1,1335 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +import logging as std_logging +import re +from collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.ces_v1beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.ces_v1beta.services.assistant_service import pagers +from google.cloud.ces_v1beta.types import assistant_service, common + +from .client import AssistantServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, AssistantServiceTransport +from .transports.grpc_asyncio import AssistantServiceGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class AssistantServiceAsyncClient: + """The service that manages assistant-related resources in + Customer Engagement Suite (CES). The assistant, Arc, is a + conversational agent embedded in CES applications to help users + with building their agents. + """ + + _client: AssistantServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = AssistantServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AssistantServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = AssistantServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = AssistantServiceClient._DEFAULT_UNIVERSE + + app_path = staticmethod(AssistantServiceClient.app_path) + parse_app_path = staticmethod(AssistantServiceClient.parse_app_path) + assistant_session_path = staticmethod(AssistantServiceClient.assistant_session_path) + parse_assistant_session_path = staticmethod( + AssistantServiceClient.parse_assistant_session_path + ) + common_billing_account_path = staticmethod( + AssistantServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + AssistantServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(AssistantServiceClient.common_folder_path) + parse_common_folder_path = staticmethod( + AssistantServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + AssistantServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + AssistantServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod(AssistantServiceClient.common_project_path) + parse_common_project_path = staticmethod( + AssistantServiceClient.parse_common_project_path + ) + common_location_path = staticmethod(AssistantServiceClient.common_location_path) + parse_common_location_path = staticmethod( + AssistantServiceClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + AssistantServiceAsyncClient: The constructed client. + """ + sa_info_func = ( + AssistantServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(AssistantServiceAsyncClient, info, *args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + AssistantServiceAsyncClient: The constructed client. + """ + sa_file_func = ( + AssistantServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(AssistantServiceAsyncClient, filename, *args, **kwargs) + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return AssistantServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> AssistantServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AssistantServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = AssistantServiceClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, AssistantServiceTransport, Callable[..., AssistantServiceTransport] + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the assistant service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,AssistantServiceTransport,Callable[..., AssistantServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the AssistantServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = AssistantServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.ces_v1beta.AssistantServiceAsyncClient`.", + extra={ + "serviceName": "google.cloud.ces.v1beta.AssistantService", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.cloud.ces.v1beta.AssistantService", + "credentialsType": None, + }, + ) + + async def list_assistant_sessions( + self, + request: Optional[ + Union[assistant_service.ListAssistantSessionsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAssistantSessionsAsyncPager: + r"""Lists all assistant sessions in the given app. + + .. 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 ces_v1beta + + async def sample_list_assistant_sessions(): + # Create a client + client = ces_v1beta.AssistantServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ListAssistantSessionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assistant_sessions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.ListAssistantSessionsRequest, dict]]): + The request object. Request message for + [AssistantService.ListAssistantSessions][google.cloud.ces.v1beta.AssistantService.ListAssistantSessions]. + parent (:class:`str`): + Required. The app to list assistant sessions from. + Format: + ``projects/{project}/locations/{location}/apps/{app}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.services.assistant_service.pagers.ListAssistantSessionsAsyncPager: + Response message for + [AssistantService.ListAssistantSessions][google.cloud.ces.v1beta.AssistantService.ListAssistantSessions]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # 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. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + 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." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, assistant_service.ListAssistantSessionsRequest): + request = assistant_service.ListAssistantSessionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_assistant_sessions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListAssistantSessionsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_assistant_session( + self, + request: Optional[ + Union[assistant_service.GetAssistantSessionRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> assistant_service.AssistantSession: + r"""Gets details of the specified assistant session. + + .. 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 ces_v1beta + + async def sample_get_assistant_session(): + # Create a client + client = ces_v1beta.AssistantServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GetAssistantSessionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_assistant_session(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.GetAssistantSessionRequest, dict]]): + The request object. Request message for + [AssistantService.GetAssistantSession][google.cloud.ces.v1beta.AssistantService.GetAssistantSession]. + name (:class:`str`): + Required. The name of the assistant session to retrieve. + Format: + ``projects/{project}/locations/{location}/apps/{app}/assistantSessions/{assistant_session}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.AssistantSession: + An assistant session represents a + conversation between a user and the + assistant agent. + + """ + # 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. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + 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." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, assistant_service.GetAssistantSessionRequest): + request = assistant_service.GetAssistantSessionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_assistant_session + ] + + # 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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_assistant_session( + self, + request: Optional[ + Union[assistant_service.CreateAssistantSessionRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + assistant_session_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> assistant_service.AssistantSession: + r"""Creates a new assistant session in the given app. + + .. 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 ces_v1beta + + async def sample_create_assistant_session(): + # Create a client + client = ces_v1beta.AssistantServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.CreateAssistantSessionRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_assistant_session(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.CreateAssistantSessionRequest, dict]]): + The request object. Request message for + [AssistantService.CreateAssistantSession][google.cloud.ces.v1beta.AssistantService.CreateAssistantSession]. + parent (:class:`str`): + Required. The app to create the assistant session in + Format: + ``projects/{project}/locations/{location}/apps/{app}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + assistant_session_id (:class:`str`): + Optional. The ID to use for the + assistant session, which will become the + final component of the assistant + session's resource name. If not + provided, a unique ID will be + automatically assigned for the assistant + session. + + This corresponds to the ``assistant_session_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.AssistantSession: + An assistant session represents a + conversation between a user and the + assistant agent. + + """ + # 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. + flattened_params = [parent, assistant_session_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + 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." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, assistant_service.CreateAssistantSessionRequest): + request = assistant_service.CreateAssistantSessionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if assistant_session_id is not None: + request.assistant_session_id = assistant_session_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_assistant_session + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_assistant_session( + self, + request: Optional[ + Union[assistant_service.DeleteAssistantSessionRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified assistant session. + + .. 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 ces_v1beta + + async def sample_delete_assistant_session(): + # Create a client + client = ces_v1beta.AssistantServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteAssistantSessionRequest( + name="name_value", + ) + + # Make the request + await client.delete_assistant_session(request=request) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.DeleteAssistantSessionRequest, dict]]): + The request object. Request message for + [AssistantService.DeleteAssistantSession][google.cloud.ces.v1beta.AssistantService.DeleteAssistantSession]. + name (:class:`str`): + Required. The name of the assistant session to delete. + Format: + ``projects/{project}/locations/{location}/apps/{app}/assistantSessions/{assistant_session}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # 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. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + 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." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, assistant_service.DeleteAssistantSessionRequest): + request = assistant_service.DeleteAssistantSessionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_assistant_session + ] + + # 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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def run_assistant( + self, + request: Optional[Union[assistant_service.RunAssistantRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> assistant_service.RunAssistantResponse: + r"""Runs the assistant agent for the specified assistant + session. + + .. 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 ces_v1beta + + async def sample_run_assistant(): + # Create a client + client = ces_v1beta.AssistantServiceAsyncClient() + + # Initialize request argument(s) + message = ces_v1beta.AssistantMessage() + message.role = "role_value" + + request = ces_v1beta.RunAssistantRequest( + app="app_value", + assistant_session="assistant_session_value", + message=message, + ) + + # Make the request + response = await client.run_assistant(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.RunAssistantRequest, dict]]): + The request object. Request message for + [AssistantService.RunAssistant][google.cloud.ces.v1beta.AssistantService.RunAssistant]. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.RunAssistantResponse: + Response message for + [AssistantService.RunAssistant][google.cloud.ces.v1beta.AssistantService.RunAssistant]. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, assistant_service.RunAssistantRequest): + request = assistant_service.RunAssistantRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.run_assistant + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("app", request.app),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def chat_ai_assistant( + self, + request: Optional[Union[assistant_service.ChatAiAssistantRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> assistant_service.ChatAiAssistantResponse: + r"""Runs Arc, the AI assistant, for the specified + assistant session. + + .. 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 ces_v1beta + + async def sample_chat_ai_assistant(): + # Create a client + client = ces_v1beta.AssistantServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ChatAiAssistantRequest( + app="app_value", + assistant_session="assistant_session_value", + message="message_value", + ) + + # Make the request + response = await client.chat_ai_assistant(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.ChatAiAssistantRequest, dict]]): + The request object. Request message for + [AssistantService.ChatAiAssistant][google.cloud.ces.v1beta.AssistantService.ChatAiAssistant]. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.ChatAiAssistantResponse: + Response message for + [AssistantService.ChatAiAssistant][google.cloud.ces.v1beta.AssistantService.ChatAiAssistant]. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, assistant_service.ChatAiAssistantRequest): + request = assistant_service.ChatAiAssistantRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.chat_ai_assistant + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("app", request.app),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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[Union[operations_pb2.ListOperationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.DeleteOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.DeleteOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_location( + self, + request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.GetLocationRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.GetLocationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.ListLocationsRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.ListLocationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "AssistantServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("AssistantServiceAsyncClient",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/client.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/client.py new file mode 100644 index 000000000000..a00d5bfad995 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/client.py @@ -0,0 +1,1659 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +import json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.ces_v1beta import gapic_version as package_version +from google.cloud.ces_v1beta._compat import ( + get_api_endpoint, + get_default_mtls_endpoint, + get_universe_domain, + read_environment_variables, + should_use_client_cert, +) + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.ces_v1beta.services.assistant_service import pagers +from google.cloud.ces_v1beta.types import assistant_service, common + +from .transports.base import DEFAULT_CLIENT_INFO, AssistantServiceTransport +from .transports.grpc import AssistantServiceGrpcTransport +from .transports.grpc_asyncio import AssistantServiceGrpcAsyncIOTransport +from .transports.rest import AssistantServiceRestTransport + + +class AssistantServiceClientMeta(type): + """Metaclass for the AssistantService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[AssistantServiceTransport]] + _transport_registry["grpc"] = AssistantServiceGrpcTransport + _transport_registry["grpc_asyncio"] = AssistantServiceGrpcAsyncIOTransport + _transport_registry["rest"] = AssistantServiceRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[AssistantServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class AssistantServiceClient(metaclass=AssistantServiceClientMeta): + """The service that manages assistant-related resources in + Customer Engagement Suite (CES). The assistant, Arc, is a + conversational agent embedded in CES applications to help users + with building their agents. + """ + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "ces.googleapis.com" + DEFAULT_MTLS_ENDPOINT = get_default_mtls_endpoint(DEFAULT_ENDPOINT) + + _DEFAULT_ENDPOINT_TEMPLATE = "ces.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + AssistantServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + AssistantServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> AssistantServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AssistantServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def app_path( + project: str, + location: str, + app: str, + ) -> str: + """Returns a fully-qualified app string.""" + return "projects/{project}/locations/{location}/apps/{app}".format( + project=project, + location=location, + app=app, + ) + + @staticmethod + def parse_app_path(path: str) -> Dict[str, str]: + """Parses a app path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/apps/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def assistant_session_path( + project: str, + location: str, + app: str, + assistant_session: str, + ) -> str: + """Returns a fully-qualified assistant_session string.""" + return "projects/{project}/locations/{location}/apps/{app}/assistantSessions/{assistant_session}".format( + project=project, + location=location, + app=app, + assistant_session=assistant_session, + ) + + @staticmethod + def parse_assistant_session_path(path: str) -> Dict[str, str]: + """Parses a assistant_session path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/apps/(?P.+?)/assistantSessions/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = should_use_client_cert() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, AssistantServiceTransport, Callable[..., AssistantServiceTransport] + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the assistant service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,AssistantServiceTransport,Callable[..., AssistantServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the AssistantServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + read_environment_variables() + ) + self._client_cert_source = AssistantServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = get_universe_domain( + universe_domain_opt, + self._universe_domain_env, + default_universe=AssistantServiceClient._DEFAULT_UNIVERSE, + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, AssistantServiceTransport) + if transport_provided: + # transport is a AssistantServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(AssistantServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or get_api_endpoint( + api_override=self._client_options.api_endpoint, + universe_domain=self._universe_domain, + default_universe=AssistantServiceClient._DEFAULT_UNIVERSE, + default_mtls_endpoint=AssistantServiceClient.DEFAULT_MTLS_ENDPOINT, + default_endpoint_template=AssistantServiceClient._DEFAULT_ENDPOINT_TEMPLATE, + use_mtls=self._use_mtls_endpoint == "always" + or (self._use_mtls_endpoint == "auto" and self._client_cert_source), + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[AssistantServiceTransport], + Callable[..., AssistantServiceTransport], + ] = ( + AssistantServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., AssistantServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.ces_v1beta.AssistantServiceClient`.", + extra={ + "serviceName": "google.cloud.ces.v1beta.AssistantService", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.cloud.ces.v1beta.AssistantService", + "credentialsType": None, + }, + ) + + def list_assistant_sessions( + self, + request: Optional[ + Union[assistant_service.ListAssistantSessionsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAssistantSessionsPager: + r"""Lists all assistant sessions in the given app. + + .. 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 ces_v1beta + + def sample_list_assistant_sessions(): + # Create a client + client = ces_v1beta.AssistantServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ListAssistantSessionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assistant_sessions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.ListAssistantSessionsRequest, dict]): + The request object. Request message for + [AssistantService.ListAssistantSessions][google.cloud.ces.v1beta.AssistantService.ListAssistantSessions]. + parent (str): + Required. The app to list assistant sessions from. + Format: + ``projects/{project}/locations/{location}/apps/{app}`` + + This corresponds to the ``parent`` 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.services.assistant_service.pagers.ListAssistantSessionsPager: + Response message for + [AssistantService.ListAssistantSessions][google.cloud.ces.v1beta.AssistantService.ListAssistantSessions]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # 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. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + 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." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, assistant_service.ListAssistantSessionsRequest): + request = assistant_service.ListAssistantSessionsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_assistant_sessions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListAssistantSessionsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_assistant_session( + self, + request: Optional[ + Union[assistant_service.GetAssistantSessionRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> assistant_service.AssistantSession: + r"""Gets details of the specified assistant session. + + .. 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 ces_v1beta + + def sample_get_assistant_session(): + # Create a client + client = ces_v1beta.AssistantServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GetAssistantSessionRequest( + name="name_value", + ) + + # Make the request + response = client.get_assistant_session(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.GetAssistantSessionRequest, dict]): + The request object. Request message for + [AssistantService.GetAssistantSession][google.cloud.ces.v1beta.AssistantService.GetAssistantSession]. + name (str): + Required. The name of the assistant session to retrieve. + Format: + ``projects/{project}/locations/{location}/apps/{app}/assistantSessions/{assistant_session}`` + + This corresponds to the ``name`` 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.AssistantSession: + An assistant session represents a + conversation between a user and the + assistant agent. + + """ + # 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. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + 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." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, assistant_service.GetAssistantSessionRequest): + request = assistant_service.GetAssistantSessionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_assistant_session] + + # 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_assistant_session( + self, + request: Optional[ + Union[assistant_service.CreateAssistantSessionRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + assistant_session_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> assistant_service.AssistantSession: + r"""Creates a new assistant session in the given app. + + .. 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 ces_v1beta + + def sample_create_assistant_session(): + # Create a client + client = ces_v1beta.AssistantServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.CreateAssistantSessionRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_assistant_session(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.CreateAssistantSessionRequest, dict]): + The request object. Request message for + [AssistantService.CreateAssistantSession][google.cloud.ces.v1beta.AssistantService.CreateAssistantSession]. + parent (str): + Required. The app to create the assistant session in + Format: + ``projects/{project}/locations/{location}/apps/{app}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + assistant_session_id (str): + Optional. The ID to use for the + assistant session, which will become the + final component of the assistant + session's resource name. If not + provided, a unique ID will be + automatically assigned for the assistant + session. + + This corresponds to the ``assistant_session_id`` 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.AssistantSession: + An assistant session represents a + conversation between a user and the + assistant agent. + + """ + # 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. + flattened_params = [parent, assistant_session_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + 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." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, assistant_service.CreateAssistantSessionRequest): + request = assistant_service.CreateAssistantSessionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if assistant_session_id is not None: + request.assistant_session_id = assistant_session_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_assistant_session] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_assistant_session( + self, + request: Optional[ + Union[assistant_service.DeleteAssistantSessionRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified assistant session. + + .. 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 ces_v1beta + + def sample_delete_assistant_session(): + # Create a client + client = ces_v1beta.AssistantServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteAssistantSessionRequest( + name="name_value", + ) + + # Make the request + client.delete_assistant_session(request=request) + + Args: + request (Union[google.cloud.ces_v1beta.types.DeleteAssistantSessionRequest, dict]): + The request object. Request message for + [AssistantService.DeleteAssistantSession][google.cloud.ces.v1beta.AssistantService.DeleteAssistantSession]. + name (str): + Required. The name of the assistant session to delete. + Format: + ``projects/{project}/locations/{location}/apps/{app}/assistantSessions/{assistant_session}`` + + This corresponds to the ``name`` 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # 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. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + 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." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, assistant_service.DeleteAssistantSessionRequest): + request = assistant_service.DeleteAssistantSessionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_assistant_session] + + # 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def run_assistant( + self, + request: Optional[Union[assistant_service.RunAssistantRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> assistant_service.RunAssistantResponse: + r"""Runs the assistant agent for the specified assistant + session. + + .. 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 ces_v1beta + + def sample_run_assistant(): + # Create a client + client = ces_v1beta.AssistantServiceClient() + + # Initialize request argument(s) + message = ces_v1beta.AssistantMessage() + message.role = "role_value" + + request = ces_v1beta.RunAssistantRequest( + app="app_value", + assistant_session="assistant_session_value", + message=message, + ) + + # Make the request + response = client.run_assistant(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.RunAssistantRequest, dict]): + The request object. Request message for + [AssistantService.RunAssistant][google.cloud.ces.v1beta.AssistantService.RunAssistant]. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.RunAssistantResponse: + Response message for + [AssistantService.RunAssistant][google.cloud.ces.v1beta.AssistantService.RunAssistant]. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, assistant_service.RunAssistantRequest): + request = assistant_service.RunAssistantRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.run_assistant] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("app", request.app),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def chat_ai_assistant( + self, + request: Optional[Union[assistant_service.ChatAiAssistantRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> assistant_service.ChatAiAssistantResponse: + r"""Runs Arc, the AI assistant, for the specified + assistant session. + + .. 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 ces_v1beta + + def sample_chat_ai_assistant(): + # Create a client + client = ces_v1beta.AssistantServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ChatAiAssistantRequest( + app="app_value", + assistant_session="assistant_session_value", + message="message_value", + ) + + # Make the request + response = client.chat_ai_assistant(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.ChatAiAssistantRequest, dict]): + The request object. Request message for + [AssistantService.ChatAiAssistant][google.cloud.ces.v1beta.AssistantService.ChatAiAssistant]. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.ChatAiAssistantResponse: + Response message for + [AssistantService.ChatAiAssistant][google.cloud.ces.v1beta.AssistantService.ChatAiAssistant]. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, assistant_service.ChatAiAssistantRequest): + request = assistant_service.ChatAiAssistantRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.chat_ai_assistant] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("app", request.app),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "AssistantServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def delete_operation( + self, + request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.DeleteOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.DeleteOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_location( + self, + request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.GetLocationRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.GetLocationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def list_locations( + self, + request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.ListLocationsRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.ListLocationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("AssistantServiceClient",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/pagers.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/pagers.py new file mode 100644 index 000000000000..226a2b97c74b --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/pagers.py @@ -0,0 +1,201 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.ces_v1beta.types import assistant_service + + +class ListAssistantSessionsPager: + """A pager for iterating through ``list_assistant_sessions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.ces_v1beta.types.ListAssistantSessionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``assistant_sessions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAssistantSessions`` requests and continue to iterate + through the ``assistant_sessions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.ces_v1beta.types.ListAssistantSessionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., assistant_service.ListAssistantSessionsResponse], + request: assistant_service.ListAssistantSessionsRequest, + response: assistant_service.ListAssistantSessionsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.ces_v1beta.types.ListAssistantSessionsRequest): + The initial request object. + response (google.cloud.ces_v1beta.types.ListAssistantSessionsResponse): + The initial response object. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = assistant_service.ListAssistantSessionsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[assistant_service.ListAssistantSessionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[assistant_service.AssistantSession]: + for page in self.pages: + yield from page.assistant_sessions + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAssistantSessionsAsyncPager: + """A pager for iterating through ``list_assistant_sessions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.ces_v1beta.types.ListAssistantSessionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``assistant_sessions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAssistantSessions`` requests and continue to iterate + through the ``assistant_sessions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.ces_v1beta.types.ListAssistantSessionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., Awaitable[assistant_service.ListAssistantSessionsResponse] + ], + request: assistant_service.ListAssistantSessionsRequest, + response: assistant_service.ListAssistantSessionsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.ces_v1beta.types.ListAssistantSessionsRequest): + The initial request object. + response (google.cloud.ces_v1beta.types.ListAssistantSessionsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = assistant_service.ListAssistantSessionsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[assistant_service.ListAssistantSessionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[assistant_service.AssistantSession]: + async def async_generator(): + async for page in self.pages: + for response in page.assistant_sessions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/transports/README.rst b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/transports/README.rst new file mode 100644 index 000000000000..098d53ed8fdd --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/transports/README.rst @@ -0,0 +1,10 @@ + +transport inheritance structure +_______________________________ + +``AssistantServiceTransport`` is the ABC for all transports. + +- public child ``AssistantServiceGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). +- public child ``AssistantServiceGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). +- private child ``_BaseAssistantServiceRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). +- public child ``AssistantServiceRestTransport`` for sync REST transport with inner classes ``METHOD`` derived from the parent's corresponding ``_BaseMETHOD`` classes (defined in ``rest.py``). diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/transports/__init__.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/transports/__init__.py new file mode 100644 index 000000000000..770d1dcab785 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 collections import OrderedDict +from typing import Dict, Type + +from .base import AssistantServiceTransport +from .grpc import AssistantServiceGrpcTransport +from .grpc_asyncio import AssistantServiceGrpcAsyncIOTransport +from .rest import AssistantServiceRestInterceptor, AssistantServiceRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AssistantServiceTransport]] +_transport_registry["grpc"] = AssistantServiceGrpcTransport +_transport_registry["grpc_asyncio"] = AssistantServiceGrpcAsyncIOTransport +_transport_registry["rest"] = AssistantServiceRestTransport + +__all__ = ( + "AssistantServiceTransport", + "AssistantServiceGrpcTransport", + "AssistantServiceGrpcAsyncIOTransport", + "AssistantServiceRestTransport", + "AssistantServiceRestInterceptor", +) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/transports/base.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/transports/base.py new file mode 100644 index 000000000000..cb11c681b910 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/transports/base.py @@ -0,0 +1,364 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.ces_v1beta import gapic_version as package_version +from google.cloud.ces_v1beta.types import assistant_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class AssistantServiceTransport(abc.ABC): + """Abstract transport class for AssistantService.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/ces", + "https://www.googleapis.com/auth/cloud-platform", + ) + + DEFAULT_HOST: str = "ces.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'ces.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_assistant_sessions: gapic_v1.method.wrap_method( + self.list_assistant_sessions, + default_timeout=None, + client_info=client_info, + ), + self.get_assistant_session: gapic_v1.method.wrap_method( + self.get_assistant_session, + default_timeout=None, + client_info=client_info, + ), + self.create_assistant_session: gapic_v1.method.wrap_method( + self.create_assistant_session, + default_timeout=None, + client_info=client_info, + ), + self.delete_assistant_session: gapic_v1.method.wrap_method( + self.delete_assistant_session, + default_timeout=None, + client_info=client_info, + ), + self.run_assistant: gapic_v1.method.wrap_method( + self.run_assistant, + default_timeout=None, + client_info=client_info, + ), + self.chat_ai_assistant: gapic_v1.method.wrap_method( + self.chat_ai_assistant, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=300.0, + ), + default_timeout=300.0, + client_info=client_info, + ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def list_assistant_sessions( + self, + ) -> Callable[ + [assistant_service.ListAssistantSessionsRequest], + Union[ + assistant_service.ListAssistantSessionsResponse, + Awaitable[assistant_service.ListAssistantSessionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_assistant_session( + self, + ) -> Callable[ + [assistant_service.GetAssistantSessionRequest], + Union[ + assistant_service.AssistantSession, + Awaitable[assistant_service.AssistantSession], + ], + ]: + raise NotImplementedError() + + @property + def create_assistant_session( + self, + ) -> Callable[ + [assistant_service.CreateAssistantSessionRequest], + Union[ + assistant_service.AssistantSession, + Awaitable[assistant_service.AssistantSession], + ], + ]: + raise NotImplementedError() + + @property + def delete_assistant_session( + self, + ) -> Callable[ + [assistant_service.DeleteAssistantSessionRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def run_assistant( + self, + ) -> Callable[ + [assistant_service.RunAssistantRequest], + Union[ + assistant_service.RunAssistantResponse, + Awaitable[assistant_service.RunAssistantResponse], + ], + ]: + raise NotImplementedError() + + @property + def chat_ai_assistant( + self, + ) -> Callable[ + [assistant_service.ChatAiAssistantRequest], + Union[ + assistant_service.ChatAiAssistantResponse, + Awaitable[assistant_service.ChatAiAssistantResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def get_location( + self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[ + locations_pb2.ListLocationsResponse, + Awaitable[locations_pb2.ListLocationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("AssistantServiceTransport",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/transports/grpc.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/transports/grpc.py new file mode 100644 index 000000000000..6e461bd61813 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/transports/grpc.py @@ -0,0 +1,620 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +import json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson + +from google.cloud.ces_v1beta.types import assistant_service + +from .base import DEFAULT_CLIENT_INFO, AssistantServiceTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.ces.v1beta.AssistantService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.ces.v1beta.AssistantService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class AssistantServiceGrpcTransport(AssistantServiceTransport): + """gRPC backend transport for AssistantService. + + The service that manages assistant-related resources in + Customer Engagement Suite (CES). The assistant, Arc, is a + conversational agent embedded in CES applications to help users + with building their agents. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "ces.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'ces.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "ces.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def list_assistant_sessions( + self, + ) -> Callable[ + [assistant_service.ListAssistantSessionsRequest], + assistant_service.ListAssistantSessionsResponse, + ]: + r"""Return a callable for the list assistant sessions method over gRPC. + + Lists all assistant sessions in the given app. + + Returns: + Callable[[~.ListAssistantSessionsRequest], + ~.ListAssistantSessionsResponse]: + 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 "list_assistant_sessions" not in self._stubs: + self._stubs["list_assistant_sessions"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AssistantService/ListAssistantSessions", + request_serializer=assistant_service.ListAssistantSessionsRequest.serialize, + response_deserializer=assistant_service.ListAssistantSessionsResponse.deserialize, + ) + return self._stubs["list_assistant_sessions"] + + @property + def get_assistant_session( + self, + ) -> Callable[ + [assistant_service.GetAssistantSessionRequest], + assistant_service.AssistantSession, + ]: + r"""Return a callable for the get assistant session method over gRPC. + + Gets details of the specified assistant session. + + Returns: + Callable[[~.GetAssistantSessionRequest], + ~.AssistantSession]: + 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_assistant_session" not in self._stubs: + self._stubs["get_assistant_session"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AssistantService/GetAssistantSession", + request_serializer=assistant_service.GetAssistantSessionRequest.serialize, + response_deserializer=assistant_service.AssistantSession.deserialize, + ) + return self._stubs["get_assistant_session"] + + @property + def create_assistant_session( + self, + ) -> Callable[ + [assistant_service.CreateAssistantSessionRequest], + assistant_service.AssistantSession, + ]: + r"""Return a callable for the create assistant session method over gRPC. + + Creates a new assistant session in the given app. + + Returns: + Callable[[~.CreateAssistantSessionRequest], + ~.AssistantSession]: + 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 "create_assistant_session" not in self._stubs: + self._stubs["create_assistant_session"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AssistantService/CreateAssistantSession", + request_serializer=assistant_service.CreateAssistantSessionRequest.serialize, + response_deserializer=assistant_service.AssistantSession.deserialize, + ) + return self._stubs["create_assistant_session"] + + @property + def delete_assistant_session( + self, + ) -> Callable[[assistant_service.DeleteAssistantSessionRequest], empty_pb2.Empty]: + r"""Return a callable for the delete assistant session method over gRPC. + + Deletes the specified assistant session. + + Returns: + Callable[[~.DeleteAssistantSessionRequest], + ~.Empty]: + 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 "delete_assistant_session" not in self._stubs: + self._stubs["delete_assistant_session"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AssistantService/DeleteAssistantSession", + request_serializer=assistant_service.DeleteAssistantSessionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_assistant_session"] + + @property + def run_assistant( + self, + ) -> Callable[ + [assistant_service.RunAssistantRequest], assistant_service.RunAssistantResponse + ]: + r"""Return a callable for the run assistant method over gRPC. + + Runs the assistant agent for the specified assistant + session. + + Returns: + Callable[[~.RunAssistantRequest], + ~.RunAssistantResponse]: + 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 "run_assistant" not in self._stubs: + self._stubs["run_assistant"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AssistantService/RunAssistant", + request_serializer=assistant_service.RunAssistantRequest.serialize, + response_deserializer=assistant_service.RunAssistantResponse.deserialize, + ) + return self._stubs["run_assistant"] + + @property + def chat_ai_assistant( + self, + ) -> Callable[ + [assistant_service.ChatAiAssistantRequest], + assistant_service.ChatAiAssistantResponse, + ]: + r"""Return a callable for the chat ai assistant method over gRPC. + + Runs Arc, the AI assistant, for the specified + assistant session. + + Returns: + Callable[[~.ChatAiAssistantRequest], + ~.ChatAiAssistantResponse]: + 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 "chat_ai_assistant" not in self._stubs: + self._stubs["chat_ai_assistant"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AssistantService/ChatAiAssistant", + request_serializer=assistant_service.ChatAiAssistantRequest.serialize, + response_deserializer=assistant_service.ChatAiAssistantResponse.deserialize, + ) + return self._stubs["chat_ai_assistant"] + + def close(self): + self._logged_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # 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 "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # 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 "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # 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_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # 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 "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # 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 "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # 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_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("AssistantServiceGrpcTransport",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/transports/grpc_asyncio.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..f86e0ba24988 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/transports/grpc_asyncio.py @@ -0,0 +1,711 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +import inspect +import json +import logging as std_logging +import pickle +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore + +from google.cloud.ces_v1beta.types import assistant_service + +from .base import DEFAULT_CLIENT_INFO, AssistantServiceTransport +from .grpc import AssistantServiceGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.ces.v1beta.AssistantService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.ces.v1beta.AssistantService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class AssistantServiceGrpcAsyncIOTransport(AssistantServiceTransport): + """gRPC AsyncIO backend transport for AssistantService. + + The service that manages assistant-related resources in + Customer Engagement Suite (CES). The assistant, Arc, is a + conversational agent embedded in CES applications to help users + with building their agents. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "ces.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "ces.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'ces.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_assistant_sessions( + self, + ) -> Callable[ + [assistant_service.ListAssistantSessionsRequest], + Awaitable[assistant_service.ListAssistantSessionsResponse], + ]: + r"""Return a callable for the list assistant sessions method over gRPC. + + Lists all assistant sessions in the given app. + + Returns: + Callable[[~.ListAssistantSessionsRequest], + Awaitable[~.ListAssistantSessionsResponse]]: + 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 "list_assistant_sessions" not in self._stubs: + self._stubs["list_assistant_sessions"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AssistantService/ListAssistantSessions", + request_serializer=assistant_service.ListAssistantSessionsRequest.serialize, + response_deserializer=assistant_service.ListAssistantSessionsResponse.deserialize, + ) + return self._stubs["list_assistant_sessions"] + + @property + def get_assistant_session( + self, + ) -> Callable[ + [assistant_service.GetAssistantSessionRequest], + Awaitable[assistant_service.AssistantSession], + ]: + r"""Return a callable for the get assistant session method over gRPC. + + Gets details of the specified assistant session. + + Returns: + Callable[[~.GetAssistantSessionRequest], + Awaitable[~.AssistantSession]]: + 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_assistant_session" not in self._stubs: + self._stubs["get_assistant_session"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AssistantService/GetAssistantSession", + request_serializer=assistant_service.GetAssistantSessionRequest.serialize, + response_deserializer=assistant_service.AssistantSession.deserialize, + ) + return self._stubs["get_assistant_session"] + + @property + def create_assistant_session( + self, + ) -> Callable[ + [assistant_service.CreateAssistantSessionRequest], + Awaitable[assistant_service.AssistantSession], + ]: + r"""Return a callable for the create assistant session method over gRPC. + + Creates a new assistant session in the given app. + + Returns: + Callable[[~.CreateAssistantSessionRequest], + Awaitable[~.AssistantSession]]: + 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 "create_assistant_session" not in self._stubs: + self._stubs["create_assistant_session"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AssistantService/CreateAssistantSession", + request_serializer=assistant_service.CreateAssistantSessionRequest.serialize, + response_deserializer=assistant_service.AssistantSession.deserialize, + ) + return self._stubs["create_assistant_session"] + + @property + def delete_assistant_session( + self, + ) -> Callable[ + [assistant_service.DeleteAssistantSessionRequest], Awaitable[empty_pb2.Empty] + ]: + r"""Return a callable for the delete assistant session method over gRPC. + + Deletes the specified assistant session. + + Returns: + Callable[[~.DeleteAssistantSessionRequest], + Awaitable[~.Empty]]: + 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 "delete_assistant_session" not in self._stubs: + self._stubs["delete_assistant_session"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AssistantService/DeleteAssistantSession", + request_serializer=assistant_service.DeleteAssistantSessionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_assistant_session"] + + @property + def run_assistant( + self, + ) -> Callable[ + [assistant_service.RunAssistantRequest], + Awaitable[assistant_service.RunAssistantResponse], + ]: + r"""Return a callable for the run assistant method over gRPC. + + Runs the assistant agent for the specified assistant + session. + + Returns: + Callable[[~.RunAssistantRequest], + Awaitable[~.RunAssistantResponse]]: + 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 "run_assistant" not in self._stubs: + self._stubs["run_assistant"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AssistantService/RunAssistant", + request_serializer=assistant_service.RunAssistantRequest.serialize, + response_deserializer=assistant_service.RunAssistantResponse.deserialize, + ) + return self._stubs["run_assistant"] + + @property + def chat_ai_assistant( + self, + ) -> Callable[ + [assistant_service.ChatAiAssistantRequest], + Awaitable[assistant_service.ChatAiAssistantResponse], + ]: + r"""Return a callable for the chat ai assistant method over gRPC. + + Runs Arc, the AI assistant, for the specified + assistant session. + + Returns: + Callable[[~.ChatAiAssistantRequest], + Awaitable[~.ChatAiAssistantResponse]]: + 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 "chat_ai_assistant" not in self._stubs: + self._stubs["chat_ai_assistant"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AssistantService/ChatAiAssistant", + request_serializer=assistant_service.ChatAiAssistantRequest.serialize, + response_deserializer=assistant_service.ChatAiAssistantResponse.deserialize, + ) + return self._stubs["chat_ai_assistant"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_assistant_sessions: self._wrap_method( + self.list_assistant_sessions, + default_timeout=None, + client_info=client_info, + ), + self.get_assistant_session: self._wrap_method( + self.get_assistant_session, + default_timeout=None, + client_info=client_info, + ), + self.create_assistant_session: self._wrap_method( + self.create_assistant_session, + default_timeout=None, + client_info=client_info, + ), + self.delete_assistant_session: self._wrap_method( + self.delete_assistant_session, + default_timeout=None, + client_info=client_info, + ), + self.run_assistant: self._wrap_method( + self.run_assistant, + default_timeout=None, + client_info=client_info, + ), + self.chat_ai_assistant: self._wrap_method( + self.chat_ai_assistant, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=300.0, + ), + default_timeout=300.0, + client_info=client_info, + ), + self.get_location: self._wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # 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 "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # 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 "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # 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_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # 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 "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # 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 "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # 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_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + +__all__ = ("AssistantServiceGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/transports/rest.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/transports/rest.py new file mode 100644 index 000000000000..1e7714d6ee2d --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/transports/rest.py @@ -0,0 +1,2385 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +import dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.ces_v1beta._compat import transcode_request +from google.cloud.ces_v1beta.types import assistant_service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseAssistantServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class AssistantServiceRestInterceptor: + """Interceptor for AssistantService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the AssistantServiceRestTransport. + + .. code-block:: python + class MyCustomAssistantServiceInterceptor(AssistantServiceRestInterceptor): + def pre_chat_ai_assistant(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_chat_ai_assistant(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_assistant_session(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_assistant_session(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_assistant_session(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_assistant_session(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_assistant_session(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_assistant_sessions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_assistant_sessions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_run_assistant(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_run_assistant(self, response): + logging.log(f"Received response: {response}") + return response + + transport = AssistantServiceRestTransport(interceptor=MyCustomAssistantServiceInterceptor()) + client = AssistantServiceClient(transport=transport) + + + """ + + def pre_chat_ai_assistant( + self, + request: assistant_service.ChatAiAssistantRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + assistant_service.ChatAiAssistantRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for chat_ai_assistant + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssistantService server. + """ + return request, metadata + + def post_chat_ai_assistant( + self, response: assistant_service.ChatAiAssistantResponse + ) -> assistant_service.ChatAiAssistantResponse: + """Post-rpc interceptor for chat_ai_assistant + + DEPRECATED. Please use the `post_chat_ai_assistant_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AssistantService server but before + it is returned to user code. This `post_chat_ai_assistant` interceptor runs + before the `post_chat_ai_assistant_with_metadata` interceptor. + """ + return response + + def post_chat_ai_assistant_with_metadata( + self, + response: assistant_service.ChatAiAssistantResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + assistant_service.ChatAiAssistantResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for chat_ai_assistant + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AssistantService server but before it is returned to user code. + + We recommend only using this `post_chat_ai_assistant_with_metadata` + interceptor in new development instead of the `post_chat_ai_assistant` interceptor. + When both interceptors are used, this `post_chat_ai_assistant_with_metadata` interceptor runs after the + `post_chat_ai_assistant` interceptor. The (possibly modified) response returned by + `post_chat_ai_assistant` will be passed to + `post_chat_ai_assistant_with_metadata`. + """ + return response, metadata + + def pre_create_assistant_session( + self, + request: assistant_service.CreateAssistantSessionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + assistant_service.CreateAssistantSessionRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_assistant_session + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssistantService server. + """ + return request, metadata + + def post_create_assistant_session( + self, response: assistant_service.AssistantSession + ) -> assistant_service.AssistantSession: + """Post-rpc interceptor for create_assistant_session + + DEPRECATED. Please use the `post_create_assistant_session_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AssistantService server but before + it is returned to user code. This `post_create_assistant_session` interceptor runs + before the `post_create_assistant_session_with_metadata` interceptor. + """ + return response + + def post_create_assistant_session_with_metadata( + self, + response: assistant_service.AssistantSession, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + assistant_service.AssistantSession, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for create_assistant_session + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AssistantService server but before it is returned to user code. + + We recommend only using this `post_create_assistant_session_with_metadata` + interceptor in new development instead of the `post_create_assistant_session` interceptor. + When both interceptors are used, this `post_create_assistant_session_with_metadata` interceptor runs after the + `post_create_assistant_session` interceptor. The (possibly modified) response returned by + `post_create_assistant_session` will be passed to + `post_create_assistant_session_with_metadata`. + """ + return response, metadata + + def pre_delete_assistant_session( + self, + request: assistant_service.DeleteAssistantSessionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + assistant_service.DeleteAssistantSessionRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_assistant_session + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssistantService server. + """ + return request, metadata + + def pre_get_assistant_session( + self, + request: assistant_service.GetAssistantSessionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + assistant_service.GetAssistantSessionRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_assistant_session + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssistantService server. + """ + return request, metadata + + def post_get_assistant_session( + self, response: assistant_service.AssistantSession + ) -> assistant_service.AssistantSession: + """Post-rpc interceptor for get_assistant_session + + DEPRECATED. Please use the `post_get_assistant_session_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AssistantService server but before + it is returned to user code. This `post_get_assistant_session` interceptor runs + before the `post_get_assistant_session_with_metadata` interceptor. + """ + return response + + def post_get_assistant_session_with_metadata( + self, + response: assistant_service.AssistantSession, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + assistant_service.AssistantSession, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for get_assistant_session + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AssistantService server but before it is returned to user code. + + We recommend only using this `post_get_assistant_session_with_metadata` + interceptor in new development instead of the `post_get_assistant_session` interceptor. + When both interceptors are used, this `post_get_assistant_session_with_metadata` interceptor runs after the + `post_get_assistant_session` interceptor. The (possibly modified) response returned by + `post_get_assistant_session` will be passed to + `post_get_assistant_session_with_metadata`. + """ + return response, metadata + + def pre_list_assistant_sessions( + self, + request: assistant_service.ListAssistantSessionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + assistant_service.ListAssistantSessionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_assistant_sessions + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssistantService server. + """ + return request, metadata + + def post_list_assistant_sessions( + self, response: assistant_service.ListAssistantSessionsResponse + ) -> assistant_service.ListAssistantSessionsResponse: + """Post-rpc interceptor for list_assistant_sessions + + DEPRECATED. Please use the `post_list_assistant_sessions_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AssistantService server but before + it is returned to user code. This `post_list_assistant_sessions` interceptor runs + before the `post_list_assistant_sessions_with_metadata` interceptor. + """ + return response + + def post_list_assistant_sessions_with_metadata( + self, + response: assistant_service.ListAssistantSessionsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + assistant_service.ListAssistantSessionsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_assistant_sessions + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AssistantService server but before it is returned to user code. + + We recommend only using this `post_list_assistant_sessions_with_metadata` + interceptor in new development instead of the `post_list_assistant_sessions` interceptor. + When both interceptors are used, this `post_list_assistant_sessions_with_metadata` interceptor runs after the + `post_list_assistant_sessions` interceptor. The (possibly modified) response returned by + `post_list_assistant_sessions` will be passed to + `post_list_assistant_sessions_with_metadata`. + """ + return response, metadata + + def pre_run_assistant( + self, + request: assistant_service.RunAssistantRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + assistant_service.RunAssistantRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for run_assistant + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssistantService server. + """ + return request, metadata + + def post_run_assistant( + self, response: assistant_service.RunAssistantResponse + ) -> assistant_service.RunAssistantResponse: + """Post-rpc interceptor for run_assistant + + DEPRECATED. Please use the `post_run_assistant_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AssistantService server but before + it is returned to user code. This `post_run_assistant` interceptor runs + before the `post_run_assistant_with_metadata` interceptor. + """ + return response + + def post_run_assistant_with_metadata( + self, + response: assistant_service.RunAssistantResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + assistant_service.RunAssistantResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for run_assistant + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AssistantService server but before it is returned to user code. + + We recommend only using this `post_run_assistant_with_metadata` + interceptor in new development instead of the `post_run_assistant` interceptor. + When both interceptors are used, this `post_run_assistant_with_metadata` interceptor runs after the + `post_run_assistant` interceptor. The (possibly modified) response returned by + `post_run_assistant` will be passed to + `post_run_assistant_with_metadata`. + """ + return response, metadata + + def pre_get_location( + self, + request: locations_pb2.GetLocationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssistantService server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.Location + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the AssistantService server but before + it is returned to user code. + """ + return response + + def pre_list_locations( + self, + request: locations_pb2.ListLocationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssistantService server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsResponse + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the AssistantService server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssistantService server. + """ + return request, metadata + + def post_cancel_operation(self, response: None) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the AssistantService server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, + request: operations_pb2.DeleteOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssistantService server. + """ + return request, metadata + + def post_delete_operation(self, response: None) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the AssistantService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssistantService server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the AssistantService server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssistantService server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the AssistantService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class AssistantServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AssistantServiceRestInterceptor + + +class AssistantServiceRestTransport(_BaseAssistantServiceRestTransport): + """REST backend synchronous transport for AssistantService. + + The service that manages assistant-related resources in + Customer Engagement Suite (CES). The assistant, Arc, is a + conversational agent embedded in CES applications to help users + with building their agents. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "ces.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[AssistantServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'ces.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[AssistantServiceRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or AssistantServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _ChatAiAssistant( + _BaseAssistantServiceRestTransport._BaseChatAiAssistant, + AssistantServiceRestStub, + ): + def __hash__(self): + return hash("AssistantServiceRestTransport.ChatAiAssistant") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: assistant_service.ChatAiAssistantRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> assistant_service.ChatAiAssistantResponse: + r"""Call the chat ai assistant method over HTTP. + + Args: + request (~.assistant_service.ChatAiAssistantRequest): + The request object. Request message for + [AssistantService.ChatAiAssistant][google.cloud.ces.v1beta.AssistantService.ChatAiAssistant]. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.assistant_service.ChatAiAssistantResponse: + Response message for + [AssistantService.ChatAiAssistant][google.cloud.ces.v1beta.AssistantService.ChatAiAssistant]. + + """ + + http_options = _BaseAssistantServiceRestTransport._BaseChatAiAssistant._get_http_options() + request, metadata = self._interceptor.pre_chat_ai_assistant( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseAssistantServiceRestTransport._BaseChatAiAssistant, + "_BaseChatAiAssistant__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AssistantServiceClient.ChatAiAssistant", + extra={ + "serviceName": "google.cloud.ces.v1beta.AssistantService", + "rpcName": "ChatAiAssistant", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AssistantServiceRestTransport._ChatAiAssistant._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + 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 = assistant_service.ChatAiAssistantResponse() + pb_resp = assistant_service.ChatAiAssistantResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_chat_ai_assistant(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_chat_ai_assistant_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + assistant_service.ChatAiAssistantResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AssistantServiceClient.chat_ai_assistant", + extra={ + "serviceName": "google.cloud.ces.v1beta.AssistantService", + "rpcName": "ChatAiAssistant", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateAssistantSession( + _BaseAssistantServiceRestTransport._BaseCreateAssistantSession, + AssistantServiceRestStub, + ): + def __hash__(self): + return hash("AssistantServiceRestTransport.CreateAssistantSession") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: assistant_service.CreateAssistantSessionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> assistant_service.AssistantSession: + r"""Call the create assistant session method over HTTP. + + Args: + request (~.assistant_service.CreateAssistantSessionRequest): + The request object. Request message for + [AssistantService.CreateAssistantSession][google.cloud.ces.v1beta.AssistantService.CreateAssistantSession]. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.assistant_service.AssistantSession: + An assistant session represents a + conversation between a user and the + assistant agent. + + """ + + http_options = _BaseAssistantServiceRestTransport._BaseCreateAssistantSession._get_http_options() + request, metadata = self._interceptor.pre_create_assistant_session( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseAssistantServiceRestTransport._BaseCreateAssistantSession, + "_BaseCreateAssistantSession__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AssistantServiceClient.CreateAssistantSession", + extra={ + "serviceName": "google.cloud.ces.v1beta.AssistantService", + "rpcName": "CreateAssistantSession", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + AssistantServiceRestTransport._CreateAssistantSession._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + 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 = assistant_service.AssistantSession() + pb_resp = assistant_service.AssistantSession.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_assistant_session(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_assistant_session_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = assistant_service.AssistantSession.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AssistantServiceClient.create_assistant_session", + extra={ + "serviceName": "google.cloud.ces.v1beta.AssistantService", + "rpcName": "CreateAssistantSession", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteAssistantSession( + _BaseAssistantServiceRestTransport._BaseDeleteAssistantSession, + AssistantServiceRestStub, + ): + def __hash__(self): + return hash("AssistantServiceRestTransport.DeleteAssistantSession") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: assistant_service.DeleteAssistantSessionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete assistant session method over HTTP. + + Args: + request (~.assistant_service.DeleteAssistantSessionRequest): + The request object. Request message for + [AssistantService.DeleteAssistantSession][google.cloud.ces.v1beta.AssistantService.DeleteAssistantSession]. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseAssistantServiceRestTransport._BaseDeleteAssistantSession._get_http_options() + request, metadata = self._interceptor.pre_delete_assistant_session( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseAssistantServiceRestTransport._BaseDeleteAssistantSession, + "_BaseDeleteAssistantSession__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AssistantServiceClient.DeleteAssistantSession", + extra={ + "serviceName": "google.cloud.ces.v1beta.AssistantService", + "rpcName": "DeleteAssistantSession", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + AssistantServiceRestTransport._DeleteAssistantSession._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _GetAssistantSession( + _BaseAssistantServiceRestTransport._BaseGetAssistantSession, + AssistantServiceRestStub, + ): + def __hash__(self): + return hash("AssistantServiceRestTransport.GetAssistantSession") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: assistant_service.GetAssistantSessionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> assistant_service.AssistantSession: + r"""Call the get assistant session method over HTTP. + + Args: + request (~.assistant_service.GetAssistantSessionRequest): + The request object. Request message for + [AssistantService.GetAssistantSession][google.cloud.ces.v1beta.AssistantService.GetAssistantSession]. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.assistant_service.AssistantSession: + An assistant session represents a + conversation between a user and the + assistant agent. + + """ + + http_options = _BaseAssistantServiceRestTransport._BaseGetAssistantSession._get_http_options() + request, metadata = self._interceptor.pre_get_assistant_session( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseAssistantServiceRestTransport._BaseGetAssistantSession, + "_BaseGetAssistantSession__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AssistantServiceClient.GetAssistantSession", + extra={ + "serviceName": "google.cloud.ces.v1beta.AssistantService", + "rpcName": "GetAssistantSession", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AssistantServiceRestTransport._GetAssistantSession._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # 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 = assistant_service.AssistantSession() + pb_resp = assistant_service.AssistantSession.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_assistant_session(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_assistant_session_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = assistant_service.AssistantSession.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AssistantServiceClient.get_assistant_session", + extra={ + "serviceName": "google.cloud.ces.v1beta.AssistantService", + "rpcName": "GetAssistantSession", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListAssistantSessions( + _BaseAssistantServiceRestTransport._BaseListAssistantSessions, + AssistantServiceRestStub, + ): + def __hash__(self): + return hash("AssistantServiceRestTransport.ListAssistantSessions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: assistant_service.ListAssistantSessionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> assistant_service.ListAssistantSessionsResponse: + r"""Call the list assistant sessions method over HTTP. + + Args: + request (~.assistant_service.ListAssistantSessionsRequest): + The request object. Request message for + [AssistantService.ListAssistantSessions][google.cloud.ces.v1beta.AssistantService.ListAssistantSessions]. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.assistant_service.ListAssistantSessionsResponse: + Response message for + [AssistantService.ListAssistantSessions][google.cloud.ces.v1beta.AssistantService.ListAssistantSessions]. + + """ + + http_options = _BaseAssistantServiceRestTransport._BaseListAssistantSessions._get_http_options() + request, metadata = self._interceptor.pre_list_assistant_sessions( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseAssistantServiceRestTransport._BaseListAssistantSessions, + "_BaseListAssistantSessions__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AssistantServiceClient.ListAssistantSessions", + extra={ + "serviceName": "google.cloud.ces.v1beta.AssistantService", + "rpcName": "ListAssistantSessions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + AssistantServiceRestTransport._ListAssistantSessions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # 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 = assistant_service.ListAssistantSessionsResponse() + pb_resp = assistant_service.ListAssistantSessionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_assistant_sessions(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_assistant_sessions_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + assistant_service.ListAssistantSessionsResponse.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AssistantServiceClient.list_assistant_sessions", + extra={ + "serviceName": "google.cloud.ces.v1beta.AssistantService", + "rpcName": "ListAssistantSessions", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _RunAssistant( + _BaseAssistantServiceRestTransport._BaseRunAssistant, AssistantServiceRestStub + ): + def __hash__(self): + return hash("AssistantServiceRestTransport.RunAssistant") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: assistant_service.RunAssistantRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> assistant_service.RunAssistantResponse: + r"""Call the run assistant method over HTTP. + + Args: + request (~.assistant_service.RunAssistantRequest): + The request object. Request message for + [AssistantService.RunAssistant][google.cloud.ces.v1beta.AssistantService.RunAssistant]. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.assistant_service.RunAssistantResponse: + Response message for + [AssistantService.RunAssistant][google.cloud.ces.v1beta.AssistantService.RunAssistant]. + + """ + + http_options = ( + _BaseAssistantServiceRestTransport._BaseRunAssistant._get_http_options() + ) + request, metadata = self._interceptor.pre_run_assistant(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseAssistantServiceRestTransport._BaseRunAssistant, + "_BaseRunAssistant__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AssistantServiceClient.RunAssistant", + extra={ + "serviceName": "google.cloud.ces.v1beta.AssistantService", + "rpcName": "RunAssistant", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AssistantServiceRestTransport._RunAssistant._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + 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 = assistant_service.RunAssistantResponse() + pb_resp = assistant_service.RunAssistantResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_run_assistant(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_run_assistant_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = assistant_service.RunAssistantResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AssistantServiceClient.run_assistant", + extra={ + "serviceName": "google.cloud.ces.v1beta.AssistantService", + "rpcName": "RunAssistant", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def chat_ai_assistant( + self, + ) -> Callable[ + [assistant_service.ChatAiAssistantRequest], + assistant_service.ChatAiAssistantResponse, + ]: + # 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._ChatAiAssistant(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_assistant_session( + self, + ) -> Callable[ + [assistant_service.CreateAssistantSessionRequest], + assistant_service.AssistantSession, + ]: + # 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._CreateAssistantSession( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def delete_assistant_session( + self, + ) -> Callable[[assistant_service.DeleteAssistantSessionRequest], empty_pb2.Empty]: + # 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._DeleteAssistantSession( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def get_assistant_session( + self, + ) -> Callable[ + [assistant_service.GetAssistantSessionRequest], + assistant_service.AssistantSession, + ]: + # 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._GetAssistantSession(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_assistant_sessions( + self, + ) -> Callable[ + [assistant_service.ListAssistantSessionsRequest], + assistant_service.ListAssistantSessionsResponse, + ]: + # 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._ListAssistantSessions(self._session, self._host, self._interceptor) # type: ignore + + @property + def run_assistant( + self, + ) -> Callable[ + [assistant_service.RunAssistantRequest], assistant_service.RunAssistantResponse + ]: + # 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._RunAssistant(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation( + _BaseAssistantServiceRestTransport._BaseGetLocation, AssistantServiceRestStub + ): + def __hash__(self): + return hash("AssistantServiceRestTransport.GetLocation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: locations_pb2.GetLocationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options = ( + _BaseAssistantServiceRestTransport._BaseGetLocation._get_http_options() + ) + request, metadata = self._interceptor.pre_get_location(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseAssistantServiceRestTransport._BaseGetLocation, + "_BaseGetLocation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AssistantServiceClient.GetLocation", + extra={ + "serviceName": "google.cloud.ces.v1beta.AssistantService", + "rpcName": "GetLocation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AssistantServiceRestTransport._GetLocation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.Location() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_location(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AssistantServiceAsyncClient.GetLocation", + extra={ + "serviceName": "google.cloud.ces.v1beta.AssistantService", + "rpcName": "GetLocation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations( + _BaseAssistantServiceRestTransport._BaseListLocations, AssistantServiceRestStub + ): + def __hash__(self): + return hash("AssistantServiceRestTransport.ListLocations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: locations_pb2.ListLocationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options = _BaseAssistantServiceRestTransport._BaseListLocations._get_http_options() + request, metadata = self._interceptor.pre_list_locations(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseAssistantServiceRestTransport._BaseListLocations, + "_BaseListLocations__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AssistantServiceClient.ListLocations", + extra={ + "serviceName": "google.cloud.ces.v1beta.AssistantService", + "rpcName": "ListLocations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AssistantServiceRestTransport._ListLocations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_locations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AssistantServiceAsyncClient.ListLocations", + extra={ + "serviceName": "google.cloud.ces.v1beta.AssistantService", + "rpcName": "ListLocations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation( + _BaseAssistantServiceRestTransport._BaseCancelOperation, + AssistantServiceRestStub, + ): + def __hash__(self): + return hash("AssistantServiceRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseAssistantServiceRestTransport._BaseCancelOperation._get_http_options() + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseAssistantServiceRestTransport._BaseCancelOperation, + "_BaseCancelOperation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AssistantServiceClient.CancelOperation", + extra={ + "serviceName": "google.cloud.ces.v1beta.AssistantService", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AssistantServiceRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + 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 self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation( + _BaseAssistantServiceRestTransport._BaseDeleteOperation, + AssistantServiceRestStub, + ): + def __hash__(self): + return hash("AssistantServiceRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.DeleteOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseAssistantServiceRestTransport._BaseDeleteOperation._get_http_options() + request, metadata = self._interceptor.pre_delete_operation( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseAssistantServiceRestTransport._BaseDeleteOperation, + "_BaseDeleteOperation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AssistantServiceClient.DeleteOperation", + extra={ + "serviceName": "google.cloud.ces.v1beta.AssistantService", + "rpcName": "DeleteOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AssistantServiceRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # 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 self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BaseAssistantServiceRestTransport._BaseGetOperation, AssistantServiceRestStub + ): + def __hash__(self): + return hash("AssistantServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = ( + _BaseAssistantServiceRestTransport._BaseGetOperation._get_http_options() + ) + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseAssistantServiceRestTransport._BaseGetOperation, + "_BaseGetOperation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AssistantServiceClient.GetOperation", + extra={ + "serviceName": "google.cloud.ces.v1beta.AssistantService", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AssistantServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AssistantServiceAsyncClient.GetOperation", + extra={ + "serviceName": "google.cloud.ces.v1beta.AssistantService", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations( + _BaseAssistantServiceRestTransport._BaseListOperations, AssistantServiceRestStub + ): + def __hash__(self): + return hash("AssistantServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = _BaseAssistantServiceRestTransport._BaseListOperations._get_http_options() + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseAssistantServiceRestTransport._BaseListOperations, + "_BaseListOperations__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AssistantServiceClient.ListOperations", + extra={ + "serviceName": "google.cloud.ces.v1beta.AssistantService", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AssistantServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AssistantServiceAsyncClient.ListOperations", + extra={ + "serviceName": "google.cloud.ces.v1beta.AssistantService", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("AssistantServiceRestTransport",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/transports/rest_base.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/transports/rest_base.py new file mode 100644 index 000000000000..990fa546afc4 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/assistant_service/transports/rest_base.py @@ -0,0 +1,278 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.ces_v1beta.types import assistant_service + +from .base import DEFAULT_CLIENT_INFO, AssistantServiceTransport + + +class _BaseAssistantServiceRestTransport(AssistantServiceTransport): + """Base REST backend transport for AssistantService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "ces.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'ces.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseChatAiAssistant: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{app=projects/*/locations/*/apps/*}:chatAiAssistant", + "body": "*", + }, + ] + return http_options + + class _BaseCreateAssistantSession: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*/apps/*}/assistantSessions", + "body": "*", + }, + ] + return http_options + + class _BaseDeleteAssistantSession: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*/assistantSessions/*}", + }, + ] + return http_options + + class _BaseGetAssistantSession: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*/assistantSessions/*}", + }, + ] + return http_options + + class _BaseListAssistantSessions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*/apps/*}/assistantSessions", + }, + ] + return http_options + + class _BaseRunAssistant: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{app=projects/*/locations/*/apps/*}:runAssistant", + "body": "*", + }, + ] + return http_options + + class _BaseGetLocation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*}", + }, + ] + return http_options + + class _BaseListLocations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*}/locations", + }, + ] + return http_options + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ] + return http_options + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*}/operations", + }, + ] + return http_options + + +__all__ = ("_BaseAssistantServiceRestTransport",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/async_client.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/async_client.py index 0d7a6e4a4be0..37cb412c8ff6 100644 --- a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/async_client.py +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/async_client.py @@ -58,6 +58,7 @@ from google.cloud.ces_v1beta.types import ( agent_service, app, + common, evaluation, evaluation_metrics_config, evaluation_service, diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/client.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/client.py index da426e1fb650..c65405d72d64 100644 --- a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/client.py +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/client.py @@ -82,6 +82,7 @@ from google.cloud.ces_v1beta.types import ( agent_service, app, + common, evaluation, evaluation_metrics_config, evaluation_service, diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/async_client.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/async_client.py index 35a56a9e8b45..c79091c2bce4 100644 --- a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/async_client.py +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/async_client.py @@ -47,10 +47,12 @@ except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from google.cloud.location import locations_pb2 # type: ignore from google.longrunning import operations_pb2 # type: ignore -from google.cloud.ces_v1beta.types import session_service +from google.cloud.ces_v1beta.types import common, example, session_service from .client import SessionServiceClient from .transports.base import DEFAULT_CLIENT_INFO, SessionServiceTransport @@ -82,6 +84,12 @@ class SessionServiceAsyncClient: agent_path = staticmethod(SessionServiceClient.agent_path) parse_agent_path = staticmethod(SessionServiceClient.parse_agent_path) + app_path = staticmethod(SessionServiceClient.app_path) + parse_app_path = staticmethod(SessionServiceClient.parse_app_path) + assistant_session_path = staticmethod(SessionServiceClient.assistant_session_path) + parse_assistant_session_path = staticmethod( + SessionServiceClient.parse_assistant_session_path + ) session_path = staticmethod(SessionServiceClient.session_path) parse_session_path = staticmethod(SessionServiceClient.parse_session_path) tool_path = staticmethod(SessionServiceClient.tool_path) @@ -667,6 +675,281 @@ def request_generator(): # Done; return the response. return response + def stream_chat_ai_assistant( + self, + request: Optional[ + Union[session_service.StreamChatAiAssistantRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> Awaitable[AsyncIterable[session_service.StreamChatAiAssistantResponse]]: + r"""Runs Arc, the AI assistant, for the specified + assistant session in a streaming fashion. + + .. 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 ces_v1beta + + async def sample_stream_chat_ai_assistant(): + # Create a client + client = ces_v1beta.SessionServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.StreamChatAiAssistantRequest( + name="name_value", + ) + + # Make the request + stream = await client.stream_chat_ai_assistant(request=request) + + # Handle the response + async for response in stream: + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.StreamChatAiAssistantRequest, dict]]): + The request object. Request message for + [SessionService.StreamChatAiAssistant][google.cloud.ces.v1beta.SessionService.StreamChatAiAssistant]. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + AsyncIterable[google.cloud.ces_v1beta.types.StreamChatAiAssistantResponse]: + Response message for + [SessionService.StreamChatAiAssistant][google.cloud.ces.v1beta.SessionService.StreamChatAiAssistant]. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, session_service.StreamChatAiAssistantRequest): + request = session_service.StreamChatAiAssistantRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.stream_chat_ai_assistant + ] + + # 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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def cancel_assistant_turn( + self, + request: Optional[ + Union[session_service.CancelAssistantTurnRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> session_service.CancelAssistantTurnResponse: + r"""Cancels the assistant session's in-flight turn, if + any: the explicit user stop for a turn running detached + from any stream. A cancel landing on a task that does + not host the turn preempts it through the session turn + epoch instead, ending it within one lease renewal. + + .. 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 ces_v1beta + + async def sample_cancel_assistant_turn(): + # Create a client + client = ces_v1beta.SessionServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.CancelAssistantTurnRequest( + name="name_value", + ) + + # Make the request + response = await client.cancel_assistant_turn(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.CancelAssistantTurnRequest, dict]]): + The request object. Request to cancel an assistant + session's in-flight turn. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.CancelAssistantTurnResponse: + Response for CancelAssistantTurn. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, session_service.CancelAssistantTurnRequest): + request = session_service.CancelAssistantTurnRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.cancel_assistant_turn + ] + + # 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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def generate_onboarding_suggestions( + self, + request: Optional[ + Union[session_service.GenerateOnboardingSuggestionsRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> session_service.GenerateOnboardingSuggestionsResponse: + r"""Generates personalized onboarding suggestions for the + Arc zero state: classifies the requesting user (new / + exploring / returning) from their assistant-session + history in the app and returns suggestion chips (resume + a session, continue work, or start something new) to + render before any message is sent. + + .. 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 ces_v1beta + + async def sample_generate_onboarding_suggestions(): + # Create a client + client = ces_v1beta.SessionServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GenerateOnboardingSuggestionsRequest( + name="name_value", + ) + + # Make the request + response = await client.generate_onboarding_suggestions(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.GenerateOnboardingSuggestionsRequest, dict]]): + The request object. Request message for + [SessionService.GenerateOnboardingSuggestions][google.cloud.ces.v1beta.SessionService.GenerateOnboardingSuggestions]. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.GenerateOnboardingSuggestionsResponse: + Response message for + [SessionService.GenerateOnboardingSuggestions][google.cloud.ces.v1beta.SessionService.GenerateOnboardingSuggestions]. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, session_service.GenerateOnboardingSuggestionsRequest + ): + request = session_service.GenerateOnboardingSuggestionsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.generate_onboarding_suggestions + ] + + # 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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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[Union[operations_pb2.ListOperationsRequest, dict]] = None, diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/client.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/client.py index b93530f09b3a..5fe2a0d0c0b2 100644 --- a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/client.py +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/client.py @@ -70,10 +70,12 @@ _LOGGER = std_logging.getLogger(__name__) +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from google.cloud.location import locations_pb2 # type: ignore from google.longrunning import operations_pb2 # type: ignore -from google.cloud.ces_v1beta.types import session_service +from google.cloud.ces_v1beta.types import common, example, session_service from .transports.base import DEFAULT_CLIENT_INFO, SessionServiceTransport from .transports.grpc import SessionServiceGrpcTransport @@ -201,6 +203,52 @@ def parse_agent_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def app_path( + project: str, + location: str, + app: str, + ) -> str: + """Returns a fully-qualified app string.""" + return "projects/{project}/locations/{location}/apps/{app}".format( + project=project, + location=location, + app=app, + ) + + @staticmethod + def parse_app_path(path: str) -> Dict[str, str]: + """Parses a app path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/apps/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def assistant_session_path( + project: str, + location: str, + app: str, + assistant_session: str, + ) -> str: + """Returns a fully-qualified assistant_session string.""" + return "projects/{project}/locations/{location}/apps/{app}/assistantSessions/{assistant_session}".format( + project=project, + location=location, + app=app, + assistant_session=assistant_session, + ) + + @staticmethod + def parse_assistant_session_path(path: str) -> Dict[str, str]: + """Parses a assistant_session path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/apps/(?P.+?)/assistantSessions/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def session_path( project: str, @@ -1025,6 +1073,277 @@ def request_generator(): # Done; return the response. return response + def stream_chat_ai_assistant( + self, + request: Optional[ + Union[session_service.StreamChatAiAssistantRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> Iterable[session_service.StreamChatAiAssistantResponse]: + r"""Runs Arc, the AI assistant, for the specified + assistant session in a streaming fashion. + + .. 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 ces_v1beta + + def sample_stream_chat_ai_assistant(): + # Create a client + client = ces_v1beta.SessionServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.StreamChatAiAssistantRequest( + name="name_value", + ) + + # Make the request + stream = client.stream_chat_ai_assistant(request=request) + + # Handle the response + for response in stream: + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.StreamChatAiAssistantRequest, dict]): + The request object. Request message for + [SessionService.StreamChatAiAssistant][google.cloud.ces.v1beta.SessionService.StreamChatAiAssistant]. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + Iterable[google.cloud.ces_v1beta.types.StreamChatAiAssistantResponse]: + Response message for + [SessionService.StreamChatAiAssistant][google.cloud.ces.v1beta.SessionService.StreamChatAiAssistant]. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, session_service.StreamChatAiAssistantRequest): + request = session_service.StreamChatAiAssistantRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.stream_chat_ai_assistant] + + # 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def cancel_assistant_turn( + self, + request: Optional[ + Union[session_service.CancelAssistantTurnRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> session_service.CancelAssistantTurnResponse: + r"""Cancels the assistant session's in-flight turn, if + any: the explicit user stop for a turn running detached + from any stream. A cancel landing on a task that does + not host the turn preempts it through the session turn + epoch instead, ending it within one lease renewal. + + .. 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 ces_v1beta + + def sample_cancel_assistant_turn(): + # Create a client + client = ces_v1beta.SessionServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.CancelAssistantTurnRequest( + name="name_value", + ) + + # Make the request + response = client.cancel_assistant_turn(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.CancelAssistantTurnRequest, dict]): + The request object. Request to cancel an assistant + session's in-flight turn. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.CancelAssistantTurnResponse: + Response for CancelAssistantTurn. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, session_service.CancelAssistantTurnRequest): + request = session_service.CancelAssistantTurnRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_assistant_turn] + + # 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def generate_onboarding_suggestions( + self, + request: Optional[ + Union[session_service.GenerateOnboardingSuggestionsRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> session_service.GenerateOnboardingSuggestionsResponse: + r"""Generates personalized onboarding suggestions for the + Arc zero state: classifies the requesting user (new / + exploring / returning) from their assistant-session + history in the app and returns suggestion chips (resume + a session, continue work, or start something new) to + render before any message is sent. + + .. 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 ces_v1beta + + def sample_generate_onboarding_suggestions(): + # Create a client + client = ces_v1beta.SessionServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GenerateOnboardingSuggestionsRequest( + name="name_value", + ) + + # Make the request + response = client.generate_onboarding_suggestions(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.GenerateOnboardingSuggestionsRequest, dict]): + The request object. Request message for + [SessionService.GenerateOnboardingSuggestions][google.cloud.ces.v1beta.SessionService.GenerateOnboardingSuggestions]. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.GenerateOnboardingSuggestionsResponse: + Response message for + [SessionService.GenerateOnboardingSuggestions][google.cloud.ces.v1beta.SessionService.GenerateOnboardingSuggestions]. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, session_service.GenerateOnboardingSuggestionsRequest + ): + request = session_service.GenerateOnboardingSuggestionsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.generate_onboarding_suggestions + ] + + # 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "SessionServiceClient": return self diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/base.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/base.py index f8b593ce678e..539d7e3e3074 100644 --- a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/base.py +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/base.py @@ -174,6 +174,28 @@ def _prep_wrapped_messages(self, client_info): default_timeout=3600.0, client_info=client_info, ), + self.stream_chat_ai_assistant: gapic_v1.method.wrap_method( + self.stream_chat_ai_assistant, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + deadline=3600.0, + ), + default_timeout=3600.0, + client_info=client_info, + ), + self.cancel_assistant_turn: gapic_v1.method.wrap_method( + self.cancel_assistant_turn, + default_timeout=None, + client_info=client_info, + ), + self.generate_onboarding_suggestions: gapic_v1.method.wrap_method( + self.generate_onboarding_suggestions, + default_timeout=None, + client_info=client_info, + ), self.get_location: gapic_v1.method.wrap_method( self.get_location, default_timeout=None, @@ -251,6 +273,42 @@ def bidi_run_session( ]: raise NotImplementedError() + @property + def stream_chat_ai_assistant( + self, + ) -> Callable[ + [session_service.StreamChatAiAssistantRequest], + Union[ + session_service.StreamChatAiAssistantResponse, + Awaitable[session_service.StreamChatAiAssistantResponse], + ], + ]: + raise NotImplementedError() + + @property + def cancel_assistant_turn( + self, + ) -> Callable[ + [session_service.CancelAssistantTurnRequest], + Union[ + session_service.CancelAssistantTurnResponse, + Awaitable[session_service.CancelAssistantTurnResponse], + ], + ]: + raise NotImplementedError() + + @property + def generate_onboarding_suggestions( + self, + ) -> Callable[ + [session_service.GenerateOnboardingSuggestionsRequest], + Union[ + session_service.GenerateOnboardingSuggestionsResponse, + Awaitable[session_service.GenerateOnboardingSuggestionsResponse], + ], + ]: + raise NotImplementedError() + @property def list_operations( self, diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/grpc.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/grpc.py index 455a557d82fd..4089398cb363 100644 --- a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/grpc.py +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/grpc.py @@ -483,6 +483,106 @@ def bidi_run_session( ) return self._stubs["bidi_run_session"] + @property + def stream_chat_ai_assistant( + self, + ) -> Callable[ + [session_service.StreamChatAiAssistantRequest], + session_service.StreamChatAiAssistantResponse, + ]: + r"""Return a callable for the stream chat ai assistant method over gRPC. + + Runs Arc, the AI assistant, for the specified + assistant session in a streaming fashion. + + Returns: + Callable[[~.StreamChatAiAssistantRequest], + ~.StreamChatAiAssistantResponse]: + 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 "stream_chat_ai_assistant" not in self._stubs: + self._stubs["stream_chat_ai_assistant"] = self._logged_channel.unary_stream( + "/google.cloud.ces.v1beta.SessionService/StreamChatAiAssistant", + request_serializer=session_service.StreamChatAiAssistantRequest.serialize, + response_deserializer=session_service.StreamChatAiAssistantResponse.deserialize, + ) + return self._stubs["stream_chat_ai_assistant"] + + @property + def cancel_assistant_turn( + self, + ) -> Callable[ + [session_service.CancelAssistantTurnRequest], + session_service.CancelAssistantTurnResponse, + ]: + r"""Return a callable for the cancel assistant turn method over gRPC. + + Cancels the assistant session's in-flight turn, if + any: the explicit user stop for a turn running detached + from any stream. A cancel landing on a task that does + not host the turn preempts it through the session turn + epoch instead, ending it within one lease renewal. + + Returns: + Callable[[~.CancelAssistantTurnRequest], + ~.CancelAssistantTurnResponse]: + 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 "cancel_assistant_turn" not in self._stubs: + self._stubs["cancel_assistant_turn"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.SessionService/CancelAssistantTurn", + request_serializer=session_service.CancelAssistantTurnRequest.serialize, + response_deserializer=session_service.CancelAssistantTurnResponse.deserialize, + ) + return self._stubs["cancel_assistant_turn"] + + @property + def generate_onboarding_suggestions( + self, + ) -> Callable[ + [session_service.GenerateOnboardingSuggestionsRequest], + session_service.GenerateOnboardingSuggestionsResponse, + ]: + r"""Return a callable for the generate onboarding + suggestions method over gRPC. + + Generates personalized onboarding suggestions for the + Arc zero state: classifies the requesting user (new / + exploring / returning) from their assistant-session + history in the app and returns suggestion chips (resume + a session, continue work, or start something new) to + render before any message is sent. + + Returns: + Callable[[~.GenerateOnboardingSuggestionsRequest], + ~.GenerateOnboardingSuggestionsResponse]: + 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 "generate_onboarding_suggestions" not in self._stubs: + self._stubs["generate_onboarding_suggestions"] = ( + self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.SessionService/GenerateOnboardingSuggestions", + request_serializer=session_service.GenerateOnboardingSuggestionsRequest.serialize, + response_deserializer=session_service.GenerateOnboardingSuggestionsResponse.deserialize, + ) + ) + return self._stubs["generate_onboarding_suggestions"] + def close(self): self._logged_channel.close() diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/grpc_asyncio.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/grpc_asyncio.py index 60b820b4f32a..3582800aea3d 100644 --- a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/grpc_asyncio.py @@ -493,6 +493,106 @@ def bidi_run_session( ) return self._stubs["bidi_run_session"] + @property + def stream_chat_ai_assistant( + self, + ) -> Callable[ + [session_service.StreamChatAiAssistantRequest], + Awaitable[session_service.StreamChatAiAssistantResponse], + ]: + r"""Return a callable for the stream chat ai assistant method over gRPC. + + Runs Arc, the AI assistant, for the specified + assistant session in a streaming fashion. + + Returns: + Callable[[~.StreamChatAiAssistantRequest], + Awaitable[~.StreamChatAiAssistantResponse]]: + 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 "stream_chat_ai_assistant" not in self._stubs: + self._stubs["stream_chat_ai_assistant"] = self._logged_channel.unary_stream( + "/google.cloud.ces.v1beta.SessionService/StreamChatAiAssistant", + request_serializer=session_service.StreamChatAiAssistantRequest.serialize, + response_deserializer=session_service.StreamChatAiAssistantResponse.deserialize, + ) + return self._stubs["stream_chat_ai_assistant"] + + @property + def cancel_assistant_turn( + self, + ) -> Callable[ + [session_service.CancelAssistantTurnRequest], + Awaitable[session_service.CancelAssistantTurnResponse], + ]: + r"""Return a callable for the cancel assistant turn method over gRPC. + + Cancels the assistant session's in-flight turn, if + any: the explicit user stop for a turn running detached + from any stream. A cancel landing on a task that does + not host the turn preempts it through the session turn + epoch instead, ending it within one lease renewal. + + Returns: + Callable[[~.CancelAssistantTurnRequest], + Awaitable[~.CancelAssistantTurnResponse]]: + 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 "cancel_assistant_turn" not in self._stubs: + self._stubs["cancel_assistant_turn"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.SessionService/CancelAssistantTurn", + request_serializer=session_service.CancelAssistantTurnRequest.serialize, + response_deserializer=session_service.CancelAssistantTurnResponse.deserialize, + ) + return self._stubs["cancel_assistant_turn"] + + @property + def generate_onboarding_suggestions( + self, + ) -> Callable[ + [session_service.GenerateOnboardingSuggestionsRequest], + Awaitable[session_service.GenerateOnboardingSuggestionsResponse], + ]: + r"""Return a callable for the generate onboarding + suggestions method over gRPC. + + Generates personalized onboarding suggestions for the + Arc zero state: classifies the requesting user (new / + exploring / returning) from their assistant-session + history in the app and returns suggestion chips (resume + a session, continue work, or start something new) to + render before any message is sent. + + Returns: + Callable[[~.GenerateOnboardingSuggestionsRequest], + Awaitable[~.GenerateOnboardingSuggestionsResponse]]: + 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 "generate_onboarding_suggestions" not in self._stubs: + self._stubs["generate_onboarding_suggestions"] = ( + self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.SessionService/GenerateOnboardingSuggestions", + request_serializer=session_service.GenerateOnboardingSuggestionsRequest.serialize, + response_deserializer=session_service.GenerateOnboardingSuggestionsResponse.deserialize, + ) + ) + return self._stubs["generate_onboarding_suggestions"] + def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { @@ -525,6 +625,28 @@ def _prep_wrapped_messages(self, client_info): default_timeout=3600.0, client_info=client_info, ), + self.stream_chat_ai_assistant: self._wrap_method( + self.stream_chat_ai_assistant, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + deadline=3600.0, + ), + default_timeout=3600.0, + client_info=client_info, + ), + self.cancel_assistant_turn: self._wrap_method( + self.cancel_assistant_turn, + default_timeout=None, + client_info=client_info, + ), + self.generate_onboarding_suggestions: self._wrap_method( + self.generate_onboarding_suggestions, + default_timeout=None, + client_info=client_info, + ), self.get_location: self._wrap_method( self.get_location, default_timeout=None, diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/rest.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/rest.py index 84e5181602ec..4bdeb6869678 100644 --- a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/rest.py +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/rest.py @@ -74,6 +74,22 @@ class SessionServiceRestInterceptor: .. code-block:: python class MyCustomSessionServiceInterceptor(SessionServiceRestInterceptor): + def pre_cancel_assistant_turn(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_cancel_assistant_turn(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_generate_onboarding_suggestions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_generate_onboarding_suggestions(self, response): + logging.log(f"Received response: {response}") + return response + def pre_run_session(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -82,6 +98,14 @@ def post_run_session(self, response): logging.log(f"Received response: {response}") return response + def pre_stream_chat_ai_assistant(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_stream_chat_ai_assistant(self, response): + logging.log(f"Received response: {response}") + return response + def pre_stream_run_session(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -96,6 +120,110 @@ def post_stream_run_session(self, response): """ + def pre_cancel_assistant_turn( + self, + request: session_service.CancelAssistantTurnRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + session_service.CancelAssistantTurnRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for cancel_assistant_turn + + Override in a subclass to manipulate the request or metadata + before they are sent to the SessionService server. + """ + return request, metadata + + def post_cancel_assistant_turn( + self, response: session_service.CancelAssistantTurnResponse + ) -> session_service.CancelAssistantTurnResponse: + """Post-rpc interceptor for cancel_assistant_turn + + DEPRECATED. Please use the `post_cancel_assistant_turn_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SessionService server but before + it is returned to user code. This `post_cancel_assistant_turn` interceptor runs + before the `post_cancel_assistant_turn_with_metadata` interceptor. + """ + return response + + def post_cancel_assistant_turn_with_metadata( + self, + response: session_service.CancelAssistantTurnResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + session_service.CancelAssistantTurnResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for cancel_assistant_turn + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SessionService server but before it is returned to user code. + + We recommend only using this `post_cancel_assistant_turn_with_metadata` + interceptor in new development instead of the `post_cancel_assistant_turn` interceptor. + When both interceptors are used, this `post_cancel_assistant_turn_with_metadata` interceptor runs after the + `post_cancel_assistant_turn` interceptor. The (possibly modified) response returned by + `post_cancel_assistant_turn` will be passed to + `post_cancel_assistant_turn_with_metadata`. + """ + return response, metadata + + def pre_generate_onboarding_suggestions( + self, + request: session_service.GenerateOnboardingSuggestionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + session_service.GenerateOnboardingSuggestionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for generate_onboarding_suggestions + + Override in a subclass to manipulate the request or metadata + before they are sent to the SessionService server. + """ + return request, metadata + + def post_generate_onboarding_suggestions( + self, response: session_service.GenerateOnboardingSuggestionsResponse + ) -> session_service.GenerateOnboardingSuggestionsResponse: + """Post-rpc interceptor for generate_onboarding_suggestions + + DEPRECATED. Please use the `post_generate_onboarding_suggestions_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SessionService server but before + it is returned to user code. This `post_generate_onboarding_suggestions` interceptor runs + before the `post_generate_onboarding_suggestions_with_metadata` interceptor. + """ + return response + + def post_generate_onboarding_suggestions_with_metadata( + self, + response: session_service.GenerateOnboardingSuggestionsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + session_service.GenerateOnboardingSuggestionsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for generate_onboarding_suggestions + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SessionService server but before it is returned to user code. + + We recommend only using this `post_generate_onboarding_suggestions_with_metadata` + interceptor in new development instead of the `post_generate_onboarding_suggestions` interceptor. + When both interceptors are used, this `post_generate_onboarding_suggestions_with_metadata` interceptor runs after the + `post_generate_onboarding_suggestions` interceptor. The (possibly modified) response returned by + `post_generate_onboarding_suggestions` will be passed to + `post_generate_onboarding_suggestions_with_metadata`. + """ + return response, metadata + def pre_run_session( self, request: session_service.RunSessionRequest, @@ -146,6 +274,57 @@ def post_run_session_with_metadata( """ return response, metadata + def pre_stream_chat_ai_assistant( + self, + request: session_service.StreamChatAiAssistantRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + session_service.StreamChatAiAssistantRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for stream_chat_ai_assistant + + Override in a subclass to manipulate the request or metadata + before they are sent to the SessionService server. + """ + return request, metadata + + def post_stream_chat_ai_assistant( + self, response: rest_streaming.ResponseIterator + ) -> rest_streaming.ResponseIterator: + """Post-rpc interceptor for stream_chat_ai_assistant + + DEPRECATED. Please use the `post_stream_chat_ai_assistant_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SessionService server but before + it is returned to user code. This `post_stream_chat_ai_assistant` interceptor runs + before the `post_stream_chat_ai_assistant_with_metadata` interceptor. + """ + return response + + def post_stream_chat_ai_assistant_with_metadata( + self, + response: rest_streaming.ResponseIterator, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + rest_streaming.ResponseIterator, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for stream_chat_ai_assistant + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SessionService server but before it is returned to user code. + + We recommend only using this `post_stream_chat_ai_assistant_with_metadata` + interceptor in new development instead of the `post_stream_chat_ai_assistant` interceptor. + When both interceptors are used, this `post_stream_chat_ai_assistant_with_metadata` interceptor runs after the + `post_stream_chat_ai_assistant` interceptor. The (possibly modified) response returned by + `post_stream_chat_ai_assistant` will be passed to + `post_stream_chat_ai_assistant_with_metadata`. + """ + return response, metadata + def pre_stream_run_session( self, request: session_service.RunSessionRequest, @@ -455,6 +634,315 @@ def __call__( "Method BidiRunSession is not available over REST transport" ) + class _CancelAssistantTurn( + _BaseSessionServiceRestTransport._BaseCancelAssistantTurn, + SessionServiceRestStub, + ): + def __hash__(self): + return hash("SessionServiceRestTransport.CancelAssistantTurn") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: session_service.CancelAssistantTurnRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> session_service.CancelAssistantTurnResponse: + r"""Call the cancel assistant turn method over HTTP. + + Args: + request (~.session_service.CancelAssistantTurnRequest): + The request object. Request to cancel an assistant + session's in-flight turn. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.session_service.CancelAssistantTurnResponse: + Response for CancelAssistantTurn. + """ + + http_options = _BaseSessionServiceRestTransport._BaseCancelAssistantTurn._get_http_options() + request, metadata = self._interceptor.pre_cancel_assistant_turn( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseSessionServiceRestTransport._BaseCancelAssistantTurn, + "_BaseCancelAssistantTurn__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.SessionServiceClient.CancelAssistantTurn", + extra={ + "serviceName": "google.cloud.ces.v1beta.SessionService", + "rpcName": "CancelAssistantTurn", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SessionServiceRestTransport._CancelAssistantTurn._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + 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 = session_service.CancelAssistantTurnResponse() + pb_resp = session_service.CancelAssistantTurnResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_cancel_assistant_turn(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_cancel_assistant_turn_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + session_service.CancelAssistantTurnResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.SessionServiceClient.cancel_assistant_turn", + extra={ + "serviceName": "google.cloud.ces.v1beta.SessionService", + "rpcName": "CancelAssistantTurn", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GenerateOnboardingSuggestions( + _BaseSessionServiceRestTransport._BaseGenerateOnboardingSuggestions, + SessionServiceRestStub, + ): + def __hash__(self): + return hash("SessionServiceRestTransport.GenerateOnboardingSuggestions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: session_service.GenerateOnboardingSuggestionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> session_service.GenerateOnboardingSuggestionsResponse: + r"""Call the generate onboarding + suggestions method over HTTP. + + Args: + request (~.session_service.GenerateOnboardingSuggestionsRequest): + The request object. Request message for + [SessionService.GenerateOnboardingSuggestions][google.cloud.ces.v1beta.SessionService.GenerateOnboardingSuggestions]. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.session_service.GenerateOnboardingSuggestionsResponse: + Response message for + [SessionService.GenerateOnboardingSuggestions][google.cloud.ces.v1beta.SessionService.GenerateOnboardingSuggestions]. + + """ + + http_options = _BaseSessionServiceRestTransport._BaseGenerateOnboardingSuggestions._get_http_options() + request, metadata = self._interceptor.pre_generate_onboarding_suggestions( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseSessionServiceRestTransport._BaseGenerateOnboardingSuggestions, + "_BaseGenerateOnboardingSuggestions__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.SessionServiceClient.GenerateOnboardingSuggestions", + extra={ + "serviceName": "google.cloud.ces.v1beta.SessionService", + "rpcName": "GenerateOnboardingSuggestions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SessionServiceRestTransport._GenerateOnboardingSuggestions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + 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 = session_service.GenerateOnboardingSuggestionsResponse() + pb_resp = session_service.GenerateOnboardingSuggestionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_generate_onboarding_suggestions(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_generate_onboarding_suggestions_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + session_service.GenerateOnboardingSuggestionsResponse.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.SessionServiceClient.generate_onboarding_suggestions", + extra={ + "serviceName": "google.cloud.ces.v1beta.SessionService", + "rpcName": "GenerateOnboardingSuggestions", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _RunSession( _BaseSessionServiceRestTransport._BaseRunSession, SessionServiceRestStub ): @@ -607,6 +1095,152 @@ def __call__( ) return resp + class _StreamChatAiAssistant( + _BaseSessionServiceRestTransport._BaseStreamChatAiAssistant, + SessionServiceRestStub, + ): + def __hash__(self): + return hash("SessionServiceRestTransport.StreamChatAiAssistant") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + stream=True, + ) + return response + + def __call__( + self, + request: session_service.StreamChatAiAssistantRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> rest_streaming.ResponseIterator: + r"""Call the stream chat ai assistant method over HTTP. + + Args: + request (~.session_service.StreamChatAiAssistantRequest): + The request object. Request message for + [SessionService.StreamChatAiAssistant][google.cloud.ces.v1beta.SessionService.StreamChatAiAssistant]. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.session_service.StreamChatAiAssistantResponse: + Response message for + [SessionService.StreamChatAiAssistant][google.cloud.ces.v1beta.SessionService.StreamChatAiAssistant]. + + """ + + http_options = _BaseSessionServiceRestTransport._BaseStreamChatAiAssistant._get_http_options() + request, metadata = self._interceptor.pre_stream_chat_ai_assistant( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseSessionServiceRestTransport._BaseStreamChatAiAssistant, + "_BaseStreamChatAiAssistant__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.SessionServiceClient.StreamChatAiAssistant", + extra={ + "serviceName": "google.cloud.ces.v1beta.SessionService", + "rpcName": "StreamChatAiAssistant", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SessionServiceRestTransport._StreamChatAiAssistant._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + 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 = rest_streaming.ResponseIterator( + response, session_service.StreamChatAiAssistantResponse + ) + + resp = self._interceptor.post_stream_chat_ai_assistant(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_stream_chat_ai_assistant_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + http_response = { + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.SessionServiceClient.stream_chat_ai_assistant", + extra={ + "serviceName": "google.cloud.ces.v1beta.SessionService", + "rpcName": "StreamChatAiAssistant", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _StreamRunSession( _BaseSessionServiceRestTransport._BaseStreamRunSession, SessionServiceRestStub ): @@ -763,6 +1397,30 @@ def bidi_run_session( # In C++ this would require a dynamic_cast return self._BidiRunSession(self._session, self._host, self._interceptor) # type: ignore + @property + def cancel_assistant_turn( + self, + ) -> Callable[ + [session_service.CancelAssistantTurnRequest], + session_service.CancelAssistantTurnResponse, + ]: + # 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._CancelAssistantTurn(self._session, self._host, self._interceptor) # type: ignore + + @property + def generate_onboarding_suggestions( + self, + ) -> Callable[ + [session_service.GenerateOnboardingSuggestionsRequest], + session_service.GenerateOnboardingSuggestionsResponse, + ]: + # 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._GenerateOnboardingSuggestions( + self._session, self._host, self._interceptor + ) # type: ignore + @property def run_session( self, @@ -773,6 +1431,17 @@ def run_session( # In C++ this would require a dynamic_cast return self._RunSession(self._session, self._host, self._interceptor) # type: ignore + @property + def stream_chat_ai_assistant( + self, + ) -> Callable[ + [session_service.StreamChatAiAssistantRequest], + session_service.StreamChatAiAssistantResponse, + ]: + # 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._StreamChatAiAssistant(self._session, self._host, self._interceptor) # type: ignore + @property def stream_run_session( self, diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/rest_base.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/rest_base.py index b14c0643b4f5..5351bed08671 100644 --- a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/rest_base.py +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/rest_base.py @@ -93,6 +93,40 @@ class _BaseBidiRunSession: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") + class _BaseCancelAssistantTurn: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*/assistantSessions/*}:cancelAssistantTurn", + "body": "*", + }, + ] + return http_options + + class _BaseGenerateOnboardingSuggestions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*}:generateOnboardingSuggestions", + "body": "*", + }, + ] + return http_options + class _BaseRunSession: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -110,6 +144,23 @@ def _get_http_options(): ] return http_options + class _BaseStreamChatAiAssistant: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*/assistantSessions/*}:streamChatAiAssistant", + "body": "*", + }, + ] + return http_options + class _BaseStreamRunSession: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/__init__.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/__init__.py index 5e8a6f8cbd0f..cf7955a3e8d5 100644 --- a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/__init__.py +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/__init__.py @@ -20,6 +20,7 @@ AgentCard, AgentInterface, AgentSkill, + RemoteA2aConfig, RemoteAgentTool, ) from .agent_service import ( @@ -42,6 +43,7 @@ DeleteGuardrailRequest, DeleteToolRequest, DeleteToolsetRequest, + DeployChannelResponse, ExportAppRequest, ExportAppResponse, GenerateAppResourceOperationMetadata, @@ -86,6 +88,7 @@ RestoreAppVersionResponse, UpdateAgentRequest, UpdateAppRequest, + UpdateAppVersionRequest, UpdateDeploymentRequest, UpdateExampleRequest, UpdateGuardrailRequest, @@ -110,6 +113,8 @@ ClientCertificateSettings, CloudLoggingSettings, ConversationLoggingSettings, + CustomVoiceSample, + DashboardSettings, DataStoreSettings, ErrorHandlingSettings, EvaluationMetricsThresholds, @@ -127,6 +132,26 @@ AppSnapshot, AppVersion, ) +from .assistant_service import ( + ActiveTurnInfo, + AssistantChunk, + AssistantMessage, + AssistantOutput, + AssistantSession, + AssistantSessionArtifact, + AssistantSessionState, + ChatAiAssistantRequest, + ChatAiAssistantResponse, + CreateAssistantSessionRequest, + DeleteAssistantSessionRequest, + GetAssistantSessionRequest, + ListAssistantSessionsRequest, + ListAssistantSessionsResponse, + RunAssistantRequest, + RunAssistantResponse, + TypedPayload, + UserResponseSuggestions, +) from .auth import ( ApiAuthentication, ApiKeyConfig, @@ -152,9 +177,11 @@ ExecutionType, ModelSettings, ServiceDirectoryConfig, + SessionCheckpoint, Span, TlsConfig, TriggerAction, + UiEvent, ) from .connector_tool import ( Action, @@ -173,6 +200,7 @@ DataStoreTool, ) from .deployment import ( + AgentRegistryDeployment, Deployment, ExperimentConfig, InstagramCredentials, @@ -323,16 +351,26 @@ SecuritySettings, ) from .session_service import ( + ArtifactChunk, + AssistantConfirmationRequest, + AssistantConfirmationResponse, + AssistantSuggestion, AudioEncoding, BidiSessionClientMessage, BidiSessionServerMessage, + CancelAssistantTurnRequest, + CancelAssistantTurnResponse, Citations, EndSession, Event, + GenerateOnboardingSuggestionsRequest, + GenerateOnboardingSuggestionsResponse, GoAway, InputAudioConfig, InterruptionSignal, MockConfig, + OperationCompletedEvent, + OptionQuestionsChunk, OutputAudioConfig, RecognitionResult, RunSessionRequest, @@ -340,8 +378,14 @@ SessionConfig, SessionInput, SessionOutput, + StreamChatAiAssistantRequest, + StreamChatAiAssistantResponse, ToolCalls, ToolResponses, + TurnCompletedEvent, + TurnHandoffEvent, + TurnMetadata, + TurnResumeSnapshot, ) from .system_tool import ( SystemTool, @@ -376,6 +420,7 @@ "AgentCard", "AgentInterface", "AgentSkill", + "RemoteA2aConfig", "RemoteAgentTool", "BatchDeleteConversationsRequest", "BatchDeleteConversationsResponse", @@ -396,6 +441,7 @@ "DeleteGuardrailRequest", "DeleteToolRequest", "DeleteToolsetRequest", + "DeployChannelResponse", "ExportAppRequest", "ExportAppResponse", "GenerateAppResourceOperationMetadata", @@ -440,6 +486,7 @@ "RestoreAppVersionResponse", "UpdateAgentRequest", "UpdateAppRequest", + "UpdateAppVersionRequest", "UpdateDeploymentRequest", "UpdateExampleRequest", "UpdateGuardrailRequest", @@ -458,6 +505,8 @@ "ClientCertificateSettings", "CloudLoggingSettings", "ConversationLoggingSettings", + "CustomVoiceSample", + "DashboardSettings", "DataStoreSettings", "ErrorHandlingSettings", "EvaluationMetricsThresholds", @@ -472,6 +521,24 @@ "VpcScSettings", "AppSnapshot", "AppVersion", + "ActiveTurnInfo", + "AssistantChunk", + "AssistantMessage", + "AssistantOutput", + "AssistantSession", + "AssistantSessionArtifact", + "ChatAiAssistantRequest", + "ChatAiAssistantResponse", + "CreateAssistantSessionRequest", + "DeleteAssistantSessionRequest", + "GetAssistantSessionRequest", + "ListAssistantSessionsRequest", + "ListAssistantSessionsResponse", + "RunAssistantRequest", + "RunAssistantResponse", + "TypedPayload", + "UserResponseSuggestions", + "AssistantSessionState", "ApiAuthentication", "ApiKeyConfig", "BearerTokenConfig", @@ -487,9 +554,11 @@ "EvaluationRunCachingSettings", "ModelSettings", "ServiceDirectoryConfig", + "SessionCheckpoint", "Span", "TlsConfig", "TriggerAction", + "UiEvent", "ExecutionType", "Action", "ConnectorTool", @@ -497,6 +566,7 @@ "Conversation", "DataStore", "DataStoreTool", + "AgentRegistryDeployment", "Deployment", "ExperimentConfig", "InstagramCredentials", @@ -603,15 +673,25 @@ "WebSearchQuery", "EndpointControlPolicy", "SecuritySettings", + "ArtifactChunk", + "AssistantConfirmationRequest", + "AssistantConfirmationResponse", + "AssistantSuggestion", "BidiSessionClientMessage", "BidiSessionServerMessage", + "CancelAssistantTurnRequest", + "CancelAssistantTurnResponse", "Citations", "EndSession", "Event", + "GenerateOnboardingSuggestionsRequest", + "GenerateOnboardingSuggestionsResponse", "GoAway", "InputAudioConfig", "InterruptionSignal", "MockConfig", + "OperationCompletedEvent", + "OptionQuestionsChunk", "OutputAudioConfig", "RecognitionResult", "RunSessionRequest", @@ -619,8 +699,14 @@ "SessionConfig", "SessionInput", "SessionOutput", + "StreamChatAiAssistantRequest", + "StreamChatAiAssistantResponse", "ToolCalls", "ToolResponses", + "TurnCompletedEvent", + "TurnHandoffEvent", + "TurnMetadata", + "TurnResumeSnapshot", "AudioEncoding", "SystemTool", "Tool", diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/agent.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/agent.py index d49925b7833d..c0a934981a5f 100644 --- a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/agent.py +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/agent.py @@ -20,7 +20,7 @@ import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore import proto # type: ignore -from google.cloud.ces_v1beta.types import agent_transfers, common +from google.cloud.ces_v1beta.types import agent_card, agent_transfers, common __protobuf__ = proto.module( package="google.cloud.ces.v1beta", @@ -58,6 +58,12 @@ class Agent(proto.Message): CES service agent ``service-@gcp-sa-ces.iam.gserviceaccount.com``. + This field is a member of `oneof`_ ``agent_type``. + remote_a2a_agent (google.cloud.ces_v1beta.types.Agent.RemoteA2aAgent): + Optional. The remote + `A2A `__ agent to be used + for the agent execution. + This field is a member of `oneof`_ ``agent_type``. name (str): Identifier. The unique identifier of the agent. Format: @@ -243,6 +249,21 @@ class RemoteDialogflowAgent(proto.Message): number=7, ) + class RemoteA2aAgent(proto.Message): + r"""The agent which will transfer execution to a remote + `A2A `__ agent. + + Attributes: + a2a_config (google.cloud.ces_v1beta.types.RemoteA2aConfig): + Required. The A2A connection configuration. + """ + + a2a_config: agent_card.RemoteA2aConfig = proto.Field( + proto.MESSAGE, + number=1, + message=agent_card.RemoteA2aConfig, + ) + class AgentToolset(proto.Message): r"""A toolset with a selection of its tools. @@ -276,6 +297,12 @@ class AgentToolset(proto.Message): oneof="agent_type", message=RemoteDialogflowAgent, ) + remote_a2a_agent: RemoteA2aAgent = proto.Field( + proto.MESSAGE, + number=41, + oneof="agent_type", + message=RemoteA2aAgent, + ) name: str = proto.Field( proto.STRING, number=1, diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/agent_card.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/agent_card.py index 7d1e4ba85bb2..a5360bfcb904 100644 --- a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/agent_card.py +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/agent_card.py @@ -19,12 +19,15 @@ import proto # type: ignore +from google.cloud.ces_v1beta.types import auth + __protobuf__ = proto.module( package="google.cloud.ces.v1beta", manifest={ "AgentCard", "AgentInterface", "AgentSkill", + "RemoteA2aConfig", "RemoteAgentTool", }, ) @@ -184,6 +187,85 @@ class AgentSkill(proto.Message): ) +class RemoteA2aConfig(proto.Message): + r"""Shared configuration for connecting to a remote + `A2A `__ agent. + + 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: + agent_card (google.cloud.ces_v1beta.types.AgentCard): + Optional. The full agent card defined inline. + + This field is a member of `oneof`_ ``agent_spec``. + agent_registry (str): + Optional. Reference to the agent in the Agent Registry. + Format: + ``projects/{project}/locations/{location}/agents/{agent}`` + + This field is a member of `oneof`_ ``agent_spec``. + api_authentication (google.cloud.ces_v1beta.types.ApiAuthentication): + Optional. Authentication configuration for + calling the remote agent. Optional if the + registry reference already handles + authentication. + input_variable_mapping (MutableMapping[str, str]): + Optional. Mapping of input variable names of + remote agent to GECX variable names. + output_variable_mapping (MutableMapping[str, str]): + Optional. Mapping of output variable names of + remote agent to GECX variable names. + streaming_enabled (bool): + Optional. Whether streaming is enabled for + the remote agent. + context_id (str): + Optional. If not empty, interactions with the remote A2A + agent will use this context ID. This context_id field can + refer to a session variable like + ``$context.variables.order_agent_session_id``. + """ + + agent_card: "AgentCard" = proto.Field( + proto.MESSAGE, + number=1, + oneof="agent_spec", + message="AgentCard", + ) + agent_registry: str = proto.Field( + proto.STRING, + number=2, + oneof="agent_spec", + ) + api_authentication: auth.ApiAuthentication = proto.Field( + proto.MESSAGE, + number=3, + message=auth.ApiAuthentication, + ) + input_variable_mapping: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + output_variable_mapping: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + streaming_enabled: bool = proto.Field( + proto.BOOL, + number=6, + ) + context_id: str = proto.Field( + proto.STRING, + number=7, + ) + + class RemoteAgentTool(proto.Message): r"""Represents a tool that allows the agent to call another remote agent. @@ -196,6 +278,20 @@ class RemoteAgentTool(proto.Message): agent_card (google.cloud.ces_v1beta.types.AgentCard): Required. The agent card of the remote agent that this tool invokes. + api_authentication (google.cloud.ces_v1beta.types.ApiAuthentication): + Optional. Authentication configuration for + calling the remote agent. + stateful_agent (bool): + Optional. When enabled, the interaction between the CXAS app + and the remote agent will share the same context. If the + remote agent returns a context_id, it will be persisted for + the entirety of the session for this remote agent tool. + input_variable_mapping (MutableMapping[str, str]): + Optional. Mapping of input variable names of + remote agent to GECX variable names. + output_variable_mapping (MutableMapping[str, str]): + Optional. Mapping of output variable names of + remote agent to GECX variable names. """ name: str = proto.Field( @@ -211,6 +307,25 @@ class RemoteAgentTool(proto.Message): number=3, message="AgentCard", ) + api_authentication: auth.ApiAuthentication = proto.Field( + proto.MESSAGE, + number=4, + message=auth.ApiAuthentication, + ) + stateful_agent: bool = proto.Field( + proto.BOOL, + number=5, + ) + input_variable_mapping: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=6, + ) + output_variable_mapping: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/agent_service.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/agent_service.py index 747073c49d9c..1ed96613a118 100644 --- a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/agent_service.py +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/agent_service.py @@ -86,6 +86,7 @@ "ListDeploymentsResponse", "GetDeploymentRequest", "CreateDeploymentRequest", + "DeployChannelResponse", "UpdateDeploymentRequest", "DeleteDeploymentRequest", "ListToolsetsRequest", @@ -99,6 +100,7 @@ "GetAppVersionRequest", "DeleteAppVersionRequest", "CreateAppVersionRequest", + "UpdateAppVersionRequest", "RestoreAppVersionRequest", "RestoreAppVersionResponse", "GenerateAppResourceRequest", @@ -419,6 +421,15 @@ class ImportAppRequest(proto.Message): file with the app folder structure. This field is a member of `oneof`_ ``app``. + json_patch_content (str): + Optional. Patch content as a JSON string. + + This field is a member of `oneof`_ ``json_patch``. + json_patch_gcs_uri (str): + Optional. A Cloud Storage URI pointing to a + JSON file containing the patches. + + This field is a member of `oneof`_ ``json_patch``. parent (str): Required. The parent resource name with the location of the app to import. @@ -459,6 +470,11 @@ class ImportOptions(proto.Message): conflict_resolution_strategy (google.cloud.ces_v1beta.types.ImportAppRequest.ImportOptions.ConflictResolutionStrategy): Optional. The strategy to use when resolving conflicts during import. + validate_only (bool): + Optional. Flag for dry-running the import + process. If set to true, the import process will + only perform validations and will not make any + changes to the existing app or create a new one. """ class ConflictResolutionStrategy(proto.Enum): @@ -502,6 +518,10 @@ class ConflictResolutionStrategy(proto.Enum): number=1, enum="ImportAppRequest.ImportOptions.ConflictResolutionStrategy", ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) gcs_uri: str = proto.Field( proto.STRING, @@ -513,6 +533,16 @@ class ConflictResolutionStrategy(proto.Enum): number=5, oneof="app", ) + json_patch_content: str = proto.Field( + proto.STRING, + number=9, + oneof="json_patch", + ) + json_patch_gcs_uri: str = proto.Field( + proto.STRING, + number=10, + oneof="json_patch", + ) parent: str = proto.Field( proto.STRING, number=1, @@ -1681,6 +1711,22 @@ class CreateDeploymentRequest(proto.Message): ) +class DeployChannelResponse(proto.Message): + r"""Response message for + [AgentService.DeployChannel][google.cloud.ces.v1beta.AgentService.DeployChannel]. + + Attributes: + deployment (google.cloud.ces_v1beta.types.Deployment): + The created deployment. + """ + + deployment: gcc_deployment.Deployment = proto.Field( + proto.MESSAGE, + number=1, + message=gcc_deployment.Deployment, + ) + + class UpdateDeploymentRequest(proto.Message): r"""Request message for [AgentService.UpdateDeployment][google.cloud.ces.v1beta.AgentService.UpdateDeployment]. @@ -2079,6 +2125,30 @@ class CreateAppVersionRequest(proto.Message): ) +class UpdateAppVersionRequest(proto.Message): + r"""Request message for + [AgentService.UpdateAppVersion][google.cloud.ces.v1beta.AgentService.UpdateAppVersion]. + + Attributes: + app_version (google.cloud.ces_v1beta.types.AppVersion): + Required. The app version to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to update. If empty, fields + ``display_name`` and ``description`` will be updated. + """ + + app_version: gcc_app_version.AppVersion = proto.Field( + proto.MESSAGE, + number=1, + message=gcc_app_version.AppVersion, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + class RestoreAppVersionRequest(proto.Message): r"""Request message for [AgentService.RestoreAppVersion][google.cloud.ces.v1beta.AgentService.RestoreAppVersion] diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/app.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/app.py index 96f63b85aa38..020cbfc4f57b 100644 --- a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/app.py +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/app.py @@ -34,8 +34,10 @@ package="google.cloud.ces.v1beta", manifest={ "App", + "DashboardSettings", "TimeZoneSettings", "LanguageSettings", + "CustomVoiceSample", "AudioProcessingConfig", "AmbientSoundConfig", "BargeInConfig", @@ -159,6 +161,10 @@ class App(proto.Message): validation_errors (MutableSequence[str]): Output only. Misconfigurations or warnings in the app. + dashboard_settings (google.cloud.ces_v1beta.types.DashboardSettings): + Optional. App-specific dashboard settings for + linking and configuring Contact Center Insights + dashboards. """ class ToolExecutionMode(proto.Enum): @@ -354,6 +360,32 @@ class VariableDeclaration(proto.Message): proto.STRING, number=39, ) + dashboard_settings: "DashboardSettings" = proto.Field( + proto.MESSAGE, + number=43, + message="DashboardSettings", + ) + + +class DashboardSettings(proto.Message): + r"""Settings for dashboards associated with the app, that show up + in the Monitoring view. + + Attributes: + default_dashboard (str): + Optional. The resource name of the default Contact Center + Insights dashboard associated with the app. This is the + dashboard that will be displayed when users navigate to the + Monitoring view for the app. + + Format: + ``projects/{project}/locations/{location}/dashboards/{dashboard}`` + """ + + default_dashboard: str = proto.Field( + proto.STRING, + number=1, + ) class TimeZoneSettings(proto.Message): @@ -383,10 +415,9 @@ class LanguageSettings(proto.Message): Optional. List of languages codes supported by the app, in addition to the ``default_language_code``. enable_multilingual_support (bool): - Optional. Enables multilingual support. If - true, agents in the app will use pre-built - instructions to improve handling of multilingual - input. + Optional. Enables multilingual support. If ``true``, agents + in the app will use pre-built instructions to improve + handling of multilingual input. fallback_action (str): Optional. Deprecated: This feature is no longer supported. Use ``enable_multilingual_support`` instead to improve @@ -424,6 +455,131 @@ class LanguageSettings(proto.Message): ) +class CustomVoiceSample(proto.Message): + r"""Configuration for a custom voice sample used for voice + cloning. + + Attributes: + name (str): + Optional. The user-defined name for the + custom voice sample. + voice_sample_gcs_uri (str): + Optional. The Cloud Storage URI to the audio + sample for voice cloning. The audio sample + should be a mono-channel, 24kHz WAV file. + consent_audio_gcs_uri (str): + Optional. Consent audio for voice cloning. + voice_instruction (str): + Optional. Natural language instructions for + voice style, tone, pacing, or pronunciation. + preview_audio_content (bytes): + Output only. Synthesized preview audio for + custom voice, formatted as canonical WAV + (LINEAR16, 24kHz, 16-bit, mono). + preview_text (str): + Optional. Text for synthesizing preview audio + for custom voice. + warnings (MutableSequence[google.cloud.ces_v1beta.types.CustomVoiceSample.Warning]): + Output only. Warning messages encountered + during voice clone processing (e.g. low audio + level). + voice_instruction_mode (google.cloud.ces_v1beta.types.CustomVoiceSample.VoiceInstructionMode): + Optional. Instruction mode for the voice sample. If + unspecified, defaults to NO_INSTRUCTION. + """ + + class VoiceInstructionMode(proto.Enum): + r"""Instruction mode for the voice sample. + + Values: + VOICE_INSTRUCTION_MODE_UNSPECIFIED (0): + Unspecified instruction mode. Defaults to NO_INSTRUCTION. + NO_INSTRUCTION (1): + No voice instruction will be used. + GENERATE_INSTRUCTION (2): + Voice instruction will be automatically + generated by AI from the audio sample. + CUSTOM_INSTRUCTION (3): + Custom voice instruction provided by the + user. + """ + + VOICE_INSTRUCTION_MODE_UNSPECIFIED = 0 + NO_INSTRUCTION = 1 + GENERATE_INSTRUCTION = 2 + CUSTOM_INSTRUCTION = 3 + + class Warning(proto.Message): + r"""A warning message encountered during voice sample processing. + + Attributes: + message (str): + Output only. A human-readable description of + the warning. + type_ (google.cloud.ces_v1beta.types.CustomVoiceSample.Warning.WarningType): + Output only. The type of the warning. + """ + + class WarningType(proto.Enum): + r"""Type of warning encountered during voice sample processing. + + Values: + WARNING_TYPE_UNSPECIFIED (0): + Unspecified warning type. + LOW_AUDIO_LEVEL (1): + The audio level of the voice sample is too + low (e.g. low RMS amplitude). + """ + + WARNING_TYPE_UNSPECIFIED = 0 + LOW_AUDIO_LEVEL = 1 + + message: str = proto.Field( + proto.STRING, + number=1, + ) + type_: "CustomVoiceSample.Warning.WarningType" = proto.Field( + proto.ENUM, + number=2, + enum="CustomVoiceSample.Warning.WarningType", + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + voice_sample_gcs_uri: str = proto.Field( + proto.STRING, + number=2, + ) + consent_audio_gcs_uri: str = proto.Field( + proto.STRING, + number=3, + ) + voice_instruction: str = proto.Field( + proto.STRING, + number=4, + ) + preview_audio_content: bytes = proto.Field( + proto.BYTES, + number=5, + ) + preview_text: str = proto.Field( + proto.STRING, + number=6, + ) + warnings: MutableSequence[Warning] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=Warning, + ) + voice_instruction_mode: VoiceInstructionMode = proto.Field( + proto.ENUM, + number=8, + enum=VoiceInstructionMode, + ) + + class AudioProcessingConfig(proto.Message): r"""Configuration for how the input and output audio should be processed and delivered. @@ -454,6 +610,9 @@ class AudioProcessingConfig(proto.Message): to be played with the synthesized agent response, to enhance the naturalness of the conversation. + custom_voice_samples (MutableSequence[google.cloud.ces_v1beta.types.CustomVoiceSample]): + Optional. Configures custom voice samples for + voice cloning. """ synthesize_speech_configs: MutableMapping[str, "SynthesizeSpeechConfig"] = ( @@ -479,6 +638,11 @@ class AudioProcessingConfig(proto.Message): number=5, message="AmbientSoundConfig", ) + custom_voice_samples: MutableSequence["CustomVoiceSample"] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message="CustomVoiceSample", + ) class AmbientSoundConfig(proto.Message): @@ -736,6 +900,19 @@ class LoggingSettings(proto.Message): Optional. Settings to describe the conversation data collection behaviors for the LLM analysis pipeline for the app. + required_recording_consent (bool): + Optional. Whether the app has to say what may be recorded + before anything is kept. + + When true, a session starts with recording off and stays off + until the client sends + [SessionInput.recording_control][google.cloud.ces.v1main.SessionInput.recording_control], + which then decides every turn from that point on. This + covers audio recording as well as conversation history, + BigQuery export and Cloud Logging. + + When ``false``, the default, the settings above decide on + their own and the client does not have to send anything. """ redaction_config: "RedactionConfig" = proto.Field( @@ -785,6 +962,10 @@ class LoggingSettings(proto.Message): number=7, message="MetricAnalysisSettings", ) + required_recording_consent: bool = proto.Field( + proto.BOOL, + number=10, + ) class ErrorHandlingSettings(proto.Message): @@ -1349,10 +1530,9 @@ class RedactionConfig(proto.Message): Attributes: enable_redaction (bool): - Optional. If true, redaction will be applied - in various logging scenarios, including - conversation history, Cloud Logging and audio - recording. + Optional. If ``true``, redaction will be applied in various + logging scenarios, including conversation history, Cloud + Logging and audio recording. inspect_template (str): Optional. `DLP `__ inspect template name to configure detection of sensitive diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/app_version.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/app_version.py index af44bd95856e..e9ee5a17ff8e 100644 --- a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/app_version.py +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/app_version.py @@ -103,6 +103,9 @@ class AppVersion(proto.Message): create_time (google.protobuf.timestamp_pb2.Timestamp): Output only. Timestamp when the app version was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the app version + was last updated. snapshot (google.cloud.ces_v1beta.types.AppSnapshot): Output only. The snapshot of the app when the version is created. @@ -134,6 +137,11 @@ class AppVersion(proto.Message): number=5, message=timestamp_pb2.Timestamp, ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) snapshot: "AppSnapshot" = proto.Field( proto.MESSAGE, number=8, diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/assistant_service.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/assistant_service.py new file mode 100644 index 000000000000..9bc563ec2049 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/assistant_service.py @@ -0,0 +1,829 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 google.protobuf.struct_pb2 as struct_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.ces_v1beta.types import common + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "AssistantSessionState", + "ListAssistantSessionsRequest", + "ListAssistantSessionsResponse", + "GetAssistantSessionRequest", + "CreateAssistantSessionRequest", + "DeleteAssistantSessionRequest", + "RunAssistantRequest", + "RunAssistantResponse", + "AssistantSession", + "ActiveTurnInfo", + "AssistantSessionArtifact", + "AssistantChunk", + "AssistantOutput", + "AssistantMessage", + "TypedPayload", + "UserResponseSuggestions", + "ChatAiAssistantRequest", + "ChatAiAssistantResponse", + }, +) + + +class AssistantSessionState(proto.Enum): + r"""The status of the assistant session. + + Values: + ASSISTANT_SESSION_STATE_UNSPECIFIED (0): + The default value. This value is used if the + status is not specified. + PROCESSING (1): + The assistant agent is processing the request + as a long running task. + IDLE (2): + The assistant agent is idle and does not have + any pending requests or response. + PENDING_REVIEW (3): + The assistant agent is done processing a long + running task and has a response ready for the + user. + """ + + ASSISTANT_SESSION_STATE_UNSPECIFIED = 0 + PROCESSING = 1 + IDLE = 2 + PENDING_REVIEW = 3 + + +class ListAssistantSessionsRequest(proto.Message): + r"""Request message for + [AssistantService.ListAssistantSessions][google.cloud.ces.v1beta.AssistantService.ListAssistantSessions]. + + Attributes: + parent (str): + Required. The app to list assistant sessions from. Format: + ``projects/{project}/locations/{location}/apps/{app}`` + page_size (int): + Optional. Requested page size. Server may + return fewer items than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + Optional. The + [next_page_token][google.cloud.ces.v1beta.ListAssistantSessionsResponse.next_page_token] + value returned from a previous list + [AssistantService.ListAssistantSessions][google.cloud.ces.v1beta.AssistantService.ListAssistantSessions] + call. + filter (str): + Optional. Filter to be applied when listing + the assistant sessions. See + https://google.aip.dev/160 for more details. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListAssistantSessionsResponse(proto.Message): + r"""Response message for + [AssistantService.ListAssistantSessions][google.cloud.ces.v1beta.AssistantService.ListAssistantSessions]. + + Attributes: + assistant_sessions (MutableSequence[google.cloud.ces_v1beta.types.AssistantSession]): + The list of assistant sessions. + next_page_token (str): + Optional. A token that can be sent as + [ListAssistantSessionsRequest.page_token][google.cloud.ces.v1beta.ListAssistantSessionsRequest.page_token] + to retrieve the next page. Absence of this field indicates + there are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + assistant_sessions: MutableSequence["AssistantSession"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="AssistantSession", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetAssistantSessionRequest(proto.Message): + r"""Request message for + [AssistantService.GetAssistantSession][google.cloud.ces.v1beta.AssistantService.GetAssistantSession]. + + Attributes: + name (str): + Required. The name of the assistant session to retrieve. + Format: + ``projects/{project}/locations/{location}/apps/{app}/assistantSessions/{assistant_session}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateAssistantSessionRequest(proto.Message): + r"""Request message for + [AssistantService.CreateAssistantSession][google.cloud.ces.v1beta.AssistantService.CreateAssistantSession]. + + Attributes: + parent (str): + Required. The app to create the assistant session in Format: + ``projects/{project}/locations/{location}/apps/{app}`` + assistant_session_id (str): + Optional. The ID to use for the assistant + session, which will become the final component + of the assistant session's resource name. If not + provided, a unique ID will be automatically + assigned for the assistant session. + assistant_session_messages (MutableSequence[google.cloud.ces_v1beta.types.AssistantMessage]): + Optional. The messages to seed the assistant + session with. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + assistant_session_id: str = proto.Field( + proto.STRING, + number=2, + ) + assistant_session_messages: MutableSequence["AssistantMessage"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=3, + message="AssistantMessage", + ) + ) + + +class DeleteAssistantSessionRequest(proto.Message): + r"""Request message for + [AssistantService.DeleteAssistantSession][google.cloud.ces.v1beta.AssistantService.DeleteAssistantSession]. + + Attributes: + name (str): + Required. The name of the assistant session to delete. + Format: + ``projects/{project}/locations/{location}/apps/{app}/assistantSessions/{assistant_session}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class RunAssistantRequest(proto.Message): + r"""Request message for + [AssistantService.RunAssistant][google.cloud.ces.v1beta.AssistantService.RunAssistant]. + + Attributes: + app (str): + Required. The app to run assistant for. Format: + ``projects/{project}/locations/{location}/apps/{app}`` + assistant_session (str): + Required. The assistant session to be used to run the + assistant. Format: + ``projects/{project}/locations/{location}/apps/{app}/assistantSessions/{assistant_session}`` + message (google.cloud.ces_v1beta.types.AssistantMessage): + Required. The message to send to the + assistant agent. + interaction_type (google.cloud.ces_v1beta.types.RunAssistantRequest.InteractionType): + Optional. Different interaction types for the + assistant message. + """ + + class InteractionType(proto.Enum): + r"""The type of interaction for the message sent to the + assistant. + + Values: + INTERACTION_TYPE_UNSPECIFIED (0): + The default value. This value is used if the + type is not specified. + NEW_MESSAGE (1): + The message is a user input. User input is + provided in the chunk list. + POLL (2): + The message is for polling the state of the + assistant session. + DISMISS (3): + The message is to dismiss the assistant + session pending review. This will change the + state of the assistant session to idle. + """ + + INTERACTION_TYPE_UNSPECIFIED = 0 + NEW_MESSAGE = 1 + POLL = 2 + DISMISS = 3 + + app: str = proto.Field( + proto.STRING, + number=1, + ) + assistant_session: str = proto.Field( + proto.STRING, + number=2, + ) + message: "AssistantMessage" = proto.Field( + proto.MESSAGE, + number=3, + message="AssistantMessage", + ) + interaction_type: InteractionType = proto.Field( + proto.ENUM, + number=4, + enum=InteractionType, + ) + + +class RunAssistantResponse(proto.Message): + r"""Response message for + [AssistantService.RunAssistant][google.cloud.ces.v1beta.AssistantService.RunAssistant]. + + Attributes: + output (google.cloud.ces_v1beta.types.AssistantOutput): + Required. The output from the assistant + agent. + state (google.cloud.ces_v1beta.types.AssistantSessionState): + Output only. The status of the assistant + session. + """ + + output: "AssistantOutput" = proto.Field( + proto.MESSAGE, + number=1, + message="AssistantOutput", + ) + state: "AssistantSessionState" = proto.Field( + proto.ENUM, + number=3, + enum="AssistantSessionState", + ) + + +class AssistantSession(proto.Message): + r"""An assistant session represents a conversation between a user + and the assistant agent. + + Attributes: + name (str): + Required. Identifier. The unique identifier of the session. + Format: + ``projects/{project}/locations/{location}/apps/{app}/assistantSessions/{session}`` + requestor (str): + Output only. The user who initiated the + session. + messages (MutableSequence[google.cloud.ces_v1beta.types.AssistantMessage]): + Optional. History of messages in the session. + state (google.cloud.ces_v1beta.types.AssistantSessionState): + Output only. The status of the assistant + session. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the assistant session + was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the assistant session + was last updated. + user_response_suggestions (google.cloud.ces_v1beta.types.UserResponseSuggestions): + Output only. Suggested user responses from + the assistant agent. + display_name (str): + Optional. The display name of the assistant + session. + artifacts (MutableSequence[google.cloud.ces_v1beta.types.AssistantSessionArtifact]): + Output only. Document artifacts (e.g. + generated TDDs in markdown) produced by the + assistant in this session. Pointers only; the + file content lives in the customer's Cloud + Storage bucket. + session_checkpoint (google.cloud.ces_v1beta.types.SessionCheckpoint): + Output only. Session checkpoint containing + user intent and rolling history summary. + active_turn (google.cloud.ces_v1beta.types.ActiveTurnInfo): + Output only. Attachment info for this + session's currently running turn. Unset when no + turn is running. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + requestor: str = proto.Field( + proto.STRING, + number=2, + ) + messages: MutableSequence["AssistantMessage"] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="AssistantMessage", + ) + state: "AssistantSessionState" = proto.Field( + proto.ENUM, + number=4, + enum="AssistantSessionState", + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + user_response_suggestions: "UserResponseSuggestions" = proto.Field( + proto.MESSAGE, + number=7, + message="UserResponseSuggestions", + ) + display_name: str = proto.Field( + proto.STRING, + number=8, + ) + artifacts: MutableSequence["AssistantSessionArtifact"] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message="AssistantSessionArtifact", + ) + session_checkpoint: common.SessionCheckpoint = proto.Field( + proto.MESSAGE, + number=10, + message=common.SessionCheckpoint, + ) + active_turn: "ActiveTurnInfo" = proto.Field( + proto.MESSAGE, + number=11, + message="ActiveTurnInfo", + ) + + +class ActiveTurnInfo(proto.Message): + r"""Live-attachment info for a session turn that is currently + running, disconnected from its client, or parked for pickup by + another server task. + + Attributes: + turn_id (str): + Identifies the turn; echoed by resume + snapshots on the streaming API. + status (google.cloud.ces_v1beta.types.ActiveTurnInfo.Status): + Current attachment status. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the turn started. + last_progress_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the turn last persisted + progress. + orphan_deadline_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the turn will be wound down + if no client attaches. + """ + + class Status(proto.Enum): + r"""How the running turn currently relates to clients and server + tasks. + + Values: + STATUS_UNSPECIFIED (0): + Unspecified. + RUNNING (1): + The turn is executing with at least one + client attached. + DISCONNECTED (2): + The turn is executing with no client + attached. + RESUMING (3): + The turn is parked for pickup: the next + attach continues it. + ABANDONED (4): + The turn's server lease has lapsed and no + task is driving it; the next read seals it to a + committed partial. Not attachable. + """ + + STATUS_UNSPECIFIED = 0 + RUNNING = 1 + DISCONNECTED = 2 + RESUMING = 3 + ABANDONED = 4 + + turn_id: str = proto.Field( + proto.STRING, + number=1, + ) + status: Status = proto.Field( + proto.ENUM, + number=2, + enum=Status, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + last_progress_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + orphan_deadline_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + + +class AssistantSessionArtifact(proto.Message): + r"""A document artifact generated by the assistant within a + session, stored as a file in the customer's Cloud Storage + bucket. + + Attributes: + id (str): + Output only. The unique identifier of the + artifact within the session. + display_name (str): + Output only. The file name shown to the user, e.g. + "hotel_booking_tdd.md". + gcs_uri (str): + Output only. The Cloud Storage object holding the artifact + content. Example: + "gs://{project}-agent-assist-artifacts/agent-assist-generated/1_tdd.md". + mime_type (str): + Output only. The IANA media type of the + artifact content, e.g. "text/markdown". + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the artifact was persisted. + turn_index (int): + Output only. Index of the message in + [AssistantSession.messages] whose turn produced the + artifact, for placing the artifact chip when history is + restored. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + gcs_uri: str = proto.Field( + proto.STRING, + number=3, + ) + mime_type: str = proto.Field( + proto.STRING, + number=4, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + turn_index: int = proto.Field( + proto.INT32, + number=6, + ) + + +class AssistantChunk(proto.Message): + r"""A chunk of data in an assistant message. + + 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: + text (str): + Optional. Text data. + + This field is a member of `oneof`_ ``data``. + thought (str): + Optional. Thought generated by the model. + + This field is a member of `oneof`_ ``data``. + payload (google.protobuf.struct_pb2.Struct): + Optional. Payload which contains structured + responses like the quality report, agent version + name, suggested responses etc. + + This field is a member of `oneof`_ ``data``. + typed_payload (google.cloud.ces_v1beta.types.TypedPayload): + Optional. Typed payload which contains + structured responses. + + This field is a member of `oneof`_ ``data``. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. Timestamp when the chunk was + created or emitted. + """ + + text: str = proto.Field( + proto.STRING, + number=1, + oneof="data", + ) + thought: str = proto.Field( + proto.STRING, + number=2, + oneof="data", + ) + payload: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=3, + oneof="data", + message=struct_pb2.Struct, + ) + typed_payload: "TypedPayload" = proto.Field( + proto.MESSAGE, + number=4, + oneof="data", + message="TypedPayload", + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + + +class AssistantOutput(proto.Message): + r"""The output from the assistant agent. + + Attributes: + message (google.cloud.ces_v1beta.types.AssistantMessage): + Required. The response from the assistant + agent. + user_response_suggestions (google.cloud.ces_v1beta.types.UserResponseSuggestions): + Output only. Suggested user responses from + the assistant agent. + """ + + message: "AssistantMessage" = proto.Field( + proto.MESSAGE, + number=1, + message="AssistantMessage", + ) + user_response_suggestions: "UserResponseSuggestions" = proto.Field( + proto.MESSAGE, + number=2, + message="UserResponseSuggestions", + ) + + +class AssistantMessage(proto.Message): + r"""A message in an assistant session. + + Attributes: + role (str): + Required. Role within the conversation "user" + or "model". + chunks (MutableSequence[google.cloud.ces_v1beta.types.AssistantChunk]): + Optional. Content of the message as chunks. + event_time (google.protobuf.timestamp_pb2.Timestamp): + Required. Timestamp when the message was sent + or received. + attached_gcs_uris (MutableSequence[str]): + Optional. Cloud Storage URIs for files + uploaded by the user during this turn. This + allows attachments to be persisted and rendered + in the session history UI. Example: + "gs://cxas-transient-uploads/uuid/prd.pdf". + """ + + role: str = proto.Field( + proto.STRING, + number=1, + ) + chunks: MutableSequence["AssistantChunk"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="AssistantChunk", + ) + event_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + attached_gcs_uris: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + + +class TypedPayload(proto.Message): + r"""Payload with a type. + + Attributes: + display_name (str): + Required. The display name of the payload. + type_ (str): + Required. The type of the payload. + value (google.protobuf.struct_pb2.Struct): + Required. The value of the payload. + metadata (google.protobuf.struct_pb2.Struct): + Optional. The metadata of the payload. + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + type_: str = proto.Field( + proto.STRING, + number=2, + ) + value: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=3, + message=struct_pb2.Struct, + ) + metadata: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=4, + message=struct_pb2.Struct, + ) + + +class UserResponseSuggestions(proto.Message): + r"""Suggested user responses from the assistant agent. + + Attributes: + suggestions (MutableSequence[str]): + Required. The assistant suggested user + responses. These are suggestions for the user on + how to interact with the assistant. + """ + + suggestions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class ChatAiAssistantRequest(proto.Message): + r"""Request message for + [AssistantService.ChatAiAssistant][google.cloud.ces.v1beta.AssistantService.ChatAiAssistant]. + + Attributes: + app (str): + Required. The app to run assistant for. Format: + ``projects/{project}/locations/{location}/apps/{app}`` + assistant_session (str): + Required. The assistant session to be used to run the + assistant. Format: + ``projects/{project}/locations/{location}/apps/{app}/assistantSessions/{assistant_session}`` + message (str): + Required. The message to send to the + assistant agent. + attached_gcs_uris (MutableSequence[str]): + Optional. Cloud Storage URIs for files + uploaded by the user during this turn. Example: + "gs://cxas-transient-uploads/uuid/prd.pdf". + context_token (str): + Optional. Opaque onboarding context token returned by + [SessionService.GenerateOnboardingSuggestions][google.cloud.ces.v1beta.SessionService.GenerateOnboardingSuggestions]. + When set and still fresh, the server reuses the onboarding + snapshot computed for the zero state instead of recomputing + it for the first conversation turn. + """ + + app: str = proto.Field( + proto.STRING, + number=1, + ) + assistant_session: str = proto.Field( + proto.STRING, + number=2, + ) + message: str = proto.Field( + proto.STRING, + number=3, + ) + attached_gcs_uris: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + context_token: str = proto.Field( + proto.STRING, + number=6, + ) + + +class ChatAiAssistantResponse(proto.Message): + r"""Response message for + [AssistantService.ChatAiAssistant][google.cloud.ces.v1beta.AssistantService.ChatAiAssistant]. + + 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: + text_chunk (str): + Text Token (for streaming Gemini responses + word-by-word) + + This field is a member of `oneof`_ ``event``. + status_message (str): + Simple status update + + This field is a member of `oneof`_ ``event``. + session_checkpoint (google.cloud.ces_v1beta.types.SessionCheckpoint): + Session checkpoint/compaction recap event + containing user intent and rolling summary. + + This field is a member of `oneof`_ ``event``. + event_id (str): + Unique identifier for the event. + event_time (google.protobuf.timestamp_pb2.Timestamp): + Timestamp when the event occurred. + ui_event (google.cloud.ces_v1beta.types.UiEvent): + Optional. UI event payload. + """ + + text_chunk: str = proto.Field( + proto.STRING, + number=3, + oneof="event", + ) + status_message: str = proto.Field( + proto.STRING, + number=4, + oneof="event", + ) + session_checkpoint: common.SessionCheckpoint = proto.Field( + proto.MESSAGE, + number=13, + oneof="event", + message=common.SessionCheckpoint, + ) + event_id: str = proto.Field( + proto.STRING, + number=1, + ) + event_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + ui_event: common.UiEvent = proto.Field( + proto.MESSAGE, + number=5, + message=common.UiEvent, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/common.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/common.py index f50cc1801f50..5463cdcdd19a 100644 --- a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/common.py +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/common.py @@ -34,6 +34,8 @@ "ChannelProfile", "Span", "EvaluationRunCachingSettings", + "UiEvent", + "SessionCheckpoint", }, ) @@ -128,8 +130,32 @@ class ModelSettings(proto.Message): responses that are more creative. This field is a member of `oneof`_ ``_temperature``. + thinking_level (google.cloud.ces_v1beta.types.ModelSettings.ThinkingLevel): + Optional. The thinking level of the model. """ + class ThinkingLevel(proto.Enum): + r"""Thinking level configuration for the model. + + Values: + THINKING_LEVEL_UNSPECIFIED (0): + Thinking level is unspecified. + DEFAULT (1): + Default thinking level. + LOW (2): + Low thinking level. + MEDIUM (3): + Medium thinking level. + HIGH (4): + High thinking level. + """ + + THINKING_LEVEL_UNSPECIFIED = 0 + DEFAULT = 1 + LOW = 2 + MEDIUM = 3 + HIGH = 4 + model: str = proto.Field( proto.STRING, number=1, @@ -139,6 +165,11 @@ class ModelSettings(proto.Message): number=2, optional=True, ) + thinking_level: ThinkingLevel = proto.Field( + proto.ENUM, + number=5, + enum=ThinkingLevel, + ) class TriggerAction(proto.Message): @@ -768,4 +799,43 @@ class EvaluationRunCachingMode(proto.Enum): ) +class UiEvent(proto.Message): + r"""Represents a UI event payload. + + Attributes: + mime_type (str): + The media type (MIME type) indicating the + format of the UI event payload (e.g., + "application/json+a2ui"). + json_payload (str): + The JSON payload representing the A2UI + surface. + """ + + mime_type: str = proto.Field( + proto.STRING, + number=1, + ) + json_payload: str = proto.Field( + proto.STRING, + number=2, + ) + + +class SessionCheckpoint(proto.Message): + r"""Session checkpoint containing inferred user intent for + session title and UI. + + Attributes: + user_intent (str): + Inferred user goal or topic for the session + (e.g. "Building E-Commerce Support Agent"). + """ + + user_intent: str = proto.Field( + proto.STRING, + number=1, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/conversation.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/conversation.py index 1ac6c33352cf..b13a6badd618 100644 --- a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/conversation.py +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/conversation.py @@ -169,6 +169,10 @@ class Turn(proto.Message): root_span (google.cloud.ces_v1beta.types.Span): Optional. The root span of the action processing. + user_intended_text (str): + Optional. The intended ground-truth text from + the Simulated Caller (Polysynth). Only populated + when word error rate metrics are enabled. """ messages: MutableSequence[example.Message] = proto.RepeatedField( @@ -181,6 +185,10 @@ class Turn(proto.Message): number=2, message=common.Span, ) + user_intended_text: str = proto.Field( + proto.STRING, + number=3, + ) name: str = proto.Field( proto.STRING, diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/data_store_tool.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/data_store_tool.py index 93930b783e95..6577d504ff04 100644 --- a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/data_store_tool.py +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/data_store_tool.py @@ -435,6 +435,27 @@ class ControlPoint(proto.Message): message="DataStoreTool.BoostSpec.ConditionBoostSpec", ) + class SnippetsConfig(proto.Message): + r"""Snippets configuration. + + Attributes: + enable_snippets (bool): + Optional. Whether snippets are enabled. + max_snippets (int): + Optional. Number of snippets to return per + query. If unset, returns all snippets from the + service by default. + """ + + enable_snippets: bool = proto.Field( + proto.BOOL, + number=1, + ) + max_snippets: int = proto.Field( + proto.INT32, + number=2, + ) + class ModalityConfig(proto.Message): r"""If specified, will apply the given configuration for the specified modality. @@ -448,6 +469,8 @@ class ModalityConfig(proto.Message): Optional. The summarization config. grounding_config (google.cloud.ces_v1beta.types.DataStoreTool.GroundingConfig): Optional. The grounding configuration. + snippets_config (google.cloud.ces_v1beta.types.DataStoreTool.SnippetsConfig): + Optional. The snippets configuration. """ class ModalityType(proto.Enum): @@ -486,6 +509,11 @@ class ModalityType(proto.Enum): number=4, message="DataStoreTool.GroundingConfig", ) + snippets_config: "DataStoreTool.SnippetsConfig" = proto.Field( + proto.MESSAGE, + number=5, + message="DataStoreTool.SnippetsConfig", + ) data_store_source: DataStoreSource = proto.Field( proto.MESSAGE, diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/deployment.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/deployment.py index 5ea183e92ee6..cd4b0ba64f83 100644 --- a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/deployment.py +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/deployment.py @@ -27,6 +27,7 @@ manifest={ "ExperimentConfig", "Deployment", + "AgentRegistryDeployment", "WhatsAppCredentials", "InstagramCredentials", }, @@ -166,8 +167,42 @@ class Deployment(proto.Message): Optional. Input only. Ephemeral Instagram credentials required when configuring a Instagram channel profile. + model_settings (google.cloud.ces_v1beta.types.ModelSettings): + Optional. Model settings for the deployment. + Overrides model settings configured at the + app/agent levels. Note: Deployment-level model + settings override is gated behind an allowlist. + Contact the CXAS team to enable this field. + modality (google.cloud.ces_v1beta.types.Deployment.Modality): + Optional. The modality of the deployment. + Note: Deployment-level modality override is + gated behind an allowlist. Contact the CXAS team + to enable this field. + agent_registry_deployment (google.cloud.ces_v1beta.types.AgentRegistryDeployment): + Optional. Configuration for deploying this + deployment to Agent Registry. If present, this + deployment will be published to Agent Registry. """ + class Modality(proto.Enum): + r"""The modality of the deployment. + + Values: + MODALITY_UNSPECIFIED (0): + Unknown modality. + MODALITY_TEXT (1): + Text modality. + MODALITY_VOICE (2): + Voice modality. + MODALITY_VIDEO (3): + Video modality. + """ + + MODALITY_UNSPECIFIED = 0 + MODALITY_TEXT = 1 + MODALITY_VOICE = 2 + MODALITY_VIDEO = 3 + name: str = proto.Field( proto.STRING, number=1, @@ -214,6 +249,37 @@ class Deployment(proto.Message): number=11, message="InstagramCredentials", ) + model_settings: common.ModelSettings = proto.Field( + proto.MESSAGE, + number=12, + message=common.ModelSettings, + ) + modality: Modality = proto.Field( + proto.ENUM, + number=13, + enum=Modality, + ) + agent_registry_deployment: "AgentRegistryDeployment" = proto.Field( + proto.MESSAGE, + number=14, + message="AgentRegistryDeployment", + ) + + +class AgentRegistryDeployment(proto.Message): + r"""Configuration and status for Agent Registry deployment. + + Attributes: + agent_registry_service_name (str): + Optional. Output only. The resource name of the deployed + Agent Registry service. Format: + ``projects/{project}/locations/{location}/services/{service}`` + """ + + agent_registry_service_name: str = proto.Field( + proto.STRING, + number=1, + ) class WhatsAppCredentials(proto.Message): @@ -235,7 +301,7 @@ class WhatsAppCredentials(proto.Message): waba_id (str): Required. The WhatsApp Business Account ID. conversation_profile_id (str): - Required. The Conversation Profile ID to use + Optional. The Conversation Profile ID to use for the deployment. """ @@ -273,7 +339,7 @@ class InstagramCredentials(proto.Message): Required. The Meta auth code provided by the embedded signup flow. conversation_profile_id (str): - Required. The Conversation Profile ID to use + Optional. The Conversation Profile ID to use for the deployment. """ diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/evaluation.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/evaluation.py index 6e39545ee621..3bf5995a6961 100644 --- a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/evaluation.py +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/evaluation.py @@ -1119,6 +1119,13 @@ class EvaluationResult(proto.Message): golden_run_method (google.cloud.ces_v1beta.types.GoldenRunMethod): Output only. The method used to run the golden evaluation. + root_span (google.cloud.ces_v1beta.types.Span): + Output only. The root span of the evaluation + execution, which includes information about each + step of the evaluation. + outcome_metadata (google.cloud.ces_v1beta.types.EvaluationResult.OutcomeMetadata): + Output only. The outcome metadata of the evaluation. Only + populated if execution_state is COMPLETE. """ class Outcome(proto.Enum): @@ -1171,6 +1178,20 @@ class ExecutionState(proto.Enum): ERROR = 3 CANCELLED = 4 + class OutcomeMetadata(proto.Enum): + r"""Metadata about the outcome of the evaluation. + + Values: + OUTCOME_METADATA_UNSPECIFIED (0): + Unspecified outcome metadata. + GRACEFUL_HANDOFF (1): + The evaluation resulted in a graceful handoff + to a human representative. + """ + + OUTCOME_METADATA_UNSPECIFIED = 0 + GRACEFUL_HANDOFF = 1 + class GoldenExpectationOutcome(proto.Message): r"""Specifies the expectation and the result of that expectation. @@ -1920,12 +1941,13 @@ class UserGoalSatisfactionResult(proto.Message): Attributes: score (int): Output only. The user task satisfaction - score. Can be -1, 0, 1. + score. Can be -1, 0, 1, 2. This field is a member of `oneof`_ ``_score``. label (str): Output only. The label associated with each - score. Score 1: User Task Satisfied + score. Score 2: Graceful Handoff + Score 1: User Task Satisfied Score 0: User Task Not Satisfied Score -1: User Task Unspecified explanation (str): @@ -2152,6 +2174,16 @@ class TaskCompletionResult(proto.Message): number=19, enum=golden_run.GoldenRunMethod, ) + root_span: common.Span = proto.Field( + proto.MESSAGE, + number=24, + message=common.Span, + ) + outcome_metadata: OutcomeMetadata = proto.Field( + proto.ENUM, + number=25, + enum=OutcomeMetadata, + ) class EvaluationRun(proto.Message): @@ -2923,7 +2955,8 @@ class RunEvaluationRequest(proto.Message): Optional. The display name of the evaluation run. app_version (str): - Optional. The app version to evaluate. Format: + Optional. The app version to evaluate. At most one of + ``app_version`` or ``deployment`` can be set. Format: ``projects/{project}/locations/{location}/apps/{app}/versions/{version}`` config (google.cloud.ces_v1beta.types.EvaluationConfig): Optional. The configuration to use for the diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/example.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/example.py index 105f0c90c00c..802a171c26a5 100644 --- a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/example.py +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/example.py @@ -301,6 +301,8 @@ class Image(proto.Message): - image/webp data (bytes): Required. Raw bytes of the image. + alt_text (str): + Optional. The alternative text for the image. """ mime_type: str = proto.Field( @@ -311,6 +313,10 @@ class Image(proto.Message): proto.BYTES, number=2, ) + alt_text: str = proto.Field( + proto.STRING, + number=4, + ) class ToolCall(proto.Message): @@ -344,6 +350,17 @@ class ToolCall(proto.Message): args (google.protobuf.struct_pb2.Struct): Optional. The input parameters and values for the tool in JSON object format. + parent_tool_call_id (str): + Output only. The id of the tool call that + caused this one, when it was issued by a + sub-agent working on behalf of a parent call. + Empty for top-level calls. Lets a client group a + sub-agent's work under the call that started it + instead of rendering every step as a sibling. + agent_name (str): + Output only. Human-readable name of the agent + that issued this call, e.g. "Contract + Architect". Empty when the root agent issued it. """ tool: str = proto.Field( @@ -370,6 +387,14 @@ class ToolCall(proto.Message): number=3, message=struct_pb2.Struct, ) + parent_tool_call_id: str = proto.Field( + proto.STRING, + number=6, + ) + agent_name: str = proto.Field( + proto.STRING, + number=7, + ) class ToolResponse(proto.Message): @@ -405,6 +430,17 @@ class ToolResponse(proto.Message): details (if any). If "output" and "error" keys are not specified, then whole "response" is treated as tool execution result. + parent_tool_call_id (str): + Output only. The id of the tool call that + caused this one, when it was issued by a + sub-agent working on behalf of a parent call. + Empty for top-level calls. Lets a client group a + sub-agent's work under the call that started it + instead of rendering every step as a sibling. + agent_name (str): + Output only. Human-readable name of the agent + that issued this call, e.g. "Contract + Architect". Empty when the root agent issued it. """ tool: str = proto.Field( @@ -431,6 +467,14 @@ class ToolResponse(proto.Message): number=3, message=struct_pb2.Struct, ) + parent_tool_call_id: str = proto.Field( + proto.STRING, + number=6, + ) + agent_name: str = proto.Field( + proto.STRING, + number=7, + ) class AgentTransfer(proto.Message): diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/guardrail.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/guardrail.py index 0f4b5084bef6..245a7fe2e22b 100644 --- a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/guardrail.py +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/guardrail.py @@ -71,6 +71,11 @@ class Guardrail(proto.Message): the conversation based on the result of the callback execution. + This field is a member of `oneof`_ ``guardrail_type``. + supervisor (google.cloud.ces_v1beta.types.Guardrail.Supervisor): + Optional. Guardrail that runs supervisor + intervention. + This field is a member of `oneof`_ ``guardrail_type``. name (str): Identifier. The unique identifier of the guardrail. Format: @@ -116,6 +121,13 @@ class ContentFilter(proto.Message): disregard_diacritics (bool): Optional. If true, diacritics are ignored during matching. + sensitive_words_exemptions (MutableSequence[str]): + Optional. Entries of the sensitive words list that this + guardrail allows. Only valid when match_type is + SENSITIVE_WORDS. Each value must equal a list entry + (case-insensitive, surrounding whitespace ignored); other + values have no effect. Applies to this guardrail only. At + most 1000 entries of up to 256 characters each. """ class MatchType(proto.Enum): @@ -134,12 +146,20 @@ class MatchType(proto.Enum): REGEXP_MATCH (3): Content is matched using regular expression syntax. + SENSITIVE_WORDS (4): + Content is matched against a system-managed + list of sensitive words and phrases. Attaching a + guardrail with this match type to an app or + agent replaces the default sensitive words + filter for the affected agents; disable the + guardrail to opt out of the default filter. """ MATCH_TYPE_UNSPECIFIED = 0 SIMPLE_STRING_MATCH = 1 WORD_BOUNDARY_STRING_MATCH = 2 REGEXP_MATCH = 3 + SENSITIVE_WORDS = 4 banned_contents: MutableSequence[str] = proto.RepeatedField( proto.STRING, @@ -162,6 +182,10 @@ class MatchType(proto.Enum): proto.BOOL, number=5, ) + sensitive_words_exemptions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) class LlmPromptSecurity(proto.Message): r"""Guardrail that blocks the conversation if the input is @@ -245,7 +269,10 @@ class LlmPolicy(proto.Message): model_settings (google.cloud.ces_v1beta.types.ModelSettings): Optional. Model settings. prompt (str): - Required. Policy prompt. + Required. Policy prompt. Supports session variable + placeholders (``{var}``) as well as + ``{agent_system_instruction}`` to inject the agent's + resolved system instructions. policy_scope (google.cloud.ces_v1beta.types.Guardrail.LlmPolicy.PolicyScope): Required. Defines when to apply the policy check during the conversation. If set to ``POLICY_SCOPE_UNSPECIFIED``, the @@ -341,6 +368,10 @@ class HarmCategory(proto.Enum): HARM_CATEGORY_SEXUALLY_EXPLICIT (4): The harm category is sexually explicit content. + HARM_CATEGORY_PROFANITY (5): + The harm category is profanity. + HARM_CATEGORY_TOXIC (6): + The harm category is toxic. """ HARM_CATEGORY_UNSPECIFIED = 0 @@ -348,6 +379,8 @@ class HarmCategory(proto.Enum): HARM_CATEGORY_DANGEROUS_CONTENT = 2 HARM_CATEGORY_HARASSMENT = 3 HARM_CATEGORY_SEXUALLY_EXPLICIT = 4 + HARM_CATEGORY_PROFANITY = 5 + HARM_CATEGORY_TOXIC = 6 class HarmBlockThreshold(proto.Enum): r"""Probability based thresholds levels for blocking. @@ -476,6 +509,82 @@ class CodeCallback(proto.Message): message=common.Callback, ) + class Supervisor(proto.Message): + r"""Guardrail that runs supervisor intervention. + + Attributes: + type_ (google.cloud.ces_v1beta.types.Guardrail.Supervisor.Type): + Optional. The type of the supervisor. + detection_mode (google.cloud.ces_v1beta.types.Guardrail.Supervisor.DetectionMode): + Optional. The detection mode of the + supervisor. + """ + + class Type(proto.Enum): + r"""Type of supervisor. + + Values: + TYPE_UNSPECIFIED (0): + Type is unspecified. + INVALID_TEXT (1): + Invalid text issue type. + LANGUAGE_SHIFT (2): + Language shift issue type. + SPEAKER_SHIFT (3): + Speaker shift issue type. + AUDIO_MISMATCH (4): + Audio mismatch issue type. + MISSING_TOOL_CALL (5): + Missing tool call issue type. + CUSTOM (6): + Custom issue type. + CHOPPY_AUDIO (7): + Choppy audio issue type. + PROFANITY (8): + Agent profanity issue type. + """ + + TYPE_UNSPECIFIED = 0 + INVALID_TEXT = 1 + LANGUAGE_SHIFT = 2 + SPEAKER_SHIFT = 3 + AUDIO_MISMATCH = 4 + MISSING_TOOL_CALL = 5 + CUSTOM = 6 + CHOPPY_AUDIO = 7 + PROFANITY = 8 + + class DetectionMode(proto.Enum): + r"""Detection mode of the supervisor. + + Values: + DETECTION_MODE_UNSPECIFIED (0): + Detection mode is unspecified. Default to NON_BLOCKING. + NON_BLOCKING (1): + Non blocking detection mode. + Response is not blocked when the supervisor + detection is ongoing. + BLOCKING (2): + Blocking detection mode. + Response is blocked when the supervisor + detection is ongoing. + """ + + DETECTION_MODE_UNSPECIFIED = 0 + NON_BLOCKING = 1 + BLOCKING = 2 + + type_: "Guardrail.Supervisor.Type" = proto.Field( + proto.ENUM, + number=1, + enum="Guardrail.Supervisor.Type", + ) + detection_mode: "Guardrail.Supervisor.DetectionMode" = proto.Field( + proto.ENUM, + number=2, + enum="Guardrail.Supervisor.DetectionMode", + ) + content_filter: ContentFilter = proto.Field( proto.MESSAGE, number=8, @@ -506,6 +615,12 @@ class CodeCallback(proto.Message): oneof="guardrail_type", message=CodeCallback, ) + supervisor: Supervisor = proto.Field( + proto.MESSAGE, + number=16, + oneof="guardrail_type", + message=Supervisor, + ) name: str = proto.Field( proto.STRING, number=1, diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/session_service.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/session_service.py index c6c8e0e78697..55e0bf0eff38 100644 --- a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/session_service.py +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/session_service.py @@ -19,6 +19,8 @@ import google.protobuf.any_pb2 as any_pb2 # type: ignore import google.protobuf.struct_pb2 as struct_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore import proto # type: ignore from google.cloud.ces_v1beta.types import common, example, mocks, search_suggestions @@ -45,6 +47,22 @@ "RunSessionResponse", "BidiSessionClientMessage", "BidiSessionServerMessage", + "StreamChatAiAssistantRequest", + "AssistantSuggestion", + "GenerateOnboardingSuggestionsRequest", + "GenerateOnboardingSuggestionsResponse", + "ArtifactChunk", + "OptionQuestionsChunk", + "AssistantConfirmationRequest", + "AssistantConfirmationResponse", + "OperationCompletedEvent", + "TurnMetadata", + "StreamChatAiAssistantResponse", + "CancelAssistantTurnRequest", + "CancelAssistantTurnResponse", + "TurnResumeSnapshot", + "TurnHandoffEvent", + "TurnCompletedEvent", }, ) @@ -223,13 +241,33 @@ class SessionConfig(proto.Message): agent when the session control is transferred to the remote agent. enable_text_streaming (bool): - Optional. Whether to enable streaming text outputs from the - model. By default, text outputs from the model are collected - before sending to the client. NOTE: This is only supported - for text (non-voice) sessions via + Optional. Whether to stream text output from the model to + the client incrementally as it is generated. Defaults to + ``false``. + + - When disabled, the model's text output is buffered, and + each text output sent to the client is a complete + sentence. Clients can render each text output on a new + line. + - When enabled, each text output may contain only part of a + sentence. Clients should concatenate consecutive text + outputs to render the complete response. + + NOTE: This is only supported for text (non-voice) sessions + using [StreamRunSession][google.cloud.ces.v1beta.SessionService.StreamRunSession] or [BidiRunSession][google.cloud.ces.v1beta.SessionService.BidiRunSession]. + include_llm_thought_summary (bool): + Optional. Whether to include LLM thought + summaries in the session outputs. + exclude_diagnostic_info (bool): + Optional. Whether to exclude diagnostic info + from the session output. + include_progress_update (bool): + Optional. Whether to include intermediate processing update + to the client. If enabled, the update will be sent back in + [SessionOutput.progress][google.cloud.ces.v1beta.SessionOutput.progress]. """ class RemoteDialogflowQueryParameters(proto.Message): @@ -310,6 +348,18 @@ class RemoteDialogflowQueryParameters(proto.Message): proto.BOOL, number=18, ) + include_llm_thought_summary: bool = proto.Field( + proto.BOOL, + number=21, + ) + exclude_diagnostic_info: bool = proto.Field( + proto.BOOL, + number=24, + ) + include_progress_update: bool = proto.Field( + proto.BOOL, + number=28, + ) class ToolCalls(proto.Message): @@ -350,6 +400,9 @@ class Citations(proto.Message): Attributes: cited_chunks (MutableSequence[google.cloud.ces_v1beta.types.Citations.CitedChunk]): List of cited pieces of information. + inline_citations (MutableSequence[google.cloud.ces_v1beta.types.Citations.InlineCitation]): + Optional. List of inline citations in the + agent response. """ class CitedChunk(proto.Message): @@ -384,11 +437,44 @@ class CitedChunk(proto.Message): number=4, ) + class InlineCitation(proto.Message): + r"""An inline citation in the response text. + + Attributes: + start_index (int): + The starting index (in bytes) of the text + segment in the agent response. + end_index (int): + The ending index (in bytes) of the text + segment in the agent response. + cited_chunk_indices (MutableSequence[int]): + The indices of the cited chunks that back this text segment. + Indices refer to the elements in ``cited_chunks``. + """ + + start_index: int = proto.Field( + proto.INT32, + number=1, + ) + end_index: int = proto.Field( + proto.INT32, + number=2, + ) + cited_chunk_indices: MutableSequence[int] = proto.RepeatedField( + proto.INT32, + number=3, + ) + cited_chunks: MutableSequence[CitedChunk] = proto.RepeatedField( proto.MESSAGE, number=1, message=CitedChunk, ) + inline_citations: MutableSequence[InlineCitation] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=InlineCitation, + ) class Event(proto.Message): @@ -397,12 +483,20 @@ class Event(proto.Message): Attributes: event (str): Required. The name of the event. + variables (google.protobuf.struct_pb2.Struct): + Optional. Additional variables associated + with the event. """ event: str = proto.Field( proto.STRING, number=1, ) + variables: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=2, + message=struct_pb2.Struct, + ) class SessionInput(proto.Message): @@ -467,8 +561,57 @@ class SessionInput(proto.Message): NOTE: This field does not apply to audio and DTMF inputs, as they are always processed automatically based on the endpointing signal. + recording_control (google.cloud.ces_v1beta.types.SessionInput.RecordingControl): + Optional. Whether the conversation may be + recorded and logged from here on. + Use this when the app, rather than the agent, + decides what may be kept: + + for example when the end user has to consent to + being recorded before anything about the call + can be stored. + + The value stays in effect until the client sends + a different one, so it only needs to be sent + when the answer changes. Whatever is in effect + when a turn completes decides that turn, both + whether its audio reaches the recording bucket + and whether its transcript reaches conversation + history, BigQuery and Cloud Logging. It covers + the agent's side of the turn as well as the end + user's. + + Turns that complete before the client first + sends this are recorded according to the app's + logging settings, as though the field did not + exist. + + If more than one input in the same request sets + it, the last one wins. """ + class RecordingControl(proto.Enum): + r"""What the app has decided may be recorded and logged. + + This enum is extensible; new values may be added in the future. + + Values: + RECORDING_CONTROL_UNSPECIFIED (0): + The app is not controlling recording. The + app's logging settings decide, as they do for + every session that never sets this field. + RECORDING_ENABLED (1): + The conversation may be recorded and logged + from here on. + RECORDING_DISABLED (2): + The conversation may not be recorded or + logged from here on. + """ + + RECORDING_CONTROL_UNSPECIFIED = 0 + RECORDING_ENABLED = 1 + RECORDING_DISABLED = 2 + text: str = proto.Field( proto.STRING, number=1, @@ -518,6 +661,11 @@ class SessionInput(proto.Message): proto.BOOL, number=8, ) + recording_control: RecordingControl = proto.Field( + proto.ENUM, + number=10, + enum=RecordingControl, + ) class SessionOutput(proto.Message): @@ -562,6 +710,15 @@ class SessionOutput(proto.Message): Custom payload with structured output from the CES agent. + This field is a member of `oneof`_ ``output_type``. + image (google.cloud.ces_v1beta.types.Image): + Output image from the CES agent. + + This field is a member of `oneof`_ ``output_type``. + progress (str): + Intermediate progress update from the CES + agent. + This field is a member of `oneof`_ ``output_type``. turn_index (int): Indicates the sequential order of @@ -646,6 +803,17 @@ class DiagnosticInfo(proto.Message): oneof="output_type", message=struct_pb2.Struct, ) + image: example.Image = proto.Field( + proto.MESSAGE, + number=13, + oneof="output_type", + message=example.Image, + ) + progress: str = proto.Field( + proto.STRING, + number=14, + oneof="output_type", + ) turn_index: int = proto.Field( proto.INT32, number=6, @@ -879,4 +1047,1136 @@ class BidiSessionServerMessage(proto.Message): ) +class StreamChatAiAssistantRequest(proto.Message): + r"""Request message for + [SessionService.StreamChatAiAssistant][google.cloud.ces.v1beta.SessionService.StreamChatAiAssistant]. + + Attributes: + name (str): + Required. The assistant session to be used to run the + assistant. Format: + ``projects/{project}/locations/{location}/apps/{app}/assistantSessions/{assistant_session}`` + message (str): + Optional. The message to send to the assistant agent. May be + empty when ``confirmation_response`` is set (answering a + pending confirmation without adding a new message); at least + one of the two must be provided. + attached_gcs_uris (MutableSequence[str]): + Optional. Cloud Storage URIs for files + uploaded by the user during this turn. Example: + "gs://cxas-transient-uploads/uuid/prd.pdf". + context_token (str): + Optional. Opaque onboarding context token returned by + [SessionService.GenerateOnboardingSuggestions][google.cloud.ces.v1beta.SessionService.GenerateOnboardingSuggestions]. + When set and still fresh, the server reuses the onboarding + snapshot computed for the zero state instead of recomputing + it for the first conversation turn. + confirmation_response (google.cloud.ces_v1beta.types.AssistantConfirmationResponse): + Optional. The user's answer to a pending + [AssistantConfirmationRequest][google.cloud.ces.v1beta.AssistantConfirmationRequest]. + When set, the server resumes the paused agent with this + answer instead of (or in addition to) starting a new prompt + turn. + client_capabilities (MutableSequence[google.cloud.ces_v1beta.types.StreamChatAiAssistantRequest.ClientCapability]): + Optional. Response features this client can render. The + server only emits events that need a capability (e.g. + ``confirmation_request``) when the capability is declared, + so older clients never receive events they would silently + drop. + operation_completed_event (google.cloud.ces_v1beta.types.OperationCompletedEvent): + Optional. Resumes an assistant session paused + waiting for a client-managed long-running + operation to complete. + resume_from_sequence_number (int): + Optional. Optional cursor to resume and + replay events from an in-flight or completed + turn. + attach_only (bool): + Optional. Optional flag to attach to an + existing in-flight turn without submitting a new + message. + """ + + class ClientCapability(proto.Enum): + r"""Response features a client can declare. + + Values: + CLIENT_CAPABILITY_UNSPECIFIED (0): + Unspecified capability; ignored. + CONFIRMATION_CARDS (1): + The client renders + [AssistantConfirmationRequest][google.cloud.ces.v1beta.AssistantConfirmationRequest] + cards and answers them via ``confirmation_response``. + CLIENT_MANAGED_LRO (2): + The client manages long-running operations out-of-band by + polling the operation and sending + ``operation_completed_event`` to resume the turn. If not + declared, the server manages LRO polling and completes the + turn inline. + """ + + CLIENT_CAPABILITY_UNSPECIFIED = 0 + CONFIRMATION_CARDS = 1 + CLIENT_MANAGED_LRO = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + message: str = proto.Field( + proto.STRING, + number=3, + ) + attached_gcs_uris: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + context_token: str = proto.Field( + proto.STRING, + number=6, + ) + confirmation_response: "AssistantConfirmationResponse" = proto.Field( + proto.MESSAGE, + number=7, + message="AssistantConfirmationResponse", + ) + client_capabilities: MutableSequence[ClientCapability] = proto.RepeatedField( + proto.ENUM, + number=8, + enum=ClientCapability, + ) + operation_completed_event: "OperationCompletedEvent" = proto.Field( + proto.MESSAGE, + number=9, + message="OperationCompletedEvent", + ) + resume_from_sequence_number: int = proto.Field( + proto.INT64, + number=11, + ) + attach_only: bool = proto.Field( + proto.BOOL, + number=12, + ) + + +class AssistantSuggestion(proto.Message): + r"""A single personalized onboarding suggestion chip for Arc's + zero state. + + 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: + seed_prompt (str): + Prefill the composer with this text; the user + reviews and sends. + + This field is a member of `oneof`_ ``action``. + load_session (google.cloud.ces_v1beta.types.AssistantSuggestion.LoadSession): + Open an existing assistant session. + + This field is a member of `oneof`_ ``action``. + send_message (str): + Prefill the composer with this text and + submit immediately. Only used for quick-reply + chips inside an active onboarding conversation. + + This field is a member of `oneof`_ ``action``. + suggestion_id (str): + Stable identifier for this suggestion, + round-tripped by clients in interaction logging. + label (str): + Chip label shown to the user (at most 60 + characters). + rationale (str): + Optional short explanation of why this + suggestion is shown (tooltip / rationale + popover). + icon (google.cloud.ces_v1beta.types.AssistantSuggestion.Icon): + Icon hint for the chip. + source (google.cloud.ces_v1beta.types.AssistantSuggestion.Source): + How this suggestion was produced. + candidate_type (str): + Rule-table candidate type in kebab-case (e.g. + "resume-pending-review"), for metrics. + """ + + class Icon(proto.Enum): + r"""Icon hint for the chip. + + Values: + ICON_UNSPECIFIED (0): + Unspecified icon. + RESUME (1): + Resume a previous session. + BUILD (2): + Build something new. + EVALUATE (3): + Evaluation-related suggestion. + DEPLOY (4): + Deployment-related suggestion. + EXPLORE (5): + Exploration / discovery suggestion. + FIX (6): + Fix an error or failing state. + """ + + ICON_UNSPECIFIED = 0 + RESUME = 1 + BUILD = 2 + EVALUATE = 3 + DEPLOY = 4 + EXPLORE = 5 + FIX = 6 + + class Source(proto.Enum): + r"""How this suggestion was produced. + + Values: + SOURCE_UNSPECIFIED (0): + Unspecified source. + RULE (1): + Deterministic rule-table candidate with + template phrasing. + LLM_RANKED (2): + Rule-table candidate re-ranked and phrased by + the LLM phrasing step. + """ + + SOURCE_UNSPECIFIED = 0 + RULE = 1 + LLM_RANKED = 2 + + class LoadSession(proto.Message): + r"""Parameters for the load_session action. + + Attributes: + assistant_session_id (str): + Identifier of the assistant session to open + (the final segment of the AssistantSession + resource name). + """ + + assistant_session_id: str = proto.Field( + proto.STRING, + number=1, + ) + + seed_prompt: str = proto.Field( + proto.STRING, + number=5, + oneof="action", + ) + load_session: LoadSession = proto.Field( + proto.MESSAGE, + number=6, + oneof="action", + message=LoadSession, + ) + send_message: str = proto.Field( + proto.STRING, + number=7, + oneof="action", + ) + suggestion_id: str = proto.Field( + proto.STRING, + number=1, + ) + label: str = proto.Field( + proto.STRING, + number=2, + ) + rationale: str = proto.Field( + proto.STRING, + number=3, + ) + icon: Icon = proto.Field( + proto.ENUM, + number=4, + enum=Icon, + ) + source: Source = proto.Field( + proto.ENUM, + number=8, + enum=Source, + ) + candidate_type: str = proto.Field( + proto.STRING, + number=9, + ) + + +class GenerateOnboardingSuggestionsRequest(proto.Message): + r"""Request message for + [SessionService.GenerateOnboardingSuggestions][google.cloud.ces.v1beta.SessionService.GenerateOnboardingSuggestions]. + + Attributes: + name (str): + Required. The app whose zero state is being rendered. + Format: + ``projects/{project}/locations/{location}/apps/{app}`` + max_suggestions (int): + Optional. Maximum number of suggestions to + return. Defaults to 4 when unset. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + max_suggestions: int = proto.Field( + proto.INT32, + number=2, + ) + + +class GenerateOnboardingSuggestionsResponse(proto.Message): + r"""Response message for + [SessionService.GenerateOnboardingSuggestions][google.cloud.ces.v1beta.SessionService.GenerateOnboardingSuggestions]. + + Attributes: + user_profile (google.cloud.ces_v1beta.types.GenerateOnboardingSuggestionsResponse.UserProfile): + Classification of the requesting user's + history. + suggestions (MutableSequence[google.cloud.ces_v1beta.types.AssistantSuggestion]): + Personalized suggestions, ranked most + relevant first. + context_token (str): + Opaque token capturing the onboarding snapshot used to + generate these suggestions. Clients echo it on the first + [StreamChatAiAssistantRequest][google.cloud.ces.v1beta.StreamChatAiAssistantRequest] + so the server can reuse the snapshot. + """ + + class UserProfile(proto.Enum): + r"""Classification of the requesting user's history with the + assistant in this app. + + Values: + USER_PROFILE_UNSPECIFIED (0): + Unspecified profile. + NEW (1): + No assistant sessions containing messages. + EXPLORING (2): + One or two assistant sessions containing + messages. + RETURNING (3): + More than two assistant sessions containing + messages. + """ + + USER_PROFILE_UNSPECIFIED = 0 + NEW = 1 + EXPLORING = 2 + RETURNING = 3 + + user_profile: UserProfile = proto.Field( + proto.ENUM, + number=1, + enum=UserProfile, + ) + suggestions: MutableSequence["AssistantSuggestion"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="AssistantSuggestion", + ) + context_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ArtifactChunk(proto.Message): + r"""A streamed fragment of a document artifact (e.g. a markdown + TDD) that the assistant is generating. Content deltas stream + while the document is being written so clients can render a live + preview; the FINALIZED chunk carries the GCS URI once the file + has been persisted. + + Attributes: + artifact_id (str): + Identifier of the artifact, stable across all + chunks of one artifact within the stream. + display_name (str): + The file name shown to the user, e.g. + "hotel_booking_tdd.md". Set on STARTED (and repeated on + FINALIZED). + mime_type (str): + The IANA media type of the artifact content, + e.g. "text/markdown". + content_delta (str): + Incremental artifact content. Set on DELTA + chunks. + gcs_uri (str): + The GCS object the artifact was persisted to. + Set on FINALIZED chunks. + state (google.cloud.ces_v1beta.types.ArtifactChunk.State): + Lifecycle position of this chunk. + """ + + class State(proto.Enum): + r"""Lifecycle position of this chunk within the artifact's + stream. + + Values: + STATE_UNSPECIFIED (0): + Unused default. + STARTED (1): + The assistant started generating the + artifact. + DELTA (2): + A content increment; content_delta is set. + FINALIZED (3): + The artifact was persisted; gcs_uri is set. + FAILED (4): + Generation or persistence failed; the + artifact was not saved. + CLOSED (5): + The document finished streaming: its content was fully + delivered via content_delta chunks. Persistence may still + follow; a FINALIZED chunk with a gcs_uri is sent if and when + the artifact is saved. + """ + + STATE_UNSPECIFIED = 0 + STARTED = 1 + DELTA = 2 + FINALIZED = 3 + FAILED = 4 + CLOSED = 5 + + artifact_id: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + mime_type: str = proto.Field( + proto.STRING, + number=3, + ) + content_delta: str = proto.Field( + proto.STRING, + number=4, + ) + gcs_uri: str = proto.Field( + proto.STRING, + number=5, + ) + state: State = proto.Field( + proto.ENUM, + number=6, + enum=State, + ) + + +class OptionQuestionsChunk(proto.Message): + r"""Structured clarification options the assistant asks the user + to choose among, transduced server-side out of the model's turn + (the option block is stripped from the streamed and persisted + text). The console renders a keyboard-navigable option list + docked above the composer. + + Attributes: + questions (MutableSequence[google.cloud.ces_v1beta.types.OptionQuestionsChunk.Question]): + The questions asked this turn. More than one + entry drives the console's "1 of N" pager. + """ + + class Option(proto.Message): + r"""A single selectable option. + + Attributes: + title (str): + Short plain-text option title (no markdown, + no numbering). + details (str): + Optional trade-off details shown as secondary + text. + submit_text (str): + Optional message text to send when the option is chosen; + defaults to ``title`` when empty. + """ + + title: str = proto.Field( + proto.STRING, + number=1, + ) + details: str = proto.Field( + proto.STRING, + number=2, + ) + submit_text: str = proto.Field( + proto.STRING, + number=3, + ) + + class Question(proto.Message): + r"""One question with its options. + + Attributes: + question (str): + The question header text. + options (MutableSequence[google.cloud.ces_v1beta.types.OptionQuestionsChunk.Option]): + The selectable options, in presentation + order. + """ + + question: str = proto.Field( + proto.STRING, + number=1, + ) + options: MutableSequence["OptionQuestionsChunk.Option"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="OptionQuestionsChunk.Option", + ) + + questions: MutableSequence[Question] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Question, + ) + + +class AssistantConfirmationRequest(proto.Message): + r"""A blocking question or confirmation the assistant needs answered + before an agent action can proceed. The requesting agent is paused + and resumes only when the answer arrives on a later + [StreamChatAiAssistantRequest.confirmation_response][google.cloud.ces.v1beta.StreamChatAiAssistantRequest.confirmation_response]. + + Attributes: + confirmation_id (str): + Identifier correlating this request with its + response. Opaque to clients; must be echoed + verbatim on the answering request. + context (str): + Context describing what is being confirmed + (e.g. the action the agent wants to take, or the + question it needs answered). Rendered as plain + text, not Markdown. + positive_label (str): + Label for the approving action of a binary confirmation + (e.g. "Publish"). Unset when ``questions`` is populated. + negative_label (str): + Label for the declining action of a binary confirmation + (e.g. "Not yet"). Unset when ``questions`` is populated. + questions (MutableSequence[google.cloud.ces_v1beta.types.OptionQuestionsChunk.Question]): + Multi-choice form of the confirmation. When populated, the + card renders a selectable option list and the chosen + option's submit_text (or free-form user text) is returned as + [AssistantConfirmationResponse.answer_text][google.cloud.ces.v1beta.AssistantConfirmationResponse.answer_text]. + tool (str): + Name of the tool call the agent paused on (e.g. + "update_app"), for the card header. Unset for pure + questions. + agent_name (str): + Display label of the agent that raised the confirmation + (e.g. ``"Contract Architect"``), for the card header. + expire_time (google.protobuf.timestamp_pb2.Timestamp): + Time after which this confirmation can no + longer be answered. An expired card renders as + inactive, and the server declines the + confirmation on the next turn so the paused + agent does not wait indefinitely. + """ + + confirmation_id: str = proto.Field( + proto.STRING, + number=1, + ) + context: str = proto.Field( + proto.STRING, + number=2, + ) + positive_label: str = proto.Field( + proto.STRING, + number=3, + ) + negative_label: str = proto.Field( + proto.STRING, + number=4, + ) + questions: MutableSequence["OptionQuestionsChunk.Question"] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message="OptionQuestionsChunk.Question", + ) + tool: str = proto.Field( + proto.STRING, + number=6, + ) + agent_name: str = proto.Field( + proto.STRING, + number=7, + ) + expire_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + + +class AssistantConfirmationResponse(proto.Message): + r"""The user's answer to an + [AssistantConfirmationRequest][google.cloud.ces.v1beta.AssistantConfirmationRequest], + sent on the next + [SessionService.StreamChatAiAssistant][google.cloud.ces.v1beta.SessionService.StreamChatAiAssistant] + call to resume the paused agent. + + 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: + confirmed (bool): + Binary answer: true approves the paused + action, false declines it. + + This field is a member of `oneof`_ ``response``. + answer_text (str): + The chosen option's submit_text, or free-form user text. The + paused action is cancelled and the text is handed to the + agent to act on. + + This field is a member of `oneof`_ ``response``. + confirmation_id (str): + The + [AssistantConfirmationRequest.confirmation_id][google.cloud.ces.v1beta.AssistantConfirmationRequest.confirmation_id] + being answered. + """ + + confirmed: bool = proto.Field( + proto.BOOL, + number=2, + oneof="response", + ) + answer_text: str = proto.Field( + proto.STRING, + number=3, + oneof="response", + ) + confirmation_id: str = proto.Field( + proto.STRING, + number=1, + ) + + +class OperationCompletedEvent(proto.Message): + r"""Event sent by the client or background worker to resume an + assistant session after an asynchronous Long-Running Operation + (LRO) completes. + + Attributes: + operation_name (str): + The operation resource name (e.g. ``operations/{op}``). + target_resource_name (str): + The primary resource targeted or produced by + the operation (e.g. evaluation run ID, app ID, + dataset ID). + operation_type (str): + The operation type or tool name (e.g. "run_evaluation", + "copy_app", "export_app"). + status (str): + Status of the operation run (e.g. + "SUCCEEDED", "FAILED", "CANCELLED"). + deduplication_token (str): + Optional deduplication token (e.g. UUID) to + prevent duplicate turn execution from concurrent + browser tabs. + error (google.rpc.status_pb2.Status): + Optional canonical error status if the + operation failed. + metadata (google.protobuf.struct_pb2.Struct): + Optional structured result metadata (e.g. pass_rate, + total_examples, export_uri). + """ + + operation_name: str = proto.Field( + proto.STRING, + number=1, + ) + target_resource_name: str = proto.Field( + proto.STRING, + number=2, + ) + operation_type: str = proto.Field( + proto.STRING, + number=3, + ) + status: str = proto.Field( + proto.STRING, + number=4, + ) + deduplication_token: str = proto.Field( + proto.STRING, + number=5, + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=6, + message=status_pb2.Status, + ) + metadata: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=7, + message=struct_pb2.Struct, + ) + + +class TurnMetadata(proto.Message): + r"""Turn-level metadata and intent categorization. + + Attributes: + contract_related (bool): + Indicates whether this assistant turn was + contract-related (e.g. contract drafting, + alignment, extraction, or revision). + contract_finalized (bool): + Set on the final artifact event of a turn whose contract + draft was published (a revision was activated). Terminal for + the clarification flow of this draft: contract_progress is + authoritative and complete. + contract_streaming_phase (google.cloud.ces_v1beta.types.TurnMetadata.ContractStreamingPhase): + Set only on in-flight progress estimates + emitted while a contract artifact fence is + streaming, and on the revision-turn-start event. + Unset on authoritative payloads. + contract_draft_complete (bool): + Set on the terminal event of a contract draft whose every + placeholder is resolved (contract_progress is 100%), whether + or not the draft was published. Clients complete and dismiss + the contract progress display on it; publication is reported + separately by contract_finalized. + """ + + class ContractStreamingPhase(proto.Enum): + r"""Streaming phase of the contract progress payload. + + Values: + CONTRACT_STREAMING_PHASE_UNSPECIFIED (0): + The payload is authoritative (computed from a + complete contract document, a persisted + snapshot, or the pre-draft state). Clients must + replace any previously received progress with + it. + DRAFTING (1): + An initial contract draft is streaming. contract_progress is + an in-flight estimate: non-decreasing within one artifact + fence, capped below the authoritative range, with + pillar_breakdowns carrying total_item_count == 0 to mark + estimated pillar states. + REVISING (2): + A revision of an existing contract is + streaming (for example after an annotation + submission). Same estimate semantics as + DRAFTING. + """ + + CONTRACT_STREAMING_PHASE_UNSPECIFIED = 0 + DRAFTING = 1 + REVISING = 2 + + contract_related: bool = proto.Field( + proto.BOOL, + number=1, + ) + contract_finalized: bool = proto.Field( + proto.BOOL, + number=3, + ) + contract_streaming_phase: ContractStreamingPhase = proto.Field( + proto.ENUM, + number=4, + enum=ContractStreamingPhase, + ) + contract_draft_complete: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class StreamChatAiAssistantResponse(proto.Message): + r"""Response message for + [SessionService.StreamChatAiAssistant][google.cloud.ces.v1beta.SessionService.StreamChatAiAssistant]. + + 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: + text_chunk (str): + Text Token (for streaming Gemini responses + word-by-word). + + This field is a member of `oneof`_ ``event``. + status (google.rpc.status_pb2.Status): + Simple status update. + + This field is a member of `oneof`_ ``event``. + thought_chunk (str): + Thought text chunk (agent's reasoning before + generating response). + + This field is a member of `oneof`_ ``event``. + tool_call (google.cloud.ces_v1beta.types.ToolCall): + Tool call execution event. + + This field is a member of `oneof`_ ``event``. + tool_response (google.cloud.ces_v1beta.types.ToolResponse): + Tool call response event. + + This field is a member of `oneof`_ ``event``. + artifact_chunk (google.cloud.ces_v1beta.types.ArtifactChunk): + Generated-document artifact event (live + preview deltas + final GCS pointer). + + This field is a member of `oneof`_ ``event``. + option_questions_chunk (google.cloud.ces_v1beta.types.OptionQuestionsChunk): + Structured clarification options parsed out + of the model turn. The console renders these as + a selectable option list instead of raw text. + + This field is a member of `oneof`_ ``event``. + confirmation_request (google.cloud.ces_v1beta.types.AssistantConfirmationRequest): + A blocking confirmation the agent paused on. The agent + resumes when the answer arrives on a later request's + ``confirmation_response``. Only sent to clients that + declared the CONFIRMATION_CARDS capability on the request. + + This field is a member of `oneof`_ ``event``. + session_checkpoint (google.cloud.ces_v1beta.types.SessionCheckpoint): + Session checkpoint/compaction recap event + containing user intent and rolling summary. + + This field is a member of `oneof`_ ``event``. + resume_snapshot (google.cloud.ces_v1beta.types.TurnResumeSnapshot): + A compacted replay of an in-flight turn, sent + as the first event of every attach or resume + before any live event. The client replaces any + locally rendered state for this turn with the + snapshot's contents. + + This field is a member of `oneof`_ ``event``. + handoff (google.cloud.ces_v1beta.types.TurnHandoffEvent): + Tells the client to silently reconnect with + resume_from_sequence_number: the task serving this stream is + going away and the turn will continue elsewhere. Not an + error; the stream completes normally after this event. + + This field is a member of `oneof`_ ``event``. + turn_completed (google.cloud.ces_v1beta.types.TurnCompletedEvent): + The turn has ended. Sent as the last event of + every turn, on the original stream and on every + attached or resumed stream, so clients can end + the turn on an explicit signal instead of + inferring it from stream closure. + + This field is a member of `oneof`_ ``event``. + event_id (str): + Unique identifier for the event. + event_time (google.protobuf.timestamp_pb2.Timestamp): + Timestamp when the event occurred. + ui_event (google.cloud.ces_v1beta.types.UiEvent): + Optional. UI event payload. + turn_metadata (google.cloud.ces_v1beta.types.TurnMetadata): + Optional. Turn-level metadata and intent + categorization. + sequence_number (int): + Optional. Monotonically increasing sequence + number for this session turn. + turn_in_progress (bool): + Optional. Indicates whether the turn is still + actively running in the background. + """ + + text_chunk: str = proto.Field( + proto.STRING, + number=3, + oneof="event", + ) + status: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=4, + oneof="event", + message=status_pb2.Status, + ) + thought_chunk: str = proto.Field( + proto.STRING, + number=6, + oneof="event", + ) + tool_call: example.ToolCall = proto.Field( + proto.MESSAGE, + number=7, + oneof="event", + message=example.ToolCall, + ) + tool_response: example.ToolResponse = proto.Field( + proto.MESSAGE, + number=8, + oneof="event", + message=example.ToolResponse, + ) + artifact_chunk: "ArtifactChunk" = proto.Field( + proto.MESSAGE, + number=9, + oneof="event", + message="ArtifactChunk", + ) + option_questions_chunk: "OptionQuestionsChunk" = proto.Field( + proto.MESSAGE, + number=10, + oneof="event", + message="OptionQuestionsChunk", + ) + confirmation_request: "AssistantConfirmationRequest" = proto.Field( + proto.MESSAGE, + number=12, + oneof="event", + message="AssistantConfirmationRequest", + ) + session_checkpoint: common.SessionCheckpoint = proto.Field( + proto.MESSAGE, + number=13, + oneof="event", + message=common.SessionCheckpoint, + ) + resume_snapshot: "TurnResumeSnapshot" = proto.Field( + proto.MESSAGE, + number=17, + oneof="event", + message="TurnResumeSnapshot", + ) + handoff: "TurnHandoffEvent" = proto.Field( + proto.MESSAGE, + number=18, + oneof="event", + message="TurnHandoffEvent", + ) + turn_completed: "TurnCompletedEvent" = proto.Field( + proto.MESSAGE, + number=19, + oneof="event", + message="TurnCompletedEvent", + ) + event_id: str = proto.Field( + proto.STRING, + number=1, + ) + event_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + ui_event: common.UiEvent = proto.Field( + proto.MESSAGE, + number=5, + message=common.UiEvent, + ) + turn_metadata: "TurnMetadata" = proto.Field( + proto.MESSAGE, + number=11, + message="TurnMetadata", + ) + sequence_number: int = proto.Field( + proto.INT64, + number=15, + ) + turn_in_progress: bool = proto.Field( + proto.BOOL, + number=16, + ) + + +class CancelAssistantTurnRequest(proto.Message): + r"""Request to cancel an assistant session's in-flight turn. + + Attributes: + name (str): + Required. The assistant session whose + in-flight turn to cancel. + turn_id (str): + Optional. The turn to cancel; empty cancels + whichever turn is running. A cancel naming a + turn that is no longer the running one is a + no-op. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + turn_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CancelAssistantTurnResponse(proto.Message): + r"""Response for CancelAssistantTurn. + + Attributes: + cancelled (bool): + Whether an in-flight turn was found and asked + to stop (directly on this task, or through an + epoch preemption for a turn hosted elsewhere). + """ + + cancelled: bool = proto.Field( + proto.BOOL, + number=1, + ) + + +class TurnResumeSnapshot(proto.Message): + r"""A compacted replay of an in-flight turn: everything needed to + render the turn's visible output so far, plus the position live + events continue from. + + Attributes: + turn_id (str): + Identifies the turn being attached to. + resolved_sequence_number (int): + The position this snapshot represents. Live events follow + with sequence_number strictly greater than this. When lower + than the resume_from_sequence_number the client requested, + flushed progress lags what the client already rendered: the + client must discard its rendered content of this turn beyond + this position before applying the snapshot. + events (MutableSequence[google.cloud.ces_v1beta.types.StreamChatAiAssistantResponse]): + Compacted events reconstructing the turn's + visible output, in render order, using the same + event shapes as live streaming. + orphan_deadline_time (google.protobuf.timestamp_pb2.Timestamp): + When the turn will be wound down if no client + remains attached. + """ + + turn_id: str = proto.Field( + proto.STRING, + number=1, + ) + resolved_sequence_number: int = proto.Field( + proto.INT64, + number=2, + ) + events: MutableSequence["StreamChatAiAssistantResponse"] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="StreamChatAiAssistantResponse", + ) + orphan_deadline_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + +class TurnHandoffEvent(proto.Message): + r"""Emitted before this task stops serving the stream mid-turn (e.g. a + server restart). The turn's state is persisted; a reconnect carrying + resume_from_sequence_number continues it on another task. + + Attributes: + turn_id (str): + Identifies the turn to resume. + reason (google.cloud.ces_v1beta.types.TurnHandoffEvent.Reason): + Why the stream is handing off. + """ + + class Reason(proto.Enum): + r"""Why the stream is handing off. + + Values: + REASON_UNSPECIFIED (0): + Unspecified. + SERVER_RESTART (1): + The serving task is shutting down (release + push or rescheduling). + """ + + REASON_UNSPECIFIED = 0 + SERVER_RESTART = 1 + + turn_id: str = proto.Field( + proto.STRING, + number=1, + ) + reason: Reason = proto.Field( + proto.ENUM, + number=2, + enum=Reason, + ) + + +class TurnCompletedEvent(proto.Message): + r"""Terminal event of a turn (see + StreamChatAiAssistantResponse.turn_completed). + + Attributes: + turn_id (str): + Identifier of the turn that ended; matches + TurnResumeSnapshot.turn_id and ActiveTurnInfo.turn_id. + reason (google.cloud.ces_v1beta.types.TurnCompletedEvent.Reason): + Why the turn ended. + final_sequence_number (int): + Sequence number of the last event the turn + produced. A client whose cursor is lower missed + content and should reload the session to see it. + """ + + class Reason(proto.Enum): + r"""Why the turn ended, so a client that attached late can word + the outcome instead of guessing from an empty stream. + + Values: + REASON_UNSPECIFIED (0): + Unspecified. + COMPLETED (1): + The turn ran to completion; the session holds + its committed output. + ABANDONED (2): + No task was driving the turn any more; it was + sealed to a committed partial and cannot be + continued. + RESUME_UNAVAILABLE (3): + This server does not serve attach or resume + for the session, so nothing was tailed; the + client should reload the session instead. + """ + + REASON_UNSPECIFIED = 0 + COMPLETED = 1 + ABANDONED = 2 + RESUME_UNAVAILABLE = 3 + + turn_id: str = proto.Field( + proto.STRING, + number=1, + ) + reason: Reason = proto.Field( + proto.ENUM, + number=2, + enum=Reason, + ) + final_sequence_number: int = proto.Field( + proto.INT64, + number=3, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/tool.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/tool.py index 522f9fc453f4..adcc5162bdd8 100644 --- a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/tool.py +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/tool.py @@ -143,6 +143,10 @@ class Tool(proto.Message): tool_fake_config (google.cloud.ces_v1beta.types.ToolFakeConfig): Optional. Configuration for tool behavior in fake mode. + read_only (bool): + Output only. Indicates whether the tool is + read-only. If true, the tool cannot be modified + by the user. """ client_function: gcc_client_function.ClientFunction = proto.Field( @@ -258,6 +262,10 @@ class Tool(proto.Message): number=20, message=fakes.ToolFakeConfig, ) + read_only: bool = proto.Field( + proto.BOOL, + number=29, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_guardrail_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_guardrail_async.py index 0b7a9e1bc48f..e881fb19ebf2 100644 --- a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_guardrail_async.py +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_guardrail_async.py @@ -40,7 +40,7 @@ async def sample_create_guardrail(): # Initialize request argument(s) guardrail = ces_v1beta.Guardrail() - guardrail.content_filter.match_type = "REGEXP_MATCH" + guardrail.content_filter.match_type = "SENSITIVE_WORDS" guardrail.display_name = "display_name_value" request = ces_v1beta.CreateGuardrailRequest( diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_guardrail_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_guardrail_sync.py index ffc096fd2be6..7293cde92cba 100644 --- a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_guardrail_sync.py +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_guardrail_sync.py @@ -40,7 +40,7 @@ def sample_create_guardrail(): # Initialize request argument(s) guardrail = ces_v1beta.Guardrail() - guardrail.content_filter.match_type = "REGEXP_MATCH" + guardrail.content_filter.match_type = "SENSITIVE_WORDS" guardrail.display_name = "display_name_value" request = ces_v1beta.CreateGuardrailRequest( diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_import_app_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_import_app_async.py index 6b1d45ce8a26..8ab9107a5a6a 100644 --- a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_import_app_async.py +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_import_app_async.py @@ -41,6 +41,7 @@ async def sample_import_app(): # Initialize request argument(s) request = ces_v1beta.ImportAppRequest( gcs_uri="gcs_uri_value", + json_patch_content="json_patch_content_value", parent="parent_value", ) diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_import_app_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_import_app_sync.py index 531c86aabec8..db417c08bedd 100644 --- a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_import_app_sync.py +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_import_app_sync.py @@ -41,6 +41,7 @@ def sample_import_app(): # Initialize request argument(s) request = ces_v1beta.ImportAppRequest( gcs_uri="gcs_uri_value", + json_patch_content="json_patch_content_value", parent="parent_value", ) diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_app_version_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_app_version_async.py new file mode 100644 index 000000000000..a1128a064f29 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_app_version_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 UpdateAppVersion +# 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-ces + + +# [START ces_v1beta_generated_AgentService_UpdateAppVersion_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 ces_v1beta + + +async def sample_update_app_version(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.UpdateAppVersionRequest() + + # Make the request + response = await client.update_app_version(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_UpdateAppVersion_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_app_version_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_app_version_sync.py new file mode 100644 index 000000000000..034dc7cee018 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_app_version_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 UpdateAppVersion +# 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-ces + + +# [START ces_v1beta_generated_AgentService_UpdateAppVersion_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 ces_v1beta + + +def sample_update_app_version(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.UpdateAppVersionRequest() + + # Make the request + response = client.update_app_version(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_UpdateAppVersion_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_guardrail_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_guardrail_async.py index 496efb1b6b86..294b62d9887d 100644 --- a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_guardrail_async.py +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_guardrail_async.py @@ -40,7 +40,7 @@ async def sample_update_guardrail(): # Initialize request argument(s) guardrail = ces_v1beta.Guardrail() - guardrail.content_filter.match_type = "REGEXP_MATCH" + guardrail.content_filter.match_type = "SENSITIVE_WORDS" guardrail.display_name = "display_name_value" request = ces_v1beta.UpdateGuardrailRequest( diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_guardrail_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_guardrail_sync.py index bebdc6715b21..932950500a38 100644 --- a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_guardrail_sync.py +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_guardrail_sync.py @@ -40,7 +40,7 @@ def sample_update_guardrail(): # Initialize request argument(s) guardrail = ces_v1beta.Guardrail() - guardrail.content_filter.match_type = "REGEXP_MATCH" + guardrail.content_filter.match_type = "SENSITIVE_WORDS" guardrail.display_name = "display_name_value" request = ces_v1beta.UpdateGuardrailRequest( diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_chat_ai_assistant_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_chat_ai_assistant_async.py new file mode 100644 index 000000000000..410e1782555b --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_chat_ai_assistant_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 ChatAiAssistant +# 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-ces + + +# [START ces_v1beta_generated_AssistantService_ChatAiAssistant_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 ces_v1beta + + +async def sample_chat_ai_assistant(): + # Create a client + client = ces_v1beta.AssistantServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ChatAiAssistantRequest( + app="app_value", + assistant_session="assistant_session_value", + message="message_value", + ) + + # Make the request + response = await client.chat_ai_assistant(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AssistantService_ChatAiAssistant_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_chat_ai_assistant_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_chat_ai_assistant_sync.py new file mode 100644 index 000000000000..5d4d69b77ec1 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_chat_ai_assistant_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 ChatAiAssistant +# 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-ces + + +# [START ces_v1beta_generated_AssistantService_ChatAiAssistant_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 ces_v1beta + + +def sample_chat_ai_assistant(): + # Create a client + client = ces_v1beta.AssistantServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ChatAiAssistantRequest( + app="app_value", + assistant_session="assistant_session_value", + message="message_value", + ) + + # Make the request + response = client.chat_ai_assistant(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AssistantService_ChatAiAssistant_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_create_assistant_session_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_create_assistant_session_async.py new file mode 100644 index 000000000000..e8c222d61c7e --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_create_assistant_session_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 CreateAssistantSession +# 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-ces + + +# [START ces_v1beta_generated_AssistantService_CreateAssistantSession_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 ces_v1beta + + +async def sample_create_assistant_session(): + # Create a client + client = ces_v1beta.AssistantServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.CreateAssistantSessionRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_assistant_session(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AssistantService_CreateAssistantSession_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_create_assistant_session_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_create_assistant_session_sync.py new file mode 100644 index 000000000000..d5ec07a59841 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_create_assistant_session_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 CreateAssistantSession +# 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-ces + + +# [START ces_v1beta_generated_AssistantService_CreateAssistantSession_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 ces_v1beta + + +def sample_create_assistant_session(): + # Create a client + client = ces_v1beta.AssistantServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.CreateAssistantSessionRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_assistant_session(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AssistantService_CreateAssistantSession_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_delete_assistant_session_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_delete_assistant_session_async.py new file mode 100644 index 000000000000..dc11b038e313 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_delete_assistant_session_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 DeleteAssistantSession +# 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-ces + + +# [START ces_v1beta_generated_AssistantService_DeleteAssistantSession_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 ces_v1beta + + +async def sample_delete_assistant_session(): + # Create a client + client = ces_v1beta.AssistantServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteAssistantSessionRequest( + name="name_value", + ) + + # Make the request + await client.delete_assistant_session(request=request) + + +# [END ces_v1beta_generated_AssistantService_DeleteAssistantSession_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_delete_assistant_session_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_delete_assistant_session_sync.py new file mode 100644 index 000000000000..b8d5cd05b20b --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_delete_assistant_session_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 DeleteAssistantSession +# 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-ces + + +# [START ces_v1beta_generated_AssistantService_DeleteAssistantSession_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 ces_v1beta + + +def sample_delete_assistant_session(): + # Create a client + client = ces_v1beta.AssistantServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteAssistantSessionRequest( + name="name_value", + ) + + # Make the request + client.delete_assistant_session(request=request) + + +# [END ces_v1beta_generated_AssistantService_DeleteAssistantSession_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_get_assistant_session_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_get_assistant_session_async.py new file mode 100644 index 000000000000..11c752bac38a --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_get_assistant_session_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 GetAssistantSession +# 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-ces + + +# [START ces_v1beta_generated_AssistantService_GetAssistantSession_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 ces_v1beta + + +async def sample_get_assistant_session(): + # Create a client + client = ces_v1beta.AssistantServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GetAssistantSessionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_assistant_session(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AssistantService_GetAssistantSession_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_get_assistant_session_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_get_assistant_session_sync.py new file mode 100644 index 000000000000..cac691c02c4f --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_get_assistant_session_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 GetAssistantSession +# 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-ces + + +# [START ces_v1beta_generated_AssistantService_GetAssistantSession_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 ces_v1beta + + +def sample_get_assistant_session(): + # Create a client + client = ces_v1beta.AssistantServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GetAssistantSessionRequest( + name="name_value", + ) + + # Make the request + response = client.get_assistant_session(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AssistantService_GetAssistantSession_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_list_assistant_sessions_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_list_assistant_sessions_async.py new file mode 100644 index 000000000000..f71bf58273dd --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_list_assistant_sessions_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 ListAssistantSessions +# 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-ces + + +# [START ces_v1beta_generated_AssistantService_ListAssistantSessions_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 ces_v1beta + + +async def sample_list_assistant_sessions(): + # Create a client + client = ces_v1beta.AssistantServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ListAssistantSessionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assistant_sessions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END ces_v1beta_generated_AssistantService_ListAssistantSessions_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_list_assistant_sessions_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_list_assistant_sessions_sync.py new file mode 100644 index 000000000000..175f8f3a69b3 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_list_assistant_sessions_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 ListAssistantSessions +# 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-ces + + +# [START ces_v1beta_generated_AssistantService_ListAssistantSessions_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 ces_v1beta + + +def sample_list_assistant_sessions(): + # Create a client + client = ces_v1beta.AssistantServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ListAssistantSessionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assistant_sessions(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END ces_v1beta_generated_AssistantService_ListAssistantSessions_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_run_assistant_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_run_assistant_async.py new file mode 100644 index 000000000000..ee62088d6d25 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_run_assistant_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 RunAssistant +# 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-ces + + +# [START ces_v1beta_generated_AssistantService_RunAssistant_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 ces_v1beta + + +async def sample_run_assistant(): + # Create a client + client = ces_v1beta.AssistantServiceAsyncClient() + + # Initialize request argument(s) + message = ces_v1beta.AssistantMessage() + message.role = "role_value" + + request = ces_v1beta.RunAssistantRequest( + app="app_value", + assistant_session="assistant_session_value", + message=message, + ) + + # Make the request + response = await client.run_assistant(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AssistantService_RunAssistant_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_run_assistant_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_run_assistant_sync.py new file mode 100644 index 000000000000..909d010ba427 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_assistant_service_run_assistant_sync.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 RunAssistant +# 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-ces + + +# [START ces_v1beta_generated_AssistantService_RunAssistant_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 ces_v1beta + + +def sample_run_assistant(): + # Create a client + client = ces_v1beta.AssistantServiceClient() + + # Initialize request argument(s) + message = ces_v1beta.AssistantMessage() + message.role = "role_value" + + request = ces_v1beta.RunAssistantRequest( + app="app_value", + assistant_session="assistant_session_value", + message=message, + ) + + # Make the request + response = client.run_assistant(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AssistantService_RunAssistant_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_session_service_cancel_assistant_turn_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_session_service_cancel_assistant_turn_async.py new file mode 100644 index 000000000000..175a0c1153bf --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_session_service_cancel_assistant_turn_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 CancelAssistantTurn +# 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-ces + + +# [START ces_v1beta_generated_SessionService_CancelAssistantTurn_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 ces_v1beta + + +async def sample_cancel_assistant_turn(): + # Create a client + client = ces_v1beta.SessionServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.CancelAssistantTurnRequest( + name="name_value", + ) + + # Make the request + response = await client.cancel_assistant_turn(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_SessionService_CancelAssistantTurn_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_session_service_cancel_assistant_turn_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_session_service_cancel_assistant_turn_sync.py new file mode 100644 index 000000000000..47cf4cd45ec7 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_session_service_cancel_assistant_turn_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 CancelAssistantTurn +# 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-ces + + +# [START ces_v1beta_generated_SessionService_CancelAssistantTurn_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 ces_v1beta + + +def sample_cancel_assistant_turn(): + # Create a client + client = ces_v1beta.SessionServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.CancelAssistantTurnRequest( + name="name_value", + ) + + # Make the request + response = client.cancel_assistant_turn(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_SessionService_CancelAssistantTurn_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_session_service_generate_onboarding_suggestions_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_session_service_generate_onboarding_suggestions_async.py new file mode 100644 index 000000000000..44f938b727f1 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_session_service_generate_onboarding_suggestions_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 GenerateOnboardingSuggestions +# 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-ces + + +# [START ces_v1beta_generated_SessionService_GenerateOnboardingSuggestions_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 ces_v1beta + + +async def sample_generate_onboarding_suggestions(): + # Create a client + client = ces_v1beta.SessionServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GenerateOnboardingSuggestionsRequest( + name="name_value", + ) + + # Make the request + response = await client.generate_onboarding_suggestions(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_SessionService_GenerateOnboardingSuggestions_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_session_service_generate_onboarding_suggestions_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_session_service_generate_onboarding_suggestions_sync.py new file mode 100644 index 000000000000..e98033fa0c30 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_session_service_generate_onboarding_suggestions_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 GenerateOnboardingSuggestions +# 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-ces + + +# [START ces_v1beta_generated_SessionService_GenerateOnboardingSuggestions_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 ces_v1beta + + +def sample_generate_onboarding_suggestions(): + # Create a client + client = ces_v1beta.SessionServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GenerateOnboardingSuggestionsRequest( + name="name_value", + ) + + # Make the request + response = client.generate_onboarding_suggestions(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_SessionService_GenerateOnboardingSuggestions_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_session_service_stream_chat_ai_assistant_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_session_service_stream_chat_ai_assistant_async.py new file mode 100644 index 000000000000..c02a447b7898 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_session_service_stream_chat_ai_assistant_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 StreamChatAiAssistant +# 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-ces + + +# [START ces_v1beta_generated_SessionService_StreamChatAiAssistant_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 ces_v1beta + + +async def sample_stream_chat_ai_assistant(): + # Create a client + client = ces_v1beta.SessionServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.StreamChatAiAssistantRequest( + name="name_value", + ) + + # Make the request + stream = await client.stream_chat_ai_assistant(request=request) + + # Handle the response + async for response in stream: + print(response) + + +# [END ces_v1beta_generated_SessionService_StreamChatAiAssistant_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_session_service_stream_chat_ai_assistant_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_session_service_stream_chat_ai_assistant_sync.py new file mode 100644 index 000000000000..27ac5fe76e6b --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_session_service_stream_chat_ai_assistant_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 StreamChatAiAssistant +# 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-ces + + +# [START ces_v1beta_generated_SessionService_StreamChatAiAssistant_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 ces_v1beta + + +def sample_stream_chat_ai_assistant(): + # Create a client + client = ces_v1beta.SessionServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.StreamChatAiAssistantRequest( + name="name_value", + ) + + # Make the request + stream = client.stream_chat_ai_assistant(request=request) + + # Handle the response + for response in stream: + print(response) + + +# [END ces_v1beta_generated_SessionService_StreamChatAiAssistant_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/snippet_metadata_google.cloud.ces.v1beta.json b/packages/google-cloud-ces/samples/generated_samples/snippet_metadata_google.cloud.ces.v1beta.json index 72cc9c1f40b1..1caa642a73e5 100644 --- a/packages/google-cloud-ces/samples/generated_samples/snippet_metadata_google.cloud.ces.v1beta.json +++ b/packages/google-cloud-ces/samples/generated_samples/snippet_metadata_google.cloud.ces.v1beta.json @@ -5139,12 +5139,12 @@ "regionTag": "ces_v1beta_generated_AgentService_ImportApp_async", "segments": [ { - "end": 56, + "end": 57, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 57, "start": 27, "type": "SHORT" }, @@ -5154,18 +5154,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "end": 54, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 58, + "start": 55, "type": "RESPONSE_HANDLING" } ], @@ -5227,12 +5227,12 @@ "regionTag": "ces_v1beta_generated_AgentService_ImportApp_sync", "segments": [ { - "end": 56, + "end": 57, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 57, "start": 27, "type": "SHORT" }, @@ -5242,18 +5242,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "end": 54, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 58, + "start": 55, "type": "RESPONSE_HANDLING" } ], @@ -7199,6 +7199,175 @@ ], "title": "ces_v1beta_generated_agent_service_update_agent_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.update_app_version", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.UpdateAppVersion", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "UpdateAppVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.UpdateAppVersionRequest" + }, + { + "name": "app_version", + "type": "google.cloud.ces_v1beta.types.AppVersion" + }, + { + "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, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.AppVersion", + "shortName": "update_app_version" + }, + "description": "Sample for UpdateAppVersion", + "file": "ces_v1beta_generated_agent_service_update_app_version_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_UpdateAppVersion_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": "ces_v1beta_generated_agent_service_update_app_version_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.update_app_version", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.UpdateAppVersion", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "UpdateAppVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.UpdateAppVersionRequest" + }, + { + "name": "app_version", + "type": "google.cloud.ces_v1beta.types.AppVersion" + }, + { + "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, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.AppVersion", + "shortName": "update_app_version" + }, + "description": "Sample for UpdateAppVersion", + "file": "ces_v1beta_generated_agent_service_update_app_version_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_UpdateAppVersion_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": "ces_v1beta_generated_agent_service_update_app_version_sync.py" + }, { "canonical": true, "clientMethod": { @@ -8387,34 +8556,22 @@ "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", - "shortName": "EvaluationServiceAsyncClient" + "fullName": "google.cloud.ces_v1beta.AssistantServiceAsyncClient", + "shortName": "AssistantServiceAsyncClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.create_evaluation_dataset", + "fullName": "google.cloud.ces_v1beta.AssistantServiceAsyncClient.chat_ai_assistant", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.CreateEvaluationDataset", + "fullName": "google.cloud.ces.v1beta.AssistantService.ChatAiAssistant", "service": { - "fullName": "google.cloud.ces.v1beta.EvaluationService", - "shortName": "EvaluationService" + "fullName": "google.cloud.ces.v1beta.AssistantService", + "shortName": "AssistantService" }, - "shortName": "CreateEvaluationDataset" + "shortName": "ChatAiAssistant" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.CreateEvaluationDatasetRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "evaluation_dataset", - "type": "google.cloud.ces_v1beta.types.EvaluationDataset" - }, - { - "name": "evaluation_dataset_id", - "type": "str" + "type": "google.cloud.ces_v1beta.types.ChatAiAssistantRequest" }, { "name": "retry", @@ -8429,22 +8586,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.types.EvaluationDataset", - "shortName": "create_evaluation_dataset" + "resultType": "google.cloud.ces_v1beta.types.ChatAiAssistantResponse", + "shortName": "chat_ai_assistant" }, - "description": "Sample for CreateEvaluationDataset", - "file": "ces_v1beta_generated_evaluation_service_create_evaluation_dataset_async.py", + "description": "Sample for ChatAiAssistant", + "file": "ces_v1beta_generated_assistant_service_chat_ai_assistant_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_CreateEvaluationDataset_async", + "regionTag": "ces_v1beta_generated_AssistantService_ChatAiAssistant_async", "segments": [ { - "end": 55, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 53, "start": 27, "type": "SHORT" }, @@ -8454,55 +8611,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_create_evaluation_dataset_async.py" + "title": "ces_v1beta_generated_assistant_service_chat_ai_assistant_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", - "shortName": "EvaluationServiceClient" + "fullName": "google.cloud.ces_v1beta.AssistantServiceClient", + "shortName": "AssistantServiceClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.create_evaluation_dataset", + "fullName": "google.cloud.ces_v1beta.AssistantServiceClient.chat_ai_assistant", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.CreateEvaluationDataset", + "fullName": "google.cloud.ces.v1beta.AssistantService.ChatAiAssistant", "service": { - "fullName": "google.cloud.ces.v1beta.EvaluationService", - "shortName": "EvaluationService" + "fullName": "google.cloud.ces.v1beta.AssistantService", + "shortName": "AssistantService" }, - "shortName": "CreateEvaluationDataset" + "shortName": "ChatAiAssistant" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.CreateEvaluationDatasetRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "evaluation_dataset", - "type": "google.cloud.ces_v1beta.types.EvaluationDataset" - }, - { - "name": "evaluation_dataset_id", - "type": "str" + "type": "google.cloud.ces_v1beta.types.ChatAiAssistantRequest" }, { "name": "retry", @@ -8517,22 +8662,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.types.EvaluationDataset", - "shortName": "create_evaluation_dataset" + "resultType": "google.cloud.ces_v1beta.types.ChatAiAssistantResponse", + "shortName": "chat_ai_assistant" }, - "description": "Sample for CreateEvaluationDataset", - "file": "ces_v1beta_generated_evaluation_service_create_evaluation_dataset_sync.py", + "description": "Sample for ChatAiAssistant", + "file": "ces_v1beta_generated_assistant_service_chat_ai_assistant_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_CreateEvaluationDataset_sync", + "regionTag": "ces_v1beta_generated_AssistantService_ChatAiAssistant_sync", "segments": [ { - "end": 55, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 53, "start": 27, "type": "SHORT" }, @@ -8542,55 +8687,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_create_evaluation_dataset_sync.py" + "title": "ces_v1beta_generated_assistant_service_chat_ai_assistant_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", - "shortName": "EvaluationServiceAsyncClient" + "fullName": "google.cloud.ces_v1beta.AssistantServiceAsyncClient", + "shortName": "AssistantServiceAsyncClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.create_evaluation_expectation", + "fullName": "google.cloud.ces_v1beta.AssistantServiceAsyncClient.create_assistant_session", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.CreateEvaluationExpectation", + "fullName": "google.cloud.ces.v1beta.AssistantService.CreateAssistantSession", "service": { - "fullName": "google.cloud.ces.v1beta.EvaluationService", - "shortName": "EvaluationService" + "fullName": "google.cloud.ces.v1beta.AssistantService", + "shortName": "AssistantService" }, - "shortName": "CreateEvaluationExpectation" + "shortName": "CreateAssistantSession" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.CreateEvaluationExpectationRequest" + "type": "google.cloud.ces_v1beta.types.CreateAssistantSessionRequest" }, { "name": "parent", "type": "str" }, { - "name": "evaluation_expectation", - "type": "google.cloud.ces_v1beta.types.EvaluationExpectation" - }, - { - "name": "evaluation_expectation_id", + "name": "assistant_session_id", "type": "str" }, { @@ -8606,22 +8747,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.types.EvaluationExpectation", - "shortName": "create_evaluation_expectation" + "resultType": "google.cloud.ces_v1beta.types.AssistantSession", + "shortName": "create_assistant_session" }, - "description": "Sample for CreateEvaluationExpectation", - "file": "ces_v1beta_generated_evaluation_service_create_evaluation_expectation_async.py", + "description": "Sample for CreateAssistantSession", + "file": "ces_v1beta_generated_assistant_service_create_assistant_session_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_CreateEvaluationExpectation_async", + "regionTag": "ces_v1beta_generated_AssistantService_CreateAssistantSession_async", "segments": [ { - "end": 56, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 51, "start": 27, "type": "SHORT" }, @@ -8631,54 +8772,50 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 51, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_create_evaluation_expectation_async.py" + "title": "ces_v1beta_generated_assistant_service_create_assistant_session_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", - "shortName": "EvaluationServiceClient" + "fullName": "google.cloud.ces_v1beta.AssistantServiceClient", + "shortName": "AssistantServiceClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.create_evaluation_expectation", + "fullName": "google.cloud.ces_v1beta.AssistantServiceClient.create_assistant_session", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.CreateEvaluationExpectation", + "fullName": "google.cloud.ces.v1beta.AssistantService.CreateAssistantSession", "service": { - "fullName": "google.cloud.ces.v1beta.EvaluationService", - "shortName": "EvaluationService" + "fullName": "google.cloud.ces.v1beta.AssistantService", + "shortName": "AssistantService" }, - "shortName": "CreateEvaluationExpectation" + "shortName": "CreateAssistantSession" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.CreateEvaluationExpectationRequest" + "type": "google.cloud.ces_v1beta.types.CreateAssistantSessionRequest" }, { "name": "parent", "type": "str" }, { - "name": "evaluation_expectation", - "type": "google.cloud.ces_v1beta.types.EvaluationExpectation" - }, - { - "name": "evaluation_expectation_id", + "name": "assistant_session_id", "type": "str" }, { @@ -8694,22 +8831,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.types.EvaluationExpectation", - "shortName": "create_evaluation_expectation" + "resultType": "google.cloud.ces_v1beta.types.AssistantSession", + "shortName": "create_assistant_session" }, - "description": "Sample for CreateEvaluationExpectation", - "file": "ces_v1beta_generated_evaluation_service_create_evaluation_expectation_sync.py", + "description": "Sample for CreateAssistantSession", + "file": "ces_v1beta_generated_assistant_service_create_assistant_session_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_CreateEvaluationExpectation_sync", + "regionTag": "ces_v1beta_generated_AssistantService_CreateAssistantSession_sync", "segments": [ { - "end": 56, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 51, "start": 27, "type": "SHORT" }, @@ -8719,55 +8856,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 51, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_create_evaluation_expectation_sync.py" + "title": "ces_v1beta_generated_assistant_service_create_assistant_session_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", - "shortName": "EvaluationServiceAsyncClient" + "fullName": "google.cloud.ces_v1beta.AssistantServiceAsyncClient", + "shortName": "AssistantServiceAsyncClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.create_evaluation", + "fullName": "google.cloud.ces_v1beta.AssistantServiceAsyncClient.delete_assistant_session", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.CreateEvaluation", + "fullName": "google.cloud.ces.v1beta.AssistantService.DeleteAssistantSession", "service": { - "fullName": "google.cloud.ces.v1beta.EvaluationService", - "shortName": "EvaluationService" + "fullName": "google.cloud.ces.v1beta.AssistantService", + "shortName": "AssistantService" }, - "shortName": "CreateEvaluation" + "shortName": "DeleteAssistantSession" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.CreateEvaluationRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "evaluation", - "type": "google.cloud.ces_v1beta.types.Evaluation" + "type": "google.cloud.ces_v1beta.types.DeleteAssistantSessionRequest" }, { - "name": "evaluation_id", + "name": "name", "type": "str" }, { @@ -8783,22 +8912,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.types.Evaluation", - "shortName": "create_evaluation" + "shortName": "delete_assistant_session" }, - "description": "Sample for CreateEvaluation", - "file": "ces_v1beta_generated_evaluation_service_create_evaluation_async.py", + "description": "Sample for DeleteAssistantSession", + "file": "ces_v1beta_generated_assistant_service_delete_assistant_session_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_CreateEvaluation_async", + "regionTag": "ces_v1beta_generated_AssistantService_DeleteAssistantSession_async", "segments": [ { - "end": 56, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 49, "start": 27, "type": "SHORT" }, @@ -8808,54 +8936,44 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 51, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_create_evaluation_async.py" + "title": "ces_v1beta_generated_assistant_service_delete_assistant_session_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", - "shortName": "EvaluationServiceClient" + "fullName": "google.cloud.ces_v1beta.AssistantServiceClient", + "shortName": "AssistantServiceClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.create_evaluation", + "fullName": "google.cloud.ces_v1beta.AssistantServiceClient.delete_assistant_session", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.CreateEvaluation", + "fullName": "google.cloud.ces.v1beta.AssistantService.DeleteAssistantSession", "service": { - "fullName": "google.cloud.ces.v1beta.EvaluationService", - "shortName": "EvaluationService" + "fullName": "google.cloud.ces.v1beta.AssistantService", + "shortName": "AssistantService" }, - "shortName": "CreateEvaluation" + "shortName": "DeleteAssistantSession" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.CreateEvaluationRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "evaluation", - "type": "google.cloud.ces_v1beta.types.Evaluation" + "type": "google.cloud.ces_v1beta.types.DeleteAssistantSessionRequest" }, { - "name": "evaluation_id", + "name": "name", "type": "str" }, { @@ -8871,22 +8989,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.types.Evaluation", - "shortName": "create_evaluation" + "shortName": "delete_assistant_session" }, - "description": "Sample for CreateEvaluation", - "file": "ces_v1beta_generated_evaluation_service_create_evaluation_sync.py", + "description": "Sample for DeleteAssistantSession", + "file": "ces_v1beta_generated_assistant_service_delete_assistant_session_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_CreateEvaluation_sync", + "regionTag": "ces_v1beta_generated_AssistantService_DeleteAssistantSession_sync", "segments": [ { - "end": 56, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 49, "start": 27, "type": "SHORT" }, @@ -8896,55 +9013,45 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 51, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_create_evaluation_sync.py" + "title": "ces_v1beta_generated_assistant_service_delete_assistant_session_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", - "shortName": "EvaluationServiceAsyncClient" + "fullName": "google.cloud.ces_v1beta.AssistantServiceAsyncClient", + "shortName": "AssistantServiceAsyncClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.create_scheduled_evaluation_run", + "fullName": "google.cloud.ces_v1beta.AssistantServiceAsyncClient.get_assistant_session", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.CreateScheduledEvaluationRun", + "fullName": "google.cloud.ces.v1beta.AssistantService.GetAssistantSession", "service": { - "fullName": "google.cloud.ces.v1beta.EvaluationService", - "shortName": "EvaluationService" + "fullName": "google.cloud.ces.v1beta.AssistantService", + "shortName": "AssistantService" }, - "shortName": "CreateScheduledEvaluationRun" + "shortName": "GetAssistantSession" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.CreateScheduledEvaluationRunRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "scheduled_evaluation_run", - "type": "google.cloud.ces_v1beta.types.ScheduledEvaluationRun" + "type": "google.cloud.ces_v1beta.types.GetAssistantSessionRequest" }, { - "name": "scheduled_evaluation_run_id", + "name": "name", "type": "str" }, { @@ -8960,22 +9067,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.types.ScheduledEvaluationRun", - "shortName": "create_scheduled_evaluation_run" + "resultType": "google.cloud.ces_v1beta.types.AssistantSession", + "shortName": "get_assistant_session" }, - "description": "Sample for CreateScheduledEvaluationRun", - "file": "ces_v1beta_generated_evaluation_service_create_scheduled_evaluation_run_async.py", + "description": "Sample for GetAssistantSession", + "file": "ces_v1beta_generated_assistant_service_get_assistant_session_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_CreateScheduledEvaluationRun_async", + "regionTag": "ces_v1beta_generated_AssistantService_GetAssistantSession_async", "segments": [ { - "end": 57, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 57, + "end": 51, "start": 27, "type": "SHORT" }, @@ -8985,54 +9092,46 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 51, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 54, - "start": 52, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 58, - "start": 55, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_create_scheduled_evaluation_run_async.py" + "title": "ces_v1beta_generated_assistant_service_get_assistant_session_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", - "shortName": "EvaluationServiceClient" + "fullName": "google.cloud.ces_v1beta.AssistantServiceClient", + "shortName": "AssistantServiceClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.create_scheduled_evaluation_run", + "fullName": "google.cloud.ces_v1beta.AssistantServiceClient.get_assistant_session", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.CreateScheduledEvaluationRun", + "fullName": "google.cloud.ces.v1beta.AssistantService.GetAssistantSession", "service": { - "fullName": "google.cloud.ces.v1beta.EvaluationService", - "shortName": "EvaluationService" + "fullName": "google.cloud.ces.v1beta.AssistantService", + "shortName": "AssistantService" }, - "shortName": "CreateScheduledEvaluationRun" + "shortName": "GetAssistantSession" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.CreateScheduledEvaluationRunRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "scheduled_evaluation_run", - "type": "google.cloud.ces_v1beta.types.ScheduledEvaluationRun" + "type": "google.cloud.ces_v1beta.types.GetAssistantSessionRequest" }, { - "name": "scheduled_evaluation_run_id", + "name": "name", "type": "str" }, { @@ -9048,22 +9147,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.types.ScheduledEvaluationRun", - "shortName": "create_scheduled_evaluation_run" + "resultType": "google.cloud.ces_v1beta.types.AssistantSession", + "shortName": "get_assistant_session" }, - "description": "Sample for CreateScheduledEvaluationRun", - "file": "ces_v1beta_generated_evaluation_service_create_scheduled_evaluation_run_sync.py", + "description": "Sample for GetAssistantSession", + "file": "ces_v1beta_generated_assistant_service_get_assistant_session_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_CreateScheduledEvaluationRun_sync", + "regionTag": "ces_v1beta_generated_AssistantService_GetAssistantSession_sync", "segments": [ { - "end": 57, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 57, + "end": 51, "start": 27, "type": "SHORT" }, @@ -9073,47 +9172,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 51, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 54, - "start": 52, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 58, - "start": 55, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_create_scheduled_evaluation_run_sync.py" + "title": "ces_v1beta_generated_assistant_service_get_assistant_session_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", - "shortName": "EvaluationServiceAsyncClient" + "fullName": "google.cloud.ces_v1beta.AssistantServiceAsyncClient", + "shortName": "AssistantServiceAsyncClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.delete_evaluation_dataset", + "fullName": "google.cloud.ces_v1beta.AssistantServiceAsyncClient.list_assistant_sessions", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationDataset", + "fullName": "google.cloud.ces.v1beta.AssistantService.ListAssistantSessions", "service": { - "fullName": "google.cloud.ces.v1beta.EvaluationService", - "shortName": "EvaluationService" + "fullName": "google.cloud.ces.v1beta.AssistantService", + "shortName": "AssistantService" }, - "shortName": "DeleteEvaluationDataset" + "shortName": "ListAssistantSessions" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.DeleteEvaluationDatasetRequest" + "type": "google.cloud.ces_v1beta.types.ListAssistantSessionsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -9129,21 +9228,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_evaluation_dataset" + "resultType": "google.cloud.ces_v1beta.services.assistant_service.pagers.ListAssistantSessionsAsyncPager", + "shortName": "list_assistant_sessions" }, - "description": "Sample for DeleteEvaluationDataset", - "file": "ces_v1beta_generated_evaluation_service_delete_evaluation_dataset_async.py", + "description": "Sample for ListAssistantSessions", + "file": "ces_v1beta_generated_assistant_service_list_assistant_sessions_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_DeleteEvaluationDataset_async", + "regionTag": "ces_v1beta_generated_AssistantService_ListAssistantSessions_async", "segments": [ { - "end": 49, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 52, "start": 27, "type": "SHORT" }, @@ -9158,39 +9258,41 @@ "type": "REQUEST_INITIALIZATION" }, { + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_delete_evaluation_dataset_async.py" + "title": "ces_v1beta_generated_assistant_service_list_assistant_sessions_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", - "shortName": "EvaluationServiceClient" + "fullName": "google.cloud.ces_v1beta.AssistantServiceClient", + "shortName": "AssistantServiceClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.delete_evaluation_dataset", + "fullName": "google.cloud.ces_v1beta.AssistantServiceClient.list_assistant_sessions", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationDataset", + "fullName": "google.cloud.ces.v1beta.AssistantService.ListAssistantSessions", "service": { - "fullName": "google.cloud.ces.v1beta.EvaluationService", - "shortName": "EvaluationService" + "fullName": "google.cloud.ces.v1beta.AssistantService", + "shortName": "AssistantService" }, - "shortName": "DeleteEvaluationDataset" + "shortName": "ListAssistantSessions" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.DeleteEvaluationDatasetRequest" + "type": "google.cloud.ces_v1beta.types.ListAssistantSessionsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -9206,21 +9308,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_evaluation_dataset" + "resultType": "google.cloud.ces_v1beta.services.assistant_service.pagers.ListAssistantSessionsPager", + "shortName": "list_assistant_sessions" }, - "description": "Sample for DeleteEvaluationDataset", - "file": "ces_v1beta_generated_evaluation_service_delete_evaluation_dataset_sync.py", + "description": "Sample for ListAssistantSessions", + "file": "ces_v1beta_generated_assistant_service_list_assistant_sessions_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_DeleteEvaluationDataset_sync", + "regionTag": "ces_v1beta_generated_AssistantService_ListAssistantSessions_sync", "segments": [ { - "end": 49, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 52, "start": 27, "type": "SHORT" }, @@ -9235,41 +9338,39 @@ "type": "REQUEST_INITIALIZATION" }, { + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_delete_evaluation_dataset_sync.py" + "title": "ces_v1beta_generated_assistant_service_list_assistant_sessions_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", - "shortName": "EvaluationServiceAsyncClient" + "fullName": "google.cloud.ces_v1beta.AssistantServiceAsyncClient", + "shortName": "AssistantServiceAsyncClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.delete_evaluation_expectation", + "fullName": "google.cloud.ces_v1beta.AssistantServiceAsyncClient.run_assistant", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationExpectation", + "fullName": "google.cloud.ces.v1beta.AssistantService.RunAssistant", "service": { - "fullName": "google.cloud.ces.v1beta.EvaluationService", - "shortName": "EvaluationService" + "fullName": "google.cloud.ces.v1beta.AssistantService", + "shortName": "AssistantService" }, - "shortName": "DeleteEvaluationExpectation" + "shortName": "RunAssistant" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.DeleteEvaluationExpectationRequest" - }, - { - "name": "name", - "type": "str" + "type": "google.cloud.ces_v1beta.types.RunAssistantRequest" }, { "name": "retry", @@ -9284,21 +9385,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_evaluation_expectation" + "resultType": "google.cloud.ces_v1beta.types.RunAssistantResponse", + "shortName": "run_assistant" }, - "description": "Sample for DeleteEvaluationExpectation", - "file": "ces_v1beta_generated_evaluation_service_delete_evaluation_expectation_async.py", + "description": "Sample for RunAssistant", + "file": "ces_v1beta_generated_assistant_service_run_assistant_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_DeleteEvaluationExpectation_async", + "regionTag": "ces_v1beta_generated_AssistantService_RunAssistant_async", "segments": [ { - "end": 49, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 56, "start": 27, "type": "SHORT" }, @@ -9308,45 +9410,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "start": 46, + "end": 53, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_delete_evaluation_expectation_async.py" + "title": "ces_v1beta_generated_assistant_service_run_assistant_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", - "shortName": "EvaluationServiceClient" + "fullName": "google.cloud.ces_v1beta.AssistantServiceClient", + "shortName": "AssistantServiceClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.delete_evaluation_expectation", + "fullName": "google.cloud.ces_v1beta.AssistantServiceClient.run_assistant", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationExpectation", + "fullName": "google.cloud.ces.v1beta.AssistantService.RunAssistant", "service": { - "fullName": "google.cloud.ces.v1beta.EvaluationService", - "shortName": "EvaluationService" + "fullName": "google.cloud.ces.v1beta.AssistantService", + "shortName": "AssistantService" }, - "shortName": "DeleteEvaluationExpectation" + "shortName": "RunAssistant" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.DeleteEvaluationExpectationRequest" - }, - { - "name": "name", - "type": "str" + "type": "google.cloud.ces_v1beta.types.RunAssistantRequest" }, { "name": "retry", @@ -9361,21 +9461,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_evaluation_expectation" + "resultType": "google.cloud.ces_v1beta.types.RunAssistantResponse", + "shortName": "run_assistant" }, - "description": "Sample for DeleteEvaluationExpectation", - "file": "ces_v1beta_generated_evaluation_service_delete_evaluation_expectation_sync.py", + "description": "Sample for RunAssistant", + "file": "ces_v1beta_generated_assistant_service_run_assistant_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_DeleteEvaluationExpectation_sync", + "regionTag": "ces_v1beta_generated_AssistantService_RunAssistant_sync", "segments": [ { - "end": 49, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 56, "start": 27, "type": "SHORT" }, @@ -9385,20 +9486,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "start": 46, + "end": 53, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_delete_evaluation_expectation_sync.py" + "title": "ces_v1beta_generated_assistant_service_run_assistant_sync.py" }, { "canonical": true, @@ -9408,22 +9511,30 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", "shortName": "EvaluationServiceAsyncClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.delete_evaluation_result", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.create_evaluation_dataset", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationResult", + "fullName": "google.cloud.ces.v1beta.EvaluationService.CreateEvaluationDataset", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "DeleteEvaluationResult" + "shortName": "CreateEvaluationDataset" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.DeleteEvaluationResultRequest" + "type": "google.cloud.ces_v1beta.types.CreateEvaluationDatasetRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "evaluation_dataset", + "type": "google.cloud.ces_v1beta.types.EvaluationDataset" + }, + { + "name": "evaluation_dataset_id", "type": "str" }, { @@ -9439,21 +9550,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_evaluation_result" + "resultType": "google.cloud.ces_v1beta.types.EvaluationDataset", + "shortName": "create_evaluation_dataset" }, - "description": "Sample for DeleteEvaluationResult", - "file": "ces_v1beta_generated_evaluation_service_delete_evaluation_result_async.py", + "description": "Sample for CreateEvaluationDataset", + "file": "ces_v1beta_generated_evaluation_service_create_evaluation_dataset_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_DeleteEvaluationResult_async", + "regionTag": "ces_v1beta_generated_EvaluationService_CreateEvaluationDataset_async", "segments": [ { - "end": 49, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 55, "start": 27, "type": "SHORT" }, @@ -9463,20 +9575,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "start": 46, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_delete_evaluation_result_async.py" + "title": "ces_v1beta_generated_evaluation_service_create_evaluation_dataset_async.py" }, { "canonical": true, @@ -9485,22 +9599,30 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", "shortName": "EvaluationServiceClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.delete_evaluation_result", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.create_evaluation_dataset", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationResult", + "fullName": "google.cloud.ces.v1beta.EvaluationService.CreateEvaluationDataset", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "DeleteEvaluationResult" + "shortName": "CreateEvaluationDataset" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.DeleteEvaluationResultRequest" + "type": "google.cloud.ces_v1beta.types.CreateEvaluationDatasetRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "evaluation_dataset", + "type": "google.cloud.ces_v1beta.types.EvaluationDataset" + }, + { + "name": "evaluation_dataset_id", "type": "str" }, { @@ -9516,21 +9638,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_evaluation_result" + "resultType": "google.cloud.ces_v1beta.types.EvaluationDataset", + "shortName": "create_evaluation_dataset" }, - "description": "Sample for DeleteEvaluationResult", - "file": "ces_v1beta_generated_evaluation_service_delete_evaluation_result_sync.py", + "description": "Sample for CreateEvaluationDataset", + "file": "ces_v1beta_generated_evaluation_service_create_evaluation_dataset_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_DeleteEvaluationResult_sync", + "regionTag": "ces_v1beta_generated_EvaluationService_CreateEvaluationDataset_sync", "segments": [ { - "end": 49, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 55, "start": 27, "type": "SHORT" }, @@ -9540,20 +9663,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "start": 46, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_delete_evaluation_result_sync.py" + "title": "ces_v1beta_generated_evaluation_service_create_evaluation_dataset_sync.py" }, { "canonical": true, @@ -9563,22 +9688,30 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", "shortName": "EvaluationServiceAsyncClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.delete_evaluation_run", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.create_evaluation_expectation", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationRun", + "fullName": "google.cloud.ces.v1beta.EvaluationService.CreateEvaluationExpectation", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "DeleteEvaluationRun" + "shortName": "CreateEvaluationExpectation" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.DeleteEvaluationRunRequest" + "type": "google.cloud.ces_v1beta.types.CreateEvaluationExpectationRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "evaluation_expectation", + "type": "google.cloud.ces_v1beta.types.EvaluationExpectation" + }, + { + "name": "evaluation_expectation_id", "type": "str" }, { @@ -9594,22 +9727,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_evaluation_run" + "resultType": "google.cloud.ces_v1beta.types.EvaluationExpectation", + "shortName": "create_evaluation_expectation" }, - "description": "Sample for DeleteEvaluationRun", - "file": "ces_v1beta_generated_evaluation_service_delete_evaluation_run_async.py", + "description": "Sample for CreateEvaluationExpectation", + "file": "ces_v1beta_generated_evaluation_service_create_evaluation_expectation_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_DeleteEvaluationRun_async", + "regionTag": "ces_v1beta_generated_EvaluationService_CreateEvaluationExpectation_async", "segments": [ { - "end": 55, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 56, "start": 27, "type": "SHORT" }, @@ -9619,22 +9752,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 53, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_delete_evaluation_run_async.py" + "title": "ces_v1beta_generated_evaluation_service_create_evaluation_expectation_async.py" }, { "canonical": true, @@ -9643,22 +9776,30 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", "shortName": "EvaluationServiceClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.delete_evaluation_run", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.create_evaluation_expectation", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationRun", + "fullName": "google.cloud.ces.v1beta.EvaluationService.CreateEvaluationExpectation", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "DeleteEvaluationRun" + "shortName": "CreateEvaluationExpectation" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.DeleteEvaluationRunRequest" + "type": "google.cloud.ces_v1beta.types.CreateEvaluationExpectationRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "evaluation_expectation", + "type": "google.cloud.ces_v1beta.types.EvaluationExpectation" + }, + { + "name": "evaluation_expectation_id", "type": "str" }, { @@ -9674,22 +9815,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_evaluation_run" + "resultType": "google.cloud.ces_v1beta.types.EvaluationExpectation", + "shortName": "create_evaluation_expectation" }, - "description": "Sample for DeleteEvaluationRun", - "file": "ces_v1beta_generated_evaluation_service_delete_evaluation_run_sync.py", + "description": "Sample for CreateEvaluationExpectation", + "file": "ces_v1beta_generated_evaluation_service_create_evaluation_expectation_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_DeleteEvaluationRun_sync", + "regionTag": "ces_v1beta_generated_EvaluationService_CreateEvaluationExpectation_sync", "segments": [ { - "end": 55, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 56, "start": 27, "type": "SHORT" }, @@ -9699,22 +9840,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 53, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_delete_evaluation_run_sync.py" + "title": "ces_v1beta_generated_evaluation_service_create_evaluation_expectation_sync.py" }, { "canonical": true, @@ -9724,22 +9865,30 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", "shortName": "EvaluationServiceAsyncClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.delete_evaluation", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.create_evaluation", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.DeleteEvaluation", + "fullName": "google.cloud.ces.v1beta.EvaluationService.CreateEvaluation", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "DeleteEvaluation" + "shortName": "CreateEvaluation" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.DeleteEvaluationRequest" + "type": "google.cloud.ces_v1beta.types.CreateEvaluationRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "evaluation", + "type": "google.cloud.ces_v1beta.types.Evaluation" + }, + { + "name": "evaluation_id", "type": "str" }, { @@ -9755,21 +9904,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_evaluation" + "resultType": "google.cloud.ces_v1beta.types.Evaluation", + "shortName": "create_evaluation" }, - "description": "Sample for DeleteEvaluation", - "file": "ces_v1beta_generated_evaluation_service_delete_evaluation_async.py", + "description": "Sample for CreateEvaluation", + "file": "ces_v1beta_generated_evaluation_service_create_evaluation_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_DeleteEvaluation_async", + "regionTag": "ces_v1beta_generated_EvaluationService_CreateEvaluation_async", "segments": [ { - "end": 49, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 56, "start": 27, "type": "SHORT" }, @@ -9779,20 +9929,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "start": 46, + "end": 53, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_delete_evaluation_async.py" + "title": "ces_v1beta_generated_evaluation_service_create_evaluation_async.py" }, { "canonical": true, @@ -9801,22 +9953,30 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", "shortName": "EvaluationServiceClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.delete_evaluation", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.create_evaluation", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.DeleteEvaluation", + "fullName": "google.cloud.ces.v1beta.EvaluationService.CreateEvaluation", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "DeleteEvaluation" + "shortName": "CreateEvaluation" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.DeleteEvaluationRequest" + "type": "google.cloud.ces_v1beta.types.CreateEvaluationRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "evaluation", + "type": "google.cloud.ces_v1beta.types.Evaluation" + }, + { + "name": "evaluation_id", "type": "str" }, { @@ -9832,21 +9992,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_evaluation" + "resultType": "google.cloud.ces_v1beta.types.Evaluation", + "shortName": "create_evaluation" }, - "description": "Sample for DeleteEvaluation", - "file": "ces_v1beta_generated_evaluation_service_delete_evaluation_sync.py", + "description": "Sample for CreateEvaluation", + "file": "ces_v1beta_generated_evaluation_service_create_evaluation_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_DeleteEvaluation_sync", + "regionTag": "ces_v1beta_generated_EvaluationService_CreateEvaluation_sync", "segments": [ { - "end": 49, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 56, "start": 27, "type": "SHORT" }, @@ -9856,20 +10017,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "start": 46, + "end": 53, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_delete_evaluation_sync.py" + "title": "ces_v1beta_generated_evaluation_service_create_evaluation_sync.py" }, { "canonical": true, @@ -9879,22 +10042,30 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", "shortName": "EvaluationServiceAsyncClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.delete_scheduled_evaluation_run", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.create_scheduled_evaluation_run", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.DeleteScheduledEvaluationRun", + "fullName": "google.cloud.ces.v1beta.EvaluationService.CreateScheduledEvaluationRun", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "DeleteScheduledEvaluationRun" + "shortName": "CreateScheduledEvaluationRun" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.DeleteScheduledEvaluationRunRequest" + "type": "google.cloud.ces_v1beta.types.CreateScheduledEvaluationRunRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "scheduled_evaluation_run", + "type": "google.cloud.ces_v1beta.types.ScheduledEvaluationRun" + }, + { + "name": "scheduled_evaluation_run_id", "type": "str" }, { @@ -9910,21 +10081,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_scheduled_evaluation_run" + "resultType": "google.cloud.ces_v1beta.types.ScheduledEvaluationRun", + "shortName": "create_scheduled_evaluation_run" }, - "description": "Sample for DeleteScheduledEvaluationRun", - "file": "ces_v1beta_generated_evaluation_service_delete_scheduled_evaluation_run_async.py", + "description": "Sample for CreateScheduledEvaluationRun", + "file": "ces_v1beta_generated_evaluation_service_create_scheduled_evaluation_run_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_DeleteScheduledEvaluationRun_async", + "regionTag": "ces_v1beta_generated_EvaluationService_CreateScheduledEvaluationRun_async", "segments": [ { - "end": 49, + "end": 57, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 57, "start": 27, "type": "SHORT" }, @@ -9934,20 +10106,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "start": 46, + "end": 54, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 58, + "start": 55, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_delete_scheduled_evaluation_run_async.py" + "title": "ces_v1beta_generated_evaluation_service_create_scheduled_evaluation_run_async.py" }, { "canonical": true, @@ -9956,22 +10130,30 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", "shortName": "EvaluationServiceClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.delete_scheduled_evaluation_run", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.create_scheduled_evaluation_run", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.DeleteScheduledEvaluationRun", + "fullName": "google.cloud.ces.v1beta.EvaluationService.CreateScheduledEvaluationRun", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "DeleteScheduledEvaluationRun" + "shortName": "CreateScheduledEvaluationRun" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.DeleteScheduledEvaluationRunRequest" + "type": "google.cloud.ces_v1beta.types.CreateScheduledEvaluationRunRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "scheduled_evaluation_run", + "type": "google.cloud.ces_v1beta.types.ScheduledEvaluationRun" + }, + { + "name": "scheduled_evaluation_run_id", "type": "str" }, { @@ -9987,21 +10169,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_scheduled_evaluation_run" + "resultType": "google.cloud.ces_v1beta.types.ScheduledEvaluationRun", + "shortName": "create_scheduled_evaluation_run" }, - "description": "Sample for DeleteScheduledEvaluationRun", - "file": "ces_v1beta_generated_evaluation_service_delete_scheduled_evaluation_run_sync.py", + "description": "Sample for CreateScheduledEvaluationRun", + "file": "ces_v1beta_generated_evaluation_service_create_scheduled_evaluation_run_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_DeleteScheduledEvaluationRun_sync", + "regionTag": "ces_v1beta_generated_EvaluationService_CreateScheduledEvaluationRun_sync", "segments": [ { - "end": 49, + "end": 57, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 57, "start": 27, "type": "SHORT" }, @@ -10011,20 +10194,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "start": 46, + "end": 54, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 58, + "start": 55, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_delete_scheduled_evaluation_run_sync.py" + "title": "ces_v1beta_generated_evaluation_service_create_scheduled_evaluation_run_sync.py" }, { "canonical": true, @@ -10034,28 +10219,24 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", "shortName": "EvaluationServiceAsyncClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.export_evaluation_results", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.delete_evaluation_dataset", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.ExportEvaluationResults", + "fullName": "google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationDataset", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "ExportEvaluationResults" + "shortName": "DeleteEvaluationDataset" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.ExportEvaluationResultsRequest" + "type": "google.cloud.ces_v1beta.types.DeleteEvaluationDatasetRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, - { - "name": "names", - "type": "MutableSequence[str]" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -10069,22 +10250,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "export_evaluation_results" + "shortName": "delete_evaluation_dataset" }, - "description": "Sample for ExportEvaluationResults", - "file": "ces_v1beta_generated_evaluation_service_export_evaluation_results_async.py", + "description": "Sample for DeleteEvaluationDataset", + "file": "ces_v1beta_generated_evaluation_service_delete_evaluation_dataset_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_ExportEvaluationResults_async", + "regionTag": "ces_v1beta_generated_EvaluationService_DeleteEvaluationDataset_async", "segments": [ { - "end": 56, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 49, "start": 27, "type": "SHORT" }, @@ -10094,22 +10274,20 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_export_evaluation_results_async.py" + "title": "ces_v1beta_generated_evaluation_service_delete_evaluation_dataset_async.py" }, { "canonical": true, @@ -10118,28 +10296,24 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", "shortName": "EvaluationServiceClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.export_evaluation_results", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.delete_evaluation_dataset", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.ExportEvaluationResults", + "fullName": "google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationDataset", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "ExportEvaluationResults" + "shortName": "DeleteEvaluationDataset" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.ExportEvaluationResultsRequest" + "type": "google.cloud.ces_v1beta.types.DeleteEvaluationDatasetRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, - { - "name": "names", - "type": "MutableSequence[str]" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -10153,22 +10327,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "export_evaluation_results" + "shortName": "delete_evaluation_dataset" }, - "description": "Sample for ExportEvaluationResults", - "file": "ces_v1beta_generated_evaluation_service_export_evaluation_results_sync.py", + "description": "Sample for DeleteEvaluationDataset", + "file": "ces_v1beta_generated_evaluation_service_delete_evaluation_dataset_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_ExportEvaluationResults_sync", + "regionTag": "ces_v1beta_generated_EvaluationService_DeleteEvaluationDataset_sync", "segments": [ { - "end": 56, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 49, "start": 27, "type": "SHORT" }, @@ -10178,22 +10351,20 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_export_evaluation_results_sync.py" + "title": "ces_v1beta_generated_evaluation_service_delete_evaluation_dataset_sync.py" }, { "canonical": true, @@ -10203,28 +10374,24 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", "shortName": "EvaluationServiceAsyncClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.export_evaluation_runs", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.delete_evaluation_expectation", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.ExportEvaluationRuns", + "fullName": "google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationExpectation", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "ExportEvaluationRuns" + "shortName": "DeleteEvaluationExpectation" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.ExportEvaluationRunsRequest" + "type": "google.cloud.ces_v1beta.types.DeleteEvaluationExpectationRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, - { - "name": "names", - "type": "MutableSequence[str]" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -10238,22 +10405,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "export_evaluation_runs" + "shortName": "delete_evaluation_expectation" }, - "description": "Sample for ExportEvaluationRuns", - "file": "ces_v1beta_generated_evaluation_service_export_evaluation_runs_async.py", + "description": "Sample for DeleteEvaluationExpectation", + "file": "ces_v1beta_generated_evaluation_service_delete_evaluation_expectation_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_ExportEvaluationRuns_async", + "regionTag": "ces_v1beta_generated_EvaluationService_DeleteEvaluationExpectation_async", "segments": [ { - "end": 56, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 49, "start": 27, "type": "SHORT" }, @@ -10263,22 +10429,20 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_export_evaluation_runs_async.py" + "title": "ces_v1beta_generated_evaluation_service_delete_evaluation_expectation_async.py" }, { "canonical": true, @@ -10287,28 +10451,24 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", "shortName": "EvaluationServiceClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.export_evaluation_runs", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.delete_evaluation_expectation", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.ExportEvaluationRuns", + "fullName": "google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationExpectation", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "ExportEvaluationRuns" + "shortName": "DeleteEvaluationExpectation" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.ExportEvaluationRunsRequest" + "type": "google.cloud.ces_v1beta.types.DeleteEvaluationExpectationRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, - { - "name": "names", - "type": "MutableSequence[str]" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -10322,22 +10482,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "export_evaluation_runs" + "shortName": "delete_evaluation_expectation" }, - "description": "Sample for ExportEvaluationRuns", - "file": "ces_v1beta_generated_evaluation_service_export_evaluation_runs_sync.py", + "description": "Sample for DeleteEvaluationExpectation", + "file": "ces_v1beta_generated_evaluation_service_delete_evaluation_expectation_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_ExportEvaluationRuns_sync", + "regionTag": "ces_v1beta_generated_EvaluationService_DeleteEvaluationExpectation_sync", "segments": [ { - "end": 56, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 49, "start": 27, "type": "SHORT" }, @@ -10347,22 +10506,20 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_export_evaluation_runs_sync.py" + "title": "ces_v1beta_generated_evaluation_service_delete_evaluation_expectation_sync.py" }, { "canonical": true, @@ -10372,22 +10529,22 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", "shortName": "EvaluationServiceAsyncClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.export_evaluations", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.delete_evaluation_result", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.ExportEvaluations", + "fullName": "google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationResult", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "ExportEvaluations" + "shortName": "DeleteEvaluationResult" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.ExportEvaluationsRequest" + "type": "google.cloud.ces_v1beta.types.DeleteEvaluationResultRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -10403,22 +10560,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "export_evaluations" + "shortName": "delete_evaluation_result" }, - "description": "Sample for ExportEvaluations", - "file": "ces_v1beta_generated_evaluation_service_export_evaluations_async.py", + "description": "Sample for DeleteEvaluationResult", + "file": "ces_v1beta_generated_evaluation_service_delete_evaluation_result_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_ExportEvaluations_async", + "regionTag": "ces_v1beta_generated_EvaluationService_DeleteEvaluationResult_async", "segments": [ { - "end": 56, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 49, "start": 27, "type": "SHORT" }, @@ -10428,22 +10584,20 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_export_evaluations_async.py" + "title": "ces_v1beta_generated_evaluation_service_delete_evaluation_result_async.py" }, { "canonical": true, @@ -10452,22 +10606,22 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", "shortName": "EvaluationServiceClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.export_evaluations", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.delete_evaluation_result", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.ExportEvaluations", + "fullName": "google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationResult", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "ExportEvaluations" + "shortName": "DeleteEvaluationResult" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.ExportEvaluationsRequest" + "type": "google.cloud.ces_v1beta.types.DeleteEvaluationResultRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -10483,22 +10637,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "export_evaluations" + "shortName": "delete_evaluation_result" }, - "description": "Sample for ExportEvaluations", - "file": "ces_v1beta_generated_evaluation_service_export_evaluations_sync.py", + "description": "Sample for DeleteEvaluationResult", + "file": "ces_v1beta_generated_evaluation_service_delete_evaluation_result_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_ExportEvaluations_sync", + "regionTag": "ces_v1beta_generated_EvaluationService_DeleteEvaluationResult_sync", "segments": [ { - "end": 56, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 49, "start": 27, "type": "SHORT" }, @@ -10508,22 +10661,20 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_export_evaluations_sync.py" + "title": "ces_v1beta_generated_evaluation_service_delete_evaluation_result_sync.py" }, { "canonical": true, @@ -10533,22 +10684,22 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", "shortName": "EvaluationServiceAsyncClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.generate_evaluation", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.delete_evaluation_run", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.GenerateEvaluation", + "fullName": "google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationRun", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "GenerateEvaluation" + "shortName": "DeleteEvaluationRun" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.GenerateEvaluationRequest" + "type": "google.cloud.ces_v1beta.types.DeleteEvaluationRunRequest" }, { - "name": "conversation", + "name": "name", "type": "str" }, { @@ -10565,13 +10716,13 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "generate_evaluation" + "shortName": "delete_evaluation_run" }, - "description": "Sample for GenerateEvaluation", - "file": "ces_v1beta_generated_evaluation_service_generate_evaluation_async.py", + "description": "Sample for DeleteEvaluationRun", + "file": "ces_v1beta_generated_evaluation_service_delete_evaluation_run_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_GenerateEvaluation_async", + "regionTag": "ces_v1beta_generated_EvaluationService_DeleteEvaluationRun_async", "segments": [ { "end": 55, @@ -10604,7 +10755,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_generate_evaluation_async.py" + "title": "ces_v1beta_generated_evaluation_service_delete_evaluation_run_async.py" }, { "canonical": true, @@ -10613,22 +10764,22 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", "shortName": "EvaluationServiceClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.generate_evaluation", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.delete_evaluation_run", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.GenerateEvaluation", + "fullName": "google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationRun", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "GenerateEvaluation" + "shortName": "DeleteEvaluationRun" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.GenerateEvaluationRequest" + "type": "google.cloud.ces_v1beta.types.DeleteEvaluationRunRequest" }, { - "name": "conversation", + "name": "name", "type": "str" }, { @@ -10645,13 +10796,13 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "generate_evaluation" + "shortName": "delete_evaluation_run" }, - "description": "Sample for GenerateEvaluation", - "file": "ces_v1beta_generated_evaluation_service_generate_evaluation_sync.py", + "description": "Sample for DeleteEvaluationRun", + "file": "ces_v1beta_generated_evaluation_service_delete_evaluation_run_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_GenerateEvaluation_sync", + "regionTag": "ces_v1beta_generated_EvaluationService_DeleteEvaluationRun_sync", "segments": [ { "end": 55, @@ -10684,7 +10835,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_generate_evaluation_sync.py" + "title": "ces_v1beta_generated_evaluation_service_delete_evaluation_run_sync.py" }, { "canonical": true, @@ -10694,19 +10845,19 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", "shortName": "EvaluationServiceAsyncClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.get_evaluation_dataset", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.delete_evaluation", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.GetEvaluationDataset", + "fullName": "google.cloud.ces.v1beta.EvaluationService.DeleteEvaluation", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "GetEvaluationDataset" + "shortName": "DeleteEvaluation" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.GetEvaluationDatasetRequest" + "type": "google.cloud.ces_v1beta.types.DeleteEvaluationRequest" }, { "name": "name", @@ -10725,22 +10876,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.types.EvaluationDataset", - "shortName": "get_evaluation_dataset" + "shortName": "delete_evaluation" }, - "description": "Sample for GetEvaluationDataset", - "file": "ces_v1beta_generated_evaluation_service_get_evaluation_dataset_async.py", + "description": "Sample for DeleteEvaluation", + "file": "ces_v1beta_generated_evaluation_service_delete_evaluation_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_GetEvaluationDataset_async", + "regionTag": "ces_v1beta_generated_EvaluationService_DeleteEvaluation_async", "segments": [ { - "end": 51, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 49, "start": 27, "type": "SHORT" }, @@ -10755,17 +10905,15 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_get_evaluation_dataset_async.py" + "title": "ces_v1beta_generated_evaluation_service_delete_evaluation_async.py" }, { "canonical": true, @@ -10774,19 +10922,19 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", "shortName": "EvaluationServiceClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.get_evaluation_dataset", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.delete_evaluation", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.GetEvaluationDataset", + "fullName": "google.cloud.ces.v1beta.EvaluationService.DeleteEvaluation", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "GetEvaluationDataset" + "shortName": "DeleteEvaluation" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.GetEvaluationDatasetRequest" + "type": "google.cloud.ces_v1beta.types.DeleteEvaluationRequest" }, { "name": "name", @@ -10805,22 +10953,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.types.EvaluationDataset", - "shortName": "get_evaluation_dataset" + "shortName": "delete_evaluation" }, - "description": "Sample for GetEvaluationDataset", - "file": "ces_v1beta_generated_evaluation_service_get_evaluation_dataset_sync.py", + "description": "Sample for DeleteEvaluation", + "file": "ces_v1beta_generated_evaluation_service_delete_evaluation_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_GetEvaluationDataset_sync", + "regionTag": "ces_v1beta_generated_EvaluationService_DeleteEvaluation_sync", "segments": [ { - "end": 51, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 49, "start": 27, "type": "SHORT" }, @@ -10835,17 +10982,15 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_get_evaluation_dataset_sync.py" + "title": "ces_v1beta_generated_evaluation_service_delete_evaluation_sync.py" }, { "canonical": true, @@ -10855,19 +11000,19 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", "shortName": "EvaluationServiceAsyncClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.get_evaluation_expectation", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.delete_scheduled_evaluation_run", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.GetEvaluationExpectation", + "fullName": "google.cloud.ces.v1beta.EvaluationService.DeleteScheduledEvaluationRun", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "GetEvaluationExpectation" + "shortName": "DeleteScheduledEvaluationRun" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.GetEvaluationExpectationRequest" + "type": "google.cloud.ces_v1beta.types.DeleteScheduledEvaluationRunRequest" }, { "name": "name", @@ -10886,22 +11031,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.types.EvaluationExpectation", - "shortName": "get_evaluation_expectation" + "shortName": "delete_scheduled_evaluation_run" }, - "description": "Sample for GetEvaluationExpectation", - "file": "ces_v1beta_generated_evaluation_service_get_evaluation_expectation_async.py", + "description": "Sample for DeleteScheduledEvaluationRun", + "file": "ces_v1beta_generated_evaluation_service_delete_scheduled_evaluation_run_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_GetEvaluationExpectation_async", + "regionTag": "ces_v1beta_generated_EvaluationService_DeleteScheduledEvaluationRun_async", "segments": [ { - "end": 51, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 49, "start": 27, "type": "SHORT" }, @@ -10916,17 +11060,15 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_get_evaluation_expectation_async.py" + "title": "ces_v1beta_generated_evaluation_service_delete_scheduled_evaluation_run_async.py" }, { "canonical": true, @@ -10935,19 +11077,19 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", "shortName": "EvaluationServiceClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.get_evaluation_expectation", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.delete_scheduled_evaluation_run", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.GetEvaluationExpectation", + "fullName": "google.cloud.ces.v1beta.EvaluationService.DeleteScheduledEvaluationRun", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "GetEvaluationExpectation" + "shortName": "DeleteScheduledEvaluationRun" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.GetEvaluationExpectationRequest" + "type": "google.cloud.ces_v1beta.types.DeleteScheduledEvaluationRunRequest" }, { "name": "name", @@ -10966,22 +11108,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.types.EvaluationExpectation", - "shortName": "get_evaluation_expectation" + "shortName": "delete_scheduled_evaluation_run" }, - "description": "Sample for GetEvaluationExpectation", - "file": "ces_v1beta_generated_evaluation_service_get_evaluation_expectation_sync.py", + "description": "Sample for DeleteScheduledEvaluationRun", + "file": "ces_v1beta_generated_evaluation_service_delete_scheduled_evaluation_run_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_GetEvaluationExpectation_sync", + "regionTag": "ces_v1beta_generated_EvaluationService_DeleteScheduledEvaluationRun_sync", "segments": [ { - "end": 51, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 49, "start": 27, "type": "SHORT" }, @@ -10996,17 +11137,15 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_get_evaluation_expectation_sync.py" + "title": "ces_v1beta_generated_evaluation_service_delete_scheduled_evaluation_run_sync.py" }, { "canonical": true, @@ -11016,24 +11155,28 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", "shortName": "EvaluationServiceAsyncClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.get_evaluation_result", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.export_evaluation_results", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.GetEvaluationResult", + "fullName": "google.cloud.ces.v1beta.EvaluationService.ExportEvaluationResults", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "GetEvaluationResult" + "shortName": "ExportEvaluationResults" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.GetEvaluationResultRequest" + "type": "google.cloud.ces_v1beta.types.ExportEvaluationResultsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, + { + "name": "names", + "type": "MutableSequence[str]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -11047,22 +11190,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.types.EvaluationResult", - "shortName": "get_evaluation_result" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "export_evaluation_results" }, - "description": "Sample for GetEvaluationResult", - "file": "ces_v1beta_generated_evaluation_service_get_evaluation_result_async.py", + "description": "Sample for ExportEvaluationResults", + "file": "ces_v1beta_generated_evaluation_service_export_evaluation_results_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_GetEvaluationResult_async", + "regionTag": "ces_v1beta_generated_EvaluationService_ExportEvaluationResults_async", "segments": [ { - "end": 51, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 56, "start": 27, "type": "SHORT" }, @@ -11072,22 +11215,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_get_evaluation_result_async.py" + "title": "ces_v1beta_generated_evaluation_service_export_evaluation_results_async.py" }, { "canonical": true, @@ -11096,24 +11239,28 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", "shortName": "EvaluationServiceClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.get_evaluation_result", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.export_evaluation_results", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.GetEvaluationResult", + "fullName": "google.cloud.ces.v1beta.EvaluationService.ExportEvaluationResults", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "GetEvaluationResult" + "shortName": "ExportEvaluationResults" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.GetEvaluationResultRequest" + "type": "google.cloud.ces_v1beta.types.ExportEvaluationResultsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, + { + "name": "names", + "type": "MutableSequence[str]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -11127,22 +11274,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.types.EvaluationResult", - "shortName": "get_evaluation_result" + "resultType": "google.api_core.operation.Operation", + "shortName": "export_evaluation_results" }, - "description": "Sample for GetEvaluationResult", - "file": "ces_v1beta_generated_evaluation_service_get_evaluation_result_sync.py", + "description": "Sample for ExportEvaluationResults", + "file": "ces_v1beta_generated_evaluation_service_export_evaluation_results_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_GetEvaluationResult_sync", + "regionTag": "ces_v1beta_generated_EvaluationService_ExportEvaluationResults_sync", "segments": [ { - "end": 51, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 56, "start": 27, "type": "SHORT" }, @@ -11152,22 +11299,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_get_evaluation_result_sync.py" + "title": "ces_v1beta_generated_evaluation_service_export_evaluation_results_sync.py" }, { "canonical": true, @@ -11177,24 +11324,28 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", "shortName": "EvaluationServiceAsyncClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.get_evaluation_run", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.export_evaluation_runs", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.GetEvaluationRun", + "fullName": "google.cloud.ces.v1beta.EvaluationService.ExportEvaluationRuns", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "GetEvaluationRun" + "shortName": "ExportEvaluationRuns" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.GetEvaluationRunRequest" + "type": "google.cloud.ces_v1beta.types.ExportEvaluationRunsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, + { + "name": "names", + "type": "MutableSequence[str]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -11208,22 +11359,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.types.EvaluationRun", - "shortName": "get_evaluation_run" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "export_evaluation_runs" }, - "description": "Sample for GetEvaluationRun", - "file": "ces_v1beta_generated_evaluation_service_get_evaluation_run_async.py", + "description": "Sample for ExportEvaluationRuns", + "file": "ces_v1beta_generated_evaluation_service_export_evaluation_runs_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_GetEvaluationRun_async", + "regionTag": "ces_v1beta_generated_EvaluationService_ExportEvaluationRuns_async", "segments": [ { - "end": 51, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 56, "start": 27, "type": "SHORT" }, @@ -11233,22 +11384,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_get_evaluation_run_async.py" + "title": "ces_v1beta_generated_evaluation_service_export_evaluation_runs_async.py" }, { "canonical": true, @@ -11257,24 +11408,28 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", "shortName": "EvaluationServiceClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.get_evaluation_run", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.export_evaluation_runs", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.GetEvaluationRun", + "fullName": "google.cloud.ces.v1beta.EvaluationService.ExportEvaluationRuns", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "GetEvaluationRun" + "shortName": "ExportEvaluationRuns" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.GetEvaluationRunRequest" + "type": "google.cloud.ces_v1beta.types.ExportEvaluationRunsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, + { + "name": "names", + "type": "MutableSequence[str]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -11288,22 +11443,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.types.EvaluationRun", - "shortName": "get_evaluation_run" + "resultType": "google.api_core.operation.Operation", + "shortName": "export_evaluation_runs" }, - "description": "Sample for GetEvaluationRun", - "file": "ces_v1beta_generated_evaluation_service_get_evaluation_run_sync.py", + "description": "Sample for ExportEvaluationRuns", + "file": "ces_v1beta_generated_evaluation_service_export_evaluation_runs_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_GetEvaluationRun_sync", + "regionTag": "ces_v1beta_generated_EvaluationService_ExportEvaluationRuns_sync", "segments": [ { - "end": 51, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 56, "start": 27, "type": "SHORT" }, @@ -11313,22 +11468,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_get_evaluation_run_sync.py" + "title": "ces_v1beta_generated_evaluation_service_export_evaluation_runs_sync.py" }, { "canonical": true, @@ -11338,22 +11493,22 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", "shortName": "EvaluationServiceAsyncClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.get_evaluation", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.export_evaluations", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.GetEvaluation", + "fullName": "google.cloud.ces.v1beta.EvaluationService.ExportEvaluations", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "GetEvaluation" + "shortName": "ExportEvaluations" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.GetEvaluationRequest" + "type": "google.cloud.ces_v1beta.types.ExportEvaluationsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -11369,22 +11524,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.types.Evaluation", - "shortName": "get_evaluation" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "export_evaluations" }, - "description": "Sample for GetEvaluation", - "file": "ces_v1beta_generated_evaluation_service_get_evaluation_async.py", + "description": "Sample for ExportEvaluations", + "file": "ces_v1beta_generated_evaluation_service_export_evaluations_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_GetEvaluation_async", + "regionTag": "ces_v1beta_generated_EvaluationService_ExportEvaluations_async", "segments": [ { - "end": 51, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 56, "start": 27, "type": "SHORT" }, @@ -11394,22 +11549,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_get_evaluation_async.py" + "title": "ces_v1beta_generated_evaluation_service_export_evaluations_async.py" }, { "canonical": true, @@ -11418,22 +11573,22 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", "shortName": "EvaluationServiceClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.get_evaluation", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.export_evaluations", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.GetEvaluation", + "fullName": "google.cloud.ces.v1beta.EvaluationService.ExportEvaluations", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "GetEvaluation" + "shortName": "ExportEvaluations" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.GetEvaluationRequest" + "type": "google.cloud.ces_v1beta.types.ExportEvaluationsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -11449,22 +11604,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.types.Evaluation", - "shortName": "get_evaluation" + "resultType": "google.api_core.operation.Operation", + "shortName": "export_evaluations" }, - "description": "Sample for GetEvaluation", - "file": "ces_v1beta_generated_evaluation_service_get_evaluation_sync.py", + "description": "Sample for ExportEvaluations", + "file": "ces_v1beta_generated_evaluation_service_export_evaluations_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_GetEvaluation_sync", + "regionTag": "ces_v1beta_generated_EvaluationService_ExportEvaluations_sync", "segments": [ { - "end": 51, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 56, "start": 27, "type": "SHORT" }, @@ -11474,22 +11629,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_get_evaluation_sync.py" + "title": "ces_v1beta_generated_evaluation_service_export_evaluations_sync.py" }, { "canonical": true, @@ -11499,22 +11654,22 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", "shortName": "EvaluationServiceAsyncClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.get_scheduled_evaluation_run", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.generate_evaluation", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.GetScheduledEvaluationRun", + "fullName": "google.cloud.ces.v1beta.EvaluationService.GenerateEvaluation", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "GetScheduledEvaluationRun" + "shortName": "GenerateEvaluation" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.GetScheduledEvaluationRunRequest" + "type": "google.cloud.ces_v1beta.types.GenerateEvaluationRequest" }, { - "name": "name", + "name": "conversation", "type": "str" }, { @@ -11530,22 +11685,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.types.ScheduledEvaluationRun", - "shortName": "get_scheduled_evaluation_run" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "generate_evaluation" }, - "description": "Sample for GetScheduledEvaluationRun", - "file": "ces_v1beta_generated_evaluation_service_get_scheduled_evaluation_run_async.py", + "description": "Sample for GenerateEvaluation", + "file": "ces_v1beta_generated_evaluation_service_generate_evaluation_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_GetScheduledEvaluationRun_async", + "regionTag": "ces_v1beta_generated_EvaluationService_GenerateEvaluation_async", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -11560,17 +11715,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_get_scheduled_evaluation_run_async.py" + "title": "ces_v1beta_generated_evaluation_service_generate_evaluation_async.py" }, { "canonical": true, @@ -11579,22 +11734,22 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", "shortName": "EvaluationServiceClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.get_scheduled_evaluation_run", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.generate_evaluation", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.GetScheduledEvaluationRun", + "fullName": "google.cloud.ces.v1beta.EvaluationService.GenerateEvaluation", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "GetScheduledEvaluationRun" + "shortName": "GenerateEvaluation" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.GetScheduledEvaluationRunRequest" + "type": "google.cloud.ces_v1beta.types.GenerateEvaluationRequest" }, { - "name": "name", + "name": "conversation", "type": "str" }, { @@ -11610,22 +11765,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.types.ScheduledEvaluationRun", - "shortName": "get_scheduled_evaluation_run" + "resultType": "google.api_core.operation.Operation", + "shortName": "generate_evaluation" }, - "description": "Sample for GetScheduledEvaluationRun", - "file": "ces_v1beta_generated_evaluation_service_get_scheduled_evaluation_run_sync.py", + "description": "Sample for GenerateEvaluation", + "file": "ces_v1beta_generated_evaluation_service_generate_evaluation_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_GetScheduledEvaluationRun_sync", + "regionTag": "ces_v1beta_generated_EvaluationService_GenerateEvaluation_sync", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -11640,17 +11795,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_get_scheduled_evaluation_run_sync.py" + "title": "ces_v1beta_generated_evaluation_service_generate_evaluation_sync.py" }, { "canonical": true, @@ -11660,22 +11815,22 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", "shortName": "EvaluationServiceAsyncClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.import_evaluations", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.get_evaluation_dataset", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.ImportEvaluations", + "fullName": "google.cloud.ces.v1beta.EvaluationService.GetEvaluationDataset", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "ImportEvaluations" + "shortName": "GetEvaluationDataset" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.ImportEvaluationsRequest" + "type": "google.cloud.ces_v1beta.types.GetEvaluationDatasetRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -11691,22 +11846,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "import_evaluations" + "resultType": "google.cloud.ces_v1beta.types.EvaluationDataset", + "shortName": "get_evaluation_dataset" }, - "description": "Sample for ImportEvaluations", - "file": "ces_v1beta_generated_evaluation_service_import_evaluations_async.py", + "description": "Sample for GetEvaluationDataset", + "file": "ces_v1beta_generated_evaluation_service_get_evaluation_dataset_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_ImportEvaluations_async", + "regionTag": "ces_v1beta_generated_EvaluationService_GetEvaluationDataset_async", "segments": [ { - "end": 55, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 51, "start": 27, "type": "SHORT" }, @@ -11721,17 +11876,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_import_evaluations_async.py" + "title": "ces_v1beta_generated_evaluation_service_get_evaluation_dataset_async.py" }, { "canonical": true, @@ -11740,22 +11895,22 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", "shortName": "EvaluationServiceClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.import_evaluations", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.get_evaluation_dataset", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.ImportEvaluations", + "fullName": "google.cloud.ces.v1beta.EvaluationService.GetEvaluationDataset", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "ImportEvaluations" + "shortName": "GetEvaluationDataset" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.ImportEvaluationsRequest" + "type": "google.cloud.ces_v1beta.types.GetEvaluationDatasetRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -11771,22 +11926,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "import_evaluations" + "resultType": "google.cloud.ces_v1beta.types.EvaluationDataset", + "shortName": "get_evaluation_dataset" }, - "description": "Sample for ImportEvaluations", - "file": "ces_v1beta_generated_evaluation_service_import_evaluations_sync.py", + "description": "Sample for GetEvaluationDataset", + "file": "ces_v1beta_generated_evaluation_service_get_evaluation_dataset_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_ImportEvaluations_sync", + "regionTag": "ces_v1beta_generated_EvaluationService_GetEvaluationDataset_sync", "segments": [ { - "end": 55, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 51, "start": 27, "type": "SHORT" }, @@ -11801,17 +11956,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_import_evaluations_sync.py" + "title": "ces_v1beta_generated_evaluation_service_get_evaluation_dataset_sync.py" }, { "canonical": true, @@ -11821,22 +11976,22 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", "shortName": "EvaluationServiceAsyncClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.list_evaluation_datasets", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.get_evaluation_expectation", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.ListEvaluationDatasets", + "fullName": "google.cloud.ces.v1beta.EvaluationService.GetEvaluationExpectation", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "ListEvaluationDatasets" + "shortName": "GetEvaluationExpectation" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.ListEvaluationDatasetsRequest" + "type": "google.cloud.ces_v1beta.types.GetEvaluationExpectationRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -11852,22 +12007,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationDatasetsAsyncPager", - "shortName": "list_evaluation_datasets" + "resultType": "google.cloud.ces_v1beta.types.EvaluationExpectation", + "shortName": "get_evaluation_expectation" }, - "description": "Sample for ListEvaluationDatasets", - "file": "ces_v1beta_generated_evaluation_service_list_evaluation_datasets_async.py", + "description": "Sample for GetEvaluationExpectation", + "file": "ces_v1beta_generated_evaluation_service_get_evaluation_expectation_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_ListEvaluationDatasets_async", + "regionTag": "ces_v1beta_generated_EvaluationService_GetEvaluationExpectation_async", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -11887,12 +12042,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_list_evaluation_datasets_async.py" + "title": "ces_v1beta_generated_evaluation_service_get_evaluation_expectation_async.py" }, { "canonical": true, @@ -11901,22 +12056,22 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", "shortName": "EvaluationServiceClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.list_evaluation_datasets", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.get_evaluation_expectation", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.ListEvaluationDatasets", + "fullName": "google.cloud.ces.v1beta.EvaluationService.GetEvaluationExpectation", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "ListEvaluationDatasets" + "shortName": "GetEvaluationExpectation" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.ListEvaluationDatasetsRequest" + "type": "google.cloud.ces_v1beta.types.GetEvaluationExpectationRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -11932,22 +12087,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationDatasetsPager", - "shortName": "list_evaluation_datasets" + "resultType": "google.cloud.ces_v1beta.types.EvaluationExpectation", + "shortName": "get_evaluation_expectation" }, - "description": "Sample for ListEvaluationDatasets", - "file": "ces_v1beta_generated_evaluation_service_list_evaluation_datasets_sync.py", + "description": "Sample for GetEvaluationExpectation", + "file": "ces_v1beta_generated_evaluation_service_get_evaluation_expectation_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_ListEvaluationDatasets_sync", + "regionTag": "ces_v1beta_generated_EvaluationService_GetEvaluationExpectation_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -11967,12 +12122,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_list_evaluation_datasets_sync.py" + "title": "ces_v1beta_generated_evaluation_service_get_evaluation_expectation_sync.py" }, { "canonical": true, @@ -11982,22 +12137,22 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", "shortName": "EvaluationServiceAsyncClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.list_evaluation_expectations", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.get_evaluation_result", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.ListEvaluationExpectations", + "fullName": "google.cloud.ces.v1beta.EvaluationService.GetEvaluationResult", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "ListEvaluationExpectations" + "shortName": "GetEvaluationResult" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.ListEvaluationExpectationsRequest" + "type": "google.cloud.ces_v1beta.types.GetEvaluationResultRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -12013,22 +12168,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationExpectationsAsyncPager", - "shortName": "list_evaluation_expectations" + "resultType": "google.cloud.ces_v1beta.types.EvaluationResult", + "shortName": "get_evaluation_result" }, - "description": "Sample for ListEvaluationExpectations", - "file": "ces_v1beta_generated_evaluation_service_list_evaluation_expectations_async.py", + "description": "Sample for GetEvaluationResult", + "file": "ces_v1beta_generated_evaluation_service_get_evaluation_result_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_ListEvaluationExpectations_async", + "regionTag": "ces_v1beta_generated_EvaluationService_GetEvaluationResult_async", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -12048,12 +12203,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_list_evaluation_expectations_async.py" + "title": "ces_v1beta_generated_evaluation_service_get_evaluation_result_async.py" }, { "canonical": true, @@ -12062,22 +12217,22 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", "shortName": "EvaluationServiceClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.list_evaluation_expectations", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.get_evaluation_result", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.ListEvaluationExpectations", + "fullName": "google.cloud.ces.v1beta.EvaluationService.GetEvaluationResult", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "ListEvaluationExpectations" + "shortName": "GetEvaluationResult" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.ListEvaluationExpectationsRequest" + "type": "google.cloud.ces_v1beta.types.GetEvaluationResultRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -12093,22 +12248,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationExpectationsPager", - "shortName": "list_evaluation_expectations" + "resultType": "google.cloud.ces_v1beta.types.EvaluationResult", + "shortName": "get_evaluation_result" }, - "description": "Sample for ListEvaluationExpectations", - "file": "ces_v1beta_generated_evaluation_service_list_evaluation_expectations_sync.py", + "description": "Sample for GetEvaluationResult", + "file": "ces_v1beta_generated_evaluation_service_get_evaluation_result_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_ListEvaluationExpectations_sync", + "regionTag": "ces_v1beta_generated_EvaluationService_GetEvaluationResult_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -12128,12 +12283,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_list_evaluation_expectations_sync.py" + "title": "ces_v1beta_generated_evaluation_service_get_evaluation_result_sync.py" }, { "canonical": true, @@ -12143,22 +12298,22 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", "shortName": "EvaluationServiceAsyncClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.list_evaluation_results", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.get_evaluation_run", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.ListEvaluationResults", + "fullName": "google.cloud.ces.v1beta.EvaluationService.GetEvaluationRun", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "ListEvaluationResults" + "shortName": "GetEvaluationRun" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.ListEvaluationResultsRequest" + "type": "google.cloud.ces_v1beta.types.GetEvaluationRunRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -12174,22 +12329,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationResultsAsyncPager", - "shortName": "list_evaluation_results" + "resultType": "google.cloud.ces_v1beta.types.EvaluationRun", + "shortName": "get_evaluation_run" }, - "description": "Sample for ListEvaluationResults", - "file": "ces_v1beta_generated_evaluation_service_list_evaluation_results_async.py", + "description": "Sample for GetEvaluationRun", + "file": "ces_v1beta_generated_evaluation_service_get_evaluation_run_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_ListEvaluationResults_async", + "regionTag": "ces_v1beta_generated_EvaluationService_GetEvaluationRun_async", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -12209,12 +12364,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_list_evaluation_results_async.py" + "title": "ces_v1beta_generated_evaluation_service_get_evaluation_run_async.py" }, { "canonical": true, @@ -12223,22 +12378,22 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", "shortName": "EvaluationServiceClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.list_evaluation_results", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.get_evaluation_run", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.ListEvaluationResults", + "fullName": "google.cloud.ces.v1beta.EvaluationService.GetEvaluationRun", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "ListEvaluationResults" + "shortName": "GetEvaluationRun" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.ListEvaluationResultsRequest" + "type": "google.cloud.ces_v1beta.types.GetEvaluationRunRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -12254,22 +12409,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationResultsPager", - "shortName": "list_evaluation_results" + "resultType": "google.cloud.ces_v1beta.types.EvaluationRun", + "shortName": "get_evaluation_run" }, - "description": "Sample for ListEvaluationResults", - "file": "ces_v1beta_generated_evaluation_service_list_evaluation_results_sync.py", + "description": "Sample for GetEvaluationRun", + "file": "ces_v1beta_generated_evaluation_service_get_evaluation_run_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_ListEvaluationResults_sync", + "regionTag": "ces_v1beta_generated_EvaluationService_GetEvaluationRun_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -12289,12 +12444,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_list_evaluation_results_sync.py" + "title": "ces_v1beta_generated_evaluation_service_get_evaluation_run_sync.py" }, { "canonical": true, @@ -12304,22 +12459,22 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", "shortName": "EvaluationServiceAsyncClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.list_evaluation_runs", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.get_evaluation", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.ListEvaluationRuns", + "fullName": "google.cloud.ces.v1beta.EvaluationService.GetEvaluation", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "ListEvaluationRuns" + "shortName": "GetEvaluation" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.ListEvaluationRunsRequest" + "type": "google.cloud.ces_v1beta.types.GetEvaluationRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -12335,22 +12490,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationRunsAsyncPager", - "shortName": "list_evaluation_runs" + "resultType": "google.cloud.ces_v1beta.types.Evaluation", + "shortName": "get_evaluation" }, - "description": "Sample for ListEvaluationRuns", - "file": "ces_v1beta_generated_evaluation_service_list_evaluation_runs_async.py", + "description": "Sample for GetEvaluation", + "file": "ces_v1beta_generated_evaluation_service_get_evaluation_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_ListEvaluationRuns_async", + "regionTag": "ces_v1beta_generated_EvaluationService_GetEvaluation_async", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -12370,12 +12525,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_list_evaluation_runs_async.py" + "title": "ces_v1beta_generated_evaluation_service_get_evaluation_async.py" }, { "canonical": true, @@ -12384,22 +12539,22 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", "shortName": "EvaluationServiceClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.list_evaluation_runs", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.get_evaluation", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.ListEvaluationRuns", + "fullName": "google.cloud.ces.v1beta.EvaluationService.GetEvaluation", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "ListEvaluationRuns" + "shortName": "GetEvaluation" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.ListEvaluationRunsRequest" + "type": "google.cloud.ces_v1beta.types.GetEvaluationRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -12415,22 +12570,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationRunsPager", - "shortName": "list_evaluation_runs" + "resultType": "google.cloud.ces_v1beta.types.Evaluation", + "shortName": "get_evaluation" }, - "description": "Sample for ListEvaluationRuns", - "file": "ces_v1beta_generated_evaluation_service_list_evaluation_runs_sync.py", + "description": "Sample for GetEvaluation", + "file": "ces_v1beta_generated_evaluation_service_get_evaluation_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_ListEvaluationRuns_sync", + "regionTag": "ces_v1beta_generated_EvaluationService_GetEvaluation_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -12450,12 +12605,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_list_evaluation_runs_sync.py" + "title": "ces_v1beta_generated_evaluation_service_get_evaluation_sync.py" }, { "canonical": true, @@ -12465,22 +12620,22 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", "shortName": "EvaluationServiceAsyncClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.list_evaluations", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.get_scheduled_evaluation_run", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.ListEvaluations", + "fullName": "google.cloud.ces.v1beta.EvaluationService.GetScheduledEvaluationRun", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "ListEvaluations" + "shortName": "GetScheduledEvaluationRun" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.ListEvaluationsRequest" + "type": "google.cloud.ces_v1beta.types.GetScheduledEvaluationRunRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -12496,22 +12651,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationsAsyncPager", - "shortName": "list_evaluations" + "resultType": "google.cloud.ces_v1beta.types.ScheduledEvaluationRun", + "shortName": "get_scheduled_evaluation_run" }, - "description": "Sample for ListEvaluations", - "file": "ces_v1beta_generated_evaluation_service_list_evaluations_async.py", + "description": "Sample for GetScheduledEvaluationRun", + "file": "ces_v1beta_generated_evaluation_service_get_scheduled_evaluation_run_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_ListEvaluations_async", + "regionTag": "ces_v1beta_generated_EvaluationService_GetScheduledEvaluationRun_async", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -12531,12 +12686,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_list_evaluations_async.py" + "title": "ces_v1beta_generated_evaluation_service_get_scheduled_evaluation_run_async.py" }, { "canonical": true, @@ -12545,22 +12700,22 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", "shortName": "EvaluationServiceClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.list_evaluations", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.get_scheduled_evaluation_run", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.ListEvaluations", + "fullName": "google.cloud.ces.v1beta.EvaluationService.GetScheduledEvaluationRun", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "ListEvaluations" + "shortName": "GetScheduledEvaluationRun" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.ListEvaluationsRequest" + "type": "google.cloud.ces_v1beta.types.GetScheduledEvaluationRunRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -12576,22 +12731,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationsPager", - "shortName": "list_evaluations" + "resultType": "google.cloud.ces_v1beta.types.ScheduledEvaluationRun", + "shortName": "get_scheduled_evaluation_run" }, - "description": "Sample for ListEvaluations", - "file": "ces_v1beta_generated_evaluation_service_list_evaluations_sync.py", + "description": "Sample for GetScheduledEvaluationRun", + "file": "ces_v1beta_generated_evaluation_service_get_scheduled_evaluation_run_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_ListEvaluations_sync", + "regionTag": "ces_v1beta_generated_EvaluationService_GetScheduledEvaluationRun_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -12611,12 +12766,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_list_evaluations_sync.py" + "title": "ces_v1beta_generated_evaluation_service_get_scheduled_evaluation_run_sync.py" }, { "canonical": true, @@ -12626,19 +12781,19 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", "shortName": "EvaluationServiceAsyncClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.list_scheduled_evaluation_runs", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.import_evaluations", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.ListScheduledEvaluationRuns", + "fullName": "google.cloud.ces.v1beta.EvaluationService.ImportEvaluations", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "ListScheduledEvaluationRuns" + "shortName": "ImportEvaluations" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.ListScheduledEvaluationRunsRequest" + "type": "google.cloud.ces_v1beta.types.ImportEvaluationsRequest" }, { "name": "parent", @@ -12657,22 +12812,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.services.evaluation_service.pagers.ListScheduledEvaluationRunsAsyncPager", - "shortName": "list_scheduled_evaluation_runs" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "import_evaluations" }, - "description": "Sample for ListScheduledEvaluationRuns", - "file": "ces_v1beta_generated_evaluation_service_list_scheduled_evaluation_runs_async.py", + "description": "Sample for ImportEvaluations", + "file": "ces_v1beta_generated_evaluation_service_import_evaluations_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_ListScheduledEvaluationRuns_async", + "regionTag": "ces_v1beta_generated_EvaluationService_ImportEvaluations_async", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -12687,17 +12842,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_list_scheduled_evaluation_runs_async.py" + "title": "ces_v1beta_generated_evaluation_service_import_evaluations_async.py" }, { "canonical": true, @@ -12706,19 +12861,19 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", "shortName": "EvaluationServiceClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.list_scheduled_evaluation_runs", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.import_evaluations", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.ListScheduledEvaluationRuns", + "fullName": "google.cloud.ces.v1beta.EvaluationService.ImportEvaluations", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "ListScheduledEvaluationRuns" + "shortName": "ImportEvaluations" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.ListScheduledEvaluationRunsRequest" + "type": "google.cloud.ces_v1beta.types.ImportEvaluationsRequest" }, { "name": "parent", @@ -12737,22 +12892,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.services.evaluation_service.pagers.ListScheduledEvaluationRunsPager", - "shortName": "list_scheduled_evaluation_runs" + "resultType": "google.api_core.operation.Operation", + "shortName": "import_evaluations" }, - "description": "Sample for ListScheduledEvaluationRuns", - "file": "ces_v1beta_generated_evaluation_service_list_scheduled_evaluation_runs_sync.py", + "description": "Sample for ImportEvaluations", + "file": "ces_v1beta_generated_evaluation_service_import_evaluations_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_ListScheduledEvaluationRuns_sync", + "regionTag": "ces_v1beta_generated_EvaluationService_ImportEvaluations_sync", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -12767,17 +12922,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_list_scheduled_evaluation_runs_sync.py" + "title": "ces_v1beta_generated_evaluation_service_import_evaluations_sync.py" }, { "canonical": true, @@ -12787,22 +12942,22 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", "shortName": "EvaluationServiceAsyncClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.run_evaluation_result_metrics", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.list_evaluation_datasets", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.RunEvaluationResultMetrics", + "fullName": "google.cloud.ces.v1beta.EvaluationService.ListEvaluationDatasets", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "RunEvaluationResultMetrics" + "shortName": "ListEvaluationDatasets" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.RunEvaluationResultMetricsRequest" + "type": "google.cloud.ces_v1beta.types.ListEvaluationDatasetsRequest" }, { - "name": "evaluation_result_id", + "name": "parent", "type": "str" }, { @@ -12818,22 +12973,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "run_evaluation_result_metrics" + "resultType": "google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationDatasetsAsyncPager", + "shortName": "list_evaluation_datasets" }, - "description": "Sample for RunEvaluationResultMetrics", - "file": "ces_v1beta_generated_evaluation_service_run_evaluation_result_metrics_async.py", + "description": "Sample for ListEvaluationDatasets", + "file": "ces_v1beta_generated_evaluation_service_list_evaluation_datasets_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_RunEvaluationResultMetrics_async", + "regionTag": "ces_v1beta_generated_EvaluationService_ListEvaluationDatasets_async", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -12848,17 +13003,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_run_evaluation_result_metrics_async.py" + "title": "ces_v1beta_generated_evaluation_service_list_evaluation_datasets_async.py" }, { "canonical": true, @@ -12867,22 +13022,22 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", "shortName": "EvaluationServiceClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.run_evaluation_result_metrics", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.list_evaluation_datasets", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.RunEvaluationResultMetrics", + "fullName": "google.cloud.ces.v1beta.EvaluationService.ListEvaluationDatasets", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "RunEvaluationResultMetrics" + "shortName": "ListEvaluationDatasets" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.RunEvaluationResultMetricsRequest" + "type": "google.cloud.ces_v1beta.types.ListEvaluationDatasetsRequest" }, { - "name": "evaluation_result_id", + "name": "parent", "type": "str" }, { @@ -12898,22 +13053,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "run_evaluation_result_metrics" + "resultType": "google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationDatasetsPager", + "shortName": "list_evaluation_datasets" }, - "description": "Sample for RunEvaluationResultMetrics", - "file": "ces_v1beta_generated_evaluation_service_run_evaluation_result_metrics_sync.py", + "description": "Sample for ListEvaluationDatasets", + "file": "ces_v1beta_generated_evaluation_service_list_evaluation_datasets_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_RunEvaluationResultMetrics_sync", + "regionTag": "ces_v1beta_generated_EvaluationService_ListEvaluationDatasets_sync", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -12928,17 +13083,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_run_evaluation_result_metrics_sync.py" + "title": "ces_v1beta_generated_evaluation_service_list_evaluation_datasets_sync.py" }, { "canonical": true, @@ -12948,22 +13103,22 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", "shortName": "EvaluationServiceAsyncClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.run_evaluation", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.list_evaluation_expectations", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.RunEvaluation", + "fullName": "google.cloud.ces.v1beta.EvaluationService.ListEvaluationExpectations", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "RunEvaluation" + "shortName": "ListEvaluationExpectations" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.RunEvaluationRequest" + "type": "google.cloud.ces_v1beta.types.ListEvaluationExpectationsRequest" }, { - "name": "app", + "name": "parent", "type": "str" }, { @@ -12979,22 +13134,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "run_evaluation" + "resultType": "google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationExpectationsAsyncPager", + "shortName": "list_evaluation_expectations" }, - "description": "Sample for RunEvaluation", - "file": "ces_v1beta_generated_evaluation_service_run_evaluation_async.py", + "description": "Sample for ListEvaluationExpectations", + "file": "ces_v1beta_generated_evaluation_service_list_evaluation_expectations_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_RunEvaluation_async", + "regionTag": "ces_v1beta_generated_EvaluationService_ListEvaluationExpectations_async", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -13009,17 +13164,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_run_evaluation_async.py" + "title": "ces_v1beta_generated_evaluation_service_list_evaluation_expectations_async.py" }, { "canonical": true, @@ -13028,22 +13183,22 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", "shortName": "EvaluationServiceClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.run_evaluation", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.list_evaluation_expectations", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.RunEvaluation", + "fullName": "google.cloud.ces.v1beta.EvaluationService.ListEvaluationExpectations", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "RunEvaluation" + "shortName": "ListEvaluationExpectations" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.RunEvaluationRequest" + "type": "google.cloud.ces_v1beta.types.ListEvaluationExpectationsRequest" }, { - "name": "app", + "name": "parent", "type": "str" }, { @@ -13059,22 +13214,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "run_evaluation" + "resultType": "google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationExpectationsPager", + "shortName": "list_evaluation_expectations" }, - "description": "Sample for RunEvaluation", - "file": "ces_v1beta_generated_evaluation_service_run_evaluation_sync.py", + "description": "Sample for ListEvaluationExpectations", + "file": "ces_v1beta_generated_evaluation_service_list_evaluation_expectations_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_RunEvaluation_sync", + "regionTag": "ces_v1beta_generated_EvaluationService_ListEvaluationExpectations_sync", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -13089,17 +13244,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_run_evaluation_sync.py" + "title": "ces_v1beta_generated_evaluation_service_list_evaluation_expectations_sync.py" }, { "canonical": true, @@ -13109,22 +13264,22 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", "shortName": "EvaluationServiceAsyncClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.test_persona_voice", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.list_evaluation_results", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.TestPersonaVoice", + "fullName": "google.cloud.ces.v1beta.EvaluationService.ListEvaluationResults", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "TestPersonaVoice" + "shortName": "ListEvaluationResults" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.TestPersonaVoiceRequest" + "type": "google.cloud.ces_v1beta.types.ListEvaluationResultsRequest" }, { - "name": "app", + "name": "parent", "type": "str" }, { @@ -13140,22 +13295,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.types.TestPersonaVoiceResponse", - "shortName": "test_persona_voice" + "resultType": "google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationResultsAsyncPager", + "shortName": "list_evaluation_results" }, - "description": "Sample for TestPersonaVoice", - "file": "ces_v1beta_generated_evaluation_service_test_persona_voice_async.py", + "description": "Sample for ListEvaluationResults", + "file": "ces_v1beta_generated_evaluation_service_list_evaluation_results_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_TestPersonaVoice_async", + "regionTag": "ces_v1beta_generated_EvaluationService_ListEvaluationResults_async", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -13165,22 +13320,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_test_persona_voice_async.py" + "title": "ces_v1beta_generated_evaluation_service_list_evaluation_results_async.py" }, { "canonical": true, @@ -13189,22 +13344,22 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", "shortName": "EvaluationServiceClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.test_persona_voice", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.list_evaluation_results", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.TestPersonaVoice", + "fullName": "google.cloud.ces.v1beta.EvaluationService.ListEvaluationResults", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "TestPersonaVoice" + "shortName": "ListEvaluationResults" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.TestPersonaVoiceRequest" + "type": "google.cloud.ces_v1beta.types.ListEvaluationResultsRequest" }, { - "name": "app", + "name": "parent", "type": "str" }, { @@ -13220,22 +13375,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.types.TestPersonaVoiceResponse", - "shortName": "test_persona_voice" + "resultType": "google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationResultsPager", + "shortName": "list_evaluation_results" }, - "description": "Sample for TestPersonaVoice", - "file": "ces_v1beta_generated_evaluation_service_test_persona_voice_sync.py", + "description": "Sample for ListEvaluationResults", + "file": "ces_v1beta_generated_evaluation_service_list_evaluation_results_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_TestPersonaVoice_sync", + "regionTag": "ces_v1beta_generated_EvaluationService_ListEvaluationResults_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -13245,22 +13400,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_test_persona_voice_sync.py" + "title": "ces_v1beta_generated_evaluation_service_list_evaluation_results_sync.py" }, { "canonical": true, @@ -13270,27 +13425,23 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", "shortName": "EvaluationServiceAsyncClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.update_evaluation_dataset", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.list_evaluation_runs", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.UpdateEvaluationDataset", + "fullName": "google.cloud.ces.v1beta.EvaluationService.ListEvaluationRuns", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "UpdateEvaluationDataset" + "shortName": "ListEvaluationRuns" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.UpdateEvaluationDatasetRequest" - }, - { - "name": "evaluation_dataset", - "type": "google.cloud.ces_v1beta.types.EvaluationDataset" + "type": "google.cloud.ces_v1beta.types.ListEvaluationRunsRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "parent", + "type": "str" }, { "name": "retry", @@ -13305,22 +13456,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.types.EvaluationDataset", - "shortName": "update_evaluation_dataset" + "resultType": "google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationRunsAsyncPager", + "shortName": "list_evaluation_runs" }, - "description": "Sample for UpdateEvaluationDataset", - "file": "ces_v1beta_generated_evaluation_service_update_evaluation_dataset_async.py", + "description": "Sample for ListEvaluationRuns", + "file": "ces_v1beta_generated_evaluation_service_list_evaluation_runs_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_UpdateEvaluationDataset_async", + "regionTag": "ces_v1beta_generated_EvaluationService_ListEvaluationRuns_async", "segments": [ { - "end": 54, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 52, "start": 27, "type": "SHORT" }, @@ -13330,22 +13481,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 49, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_update_evaluation_dataset_async.py" + "title": "ces_v1beta_generated_evaluation_service_list_evaluation_runs_async.py" }, { "canonical": true, @@ -13354,27 +13505,23 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", "shortName": "EvaluationServiceClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.update_evaluation_dataset", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.list_evaluation_runs", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.UpdateEvaluationDataset", + "fullName": "google.cloud.ces.v1beta.EvaluationService.ListEvaluationRuns", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "UpdateEvaluationDataset" + "shortName": "ListEvaluationRuns" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.UpdateEvaluationDatasetRequest" - }, - { - "name": "evaluation_dataset", - "type": "google.cloud.ces_v1beta.types.EvaluationDataset" + "type": "google.cloud.ces_v1beta.types.ListEvaluationRunsRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "parent", + "type": "str" }, { "name": "retry", @@ -13389,22 +13536,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.types.EvaluationDataset", - "shortName": "update_evaluation_dataset" + "resultType": "google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationRunsPager", + "shortName": "list_evaluation_runs" }, - "description": "Sample for UpdateEvaluationDataset", - "file": "ces_v1beta_generated_evaluation_service_update_evaluation_dataset_sync.py", + "description": "Sample for ListEvaluationRuns", + "file": "ces_v1beta_generated_evaluation_service_list_evaluation_runs_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_UpdateEvaluationDataset_sync", + "regionTag": "ces_v1beta_generated_EvaluationService_ListEvaluationRuns_sync", "segments": [ { - "end": 54, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 52, "start": 27, "type": "SHORT" }, @@ -13414,22 +13561,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 49, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_update_evaluation_dataset_sync.py" + "title": "ces_v1beta_generated_evaluation_service_list_evaluation_runs_sync.py" }, { "canonical": true, @@ -13439,27 +13586,23 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", "shortName": "EvaluationServiceAsyncClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.update_evaluation_expectation", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.list_evaluations", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.UpdateEvaluationExpectation", + "fullName": "google.cloud.ces.v1beta.EvaluationService.ListEvaluations", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "UpdateEvaluationExpectation" + "shortName": "ListEvaluations" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.UpdateEvaluationExpectationRequest" - }, - { - "name": "evaluation_expectation", - "type": "google.cloud.ces_v1beta.types.EvaluationExpectation" + "type": "google.cloud.ces_v1beta.types.ListEvaluationsRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "parent", + "type": "str" }, { "name": "retry", @@ -13474,22 +13617,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.types.EvaluationExpectation", - "shortName": "update_evaluation_expectation" + "resultType": "google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationsAsyncPager", + "shortName": "list_evaluations" }, - "description": "Sample for UpdateEvaluationExpectation", - "file": "ces_v1beta_generated_evaluation_service_update_evaluation_expectation_async.py", + "description": "Sample for ListEvaluations", + "file": "ces_v1beta_generated_evaluation_service_list_evaluations_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_UpdateEvaluationExpectation_async", + "regionTag": "ces_v1beta_generated_EvaluationService_ListEvaluations_async", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -13499,22 +13642,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_update_evaluation_expectation_async.py" + "title": "ces_v1beta_generated_evaluation_service_list_evaluations_async.py" }, { "canonical": true, @@ -13523,27 +13666,23 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", "shortName": "EvaluationServiceClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.update_evaluation_expectation", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.list_evaluations", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.UpdateEvaluationExpectation", + "fullName": "google.cloud.ces.v1beta.EvaluationService.ListEvaluations", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "UpdateEvaluationExpectation" + "shortName": "ListEvaluations" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.UpdateEvaluationExpectationRequest" - }, - { - "name": "evaluation_expectation", - "type": "google.cloud.ces_v1beta.types.EvaluationExpectation" + "type": "google.cloud.ces_v1beta.types.ListEvaluationsRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "parent", + "type": "str" }, { "name": "retry", @@ -13558,22 +13697,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.types.EvaluationExpectation", - "shortName": "update_evaluation_expectation" + "resultType": "google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationsPager", + "shortName": "list_evaluations" }, - "description": "Sample for UpdateEvaluationExpectation", - "file": "ces_v1beta_generated_evaluation_service_update_evaluation_expectation_sync.py", + "description": "Sample for ListEvaluations", + "file": "ces_v1beta_generated_evaluation_service_list_evaluations_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_UpdateEvaluationExpectation_sync", + "regionTag": "ces_v1beta_generated_EvaluationService_ListEvaluations_sync", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -13583,22 +13722,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_update_evaluation_expectation_sync.py" + "title": "ces_v1beta_generated_evaluation_service_list_evaluations_sync.py" }, { "canonical": true, @@ -13608,27 +13747,23 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", "shortName": "EvaluationServiceAsyncClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.update_evaluation", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.list_scheduled_evaluation_runs", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.UpdateEvaluation", + "fullName": "google.cloud.ces.v1beta.EvaluationService.ListScheduledEvaluationRuns", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "UpdateEvaluation" + "shortName": "ListScheduledEvaluationRuns" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.UpdateEvaluationRequest" - }, - { - "name": "evaluation", - "type": "google.cloud.ces_v1beta.types.Evaluation" + "type": "google.cloud.ces_v1beta.types.ListScheduledEvaluationRunsRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "parent", + "type": "str" }, { "name": "retry", @@ -13643,22 +13778,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.types.Evaluation", - "shortName": "update_evaluation" + "resultType": "google.cloud.ces_v1beta.services.evaluation_service.pagers.ListScheduledEvaluationRunsAsyncPager", + "shortName": "list_scheduled_evaluation_runs" }, - "description": "Sample for UpdateEvaluation", - "file": "ces_v1beta_generated_evaluation_service_update_evaluation_async.py", + "description": "Sample for ListScheduledEvaluationRuns", + "file": "ces_v1beta_generated_evaluation_service_list_scheduled_evaluation_runs_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_UpdateEvaluation_async", + "regionTag": "ces_v1beta_generated_EvaluationService_ListScheduledEvaluationRuns_async", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -13668,22 +13803,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_update_evaluation_async.py" + "title": "ces_v1beta_generated_evaluation_service_list_scheduled_evaluation_runs_async.py" }, { "canonical": true, @@ -13692,27 +13827,104 @@ "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", "shortName": "EvaluationServiceClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.update_evaluation", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.list_scheduled_evaluation_runs", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.UpdateEvaluation", + "fullName": "google.cloud.ces.v1beta.EvaluationService.ListScheduledEvaluationRuns", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "UpdateEvaluation" + "shortName": "ListScheduledEvaluationRuns" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.UpdateEvaluationRequest" + "type": "google.cloud.ces_v1beta.types.ListScheduledEvaluationRunsRequest" }, { - "name": "evaluation", - "type": "google.cloud.ces_v1beta.types.Evaluation" + "name": "parent", + "type": "str" }, { - "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, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.services.evaluation_service.pagers.ListScheduledEvaluationRunsPager", + "shortName": "list_scheduled_evaluation_runs" + }, + "description": "Sample for ListScheduledEvaluationRuns", + "file": "ces_v1beta_generated_evaluation_service_list_scheduled_evaluation_runs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_ListScheduledEvaluationRuns_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_list_scheduled_evaluation_runs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.run_evaluation_result_metrics", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.RunEvaluationResultMetrics", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "RunEvaluationResultMetrics" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.RunEvaluationResultMetricsRequest" + }, + { + "name": "evaluation_result_id", + "type": "str" }, { "name": "retry", @@ -13727,14 +13939,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.types.Evaluation", - "shortName": "update_evaluation" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "run_evaluation_result_metrics" }, - "description": "Sample for UpdateEvaluation", - "file": "ces_v1beta_generated_evaluation_service_update_evaluation_sync.py", + "description": "Sample for RunEvaluationResultMetrics", + "file": "ces_v1beta_generated_evaluation_service_run_evaluation_result_metrics_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_UpdateEvaluation_sync", + "regionTag": "ces_v1beta_generated_EvaluationService_RunEvaluationResultMetrics_async", "segments": [ { "end": 55, @@ -13752,13 +13964,13 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { "end": 52, - "start": 50, + "start": 46, "type": "REQUEST_EXECUTION" }, { @@ -13767,37 +13979,32 @@ "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_update_evaluation_sync.py" + "title": "ces_v1beta_generated_evaluation_service_run_evaluation_result_metrics_async.py" }, { "canonical": true, "clientMethod": { - "async": true, "client": { - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", - "shortName": "EvaluationServiceAsyncClient" + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.update_scheduled_evaluation_run", + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.run_evaluation_result_metrics", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.UpdateScheduledEvaluationRun", + "fullName": "google.cloud.ces.v1beta.EvaluationService.RunEvaluationResultMetrics", "service": { "fullName": "google.cloud.ces.v1beta.EvaluationService", "shortName": "EvaluationService" }, - "shortName": "UpdateScheduledEvaluationRun" + "shortName": "RunEvaluationResultMetrics" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.UpdateScheduledEvaluationRunRequest" - }, - { - "name": "scheduled_evaluation_run", - "type": "google.cloud.ces_v1beta.types.ScheduledEvaluationRun" + "type": "google.cloud.ces_v1beta.types.RunEvaluationResultMetricsRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "evaluation_result_id", + "type": "str" }, { "name": "retry", @@ -13812,22 +14019,1419 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.types.ScheduledEvaluationRun", - "shortName": "update_scheduled_evaluation_run" + "resultType": "google.api_core.operation.Operation", + "shortName": "run_evaluation_result_metrics" }, - "description": "Sample for UpdateScheduledEvaluationRun", - "file": "ces_v1beta_generated_evaluation_service_update_scheduled_evaluation_run_async.py", + "description": "Sample for RunEvaluationResultMetrics", + "file": "ces_v1beta_generated_evaluation_service_run_evaluation_result_metrics_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_RunEvaluationResultMetrics_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_run_evaluation_result_metrics_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.run_evaluation", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.RunEvaluation", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "RunEvaluation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.RunEvaluationRequest" + }, + { + "name": "app", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "run_evaluation" + }, + "description": "Sample for RunEvaluation", + "file": "ces_v1beta_generated_evaluation_service_run_evaluation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_RunEvaluation_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_run_evaluation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.run_evaluation", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.RunEvaluation", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "RunEvaluation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.RunEvaluationRequest" + }, + { + "name": "app", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "run_evaluation" + }, + "description": "Sample for RunEvaluation", + "file": "ces_v1beta_generated_evaluation_service_run_evaluation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_RunEvaluation_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_run_evaluation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.test_persona_voice", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.TestPersonaVoice", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "TestPersonaVoice" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.TestPersonaVoiceRequest" + }, + { + "name": "app", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.TestPersonaVoiceResponse", + "shortName": "test_persona_voice" + }, + "description": "Sample for TestPersonaVoice", + "file": "ces_v1beta_generated_evaluation_service_test_persona_voice_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_TestPersonaVoice_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_test_persona_voice_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.test_persona_voice", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.TestPersonaVoice", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "TestPersonaVoice" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.TestPersonaVoiceRequest" + }, + { + "name": "app", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.TestPersonaVoiceResponse", + "shortName": "test_persona_voice" + }, + "description": "Sample for TestPersonaVoice", + "file": "ces_v1beta_generated_evaluation_service_test_persona_voice_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_TestPersonaVoice_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_test_persona_voice_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.update_evaluation_dataset", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.UpdateEvaluationDataset", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "UpdateEvaluationDataset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.UpdateEvaluationDatasetRequest" + }, + { + "name": "evaluation_dataset", + "type": "google.cloud.ces_v1beta.types.EvaluationDataset" + }, + { + "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, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.EvaluationDataset", + "shortName": "update_evaluation_dataset" + }, + "description": "Sample for UpdateEvaluationDataset", + "file": "ces_v1beta_generated_evaluation_service_update_evaluation_dataset_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_UpdateEvaluationDataset_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_update_evaluation_dataset_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.update_evaluation_dataset", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.UpdateEvaluationDataset", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "UpdateEvaluationDataset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.UpdateEvaluationDatasetRequest" + }, + { + "name": "evaluation_dataset", + "type": "google.cloud.ces_v1beta.types.EvaluationDataset" + }, + { + "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, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.EvaluationDataset", + "shortName": "update_evaluation_dataset" + }, + "description": "Sample for UpdateEvaluationDataset", + "file": "ces_v1beta_generated_evaluation_service_update_evaluation_dataset_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_UpdateEvaluationDataset_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_update_evaluation_dataset_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.update_evaluation_expectation", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.UpdateEvaluationExpectation", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "UpdateEvaluationExpectation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.UpdateEvaluationExpectationRequest" + }, + { + "name": "evaluation_expectation", + "type": "google.cloud.ces_v1beta.types.EvaluationExpectation" + }, + { + "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, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.EvaluationExpectation", + "shortName": "update_evaluation_expectation" + }, + "description": "Sample for UpdateEvaluationExpectation", + "file": "ces_v1beta_generated_evaluation_service_update_evaluation_expectation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_UpdateEvaluationExpectation_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_update_evaluation_expectation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.update_evaluation_expectation", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.UpdateEvaluationExpectation", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "UpdateEvaluationExpectation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.UpdateEvaluationExpectationRequest" + }, + { + "name": "evaluation_expectation", + "type": "google.cloud.ces_v1beta.types.EvaluationExpectation" + }, + { + "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, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.EvaluationExpectation", + "shortName": "update_evaluation_expectation" + }, + "description": "Sample for UpdateEvaluationExpectation", + "file": "ces_v1beta_generated_evaluation_service_update_evaluation_expectation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_UpdateEvaluationExpectation_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_update_evaluation_expectation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.update_evaluation", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.UpdateEvaluation", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "UpdateEvaluation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.UpdateEvaluationRequest" + }, + { + "name": "evaluation", + "type": "google.cloud.ces_v1beta.types.Evaluation" + }, + { + "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, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Evaluation", + "shortName": "update_evaluation" + }, + "description": "Sample for UpdateEvaluation", + "file": "ces_v1beta_generated_evaluation_service_update_evaluation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_UpdateEvaluation_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_update_evaluation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.update_evaluation", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.UpdateEvaluation", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "UpdateEvaluation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.UpdateEvaluationRequest" + }, + { + "name": "evaluation", + "type": "google.cloud.ces_v1beta.types.Evaluation" + }, + { + "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, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Evaluation", + "shortName": "update_evaluation" + }, + "description": "Sample for UpdateEvaluation", + "file": "ces_v1beta_generated_evaluation_service_update_evaluation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_UpdateEvaluation_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_update_evaluation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.update_scheduled_evaluation_run", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.UpdateScheduledEvaluationRun", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "UpdateScheduledEvaluationRun" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.UpdateScheduledEvaluationRunRequest" + }, + { + "name": "scheduled_evaluation_run", + "type": "google.cloud.ces_v1beta.types.ScheduledEvaluationRun" + }, + { + "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, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.ScheduledEvaluationRun", + "shortName": "update_scheduled_evaluation_run" + }, + "description": "Sample for UpdateScheduledEvaluationRun", + "file": "ces_v1beta_generated_evaluation_service_update_scheduled_evaluation_run_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_UpdateScheduledEvaluationRun_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_update_scheduled_evaluation_run_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.update_scheduled_evaluation_run", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.UpdateScheduledEvaluationRun", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "UpdateScheduledEvaluationRun" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.UpdateScheduledEvaluationRunRequest" + }, + { + "name": "scheduled_evaluation_run", + "type": "google.cloud.ces_v1beta.types.ScheduledEvaluationRun" + }, + { + "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, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.ScheduledEvaluationRun", + "shortName": "update_scheduled_evaluation_run" + }, + "description": "Sample for UpdateScheduledEvaluationRun", + "file": "ces_v1beta_generated_evaluation_service_update_scheduled_evaluation_run_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_UpdateScheduledEvaluationRun_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_update_scheduled_evaluation_run_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.upload_evaluation_audio", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.UploadEvaluationAudio", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "UploadEvaluationAudio" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.UploadEvaluationAudioRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "audio_content", + "type": "bytes" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.UploadEvaluationAudioResponse", + "shortName": "upload_evaluation_audio" + }, + "description": "Sample for UploadEvaluationAudio", + "file": "ces_v1beta_generated_evaluation_service_upload_evaluation_audio_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_UploadEvaluationAudio_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": "ces_v1beta_generated_evaluation_service_upload_evaluation_audio_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.upload_evaluation_audio", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.UploadEvaluationAudio", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "UploadEvaluationAudio" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.UploadEvaluationAudioRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "audio_content", + "type": "bytes" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.UploadEvaluationAudioResponse", + "shortName": "upload_evaluation_audio" + }, + "description": "Sample for UploadEvaluationAudio", + "file": "ces_v1beta_generated_evaluation_service_upload_evaluation_audio_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_UploadEvaluationAudio_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": "ces_v1beta_generated_evaluation_service_upload_evaluation_audio_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.SessionServiceAsyncClient", + "shortName": "SessionServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.SessionServiceAsyncClient.bidi_run_session", + "method": { + "fullName": "google.cloud.ces.v1beta.SessionService.BidiRunSession", + "service": { + "fullName": "google.cloud.ces.v1beta.SessionService", + "shortName": "SessionService" + }, + "shortName": "BidiRunSession" + }, + "parameters": [ + { + "name": "requests", + "type": "Iterator[google.cloud.ces_v1beta.types.BidiSessionClientMessage]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "Iterable[google.cloud.ces_v1beta.types.BidiSessionServerMessage]", + "shortName": "bidi_run_session" + }, + "description": "Sample for BidiRunSession", + "file": "ces_v1beta_generated_session_service_bidi_run_session_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_SessionService_BidiRunSession_async", + "segments": [ + { + "end": 65, + "start": 27, + "type": "FULL" + }, + { + "end": 65, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 58, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 61, + "start": 59, + "type": "REQUEST_EXECUTION" + }, + { + "end": 66, + "start": 62, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_session_service_bidi_run_session_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.SessionServiceClient", + "shortName": "SessionServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.SessionServiceClient.bidi_run_session", + "method": { + "fullName": "google.cloud.ces.v1beta.SessionService.BidiRunSession", + "service": { + "fullName": "google.cloud.ces.v1beta.SessionService", + "shortName": "SessionService" + }, + "shortName": "BidiRunSession" + }, + "parameters": [ + { + "name": "requests", + "type": "Iterator[google.cloud.ces_v1beta.types.BidiSessionClientMessage]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "Iterable[google.cloud.ces_v1beta.types.BidiSessionServerMessage]", + "shortName": "bidi_run_session" + }, + "description": "Sample for BidiRunSession", + "file": "ces_v1beta_generated_session_service_bidi_run_session_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_SessionService_BidiRunSession_sync", + "segments": [ + { + "end": 65, + "start": 27, + "type": "FULL" + }, + { + "end": 65, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 58, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 61, + "start": 59, + "type": "REQUEST_EXECUTION" + }, + { + "end": 66, + "start": 62, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_session_service_bidi_run_session_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.SessionServiceAsyncClient", + "shortName": "SessionServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.SessionServiceAsyncClient.cancel_assistant_turn", + "method": { + "fullName": "google.cloud.ces.v1beta.SessionService.CancelAssistantTurn", + "service": { + "fullName": "google.cloud.ces.v1beta.SessionService", + "shortName": "SessionService" + }, + "shortName": "CancelAssistantTurn" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.CancelAssistantTurnRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.CancelAssistantTurnResponse", + "shortName": "cancel_assistant_turn" + }, + "description": "Sample for CancelAssistantTurn", + "file": "ces_v1beta_generated_session_service_cancel_assistant_turn_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_UpdateScheduledEvaluationRun_async", + "regionTag": "ces_v1beta_generated_SessionService_CancelAssistantTurn_async", "segments": [ { - "end": 56, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 51, "start": 27, "type": "SHORT" }, @@ -13837,51 +15441,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 51, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_update_scheduled_evaluation_run_async.py" + "title": "ces_v1beta_generated_session_service_cancel_assistant_turn_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", - "shortName": "EvaluationServiceClient" + "fullName": "google.cloud.ces_v1beta.SessionServiceClient", + "shortName": "SessionServiceClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.update_scheduled_evaluation_run", + "fullName": "google.cloud.ces_v1beta.SessionServiceClient.cancel_assistant_turn", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.UpdateScheduledEvaluationRun", + "fullName": "google.cloud.ces.v1beta.SessionService.CancelAssistantTurn", "service": { - "fullName": "google.cloud.ces.v1beta.EvaluationService", - "shortName": "EvaluationService" + "fullName": "google.cloud.ces.v1beta.SessionService", + "shortName": "SessionService" }, - "shortName": "UpdateScheduledEvaluationRun" + "shortName": "CancelAssistantTurn" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.UpdateScheduledEvaluationRunRequest" - }, - { - "name": "scheduled_evaluation_run", - "type": "google.cloud.ces_v1beta.types.ScheduledEvaluationRun" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "type": "google.cloud.ces_v1beta.types.CancelAssistantTurnRequest" }, { "name": "retry", @@ -13896,22 +15492,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.types.ScheduledEvaluationRun", - "shortName": "update_scheduled_evaluation_run" + "resultType": "google.cloud.ces_v1beta.types.CancelAssistantTurnResponse", + "shortName": "cancel_assistant_turn" }, - "description": "Sample for UpdateScheduledEvaluationRun", - "file": "ces_v1beta_generated_evaluation_service_update_scheduled_evaluation_run_sync.py", + "description": "Sample for CancelAssistantTurn", + "file": "ces_v1beta_generated_session_service_cancel_assistant_turn_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_UpdateScheduledEvaluationRun_sync", + "regionTag": "ces_v1beta_generated_SessionService_CancelAssistantTurn_sync", "segments": [ { - "end": 56, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 51, "start": 27, "type": "SHORT" }, @@ -13921,52 +15517,44 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 51, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_update_scheduled_evaluation_run_sync.py" + "title": "ces_v1beta_generated_session_service_cancel_assistant_turn_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", - "shortName": "EvaluationServiceAsyncClient" + "fullName": "google.cloud.ces_v1beta.SessionServiceAsyncClient", + "shortName": "SessionServiceAsyncClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.upload_evaluation_audio", + "fullName": "google.cloud.ces_v1beta.SessionServiceAsyncClient.generate_onboarding_suggestions", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.UploadEvaluationAudio", + "fullName": "google.cloud.ces.v1beta.SessionService.GenerateOnboardingSuggestions", "service": { - "fullName": "google.cloud.ces.v1beta.EvaluationService", - "shortName": "EvaluationService" + "fullName": "google.cloud.ces.v1beta.SessionService", + "shortName": "SessionService" }, - "shortName": "UploadEvaluationAudio" + "shortName": "GenerateOnboardingSuggestions" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.UploadEvaluationAudioRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "audio_content", - "type": "bytes" + "type": "google.cloud.ces_v1beta.types.GenerateOnboardingSuggestionsRequest" }, { "name": "retry", @@ -13981,22 +15569,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.types.UploadEvaluationAudioResponse", - "shortName": "upload_evaluation_audio" + "resultType": "google.cloud.ces_v1beta.types.GenerateOnboardingSuggestionsResponse", + "shortName": "generate_onboarding_suggestions" }, - "description": "Sample for UploadEvaluationAudio", - "file": "ces_v1beta_generated_evaluation_service_upload_evaluation_audio_async.py", + "description": "Sample for GenerateOnboardingSuggestions", + "file": "ces_v1beta_generated_session_service_generate_onboarding_suggestions_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_UploadEvaluationAudio_async", + "regionTag": "ces_v1beta_generated_SessionService_GenerateOnboardingSuggestions_async", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -14006,51 +15594,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_upload_evaluation_audio_async.py" + "title": "ces_v1beta_generated_session_service_generate_onboarding_suggestions_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", - "shortName": "EvaluationServiceClient" + "fullName": "google.cloud.ces_v1beta.SessionServiceClient", + "shortName": "SessionServiceClient" }, - "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.upload_evaluation_audio", + "fullName": "google.cloud.ces_v1beta.SessionServiceClient.generate_onboarding_suggestions", "method": { - "fullName": "google.cloud.ces.v1beta.EvaluationService.UploadEvaluationAudio", + "fullName": "google.cloud.ces.v1beta.SessionService.GenerateOnboardingSuggestions", "service": { - "fullName": "google.cloud.ces.v1beta.EvaluationService", - "shortName": "EvaluationService" + "fullName": "google.cloud.ces.v1beta.SessionService", + "shortName": "SessionService" }, - "shortName": "UploadEvaluationAudio" + "shortName": "GenerateOnboardingSuggestions" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.UploadEvaluationAudioRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "audio_content", - "type": "bytes" + "type": "google.cloud.ces_v1beta.types.GenerateOnboardingSuggestionsRequest" }, { "name": "retry", @@ -14065,22 +15645,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.types.UploadEvaluationAudioResponse", - "shortName": "upload_evaluation_audio" + "resultType": "google.cloud.ces_v1beta.types.GenerateOnboardingSuggestionsResponse", + "shortName": "generate_onboarding_suggestions" }, - "description": "Sample for UploadEvaluationAudio", - "file": "ces_v1beta_generated_evaluation_service_upload_evaluation_audio_sync.py", + "description": "Sample for GenerateOnboardingSuggestions", + "file": "ces_v1beta_generated_session_service_generate_onboarding_suggestions_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_EvaluationService_UploadEvaluationAudio_sync", + "regionTag": "ces_v1beta_generated_SessionService_GenerateOnboardingSuggestions_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -14090,22 +15670,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_evaluation_service_upload_evaluation_audio_sync.py" + "title": "ces_v1beta_generated_session_service_generate_onboarding_suggestions_sync.py" }, { "canonical": true, @@ -14115,19 +15695,19 @@ "fullName": "google.cloud.ces_v1beta.SessionServiceAsyncClient", "shortName": "SessionServiceAsyncClient" }, - "fullName": "google.cloud.ces_v1beta.SessionServiceAsyncClient.bidi_run_session", + "fullName": "google.cloud.ces_v1beta.SessionServiceAsyncClient.run_session", "method": { - "fullName": "google.cloud.ces.v1beta.SessionService.BidiRunSession", + "fullName": "google.cloud.ces.v1beta.SessionService.RunSession", "service": { "fullName": "google.cloud.ces.v1beta.SessionService", "shortName": "SessionService" }, - "shortName": "BidiRunSession" + "shortName": "RunSession" }, "parameters": [ { - "name": "requests", - "type": "Iterator[google.cloud.ces_v1beta.types.BidiSessionClientMessage]" + "name": "request", + "type": "google.cloud.ces_v1beta.types.RunSessionRequest" }, { "name": "retry", @@ -14142,22 +15722,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "Iterable[google.cloud.ces_v1beta.types.BidiSessionServerMessage]", - "shortName": "bidi_run_session" + "resultType": "google.cloud.ces_v1beta.types.RunSessionResponse", + "shortName": "run_session" }, - "description": "Sample for BidiRunSession", - "file": "ces_v1beta_generated_session_service_bidi_run_session_async.py", + "description": "Sample for RunSession", + "file": "ces_v1beta_generated_session_service_run_session_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_SessionService_BidiRunSession_async", + "regionTag": "ces_v1beta_generated_SessionService_RunSession_async", "segments": [ { - "end": 65, + "end": 58, "start": 27, "type": "FULL" }, { - "end": 65, + "end": 58, "start": 27, "type": "SHORT" }, @@ -14167,22 +15747,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 58, + "end": 52, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 61, - "start": 59, + "end": 55, + "start": 53, "type": "REQUEST_EXECUTION" }, { - "end": 66, - "start": 62, + "end": 59, + "start": 56, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_session_service_bidi_run_session_async.py" + "title": "ces_v1beta_generated_session_service_run_session_async.py" }, { "canonical": true, @@ -14191,19 +15771,19 @@ "fullName": "google.cloud.ces_v1beta.SessionServiceClient", "shortName": "SessionServiceClient" }, - "fullName": "google.cloud.ces_v1beta.SessionServiceClient.bidi_run_session", + "fullName": "google.cloud.ces_v1beta.SessionServiceClient.run_session", "method": { - "fullName": "google.cloud.ces.v1beta.SessionService.BidiRunSession", + "fullName": "google.cloud.ces.v1beta.SessionService.RunSession", "service": { "fullName": "google.cloud.ces.v1beta.SessionService", "shortName": "SessionService" }, - "shortName": "BidiRunSession" + "shortName": "RunSession" }, "parameters": [ { - "name": "requests", - "type": "Iterator[google.cloud.ces_v1beta.types.BidiSessionClientMessage]" + "name": "request", + "type": "google.cloud.ces_v1beta.types.RunSessionRequest" }, { "name": "retry", @@ -14218,22 +15798,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "Iterable[google.cloud.ces_v1beta.types.BidiSessionServerMessage]", - "shortName": "bidi_run_session" + "resultType": "google.cloud.ces_v1beta.types.RunSessionResponse", + "shortName": "run_session" }, - "description": "Sample for BidiRunSession", - "file": "ces_v1beta_generated_session_service_bidi_run_session_sync.py", + "description": "Sample for RunSession", + "file": "ces_v1beta_generated_session_service_run_session_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_SessionService_BidiRunSession_sync", + "regionTag": "ces_v1beta_generated_SessionService_RunSession_sync", "segments": [ { - "end": 65, + "end": 58, "start": 27, "type": "FULL" }, { - "end": 65, + "end": 58, "start": 27, "type": "SHORT" }, @@ -14243,22 +15823,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 58, + "end": 52, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 61, - "start": 59, + "end": 55, + "start": 53, "type": "REQUEST_EXECUTION" }, { - "end": 66, - "start": 62, + "end": 59, + "start": 56, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_session_service_bidi_run_session_sync.py" + "title": "ces_v1beta_generated_session_service_run_session_sync.py" }, { "canonical": true, @@ -14268,19 +15848,19 @@ "fullName": "google.cloud.ces_v1beta.SessionServiceAsyncClient", "shortName": "SessionServiceAsyncClient" }, - "fullName": "google.cloud.ces_v1beta.SessionServiceAsyncClient.run_session", + "fullName": "google.cloud.ces_v1beta.SessionServiceAsyncClient.stream_chat_ai_assistant", "method": { - "fullName": "google.cloud.ces.v1beta.SessionService.RunSession", + "fullName": "google.cloud.ces.v1beta.SessionService.StreamChatAiAssistant", "service": { "fullName": "google.cloud.ces.v1beta.SessionService", "shortName": "SessionService" }, - "shortName": "RunSession" + "shortName": "StreamChatAiAssistant" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.RunSessionRequest" + "type": "google.cloud.ces_v1beta.types.StreamChatAiAssistantRequest" }, { "name": "retry", @@ -14295,22 +15875,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.types.RunSessionResponse", - "shortName": "run_session" + "resultType": "Iterable[google.cloud.ces_v1beta.types.StreamChatAiAssistantResponse]", + "shortName": "stream_chat_ai_assistant" }, - "description": "Sample for RunSession", - "file": "ces_v1beta_generated_session_service_run_session_async.py", + "description": "Sample for StreamChatAiAssistant", + "file": "ces_v1beta_generated_session_service_stream_chat_ai_assistant_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_SessionService_RunSession_async", + "regionTag": "ces_v1beta_generated_SessionService_StreamChatAiAssistant_async", "segments": [ { - "end": 58, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 58, + "end": 52, "start": 27, "type": "SHORT" }, @@ -14320,22 +15900,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 52, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 55, - "start": 53, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 59, - "start": 56, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_session_service_run_session_async.py" + "title": "ces_v1beta_generated_session_service_stream_chat_ai_assistant_async.py" }, { "canonical": true, @@ -14344,19 +15924,19 @@ "fullName": "google.cloud.ces_v1beta.SessionServiceClient", "shortName": "SessionServiceClient" }, - "fullName": "google.cloud.ces_v1beta.SessionServiceClient.run_session", + "fullName": "google.cloud.ces_v1beta.SessionServiceClient.stream_chat_ai_assistant", "method": { - "fullName": "google.cloud.ces.v1beta.SessionService.RunSession", + "fullName": "google.cloud.ces.v1beta.SessionService.StreamChatAiAssistant", "service": { "fullName": "google.cloud.ces.v1beta.SessionService", "shortName": "SessionService" }, - "shortName": "RunSession" + "shortName": "StreamChatAiAssistant" }, "parameters": [ { "name": "request", - "type": "google.cloud.ces_v1beta.types.RunSessionRequest" + "type": "google.cloud.ces_v1beta.types.StreamChatAiAssistantRequest" }, { "name": "retry", @@ -14371,22 +15951,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.ces_v1beta.types.RunSessionResponse", - "shortName": "run_session" + "resultType": "Iterable[google.cloud.ces_v1beta.types.StreamChatAiAssistantResponse]", + "shortName": "stream_chat_ai_assistant" }, - "description": "Sample for RunSession", - "file": "ces_v1beta_generated_session_service_run_session_sync.py", + "description": "Sample for StreamChatAiAssistant", + "file": "ces_v1beta_generated_session_service_stream_chat_ai_assistant_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "ces_v1beta_generated_SessionService_RunSession_sync", + "regionTag": "ces_v1beta_generated_SessionService_StreamChatAiAssistant_sync", "segments": [ { - "end": 58, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 58, + "end": 52, "start": 27, "type": "SHORT" }, @@ -14396,22 +15976,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 52, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 55, - "start": 53, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 59, - "start": 56, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "ces_v1beta_generated_session_service_run_session_sync.py" + "title": "ces_v1beta_generated_session_service_stream_chat_ai_assistant_sync.py" }, { "canonical": true, diff --git a/packages/google-cloud-ces/tests/unit/gapic/ces_v1beta/test_agent_service.py b/packages/google-cloud-ces/tests/unit/gapic/ces_v1beta/test_agent_service.py index 0f2ced6c0082..2986f1f6abb5 100644 --- a/packages/google-cloud-ces/tests/unit/gapic/ces_v1beta/test_agent_service.py +++ b/packages/google-cloud-ces/tests/unit/gapic/ces_v1beta/test_agent_service.py @@ -3419,6 +3419,8 @@ def test_import_app_non_empty_request_with_auto_populated_field(): # if they meet the requirements of AIP 4235. request = agent_service.ImportAppRequest( gcs_uri="gcs_uri_value", + json_patch_content="json_patch_content_value", + json_patch_gcs_uri="json_patch_gcs_uri_value", parent="parent_value", display_name="display_name_value", app_id="app_id_value", @@ -3434,6 +3436,8 @@ def test_import_app_non_empty_request_with_auto_populated_field(): _, args, _ = call.mock_calls[0] request_msg = agent_service.ImportAppRequest( gcs_uri="gcs_uri_value", + json_patch_content="json_patch_content_value", + json_patch_gcs_uri="json_patch_gcs_uri_value", parent="parent_value", display_name="display_name_value", app_id="app_id_value", @@ -8798,6 +8802,7 @@ def test_get_tool(request_type, transport: str = "grpc"): execution_type=common.ExecutionType.SYNCHRONOUS, etag="etag_value", generated_summary="generated_summary_value", + read_only=True, ) response = client.get_tool(request) @@ -8814,6 +8819,7 @@ def test_get_tool(request_type, transport: str = "grpc"): assert response.execution_type == common.ExecutionType.SYNCHRONOUS assert response.etag == "etag_value" assert response.generated_summary == "generated_summary_value" + assert response.read_only is True def test_get_tool_non_empty_request_with_auto_populated_field(): @@ -8948,6 +8954,7 @@ async def test_get_tool_async(request_type, transport: str = "grpc_asyncio"): execution_type=common.ExecutionType.SYNCHRONOUS, etag="etag_value", generated_summary="generated_summary_value", + read_only=True, ) ) response = await client.get_tool(request) @@ -8965,6 +8972,7 @@ async def test_get_tool_async(request_type, transport: str = "grpc_asyncio"): assert response.execution_type == common.ExecutionType.SYNCHRONOUS assert response.etag == "etag_value" assert response.generated_summary == "generated_summary_value" + assert response.read_only is True def test_get_tool_field_headers(): @@ -10718,6 +10726,7 @@ def test_create_tool(request_type, transport: str = "grpc"): execution_type=common.ExecutionType.SYNCHRONOUS, etag="etag_value", generated_summary="generated_summary_value", + read_only=True, ) response = client.create_tool(request) @@ -10734,6 +10743,7 @@ def test_create_tool(request_type, transport: str = "grpc"): assert response.execution_type == common.ExecutionType.SYNCHRONOUS assert response.etag == "etag_value" assert response.generated_summary == "generated_summary_value" + assert response.read_only is True def test_create_tool_non_empty_request_with_auto_populated_field(): @@ -10872,6 +10882,7 @@ async def test_create_tool_async(request_type, transport: str = "grpc_asyncio"): execution_type=common.ExecutionType.SYNCHRONOUS, etag="etag_value", generated_summary="generated_summary_value", + read_only=True, ) ) response = await client.create_tool(request) @@ -10889,6 +10900,7 @@ async def test_create_tool_async(request_type, transport: str = "grpc_asyncio"): assert response.execution_type == common.ExecutionType.SYNCHRONOUS assert response.etag == "etag_value" assert response.generated_summary == "generated_summary_value" + assert response.read_only is True def test_create_tool_field_headers(): @@ -11088,6 +11100,7 @@ def test_update_tool(request_type, transport: str = "grpc"): execution_type=common.ExecutionType.SYNCHRONOUS, etag="etag_value", generated_summary="generated_summary_value", + read_only=True, ) response = client.update_tool(request) @@ -11104,6 +11117,7 @@ def test_update_tool(request_type, transport: str = "grpc"): assert response.execution_type == common.ExecutionType.SYNCHRONOUS assert response.etag == "etag_value" assert response.generated_summary == "generated_summary_value" + assert response.read_only is True def test_update_tool_non_empty_request_with_auto_populated_field(): @@ -11236,6 +11250,7 @@ async def test_update_tool_async(request_type, transport: str = "grpc_asyncio"): execution_type=common.ExecutionType.SYNCHRONOUS, etag="etag_value", generated_summary="generated_summary_value", + read_only=True, ) ) response = await client.update_tool(request) @@ -11253,6 +11268,7 @@ async def test_update_tool_async(request_type, transport: str = "grpc_asyncio"): assert response.execution_type == common.ExecutionType.SYNCHRONOUS assert response.etag == "etag_value" assert response.generated_summary == "generated_summary_value" + assert response.read_only is True def test_update_tool_field_headers(): @@ -14217,6 +14233,7 @@ def test_get_deployment(request_type, transport: str = "grpc"): display_name="display_name_value", app_version="app_version_value", etag="etag_value", + modality=deployment.Deployment.Modality.MODALITY_TEXT, ) response = client.get_deployment(request) @@ -14232,6 +14249,7 @@ def test_get_deployment(request_type, transport: str = "grpc"): assert response.display_name == "display_name_value" assert response.app_version == "app_version_value" assert response.etag == "etag_value" + assert response.modality == deployment.Deployment.Modality.MODALITY_TEXT def test_get_deployment_non_empty_request_with_auto_populated_field(): @@ -14367,6 +14385,7 @@ async def test_get_deployment_async(request_type, transport: str = "grpc_asyncio display_name="display_name_value", app_version="app_version_value", etag="etag_value", + modality=deployment.Deployment.Modality.MODALITY_TEXT, ) ) response = await client.get_deployment(request) @@ -14383,6 +14402,7 @@ async def test_get_deployment_async(request_type, transport: str = "grpc_asyncio assert response.display_name == "display_name_value" assert response.app_version == "app_version_value" assert response.etag == "etag_value" + assert response.modality == deployment.Deployment.Modality.MODALITY_TEXT def test_get_deployment_field_headers(): @@ -14555,6 +14575,7 @@ def test_create_deployment(request_type, transport: str = "grpc"): display_name="display_name_value", app_version="app_version_value", etag="etag_value", + modality=gcc_deployment.Deployment.Modality.MODALITY_TEXT, ) response = client.create_deployment(request) @@ -14570,6 +14591,7 @@ def test_create_deployment(request_type, transport: str = "grpc"): assert response.display_name == "display_name_value" assert response.app_version == "app_version_value" assert response.etag == "etag_value" + assert response.modality == gcc_deployment.Deployment.Modality.MODALITY_TEXT def test_create_deployment_non_empty_request_with_auto_populated_field(): @@ -14713,6 +14735,7 @@ async def test_create_deployment_async(request_type, transport: str = "grpc_asyn display_name="display_name_value", app_version="app_version_value", etag="etag_value", + modality=gcc_deployment.Deployment.Modality.MODALITY_TEXT, ) ) response = await client.create_deployment(request) @@ -14729,6 +14752,7 @@ async def test_create_deployment_async(request_type, transport: str = "grpc_asyn assert response.display_name == "display_name_value" assert response.app_version == "app_version_value" assert response.etag == "etag_value" + assert response.modality == gcc_deployment.Deployment.Modality.MODALITY_TEXT def test_create_deployment_field_headers(): @@ -14929,6 +14953,7 @@ def test_update_deployment(request_type, transport: str = "grpc"): display_name="display_name_value", app_version="app_version_value", etag="etag_value", + modality=gcc_deployment.Deployment.Modality.MODALITY_TEXT, ) response = client.update_deployment(request) @@ -14944,6 +14969,7 @@ def test_update_deployment(request_type, transport: str = "grpc"): assert response.display_name == "display_name_value" assert response.app_version == "app_version_value" assert response.etag == "etag_value" + assert response.modality == gcc_deployment.Deployment.Modality.MODALITY_TEXT def test_update_deployment_non_empty_request_with_auto_populated_field(): @@ -15081,6 +15107,7 @@ async def test_update_deployment_async(request_type, transport: str = "grpc_asyn display_name="display_name_value", app_version="app_version_value", etag="etag_value", + modality=gcc_deployment.Deployment.Modality.MODALITY_TEXT, ) ) response = await client.update_deployment(request) @@ -15097,6 +15124,7 @@ async def test_update_deployment_async(request_type, transport: str = "grpc_asyn assert response.display_name == "display_name_value" assert response.app_version == "app_version_value" assert response.etag == "etag_value" + assert response.modality == gcc_deployment.Deployment.Modality.MODALITY_TEXT def test_update_deployment_field_headers(): @@ -18774,6 +18802,370 @@ async def test_create_app_version_flattened_error_async(): ) +@pytest.mark.parametrize( + "request_type", + [ + agent_service.UpdateAppVersionRequest(), + {}, + ], +) +def test_update_app_version(request_type, transport: str = "grpc"): + client = AgentServiceClient( + 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_app_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_app_version.AppVersion( + name="name_value", + display_name="display_name_value", + description="description_value", + creator="creator_value", + etag="etag_value", + ) + response = client.update_app_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.UpdateAppVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_app_version.AppVersion) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.creator == "creator_value" + assert response.etag == "etag_value" + + +def test_update_app_version_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.UpdateAppVersionRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_app_version), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_app_version(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.UpdateAppVersionRequest() + assert args[0] == request_msg + + +def test_update_app_version_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_app_version in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_app_version] = ( + mock_rpc + ) + request = {} + client.update_app_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_app_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_app_version_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_app_version + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_app_version + ] = mock_rpc + + request = {} + await client.update_app_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_app_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + agent_service.UpdateAppVersionRequest(), + {}, + ], +) +async def test_update_app_version_async(request_type, transport: str = "grpc_asyncio"): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + 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_app_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_app_version.AppVersion( + name="name_value", + display_name="display_name_value", + description="description_value", + creator="creator_value", + etag="etag_value", + ) + ) + response = await client.update_app_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.UpdateAppVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_app_version.AppVersion) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.creator == "creator_value" + assert response.etag == "etag_value" + + +def test_update_app_version_field_headers(): + client = AgentServiceClient( + 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_service.UpdateAppVersionRequest() + + request.app_version.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_app_version), "__call__" + ) as call: + call.return_value = gcc_app_version.AppVersion() + client.update_app_version(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", + "app_version.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_app_version_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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_service.UpdateAppVersionRequest() + + request.app_version.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_app_version), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_app_version.AppVersion() + ) + await client.update_app_version(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", + "app_version.name=name_value", + ) in kw["metadata"] + + +def test_update_app_version_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_app_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_app_version.AppVersion() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_app_version( + app_version=gcc_app_version.AppVersion(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].app_version + mock_val = gcc_app_version.AppVersion(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_app_version_flattened_error(): + client = AgentServiceClient( + 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_app_version( + agent_service.UpdateAppVersionRequest(), + app_version=gcc_app_version.AppVersion(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_app_version_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_app_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_app_version.AppVersion() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_app_version.AppVersion() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_app_version( + app_version=gcc_app_version.AppVersion(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].app_version + mock_val = gcc_app_version.AppVersion(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_app_version_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_app_version( + agent_service.UpdateAppVersionRequest(), + app_version=gcc_app_version.AppVersion(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + @pytest.mark.parametrize( "request_type", [ @@ -29325,6 +29717,184 @@ def test_create_app_version_rest_flattened_error(transport: str = "rest"): ) +def test_update_app_version_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_app_version in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_app_version] = ( + mock_rpc + ) + + request = {} + client.update_app_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_app_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_app_version_rest_required_fields( + request_type=agent_service.UpdateAppVersionRequest, +): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseUpdateAppVersion, + "_BaseUpdateAppVersion__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("updateMask",)) + + # verify required fields with non-default values are left alone + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcc_app_version.AppVersion() + # 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": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcc_app_version.AppVersion.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_app_version(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_app_version_rest_flattened(): + client = AgentServiceClient( + 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 = gcc_app_version.AppVersion() + + # get arguments that satisfy an http rule for this method + sample_request = { + "app_version": { + "name": "projects/sample1/locations/sample2/apps/sample3/versions/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + app_version=gcc_app_version.AppVersion(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 + # Convert return value to protobuf type + return_value = gcc_app_version.AppVersion.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_app_version(**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/v1beta/{app_version.name=projects/*/locations/*/apps/*/versions/*}" + % client.transport._host, + args[1], + ) + + +def test_update_app_version_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + 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_app_version( + agent_service.UpdateAppVersionRequest(), + app_version=gcc_app_version.AppVersion(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + def test_delete_app_version_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -31309,6 +31879,28 @@ def test_create_app_version_empty_call_grpc(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_app_version_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_app_version), "__call__" + ) as call: + call.return_value = gcc_app_version.AppVersion() + client.update_app_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.UpdateAppVersionRequest() + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. def test_delete_app_version_empty_call_grpc(): @@ -32023,6 +32615,7 @@ async def test_get_tool_empty_call_grpc_asyncio(): execution_type=common.ExecutionType.SYNCHRONOUS, etag="etag_value", generated_summary="generated_summary_value", + read_only=True, ) ) await client.get_tool(request=None) @@ -32165,6 +32758,7 @@ async def test_create_tool_empty_call_grpc_asyncio(): execution_type=common.ExecutionType.SYNCHRONOUS, etag="etag_value", generated_summary="generated_summary_value", + read_only=True, ) ) await client.create_tool(request=None) @@ -32195,6 +32789,7 @@ async def test_update_tool_empty_call_grpc_asyncio(): execution_type=common.ExecutionType.SYNCHRONOUS, etag="etag_value", generated_summary="generated_summary_value", + read_only=True, ) ) await client.update_tool(request=None) @@ -32410,6 +33005,7 @@ async def test_get_deployment_empty_call_grpc_asyncio(): display_name="display_name_value", app_version="app_version_value", etag="etag_value", + modality=deployment.Deployment.Modality.MODALITY_TEXT, ) ) await client.get_deployment(request=None) @@ -32441,6 +33037,7 @@ async def test_create_deployment_empty_call_grpc_asyncio(): display_name="display_name_value", app_version="app_version_value", etag="etag_value", + modality=gcc_deployment.Deployment.Modality.MODALITY_TEXT, ) ) await client.create_deployment(request=None) @@ -32472,6 +33069,7 @@ async def test_update_deployment_empty_call_grpc_asyncio(): display_name="display_name_value", app_version="app_version_value", etag="etag_value", + modality=gcc_deployment.Deployment.Modality.MODALITY_TEXT, ) ) await client.update_deployment(request=None) @@ -32735,6 +33333,38 @@ async def test_create_app_version_empty_call_grpc_asyncio(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_app_version_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_app_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_app_version.AppVersion( + name="name_value", + display_name="display_name_value", + description="description_value", + creator="creator_value", + etag="etag_value", + ) + ) + await client.update_app_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.UpdateAppVersionRequest() + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio @@ -33217,6 +33847,18 @@ def test_create_app_rest_call_success(request_type): "prebuilt_ambient_sound": "prebuilt_ambient_sound_value", "volume_gain_db": 0.1467, }, + "custom_voice_samples": [ + { + "name": "name_value", + "voice_sample_gcs_uri": "voice_sample_gcs_uri_value", + "consent_audio_gcs_uri": "consent_audio_gcs_uri_value", + "voice_instruction": "voice_instruction_value", + "preview_audio_content": b"preview_audio_content_blob", + "preview_text": "preview_text_value", + "warnings": [{"message": "message_value", "type_": 1}], + "voice_instruction_mode": 1, + } + ], }, "logging_settings": { "redaction_config": { @@ -33242,6 +33884,7 @@ def test_create_app_rest_call_success(request_type): }, "evaluation_audio_recording_config": {}, "metric_analysis_settings": {"llm_metrics_opted_out": True}, + "required_recording_consent": True, }, "error_handling_settings": { "error_handling_strategy": 1, @@ -33251,7 +33894,11 @@ def test_create_app_rest_call_success(request_type): }, "end_session_config": {"escalate_session": True}, }, - "model_settings": {"model": "model_value", "temperature": 0.1198}, + "model_settings": { + "model": "model_value", + "temperature": 0.1198, + "thinking_level": 1, + }, "tool_execution_mode": 1, "evaluation_metrics_thresholds": { "golden_evaluation_metrics_thresholds": { @@ -33398,6 +34045,7 @@ def test_create_app_rest_call_success(request_type): "evaluation_run_caching_settings": {"run_caching_mode": 1}, }, "validation_errors": ["validation_errors_value1", "validation_errors_value2"], + "dashboard_settings": {"default_dashboard": "default_dashboard_value"}, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -33613,6 +34261,18 @@ def test_update_app_rest_call_success(request_type): "prebuilt_ambient_sound": "prebuilt_ambient_sound_value", "volume_gain_db": 0.1467, }, + "custom_voice_samples": [ + { + "name": "name_value", + "voice_sample_gcs_uri": "voice_sample_gcs_uri_value", + "consent_audio_gcs_uri": "consent_audio_gcs_uri_value", + "voice_instruction": "voice_instruction_value", + "preview_audio_content": b"preview_audio_content_blob", + "preview_text": "preview_text_value", + "warnings": [{"message": "message_value", "type_": 1}], + "voice_instruction_mode": 1, + } + ], }, "logging_settings": { "redaction_config": { @@ -33638,6 +34298,7 @@ def test_update_app_rest_call_success(request_type): }, "evaluation_audio_recording_config": {}, "metric_analysis_settings": {"llm_metrics_opted_out": True}, + "required_recording_consent": True, }, "error_handling_settings": { "error_handling_strategy": 1, @@ -33647,7 +34308,11 @@ def test_update_app_rest_call_success(request_type): }, "end_session_config": {"escalate_session": True}, }, - "model_settings": {"model": "model_value", "temperature": 0.1198}, + "model_settings": { + "model": "model_value", + "temperature": 0.1198, + "thinking_level": 1, + }, "tool_execution_mode": 1, "evaluation_metrics_thresholds": { "golden_evaluation_metrics_thresholds": { @@ -33794,6 +34459,7 @@ def test_update_app_rest_call_success(request_type): "evaluation_run_caching_settings": {"run_caching_mode": 1}, }, "validation_errors": ["validation_errors_value1", "validation_errors_value2"], + "dashboard_settings": {"default_dashboard": "default_dashboard_value"}, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -35022,10 +35688,70 @@ def test_create_agent_rest_call_success(request_type): "respect_response_interruption_settings": True, "language_code_variable": "language_code_variable_value", }, + "remote_a2a_agent": { + "a2a_config": { + "agent_card": { + "name": "name_value", + "description": "description_value", + "supported_interfaces": [ + { + "url": "url_value", + "protocol_binding": "protocol_binding_value", + "tenant": "tenant_value", + "protocol_version": "protocol_version_value", + } + ], + "version": "version_value", + "skills": [ + { + "id": "id_value", + "name": "name_value", + "description": "description_value", + "tags": ["tags_value1", "tags_value2"], + "examples": ["examples_value1", "examples_value2"], + "input_modes": ["input_modes_value1", "input_modes_value2"], + "output_modes": [ + "output_modes_value1", + "output_modes_value2", + ], + } + ], + }, + "agent_registry": "agent_registry_value", + "api_authentication": { + "api_key_config": { + "key_name": "key_name_value", + "api_key_secret_version": "api_key_secret_version_value", + "request_location": 1, + }, + "oauth_config": { + "oauth_grant_type": 1, + "client_id": "client_id_value", + "client_secret_version": "client_secret_version_value", + "token_endpoint": "token_endpoint_value", + "scopes": ["scopes_value1", "scopes_value2"], + }, + "service_agent_id_token_auth_config": {}, + "service_account_auth_config": { + "service_account": "service_account_value", + "scopes": ["scopes_value1", "scopes_value2"], + }, + "bearer_token_config": {"token": "token_value"}, + }, + "input_variable_mapping": {}, + "output_variable_mapping": {}, + "streaming_enabled": True, + "context_id": "context_id_value", + } + }, "name": "name_value", "display_name": "display_name_value", "description": "description_value", - "model_settings": {"model": "model_value", "temperature": 0.1198}, + "model_settings": { + "model": "model_value", + "temperature": 0.1198, + "thinking_level": 1, + }, "instruction": "instruction_value", "tools": ["tools_value1", "tools_value2"], "child_agents": ["child_agents_value1", "child_agents_value2"], @@ -35298,10 +36024,70 @@ def test_update_agent_rest_call_success(request_type): "respect_response_interruption_settings": True, "language_code_variable": "language_code_variable_value", }, + "remote_a2a_agent": { + "a2a_config": { + "agent_card": { + "name": "name_value", + "description": "description_value", + "supported_interfaces": [ + { + "url": "url_value", + "protocol_binding": "protocol_binding_value", + "tenant": "tenant_value", + "protocol_version": "protocol_version_value", + } + ], + "version": "version_value", + "skills": [ + { + "id": "id_value", + "name": "name_value", + "description": "description_value", + "tags": ["tags_value1", "tags_value2"], + "examples": ["examples_value1", "examples_value2"], + "input_modes": ["input_modes_value1", "input_modes_value2"], + "output_modes": [ + "output_modes_value1", + "output_modes_value2", + ], + } + ], + }, + "agent_registry": "agent_registry_value", + "api_authentication": { + "api_key_config": { + "key_name": "key_name_value", + "api_key_secret_version": "api_key_secret_version_value", + "request_location": 1, + }, + "oauth_config": { + "oauth_grant_type": 1, + "client_id": "client_id_value", + "client_secret_version": "client_secret_version_value", + "token_endpoint": "token_endpoint_value", + "scopes": ["scopes_value1", "scopes_value2"], + }, + "service_agent_id_token_auth_config": {}, + "service_account_auth_config": { + "service_account": "service_account_value", + "scopes": ["scopes_value1", "scopes_value2"], + }, + "bearer_token_config": {"token": "token_value"}, + }, + "input_variable_mapping": {}, + "output_variable_mapping": {}, + "streaming_enabled": True, + "context_id": "context_id_value", + } + }, "name": "projects/sample1/locations/sample2/apps/sample3/agents/sample4", "display_name": "display_name_value", "description": "description_value", - "model_settings": {"model": "model_value", "temperature": 0.1198}, + "model_settings": { + "model": "model_value", + "temperature": 0.1198, + "thinking_level": 1, + }, "instruction": "instruction_value", "tools": ["tools_value1", "tools_value2"], "child_agents": ["child_agents_value1", "child_agents_value2"], @@ -35955,7 +36741,11 @@ def test_create_example_rest_call_success(request_type): "transcript": "transcript_value", "blob": {"mime_type": "mime_type_value", "data": b"data_blob"}, "payload": {"fields": {}}, - "image": {"mime_type": "mime_type_value", "data": b"data_blob"}, + "image": { + "mime_type": "mime_type_value", + "data": b"data_blob", + "alt_text": "alt_text_value", + }, "tool_call": { "tool": "tool_value", "toolset_tool": { @@ -35965,6 +36755,8 @@ def test_create_example_rest_call_success(request_type): "id": "id_value", "display_name": "display_name_value", "args": {}, + "parent_tool_call_id": "parent_tool_call_id_value", + "agent_name": "agent_name_value", }, "tool_response": { "tool": "tool_value", @@ -35972,6 +36764,8 @@ def test_create_example_rest_call_success(request_type): "id": "id_value", "display_name": "display_name_value", "response": {}, + "parent_tool_call_id": "parent_tool_call_id_value", + "agent_name": "agent_name_value", }, "agent_transfer": { "target_agent": "target_agent_value", @@ -36218,7 +37012,11 @@ def test_update_example_rest_call_success(request_type): "transcript": "transcript_value", "blob": {"mime_type": "mime_type_value", "data": b"data_blob"}, "payload": {"fields": {}}, - "image": {"mime_type": "mime_type_value", "data": b"data_blob"}, + "image": { + "mime_type": "mime_type_value", + "data": b"data_blob", + "alt_text": "alt_text_value", + }, "tool_call": { "tool": "tool_value", "toolset_tool": { @@ -36228,6 +37026,8 @@ def test_update_example_rest_call_success(request_type): "id": "id_value", "display_name": "display_name_value", "args": {}, + "parent_tool_call_id": "parent_tool_call_id_value", + "agent_name": "agent_name_value", }, "tool_response": { "tool": "tool_value", @@ -36235,6 +37035,8 @@ def test_update_example_rest_call_success(request_type): "id": "id_value", "display_name": "display_name_value", "response": {}, + "parent_tool_call_id": "parent_tool_call_id_value", + "agent_name": "agent_name_value", }, "agent_transfer": { "target_agent": "target_agent_value", @@ -36714,6 +37516,7 @@ def test_get_tool_rest_call_success(request_type): execution_type=common.ExecutionType.SYNCHRONOUS, etag="etag_value", generated_summary="generated_summary_value", + read_only=True, ) # Wrap the value into a proper Response obj @@ -36735,6 +37538,7 @@ def test_get_tool_rest_call_success(request_type): assert response.execution_type == common.ExecutionType.SYNCHRONOUS assert response.etag == "etag_value" assert response.generated_summary == "generated_summary_value" + assert response.read_only is True @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -37520,6 +38324,7 @@ def test_create_tool_rest_call_success(request_type): "model_settings": { "model": "model_value", "temperature": 0.1198, + "thinking_level": 1, }, "prompt": "prompt_value", "disabled": True, @@ -37533,6 +38338,7 @@ def test_create_tool_rest_call_success(request_type): "grounding_level": 0.16040000000000001, "disabled": True, }, + "snippets_config": {"enable_snippets": True, "max_snippets": 1307}, } ], "filter_parameter_behavior": 2, @@ -37614,6 +38420,10 @@ def test_create_tool_rest_call_success(request_type): } ], }, + "api_authentication": {}, + "stateful_agent": True, + "input_variable_mapping": {}, + "output_variable_mapping": {}, }, "name": "name_value", "display_name": "display_name_value", @@ -37627,6 +38437,7 @@ def test_create_tool_rest_call_success(request_type): "code_block": {"python_code": "python_code_value"}, "enable_fake_mode": True, }, + "read_only": True, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -37706,6 +38517,7 @@ def get_message_fields(field): execution_type=common.ExecutionType.SYNCHRONOUS, etag="etag_value", generated_summary="generated_summary_value", + read_only=True, ) # Wrap the value into a proper Response obj @@ -37727,6 +38539,7 @@ def get_message_fields(field): assert response.execution_type == common.ExecutionType.SYNCHRONOUS assert response.etag == "etag_value" assert response.generated_summary == "generated_summary_value" + assert response.read_only is True @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -37995,6 +38808,7 @@ def test_update_tool_rest_call_success(request_type): "model_settings": { "model": "model_value", "temperature": 0.1198, + "thinking_level": 1, }, "prompt": "prompt_value", "disabled": True, @@ -38008,6 +38822,7 @@ def test_update_tool_rest_call_success(request_type): "grounding_level": 0.16040000000000001, "disabled": True, }, + "snippets_config": {"enable_snippets": True, "max_snippets": 1307}, } ], "filter_parameter_behavior": 2, @@ -38089,6 +38904,10 @@ def test_update_tool_rest_call_success(request_type): } ], }, + "api_authentication": {}, + "stateful_agent": True, + "input_variable_mapping": {}, + "output_variable_mapping": {}, }, "name": "projects/sample1/locations/sample2/apps/sample3/tools/sample4", "display_name": "display_name_value", @@ -38102,6 +38921,7 @@ def test_update_tool_rest_call_success(request_type): "code_block": {"python_code": "python_code_value"}, "enable_fake_mode": True, }, + "read_only": True, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -38181,6 +39001,7 @@ def get_message_fields(field): execution_type=common.ExecutionType.SYNCHRONOUS, etag="etag_value", generated_summary="generated_summary_value", + read_only=True, ) # Wrap the value into a proper Response obj @@ -38202,6 +39023,7 @@ def get_message_fields(field): assert response.execution_type == common.ExecutionType.SYNCHRONOUS assert response.etag == "etag_value" assert response.generated_summary == "generated_summary_value" + assert response.read_only is True @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -38708,6 +39530,10 @@ def test_create_guardrail_rest_call_success(request_type): ], "match_type": 1, "disregard_diacritics": True, + "sensitive_words_exemptions": [ + "sensitive_words_exemptions_value1", + "sensitive_words_exemptions_value2", + ], }, "llm_prompt_security": { "default_settings": { @@ -38715,7 +39541,11 @@ def test_create_guardrail_rest_call_success(request_type): }, "custom_policy": { "max_conversation_messages": 2679, - "model_settings": {"model": "model_value", "temperature": 0.1198}, + "model_settings": { + "model": "model_value", + "temperature": 0.1198, + "thinking_level": 1, + }, "prompt": "prompt_value", "policy_scope": 1, "fail_open": True, @@ -38736,6 +39566,7 @@ def test_create_guardrail_rest_call_success(request_type): "before_model_callback": {}, "after_model_callback": {}, }, + "supervisor": {"type_": 1, "detection_mode": 1}, "name": "name_value", "display_name": "display_name_value", "description": "description_value", @@ -38978,6 +39809,10 @@ def test_update_guardrail_rest_call_success(request_type): ], "match_type": 1, "disregard_diacritics": True, + "sensitive_words_exemptions": [ + "sensitive_words_exemptions_value1", + "sensitive_words_exemptions_value2", + ], }, "llm_prompt_security": { "default_settings": { @@ -38985,7 +39820,11 @@ def test_update_guardrail_rest_call_success(request_type): }, "custom_policy": { "max_conversation_messages": 2679, - "model_settings": {"model": "model_value", "temperature": 0.1198}, + "model_settings": { + "model": "model_value", + "temperature": 0.1198, + "thinking_level": 1, + }, "prompt": "prompt_value", "policy_scope": 1, "fail_open": True, @@ -39006,6 +39845,7 @@ def test_update_guardrail_rest_call_success(request_type): "before_model_callback": {}, "after_model_callback": {}, }, + "supervisor": {"type_": 1, "detection_mode": 1}, "name": "projects/sample1/locations/sample2/apps/sample3/guardrails/sample4", "display_name": "display_name_value", "description": "description_value", @@ -39491,6 +40331,7 @@ def test_get_deployment_rest_call_success(request_type): display_name="display_name_value", app_version="app_version_value", etag="etag_value", + modality=deployment.Deployment.Modality.MODALITY_TEXT, ) # Wrap the value into a proper Response obj @@ -39511,6 +40352,7 @@ def test_get_deployment_rest_call_success(request_type): assert response.display_name == "display_name_value" assert response.app_version == "app_version_value" assert response.etag == "etag_value" + assert response.modality == deployment.Deployment.Modality.MODALITY_TEXT @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -39684,285 +40526,14 @@ def test_create_deployment_rest_call_success(request_type): "auth_code": "auth_code_value", "conversation_profile_id": "conversation_profile_id_value", }, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = agent_service.CreateDeploymentRequest.meta.fields["deployment"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["deployment"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["deployment"][field])): - del request_init["deployment"][field][i][subfield] - else: - del request_init["deployment"][field][subfield] - 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 = gcc_deployment.Deployment( - name="name_value", - display_name="display_name_value", - app_version="app_version_value", - etag="etag_value", - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = gcc_deployment.Deployment.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_deployment(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcc_deployment.Deployment) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.app_version == "app_version_value" - assert response.etag == "etag_value" - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_deployment_rest_interceptors(null_interceptor): - transport = transports.AgentServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.AgentServiceRestInterceptor(), - ) - client = AgentServiceClient(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.AgentServiceRestInterceptor, "post_create_deployment" - ) as post, - mock.patch.object( - transports.AgentServiceRestInterceptor, - "post_create_deployment_with_metadata", - ) as post_with_metadata, - mock.patch.object( - transports.AgentServiceRestInterceptor, "pre_create_deployment" - ) as pre, - ): - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = agent_service.CreateDeploymentRequest.pb( - agent_service.CreateDeploymentRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = gcc_deployment.Deployment.to_json(gcc_deployment.Deployment()) - req.return_value.content = return_value - - request = agent_service.CreateDeploymentRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcc_deployment.Deployment() - post_with_metadata.return_value = gcc_deployment.Deployment(), metadata - - client.create_deployment( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_update_deployment_rest_bad_request( - request_type=agent_service.UpdateDeploymentRequest, -): - client = AgentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # send a request that will satisfy transcoding - request_init = { - "deployment": { - "name": "projects/sample1/locations/sample2/apps/sample3/deployments/sample4" - } - } - 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 = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_deployment(request) - - -@pytest.mark.parametrize( - "request_type", - [ - agent_service.UpdateDeploymentRequest, - dict, - ], -) -def test_update_deployment_rest_call_success(request_type): - client = AgentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = { - "deployment": { - "name": "projects/sample1/locations/sample2/apps/sample3/deployments/sample4" - } - } - request_init["deployment"] = { - "name": "projects/sample1/locations/sample2/apps/sample3/deployments/sample4", - "display_name": "display_name_value", - "app_version": "app_version_value", - "channel_profile": { - "profile_id": "profile_id_value", - "channel_type": 2, - "persona_property": {"persona": 1}, - "disable_dtmf": True, - "disable_barge_in_control": True, - "web_widget_config": { - "modality": 1, - "theme": 1, - "web_widget_title": "web_widget_title_value", - "security_settings": { - "enable_public_access": True, - "enable_origin_check": True, - "allowed_origins": [ - "allowed_origins_value1", - "allowed_origins_value2", - ], - "enable_recaptcha": True, - }, - }, - "noise_suppression_level": "noise_suppression_level_value", - "whatsapp_config": { - "waba_id": "waba_id_value", - "phone_number_id": "phone_number_id_value", - "phone_number": "phone_number_value", - "display_name": "display_name_value", - "thumbnail_url": "thumbnail_url_value", - "description": "description_value", - }, - "instagram_config": { - "instagram_account_id": "instagram_account_id_value", - "display_name": "display_name_value", - "thumbnail_url": "thumbnail_url_value", - "description": "description_value", - }, - }, - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "etag": "etag_value", - "experiment_config": { - "version_release": { - "state": 1, - "traffic_allocations": [ - { - "id": "id_value", - "traffic_percentage": 1884, - "app_version": "app_version_value", - } - ], - } - }, - "whatsapp_credentials": { - "auth_code": "auth_code_value", - "pin": "pin_value", - "phone_number": "phone_number_value", - "business_account_id": "business_account_id_value", - "waba_id": "waba_id_value", - "conversation_profile_id": "conversation_profile_id_value", + "model_settings": { + "model": "model_value", + "temperature": 0.1198, + "thinking_level": 1, }, - "instagram_credentials": { - "auth_code": "auth_code_value", - "conversation_profile_id": "conversation_profile_id_value", + "modality": 1, + "agent_registry_deployment": { + "agent_registry_service_name": "agent_registry_service_name_value" }, } # The version of a generated dependency at test runtime may differ from the version used during generation. @@ -39970,7 +40541,7 @@ def test_update_deployment_rest_call_success(request_type): # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = agent_service.UpdateDeploymentRequest.meta.fields["deployment"] + test_field = agent_service.CreateDeploymentRequest.meta.fields["deployment"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -40042,6 +40613,298 @@ def get_message_fields(field): display_name="display_name_value", app_version="app_version_value", etag="etag_value", + modality=gcc_deployment.Deployment.Modality.MODALITY_TEXT, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcc_deployment.Deployment.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_deployment(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_deployment.Deployment) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.app_version == "app_version_value" + assert response.etag == "etag_value" + assert response.modality == gcc_deployment.Deployment.Modality.MODALITY_TEXT + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_deployment_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(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.AgentServiceRestInterceptor, "post_create_deployment" + ) as post, + mock.patch.object( + transports.AgentServiceRestInterceptor, + "post_create_deployment_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_create_deployment" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.CreateDeploymentRequest.pb( + agent_service.CreateDeploymentRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gcc_deployment.Deployment.to_json(gcc_deployment.Deployment()) + req.return_value.content = return_value + + request = agent_service.CreateDeploymentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcc_deployment.Deployment() + post_with_metadata.return_value = gcc_deployment.Deployment(), metadata + + client.create_deployment( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_deployment_rest_bad_request( + request_type=agent_service.UpdateDeploymentRequest, +): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "deployment": { + "name": "projects/sample1/locations/sample2/apps/sample3/deployments/sample4" + } + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_deployment(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.UpdateDeploymentRequest, + dict, + ], +) +def test_update_deployment_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "deployment": { + "name": "projects/sample1/locations/sample2/apps/sample3/deployments/sample4" + } + } + request_init["deployment"] = { + "name": "projects/sample1/locations/sample2/apps/sample3/deployments/sample4", + "display_name": "display_name_value", + "app_version": "app_version_value", + "channel_profile": { + "profile_id": "profile_id_value", + "channel_type": 2, + "persona_property": {"persona": 1}, + "disable_dtmf": True, + "disable_barge_in_control": True, + "web_widget_config": { + "modality": 1, + "theme": 1, + "web_widget_title": "web_widget_title_value", + "security_settings": { + "enable_public_access": True, + "enable_origin_check": True, + "allowed_origins": [ + "allowed_origins_value1", + "allowed_origins_value2", + ], + "enable_recaptcha": True, + }, + }, + "noise_suppression_level": "noise_suppression_level_value", + "whatsapp_config": { + "waba_id": "waba_id_value", + "phone_number_id": "phone_number_id_value", + "phone_number": "phone_number_value", + "display_name": "display_name_value", + "thumbnail_url": "thumbnail_url_value", + "description": "description_value", + }, + "instagram_config": { + "instagram_account_id": "instagram_account_id_value", + "display_name": "display_name_value", + "thumbnail_url": "thumbnail_url_value", + "description": "description_value", + }, + }, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "etag": "etag_value", + "experiment_config": { + "version_release": { + "state": 1, + "traffic_allocations": [ + { + "id": "id_value", + "traffic_percentage": 1884, + "app_version": "app_version_value", + } + ], + } + }, + "whatsapp_credentials": { + "auth_code": "auth_code_value", + "pin": "pin_value", + "phone_number": "phone_number_value", + "business_account_id": "business_account_id_value", + "waba_id": "waba_id_value", + "conversation_profile_id": "conversation_profile_id_value", + }, + "instagram_credentials": { + "auth_code": "auth_code_value", + "conversation_profile_id": "conversation_profile_id_value", + }, + "model_settings": { + "model": "model_value", + "temperature": 0.1198, + "thinking_level": 1, + }, + "modality": 1, + "agent_registry_deployment": { + "agent_registry_service_name": "agent_registry_service_name_value" + }, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = agent_service.UpdateDeploymentRequest.meta.fields["deployment"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["deployment"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["deployment"][field])): + del request_init["deployment"][field][i][subfield] + else: + del request_init["deployment"][field][subfield] + 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 = gcc_deployment.Deployment( + name="name_value", + display_name="display_name_value", + app_version="app_version_value", + etag="etag_value", + modality=gcc_deployment.Deployment.Modality.MODALITY_TEXT, ) # Wrap the value into a proper Response obj @@ -40062,6 +40925,7 @@ def get_message_fields(field): assert response.display_name == "display_name_value" assert response.app_version == "app_version_value" assert response.etag == "etag_value" + assert response.modality == gcc_deployment.Deployment.Modality.MODALITY_TEXT @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -41595,6 +42459,990 @@ def test_create_app_version_rest_call_success(request_type): "description": "description_value", "creator": "creator_value", "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "snapshot": { + "app": { + "name": "name_value", + "display_name": "display_name_value", + "description": "description_value", + "pinned": True, + "root_agent": "root_agent_value", + "language_settings": { + "default_language_code": "default_language_code_value", + "supported_language_codes": [ + "supported_language_codes_value1", + "supported_language_codes_value2", + ], + "enable_multilingual_support": True, + "fallback_action": "fallback_action_value", + }, + "time_zone_settings": {"time_zone": "time_zone_value"}, + "audio_processing_config": { + "synthesize_speech_configs": {}, + "barge_in_config": { + "disable_barge_in": True, + "barge_in_awareness": True, + }, + "inactivity_timeout": {"seconds": 751, "nanos": 543}, + "ambient_sound_config": { + "prebuilt_ambient_noise": 1, + "gcs_uri": "gcs_uri_value", + "prebuilt_ambient_sound": "prebuilt_ambient_sound_value", + "volume_gain_db": 0.1467, + }, + "custom_voice_samples": [ + { + "name": "name_value", + "voice_sample_gcs_uri": "voice_sample_gcs_uri_value", + "consent_audio_gcs_uri": "consent_audio_gcs_uri_value", + "voice_instruction": "voice_instruction_value", + "preview_audio_content": b"preview_audio_content_blob", + "preview_text": "preview_text_value", + "warnings": [{"message": "message_value", "type_": 1}], + "voice_instruction_mode": 1, + } + ], + }, + "logging_settings": { + "redaction_config": { + "enable_redaction": True, + "inspect_template": "inspect_template_value", + "deidentify_template": "deidentify_template_value", + }, + "audio_recording_config": { + "gcs_bucket": "gcs_bucket_value", + "gcs_path_prefix": "gcs_path_prefix_value", + }, + "unredacted_audio_recording_config": {}, + "bigquery_export_settings": { + "enabled": True, + "project": "project_value", + "dataset": "dataset_value", + }, + "unredacted_bigquery_export_settings": {}, + "cloud_logging_settings": {"enable_cloud_logging": True}, + "conversation_logging_settings": { + "disable_conversation_logging": True, + "retention_window": {}, + }, + "evaluation_audio_recording_config": {}, + "metric_analysis_settings": {"llm_metrics_opted_out": True}, + "required_recording_consent": True, + }, + "error_handling_settings": { + "error_handling_strategy": 1, + "fallback_response_config": { + "custom_fallback_messages": {}, + "max_fallback_attempts": 2214, + }, + "end_session_config": {"escalate_session": True}, + }, + "model_settings": { + "model": "model_value", + "temperature": 0.1198, + "thinking_level": 1, + }, + "tool_execution_mode": 1, + "evaluation_metrics_thresholds": { + "golden_evaluation_metrics_thresholds": { + "turn_level_metrics_thresholds": { + "semantic_similarity_success_threshold": 3966, + "overall_tool_invocation_correctness_threshold": 0.4833, + "semantic_similarity_channel": 1, + }, + "expectation_level_metrics_thresholds": { + "tool_invocation_parameter_correctness_threshold": 0.5037 + }, + "tool_matching_settings": {"extra_tool_call_behavior": 1}, + }, + "hallucination_metric_behavior": 1, + "golden_hallucination_metric_behavior": 1, + "scenario_hallucination_metric_behavior": 1, + }, + "variable_declarations": [ + { + "name": "name_value", + "description": "description_value", + "schema": { + "type_": 1, + "properties": {}, + "required": ["required_value1", "required_value2"], + "description": "description_value", + "items": {}, + "nullable": True, + "unique_items": True, + "prefix_items": {}, + "additional_properties": {}, + "any_of": {}, + "enum": ["enum_value1", "enum_value2"], + "default": { + "null_value": 0, + "number_value": 0.1285, + "string_value": "string_value_value", + "bool_value": True, + "struct_value": {"fields": {}}, + "list_value": {"values": {}}, + }, + "ref": "ref_value", + "defs": {}, + "title": "title_value", + "min_items": 965, + "max_items": 967, + "minimum": 0.764, + "maximum": 0.766, + }, + } + ], + "predefined_variable_declarations": {}, + "global_instruction": "global_instruction_value", + "guardrails": ["guardrails_value1", "guardrails_value2"], + "data_store_settings": { + "engines": [{"name": "name_value", "type_": 1}] + }, + "default_channel_profile": { + "profile_id": "profile_id_value", + "channel_type": 2, + "persona_property": {"persona": 1}, + "disable_dtmf": True, + "disable_barge_in_control": True, + "web_widget_config": { + "modality": 1, + "theme": 1, + "web_widget_title": "web_widget_title_value", + "security_settings": { + "enable_public_access": True, + "enable_origin_check": True, + "allowed_origins": [ + "allowed_origins_value1", + "allowed_origins_value2", + ], + "enable_recaptcha": True, + }, + }, + "noise_suppression_level": "noise_suppression_level_value", + "whatsapp_config": { + "waba_id": "waba_id_value", + "phone_number_id": "phone_number_id_value", + "phone_number": "phone_number_value", + "display_name": "display_name_value", + "thumbnail_url": "thumbnail_url_value", + "description": "description_value", + }, + "instagram_config": { + "instagram_account_id": "instagram_account_id_value", + "display_name": "display_name_value", + "thumbnail_url": "thumbnail_url_value", + "description": "description_value", + }, + }, + "metadata": {}, + "create_time": {}, + "update_time": {}, + "etag": "etag_value", + "deployment_count": 1737, + "client_certificate_settings": { + "tls_certificate": "tls_certificate_value", + "private_key": "private_key_value", + "passphrase": "passphrase_value", + }, + "vpc_sc_settings": { + "allowed_origins": [ + "allowed_origins_value1", + "allowed_origins_value2", + ] + }, + "locked": True, + "evaluation_personas": [ + { + "name": "name_value", + "description": "description_value", + "display_name": "display_name_value", + "personality": "personality_value", + "speech_config": { + "speaking_rate": 0.1373, + "environment": 3, + "voice_id": "voice_id_value", + }, + } + ], + "evaluation_settings": { + "scenario_conversation_initiator": 1, + "golden_run_method": 1, + "golden_evaluation_tool_call_behaviour": 1, + "scenario_evaluation_tool_call_behaviour": 1, + "metrics_config": { + "golden_metrics_config": { + "semantic_similarity_metrics_config": { + "enable_semantic_similarity_metrics": True + }, + "tool_correctness_metrics_config": { + "enable_tool_correctness_metrics": True + }, + "step_tool_correctness_metrics_config": {}, + }, + "scenario_metrics_config": { + "user_goal_met_metrics_config": { + "enable_user_goal_met_metrics": True + }, + "expectations_met_metrics_config": { + "enable_expectations_met_metrics": True + }, + }, + }, + "scenario_execution_mode": 1, + "evaluation_run_caching_settings": {"run_caching_mode": 1}, + }, + "validation_errors": [ + "validation_errors_value1", + "validation_errors_value2", + ], + "dashboard_settings": {"default_dashboard": "default_dashboard_value"}, + }, + "agents": [ + { + "llm_agent": {}, + "remote_dialogflow_agent": { + "agent": "agent_value", + "flow_id": "flow_id_value", + "environment_id": "environment_id_value", + "input_variable_mapping": {}, + "output_variable_mapping": {}, + "respect_response_interruption_settings": True, + "language_code_variable": "language_code_variable_value", + }, + "remote_a2a_agent": { + "a2a_config": { + "agent_card": { + "name": "name_value", + "description": "description_value", + "supported_interfaces": [ + { + "url": "url_value", + "protocol_binding": "protocol_binding_value", + "tenant": "tenant_value", + "protocol_version": "protocol_version_value", + } + ], + "version": "version_value", + "skills": [ + { + "id": "id_value", + "name": "name_value", + "description": "description_value", + "tags": ["tags_value1", "tags_value2"], + "examples": [ + "examples_value1", + "examples_value2", + ], + "input_modes": [ + "input_modes_value1", + "input_modes_value2", + ], + "output_modes": [ + "output_modes_value1", + "output_modes_value2", + ], + } + ], + }, + "agent_registry": "agent_registry_value", + "api_authentication": { + "api_key_config": { + "key_name": "key_name_value", + "api_key_secret_version": "api_key_secret_version_value", + "request_location": 1, + }, + "oauth_config": { + "oauth_grant_type": 1, + "client_id": "client_id_value", + "client_secret_version": "client_secret_version_value", + "token_endpoint": "token_endpoint_value", + "scopes": ["scopes_value1", "scopes_value2"], + }, + "service_agent_id_token_auth_config": {}, + "service_account_auth_config": { + "service_account": "service_account_value", + "scopes": ["scopes_value1", "scopes_value2"], + }, + "bearer_token_config": {"token": "token_value"}, + }, + "input_variable_mapping": {}, + "output_variable_mapping": {}, + "streaming_enabled": True, + "context_id": "context_id_value", + } + }, + "name": "name_value", + "display_name": "display_name_value", + "description": "description_value", + "model_settings": {}, + "instruction": "instruction_value", + "tools": ["tools_value1", "tools_value2"], + "child_agents": ["child_agents_value1", "child_agents_value2"], + "before_agent_callbacks": [ + { + "python_code": "python_code_value", + "description": "description_value", + "disabled": True, + "proactive_execution_enabled": True, + } + ], + "after_agent_callbacks": {}, + "before_model_callbacks": {}, + "after_model_callbacks": {}, + "before_tool_callbacks": {}, + "after_tool_callbacks": {}, + "create_time": {}, + "update_time": {}, + "guardrails": ["guardrails_value1", "guardrails_value2"], + "etag": "etag_value", + "toolsets": [ + { + "toolset": "toolset_value", + "tool_ids": ["tool_ids_value1", "tool_ids_value2"], + } + ], + "generated_summary": "generated_summary_value", + "transfer_rules": [ + { + "deterministic_transfer": { + "expression_condition": { + "expression": "expression_value" + }, + "python_code_condition": { + "python_code": "python_code_value" + }, + }, + "disable_planner_transfer": {"expression_condition": {}}, + "child_agent": "child_agent_value", + "direction": 1, + } + ], + "validation_errors": [ + "validation_errors_value1", + "validation_errors_value2", + ], + } + ], + "tools": [ + { + "client_function": { + "name": "name_value", + "description": "description_value", + "parameters": {}, + "response": {}, + }, + "open_api_tool": { + "open_api_schema": "open_api_schema_value", + "name": "name_value", + "description": "description_value", + "api_authentication": {}, + "tls_config": { + "ca_certs": [ + { + "display_name": "display_name_value", + "cert": b"cert_blob", + } + ] + }, + "service_directory_config": {"service": "service_value"}, + "ignore_unknown_fields_": True, + "url": "url_value", + }, + "google_search_tool": { + "name": "name_value", + "description": "description_value", + "context_urls": ["context_urls_value1", "context_urls_value2"], + "preferred_domains": [ + "preferred_domains_value1", + "preferred_domains_value2", + ], + "exclude_domains": [ + "exclude_domains_value1", + "exclude_domains_value2", + ], + "prompt_config": { + "text_prompt": "text_prompt_value", + "voice_prompt": "voice_prompt_value", + }, + }, + "connector_tool": { + "connection": "connection_value", + "action": { + "connection_action_id": "connection_action_id_value", + "entity_operation": { + "entity_id": "entity_id_value", + "operation": 1, + }, + "input_fields": [ + "input_fields_value1", + "input_fields_value2", + ], + "output_fields": [ + "output_fields_value1", + "output_fields_value2", + ], + }, + "auth_config": { + "oauth2_auth_code_config": { + "oauth_token": "oauth_token_value" + }, + "oauth2_jwt_bearer_config": { + "issuer": "issuer_value", + "subject": "subject_value", + "client_key": "client_key_value", + }, + }, + "name": "name_value", + "description": "description_value", + }, + "data_store_tool": { + "data_store_source": { + "filter": "filter_value", + "data_store": { + "name": "name_value", + "type_": 1, + "document_processing_mode": 1, + "display_name": "display_name_value", + "create_time": {}, + "connector_config": { + "collection": "collection_value", + "collection_display_name": "collection_display_name_value", + "data_source": "data_source_value", + }, + }, + }, + "engine_source": { + "engine": "engine_value", + "data_store_sources": {}, + "filter": "filter_value", + }, + "name": "name_value", + "description": "description_value", + "boost_specs": [ + { + "data_stores": [ + "data_stores_value1", + "data_stores_value2", + ], + "spec": [ + { + "condition_boost_specs": [ + { + "condition": "condition_value", + "boost": 0.551, + "boost_control_spec": { + "field_name": "field_name_value", + "attribute_type": 1, + "interpolation_type": 1, + "control_points": [ + { + "attribute_value": "attribute_value_value", + "boost_amount": 0.1306, + } + ], + }, + } + ] + } + ], + } + ], + "modality_configs": [ + { + "modality_type": 1, + "rewriter_config": { + "model_settings": {}, + "prompt": "prompt_value", + "disabled": True, + }, + "summarization_config": { + "model_settings": {}, + "prompt": "prompt_value", + "disabled": True, + }, + "grounding_config": { + "grounding_level": 0.16040000000000001, + "disabled": True, + }, + "snippets_config": { + "enable_snippets": True, + "max_snippets": 1307, + }, + } + ], + "filter_parameter_behavior": 2, + }, + "python_function": { + "name": "name_value", + "python_code": "python_code_value", + "description": "description_value", + "service_directory_config": {}, + }, + "mcp_tool": { + "name": "name_value", + "name_override": "name_override_value", + "description": "description_value", + "input_schema": {}, + "output_schema": {}, + "server_address": "server_address_value", + "api_authentication": {}, + "tls_config": {}, + "service_directory_config": {}, + "custom_headers": {}, + "state": 1, + }, + "file_search_tool": { + "corpus_type": 1, + "name": "name_value", + "description": "description_value", + "file_corpus": "file_corpus_value", + }, + "system_tool": { + "name": "name_value", + "description": "description_value", + }, + "agent_tool": { + "name": "name_value", + "description": "description_value", + "agent": "agent_value", + }, + "widget_tool": { + "parameters": {}, + "name": "name_value", + "description": "description_value", + "widget_type": 1, + "ui_config": {}, + "data_mapping": { + "source_tool_name": "source_tool_name_value", + "field_mappings": {}, + "python_function": {}, + "mode": 1, + "python_script": "python_script_value", + }, + "text_response_config": { + "type_": 1, + "static_text": "static_text_value", + "text_response_instruction": "text_response_instruction_value", + }, + }, + "remote_agent_tool": { + "name": "name_value", + "description": "description_value", + "agent_card": {}, + "api_authentication": {}, + "stateful_agent": True, + "input_variable_mapping": {}, + "output_variable_mapping": {}, + }, + "name": "name_value", + "display_name": "display_name_value", + "execution_type": 1, + "timeout": {}, + "create_time": {}, + "update_time": {}, + "etag": "etag_value", + "generated_summary": "generated_summary_value", + "tool_fake_config": { + "code_block": {"python_code": "python_code_value"}, + "enable_fake_mode": True, + }, + "read_only": True, + } + ], + "examples": [ + { + "name": "name_value", + "display_name": "display_name_value", + "description": "description_value", + "entry_agent": "entry_agent_value", + "messages": [ + { + "role": "role_value", + "chunks": [ + { + "text": "text_value", + "transcript": "transcript_value", + "blob": { + "mime_type": "mime_type_value", + "data": b"data_blob", + }, + "payload": {}, + "image": { + "mime_type": "mime_type_value", + "data": b"data_blob", + "alt_text": "alt_text_value", + }, + "tool_call": { + "tool": "tool_value", + "toolset_tool": { + "toolset": "toolset_value", + "tool_id": "tool_id_value", + }, + "id": "id_value", + "display_name": "display_name_value", + "args": {}, + "parent_tool_call_id": "parent_tool_call_id_value", + "agent_name": "agent_name_value", + }, + "tool_response": { + "tool": "tool_value", + "toolset_tool": {}, + "id": "id_value", + "display_name": "display_name_value", + "response": {}, + "parent_tool_call_id": "parent_tool_call_id_value", + "agent_name": "agent_name_value", + }, + "agent_transfer": { + "target_agent": "target_agent_value", + "display_name": "display_name_value", + }, + "updated_variables": {}, + "default_variables": {}, + } + ], + "event_time": {}, + } + ], + "create_time": {}, + "update_time": {}, + "invalid": True, + "etag": "etag_value", + } + ], + "guardrails": [ + { + "content_filter": { + "banned_contents": [ + "banned_contents_value1", + "banned_contents_value2", + ], + "banned_contents_in_user_input": [ + "banned_contents_in_user_input_value1", + "banned_contents_in_user_input_value2", + ], + "banned_contents_in_agent_response": [ + "banned_contents_in_agent_response_value1", + "banned_contents_in_agent_response_value2", + ], + "match_type": 1, + "disregard_diacritics": True, + "sensitive_words_exemptions": [ + "sensitive_words_exemptions_value1", + "sensitive_words_exemptions_value2", + ], + }, + "llm_prompt_security": { + "default_settings": { + "default_prompt_template": "default_prompt_template_value" + }, + "custom_policy": { + "max_conversation_messages": 2679, + "model_settings": {}, + "prompt": "prompt_value", + "policy_scope": 1, + "fail_open": True, + "allow_short_utterance": True, + }, + "fail_open": True, + }, + "llm_policy": {}, + "model_safety": { + "safety_settings": [{"category": 1, "threshold": 1}] + }, + "code_callback": { + "before_agent_callback": {}, + "after_agent_callback": {}, + "before_model_callback": {}, + "after_model_callback": {}, + }, + "supervisor": {"type_": 1, "detection_mode": 1}, + "name": "name_value", + "display_name": "display_name_value", + "description": "description_value", + "enabled": True, + "action": { + "respond_immediately": { + "responses": [{"text": "text_value", "disabled": True}] + }, + "transfer_agent": {"agent": "agent_value"}, + "generative_answer": {"prompt": "prompt_value"}, + }, + "create_time": {}, + "update_time": {}, + "etag": "etag_value", + } + ], + "toolsets": [ + { + "mcp_toolset": { + "server_address": "server_address_value", + "api_authentication": {}, + "service_directory_config": {}, + "tls_config": {}, + "custom_headers": {}, + "tool_overrides": [ + { + "tool": "tool_value", + "name_override": "name_override_value", + "description_override": "description_override_value", + "snapshot": { + "description": "description_value", + "input_schema": {}, + "output_schema": {}, + }, + } + ], + }, + "open_api_toolset": { + "open_api_schema": "open_api_schema_value", + "api_authentication": {}, + "tls_config": {}, + "service_directory_config": {}, + "ignore_unknown_fields_": True, + "url": "url_value", + }, + "connector_toolset": { + "connection": "connection_value", + "auth_config": {}, + "connector_actions": {}, + }, + "name": "name_value", + "display_name": "display_name_value", + "description": "description_value", + "timeout": {}, + "create_time": {}, + "update_time": {}, + "etag": "etag_value", + "execution_type": 1, + "tool_fake_config": {}, + } + ], + }, + "etag": "etag_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = agent_service.CreateAppVersionRequest.meta.fields["app_version"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["app_version"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["app_version"][field])): + del request_init["app_version"][field][i][subfield] + else: + del request_init["app_version"][field][subfield] + 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 = gcc_app_version.AppVersion( + name="name_value", + display_name="display_name_value", + description="description_value", + creator="creator_value", + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcc_app_version.AppVersion.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_app_version(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_app_version.AppVersion) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.creator == "creator_value" + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_app_version_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(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.AgentServiceRestInterceptor, "post_create_app_version" + ) as post, + mock.patch.object( + transports.AgentServiceRestInterceptor, + "post_create_app_version_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_create_app_version" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.CreateAppVersionRequest.pb( + agent_service.CreateAppVersionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gcc_app_version.AppVersion.to_json(gcc_app_version.AppVersion()) + req.return_value.content = return_value + + request = agent_service.CreateAppVersionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcc_app_version.AppVersion() + post_with_metadata.return_value = gcc_app_version.AppVersion(), metadata + + client.create_app_version( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_app_version_rest_bad_request( + request_type=agent_service.UpdateAppVersionRequest, +): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "app_version": { + "name": "projects/sample1/locations/sample2/apps/sample3/versions/sample4" + } + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_app_version(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.UpdateAppVersionRequest, + dict, + ], +) +def test_update_app_version_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "app_version": { + "name": "projects/sample1/locations/sample2/apps/sample3/versions/sample4" + } + } + request_init["app_version"] = { + "name": "projects/sample1/locations/sample2/apps/sample3/versions/sample4", + "display_name": "display_name_value", + "description": "description_value", + "creator": "creator_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, "snapshot": { "app": { "name": "name_value", @@ -41625,6 +43473,18 @@ def test_create_app_version_rest_call_success(request_type): "prebuilt_ambient_sound": "prebuilt_ambient_sound_value", "volume_gain_db": 0.1467, }, + "custom_voice_samples": [ + { + "name": "name_value", + "voice_sample_gcs_uri": "voice_sample_gcs_uri_value", + "consent_audio_gcs_uri": "consent_audio_gcs_uri_value", + "voice_instruction": "voice_instruction_value", + "preview_audio_content": b"preview_audio_content_blob", + "preview_text": "preview_text_value", + "warnings": [{"message": "message_value", "type_": 1}], + "voice_instruction_mode": 1, + } + ], }, "logging_settings": { "redaction_config": { @@ -41650,6 +43510,7 @@ def test_create_app_version_rest_call_success(request_type): }, "evaluation_audio_recording_config": {}, "metric_analysis_settings": {"llm_metrics_opted_out": True}, + "required_recording_consent": True, }, "error_handling_settings": { "error_handling_strategy": 1, @@ -41659,7 +43520,11 @@ def test_create_app_version_rest_call_success(request_type): }, "end_session_config": {"escalate_session": True}, }, - "model_settings": {"model": "model_value", "temperature": 0.1198}, + "model_settings": { + "model": "model_value", + "temperature": 0.1198, + "thinking_level": 1, + }, "tool_execution_mode": 1, "evaluation_metrics_thresholds": { "golden_evaluation_metrics_thresholds": { @@ -41814,6 +43679,7 @@ def test_create_app_version_rest_call_success(request_type): "validation_errors_value1", "validation_errors_value2", ], + "dashboard_settings": {"default_dashboard": "default_dashboard_value"}, }, "agents": [ { @@ -41827,6 +43693,68 @@ def test_create_app_version_rest_call_success(request_type): "respect_response_interruption_settings": True, "language_code_variable": "language_code_variable_value", }, + "remote_a2a_agent": { + "a2a_config": { + "agent_card": { + "name": "name_value", + "description": "description_value", + "supported_interfaces": [ + { + "url": "url_value", + "protocol_binding": "protocol_binding_value", + "tenant": "tenant_value", + "protocol_version": "protocol_version_value", + } + ], + "version": "version_value", + "skills": [ + { + "id": "id_value", + "name": "name_value", + "description": "description_value", + "tags": ["tags_value1", "tags_value2"], + "examples": [ + "examples_value1", + "examples_value2", + ], + "input_modes": [ + "input_modes_value1", + "input_modes_value2", + ], + "output_modes": [ + "output_modes_value1", + "output_modes_value2", + ], + } + ], + }, + "agent_registry": "agent_registry_value", + "api_authentication": { + "api_key_config": { + "key_name": "key_name_value", + "api_key_secret_version": "api_key_secret_version_value", + "request_location": 1, + }, + "oauth_config": { + "oauth_grant_type": 1, + "client_id": "client_id_value", + "client_secret_version": "client_secret_version_value", + "token_endpoint": "token_endpoint_value", + "scopes": ["scopes_value1", "scopes_value2"], + }, + "service_agent_id_token_auth_config": {}, + "service_account_auth_config": { + "service_account": "service_account_value", + "scopes": ["scopes_value1", "scopes_value2"], + }, + "bearer_token_config": {"token": "token_value"}, + }, + "input_variable_mapping": {}, + "output_variable_mapping": {}, + "streaming_enabled": True, + "context_id": "context_id_value", + } + }, "name": "name_value", "display_name": "display_name_value", "description": "description_value", @@ -41891,26 +43819,7 @@ def test_create_app_version_rest_call_success(request_type): "open_api_schema": "open_api_schema_value", "name": "name_value", "description": "description_value", - "api_authentication": { - "api_key_config": { - "key_name": "key_name_value", - "api_key_secret_version": "api_key_secret_version_value", - "request_location": 1, - }, - "oauth_config": { - "oauth_grant_type": 1, - "client_id": "client_id_value", - "client_secret_version": "client_secret_version_value", - "token_endpoint": "token_endpoint_value", - "scopes": ["scopes_value1", "scopes_value2"], - }, - "service_agent_id_token_auth_config": {}, - "service_account_auth_config": { - "service_account": "service_account_value", - "scopes": ["scopes_value1", "scopes_value2"], - }, - "bearer_token_config": {"token": "token_value"}, - }, + "api_authentication": {}, "tls_config": { "ca_certs": [ { @@ -42039,6 +43948,10 @@ def test_create_app_version_rest_call_success(request_type): "grounding_level": 0.16040000000000001, "disabled": True, }, + "snippets_config": { + "enable_snippets": True, + "max_snippets": 1307, + }, } ], "filter_parameter_behavior": 2, @@ -42099,36 +44012,11 @@ def test_create_app_version_rest_call_success(request_type): "remote_agent_tool": { "name": "name_value", "description": "description_value", - "agent_card": { - "name": "name_value", - "description": "description_value", - "supported_interfaces": [ - { - "url": "url_value", - "protocol_binding": "protocol_binding_value", - "tenant": "tenant_value", - "protocol_version": "protocol_version_value", - } - ], - "version": "version_value", - "skills": [ - { - "id": "id_value", - "name": "name_value", - "description": "description_value", - "tags": ["tags_value1", "tags_value2"], - "examples": ["examples_value1", "examples_value2"], - "input_modes": [ - "input_modes_value1", - "input_modes_value2", - ], - "output_modes": [ - "output_modes_value1", - "output_modes_value2", - ], - } - ], - }, + "agent_card": {}, + "api_authentication": {}, + "stateful_agent": True, + "input_variable_mapping": {}, + "output_variable_mapping": {}, }, "name": "name_value", "display_name": "display_name_value", @@ -42142,6 +44030,7 @@ def test_create_app_version_rest_call_success(request_type): "code_block": {"python_code": "python_code_value"}, "enable_fake_mode": True, }, + "read_only": True, } ], "examples": [ @@ -42165,6 +44054,7 @@ def test_create_app_version_rest_call_success(request_type): "image": { "mime_type": "mime_type_value", "data": b"data_blob", + "alt_text": "alt_text_value", }, "tool_call": { "tool": "tool_value", @@ -42175,6 +44065,8 @@ def test_create_app_version_rest_call_success(request_type): "id": "id_value", "display_name": "display_name_value", "args": {}, + "parent_tool_call_id": "parent_tool_call_id_value", + "agent_name": "agent_name_value", }, "tool_response": { "tool": "tool_value", @@ -42182,6 +44074,8 @@ def test_create_app_version_rest_call_success(request_type): "id": "id_value", "display_name": "display_name_value", "response": {}, + "parent_tool_call_id": "parent_tool_call_id_value", + "agent_name": "agent_name_value", }, "agent_transfer": { "target_agent": "target_agent_value", @@ -42217,6 +44111,10 @@ def test_create_app_version_rest_call_success(request_type): ], "match_type": 1, "disregard_diacritics": True, + "sensitive_words_exemptions": [ + "sensitive_words_exemptions_value1", + "sensitive_words_exemptions_value2", + ], }, "llm_prompt_security": { "default_settings": { @@ -42242,6 +44140,7 @@ def test_create_app_version_rest_call_success(request_type): "before_model_callback": {}, "after_model_callback": {}, }, + "supervisor": {"type_": 1, "detection_mode": 1}, "name": "name_value", "display_name": "display_name_value", "description": "description_value", @@ -42311,7 +44210,7 @@ def test_create_app_version_rest_call_success(request_type): # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = agent_service.CreateAppVersionRequest.meta.fields["app_version"] + test_field = agent_service.UpdateAppVersionRequest.meta.fields["app_version"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -42396,7 +44295,7 @@ def get_message_fields(field): response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_app_version(request) + response = client.update_app_version(request) # Establish that the response is the type that we expect. assert isinstance(response, gcc_app_version.AppVersion) @@ -42408,7 +44307,7 @@ def get_message_fields(field): @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_app_version_rest_interceptors(null_interceptor): +def test_update_app_version_rest_interceptors(null_interceptor): transport = transports.AgentServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -42421,21 +44320,21 @@ def test_create_app_version_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.AgentServiceRestInterceptor, "post_create_app_version" + transports.AgentServiceRestInterceptor, "post_update_app_version" ) as post, mock.patch.object( transports.AgentServiceRestInterceptor, - "post_create_app_version_with_metadata", + "post_update_app_version_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.AgentServiceRestInterceptor, "pre_create_app_version" + transports.AgentServiceRestInterceptor, "pre_update_app_version" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = agent_service.CreateAppVersionRequest.pb( - agent_service.CreateAppVersionRequest() + pb_message = agent_service.UpdateAppVersionRequest.pb( + agent_service.UpdateAppVersionRequest() ) transcode.return_value = { "method": "post", @@ -42450,7 +44349,7 @@ def test_create_app_version_rest_interceptors(null_interceptor): return_value = gcc_app_version.AppVersion.to_json(gcc_app_version.AppVersion()) req.return_value.content = return_value - request = agent_service.CreateAppVersionRequest() + request = agent_service.UpdateAppVersionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -42459,7 +44358,7 @@ def test_create_app_version_rest_interceptors(null_interceptor): post.return_value = gcc_app_version.AppVersion() post_with_metadata.return_value = gcc_app_version.AppVersion(), metadata - client.create_app_version( + client.update_app_version( request, metadata=[ ("key", "val"), @@ -44398,6 +46297,27 @@ def test_create_app_version_empty_call_rest(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_app_version_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_app_version), "__call__" + ) as call: + client.update_app_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.UpdateAppVersionRequest() + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. def test_delete_app_version_empty_call_rest(): @@ -44595,6 +46515,7 @@ def test_agent_service_base_transport(): "list_app_versions", "get_app_version", "create_app_version", + "update_app_version", "delete_app_version", "restore_app_version", "generate_app_resource", @@ -45021,6 +46942,9 @@ def test_agent_service_client_transport_session_collision(transport_name): session1 = client1.transport.create_app_version._session session2 = client2.transport.create_app_version._session assert session1 != session2 + session1 = client1.transport.update_app_version._session + session2 = client2.transport.update_app_version._session + assert session1 != session2 session1 = client1.transport.delete_app_version._session session2 = client2.transport.delete_app_version._session assert session1 != session2 @@ -45222,10 +47146,36 @@ def test_parse_agent_path(): assert expected == actual -def test_app_path(): +def test_agent_registry_service_path(): project = "winkle" location = "nautilus" - app = "scallop" + service = "scallop" + expected = "projects/{project}/locations/{location}/services/{service}".format( + project=project, + location=location, + service=service, + ) + actual = AgentServiceClient.agent_registry_service_path(project, location, service) + assert expected == actual + + +def test_parse_agent_registry_service_path(): + expected = { + "project": "abalone", + "location": "squid", + "service": "clam", + } + path = AgentServiceClient.agent_registry_service_path(**expected) + + # Check that the path construction is reversible. + actual = AgentServiceClient.parse_agent_registry_service_path(path) + assert expected == actual + + +def test_app_path(): + project = "whelk" + location = "octopus" + app = "oyster" expected = "projects/{project}/locations/{location}/apps/{app}".format( project=project, location=location, @@ -45237,9 +47187,9 @@ def test_app_path(): def test_parse_app_path(): expected = { - "project": "abalone", - "location": "squid", - "app": "clam", + "project": "nudibranch", + "location": "cuttlefish", + "app": "mussel", } path = AgentServiceClient.app_path(**expected) @@ -45249,10 +47199,10 @@ def test_parse_app_path(): def test_app_version_path(): - project = "whelk" - location = "octopus" - app = "oyster" - version = "nudibranch" + project = "winkle" + location = "nautilus" + app = "scallop" + version = "abalone" expected = ( "projects/{project}/locations/{location}/apps/{app}/versions/{version}".format( project=project, @@ -45267,10 +47217,10 @@ def test_app_version_path(): def test_parse_app_version_path(): expected = { - "project": "cuttlefish", - "location": "mussel", - "app": "winkle", - "version": "nautilus", + "project": "squid", + "location": "clam", + "app": "whelk", + "version": "octopus", } path = AgentServiceClient.app_version_path(**expected) @@ -45280,10 +47230,10 @@ def test_parse_app_version_path(): def test_changelog_path(): - project = "scallop" - location = "abalone" - app = "squid" - changelog = "clam" + project = "oyster" + location = "nudibranch" + app = "cuttlefish" + changelog = "mussel" expected = "projects/{project}/locations/{location}/apps/{app}/changelogs/{changelog}".format( project=project, location=location, @@ -45296,10 +47246,10 @@ def test_changelog_path(): def test_parse_changelog_path(): expected = { - "project": "whelk", - "location": "octopus", - "app": "oyster", - "changelog": "nudibranch", + "project": "winkle", + "location": "nautilus", + "app": "scallop", + "changelog": "abalone", } path = AgentServiceClient.changelog_path(**expected) @@ -45309,10 +47259,10 @@ def test_parse_changelog_path(): def test_conversation_path(): - project = "cuttlefish" - location = "mussel" - app = "winkle" - conversation = "nautilus" + project = "squid" + location = "clam" + app = "whelk" + conversation = "octopus" expected = "projects/{project}/locations/{location}/apps/{app}/conversations/{conversation}".format( project=project, location=location, @@ -45325,10 +47275,10 @@ def test_conversation_path(): def test_parse_conversation_path(): expected = { - "project": "scallop", - "location": "abalone", - "app": "squid", - "conversation": "clam", + "project": "oyster", + "location": "nudibranch", + "app": "cuttlefish", + "conversation": "mussel", } path = AgentServiceClient.conversation_path(**expected) @@ -45337,6 +47287,32 @@ def test_parse_conversation_path(): assert expected == actual +def test_dashboard_path(): + project = "winkle" + location = "nautilus" + dashboard = "scallop" + expected = "projects/{project}/locations/{location}/dashboards/{dashboard}".format( + project=project, + location=location, + dashboard=dashboard, + ) + actual = AgentServiceClient.dashboard_path(project, location, dashboard) + assert expected == actual + + +def test_parse_dashboard_path(): + expected = { + "project": "abalone", + "location": "squid", + "dashboard": "clam", + } + path = AgentServiceClient.dashboard_path(**expected) + + # Check that the path construction is reversible. + actual = AgentServiceClient.parse_dashboard_path(path) + assert expected == actual + + def test_dataset_path(): project = "whelk" location = "octopus" diff --git a/packages/google-cloud-ces/tests/unit/gapic/ces_v1beta/test_assistant_service.py b/packages/google-cloud-ces/tests/unit/gapic/ces_v1beta/test_assistant_service.py new file mode 100644 index 000000000000..92d6003a22f3 --- /dev/null +++ b/packages/google-cloud-ces/tests/unit/gapic/ces_v1beta/test_assistant_service.py @@ -0,0 +1,7747 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +import asyncio +import json +import math +import os +from collections.abc import AsyncIterable, Iterable, Mapping, Sequence +from unittest import mock +from unittest.mock import AsyncMock + +import grpc +import pytest +from google.api_core import api_core_version +from google.protobuf import json_format +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +import google.auth +import google.protobuf.struct_pb2 as struct_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.api_core import ( + client_options, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + path_template, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account + +from google.cloud.ces_v1beta.services.assistant_service import ( + AssistantServiceAsyncClient, + AssistantServiceClient, + pagers, + transports, +) +from google.cloud.ces_v1beta.types import assistant_service, common + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +@pytest.fixture(autouse=True) +def disable_mtls_env(): + with mock.patch.dict( + os.environ, + { + "GOOGLE_API_USE_CLIENT_CERTIFICATE": "false", + "CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE": "false", + }, + ): + yield + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +@pytest.fixture(autouse=True) +def set_event_loop(): + try: + asyncio.get_running_loop() + yield + except RuntimeError: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + yield + finally: + loop.close() + asyncio.set_event_loop(None) + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert AssistantServiceClient._get_client_cert_source(None, False) is None + assert ( + AssistantServiceClient._get_client_cert_source(mock_provided_cert_source, False) + is None + ) + assert ( + AssistantServiceClient._get_client_cert_source(mock_provided_cert_source, True) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + AssistantServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + AssistantServiceClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@pytest.mark.parametrize( + "error_code,cred_info_json,show_cred_info", + [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False), + ], +) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = AssistantServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + + +@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = AssistantServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (AssistantServiceClient, "grpc"), + (AssistantServiceAsyncClient, "grpc_asyncio"), + (AssistantServiceClient, "rest"), + ], +) +def test_assistant_service_client_from_service_account_info( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "ces.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://ces.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.AssistantServiceGrpcTransport, "grpc"), + (transports.AssistantServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AssistantServiceRestTransport, "rest"), + ], +) +def test_assistant_service_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (AssistantServiceClient, "grpc"), + (AssistantServiceAsyncClient, "grpc_asyncio"), + (AssistantServiceClient, "rest"), + ], +) +def test_assistant_service_client_from_service_account_file( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "ces.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://ces.googleapis.com" + ) + + +def test_assistant_service_client_get_transport_class(): + transport = AssistantServiceClient.get_transport_class() + available_transports = [ + transports.AssistantServiceGrpcTransport, + transports.AssistantServiceRestTransport, + ] + assert transport in available_transports + + transport = AssistantServiceClient.get_transport_class("grpc") + assert transport == transports.AssistantServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (AssistantServiceClient, transports.AssistantServiceGrpcTransport, "grpc"), + ( + AssistantServiceAsyncClient, + transports.AssistantServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (AssistantServiceClient, transports.AssistantServiceRestTransport, "rest"), + ], +) +@mock.patch.object( + AssistantServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AssistantServiceClient), +) +@mock.patch.object( + AssistantServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AssistantServiceAsyncClient), +) +def test_assistant_service_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(AssistantServiceClient, "get_transport_class") as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(AssistantServiceClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + AssistantServiceClient, + transports.AssistantServiceGrpcTransport, + "grpc", + "true", + ), + ( + AssistantServiceAsyncClient, + transports.AssistantServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + AssistantServiceClient, + transports.AssistantServiceGrpcTransport, + "grpc", + "false", + ), + ( + AssistantServiceAsyncClient, + transports.AssistantServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + AssistantServiceClient, + transports.AssistantServiceRestTransport, + "rest", + "true", + ), + ( + AssistantServiceClient, + transports.AssistantServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + AssistantServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AssistantServiceClient), +) +@mock.patch.object( + AssistantServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AssistantServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_assistant_service_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class", [AssistantServiceClient, AssistantServiceAsyncClient] +) +@mock.patch.object( + AssistantServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(AssistantServiceClient), +) +@mock.patch.object( + AssistantServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(AssistantServiceAsyncClient), +) +def test_assistant_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset. + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) + env.pop("CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE", None) + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with ( + mock.patch("builtins.open", m), + mock.patch( + "os.path.exists", + side_effect=lambda path: os.path.basename(path) + == config_filename, + ), + ): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") + env.pop("CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE", "") + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with ( + mock.patch("builtins.open", m), + mock.patch( + "os.path.exists", + side_effect=lambda path: os.path.basename(path) + == config_filename, + ), + ): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source() + ) + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + +@pytest.mark.parametrize( + "client_class", [AssistantServiceClient, AssistantServiceAsyncClient] +) +@mock.patch.object( + AssistantServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AssistantServiceClient), +) +@mock.patch.object( + AssistantServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AssistantServiceAsyncClient), +) +def test_assistant_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = AssistantServiceClient._DEFAULT_UNIVERSE + default_endpoint = AssistantServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = AssistantServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (AssistantServiceClient, transports.AssistantServiceGrpcTransport, "grpc"), + ( + AssistantServiceAsyncClient, + transports.AssistantServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (AssistantServiceClient, transports.AssistantServiceRestTransport, "rest"), + ], +) +def test_assistant_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + AssistantServiceClient, + transports.AssistantServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + AssistantServiceAsyncClient, + transports.AssistantServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + AssistantServiceClient, + transports.AssistantServiceRestTransport, + "rest", + None, + ), + ], +) +def test_assistant_service_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_assistant_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.ces_v1beta.services.assistant_service.transports.AssistantServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = AssistantServiceClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + AssistantServiceClient, + transports.AssistantServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + AssistantServiceAsyncClient, + transports.AssistantServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_assistant_service_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch.object(grpc_helpers, "create_channel") as create_channel, + ): + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "ces.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + "https://www.googleapis.com/auth/ces", + "https://www.googleapis.com/auth/cloud-platform", + ), + scopes=None, + default_host="ces.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + assistant_service.ListAssistantSessionsRequest(), + {}, + ], +) +def test_list_assistant_sessions(request_type, transport: str = "grpc"): + client = AssistantServiceClient( + 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.list_assistant_sessions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = assistant_service.ListAssistantSessionsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_assistant_sessions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = assistant_service.ListAssistantSessionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssistantSessionsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_assistant_sessions_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = assistant_service.ListAssistantSessionsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assistant_sessions), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_assistant_sessions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = assistant_service.ListAssistantSessionsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + ) + assert args[0] == request_msg + + +def test_list_assistant_sessions_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_assistant_sessions + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_assistant_sessions + ] = mock_rpc + request = {} + client.list_assistant_sessions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_assistant_sessions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_assistant_sessions_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_assistant_sessions + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_assistant_sessions + ] = mock_rpc + + request = {} + await client.list_assistant_sessions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_assistant_sessions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + assistant_service.ListAssistantSessionsRequest(), + {}, + ], +) +async def test_list_assistant_sessions_async( + request_type, transport: str = "grpc_asyncio" +): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + 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.list_assistant_sessions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + assistant_service.ListAssistantSessionsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_assistant_sessions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = assistant_service.ListAssistantSessionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssistantSessionsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_assistant_sessions_field_headers(): + client = AssistantServiceClient( + 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 = assistant_service.ListAssistantSessionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assistant_sessions), "__call__" + ) as call: + call.return_value = assistant_service.ListAssistantSessionsResponse() + client.list_assistant_sessions(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", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_assistant_sessions_field_headers_async(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = assistant_service.ListAssistantSessionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assistant_sessions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + assistant_service.ListAssistantSessionsResponse() + ) + await client.list_assistant_sessions(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", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_assistant_sessions_flattened(): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assistant_sessions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = assistant_service.ListAssistantSessionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_assistant_sessions( + parent="parent_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].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_assistant_sessions_flattened_error(): + client = AssistantServiceClient( + 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.list_assistant_sessions( + assistant_service.ListAssistantSessionsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_assistant_sessions_flattened_async(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assistant_sessions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = assistant_service.ListAssistantSessionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + assistant_service.ListAssistantSessionsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_assistant_sessions( + parent="parent_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].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_assistant_sessions_flattened_error_async(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_assistant_sessions( + assistant_service.ListAssistantSessionsRequest(), + parent="parent_value", + ) + + +def test_list_assistant_sessions_pager(transport_name: str = "grpc"): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assistant_sessions), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + assistant_service.ListAssistantSessionsResponse( + assistant_sessions=[ + assistant_service.AssistantSession(), + assistant_service.AssistantSession(), + assistant_service.AssistantSession(), + ], + next_page_token="abc", + ), + assistant_service.ListAssistantSessionsResponse( + assistant_sessions=[], + next_page_token="def", + ), + assistant_service.ListAssistantSessionsResponse( + assistant_sessions=[ + assistant_service.AssistantSession(), + ], + next_page_token="ghi", + ), + assistant_service.ListAssistantSessionsResponse( + assistant_sessions=[ + assistant_service.AssistantSession(), + assistant_service.AssistantSession(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_assistant_sessions(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, assistant_service.AssistantSession) for i in results) + + +def test_list_assistant_sessions_pages(transport_name: str = "grpc"): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assistant_sessions), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + assistant_service.ListAssistantSessionsResponse( + assistant_sessions=[ + assistant_service.AssistantSession(), + assistant_service.AssistantSession(), + assistant_service.AssistantSession(), + ], + next_page_token="abc", + ), + assistant_service.ListAssistantSessionsResponse( + assistant_sessions=[], + next_page_token="def", + ), + assistant_service.ListAssistantSessionsResponse( + assistant_sessions=[ + assistant_service.AssistantSession(), + ], + next_page_token="ghi", + ), + assistant_service.ListAssistantSessionsResponse( + assistant_sessions=[ + assistant_service.AssistantSession(), + assistant_service.AssistantSession(), + ], + ), + RuntimeError, + ) + pages = list(client.list_assistant_sessions(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_assistant_sessions_async_pager(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assistant_sessions), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + assistant_service.ListAssistantSessionsResponse( + assistant_sessions=[ + assistant_service.AssistantSession(), + assistant_service.AssistantSession(), + assistant_service.AssistantSession(), + ], + next_page_token="abc", + ), + assistant_service.ListAssistantSessionsResponse( + assistant_sessions=[], + next_page_token="def", + ), + assistant_service.ListAssistantSessionsResponse( + assistant_sessions=[ + assistant_service.AssistantSession(), + ], + next_page_token="ghi", + ), + assistant_service.ListAssistantSessionsResponse( + assistant_sessions=[ + assistant_service.AssistantSession(), + assistant_service.AssistantSession(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_assistant_sessions( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, assistant_service.AssistantSession) for i in responses) + + +@pytest.mark.asyncio +async def test_list_assistant_sessions_async_pages(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assistant_sessions), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + assistant_service.ListAssistantSessionsResponse( + assistant_sessions=[ + assistant_service.AssistantSession(), + assistant_service.AssistantSession(), + assistant_service.AssistantSession(), + ], + next_page_token="abc", + ), + assistant_service.ListAssistantSessionsResponse( + assistant_sessions=[], + next_page_token="def", + ), + assistant_service.ListAssistantSessionsResponse( + assistant_sessions=[ + assistant_service.AssistantSession(), + ], + next_page_token="ghi", + ), + assistant_service.ListAssistantSessionsResponse( + assistant_sessions=[ + assistant_service.AssistantSession(), + assistant_service.AssistantSession(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_assistant_sessions(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + assistant_service.GetAssistantSessionRequest(), + {}, + ], +) +def test_get_assistant_session(request_type, transport: str = "grpc"): + client = AssistantServiceClient( + 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.get_assistant_session), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = assistant_service.AssistantSession( + name="name_value", + requestor="requestor_value", + state=assistant_service.AssistantSessionState.PROCESSING, + display_name="display_name_value", + ) + response = client.get_assistant_session(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = assistant_service.GetAssistantSessionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, assistant_service.AssistantSession) + assert response.name == "name_value" + assert response.requestor == "requestor_value" + assert response.state == assistant_service.AssistantSessionState.PROCESSING + assert response.display_name == "display_name_value" + + +def test_get_assistant_session_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = assistant_service.GetAssistantSessionRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_assistant_session), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_assistant_session(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = assistant_service.GetAssistantSessionRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_assistant_session_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_assistant_session + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_assistant_session] = ( + mock_rpc + ) + request = {} + client.get_assistant_session(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_assistant_session(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_assistant_session_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_assistant_session + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_assistant_session + ] = mock_rpc + + request = {} + await client.get_assistant_session(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_assistant_session(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + assistant_service.GetAssistantSessionRequest(), + {}, + ], +) +async def test_get_assistant_session_async( + request_type, transport: str = "grpc_asyncio" +): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + 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.get_assistant_session), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + assistant_service.AssistantSession( + name="name_value", + requestor="requestor_value", + state=assistant_service.AssistantSessionState.PROCESSING, + display_name="display_name_value", + ) + ) + response = await client.get_assistant_session(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = assistant_service.GetAssistantSessionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, assistant_service.AssistantSession) + assert response.name == "name_value" + assert response.requestor == "requestor_value" + assert response.state == assistant_service.AssistantSessionState.PROCESSING + assert response.display_name == "display_name_value" + + +def test_get_assistant_session_field_headers(): + client = AssistantServiceClient( + 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 = assistant_service.GetAssistantSessionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_assistant_session), "__call__" + ) as call: + call.return_value = assistant_service.AssistantSession() + client.get_assistant_session(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", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_assistant_session_field_headers_async(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = assistant_service.GetAssistantSessionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_assistant_session), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + assistant_service.AssistantSession() + ) + await client.get_assistant_session(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", + "name=name_value", + ) in kw["metadata"] + + +def test_get_assistant_session_flattened(): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_assistant_session), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = assistant_service.AssistantSession() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_assistant_session( + name="name_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].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_assistant_session_flattened_error(): + client = AssistantServiceClient( + 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.get_assistant_session( + assistant_service.GetAssistantSessionRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_assistant_session_flattened_async(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_assistant_session), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = assistant_service.AssistantSession() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + assistant_service.AssistantSession() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_assistant_session( + name="name_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 + + +@pytest.mark.asyncio +async def test_get_assistant_session_flattened_error_async(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_assistant_session( + assistant_service.GetAssistantSessionRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + assistant_service.CreateAssistantSessionRequest(), + {}, + ], +) +def test_create_assistant_session(request_type, transport: str = "grpc"): + client = AssistantServiceClient( + 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.create_assistant_session), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = assistant_service.AssistantSession( + name="name_value", + requestor="requestor_value", + state=assistant_service.AssistantSessionState.PROCESSING, + display_name="display_name_value", + ) + response = client.create_assistant_session(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = assistant_service.CreateAssistantSessionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, assistant_service.AssistantSession) + assert response.name == "name_value" + assert response.requestor == "requestor_value" + assert response.state == assistant_service.AssistantSessionState.PROCESSING + assert response.display_name == "display_name_value" + + +def test_create_assistant_session_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = assistant_service.CreateAssistantSessionRequest( + parent="parent_value", + assistant_session_id="assistant_session_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_assistant_session), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_assistant_session(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = assistant_service.CreateAssistantSessionRequest( + parent="parent_value", + assistant_session_id="assistant_session_id_value", + ) + assert args[0] == request_msg + + +def test_create_assistant_session_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_assistant_session + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_assistant_session + ] = mock_rpc + request = {} + client.create_assistant_session(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_assistant_session(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_assistant_session_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_assistant_session + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_assistant_session + ] = mock_rpc + + request = {} + await client.create_assistant_session(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_assistant_session(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + assistant_service.CreateAssistantSessionRequest(), + {}, + ], +) +async def test_create_assistant_session_async( + request_type, transport: str = "grpc_asyncio" +): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + 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.create_assistant_session), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + assistant_service.AssistantSession( + name="name_value", + requestor="requestor_value", + state=assistant_service.AssistantSessionState.PROCESSING, + display_name="display_name_value", + ) + ) + response = await client.create_assistant_session(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = assistant_service.CreateAssistantSessionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, assistant_service.AssistantSession) + assert response.name == "name_value" + assert response.requestor == "requestor_value" + assert response.state == assistant_service.AssistantSessionState.PROCESSING + assert response.display_name == "display_name_value" + + +def test_create_assistant_session_field_headers(): + client = AssistantServiceClient( + 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 = assistant_service.CreateAssistantSessionRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_assistant_session), "__call__" + ) as call: + call.return_value = assistant_service.AssistantSession() + client.create_assistant_session(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", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_assistant_session_field_headers_async(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = assistant_service.CreateAssistantSessionRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_assistant_session), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + assistant_service.AssistantSession() + ) + await client.create_assistant_session(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", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_assistant_session_flattened(): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_assistant_session), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = assistant_service.AssistantSession() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_assistant_session( + parent="parent_value", + assistant_session_id="assistant_session_id_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].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].assistant_session_id + mock_val = "assistant_session_id_value" + assert arg == mock_val + + +def test_create_assistant_session_flattened_error(): + client = AssistantServiceClient( + 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.create_assistant_session( + assistant_service.CreateAssistantSessionRequest(), + parent="parent_value", + assistant_session_id="assistant_session_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_assistant_session_flattened_async(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_assistant_session), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = assistant_service.AssistantSession() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + assistant_service.AssistantSession() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_assistant_session( + parent="parent_value", + assistant_session_id="assistant_session_id_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].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].assistant_session_id + mock_val = "assistant_session_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_assistant_session_flattened_error_async(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_assistant_session( + assistant_service.CreateAssistantSessionRequest(), + parent="parent_value", + assistant_session_id="assistant_session_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + assistant_service.DeleteAssistantSessionRequest(), + {}, + ], +) +def test_delete_assistant_session(request_type, transport: str = "grpc"): + client = AssistantServiceClient( + 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.delete_assistant_session), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_assistant_session(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = assistant_service.DeleteAssistantSessionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_assistant_session_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = assistant_service.DeleteAssistantSessionRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_assistant_session), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_assistant_session(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = assistant_service.DeleteAssistantSessionRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_delete_assistant_session_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_assistant_session + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_assistant_session + ] = mock_rpc + request = {} + client.delete_assistant_session(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_assistant_session(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_assistant_session_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_assistant_session + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_assistant_session + ] = mock_rpc + + request = {} + await client.delete_assistant_session(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_assistant_session(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + assistant_service.DeleteAssistantSessionRequest(), + {}, + ], +) +async def test_delete_assistant_session_async( + request_type, transport: str = "grpc_asyncio" +): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + 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.delete_assistant_session), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_assistant_session(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = assistant_service.DeleteAssistantSessionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_assistant_session_field_headers(): + client = AssistantServiceClient( + 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 = assistant_service.DeleteAssistantSessionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_assistant_session), "__call__" + ) as call: + call.return_value = None + client.delete_assistant_session(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", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_assistant_session_field_headers_async(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = assistant_service.DeleteAssistantSessionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_assistant_session), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_assistant_session(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", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_assistant_session_flattened(): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_assistant_session), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_assistant_session( + name="name_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].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_assistant_session_flattened_error(): + client = AssistantServiceClient( + 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.delete_assistant_session( + assistant_service.DeleteAssistantSessionRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_assistant_session_flattened_async(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_assistant_session), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_assistant_session( + name="name_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 + + +@pytest.mark.asyncio +async def test_delete_assistant_session_flattened_error_async(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_assistant_session( + assistant_service.DeleteAssistantSessionRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + assistant_service.RunAssistantRequest(), + {}, + ], +) +def test_run_assistant(request_type, transport: str = "grpc"): + client = AssistantServiceClient( + 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.run_assistant), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = assistant_service.RunAssistantResponse( + state=assistant_service.AssistantSessionState.PROCESSING, + ) + response = client.run_assistant(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = assistant_service.RunAssistantRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, assistant_service.RunAssistantResponse) + assert response.state == assistant_service.AssistantSessionState.PROCESSING + + +def test_run_assistant_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = assistant_service.RunAssistantRequest( + app="app_value", + assistant_session="assistant_session_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.run_assistant), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.run_assistant(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = assistant_service.RunAssistantRequest( + app="app_value", + assistant_session="assistant_session_value", + ) + assert args[0] == request_msg + + +def test_run_assistant_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.run_assistant in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.run_assistant] = mock_rpc + request = {} + client.run_assistant(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.run_assistant(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_run_assistant_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.run_assistant + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.run_assistant + ] = mock_rpc + + request = {} + await client.run_assistant(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.run_assistant(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + assistant_service.RunAssistantRequest(), + {}, + ], +) +async def test_run_assistant_async(request_type, transport: str = "grpc_asyncio"): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + 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.run_assistant), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + assistant_service.RunAssistantResponse( + state=assistant_service.AssistantSessionState.PROCESSING, + ) + ) + response = await client.run_assistant(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = assistant_service.RunAssistantRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, assistant_service.RunAssistantResponse) + assert response.state == assistant_service.AssistantSessionState.PROCESSING + + +def test_run_assistant_field_headers(): + client = AssistantServiceClient( + 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 = assistant_service.RunAssistantRequest() + + request.app = "app_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.run_assistant), "__call__") as call: + call.return_value = assistant_service.RunAssistantResponse() + client.run_assistant(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", + "app=app_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_run_assistant_field_headers_async(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = assistant_service.RunAssistantRequest() + + request.app = "app_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.run_assistant), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + assistant_service.RunAssistantResponse() + ) + await client.run_assistant(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", + "app=app_value", + ) in kw["metadata"] + + +@pytest.mark.parametrize( + "request_type", + [ + assistant_service.ChatAiAssistantRequest(), + {}, + ], +) +def test_chat_ai_assistant(request_type, transport: str = "grpc"): + client = AssistantServiceClient( + 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.chat_ai_assistant), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = assistant_service.ChatAiAssistantResponse( + event_id="event_id_value", + text_chunk="text_chunk_value", + ) + response = client.chat_ai_assistant(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = assistant_service.ChatAiAssistantRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, assistant_service.ChatAiAssistantResponse) + assert response.event_id == "event_id_value" + + +def test_chat_ai_assistant_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = assistant_service.ChatAiAssistantRequest( + app="app_value", + assistant_session="assistant_session_value", + message="message_value", + context_token="context_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.chat_ai_assistant), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.chat_ai_assistant(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = assistant_service.ChatAiAssistantRequest( + app="app_value", + assistant_session="assistant_session_value", + message="message_value", + context_token="context_token_value", + ) + assert args[0] == request_msg + + +def test_chat_ai_assistant_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.chat_ai_assistant in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.chat_ai_assistant] = ( + mock_rpc + ) + request = {} + client.chat_ai_assistant(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.chat_ai_assistant(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_chat_ai_assistant_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.chat_ai_assistant + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.chat_ai_assistant + ] = mock_rpc + + request = {} + await client.chat_ai_assistant(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.chat_ai_assistant(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + assistant_service.ChatAiAssistantRequest(), + {}, + ], +) +async def test_chat_ai_assistant_async(request_type, transport: str = "grpc_asyncio"): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + 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.chat_ai_assistant), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + assistant_service.ChatAiAssistantResponse( + event_id="event_id_value", + ) + ) + response = await client.chat_ai_assistant(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = assistant_service.ChatAiAssistantRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, assistant_service.ChatAiAssistantResponse) + assert response.event_id == "event_id_value" + + +def test_chat_ai_assistant_field_headers(): + client = AssistantServiceClient( + 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 = assistant_service.ChatAiAssistantRequest() + + request.app = "app_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.chat_ai_assistant), "__call__" + ) as call: + call.return_value = assistant_service.ChatAiAssistantResponse() + client.chat_ai_assistant(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", + "app=app_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_chat_ai_assistant_field_headers_async(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = assistant_service.ChatAiAssistantRequest() + + request.app = "app_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.chat_ai_assistant), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + assistant_service.ChatAiAssistantResponse() + ) + await client.chat_ai_assistant(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", + "app=app_value", + ) in kw["metadata"] + + +def test_list_assistant_sessions_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_assistant_sessions + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_assistant_sessions + ] = mock_rpc + + request = {} + client.list_assistant_sessions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_assistant_sessions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_assistant_sessions_rest_required_fields( + request_type=assistant_service.ListAssistantSessionsRequest, +): + transport_class = transports.AssistantServiceRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseListAssistantSessions, + "_BaseListAssistantSessions__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = assistant_service.ListAssistantSessionsResponse() + # 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 + + # Convert return value to protobuf type + return_value = assistant_service.ListAssistantSessionsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_assistant_sessions(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_assistant_sessions_rest_flattened(): + client = AssistantServiceClient( + 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 = assistant_service.ListAssistantSessionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = assistant_service.ListAssistantSessionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_assistant_sessions(**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/v1beta/{parent=projects/*/locations/*/apps/*}/assistantSessions" + % client.transport._host, + args[1], + ) + + +def test_list_assistant_sessions_rest_flattened_error(transport: str = "rest"): + client = AssistantServiceClient( + 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.list_assistant_sessions( + assistant_service.ListAssistantSessionsRequest(), + parent="parent_value", + ) + + +def test_list_assistant_sessions_rest_pager(transport: str = "rest"): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + assistant_service.ListAssistantSessionsResponse( + assistant_sessions=[ + assistant_service.AssistantSession(), + assistant_service.AssistantSession(), + assistant_service.AssistantSession(), + ], + next_page_token="abc", + ), + assistant_service.ListAssistantSessionsResponse( + assistant_sessions=[], + next_page_token="def", + ), + assistant_service.ListAssistantSessionsResponse( + assistant_sessions=[ + assistant_service.AssistantSession(), + ], + next_page_token="ghi", + ), + assistant_service.ListAssistantSessionsResponse( + assistant_sessions=[ + assistant_service.AssistantSession(), + assistant_service.AssistantSession(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + assistant_service.ListAssistantSessionsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + pager = client.list_assistant_sessions(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, assistant_service.AssistantSession) for i in results) + + pages = list(client.list_assistant_sessions(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_assistant_session_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_assistant_session + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_assistant_session] = ( + mock_rpc + ) + + request = {} + client.get_assistant_session(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_assistant_session(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_assistant_session_rest_required_fields( + request_type=assistant_service.GetAssistantSessionRequest, +): + transport_class = transports.AssistantServiceRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGetAssistantSession, + "_BaseGetAssistantSession__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = assistant_service.AssistantSession() + # 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 + + # Convert return value to protobuf type + return_value = assistant_service.AssistantSession.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_assistant_session(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_assistant_session_rest_flattened(): + client = AssistantServiceClient( + 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 = assistant_service.AssistantSession() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/apps/sample3/assistantSessions/sample4" + } + + # 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 + # Convert return value to protobuf type + return_value = assistant_service.AssistantSession.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_assistant_session(**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/v1beta/{name=projects/*/locations/*/apps/*/assistantSessions/*}" + % client.transport._host, + args[1], + ) + + +def test_get_assistant_session_rest_flattened_error(transport: str = "rest"): + client = AssistantServiceClient( + 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_assistant_session( + assistant_service.GetAssistantSessionRequest(), + name="name_value", + ) + + +def test_create_assistant_session_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_assistant_session + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_assistant_session + ] = mock_rpc + + request = {} + client.create_assistant_session(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_assistant_session(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_assistant_session_rest_required_fields( + request_type=assistant_service.CreateAssistantSessionRequest, +): + transport_class = transports.AssistantServiceRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseCreateAssistantSession, + "_BaseCreateAssistantSession__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = assistant_service.AssistantSession() + # 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 + + # Convert return value to protobuf type + return_value = assistant_service.AssistantSession.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_assistant_session(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_assistant_session_rest_flattened(): + client = AssistantServiceClient( + 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 = assistant_service.AssistantSession() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + assistant_session_id="assistant_session_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = assistant_service.AssistantSession.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_assistant_session(**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/v1beta/{parent=projects/*/locations/*/apps/*}/assistantSessions" + % client.transport._host, + args[1], + ) + + +def test_create_assistant_session_rest_flattened_error(transport: str = "rest"): + client = AssistantServiceClient( + 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.create_assistant_session( + assistant_service.CreateAssistantSessionRequest(), + parent="parent_value", + assistant_session_id="assistant_session_id_value", + ) + + +def test_delete_assistant_session_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_assistant_session + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_assistant_session + ] = mock_rpc + + request = {} + client.delete_assistant_session(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_assistant_session(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_assistant_session_rest_required_fields( + request_type=assistant_service.DeleteAssistantSessionRequest, +): + transport_class = transports.AssistantServiceRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseDeleteAssistantSession, + "_BaseDeleteAssistantSession__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = AssistantServiceClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_assistant_session(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_assistant_session_rest_flattened(): + client = AssistantServiceClient( + 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 = None + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/apps/sample3/assistantSessions/sample4" + } + + # 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 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_assistant_session(**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/v1beta/{name=projects/*/locations/*/apps/*/assistantSessions/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_assistant_session_rest_flattened_error(transport: str = "rest"): + client = AssistantServiceClient( + 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_assistant_session( + assistant_service.DeleteAssistantSessionRequest(), + name="name_value", + ) + + +def test_run_assistant_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.run_assistant in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.run_assistant] = mock_rpc + + request = {} + client.run_assistant(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.run_assistant(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_run_assistant_rest_required_fields( + request_type=assistant_service.RunAssistantRequest, +): + transport_class = transports.AssistantServiceRestTransport + + request_init = {} + request_init["app"] = "" + request_init["assistant_session"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseRunAssistant, + "_BaseRunAssistant__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["app"] = "app_value" + jsonified_request["assistantSession"] = "assistant_session_value" + + # verify required fields with non-default values are left alone + assert "app" in jsonified_request + assert jsonified_request["app"] == "app_value" + assert "assistantSession" in jsonified_request + assert jsonified_request["assistantSession"] == "assistant_session_value" + + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = assistant_service.RunAssistantResponse() + # 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 + + # Convert return value to protobuf type + return_value = assistant_service.RunAssistantResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.run_assistant(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_chat_ai_assistant_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.chat_ai_assistant in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.chat_ai_assistant] = ( + mock_rpc + ) + + request = {} + client.chat_ai_assistant(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.chat_ai_assistant(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_chat_ai_assistant_rest_required_fields( + request_type=assistant_service.ChatAiAssistantRequest, +): + transport_class = transports.AssistantServiceRestTransport + + request_init = {} + request_init["app"] = "" + request_init["assistant_session"] = "" + request_init["message"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseChatAiAssistant, + "_BaseChatAiAssistant__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["app"] = "app_value" + jsonified_request["assistantSession"] = "assistant_session_value" + jsonified_request["message"] = "message_value" + + # verify required fields with non-default values are left alone + assert "app" in jsonified_request + assert jsonified_request["app"] == "app_value" + assert "assistantSession" in jsonified_request + assert jsonified_request["assistantSession"] == "assistant_session_value" + assert "message" in jsonified_request + assert jsonified_request["message"] == "message_value" + + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = assistant_service.ChatAiAssistantResponse() + # 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 + + # Convert return value to protobuf type + return_value = assistant_service.ChatAiAssistantResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.chat_ai_assistant(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AssistantServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AssistantServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AssistantServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AssistantServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AssistantServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AssistantServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AssistantServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AssistantServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AssistantServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AssistantServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AssistantServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AssistantServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AssistantServiceGrpcTransport, + transports.AssistantServiceGrpcAsyncIOTransport, + transports.AssistantServiceRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_kind_grpc(): + transport = AssistantServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_assistant_sessions_empty_call_grpc(): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_assistant_sessions), "__call__" + ) as call: + call.return_value = assistant_service.ListAssistantSessionsResponse() + client.list_assistant_sessions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = assistant_service.ListAssistantSessionsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_assistant_session_empty_call_grpc(): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_assistant_session), "__call__" + ) as call: + call.return_value = assistant_service.AssistantSession() + client.get_assistant_session(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = assistant_service.GetAssistantSessionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_assistant_session_empty_call_grpc(): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_assistant_session), "__call__" + ) as call: + call.return_value = assistant_service.AssistantSession() + client.create_assistant_session(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = assistant_service.CreateAssistantSessionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_assistant_session_empty_call_grpc(): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_assistant_session), "__call__" + ) as call: + call.return_value = None + client.delete_assistant_session(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = assistant_service.DeleteAssistantSessionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_run_assistant_empty_call_grpc(): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.run_assistant), "__call__") as call: + call.return_value = assistant_service.RunAssistantResponse() + client.run_assistant(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = assistant_service.RunAssistantRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_chat_ai_assistant_empty_call_grpc(): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.chat_ai_assistant), "__call__" + ) as call: + call.return_value = assistant_service.ChatAiAssistantResponse() + client.chat_ai_assistant(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = assistant_service.ChatAiAssistantRequest() + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = AssistantServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_assistant_sessions_empty_call_grpc_asyncio(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_assistant_sessions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + assistant_service.ListAssistantSessionsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_assistant_sessions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = assistant_service.ListAssistantSessionsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_assistant_session_empty_call_grpc_asyncio(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_assistant_session), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + assistant_service.AssistantSession( + name="name_value", + requestor="requestor_value", + state=assistant_service.AssistantSessionState.PROCESSING, + display_name="display_name_value", + ) + ) + await client.get_assistant_session(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = assistant_service.GetAssistantSessionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_assistant_session_empty_call_grpc_asyncio(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_assistant_session), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + assistant_service.AssistantSession( + name="name_value", + requestor="requestor_value", + state=assistant_service.AssistantSessionState.PROCESSING, + display_name="display_name_value", + ) + ) + await client.create_assistant_session(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = assistant_service.CreateAssistantSessionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_assistant_session_empty_call_grpc_asyncio(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_assistant_session), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_assistant_session(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = assistant_service.DeleteAssistantSessionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_run_assistant_empty_call_grpc_asyncio(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.run_assistant), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + assistant_service.RunAssistantResponse( + state=assistant_service.AssistantSessionState.PROCESSING, + ) + ) + await client.run_assistant(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = assistant_service.RunAssistantRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_chat_ai_assistant_empty_call_grpc_asyncio(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.chat_ai_assistant), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + assistant_service.ChatAiAssistantResponse( + event_id="event_id_value", + ) + ) + await client.chat_ai_assistant(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = assistant_service.ChatAiAssistantRequest() + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = AssistantServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_assistant_sessions_rest_bad_request( + request_type=assistant_service.ListAssistantSessionsRequest, +): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_assistant_sessions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + assistant_service.ListAssistantSessionsRequest, + dict, + ], +) +def test_list_assistant_sessions_rest_call_success(request_type): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/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 = assistant_service.ListAssistantSessionsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = assistant_service.ListAssistantSessionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_assistant_sessions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssistantSessionsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_assistant_sessions_rest_interceptors(null_interceptor): + transport = transports.AssistantServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AssistantServiceRestInterceptor(), + ) + client = AssistantServiceClient(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.AssistantServiceRestInterceptor, "post_list_assistant_sessions" + ) as post, + mock.patch.object( + transports.AssistantServiceRestInterceptor, + "post_list_assistant_sessions_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.AssistantServiceRestInterceptor, "pre_list_assistant_sessions" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = assistant_service.ListAssistantSessionsRequest.pb( + assistant_service.ListAssistantSessionsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = assistant_service.ListAssistantSessionsResponse.to_json( + assistant_service.ListAssistantSessionsResponse() + ) + req.return_value.content = return_value + + request = assistant_service.ListAssistantSessionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = assistant_service.ListAssistantSessionsResponse() + post_with_metadata.return_value = ( + assistant_service.ListAssistantSessionsResponse(), + metadata, + ) + + client.list_assistant_sessions( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_assistant_session_rest_bad_request( + request_type=assistant_service.GetAssistantSessionRequest, +): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/assistantSessions/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_assistant_session(request) + + +@pytest.mark.parametrize( + "request_type", + [ + assistant_service.GetAssistantSessionRequest, + dict, + ], +) +def test_get_assistant_session_rest_call_success(request_type): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/assistantSessions/sample4" + } + 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 = assistant_service.AssistantSession( + name="name_value", + requestor="requestor_value", + state=assistant_service.AssistantSessionState.PROCESSING, + display_name="display_name_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = assistant_service.AssistantSession.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_assistant_session(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, assistant_service.AssistantSession) + assert response.name == "name_value" + assert response.requestor == "requestor_value" + assert response.state == assistant_service.AssistantSessionState.PROCESSING + assert response.display_name == "display_name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_assistant_session_rest_interceptors(null_interceptor): + transport = transports.AssistantServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AssistantServiceRestInterceptor(), + ) + client = AssistantServiceClient(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.AssistantServiceRestInterceptor, "post_get_assistant_session" + ) as post, + mock.patch.object( + transports.AssistantServiceRestInterceptor, + "post_get_assistant_session_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.AssistantServiceRestInterceptor, "pre_get_assistant_session" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = assistant_service.GetAssistantSessionRequest.pb( + assistant_service.GetAssistantSessionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = assistant_service.AssistantSession.to_json( + assistant_service.AssistantSession() + ) + req.return_value.content = return_value + + request = assistant_service.GetAssistantSessionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = assistant_service.AssistantSession() + post_with_metadata.return_value = assistant_service.AssistantSession(), metadata + + client.get_assistant_session( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_assistant_session_rest_bad_request( + request_type=assistant_service.CreateAssistantSessionRequest, +): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_assistant_session(request) + + +@pytest.mark.parametrize( + "request_type", + [ + assistant_service.CreateAssistantSessionRequest, + dict, + ], +) +def test_create_assistant_session_rest_call_success(request_type): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/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 = assistant_service.AssistantSession( + name="name_value", + requestor="requestor_value", + state=assistant_service.AssistantSessionState.PROCESSING, + display_name="display_name_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = assistant_service.AssistantSession.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_assistant_session(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, assistant_service.AssistantSession) + assert response.name == "name_value" + assert response.requestor == "requestor_value" + assert response.state == assistant_service.AssistantSessionState.PROCESSING + assert response.display_name == "display_name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_assistant_session_rest_interceptors(null_interceptor): + transport = transports.AssistantServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AssistantServiceRestInterceptor(), + ) + client = AssistantServiceClient(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.AssistantServiceRestInterceptor, "post_create_assistant_session" + ) as post, + mock.patch.object( + transports.AssistantServiceRestInterceptor, + "post_create_assistant_session_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.AssistantServiceRestInterceptor, "pre_create_assistant_session" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = assistant_service.CreateAssistantSessionRequest.pb( + assistant_service.CreateAssistantSessionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = assistant_service.AssistantSession.to_json( + assistant_service.AssistantSession() + ) + req.return_value.content = return_value + + request = assistant_service.CreateAssistantSessionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = assistant_service.AssistantSession() + post_with_metadata.return_value = assistant_service.AssistantSession(), metadata + + client.create_assistant_session( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_assistant_session_rest_bad_request( + request_type=assistant_service.DeleteAssistantSessionRequest, +): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/assistantSessions/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_assistant_session(request) + + +@pytest.mark.parametrize( + "request_type", + [ + assistant_service.DeleteAssistantSessionRequest, + dict, + ], +) +def test_delete_assistant_session_rest_call_success(request_type): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/assistantSessions/sample4" + } + 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 = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_assistant_session(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_assistant_session_rest_interceptors(null_interceptor): + transport = transports.AssistantServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AssistantServiceRestInterceptor(), + ) + client = AssistantServiceClient(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.AssistantServiceRestInterceptor, "pre_delete_assistant_session" + ) as pre, + ): + pre.assert_not_called() + pb_message = assistant_service.DeleteAssistantSessionRequest.pb( + assistant_service.DeleteAssistantSessionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = assistant_service.DeleteAssistantSessionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_assistant_session( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_run_assistant_rest_bad_request( + request_type=assistant_service.RunAssistantRequest, +): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"app": "projects/sample1/locations/sample2/apps/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.run_assistant(request) + + +@pytest.mark.parametrize( + "request_type", + [ + assistant_service.RunAssistantRequest, + dict, + ], +) +def test_run_assistant_rest_call_success(request_type): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"app": "projects/sample1/locations/sample2/apps/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 = assistant_service.RunAssistantResponse( + state=assistant_service.AssistantSessionState.PROCESSING, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = assistant_service.RunAssistantResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.run_assistant(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, assistant_service.RunAssistantResponse) + assert response.state == assistant_service.AssistantSessionState.PROCESSING + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_run_assistant_rest_interceptors(null_interceptor): + transport = transports.AssistantServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AssistantServiceRestInterceptor(), + ) + client = AssistantServiceClient(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.AssistantServiceRestInterceptor, "post_run_assistant" + ) as post, + mock.patch.object( + transports.AssistantServiceRestInterceptor, + "post_run_assistant_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.AssistantServiceRestInterceptor, "pre_run_assistant" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = assistant_service.RunAssistantRequest.pb( + assistant_service.RunAssistantRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = assistant_service.RunAssistantResponse.to_json( + assistant_service.RunAssistantResponse() + ) + req.return_value.content = return_value + + request = assistant_service.RunAssistantRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = assistant_service.RunAssistantResponse() + post_with_metadata.return_value = ( + assistant_service.RunAssistantResponse(), + metadata, + ) + + client.run_assistant( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_chat_ai_assistant_rest_bad_request( + request_type=assistant_service.ChatAiAssistantRequest, +): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"app": "projects/sample1/locations/sample2/apps/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.chat_ai_assistant(request) + + +@pytest.mark.parametrize( + "request_type", + [ + assistant_service.ChatAiAssistantRequest, + dict, + ], +) +def test_chat_ai_assistant_rest_call_success(request_type): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"app": "projects/sample1/locations/sample2/apps/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 = assistant_service.ChatAiAssistantResponse( + event_id="event_id_value", + text_chunk="text_chunk_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = assistant_service.ChatAiAssistantResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.chat_ai_assistant(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, assistant_service.ChatAiAssistantResponse) + assert response.event_id == "event_id_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_chat_ai_assistant_rest_interceptors(null_interceptor): + transport = transports.AssistantServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AssistantServiceRestInterceptor(), + ) + client = AssistantServiceClient(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.AssistantServiceRestInterceptor, "post_chat_ai_assistant" + ) as post, + mock.patch.object( + transports.AssistantServiceRestInterceptor, + "post_chat_ai_assistant_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.AssistantServiceRestInterceptor, "pre_chat_ai_assistant" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = assistant_service.ChatAiAssistantRequest.pb( + assistant_service.ChatAiAssistantRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = assistant_service.ChatAiAssistantResponse.to_json( + assistant_service.ChatAiAssistantResponse() + ) + req.return_value.content = return_value + + request = assistant_service.ChatAiAssistantRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = assistant_service.ChatAiAssistantResponse() + post_with_metadata.return_value = ( + assistant_service.ChatAiAssistantResponse(), + metadata, + ) + + client.chat_ai_assistant( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_location(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.GetLocationRequest, + dict, + ], +) +def test_get_location_rest(request_type): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_list_locations_rest_bad_request( + request_type=locations_pb2.ListLocationsRequest, +): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "projects/sample1"}, request) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_locations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.ListLocationsRequest, + dict, + ], +) +def test_list_locations_rest(request_type): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_cancel_operation_rest_bad_request( + request_type=operations_pb2.CancelOperationRequest, +): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(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 = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_rest_bad_request( + request_type=operations_pb2.DeleteOperationRequest, +): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(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 = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_assistant_sessions_empty_call_rest(): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_assistant_sessions), "__call__" + ) as call: + client.list_assistant_sessions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = assistant_service.ListAssistantSessionsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_assistant_session_empty_call_rest(): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_assistant_session), "__call__" + ) as call: + client.get_assistant_session(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = assistant_service.GetAssistantSessionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_assistant_session_empty_call_rest(): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_assistant_session), "__call__" + ) as call: + client.create_assistant_session(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = assistant_service.CreateAssistantSessionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_assistant_session_empty_call_rest(): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_assistant_session), "__call__" + ) as call: + client.delete_assistant_session(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = assistant_service.DeleteAssistantSessionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_run_assistant_empty_call_rest(): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.run_assistant), "__call__") as call: + client.run_assistant(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = assistant_service.RunAssistantRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_chat_ai_assistant_empty_call_rest(): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.chat_ai_assistant), "__call__" + ) as call: + client.chat_ai_assistant(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = assistant_service.ChatAiAssistantRequest() + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AssistantServiceGrpcTransport, + ) + + +def test_assistant_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AssistantServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_assistant_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.ces_v1beta.services.assistant_service.transports.AssistantServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.AssistantServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_assistant_sessions", + "get_assistant_session", + "create_assistant_session", + "delete_assistant_session", + "run_assistant", + "chat_ai_assistant", + "get_location", + "list_locations", + "get_operation", + "cancel_operation", + "delete_operation", + "list_operations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_assistant_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch( + "google.cloud.ces_v1beta.services.assistant_service.transports.AssistantServiceTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AssistantServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/ces", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +def test_assistant_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with ( + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch( + "google.cloud.ces_v1beta.services.assistant_service.transports.AssistantServiceTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AssistantServiceTransport() + adc.assert_called_once() + + +def test_assistant_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + AssistantServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/ces", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AssistantServiceGrpcTransport, + transports.AssistantServiceGrpcAsyncIOTransport, + ], +) +def test_assistant_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/ces", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AssistantServiceGrpcTransport, + transports.AssistantServiceGrpcAsyncIOTransport, + transports.AssistantServiceRestTransport, + ], +) +def test_assistant_service_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AssistantServiceGrpcTransport, grpc_helpers), + (transports.AssistantServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_assistant_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with ( + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel, + ): + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "ces.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/ces", + "https://www.googleapis.com/auth/cloud-platform", + ), + scopes=["1", "2"], + default_host="ces.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AssistantServiceGrpcTransport, + transports.AssistantServiceGrpcAsyncIOTransport, + ], +) +def test_assistant_service_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_assistant_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.AssistantServiceRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_assistant_service_host_no_port(transport_name): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint="ces.googleapis.com"), + transport=transport_name, + ) + assert client.transport._host == ( + "ces.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://ces.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_assistant_service_host_with_port(transport_name): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="ces.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "ces.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://ces.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_assistant_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = AssistantServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = AssistantServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_assistant_sessions._session + session2 = client2.transport.list_assistant_sessions._session + assert session1 != session2 + session1 = client1.transport.get_assistant_session._session + session2 = client2.transport.get_assistant_session._session + assert session1 != session2 + session1 = client1.transport.create_assistant_session._session + session2 = client2.transport.create_assistant_session._session + assert session1 != session2 + session1 = client1.transport.delete_assistant_session._session + session2 = client2.transport.delete_assistant_session._session + assert session1 != session2 + session1 = client1.transport.run_assistant._session + session2 = client2.transport.run_assistant._session + assert session1 != session2 + session1 = client1.transport.chat_ai_assistant._session + session2 = client2.transport.chat_ai_assistant._session + assert session1 != session2 + + +def test_assistant_service_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AssistantServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_assistant_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AssistantServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.filterwarnings("ignore::FutureWarning") +@pytest.mark.parametrize( + "transport_class", + [ + transports.AssistantServiceGrpcTransport, + transports.AssistantServiceGrpcAsyncIOTransport, + ], +) +def test_assistant_service_transport_channel_mtls_with_client_cert_source( + transport_class, +): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.AssistantServiceGrpcTransport, + transports.AssistantServiceGrpcAsyncIOTransport, + ], +) +def test_assistant_service_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_app_path(): + project = "squid" + location = "clam" + app = "whelk" + expected = "projects/{project}/locations/{location}/apps/{app}".format( + project=project, + location=location, + app=app, + ) + actual = AssistantServiceClient.app_path(project, location, app) + assert expected == actual + + +def test_parse_app_path(): + expected = { + "project": "octopus", + "location": "oyster", + "app": "nudibranch", + } + path = AssistantServiceClient.app_path(**expected) + + # Check that the path construction is reversible. + actual = AssistantServiceClient.parse_app_path(path) + assert expected == actual + + +def test_assistant_session_path(): + project = "cuttlefish" + location = "mussel" + app = "winkle" + assistant_session = "nautilus" + expected = "projects/{project}/locations/{location}/apps/{app}/assistantSessions/{assistant_session}".format( + project=project, + location=location, + app=app, + assistant_session=assistant_session, + ) + actual = AssistantServiceClient.assistant_session_path( + project, location, app, assistant_session + ) + assert expected == actual + + +def test_parse_assistant_session_path(): + expected = { + "project": "scallop", + "location": "abalone", + "app": "squid", + "assistant_session": "clam", + } + path = AssistantServiceClient.assistant_session_path(**expected) + + # Check that the path construction is reversible. + actual = AssistantServiceClient.parse_assistant_session_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = AssistantServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = AssistantServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AssistantServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = AssistantServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = AssistantServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AssistantServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = AssistantServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = AssistantServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AssistantServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format( + project=project, + ) + actual = AssistantServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = AssistantServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AssistantServiceClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = AssistantServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = AssistantServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AssistantServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.AssistantServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.AssistantServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = AssistantServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_delete_operation(transport: str = "grpc"): + client = AssistantServiceClient( + 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 = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc_asyncio"): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + 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 = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_field_headers(): + client = AssistantServiceClient( + 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 = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_operation(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", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_operation(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", + "name=locations", + ) in kw["metadata"] + + +def test_delete_operation_from_dict(): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_delete_operation_flattened(): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + client.delete_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.DeleteOperationRequest() + + +@pytest.mark.asyncio +async def test_delete_operation_flattened_async(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.DeleteOperationRequest() + + +def test_cancel_operation(transport: str = "grpc"): + client = AssistantServiceClient( + 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 = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + 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 = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_cancel_operation_field_headers(): + client = AssistantServiceClient( + 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 = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(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", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.cancel_operation(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", + "name=locations", + ) in kw["metadata"] + + +def test_cancel_operation_from_dict(): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation_flattened(): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() + + +@pytest.mark.asyncio +async def test_cancel_operation_flattened_async(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() + + +def test_get_operation(transport: str = "grpc"): + client = AssistantServiceClient( + 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 = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + 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 = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_get_operation_field_headers(): + client = AssistantServiceClient( + 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 = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(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", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(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", + "name=locations", + ) in kw["metadata"] + + +def test_get_operation_from_dict(): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation_flattened(): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() + + +@pytest.mark.asyncio +async def test_get_operation_flattened_async(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() + + +def test_list_operations(transport: str = "grpc"): + client = AssistantServiceClient( + 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 = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + 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 = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_list_operations_field_headers(): + client = AssistantServiceClient( + 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 = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(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", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(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", + "name=locations", + ) in kw["metadata"] + + +def test_list_operations_from_dict(): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations_flattened(): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() + + +@pytest.mark.asyncio +async def test_list_operations_flattened_async(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() + + +def test_list_locations(transport: str = "grpc"): + client = AssistantServiceClient( + 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 = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc_asyncio"): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + 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 = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_list_locations_field_headers(): + client = AssistantServiceClient( + 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 = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations(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", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(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", + "name=locations", + ) in kw["metadata"] + + +def test_list_locations_from_dict(): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations_flattened(): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.ListLocationsRequest() + + +@pytest.mark.asyncio +async def test_list_locations_flattened_async(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.ListLocationsRequest() + + +def test_get_location(transport: str = "grpc"): + client = AssistantServiceClient( + 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 = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + 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 = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_get_location_field_headers(): + client = AssistantServiceClient(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 = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() + + client.get_location(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", + "name=locations/abc", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = AssistantServiceAsyncClient(credentials=async_anonymous_credentials()) + + # 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 = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(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", + "name=locations/abc", + ) in kw["metadata"] + + +def test_get_location_from_dict(): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_location_from_dict_async(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_location_flattened(): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + client.get_location() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.GetLocationRequest() + + +@pytest.mark.asyncio +async def test_get_location_flattened_async(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.GetLocationRequest() + + +def test_transport_close_grpc(): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = AssistantServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + "grpc", + ] + for transport in transports: + client = AssistantServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (AssistantServiceClient, transports.AssistantServiceGrpcTransport), + (AssistantServiceAsyncClient, transports.AssistantServiceGrpcAsyncIOTransport), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/packages/google-cloud-ces/tests/unit/gapic/ces_v1beta/test_evaluation_service.py b/packages/google-cloud-ces/tests/unit/gapic/ces_v1beta/test_evaluation_service.py index b258b84e7f13..1edaf3f3afd1 100644 --- a/packages/google-cloud-ces/tests/unit/gapic/ces_v1beta/test_evaluation_service.py +++ b/packages/google-cloud-ces/tests/unit/gapic/ces_v1beta/test_evaluation_service.py @@ -5954,6 +5954,7 @@ def test_get_evaluation_result(request_type, transport: str = "grpc"): changelog="changelog_value", execution_state=evaluation.EvaluationResult.ExecutionState.QUEUED, golden_run_method=golden_run.GoldenRunMethod.STABLE, + outcome_metadata=evaluation.EvaluationResult.OutcomeMetadata.GRACEFUL_HANDOFF, ) response = client.get_evaluation_result(request) @@ -5975,6 +5976,10 @@ def test_get_evaluation_result(request_type, transport: str = "grpc"): assert response.changelog == "changelog_value" assert response.execution_state == evaluation.EvaluationResult.ExecutionState.QUEUED assert response.golden_run_method == golden_run.GoldenRunMethod.STABLE + assert ( + response.outcome_metadata + == evaluation.EvaluationResult.OutcomeMetadata.GRACEFUL_HANDOFF + ) def test_get_evaluation_result_non_empty_request_with_auto_populated_field(): @@ -6127,6 +6132,7 @@ async def test_get_evaluation_result_async( changelog="changelog_value", execution_state=evaluation.EvaluationResult.ExecutionState.QUEUED, golden_run_method=golden_run.GoldenRunMethod.STABLE, + outcome_metadata=evaluation.EvaluationResult.OutcomeMetadata.GRACEFUL_HANDOFF, ) ) response = await client.get_evaluation_result(request) @@ -6149,6 +6155,10 @@ async def test_get_evaluation_result_async( assert response.changelog == "changelog_value" assert response.execution_state == evaluation.EvaluationResult.ExecutionState.QUEUED assert response.golden_run_method == golden_run.GoldenRunMethod.STABLE + assert ( + response.outcome_metadata + == evaluation.EvaluationResult.OutcomeMetadata.GRACEFUL_HANDOFF + ) def test_get_evaluation_result_field_headers(): @@ -23150,6 +23160,7 @@ async def test_get_evaluation_result_empty_call_grpc_asyncio(): changelog="changelog_value", execution_state=evaluation.EvaluationResult.ExecutionState.QUEUED, golden_run_method=golden_run.GoldenRunMethod.STABLE, + outcome_metadata=evaluation.EvaluationResult.OutcomeMetadata.GRACEFUL_HANDOFF, ) ) await client.get_evaluation_result(request=None) @@ -24117,20 +24128,24 @@ def test_create_evaluation_rest_call_success(request_type): "id": "id_value", "display_name": "display_name_value", "response": {"fields": {}}, + "parent_tool_call_id": "parent_tool_call_id_value", + "agent_name": "agent_name_value", } ] }, "image": { "mime_type": "mime_type_value", "data": b"data_blob", + "alt_text": "alt_text_value", }, "blob": { "mime_type": "mime_type_value", "data": b"data_blob", }, "variables": {}, - "event": {"event": "event_value"}, + "event": {"event": "event_value", "variables": {}}, "will_continue": True, + "recording_control": 1, }, "agent_transfer": { "target_agent": "target_agent_value", @@ -24143,6 +24158,8 @@ def test_create_evaluation_rest_call_success(request_type): "id": "id_value", "display_name": "display_name_value", "args": {}, + "parent_tool_call_id": "parent_tool_call_id_value", + "agent_name": "agent_name_value", }, "tool_response": {}, "agent_response": { @@ -24437,6 +24454,8 @@ def test_create_evaluation_rest_call_success(request_type): "tool_call_behaviour": 1, }, "golden_run_method": 1, + "root_span": {}, + "outcome_metadata": 1, }, "invalid": True, "last_ten_results": {}, @@ -25212,20 +25231,24 @@ def test_update_evaluation_rest_call_success(request_type): "id": "id_value", "display_name": "display_name_value", "response": {"fields": {}}, + "parent_tool_call_id": "parent_tool_call_id_value", + "agent_name": "agent_name_value", } ] }, "image": { "mime_type": "mime_type_value", "data": b"data_blob", + "alt_text": "alt_text_value", }, "blob": { "mime_type": "mime_type_value", "data": b"data_blob", }, "variables": {}, - "event": {"event": "event_value"}, + "event": {"event": "event_value", "variables": {}}, "will_continue": True, + "recording_control": 1, }, "agent_transfer": { "target_agent": "target_agent_value", @@ -25238,6 +25261,8 @@ def test_update_evaluation_rest_call_success(request_type): "id": "id_value", "display_name": "display_name_value", "args": {}, + "parent_tool_call_id": "parent_tool_call_id_value", + "agent_name": "agent_name_value", }, "tool_response": {}, "agent_response": { @@ -25532,6 +25557,8 @@ def test_update_evaluation_rest_call_success(request_type): "tool_call_behaviour": 1, }, "golden_run_method": 1, + "root_span": {}, + "outcome_metadata": 1, }, "invalid": True, "last_ten_results": {}, @@ -26675,6 +26702,7 @@ def test_get_evaluation_result_rest_call_success(request_type): changelog="changelog_value", execution_state=evaluation.EvaluationResult.ExecutionState.QUEUED, golden_run_method=golden_run.GoldenRunMethod.STABLE, + outcome_metadata=evaluation.EvaluationResult.OutcomeMetadata.GRACEFUL_HANDOFF, ) # Wrap the value into a proper Response obj @@ -26701,6 +26729,10 @@ def test_get_evaluation_result_rest_call_success(request_type): assert response.changelog == "changelog_value" assert response.execution_state == evaluation.EvaluationResult.ExecutionState.QUEUED assert response.golden_run_method == golden_run.GoldenRunMethod.STABLE + assert ( + response.outcome_metadata + == evaluation.EvaluationResult.OutcomeMetadata.GRACEFUL_HANDOFF + ) @pytest.mark.parametrize("null_interceptor", [True, False]) diff --git a/packages/google-cloud-ces/tests/unit/gapic/ces_v1beta/test_session_service.py b/packages/google-cloud-ces/tests/unit/gapic/ces_v1beta/test_session_service.py index 05229ff56aeb..19f38f3ac6ca 100644 --- a/packages/google-cloud-ces/tests/unit/gapic/ces_v1beta/test_session_service.py +++ b/packages/google-cloud-ces/tests/unit/gapic/ces_v1beta/test_session_service.py @@ -39,8 +39,10 @@ HAS_GOOGLE_AUTH_AIO = False import google.auth +import google.protobuf.any_pb2 as any_pb2 # type: ignore import google.protobuf.struct_pb2 as struct_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from google.api_core import ( client_options, gapic_v1, @@ -61,7 +63,7 @@ SessionServiceClient, transports, ) -from google.cloud.ces_v1beta.types import example, session_service, toolset_tool +from google.cloud.ces_v1beta.types import common, example, session_service, toolset_tool CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -1695,13 +1697,84 @@ async def test_bidi_run_session_async(request_type, transport: str = "grpc_async assert isinstance(message, session_service.BidiSessionServerMessage) -def test_run_session_rest_use_cached_wrapped_rpc(): +@pytest.mark.parametrize( + "request_type", + [ + session_service.StreamChatAiAssistantRequest(), + {}, + ], +) +def test_stream_chat_ai_assistant(request_type, transport: str = "grpc"): + client = SessionServiceClient( + 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.stream_chat_ai_assistant), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iter([session_service.StreamChatAiAssistantResponse()]) + response = client.stream_chat_ai_assistant(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = session_service.StreamChatAiAssistantRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + for message in response: + assert isinstance(message, session_service.StreamChatAiAssistantResponse) + + +def test_stream_chat_ai_assistant_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = session_service.StreamChatAiAssistantRequest( + name="name_value", + message="message_value", + context_token="context_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stream_chat_ai_assistant), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.stream_chat_ai_assistant(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = session_service.StreamChatAiAssistantRequest( + name="name_value", + message="message_value", + context_token="context_token_value", + ) + assert args[0] == request_msg + + +def test_stream_chat_ai_assistant_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = SessionServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -1709,106 +1782,42 @@ def test_run_session_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.run_session in client._transport._wrapped_methods + assert ( + client._transport.stream_chat_ai_assistant + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.run_session] = mock_rpc - + client._transport._wrapped_methods[ + client._transport.stream_chat_ai_assistant + ] = mock_rpc request = {} - client.run_session(request) + client.stream_chat_ai_assistant(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.run_session(request) + client.stream_chat_ai_assistant(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_run_session_rest_required_fields( - request_type=session_service.RunSessionRequest, +@pytest.mark.asyncio +async def test_stream_chat_ai_assistant_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.SessionServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - default_values = getattr( - transport_class._BaseRunSession, - "_BaseRunSession__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - # verify required fields with non-default values are left alone - - client = SessionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = session_service.RunSessionResponse() - # 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 - - # Convert return value to protobuf type - return_value = session_service.RunSessionResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.run_session(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) - - -def test_stream_run_session_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SessionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SessionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) # Should wrap all calls on client creation @@ -1817,358 +1826,2088 @@ def test_stream_run_session_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.stream_run_session in client._transport._wrapped_methods + client._client._transport.stream_chat_ai_assistant + in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.stream_run_session] = ( - mock_rpc - ) + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.stream_chat_ai_assistant + ] = mock_rpc request = {} - client.stream_run_session(request) + await client.stream_chat_ai_assistant(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.stream_run_session(request) + await client.stream_chat_ai_assistant(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_stream_run_session_rest_required_fields( - request_type=session_service.RunSessionRequest, +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + session_service.StreamChatAiAssistantRequest(), + {}, + ], +) +async def test_stream_chat_ai_assistant_async( + request_type, transport: str = "grpc_asyncio" ): - transport_class = transports.SessionServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) + client = SessionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - # verify fields with default values are dropped + # 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 - default_values = getattr( - transport_class._BaseStreamRunSession, - "_BaseStreamRunSession__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stream_chat_ai_assistant), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock( + side_effect=[session_service.StreamChatAiAssistantResponse()] + ) + response = await client.stream_chat_ai_assistant(request) - # verify required fields with default values are now present + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = session_service.StreamChatAiAssistantRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + message = await response.read() + assert isinstance(message, session_service.StreamChatAiAssistantResponse) - # verify required fields with non-default values are left alone +def test_stream_chat_ai_assistant_field_headers(): client = SessionServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = session_service.RunSessionResponse() - # 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 + # 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 = session_service.StreamChatAiAssistantRequest() - response_value = Response() - response_value.status_code = 200 + request.name = "name_value" - # Convert return value to protobuf type - return_value = session_service.RunSessionResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - json_return_value = "[{}]".format(json_return_value) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stream_chat_ai_assistant), "__call__" + ) as call: + call.return_value = iter([session_service.StreamChatAiAssistantResponse()]) + client.stream_chat_ai_assistant(request) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - with mock.patch.object(response_value, "iter_content") as iter_content: - iter_content.return_value = iter(json_return_value) - response = client.stream_run_session(request) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) +@pytest.mark.asyncio +async def test_stream_chat_ai_assistant_field_headers_async(): + client = SessionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) -def test_bidi_run_session_rest_no_http_options(): + # 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 = session_service.StreamChatAiAssistantRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stream_chat_ai_assistant), "__call__" + ) as call: + call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock( + side_effect=[session_service.StreamChatAiAssistantResponse()] + ) + await client.stream_chat_ai_assistant(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", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.parametrize( + "request_type", + [ + session_service.CancelAssistantTurnRequest(), + {}, + ], +) +def test_cancel_assistant_turn(request_type, transport: str = "grpc"): client = SessionServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - request = session_service.BidiSessionClientMessage() - requests = [request] - with pytest.raises(RuntimeError): - client.bidi_run_session(requests) + # 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 -def test_bidi_run_session_rest_error(): + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.cancel_assistant_turn), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = session_service.CancelAssistantTurnResponse( + cancelled=True, + ) + response = client.cancel_assistant_turn(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = session_service.CancelAssistantTurnRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, session_service.CancelAssistantTurnResponse) + assert response.cancelled is True + + +def test_cancel_assistant_turn_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = SessionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - # Since a `google.api.http` annotation is required for using a rest transport - # method, this should error. - with pytest.raises(NotImplementedError) as not_implemented_error: - client.bidi_run_session({}) - assert "Method BidiRunSession is not available over REST transport" in str( - not_implemented_error.value + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = session_service.CancelAssistantTurnRequest( + name="name_value", + turn_id="turn_id_value", ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.cancel_assistant_turn), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.cancel_assistant_turn(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = session_service.CancelAssistantTurnRequest( + name="name_value", + turn_id="turn_id_value", + ) + assert args[0] == request_msg + -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.SessionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): +def test_cancel_assistant_turn_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = SessionServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="grpc", ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.SessionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SessionServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # It is an error to provide an api_key and a transport instance. - transport = transports.SessionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SessionServiceClient( - client_options=options, - transport=transport, + # Ensure method has been cached + assert ( + client._transport.cancel_assistant_turn + in client._transport._wrapped_methods ) - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SessionServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.cancel_assistant_turn] = ( + mock_rpc ) + request = {} + client.cancel_assistant_turn(request) - # It is an error to provide scopes and a transport instance. - transport = transports.SessionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SessionServiceClient( - client_options={"scopes": ["1", "2"]}, + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.cancel_assistant_turn(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_cancel_assistant_turn_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SessionServiceAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.cancel_assistant_turn + in client._client._transport._wrapped_methods + ) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SessionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SessionServiceClient(transport=transport) - assert client.transport is transport + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.cancel_assistant_turn + ] = mock_rpc + request = {} + await client.cancel_assistant_turn(request) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SessionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - transport = transports.SessionServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel + await client.cancel_assistant_turn(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 +@pytest.mark.asyncio @pytest.mark.parametrize( - "transport_class", + "request_type", [ - transports.SessionServiceGrpcTransport, - transports.SessionServiceGrpcAsyncIOTransport, - transports.SessionServiceRestTransport, + session_service.CancelAssistantTurnRequest(), + {}, ], ) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() +async def test_cancel_assistant_turn_async( + request_type, transport: str = "grpc_asyncio" +): + client = SessionServiceAsyncClient( + credentials=async_anonymous_credentials(), + 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 -def test_transport_kind_grpc(): - transport = SessionServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.cancel_assistant_turn), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + session_service.CancelAssistantTurnResponse( + cancelled=True, + ) + ) + response = await client.cancel_assistant_turn(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = session_service.CancelAssistantTurnRequest() + assert args[0] == request -def test_initialize_client_w_grpc(): - client = SessionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" - ) - assert client is not None + # Establish that the response is the type that we expect. + assert isinstance(response, session_service.CancelAssistantTurnResponse) + assert response.cancelled is True -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_run_session_empty_call_grpc(): +def test_cancel_assistant_turn_field_headers(): client = SessionServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.run_session), "__call__") as call: - call.return_value = session_service.RunSessionResponse() - client.run_session(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = session_service.RunSessionRequest() - assert args[0] == request_msg + # 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 = session_service.CancelAssistantTurnRequest() + request.name = "name_value" -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_stream_run_session_empty_call_grpc(): + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.cancel_assistant_turn), "__call__" + ) as call: + call.return_value = session_service.CancelAssistantTurnResponse() + client.cancel_assistant_turn(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", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_cancel_assistant_turn_field_headers_async(): + client = SessionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = session_service.CancelAssistantTurnRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.cancel_assistant_turn), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + session_service.CancelAssistantTurnResponse() + ) + await client.cancel_assistant_turn(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", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.parametrize( + "request_type", + [ + session_service.GenerateOnboardingSuggestionsRequest(), + {}, + ], +) +def test_generate_onboarding_suggestions(request_type, transport: str = "grpc"): client = SessionServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport, ) - # Mock the actual call, and fake the request. + # 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.stream_run_session), "__call__" + type(client.transport.generate_onboarding_suggestions), "__call__" ) as call: - call.return_value = iter([session_service.RunSessionResponse()]) - client.stream_run_session(request=None) + # Designate an appropriate return value for the call. + call.return_value = session_service.GenerateOnboardingSuggestionsResponse( + user_profile=session_service.GenerateOnboardingSuggestionsResponse.UserProfile.NEW, + context_token="context_token_value", + ) + response = client.generate_onboarding_suggestions(request) - # Establish that the underlying stub method was called. + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = session_service.GenerateOnboardingSuggestionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, session_service.GenerateOnboardingSuggestionsResponse) + assert ( + response.user_profile + == session_service.GenerateOnboardingSuggestionsResponse.UserProfile.NEW + ) + assert response.context_token == "context_token_value" + + +def test_generate_onboarding_suggestions_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = session_service.GenerateOnboardingSuggestionsRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_onboarding_suggestions), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.generate_onboarding_suggestions(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = session_service.RunSessionRequest() + request_msg = session_service.GenerateOnboardingSuggestionsRequest( + name="name_value", + ) assert args[0] == request_msg -def test_transport_kind_grpc_asyncio(): - transport = SessionServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" +def test_generate_onboarding_suggestions_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -def test_initialize_client_w_grpc_asyncio(): - client = SessionServiceAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" - ) - assert client is not None + # Ensure method has been cached + assert ( + client._transport.generate_onboarding_suggestions + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.generate_onboarding_suggestions + ] = mock_rpc + request = {} + client.generate_onboarding_suggestions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_onboarding_suggestions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_run_session_empty_call_grpc_asyncio(): +async def test_generate_onboarding_suggestions_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SessionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.generate_onboarding_suggestions + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.generate_onboarding_suggestions + ] = mock_rpc + + request = {} + await client.generate_onboarding_suggestions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.generate_onboarding_suggestions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + session_service.GenerateOnboardingSuggestionsRequest(), + {}, + ], +) +async def test_generate_onboarding_suggestions_async( + request_type, transport: str = "grpc_asyncio" +): client = SessionServiceAsyncClient( credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.run_session), "__call__") as call: + # 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.generate_onboarding_suggestions), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - session_service.RunSessionResponse() + session_service.GenerateOnboardingSuggestionsResponse( + user_profile=session_service.GenerateOnboardingSuggestionsResponse.UserProfile.NEW, + context_token="context_token_value", + ) ) - await client.run_session(request=None) + response = await client.generate_onboarding_suggestions(request) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request_msg = session_service.RunSessionRequest() - assert args[0] == request_msg + request = session_service.GenerateOnboardingSuggestionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, session_service.GenerateOnboardingSuggestionsResponse) + assert ( + response.user_profile + == session_service.GenerateOnboardingSuggestionsResponse.UserProfile.NEW + ) + assert response.context_token == "context_token_value" + + +def test_generate_onboarding_suggestions_field_headers(): + client = SessionServiceClient( + 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 = session_service.GenerateOnboardingSuggestionsRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_onboarding_suggestions), "__call__" + ) as call: + call.return_value = session_service.GenerateOnboardingSuggestionsResponse() + client.generate_onboarding_suggestions(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", + "name=name_value", + ) in kw["metadata"] -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_stream_run_session_empty_call_grpc_asyncio(): +async def test_generate_onboarding_suggestions_field_headers_async(): client = SessionServiceAsyncClient( credentials=async_anonymous_credentials(), - transport="grpc_asyncio", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.stream_run_session), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) - call.return_value.read = mock.AsyncMock( - side_effect=[session_service.RunSessionResponse()] + # 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 = session_service.GenerateOnboardingSuggestionsRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_onboarding_suggestions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + session_service.GenerateOnboardingSuggestionsResponse() + ) + await client.generate_onboarding_suggestions(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", + "name=name_value", + ) in kw["metadata"] + + +def test_run_session_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.run_session in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.run_session] = mock_rpc + + request = {} + client.run_session(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.run_session(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_run_session_rest_required_fields( + request_type=session_service.RunSessionRequest, +): + transport_class = transports.SessionServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseRunSession, + "_BaseRunSession__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # verify required fields with non-default values are left alone + + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = session_service.RunSessionResponse() + # 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 + + # Convert return value to protobuf type + return_value = session_service.RunSessionResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.run_session(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_stream_run_session_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.stream_run_session in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.stream_run_session] = ( + mock_rpc + ) + + request = {} + client.stream_run_session(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.stream_run_session(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_stream_run_session_rest_required_fields( + request_type=session_service.RunSessionRequest, +): + transport_class = transports.SessionServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseStreamRunSession, + "_BaseStreamRunSession__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # verify required fields with non-default values are left alone + + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = session_service.RunSessionResponse() + # 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 + + # Convert return value to protobuf type + return_value = session_service.RunSessionResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + json_return_value = "[{}]".format(json_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + with mock.patch.object(response_value, "iter_content") as iter_content: + iter_content.return_value = iter(json_return_value) + response = client.stream_run_session(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_bidi_run_session_rest_no_http_options(): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = session_service.BidiSessionClientMessage() + requests = [request] + with pytest.raises(RuntimeError): + client.bidi_run_session(requests) + + +def test_stream_chat_ai_assistant_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.stream_chat_ai_assistant + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.stream_chat_ai_assistant + ] = mock_rpc + + request = {} + client.stream_chat_ai_assistant(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.stream_chat_ai_assistant(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_stream_chat_ai_assistant_rest_required_fields( + request_type=session_service.StreamChatAiAssistantRequest, +): + transport_class = transports.SessionServiceRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseStreamChatAiAssistant, + "_BaseStreamChatAiAssistant__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = session_service.StreamChatAiAssistantResponse() + # 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 + + # Convert return value to protobuf type + return_value = session_service.StreamChatAiAssistantResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + json_return_value = "[{}]".format(json_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + with mock.patch.object(response_value, "iter_content") as iter_content: + iter_content.return_value = iter(json_return_value) + response = client.stream_chat_ai_assistant(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_cancel_assistant_turn_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.cancel_assistant_turn + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.cancel_assistant_turn] = ( + mock_rpc + ) + + request = {} + client.cancel_assistant_turn(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.cancel_assistant_turn(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_cancel_assistant_turn_rest_required_fields( + request_type=session_service.CancelAssistantTurnRequest, +): + transport_class = transports.SessionServiceRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseCancelAssistantTurn, + "_BaseCancelAssistantTurn__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = session_service.CancelAssistantTurnResponse() + # 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 + + # Convert return value to protobuf type + return_value = session_service.CancelAssistantTurnResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.cancel_assistant_turn(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_generate_onboarding_suggestions_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.generate_onboarding_suggestions + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.generate_onboarding_suggestions + ] = mock_rpc + + request = {} + client.generate_onboarding_suggestions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_onboarding_suggestions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_generate_onboarding_suggestions_rest_required_fields( + request_type=session_service.GenerateOnboardingSuggestionsRequest, +): + transport_class = transports.SessionServiceRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGenerateOnboardingSuggestions, + "_BaseGenerateOnboardingSuggestions__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = session_service.GenerateOnboardingSuggestionsResponse() + # 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 + + # Convert return value to protobuf type + return_value = session_service.GenerateOnboardingSuggestionsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.generate_onboarding_suggestions(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_bidi_run_session_rest_error(): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # Since a `google.api.http` annotation is required for using a rest transport + # method, this should error. + with pytest.raises(NotImplementedError) as not_implemented_error: + client.bidi_run_session({}) + assert "Method BidiRunSession is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SessionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SessionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SessionServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SessionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SessionServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SessionServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SessionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SessionServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SessionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SessionServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SessionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SessionServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SessionServiceGrpcTransport, + transports.SessionServiceGrpcAsyncIOTransport, + transports.SessionServiceRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_kind_grpc(): + transport = SessionServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_run_session_empty_call_grpc(): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.run_session), "__call__") as call: + call.return_value = session_service.RunSessionResponse() + client.run_session(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = session_service.RunSessionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_stream_run_session_empty_call_grpc(): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.stream_run_session), "__call__" + ) as call: + call.return_value = iter([session_service.RunSessionResponse()]) + client.stream_run_session(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = session_service.RunSessionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_stream_chat_ai_assistant_empty_call_grpc(): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.stream_chat_ai_assistant), "__call__" + ) as call: + call.return_value = iter([session_service.StreamChatAiAssistantResponse()]) + client.stream_chat_ai_assistant(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = session_service.StreamChatAiAssistantRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_cancel_assistant_turn_empty_call_grpc(): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.cancel_assistant_turn), "__call__" + ) as call: + call.return_value = session_service.CancelAssistantTurnResponse() + client.cancel_assistant_turn(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = session_service.CancelAssistantTurnRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_generate_onboarding_suggestions_empty_call_grpc(): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_onboarding_suggestions), "__call__" + ) as call: + call.return_value = session_service.GenerateOnboardingSuggestionsResponse() + client.generate_onboarding_suggestions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = session_service.GenerateOnboardingSuggestionsRequest() + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = SessionServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = SessionServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_run_session_empty_call_grpc_asyncio(): + client = SessionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.run_session), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + session_service.RunSessionResponse() + ) + await client.run_session(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = session_service.RunSessionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_stream_run_session_empty_call_grpc_asyncio(): + client = SessionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.stream_run_session), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock( + side_effect=[session_service.RunSessionResponse()] + ) + await client.stream_run_session(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = session_service.RunSessionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_stream_chat_ai_assistant_empty_call_grpc_asyncio(): + client = SessionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.stream_chat_ai_assistant), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock( + side_effect=[session_service.StreamChatAiAssistantResponse()] + ) + await client.stream_chat_ai_assistant(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = session_service.StreamChatAiAssistantRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_cancel_assistant_turn_empty_call_grpc_asyncio(): + client = SessionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.cancel_assistant_turn), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + session_service.CancelAssistantTurnResponse( + cancelled=True, + ) + ) + await client.cancel_assistant_turn(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = session_service.CancelAssistantTurnRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_generate_onboarding_suggestions_empty_call_grpc_asyncio(): + client = SessionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_onboarding_suggestions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + session_service.GenerateOnboardingSuggestionsResponse( + user_profile=session_service.GenerateOnboardingSuggestionsResponse.UserProfile.NEW, + context_token="context_token_value", + ) + ) + await client.generate_onboarding_suggestions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = session_service.GenerateOnboardingSuggestionsRequest() + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = SessionServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_run_session_rest_bad_request(request_type=session_service.RunSessionRequest): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "config": { + "session": "projects/sample1/locations/sample2/apps/sample3/sessions/sample4" + } + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.run_session(request) + + +@pytest.mark.parametrize( + "request_type", + [ + session_service.RunSessionRequest, + dict, + ], +) +def test_run_session_rest_call_success(request_type): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "config": { + "session": "projects/sample1/locations/sample2/apps/sample3/sessions/sample4" + } + } + 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 = session_service.RunSessionResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = session_service.RunSessionResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.run_session(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, session_service.RunSessionResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_run_session_rest_interceptors(null_interceptor): + transport = transports.SessionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SessionServiceRestInterceptor(), + ) + client = SessionServiceClient(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.SessionServiceRestInterceptor, "post_run_session" + ) as post, + mock.patch.object( + transports.SessionServiceRestInterceptor, "post_run_session_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.SessionServiceRestInterceptor, "pre_run_session" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = session_service.RunSessionRequest.pb( + session_service.RunSessionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = session_service.RunSessionResponse.to_json( + session_service.RunSessionResponse() + ) + req.return_value.content = return_value + + request = session_service.RunSessionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = session_service.RunSessionResponse() + post_with_metadata.return_value = session_service.RunSessionResponse(), metadata + + client.run_session( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_stream_run_session_rest_bad_request( + request_type=session_service.RunSessionRequest, +): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "config": { + "session": "projects/sample1/locations/sample2/apps/sample3/sessions/sample4" + } + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.stream_run_session(request) + + +@pytest.mark.parametrize( + "request_type", + [ + session_service.RunSessionRequest, + dict, + ], +) +def test_stream_run_session_rest_call_success(request_type): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "config": { + "session": "projects/sample1/locations/sample2/apps/sample3/sessions/sample4" + } + } + 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 = session_service.RunSessionResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = session_service.RunSessionResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + json_return_value = "[{}]".format(json_return_value) + response_value.iter_content = mock.Mock(return_value=iter(json_return_value)) + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.stream_run_session(request) + + assert isinstance(response, Iterable) + response = next(response) + + # Establish that the response is the type that we expect. + assert isinstance(response, session_service.RunSessionResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_stream_run_session_rest_interceptors(null_interceptor): + transport = transports.SessionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SessionServiceRestInterceptor(), + ) + client = SessionServiceClient(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.SessionServiceRestInterceptor, "post_stream_run_session" + ) as post, + mock.patch.object( + transports.SessionServiceRestInterceptor, + "post_stream_run_session_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.SessionServiceRestInterceptor, "pre_stream_run_session" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = session_service.RunSessionRequest.pb( + session_service.RunSessionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = session_service.RunSessionResponse.to_json( + session_service.RunSessionResponse() + ) + req.return_value.iter_content = mock.Mock(return_value=iter(return_value)) + + request = session_service.RunSessionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = session_service.RunSessionResponse() + post_with_metadata.return_value = session_service.RunSessionResponse(), metadata + + client.stream_run_session( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_bidi_run_session_rest_error(): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + with pytest.raises(NotImplementedError) as not_implemented_error: + client.bidi_run_session({}) + assert "Method BidiRunSession is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_stream_chat_ai_assistant_rest_bad_request( + request_type=session_service.StreamChatAiAssistantRequest, +): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/assistantSessions/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.stream_chat_ai_assistant(request) + + +@pytest.mark.parametrize( + "request_type", + [ + session_service.StreamChatAiAssistantRequest, + dict, + ], +) +def test_stream_chat_ai_assistant_rest_call_success(request_type): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/assistantSessions/sample4" + } + 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 = session_service.StreamChatAiAssistantResponse( + event_id="event_id_value", + sequence_number=1601, + turn_in_progress=True, + text_chunk="text_chunk_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = session_service.StreamChatAiAssistantResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + json_return_value = "[{}]".format(json_return_value) + response_value.iter_content = mock.Mock(return_value=iter(json_return_value)) + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.stream_chat_ai_assistant(request) + + assert isinstance(response, Iterable) + response = next(response) + + # Establish that the response is the type that we expect. + assert isinstance(response, session_service.StreamChatAiAssistantResponse) + assert response.event_id == "event_id_value" + assert response.sequence_number == 1601 + assert response.turn_in_progress is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_stream_chat_ai_assistant_rest_interceptors(null_interceptor): + transport = transports.SessionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SessionServiceRestInterceptor(), + ) + client = SessionServiceClient(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.SessionServiceRestInterceptor, "post_stream_chat_ai_assistant" + ) as post, + mock.patch.object( + transports.SessionServiceRestInterceptor, + "post_stream_chat_ai_assistant_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.SessionServiceRestInterceptor, "pre_stream_chat_ai_assistant" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = session_service.StreamChatAiAssistantRequest.pb( + session_service.StreamChatAiAssistantRequest() ) - await client.stream_run_session(request=None) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = session_service.RunSessionRequest() - assert args[0] == request_msg + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = session_service.StreamChatAiAssistantResponse.to_json( + session_service.StreamChatAiAssistantResponse() + ) + req.return_value.iter_content = mock.Mock(return_value=iter(return_value)) + request = session_service.StreamChatAiAssistantRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = session_service.StreamChatAiAssistantResponse() + post_with_metadata.return_value = ( + session_service.StreamChatAiAssistantResponse(), + metadata, + ) -def test_transport_kind_rest(): - transport = SessionServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" + client.stream_chat_ai_assistant( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() -def test_run_session_rest_bad_request(request_type=session_service.RunSessionRequest): +def test_cancel_assistant_turn_rest_bad_request( + request_type=session_service.CancelAssistantTurnRequest, +): client = SessionServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "config": { - "session": "projects/sample1/locations/sample2/apps/sample3/sessions/sample4" - } + "name": "projects/sample1/locations/sample2/apps/sample3/assistantSessions/sample4" } request = request_type(**request_init) @@ -2185,52 +3924,53 @@ def test_run_session_rest_bad_request(request_type=session_service.RunSessionReq response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.run_session(request) + client.cancel_assistant_turn(request) @pytest.mark.parametrize( "request_type", [ - session_service.RunSessionRequest, + session_service.CancelAssistantTurnRequest, dict, ], ) -def test_run_session_rest_call_success(request_type): +def test_cancel_assistant_turn_rest_call_success(request_type): client = SessionServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "config": { - "session": "projects/sample1/locations/sample2/apps/sample3/sessions/sample4" - } + "name": "projects/sample1/locations/sample2/apps/sample3/assistantSessions/sample4" } 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 = session_service.RunSessionResponse() + return_value = session_service.CancelAssistantTurnResponse( + cancelled=True, + ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 # Convert return value to protobuf type - return_value = session_service.RunSessionResponse.pb(return_value) + return_value = session_service.CancelAssistantTurnResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.run_session(request) + response = client.cancel_assistant_turn(request) # Establish that the response is the type that we expect. - assert isinstance(response, session_service.RunSessionResponse) + assert isinstance(response, session_service.CancelAssistantTurnResponse) + assert response.cancelled is True @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_run_session_rest_interceptors(null_interceptor): +def test_cancel_assistant_turn_rest_interceptors(null_interceptor): transport = transports.SessionServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -2243,20 +3983,21 @@ def test_run_session_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.SessionServiceRestInterceptor, "post_run_session" + transports.SessionServiceRestInterceptor, "post_cancel_assistant_turn" ) as post, mock.patch.object( - transports.SessionServiceRestInterceptor, "post_run_session_with_metadata" + transports.SessionServiceRestInterceptor, + "post_cancel_assistant_turn_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.SessionServiceRestInterceptor, "pre_run_session" + transports.SessionServiceRestInterceptor, "pre_cancel_assistant_turn" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = session_service.RunSessionRequest.pb( - session_service.RunSessionRequest() + pb_message = session_service.CancelAssistantTurnRequest.pb( + session_service.CancelAssistantTurnRequest() ) transcode.return_value = { "method": "post", @@ -2268,21 +4009,24 @@ def test_run_session_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = session_service.RunSessionResponse.to_json( - session_service.RunSessionResponse() + return_value = session_service.CancelAssistantTurnResponse.to_json( + session_service.CancelAssistantTurnResponse() ) req.return_value.content = return_value - request = session_service.RunSessionRequest() + request = session_service.CancelAssistantTurnRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = session_service.RunSessionResponse() - post_with_metadata.return_value = session_service.RunSessionResponse(), metadata + post.return_value = session_service.CancelAssistantTurnResponse() + post_with_metadata.return_value = ( + session_service.CancelAssistantTurnResponse(), + metadata, + ) - client.run_session( + client.cancel_assistant_turn( request, metadata=[ ("key", "val"), @@ -2295,18 +4039,14 @@ def test_run_session_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_stream_run_session_rest_bad_request( - request_type=session_service.RunSessionRequest, +def test_generate_onboarding_suggestions_rest_bad_request( + request_type=session_service.GenerateOnboardingSuggestionsRequest, ): client = SessionServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "config": { - "session": "projects/sample1/locations/sample2/apps/sample3/sessions/sample4" - } - } + request_init = {"name": "projects/sample1/locations/sample2/apps/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -2322,56 +4062,58 @@ def test_stream_run_session_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.stream_run_session(request) + client.generate_onboarding_suggestions(request) @pytest.mark.parametrize( "request_type", [ - session_service.RunSessionRequest, + session_service.GenerateOnboardingSuggestionsRequest, dict, ], ) -def test_stream_run_session_rest_call_success(request_type): +def test_generate_onboarding_suggestions_rest_call_success(request_type): client = SessionServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "config": { - "session": "projects/sample1/locations/sample2/apps/sample3/sessions/sample4" - } - } + request_init = {"name": "projects/sample1/locations/sample2/apps/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 = session_service.RunSessionResponse() + return_value = session_service.GenerateOnboardingSuggestionsResponse( + user_profile=session_service.GenerateOnboardingSuggestionsResponse.UserProfile.NEW, + context_token="context_token_value", + ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 # Convert return value to protobuf type - return_value = session_service.RunSessionResponse.pb(return_value) + return_value = session_service.GenerateOnboardingSuggestionsResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) - json_return_value = "[{}]".format(json_return_value) - response_value.iter_content = mock.Mock(return_value=iter(json_return_value)) + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.stream_run_session(request) - - assert isinstance(response, Iterable) - response = next(response) + response = client.generate_onboarding_suggestions(request) # Establish that the response is the type that we expect. - assert isinstance(response, session_service.RunSessionResponse) + assert isinstance(response, session_service.GenerateOnboardingSuggestionsResponse) + assert ( + response.user_profile + == session_service.GenerateOnboardingSuggestionsResponse.UserProfile.NEW + ) + assert response.context_token == "context_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_stream_run_session_rest_interceptors(null_interceptor): +def test_generate_onboarding_suggestions_rest_interceptors(null_interceptor): transport = transports.SessionServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -2384,21 +4126,23 @@ def test_stream_run_session_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.SessionServiceRestInterceptor, "post_stream_run_session" + transports.SessionServiceRestInterceptor, + "post_generate_onboarding_suggestions", ) as post, mock.patch.object( transports.SessionServiceRestInterceptor, - "post_stream_run_session_with_metadata", + "post_generate_onboarding_suggestions_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.SessionServiceRestInterceptor, "pre_stream_run_session" + transports.SessionServiceRestInterceptor, + "pre_generate_onboarding_suggestions", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = session_service.RunSessionRequest.pb( - session_service.RunSessionRequest() + pb_message = session_service.GenerateOnboardingSuggestionsRequest.pb( + session_service.GenerateOnboardingSuggestionsRequest() ) transcode.return_value = { "method": "post", @@ -2410,21 +4154,24 @@ def test_stream_run_session_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = session_service.RunSessionResponse.to_json( - session_service.RunSessionResponse() + return_value = session_service.GenerateOnboardingSuggestionsResponse.to_json( + session_service.GenerateOnboardingSuggestionsResponse() ) - req.return_value.iter_content = mock.Mock(return_value=iter(return_value)) + req.return_value.content = return_value - request = session_service.RunSessionRequest() + request = session_service.GenerateOnboardingSuggestionsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = session_service.RunSessionResponse() - post_with_metadata.return_value = session_service.RunSessionResponse(), metadata + post.return_value = session_service.GenerateOnboardingSuggestionsResponse() + post_with_metadata.return_value = ( + session_service.GenerateOnboardingSuggestionsResponse(), + metadata, + ) - client.stream_run_session( + client.generate_onboarding_suggestions( request, metadata=[ ("key", "val"), @@ -2437,18 +4184,6 @@ def test_stream_run_session_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_bidi_run_session_rest_error(): - client = SessionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - with pytest.raises(NotImplementedError) as not_implemented_error: - client.bidi_run_session({}) - assert "Method BidiRunSession is not available over REST transport" in str( - not_implemented_error.value - ) - - def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): client = SessionServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2870,6 +4605,69 @@ def test_stream_run_session_empty_call_rest(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_stream_chat_ai_assistant_empty_call_rest(): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.stream_chat_ai_assistant), "__call__" + ) as call: + client.stream_chat_ai_assistant(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = session_service.StreamChatAiAssistantRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_cancel_assistant_turn_empty_call_rest(): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.cancel_assistant_turn), "__call__" + ) as call: + client.cancel_assistant_turn(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = session_service.CancelAssistantTurnRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_generate_onboarding_suggestions_empty_call_rest(): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_onboarding_suggestions), "__call__" + ) as call: + client.generate_onboarding_suggestions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = session_service.GenerateOnboardingSuggestionsRequest() + assert args[0] == request_msg + + def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = SessionServiceClient( @@ -2906,6 +4704,9 @@ def test_session_service_base_transport(): "run_session", "stream_run_session", "bidi_run_session", + "stream_chat_ai_assistant", + "cancel_assistant_turn", + "generate_onboarding_suggestions", "get_location", "list_locations", "get_operation", @@ -3196,6 +4997,15 @@ def test_session_service_client_transport_session_collision(transport_name): session1 = client1.transport.bidi_run_session._session session2 = client2.transport.bidi_run_session._session assert session1 != session2 + session1 = client1.transport.stream_chat_ai_assistant._session + session2 = client2.transport.stream_chat_ai_assistant._session + assert session1 != session2 + session1 = client1.transport.cancel_assistant_turn._session + session2 = client2.transport.cancel_assistant_turn._session + assert session1 != session2 + session1 = client1.transport.generate_onboarding_suggestions._session + session2 = client2.transport.generate_onboarding_suggestions._session + assert session1 != session2 def test_session_service_grpc_transport_channel(): @@ -3356,11 +5166,68 @@ def test_parse_agent_path(): assert expected == actual -def test_session_path(): +def test_app_path(): project = "winkle" location = "nautilus" app = "scallop" - session = "abalone" + expected = "projects/{project}/locations/{location}/apps/{app}".format( + project=project, + location=location, + app=app, + ) + actual = SessionServiceClient.app_path(project, location, app) + assert expected == actual + + +def test_parse_app_path(): + expected = { + "project": "abalone", + "location": "squid", + "app": "clam", + } + path = SessionServiceClient.app_path(**expected) + + # Check that the path construction is reversible. + actual = SessionServiceClient.parse_app_path(path) + assert expected == actual + + +def test_assistant_session_path(): + project = "whelk" + location = "octopus" + app = "oyster" + assistant_session = "nudibranch" + expected = "projects/{project}/locations/{location}/apps/{app}/assistantSessions/{assistant_session}".format( + project=project, + location=location, + app=app, + assistant_session=assistant_session, + ) + actual = SessionServiceClient.assistant_session_path( + project, location, app, assistant_session + ) + assert expected == actual + + +def test_parse_assistant_session_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "app": "winkle", + "assistant_session": "nautilus", + } + path = SessionServiceClient.assistant_session_path(**expected) + + # Check that the path construction is reversible. + actual = SessionServiceClient.parse_assistant_session_path(path) + assert expected == actual + + +def test_session_path(): + project = "scallop" + location = "abalone" + app = "squid" + session = "clam" expected = ( "projects/{project}/locations/{location}/apps/{app}/sessions/{session}".format( project=project, @@ -3375,10 +5242,10 @@ def test_session_path(): def test_parse_session_path(): expected = { - "project": "squid", - "location": "clam", - "app": "whelk", - "session": "octopus", + "project": "whelk", + "location": "octopus", + "app": "oyster", + "session": "nudibranch", } path = SessionServiceClient.session_path(**expected) @@ -3388,10 +5255,10 @@ def test_parse_session_path(): def test_tool_path(): - project = "oyster" - location = "nudibranch" - app = "cuttlefish" - tool = "mussel" + project = "cuttlefish" + location = "mussel" + app = "winkle" + tool = "nautilus" expected = "projects/{project}/locations/{location}/apps/{app}/tools/{tool}".format( project=project, location=location, @@ -3404,10 +5271,10 @@ def test_tool_path(): def test_parse_tool_path(): expected = { - "project": "winkle", - "location": "nautilus", - "app": "scallop", - "tool": "abalone", + "project": "scallop", + "location": "abalone", + "app": "squid", + "tool": "clam", } path = SessionServiceClient.tool_path(**expected) @@ -3417,10 +5284,10 @@ def test_parse_tool_path(): def test_toolset_path(): - project = "squid" - location = "clam" - app = "whelk" - toolset = "octopus" + project = "whelk" + location = "octopus" + app = "oyster" + toolset = "nudibranch" expected = ( "projects/{project}/locations/{location}/apps/{app}/toolsets/{toolset}".format( project=project, @@ -3435,10 +5302,10 @@ def test_toolset_path(): def test_parse_toolset_path(): expected = { - "project": "oyster", - "location": "nudibranch", - "app": "cuttlefish", - "toolset": "mussel", + "project": "cuttlefish", + "location": "mussel", + "app": "winkle", + "toolset": "nautilus", } path = SessionServiceClient.toolset_path(**expected) @@ -3448,7 +5315,7 @@ def test_parse_toolset_path(): def test_common_billing_account_path(): - billing_account = "winkle" + billing_account = "scallop" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -3458,7 +5325,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "nautilus", + "billing_account": "abalone", } path = SessionServiceClient.common_billing_account_path(**expected) @@ -3468,7 +5335,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "scallop" + folder = "squid" expected = "folders/{folder}".format( folder=folder, ) @@ -3478,7 +5345,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "abalone", + "folder": "clam", } path = SessionServiceClient.common_folder_path(**expected) @@ -3488,7 +5355,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "squid" + organization = "whelk" expected = "organizations/{organization}".format( organization=organization, ) @@ -3498,7 +5365,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "clam", + "organization": "octopus", } path = SessionServiceClient.common_organization_path(**expected) @@ -3508,7 +5375,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "whelk" + project = "oyster" expected = "projects/{project}".format( project=project, ) @@ -3518,7 +5385,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "octopus", + "project": "nudibranch", } path = SessionServiceClient.common_project_path(**expected) @@ -3528,8 +5395,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "oyster" - location = "nudibranch" + project = "cuttlefish" + location = "mussel" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -3540,8 +5407,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "cuttlefish", - "location": "mussel", + "project": "winkle", + "location": "nautilus", } path = SessionServiceClient.common_location_path(**expected)